• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.os;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.annotation.SystemApi;
22 import android.app.AppOpsManager;
23 import android.compat.annotation.UnsupportedAppUsage;
24 import android.util.ExceptionUtils;
25 import android.util.Log;
26 import android.util.Slog;
27 
28 import com.android.internal.os.BinderCallHeavyHitterWatcher;
29 import com.android.internal.os.BinderCallHeavyHitterWatcher.BinderCallHeavyHitterListener;
30 import com.android.internal.os.BinderInternal;
31 import com.android.internal.os.BinderInternal.CallSession;
32 import com.android.internal.util.FastPrintWriter;
33 import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
34 import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
35 
36 import dalvik.annotation.optimization.CriticalNative;
37 
38 import libcore.io.IoUtils;
39 import libcore.util.NativeAllocationRegistry;
40 
41 import java.io.FileDescriptor;
42 import java.io.FileInputStream;
43 import java.io.FileOutputStream;
44 import java.io.IOException;
45 import java.io.PrintWriter;
46 import java.lang.reflect.Modifier;
47 
48 /**
49  * Base class for a remotable object, the core part of a lightweight
50  * remote procedure call mechanism defined by {@link IBinder}.
51  * This class is an implementation of IBinder that provides
52  * standard local implementation of such an object.
53  *
54  * <p>Most developers will not implement this class directly, instead using the
55  * <a href="{@docRoot}guide/components/aidl.html">aidl</a> tool to describe the desired
56  * interface, having it generate the appropriate Binder subclass.  You can,
57  * however, derive directly from Binder to implement your own custom RPC
58  * protocol or simply instantiate a raw Binder object directly to use as a
59  * token that can be shared across processes.
60  *
61  * <p>This class is just a basic IPC primitive; it has no impact on an application's
62  * lifecycle, and is valid only as long as the process that created it continues to run.
63  * To use this correctly, you must be doing so within the context of a top-level
64  * application component (a {@link android.app.Service}, {@link android.app.Activity},
65  * or {@link android.content.ContentProvider}) that lets the system know your process
66  * should remain running.</p>
67  *
68  * <p>You must keep in mind the situations in which your process
69  * could go away, and thus require that you later re-create a new Binder and re-attach
70  * it when the process starts again.  For example, if you are using this within an
71  * {@link android.app.Activity}, your activity's process may be killed any time the
72  * activity is not started; if the activity is later re-created you will need to
73  * create a new Binder and hand it back to the correct place again; you need to be
74  * aware that your process may be started for another reason (for example to receive
75  * a broadcast) that will not involve re-creating the activity and thus run its code
76  * to create a new Binder.</p>
77  *
78  * @see IBinder
79  */
80 public class Binder implements IBinder {
81     /*
82      * Set this flag to true to detect anonymous, local or member classes
83      * that extend this Binder class and that are not static. These kind
84      * of classes can potentially create leaks.
85      */
86     private static final boolean FIND_POTENTIAL_LEAKS = false;
87     /** @hide */
88     public static final boolean CHECK_PARCEL_SIZE = false;
89     static final String TAG = "Binder";
90 
91     /** @hide */
92     public static boolean LOG_RUNTIME_EXCEPTION = false; // DO NOT SUBMIT WITH TRUE
93 
94     /**
95      * Value to represents that a calling work source is not set.
96      *
97      * This constatnt needs to be kept in sync with IPCThreadState::kUnsetWorkSource.
98      *
99      * @hide
100      */
101     public static final int UNSET_WORKSOURCE = -1;
102 
103     /**
104      * Control whether dump() calls are allowed.
105      */
106     private static volatile String sDumpDisabled = null;
107 
108     /**
109      * Global transaction tracker instance for this process.
110      */
111     private static volatile TransactionTracker sTransactionTracker = null;
112 
113     /**
114      * Global observer for this process.
115      */
116     private static BinderInternal.Observer sObserver = null;
117 
118     /**
119      * Guestimate of native memory associated with a Binder.
120      */
121     private static final int NATIVE_ALLOCATION_SIZE = 500;
122 
getNativeFinalizer()123     private static native long getNativeFinalizer();
124 
125     // Use a Holder to allow static initialization of Binder in the boot image, and
126     // possibly to avoid some initialization ordering issues.
127     private static class NoImagePreloadHolder {
128         public static final NativeAllocationRegistry sRegistry = new NativeAllocationRegistry(
129                 Binder.class.getClassLoader(), getNativeFinalizer(), NATIVE_ALLOCATION_SIZE);
130     }
131 
132     /**
133      * The watcher to monitor the heavy hitter from incoming transactions
134      */
135     private static volatile BinderCallHeavyHitterWatcher sHeavyHitterWatcher = null;
136 
137     // Transaction tracking code.
138 
139     /**
140      * Flag indicating whether we should be tracing transact calls.
141      */
142     private static volatile boolean sTracingEnabled = false;
143 
144     /**
145      * Enable Binder IPC tracing.
146      *
147      * @hide
148      */
enableTracing()149     public static void enableTracing() {
150         sTracingEnabled = true;
151     }
152 
153     /**
154      * Disable Binder IPC tracing.
155      *
156      * @hide
157      */
disableTracing()158     public static void disableTracing() {
159         sTracingEnabled = false;
160     }
161 
162     /**
163      * Check if binder transaction tracing is enabled.
164      *
165      * @hide
166      */
isTracingEnabled()167     public static boolean isTracingEnabled() {
168         return sTracingEnabled;
169     }
170 
171     /**
172      * Get the binder transaction tracker for this process.
173      *
174      * @hide
175      */
getTransactionTracker()176     public synchronized static TransactionTracker getTransactionTracker() {
177         if (sTransactionTracker == null)
178             sTransactionTracker = new TransactionTracker();
179         return sTransactionTracker;
180     }
181 
182     /**
183      * Get the binder transaction observer for this process.
184      *
185      * @hide
186      */
setObserver(@ullable BinderInternal.Observer observer)187     public static void setObserver(@Nullable BinderInternal.Observer observer) {
188         sObserver = observer;
189     }
190 
191     /** {@hide} */
192     static volatile boolean sWarnOnBlocking = false;
193 
194     /**
195      * Warn if any blocking binder transactions are made out from this process.
196      * This is typically only useful for the system process, to prevent it from
197      * blocking on calls to external untrusted code. Instead, all outgoing calls
198      * that require a result must be sent as {@link IBinder#FLAG_ONEWAY} calls
199      * which deliver results through a callback interface.
200      *
201      * @hide
202      */
setWarnOnBlocking(boolean warnOnBlocking)203     public static void setWarnOnBlocking(boolean warnOnBlocking) {
204         sWarnOnBlocking = warnOnBlocking;
205     }
206 
207     /**
208      * Allow blocking calls on the given interface, overriding the requested
209      * value of {@link #setWarnOnBlocking(boolean)}.
210      * <p>
211      * This should only be rarely called when you are <em>absolutely sure</em>
212      * the remote interface is a built-in system component that can never be
213      * upgraded. In particular, this <em>must never</em> be called for
214      * interfaces hosted by package that could be upgraded or replaced,
215      * otherwise you risk system instability if that remote interface wedges.
216      *
217      * @hide
218      */
allowBlocking(IBinder binder)219     public static IBinder allowBlocking(IBinder binder) {
220         try {
221             if (binder instanceof BinderProxy) {
222                 ((BinderProxy) binder).mWarnOnBlocking = false;
223             } else if (binder != null && binder.getInterfaceDescriptor() != null
224                     && binder.queryLocalInterface(binder.getInterfaceDescriptor()) == null) {
225                 Log.w(TAG, "Unable to allow blocking on interface " + binder);
226             }
227         } catch (RemoteException ignored) {
228         }
229         return binder;
230     }
231 
232     /**
233      * Reset the given interface back to the default blocking behavior,
234      * reverting any changes made by {@link #allowBlocking(IBinder)}.
235      *
236      * @hide
237      */
defaultBlocking(IBinder binder)238     public static IBinder defaultBlocking(IBinder binder) {
239         if (binder instanceof BinderProxy) {
240             ((BinderProxy) binder).mWarnOnBlocking = sWarnOnBlocking;
241         }
242         return binder;
243     }
244 
245     /**
246      * Inherit the current {@link #allowBlocking(IBinder)} value from one given
247      * interface to another.
248      *
249      * @hide
250      */
copyAllowBlocking(IBinder fromBinder, IBinder toBinder)251     public static void copyAllowBlocking(IBinder fromBinder, IBinder toBinder) {
252         if (fromBinder instanceof BinderProxy && toBinder instanceof BinderProxy) {
253             ((BinderProxy) toBinder).mWarnOnBlocking = ((BinderProxy) fromBinder).mWarnOnBlocking;
254         }
255     }
256 
257     static ThreadLocal<Boolean> sWarnOnBlockingOnCurrentThread =
258             ThreadLocal.withInitial(() -> sWarnOnBlocking);
259 
260     /**
261      * Allow blocking calls for the current thread.  See {@link #allowBlocking}.
262      *
263      * @hide
264      */
allowBlockingForCurrentThread()265     public static void allowBlockingForCurrentThread() {
266         sWarnOnBlockingOnCurrentThread.set(false);
267     }
268 
269     /**
270      * Reset the current thread to the default blocking behavior.  See {@link #defaultBlocking}.
271      *
272      * @hide
273      */
defaultBlockingForCurrentThread()274     public static void defaultBlockingForCurrentThread() {
275         sWarnOnBlockingOnCurrentThread.set(sWarnOnBlocking);
276     }
277 
278     /**
279      * Raw native pointer to JavaBBinderHolder object. Owned by this Java object. Not null.
280      */
281     @UnsupportedAppUsage
282     private final long mObject;
283 
284     private IInterface mOwner;
285     private String mDescriptor;
286 
287     /**
288      * Return the ID of the process that sent you the current transaction
289      * that is being processed.  This pid can be used with higher-level
290      * system services to determine its identity and check permissions.
291      * If the current thread is not currently executing an incoming transaction,
292      * then its own pid is returned.
293      *
294      * Warning: oneway transactions do not receive PID.
295      */
296     @CriticalNative
getCallingPid()297     public static final native int getCallingPid();
298 
299     /**
300      * Return the Linux uid assigned to the process that sent you the
301      * current transaction that is being processed.  This uid can be used with
302      * higher-level system services to determine its identity and check
303      * permissions.  If the current thread is not currently executing an
304      * incoming transaction, then its own uid is returned.
305      */
306     @CriticalNative
getCallingUid()307     public static final native int getCallingUid();
308 
309     /**
310      * Returns {@code true} if the current thread is currently executing an
311      * incoming transaction.
312      *
313      * @hide
314      */
315     @CriticalNative
isHandlingTransaction()316     public static final native boolean isHandlingTransaction();
317 
318     /**
319      * Return the Linux uid assigned to the process that sent the transaction
320      * currently being processed.
321      *
322      * @throws IllegalStateException if the current thread is not currently
323      *        executing an incoming transaction.
324      */
getCallingUidOrThrow()325     public static final int getCallingUidOrThrow() {
326         if (!isHandlingTransaction()) {
327             throw new IllegalStateException(
328                   "Thread is not in a binder transcation");
329         }
330         return getCallingUid();
331     }
332 
333     /**
334      * Return the UserHandle assigned to the process that sent you the
335      * current transaction that is being processed.  This is the user
336      * of the caller.  It is distinct from {@link #getCallingUid()} in that a
337      * particular user will have multiple distinct apps running under it each
338      * with their own uid.  If the current thread is not currently executing an
339      * incoming transaction, then its own UserHandle is returned.
340      */
getCallingUserHandle()341     public static final @NonNull UserHandle getCallingUserHandle() {
342         return UserHandle.of(UserHandle.getUserId(getCallingUid()));
343     }
344 
345     /**
346      * Reset the identity of the incoming IPC on the current thread.  This can
347      * be useful if, while handling an incoming call, you will be calling
348      * on interfaces of other objects that may be local to your process and
349      * need to do permission checks on the calls coming into them (so they
350      * will check the permission of your own local process, and not whatever
351      * process originally called you).
352      *
353      * @return Returns an opaque token that can be used to restore the
354      * original calling identity by passing it to
355      * {@link #restoreCallingIdentity(long)}.
356      *
357      * @see #getCallingPid()
358      * @see #getCallingUid()
359      * @see #restoreCallingIdentity(long)
360      */
361     @CriticalNative
clearCallingIdentity()362     public static final native long clearCallingIdentity();
363 
364     /**
365      * Restore the identity of the incoming IPC on the current thread
366      * back to a previously identity that was returned by {@link
367      * #clearCallingIdentity}.
368      *
369      * @param token The opaque token that was previously returned by
370      * {@link #clearCallingIdentity}.
371      *
372      * @see #clearCallingIdentity
373      */
374     @CriticalNative
restoreCallingIdentity(long token)375     public static final native void restoreCallingIdentity(long token);
376 
377     /**
378      * Convenience method for running the provided action enclosed in
379      * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity}
380      *
381      * Any exception thrown by the given action will be caught and rethrown after the call to
382      * {@link #restoreCallingIdentity}
383      *
384      * @hide
385      */
withCleanCallingIdentity(@onNull ThrowingRunnable action)386     public static final void withCleanCallingIdentity(@NonNull ThrowingRunnable action) {
387         Throwable throwableToPropagate = null;
388         final long callingIdentity = clearCallingIdentity();
389         try {
390             action.runOrThrow();
391         } catch (Throwable throwable) {
392             throwableToPropagate = throwable;
393         } finally {
394             restoreCallingIdentity(callingIdentity);
395             if (throwableToPropagate != null) {
396                 throw ExceptionUtils.propagate(throwableToPropagate);
397             }
398         }
399     }
400 
401     /**
402      * Convenience method for running the provided action enclosed in
403      * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity} returning the result
404      *
405      * Any exception thrown by the given action will be caught and rethrown after the call to
406      * {@link #restoreCallingIdentity}
407      *
408      * @hide
409      */
withCleanCallingIdentity(@onNull ThrowingSupplier<T> action)410     public static final <T> T withCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) {
411         Throwable throwableToPropagate = null;
412         final long callingIdentity = clearCallingIdentity();
413         try {
414             return action.getOrThrow();
415         } catch (Throwable throwable) {
416             throwableToPropagate = throwable;
417             return null; // overridden by throwing in finally block
418         } finally {
419             restoreCallingIdentity(callingIdentity);
420             if (throwableToPropagate != null) {
421                 throw ExceptionUtils.propagate(throwableToPropagate);
422             }
423         }
424     }
425 
426     /**
427      * Sets the native thread-local StrictMode policy mask.
428      *
429      * <p>The StrictMode settings are kept in two places: a Java-level
430      * threadlocal for libcore/Dalvik, and a native threadlocal (set
431      * here) for propagation via Binder calls.  This is a little
432      * unfortunate, but necessary to break otherwise more unfortunate
433      * dependencies either of Dalvik on Android, or Android
434      * native-only code on Dalvik.
435      *
436      * @see StrictMode
437      * @hide
438      */
439     @CriticalNative
setThreadStrictModePolicy(int policyMask)440     public static final native void setThreadStrictModePolicy(int policyMask);
441 
442     /**
443      * Gets the current native thread-local StrictMode policy mask.
444      *
445      * @see #setThreadStrictModePolicy
446      * @hide
447      */
448     @CriticalNative
getThreadStrictModePolicy()449     public static final native int getThreadStrictModePolicy();
450 
451     /**
452      * Sets the work source for this thread.
453      *
454      * <p>All the following binder calls on this thread will use the provided work source. If this
455      * is called during an on-going binder transaction, all the following binder calls will use the
456      * work source until the end of the transaction.
457      *
458      * <p>The concept of worksource is similar to {@link WorkSource}. However, for performance
459      * reasons, we only support one UID. This UID represents the original user responsible for the
460      * binder calls.
461      *
462      * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after setting the
463      * worksource.
464      *
465      * <p>A typical use case would be
466      * <pre>
467      * long token = Binder.setCallingWorkSourceUid(uid);
468      * try {
469      *   // Call an API.
470      * } finally {
471      *   Binder.restoreCallingWorkSource(token);
472      * }
473      * </pre>
474      *
475      * <p>The work source will be propagated for future outgoing binder transactions
476      * executed on this thread.
477      *
478      * @param workSource The original UID responsible for the binder call.
479      * @return token to restore original work source.
480      **/
481     @CriticalNative
setCallingWorkSourceUid(int workSource)482     public static final native long setCallingWorkSourceUid(int workSource);
483 
484     /**
485      * Returns the work source set by the caller.
486      *
487      * Unlike {@link Binder#getCallingUid()}, this result of this method cannot be trusted. The
488      * caller can set the value to whatever they want. Only use this value if you trust the calling
489      * uid.
490      *
491      * @return The original UID responsible for the binder transaction.
492      */
493     @CriticalNative
getCallingWorkSourceUid()494     public static final native int getCallingWorkSourceUid();
495 
496     /**
497      * Clears the work source on this thread.
498      *
499      * <p>The work source will be propagated for future outgoing binder transactions
500      * executed on this thread.
501      *
502      * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after clearing the
503      * worksource.
504      *
505      * <p>A typical use case would be
506      * <pre>
507      * long token = Binder.clearCallingWorkSource();
508      * try {
509      *   // Call an API.
510      * } finally {
511      *   Binder.restoreCallingWorkSource(token);
512      * }
513      * </pre>
514      *
515      * @return token to restore original work source.
516      **/
517     @CriticalNative
clearCallingWorkSource()518     public static final native long clearCallingWorkSource();
519 
520     /**
521      * Restores the work source on this thread using a token returned by
522      * {@link #setCallingWorkSourceUid(int) or {@link clearCallingWorkSource()}.
523      *
524      * <p>A typical use case would be
525      * <pre>
526      * long token = Binder.setCallingWorkSourceUid(uid);
527      * try {
528      *   // Call an API.
529      * } finally {
530      *   Binder.restoreCallingWorkSource(token);
531      * }
532      * </pre>
533      **/
534     @CriticalNative
restoreCallingWorkSource(long token)535     public static final native void restoreCallingWorkSource(long token);
536 
537     /**
538      * Mark as being built with VINTF-level stability promise. This API should
539      * only ever be invoked by generated code from the aidl compiler. It means
540      * that the interface represented by this binder is guaranteed to be kept
541      * stable for several years, according to the VINTF compatibility lifecycle,
542      * and the build system also keeps snapshots of these APIs and invokes the
543      * AIDL compiler to make sure that these snapshots are backwards compatible.
544      * Instead of using this API, use the @VintfStability annotation on your
545      * AIDL interface.
546      *
547      * @hide
548      */
549     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
markVintfStability()550     public final native void markVintfStability();
551 
552     /**
553      * Use a VINTF-stability binder w/o VINTF requirements. Should be called
554      * on a binder before it is sent out of process.
555      *
556      * This must be called before the object is sent to another process.
557      *
558      * @hide
559      */
forceDowngradeToSystemStability()560     public final native void forceDowngradeToSystemStability();
561 
562     /**
563      * Flush any Binder commands pending in the current thread to the kernel
564      * driver.  This can be
565      * useful to call before performing an operation that may block for a long
566      * time, to ensure that any pending object references have been released
567      * in order to prevent the process from holding on to objects longer than
568      * it needs to.
569      */
flushPendingCommands()570     public static final native void flushPendingCommands();
571 
572     /**
573      * Add the calling thread to the IPC thread pool.  This function does
574      * not return until the current process is exiting.
575      */
joinThreadPool()576     public static final void joinThreadPool() {
577         BinderInternal.joinThreadPool();
578     }
579 
580     /**
581      * Returns true if the specified interface is a proxy.
582      * @hide
583      */
isProxy(IInterface iface)584     public static final boolean isProxy(IInterface iface) {
585         return iface.asBinder() != iface;
586     }
587 
588     /**
589      * Call blocks until the number of executing binder threads is less
590      * than the maximum number of binder threads allowed for this process.
591      * @hide
592      */
blockUntilThreadAvailable()593     public static final native void blockUntilThreadAvailable();
594 
595     /**
596      * Default constructor just initializes the object.
597      *
598      * If you're creating a Binder token (a Binder object without an attached interface),
599      * you should use {@link #Binder(String)} instead.
600      */
Binder()601     public Binder() {
602         this(null);
603     }
604 
605     /**
606      * Constructor for creating a raw Binder object (token) along with a descriptor.
607      *
608      * The descriptor of binder objects usually specifies the interface they are implementing.
609      * In case of binder tokens, no interface is implemented, and the descriptor can be used
610      * as a sort of tag to help identify the binder token. This will help identify remote
611      * references to these objects more easily when debugging.
612      *
613      * @param descriptor Used to identify the creator of this token, for example the class name.
614      * Instead of creating multiple tokens with the same descriptor, consider adding a suffix to
615      * help identify them.
616      */
Binder(@ullable String descriptor)617     public Binder(@Nullable String descriptor)  {
618         mObject = getNativeBBinderHolder();
619         NoImagePreloadHolder.sRegistry.registerNativeAllocation(this, mObject);
620 
621         if (FIND_POTENTIAL_LEAKS) {
622             final Class<? extends Binder> klass = getClass();
623             if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
624                     (klass.getModifiers() & Modifier.STATIC) == 0) {
625                 Log.w(TAG, "The following Binder class should be static or leaks might occur: " +
626                     klass.getCanonicalName());
627             }
628         }
629         mDescriptor = descriptor;
630     }
631 
632     /**
633      * Convenience method for associating a specific interface with the Binder.
634      * After calling, queryLocalInterface() will be implemented for you
635      * to return the given owner IInterface when the corresponding
636      * descriptor is requested.
637      */
attachInterface(@ullable IInterface owner, @Nullable String descriptor)638     public void attachInterface(@Nullable IInterface owner, @Nullable String descriptor) {
639         mOwner = owner;
640         mDescriptor = descriptor;
641     }
642 
643     /**
644      * Default implementation returns an empty interface name.
645      */
getInterfaceDescriptor()646     public @Nullable String getInterfaceDescriptor() {
647         return mDescriptor;
648     }
649 
650     /**
651      * Default implementation always returns true -- if you got here,
652      * the object is alive.
653      */
pingBinder()654     public boolean pingBinder() {
655         return true;
656     }
657 
658     /**
659      * {@inheritDoc}
660      *
661      * Note that if you're calling on a local binder, this always returns true
662      * because your process is alive if you're calling it.
663      */
isBinderAlive()664     public boolean isBinderAlive() {
665         return true;
666     }
667 
668     /**
669      * Use information supplied to attachInterface() to return the
670      * associated IInterface if it matches the requested
671      * descriptor.
672      */
queryLocalInterface(@onNull String descriptor)673     public @Nullable IInterface queryLocalInterface(@NonNull String descriptor) {
674         if (mDescriptor != null && mDescriptor.equals(descriptor)) {
675             return mOwner;
676         }
677         return null;
678     }
679 
680     /**
681      * Control disabling of dump calls in this process.  This is used by the system
682      * process watchdog to disable incoming dump calls while it has detecting the system
683      * is hung and is reporting that back to the activity controller.  This is to
684      * prevent the controller from getting hung up on bug reports at this point.
685      * @hide
686      *
687      * @param msg The message to show instead of the dump; if null, dumps are
688      * re-enabled.
689      */
setDumpDisabled(String msg)690     public static void setDumpDisabled(String msg) {
691         sDumpDisabled = msg;
692     }
693 
694     /**
695      * Listener to be notified about each proxy-side binder call.
696      *
697      * See {@link setProxyTransactListener}.
698      * @hide
699      */
700     @SystemApi
701     public interface ProxyTransactListener {
702         /**
703          * Called before onTransact.
704          *
705          * @return an object that will be passed back to #onTransactEnded (or null).
706          * @hide
707          */
708         @Nullable
onTransactStarted(@onNull IBinder binder, int transactionCode, int flags)709         default Object onTransactStarted(@NonNull IBinder binder, int transactionCode, int flags) {
710             return onTransactStarted(binder, transactionCode);
711         }
712 
713         /**
714          * Called before onTransact.
715          *
716          * @return an object that will be passed back to #onTransactEnded (or null).
717          */
718         @Nullable
onTransactStarted(@onNull IBinder binder, int transactionCode)719         Object onTransactStarted(@NonNull IBinder binder, int transactionCode);
720 
721         /**
722          * Called after onTranact (even when an exception is thrown).
723          *
724          * @param session The object return by #onTransactStarted.
725          */
onTransactEnded(@ullable Object session)726         void onTransactEnded(@Nullable Object session);
727     }
728 
729     /**
730      * Propagates the work source to binder calls executed by the system server.
731      *
732      * <li>By default, this listener will propagate the worksource if the outgoing call happens on
733      * the same thread as the incoming binder call.
734      * <li>Custom attribution can be done by calling {@link ThreadLocalWorkSource#setUid(int)}.
735      * @hide
736      */
737     public static class PropagateWorkSourceTransactListener implements ProxyTransactListener {
738         @Override
onTransactStarted(IBinder binder, int transactionCode)739         public Object onTransactStarted(IBinder binder, int transactionCode) {
740            // Note that {@link Binder#getCallingUid()} is already set to the UID of the current
741            // process when this method is called.
742            //
743            // We use ThreadLocalWorkSource instead. It also allows feature owners to set
744            // {@link ThreadLocalWorkSource#set(int) manually to attribute resources to a UID.
745             int uid = ThreadLocalWorkSource.getUid();
746             if (uid != ThreadLocalWorkSource.UID_NONE) {
747                 return Binder.setCallingWorkSourceUid(uid);
748             }
749             return null;
750         }
751 
752         @Override
onTransactEnded(Object session)753         public void onTransactEnded(Object session) {
754             if (session != null) {
755                 long token = (long) session;
756                 Binder.restoreCallingWorkSource(token);
757             }
758         }
759     }
760 
761     /**
762      * Sets a listener for the transact method on the proxy-side.
763      *
764      * <li>The listener is global. Only fast operations should be done to avoid thread
765      * contentions.
766      * <li>The listener implementation needs to handle synchronization if needed. The methods on the
767      * listener can be called concurrently.
768      * <li>Listener set will be used for new transactions. On-going transaction will still use the
769      * previous listener (if already set).
770      * <li>The listener is called on the critical path of the binder transaction so be careful about
771      * performance.
772      * <li>Never execute another binder transaction inside the listener.
773      * @hide
774      */
775     @SystemApi
setProxyTransactListener(@ullable ProxyTransactListener listener)776     public static void setProxyTransactListener(@Nullable ProxyTransactListener listener) {
777         BinderProxy.setTransactListener(listener);
778     }
779 
780     /**
781      * Default implementation is a stub that returns false.  You will want
782      * to override this to do the appropriate unmarshalling of transactions.
783      *
784      * <p>If you want to call this, call transact().
785      *
786      * <p>Implementations that are returning a result should generally use
787      * {@link Parcel#writeNoException() Parcel.writeNoException} and
788      * {@link Parcel#writeException(Exception) Parcel.writeException} to propagate
789      * exceptions back to the caller.</p>
790      *
791      * @param code The action to perform.  This should
792      * be a number between {@link #FIRST_CALL_TRANSACTION} and
793      * {@link #LAST_CALL_TRANSACTION}.
794      * @param data Marshalled data being received from the caller.
795      * @param reply If the caller is expecting a result back, it should be marshalled
796      * in to here.
797      * @param flags Additional operation flags.  Either 0 for a normal
798      * RPC, or {@link #FLAG_ONEWAY} for a one-way RPC.
799      *
800      * @return Return true on a successful call; returning false is generally used to
801      * indicate that you did not understand the transaction code.
802      */
onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags)803     protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply,
804             int flags) throws RemoteException {
805         if (code == INTERFACE_TRANSACTION) {
806             reply.writeString(getInterfaceDescriptor());
807             return true;
808         } else if (code == DUMP_TRANSACTION) {
809             ParcelFileDescriptor fd = data.readFileDescriptor();
810             String[] args = data.readStringArray();
811             if (fd != null) {
812                 try {
813                     dump(fd.getFileDescriptor(), args);
814                 } finally {
815                     IoUtils.closeQuietly(fd);
816                 }
817             }
818             // Write the StrictMode header.
819             if (reply != null) {
820                 reply.writeNoException();
821             } else {
822                 StrictMode.clearGatheredViolations();
823             }
824             return true;
825         } else if (code == SHELL_COMMAND_TRANSACTION) {
826             ParcelFileDescriptor in = data.readFileDescriptor();
827             ParcelFileDescriptor out = data.readFileDescriptor();
828             ParcelFileDescriptor err = data.readFileDescriptor();
829             String[] args = data.readStringArray();
830             ShellCallback shellCallback = ShellCallback.CREATOR.createFromParcel(data);
831             ResultReceiver resultReceiver = ResultReceiver.CREATOR.createFromParcel(data);
832             try {
833                 if (out != null) {
834                     shellCommand(in != null ? in.getFileDescriptor() : null,
835                             out.getFileDescriptor(),
836                             err != null ? err.getFileDescriptor() : out.getFileDescriptor(),
837                             args, shellCallback, resultReceiver);
838                 }
839             } finally {
840                 IoUtils.closeQuietly(in);
841                 IoUtils.closeQuietly(out);
842                 IoUtils.closeQuietly(err);
843                 // Write the StrictMode header.
844                 if (reply != null) {
845                     reply.writeNoException();
846                 } else {
847                     StrictMode.clearGatheredViolations();
848                 }
849             }
850             return true;
851         }
852         return false;
853     }
854 
855     /**
856      * Resolves a transaction code to a human readable name.
857      *
858      * <p>Default implementation is a stub that returns null.
859      * <p>AIDL generated code will return the original method name.
860      *
861      * @param transactionCode The code to resolve.
862      * @return A human readable name.
863      * @hide
864      */
getTransactionName(int transactionCode)865     public @Nullable String getTransactionName(int transactionCode) {
866         return null;
867     }
868 
869     /**
870      * Implemented to call the more convenient version
871      * {@link #dump(FileDescriptor, PrintWriter, String[])}.
872      */
dump(@onNull FileDescriptor fd, @Nullable String[] args)873     public void dump(@NonNull FileDescriptor fd, @Nullable String[] args) {
874         FileOutputStream fout = new FileOutputStream(fd);
875         PrintWriter pw = new FastPrintWriter(fout);
876         try {
877             doDump(fd, pw, args);
878         } finally {
879             pw.flush();
880         }
881     }
882 
doDump(FileDescriptor fd, PrintWriter pw, String[] args)883     void doDump(FileDescriptor fd, PrintWriter pw, String[] args) {
884         final String disabled = sDumpDisabled;
885         if (disabled == null) {
886             try {
887                 dump(fd, pw, args);
888             } catch (SecurityException e) {
889                 pw.println("Security exception: " + e.getMessage());
890                 throw e;
891             } catch (Throwable e) {
892                 // Unlike usual calls, in this case if an exception gets thrown
893                 // back to us we want to print it back in to the dump data, since
894                 // that is where the caller expects all interesting information to
895                 // go.
896                 pw.println();
897                 pw.println("Exception occurred while dumping:");
898                 e.printStackTrace(pw);
899             }
900         } else {
901             pw.println(sDumpDisabled);
902         }
903     }
904 
905     /**
906      * Like {@link #dump(FileDescriptor, String[])}, but ensures the target
907      * executes asynchronously.
908      */
dumpAsync(@onNull final FileDescriptor fd, @Nullable final String[] args)909     public void dumpAsync(@NonNull final FileDescriptor fd, @Nullable final String[] args) {
910         final FileOutputStream fout = new FileOutputStream(fd);
911         final PrintWriter pw = new FastPrintWriter(fout);
912         Thread thr = new Thread("Binder.dumpAsync") {
913             public void run() {
914                 try {
915                     dump(fd, pw, args);
916                 } finally {
917                     pw.flush();
918                 }
919             }
920         };
921         thr.start();
922     }
923 
924     /**
925      * Print the object's state into the given stream.
926      *
927      * @param fd The raw file descriptor that the dump is being sent to.
928      * @param fout The file to which you should dump your state.  This will be
929      * closed for you after you return.
930      * @param args additional arguments to the dump request.
931      */
dump(@onNull FileDescriptor fd, @NonNull PrintWriter fout, @Nullable String[] args)932     protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter fout,
933             @Nullable String[] args) {
934     }
935 
936     /**
937      * @param in The raw file descriptor that an input data stream can be read from.
938      * @param out The raw file descriptor that normal command messages should be written to.
939      * @param err The raw file descriptor that command error messages should be written to.
940      * @param args Command-line arguments.
941      * @param callback Callback through which to interact with the invoking shell.
942      * @param resultReceiver Called when the command has finished executing, with the result code.
943      * @throws RemoteException
944      * @hide
945      */
shellCommand(@ullable FileDescriptor in, @Nullable FileDescriptor out, @Nullable FileDescriptor err, @NonNull String[] args, @Nullable ShellCallback callback, @NonNull ResultReceiver resultReceiver)946     public void shellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
947             @Nullable FileDescriptor err,
948             @NonNull String[] args, @Nullable ShellCallback callback,
949             @NonNull ResultReceiver resultReceiver) throws RemoteException {
950         onShellCommand(in, out, err, args, callback, resultReceiver);
951     }
952 
953     /**
954      * Handle a call to {@link #shellCommand}.
955      *
956      * <p>The default implementation performs a caller check to make sure the caller UID is of
957      * SHELL or ROOT, and then call {@link #handleShellCommand}.
958      *
959      * <p class="caution">Note: no permission checking is done before calling this method; you must
960      * apply any security checks as appropriate for the command being executed.
961      * Consider using {@link ShellCommand} to help in the implementation.</p>
962      * @hide
963      */
onShellCommand(@ullable FileDescriptor in, @Nullable FileDescriptor out, @Nullable FileDescriptor err, @NonNull String[] args, @Nullable ShellCallback callback, @NonNull ResultReceiver resultReceiver)964     public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
965             @Nullable FileDescriptor err,
966             @NonNull String[] args, @Nullable ShellCallback callback,
967             @NonNull ResultReceiver resultReceiver) throws RemoteException {
968 
969         final int callingUid = Binder.getCallingUid();
970         if (callingUid != Process.ROOT_UID && callingUid != Process.SHELL_UID) {
971             resultReceiver.send(-1, null);
972             throw new SecurityException("Shell commands are only callable by ADB");
973         }
974 
975         // First, convert in, out and err to @NonNull, by redirecting any that's null to /dev/null.
976         try {
977             if (in == null) {
978                 in = new FileInputStream("/dev/null").getFD();
979             }
980             if (out == null) {
981                 out = new FileOutputStream("/dev/null").getFD();
982             }
983             if (err == null) {
984                 err = out;
985             }
986         } catch (IOException e) {
987             PrintWriter pw = new FastPrintWriter(new FileOutputStream(err != null ? err : out));
988             pw.println("Failed to open /dev/null: " + e.getMessage());
989             pw.flush();
990             resultReceiver.send(-1, null);
991             return;
992         }
993         // Also make args @NonNull.
994         if (args == null) {
995             args = new String[0];
996         }
997 
998         int result = -1;
999         try (ParcelFileDescriptor inPfd = ParcelFileDescriptor.dup(in);
1000                 ParcelFileDescriptor outPfd = ParcelFileDescriptor.dup(out);
1001                 ParcelFileDescriptor errPfd = ParcelFileDescriptor.dup(err)) {
1002             result = handleShellCommand(inPfd, outPfd, errPfd, args);
1003         } catch (IOException e) {
1004             PrintWriter pw = new FastPrintWriter(new FileOutputStream(err));
1005             pw.println("dup() failed: " + e.getMessage());
1006             pw.flush();
1007         } finally {
1008             resultReceiver.send(result, null);
1009         }
1010     }
1011 
1012     /**
1013      * System services can implement this method to implement ADB shell commands.
1014      *
1015      * <p>A system binder service can implement it to handle shell commands on ADB. For example,
1016      * the Job Scheduler service implements it to handle <code>adb shell cmd jobscheduler</code>.
1017      *
1018      * <p>Commands are only executable by ADB shell; i.e. only {@link Process#SHELL_UID} and
1019      * {@link Process#ROOT_UID} can call them.
1020      *
1021      * @param in standard input
1022      * @param out standard output
1023      * @param err standard error
1024      * @param args arguments passed to the command. Can be empty. The first argument is typically
1025      *             a subcommand, such as {@code run} for {@code adb shell cmd jobscheduler run}.
1026      * @return the status code returned from the <code>cmd</code> command.
1027      *
1028      * @hide
1029      */
1030     @SystemApi
handleShellCommand(@onNull ParcelFileDescriptor in, @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err, @NonNull String[] args)1031     public int handleShellCommand(@NonNull ParcelFileDescriptor in,
1032             @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
1033             @NonNull String[] args) {
1034         FileOutputStream ferr = new FileOutputStream(err.getFileDescriptor());
1035         PrintWriter pw = new FastPrintWriter(ferr);
1036         pw.println("No shell command implementation.");
1037         pw.flush();
1038         return 0;
1039     }
1040 
1041     /** @hide */
1042     @Override
getExtension()1043     public final native @Nullable IBinder getExtension();
1044 
1045     /**
1046      * Set the binder extension.
1047      * This should be called immediately when the object is created.
1048      *
1049      * @hide
1050      */
setExtension(@ullable IBinder extension)1051     public final native void setExtension(@Nullable IBinder extension);
1052 
1053     /**
1054      * Default implementation rewinds the parcels and calls onTransact.  On
1055      * the remote side, transact calls into the binder to do the IPC.
1056      */
transact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags)1057     public final boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply,
1058             int flags) throws RemoteException {
1059         if (false) Log.v("Binder", "Transact: " + code + " to " + this);
1060 
1061         if (data != null) {
1062             data.setDataPosition(0);
1063         }
1064         boolean r = onTransact(code, data, reply, flags);
1065         if (reply != null) {
1066             reply.setDataPosition(0);
1067         }
1068         return r;
1069     }
1070 
1071     /**
1072      * Local implementation is a no-op.
1073      */
linkToDeath(@onNull DeathRecipient recipient, int flags)1074     public void linkToDeath(@NonNull DeathRecipient recipient, int flags) {
1075     }
1076 
1077     /**
1078      * Local implementation is a no-op.
1079      */
unlinkToDeath(@onNull DeathRecipient recipient, int flags)1080     public boolean unlinkToDeath(@NonNull DeathRecipient recipient, int flags) {
1081         return true;
1082     }
1083 
checkParcel(IBinder obj, int code, Parcel parcel, String msg)1084     static void checkParcel(IBinder obj, int code, Parcel parcel, String msg) {
1085         if (CHECK_PARCEL_SIZE && parcel.dataSize() >= 800*1024) {
1086             // Trying to send > 800k, this is way too much
1087             StringBuilder sb = new StringBuilder();
1088             sb.append(msg);
1089             sb.append(": on ");
1090             sb.append(obj);
1091             sb.append(" calling ");
1092             sb.append(code);
1093             sb.append(" size ");
1094             sb.append(parcel.dataSize());
1095             sb.append(" (data: ");
1096             parcel.setDataPosition(0);
1097             sb.append(parcel.readInt());
1098             sb.append(", ");
1099             sb.append(parcel.readInt());
1100             sb.append(", ");
1101             sb.append(parcel.readInt());
1102             sb.append(")");
1103             Slog.wtfStack(TAG, sb.toString());
1104         }
1105     }
1106 
getNativeBBinderHolder()1107     private static native long getNativeBBinderHolder();
1108 
1109     /**
1110      * By default, we use the calling uid since we can always trust it.
1111      */
1112     private static volatile BinderInternal.WorkSourceProvider sWorkSourceProvider =
1113             (x) -> Binder.getCallingUid();
1114 
1115     /**
1116      * Sets the work source provider.
1117      *
1118      * <li>The callback is global. Only fast operations should be done to avoid thread
1119      * contentions.
1120      * <li>The callback implementation needs to handle synchronization if needed. The methods on the
1121      * callback can be called concurrently.
1122      * <li>The callback is called on the critical path of the binder transaction so be careful about
1123      * performance.
1124      * <li>Never execute another binder transaction inside the callback.
1125      * @hide
1126      */
setWorkSourceProvider(BinderInternal.WorkSourceProvider workSourceProvider)1127     public static void setWorkSourceProvider(BinderInternal.WorkSourceProvider workSourceProvider) {
1128         if (workSourceProvider == null) {
1129             throw new IllegalArgumentException("workSourceProvider cannot be null");
1130         }
1131         sWorkSourceProvider = workSourceProvider;
1132     }
1133 
1134     // Entry point from android_util_Binder.cpp's onTransact
1135     @UnsupportedAppUsage
execTransact(int code, long dataObj, long replyObj, int flags)1136     private boolean execTransact(int code, long dataObj, long replyObj,
1137             int flags) {
1138         // At that point, the parcel request headers haven't been parsed so we do not know what
1139         // WorkSource the caller has set. Use calling uid as the default.
1140         final int callingUid = Binder.getCallingUid();
1141         final long origWorkSource = ThreadLocalWorkSource.setUid(callingUid);
1142         try {
1143             return execTransactInternal(code, dataObj, replyObj, flags, callingUid);
1144         } finally {
1145             ThreadLocalWorkSource.restore(origWorkSource);
1146         }
1147     }
1148 
execTransactInternal(int code, long dataObj, long replyObj, int flags, int callingUid)1149     private boolean execTransactInternal(int code, long dataObj, long replyObj, int flags,
1150             int callingUid) {
1151         // Make sure the observer won't change while processing a transaction.
1152         final BinderInternal.Observer observer = sObserver;
1153         final CallSession callSession =
1154                 observer != null ? observer.callStarted(this, code, UNSET_WORKSOURCE) : null;
1155         Parcel data = Parcel.obtain(dataObj);
1156         Parcel reply = Parcel.obtain(replyObj);
1157         // theoretically, we should call transact, which will call onTransact,
1158         // but all that does is rewind it, and we just got these from an IPC,
1159         // so we'll just call it directly.
1160         boolean res;
1161         // Log any exceptions as warnings, don't silently suppress them.
1162         // If the call was FLAG_ONEWAY then these exceptions disappear into the ether.
1163         final boolean tracingEnabled = Binder.isTracingEnabled();
1164         try {
1165             final BinderCallHeavyHitterWatcher heavyHitterWatcher = sHeavyHitterWatcher;
1166             if (heavyHitterWatcher != null) {
1167                 // Notify the heavy hitter watcher, if it's enabled
1168                 heavyHitterWatcher.onTransaction(callingUid, getClass(), code);
1169             }
1170             if (tracingEnabled) {
1171                 final String transactionName = getTransactionName(code);
1172                 Trace.traceBegin(Trace.TRACE_TAG_ALWAYS, getClass().getName() + ":"
1173                         + (transactionName != null ? transactionName : code));
1174             }
1175 
1176             if ((flags & FLAG_COLLECT_NOTED_APP_OPS) != 0) {
1177                 AppOpsManager.startNotedAppOpsCollection(callingUid);
1178                 try {
1179                     res = onTransact(code, data, reply, flags);
1180                 } finally {
1181                     AppOpsManager.finishNotedAppOpsCollection();
1182                 }
1183             } else {
1184                 res = onTransact(code, data, reply, flags);
1185             }
1186         } catch (RemoteException|RuntimeException e) {
1187             if (observer != null) {
1188                 observer.callThrewException(callSession, e);
1189             }
1190             if (LOG_RUNTIME_EXCEPTION) {
1191                 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
1192             }
1193             if ((flags & FLAG_ONEWAY) != 0) {
1194                 if (e instanceof RemoteException) {
1195                     Log.w(TAG, "Binder call failed.", e);
1196                 } else {
1197                     Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
1198                 }
1199             } else {
1200                 // Clear the parcel before writing the exception
1201                 reply.setDataSize(0);
1202                 reply.setDataPosition(0);
1203                 reply.writeException(e);
1204             }
1205             res = true;
1206         } finally {
1207             if (tracingEnabled) {
1208                 Trace.traceEnd(Trace.TRACE_TAG_ALWAYS);
1209             }
1210             if (observer != null) {
1211                 // The parcel RPC headers have been called during onTransact so we can now access
1212                 // the worksource uid from the parcel.
1213                 final int workSourceUid = sWorkSourceProvider.resolveWorkSourceUid(
1214                         data.readCallingWorkSourceUid());
1215                 observer.callEnded(callSession, data.dataSize(), reply.dataSize(), workSourceUid);
1216             }
1217         }
1218         checkParcel(this, code, reply, "Unreasonably large binder reply buffer");
1219         reply.recycle();
1220         data.recycle();
1221 
1222         // Just in case -- we are done with the IPC, so there should be no more strict
1223         // mode violations that have gathered for this thread.  Either they have been
1224         // parceled and are now in transport off to the caller, or we are returning back
1225         // to the main transaction loop to wait for another incoming transaction.  Either
1226         // way, strict mode begone!
1227         StrictMode.clearGatheredViolations();
1228         return res;
1229     }
1230 
1231     /**
1232      * Set the configuration for the heavy hitter watcher.
1233      *
1234      * @hide
1235      */
setHeavyHitterWatcherConfig(final boolean enabled, final int batchSize, final float threshold, @Nullable final BinderCallHeavyHitterListener listener)1236     public static synchronized void setHeavyHitterWatcherConfig(final boolean enabled,
1237             final int batchSize, final float threshold,
1238             @Nullable final BinderCallHeavyHitterListener listener) {
1239         Slog.i(TAG, "Setting heavy hitter watcher config: "
1240                 + enabled + ", " + batchSize + ", " + threshold);
1241         BinderCallHeavyHitterWatcher watcher = sHeavyHitterWatcher;
1242         if (enabled) {
1243             if (listener == null) {
1244                 throw new IllegalArgumentException();
1245             }
1246             boolean newWatcher = false;
1247             if (watcher == null) {
1248                 watcher = BinderCallHeavyHitterWatcher.getInstance();
1249                 newWatcher = true;
1250             }
1251             watcher.setConfig(true, batchSize, threshold, listener);
1252             if (newWatcher) {
1253                 sHeavyHitterWatcher = watcher;
1254             }
1255         } else if (watcher != null) {
1256             watcher.setConfig(false, 0, 0.0f, null);
1257         }
1258     }
1259 }
1260