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