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