• 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.util.ExceptionUtils;
22 import android.util.Log;
23 import android.util.Slog;
24 import android.util.SparseIntArray;
25 
26 import com.android.internal.os.BinderCallsStats;
27 import com.android.internal.os.BinderInternal;
28 import com.android.internal.util.FastPrintWriter;
29 import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
30 import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
31 
32 import libcore.io.IoUtils;
33 import libcore.util.NativeAllocationRegistry;
34 
35 import java.io.FileDescriptor;
36 import java.io.FileOutputStream;
37 import java.io.PrintWriter;
38 import java.lang.ref.WeakReference;
39 import java.lang.reflect.Modifier;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.HashMap;
43 import java.util.Map;
44 
45 /**
46  * Base class for a remotable object, the core part of a lightweight
47  * remote procedure call mechanism defined by {@link IBinder}.
48  * This class is an implementation of IBinder that provides
49  * standard local implementation of such an object.
50  *
51  * <p>Most developers will not implement this class directly, instead using the
52  * <a href="{@docRoot}guide/components/aidl.html">aidl</a> tool to describe the desired
53  * interface, having it generate the appropriate Binder subclass.  You can,
54  * however, derive directly from Binder to implement your own custom RPC
55  * protocol or simply instantiate a raw Binder object directly to use as a
56  * token that can be shared across processes.
57  *
58  * <p>This class is just a basic IPC primitive; it has no impact on an application's
59  * lifecycle, and is valid only as long as the process that created it continues to run.
60  * To use this correctly, you must be doing so within the context of a top-level
61  * application component (a {@link android.app.Service}, {@link android.app.Activity},
62  * or {@link android.content.ContentProvider}) that lets the system know your process
63  * should remain running.</p>
64  *
65  * <p>You must keep in mind the situations in which your process
66  * could go away, and thus require that you later re-create a new Binder and re-attach
67  * it when the process starts again.  For example, if you are using this within an
68  * {@link android.app.Activity}, your activity's process may be killed any time the
69  * activity is not started; if the activity is later re-created you will need to
70  * create a new Binder and hand it back to the correct place again; you need to be
71  * aware that your process may be started for another reason (for example to receive
72  * a broadcast) that will not involve re-creating the activity and thus run its code
73  * to create a new Binder.</p>
74  *
75  * @see IBinder
76  */
77 public class Binder implements IBinder {
78     /*
79      * Set this flag to true to detect anonymous, local or member classes
80      * that extend this Binder class and that are not static. These kind
81      * of classes can potentially create leaks.
82      */
83     private static final boolean FIND_POTENTIAL_LEAKS = false;
84     /** @hide */
85     public static final boolean CHECK_PARCEL_SIZE = false;
86     static final String TAG = "Binder";
87 
88     /** @hide */
89     public static boolean LOG_RUNTIME_EXCEPTION = false; // DO NOT SUBMIT WITH TRUE
90 
91     /**
92      * Control whether dump() calls are allowed.
93      */
94     private static volatile String sDumpDisabled = null;
95 
96     /**
97      * Global transaction tracker instance for this process.
98      */
99     private static volatile TransactionTracker sTransactionTracker = null;
100 
101     /**
102      * Guestimate of native memory associated with a Binder.
103      */
104     private static final int NATIVE_ALLOCATION_SIZE = 500;
105 
getNativeFinalizer()106     private static native long getNativeFinalizer();
107 
108     // Use a Holder to allow static initialization of Binder in the boot image, and
109     // possibly to avoid some initialization ordering issues.
110     private static class NoImagePreloadHolder {
111         public static final NativeAllocationRegistry sRegistry = new NativeAllocationRegistry(
112                 Binder.class.getClassLoader(), getNativeFinalizer(), NATIVE_ALLOCATION_SIZE);
113     }
114 
115     // Transaction tracking code.
116 
117     /**
118      * Flag indicating whether we should be tracing transact calls.
119      */
120     private static volatile boolean sTracingEnabled = false;
121 
122     /**
123      * Enable Binder IPC tracing.
124      *
125      * @hide
126      */
enableTracing()127     public static void enableTracing() {
128         sTracingEnabled = true;
129     }
130 
131     /**
132      * Disable Binder IPC tracing.
133      *
134      * @hide
135      */
disableTracing()136     public static void disableTracing() {
137         sTracingEnabled = false;
138     }
139 
140     /**
141      * Check if binder transaction tracing is enabled.
142      *
143      * @hide
144      */
isTracingEnabled()145     public static boolean isTracingEnabled() {
146         return sTracingEnabled;
147     }
148 
149     /**
150      * Get the binder transaction tracker for this process.
151      *
152      * @hide
153      */
getTransactionTracker()154     public synchronized static TransactionTracker getTransactionTracker() {
155         if (sTransactionTracker == null)
156             sTransactionTracker = new TransactionTracker();
157         return sTransactionTracker;
158     }
159 
160     /** {@hide} */
161     static volatile boolean sWarnOnBlocking = false;
162 
163     /**
164      * Warn if any blocking binder transactions are made out from this process.
165      * This is typically only useful for the system process, to prevent it from
166      * blocking on calls to external untrusted code. Instead, all outgoing calls
167      * that require a result must be sent as {@link IBinder#FLAG_ONEWAY} calls
168      * which deliver results through a callback interface.
169      *
170      * @hide
171      */
setWarnOnBlocking(boolean warnOnBlocking)172     public static void setWarnOnBlocking(boolean warnOnBlocking) {
173         sWarnOnBlocking = warnOnBlocking;
174     }
175 
176     /**
177      * Allow blocking calls on the given interface, overriding the requested
178      * value of {@link #setWarnOnBlocking(boolean)}.
179      * <p>
180      * This should only be rarely called when you are <em>absolutely sure</em>
181      * the remote interface is a built-in system component that can never be
182      * upgraded. In particular, this <em>must never</em> be called for
183      * interfaces hosted by package that could be upgraded or replaced,
184      * otherwise you risk system instability if that remote interface wedges.
185      *
186      * @hide
187      */
allowBlocking(IBinder binder)188     public static IBinder allowBlocking(IBinder binder) {
189         try {
190             if (binder instanceof BinderProxy) {
191                 ((BinderProxy) binder).mWarnOnBlocking = false;
192             } else if (binder != null && binder.getInterfaceDescriptor() != null
193                     && binder.queryLocalInterface(binder.getInterfaceDescriptor()) == null) {
194                 Log.w(TAG, "Unable to allow blocking on interface " + binder);
195             }
196         } catch (RemoteException ignored) {
197         }
198         return binder;
199     }
200 
201     /**
202      * Reset the given interface back to the default blocking behavior,
203      * reverting any changes made by {@link #allowBlocking(IBinder)}.
204      *
205      * @hide
206      */
defaultBlocking(IBinder binder)207     public static IBinder defaultBlocking(IBinder binder) {
208         if (binder instanceof BinderProxy) {
209             ((BinderProxy) binder).mWarnOnBlocking = sWarnOnBlocking;
210         }
211         return binder;
212     }
213 
214     /**
215      * Inherit the current {@link #allowBlocking(IBinder)} value from one given
216      * interface to another.
217      *
218      * @hide
219      */
copyAllowBlocking(IBinder fromBinder, IBinder toBinder)220     public static void copyAllowBlocking(IBinder fromBinder, IBinder toBinder) {
221         if (fromBinder instanceof BinderProxy && toBinder instanceof BinderProxy) {
222             ((BinderProxy) toBinder).mWarnOnBlocking = ((BinderProxy) fromBinder).mWarnOnBlocking;
223         }
224     }
225 
226     /**
227      * Raw native pointer to JavaBBinderHolder object. Owned by this Java object. Not null.
228      */
229     private final long mObject;
230 
231     private IInterface mOwner;
232     private String mDescriptor;
233 
234     /**
235      * Return the ID of the process that sent you the current transaction
236      * that is being processed.  This pid can be used with higher-level
237      * system services to determine its identity and check permissions.
238      * If the current thread is not currently executing an incoming transaction,
239      * then its own pid is returned.
240      */
getCallingPid()241     public static final native int getCallingPid();
242 
243     /**
244      * Return the Linux uid assigned to the process that sent you the
245      * current transaction that is being processed.  This uid can be used with
246      * higher-level system services to determine its identity and check
247      * permissions.  If the current thread is not currently executing an
248      * incoming transaction, then its own uid is returned.
249      */
getCallingUid()250     public static final native int getCallingUid();
251 
252     /**
253      * Return the UserHandle assigned to the process that sent you the
254      * current transaction that is being processed.  This is the user
255      * of the caller.  It is distinct from {@link #getCallingUid()} in that a
256      * particular user will have multiple distinct apps running under it each
257      * with their own uid.  If the current thread is not currently executing an
258      * incoming transaction, then its own UserHandle is returned.
259      */
getCallingUserHandle()260     public static final @NonNull UserHandle getCallingUserHandle() {
261         return UserHandle.of(UserHandle.getUserId(getCallingUid()));
262     }
263 
264     /**
265      * Reset the identity of the incoming IPC on the current thread.  This can
266      * be useful if, while handling an incoming call, you will be calling
267      * on interfaces of other objects that may be local to your process and
268      * need to do permission checks on the calls coming into them (so they
269      * will check the permission of your own local process, and not whatever
270      * process originally called you).
271      *
272      * @return Returns an opaque token that can be used to restore the
273      * original calling identity by passing it to
274      * {@link #restoreCallingIdentity(long)}.
275      *
276      * @see #getCallingPid()
277      * @see #getCallingUid()
278      * @see #restoreCallingIdentity(long)
279      */
clearCallingIdentity()280     public static final native long clearCallingIdentity();
281 
282     /**
283      * Restore the identity of the incoming IPC on the current thread
284      * back to a previously identity that was returned by {@link
285      * #clearCallingIdentity}.
286      *
287      * @param token The opaque token that was previously returned by
288      * {@link #clearCallingIdentity}.
289      *
290      * @see #clearCallingIdentity
291      */
restoreCallingIdentity(long token)292     public static final native void restoreCallingIdentity(long token);
293 
294     /**
295      * Convenience method for running the provided action enclosed in
296      * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity}
297      *
298      * Any exception thrown by the given action will be caught and rethrown after the call to
299      * {@link #restoreCallingIdentity}
300      *
301      * @hide
302      */
withCleanCallingIdentity(@onNull ThrowingRunnable action)303     public static final void withCleanCallingIdentity(@NonNull ThrowingRunnable action) {
304         long callingIdentity = clearCallingIdentity();
305         Throwable throwableToPropagate = null;
306         try {
307             action.runOrThrow();
308         } catch (Throwable throwable) {
309             throwableToPropagate = throwable;
310         } finally {
311             restoreCallingIdentity(callingIdentity);
312             if (throwableToPropagate != null) {
313                 throw ExceptionUtils.propagate(throwableToPropagate);
314             }
315         }
316     }
317 
318     /**
319      * Convenience method for running the provided action enclosed in
320      * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity} returning the result
321      *
322      * Any exception thrown by the given action will be caught and rethrown after the call to
323      * {@link #restoreCallingIdentity}
324      *
325      * @hide
326      */
withCleanCallingIdentity(@onNull ThrowingSupplier<T> action)327     public static final <T> T withCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) {
328         long callingIdentity = clearCallingIdentity();
329         Throwable throwableToPropagate = null;
330         try {
331             return action.getOrThrow();
332         } catch (Throwable throwable) {
333             throwableToPropagate = throwable;
334             return null; // overridden by throwing in finally block
335         } finally {
336             restoreCallingIdentity(callingIdentity);
337             if (throwableToPropagate != null) {
338                 throw ExceptionUtils.propagate(throwableToPropagate);
339             }
340         }
341     }
342 
343     /**
344      * Sets the native thread-local StrictMode policy mask.
345      *
346      * <p>The StrictMode settings are kept in two places: a Java-level
347      * threadlocal for libcore/Dalvik, and a native threadlocal (set
348      * here) for propagation via Binder calls.  This is a little
349      * unfortunate, but necessary to break otherwise more unfortunate
350      * dependencies either of Dalvik on Android, or Android
351      * native-only code on Dalvik.
352      *
353      * @see StrictMode
354      * @hide
355      */
setThreadStrictModePolicy(int policyMask)356     public static final native void setThreadStrictModePolicy(int policyMask);
357 
358     /**
359      * Gets the current native thread-local StrictMode policy mask.
360      *
361      * @see #setThreadStrictModePolicy
362      * @hide
363      */
getThreadStrictModePolicy()364     public static final native int getThreadStrictModePolicy();
365 
366     /**
367      * Flush any Binder commands pending in the current thread to the kernel
368      * driver.  This can be
369      * useful to call before performing an operation that may block for a long
370      * time, to ensure that any pending object references have been released
371      * in order to prevent the process from holding on to objects longer than
372      * it needs to.
373      */
flushPendingCommands()374     public static final native void flushPendingCommands();
375 
376     /**
377      * Add the calling thread to the IPC thread pool.  This function does
378      * not return until the current process is exiting.
379      */
joinThreadPool()380     public static final void joinThreadPool() {
381         BinderInternal.joinThreadPool();
382     }
383 
384     /**
385      * Returns true if the specified interface is a proxy.
386      * @hide
387      */
isProxy(IInterface iface)388     public static final boolean isProxy(IInterface iface) {
389         return iface.asBinder() != iface;
390     }
391 
392     /**
393      * Call blocks until the number of executing binder threads is less
394      * than the maximum number of binder threads allowed for this process.
395      * @hide
396      */
blockUntilThreadAvailable()397     public static final native void blockUntilThreadAvailable();
398 
399     /**
400      * Default constructor initializes the object.
401      */
Binder()402     public Binder() {
403         mObject = getNativeBBinderHolder();
404         NoImagePreloadHolder.sRegistry.registerNativeAllocation(this, mObject);
405 
406         if (FIND_POTENTIAL_LEAKS) {
407             final Class<? extends Binder> klass = getClass();
408             if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
409                     (klass.getModifiers() & Modifier.STATIC) == 0) {
410                 Log.w(TAG, "The following Binder class should be static or leaks might occur: " +
411                     klass.getCanonicalName());
412             }
413         }
414     }
415 
416     /**
417      * Convenience method for associating a specific interface with the Binder.
418      * After calling, queryLocalInterface() will be implemented for you
419      * to return the given owner IInterface when the corresponding
420      * descriptor is requested.
421      */
attachInterface(@ullable IInterface owner, @Nullable String descriptor)422     public void attachInterface(@Nullable IInterface owner, @Nullable String descriptor) {
423         mOwner = owner;
424         mDescriptor = descriptor;
425     }
426 
427     /**
428      * Default implementation returns an empty interface name.
429      */
getInterfaceDescriptor()430     public @Nullable String getInterfaceDescriptor() {
431         return mDescriptor;
432     }
433 
434     /**
435      * Default implementation always returns true -- if you got here,
436      * the object is alive.
437      */
pingBinder()438     public boolean pingBinder() {
439         return true;
440     }
441 
442     /**
443      * {@inheritDoc}
444      *
445      * Note that if you're calling on a local binder, this always returns true
446      * because your process is alive if you're calling it.
447      */
isBinderAlive()448     public boolean isBinderAlive() {
449         return true;
450     }
451 
452     /**
453      * Use information supplied to attachInterface() to return the
454      * associated IInterface if it matches the requested
455      * descriptor.
456      */
queryLocalInterface(@onNull String descriptor)457     public @Nullable IInterface queryLocalInterface(@NonNull String descriptor) {
458         if (mDescriptor != null && mDescriptor.equals(descriptor)) {
459             return mOwner;
460         }
461         return null;
462     }
463 
464     /**
465      * Control disabling of dump calls in this process.  This is used by the system
466      * process watchdog to disable incoming dump calls while it has detecting the system
467      * is hung and is reporting that back to the activity controller.  This is to
468      * prevent the controller from getting hung up on bug reports at this point.
469      * @hide
470      *
471      * @param msg The message to show instead of the dump; if null, dumps are
472      * re-enabled.
473      */
setDumpDisabled(String msg)474     public static void setDumpDisabled(String msg) {
475         sDumpDisabled = msg;
476     }
477 
478     /**
479      * Default implementation is a stub that returns false.  You will want
480      * to override this to do the appropriate unmarshalling of transactions.
481      *
482      * <p>If you want to call this, call transact().
483      *
484      * <p>Implementations that are returning a result should generally use
485      * {@link Parcel#writeNoException() Parcel.writeNoException} and
486      * {@link Parcel#writeException(Exception) Parcel.writeException} to propagate
487      * exceptions back to the caller.</p>
488      *
489      * @param code The action to perform.  This should
490      * be a number between {@link #FIRST_CALL_TRANSACTION} and
491      * {@link #LAST_CALL_TRANSACTION}.
492      * @param data Marshalled data being received from the caller.
493      * @param reply If the caller is expecting a result back, it should be marshalled
494      * in to here.
495      * @param flags Additional operation flags.  Either 0 for a normal
496      * RPC, or {@link #FLAG_ONEWAY} for a one-way RPC.
497      *
498      * @return Return true on a successful call; returning false is generally used to
499      * indicate that you did not understand the transaction code.
500      */
onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags)501     protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply,
502             int flags) throws RemoteException {
503         if (code == INTERFACE_TRANSACTION) {
504             reply.writeString(getInterfaceDescriptor());
505             return true;
506         } else if (code == DUMP_TRANSACTION) {
507             ParcelFileDescriptor fd = data.readFileDescriptor();
508             String[] args = data.readStringArray();
509             if (fd != null) {
510                 try {
511                     dump(fd.getFileDescriptor(), args);
512                 } finally {
513                     IoUtils.closeQuietly(fd);
514                 }
515             }
516             // Write the StrictMode header.
517             if (reply != null) {
518                 reply.writeNoException();
519             } else {
520                 StrictMode.clearGatheredViolations();
521             }
522             return true;
523         } else if (code == SHELL_COMMAND_TRANSACTION) {
524             ParcelFileDescriptor in = data.readFileDescriptor();
525             ParcelFileDescriptor out = data.readFileDescriptor();
526             ParcelFileDescriptor err = data.readFileDescriptor();
527             String[] args = data.readStringArray();
528             ShellCallback shellCallback = ShellCallback.CREATOR.createFromParcel(data);
529             ResultReceiver resultReceiver = ResultReceiver.CREATOR.createFromParcel(data);
530             try {
531                 if (out != null) {
532                     shellCommand(in != null ? in.getFileDescriptor() : null,
533                             out.getFileDescriptor(),
534                             err != null ? err.getFileDescriptor() : out.getFileDescriptor(),
535                             args, shellCallback, resultReceiver);
536                 }
537             } finally {
538                 IoUtils.closeQuietly(in);
539                 IoUtils.closeQuietly(out);
540                 IoUtils.closeQuietly(err);
541                 // Write the StrictMode header.
542                 if (reply != null) {
543                     reply.writeNoException();
544                 } else {
545                     StrictMode.clearGatheredViolations();
546                 }
547             }
548             return true;
549         }
550         return false;
551     }
552 
553     /**
554      * Implemented to call the more convenient version
555      * {@link #dump(FileDescriptor, PrintWriter, String[])}.
556      */
dump(@onNull FileDescriptor fd, @Nullable String[] args)557     public void dump(@NonNull FileDescriptor fd, @Nullable String[] args) {
558         FileOutputStream fout = new FileOutputStream(fd);
559         PrintWriter pw = new FastPrintWriter(fout);
560         try {
561             doDump(fd, pw, args);
562         } finally {
563             pw.flush();
564         }
565     }
566 
doDump(FileDescriptor fd, PrintWriter pw, String[] args)567     void doDump(FileDescriptor fd, PrintWriter pw, String[] args) {
568         final String disabled = sDumpDisabled;
569         if (disabled == null) {
570             try {
571                 dump(fd, pw, args);
572             } catch (SecurityException e) {
573                 pw.println("Security exception: " + e.getMessage());
574                 throw e;
575             } catch (Throwable e) {
576                 // Unlike usual calls, in this case if an exception gets thrown
577                 // back to us we want to print it back in to the dump data, since
578                 // that is where the caller expects all interesting information to
579                 // go.
580                 pw.println();
581                 pw.println("Exception occurred while dumping:");
582                 e.printStackTrace(pw);
583             }
584         } else {
585             pw.println(sDumpDisabled);
586         }
587     }
588 
589     /**
590      * Like {@link #dump(FileDescriptor, String[])}, but ensures the target
591      * executes asynchronously.
592      */
dumpAsync(@onNull final FileDescriptor fd, @Nullable final String[] args)593     public void dumpAsync(@NonNull final FileDescriptor fd, @Nullable final String[] args) {
594         final FileOutputStream fout = new FileOutputStream(fd);
595         final PrintWriter pw = new FastPrintWriter(fout);
596         Thread thr = new Thread("Binder.dumpAsync") {
597             public void run() {
598                 try {
599                     dump(fd, pw, args);
600                 } finally {
601                     pw.flush();
602                 }
603             }
604         };
605         thr.start();
606     }
607 
608     /**
609      * Print the object's state into the given stream.
610      *
611      * @param fd The raw file descriptor that the dump is being sent to.
612      * @param fout The file to which you should dump your state.  This will be
613      * closed for you after you return.
614      * @param args additional arguments to the dump request.
615      */
dump(@onNull FileDescriptor fd, @NonNull PrintWriter fout, @Nullable String[] args)616     protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter fout,
617             @Nullable String[] args) {
618     }
619 
620     /**
621      * @param in The raw file descriptor that an input data stream can be read from.
622      * @param out The raw file descriptor that normal command messages should be written to.
623      * @param err The raw file descriptor that command error messages should be written to.
624      * @param args Command-line arguments.
625      * @param callback Callback through which to interact with the invoking shell.
626      * @param resultReceiver Called when the command has finished executing, with the result code.
627      * @throws RemoteException
628      * @hide
629      */
shellCommand(@ullable FileDescriptor in, @Nullable FileDescriptor out, @Nullable FileDescriptor err, @NonNull String[] args, @Nullable ShellCallback callback, @NonNull ResultReceiver resultReceiver)630     public void shellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
631             @Nullable FileDescriptor err,
632             @NonNull String[] args, @Nullable ShellCallback callback,
633             @NonNull ResultReceiver resultReceiver) throws RemoteException {
634         onShellCommand(in, out, err, args, callback, resultReceiver);
635     }
636 
637     /**
638      * Handle a call to {@link #shellCommand}.  The default implementation simply prints
639      * an error message.  Override and replace with your own.
640      * <p class="caution">Note: no permission checking is done before calling this method; you must
641      * apply any security checks as appropriate for the command being executed.
642      * Consider using {@link ShellCommand} to help in the implementation.</p>
643      * @hide
644      */
onShellCommand(@ullable FileDescriptor in, @Nullable FileDescriptor out, @Nullable FileDescriptor err, @NonNull String[] args, @Nullable ShellCallback callback, @NonNull ResultReceiver resultReceiver)645     public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
646             @Nullable FileDescriptor err,
647             @NonNull String[] args, @Nullable ShellCallback callback,
648             @NonNull ResultReceiver resultReceiver) throws RemoteException {
649         FileOutputStream fout = new FileOutputStream(err != null ? err : out);
650         PrintWriter pw = new FastPrintWriter(fout);
651         pw.println("No shell command implementation.");
652         pw.flush();
653         resultReceiver.send(0, null);
654     }
655 
656     /**
657      * Default implementation rewinds the parcels and calls onTransact.  On
658      * the remote side, transact calls into the binder to do the IPC.
659      */
transact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags)660     public final boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply,
661             int flags) throws RemoteException {
662         if (false) Log.v("Binder", "Transact: " + code + " to " + this);
663 
664         if (data != null) {
665             data.setDataPosition(0);
666         }
667         boolean r = onTransact(code, data, reply, flags);
668         if (reply != null) {
669             reply.setDataPosition(0);
670         }
671         return r;
672     }
673 
674     /**
675      * Local implementation is a no-op.
676      */
linkToDeath(@onNull DeathRecipient recipient, int flags)677     public void linkToDeath(@NonNull DeathRecipient recipient, int flags) {
678     }
679 
680     /**
681      * Local implementation is a no-op.
682      */
unlinkToDeath(@onNull DeathRecipient recipient, int flags)683     public boolean unlinkToDeath(@NonNull DeathRecipient recipient, int flags) {
684         return true;
685     }
686 
checkParcel(IBinder obj, int code, Parcel parcel, String msg)687     static void checkParcel(IBinder obj, int code, Parcel parcel, String msg) {
688         if (CHECK_PARCEL_SIZE && parcel.dataSize() >= 800*1024) {
689             // Trying to send > 800k, this is way too much
690             StringBuilder sb = new StringBuilder();
691             sb.append(msg);
692             sb.append(": on ");
693             sb.append(obj);
694             sb.append(" calling ");
695             sb.append(code);
696             sb.append(" size ");
697             sb.append(parcel.dataSize());
698             sb.append(" (data: ");
699             parcel.setDataPosition(0);
700             sb.append(parcel.readInt());
701             sb.append(", ");
702             sb.append(parcel.readInt());
703             sb.append(", ");
704             sb.append(parcel.readInt());
705             sb.append(")");
706             Slog.wtfStack(TAG, sb.toString());
707         }
708     }
709 
getNativeBBinderHolder()710     private static native long getNativeBBinderHolder();
getFinalizer()711     private static native long getFinalizer();
712 
713     // Entry point from android_util_Binder.cpp's onTransact
execTransact(int code, long dataObj, long replyObj, int flags)714     private boolean execTransact(int code, long dataObj, long replyObj,
715             int flags) {
716         BinderCallsStats binderCallsStats = BinderCallsStats.getInstance();
717         BinderCallsStats.CallSession callSession = binderCallsStats.callStarted(this, code);
718         Parcel data = Parcel.obtain(dataObj);
719         Parcel reply = Parcel.obtain(replyObj);
720         // theoretically, we should call transact, which will call onTransact,
721         // but all that does is rewind it, and we just got these from an IPC,
722         // so we'll just call it directly.
723         boolean res;
724         // Log any exceptions as warnings, don't silently suppress them.
725         // If the call was FLAG_ONEWAY then these exceptions disappear into the ether.
726         final boolean tracingEnabled = Binder.isTracingEnabled();
727         try {
728             if (tracingEnabled) {
729                 Trace.traceBegin(Trace.TRACE_TAG_ALWAYS, getClass().getName() + ":" + code);
730             }
731             res = onTransact(code, data, reply, flags);
732         } catch (RemoteException|RuntimeException e) {
733             if (LOG_RUNTIME_EXCEPTION) {
734                 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
735             }
736             if ((flags & FLAG_ONEWAY) != 0) {
737                 if (e instanceof RemoteException) {
738                     Log.w(TAG, "Binder call failed.", e);
739                 } else {
740                     Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
741                 }
742             } else {
743                 // Clear the parcel before writing the exception
744                 reply.setDataSize(0);
745                 reply.setDataPosition(0);
746                 reply.writeException(e);
747             }
748             res = true;
749         } finally {
750             if (tracingEnabled) {
751                 Trace.traceEnd(Trace.TRACE_TAG_ALWAYS);
752             }
753         }
754         checkParcel(this, code, reply, "Unreasonably large binder reply buffer");
755         reply.recycle();
756         data.recycle();
757 
758         // Just in case -- we are done with the IPC, so there should be no more strict
759         // mode violations that have gathered for this thread.  Either they have been
760         // parceled and are now in transport off to the caller, or we are returning back
761         // to the main transaction loop to wait for another incoming transaction.  Either
762         // way, strict mode begone!
763         StrictMode.clearGatheredViolations();
764         binderCallsStats.callEnded(callSession);
765 
766         return res;
767     }
768 }
769 
770 /**
771  * Java proxy for a native IBinder object.
772  * Allocated and constructed by the native javaObjectforIBinder function. Never allocated
773  * directly from Java code.
774  */
775 final class BinderProxy implements IBinder {
776     // See android_util_Binder.cpp for the native half of this.
777 
778     // Assume the process-wide default value when created
779     volatile boolean mWarnOnBlocking = Binder.sWarnOnBlocking;
780 
781     /*
782      * Map from longs to BinderProxy, retaining only a WeakReference to the BinderProxies.
783      * We roll our own only because we need to lazily remove WeakReferences during accesses
784      * to avoid accumulating junk WeakReference objects. WeakHashMap isn't easily usable
785      * because we want weak values, not keys.
786      * Our hash table is never resized, but the number of entries is unlimited;
787      * performance degrades as occupancy increases significantly past MAIN_INDEX_SIZE.
788      * Not thread-safe. Client ensures there's a single access at a time.
789      */
790     private static final class ProxyMap {
791         private static final int LOG_MAIN_INDEX_SIZE = 8;
792         private static final int MAIN_INDEX_SIZE = 1 <<  LOG_MAIN_INDEX_SIZE;
793         private static final int MAIN_INDEX_MASK = MAIN_INDEX_SIZE - 1;
794         // Debuggable builds will throw an AssertionError if the number of map entries exceeds:
795         private static final int CRASH_AT_SIZE = 20_000;
796 
797         /**
798          * We next warn when we exceed this bucket size.
799          */
800         private int mWarnBucketSize = 20;
801 
802         /**
803          * Increment mWarnBucketSize by WARN_INCREMENT each time we warn.
804          */
805         private static final int WARN_INCREMENT = 10;
806 
807         /**
808          * Hash function tailored to native pointers.
809          * Returns a value < MAIN_INDEX_SIZE.
810          */
hash(long arg)811         private static int hash(long arg) {
812             return ((int) ((arg >> 2) ^ (arg >> (2 + LOG_MAIN_INDEX_SIZE)))) & MAIN_INDEX_MASK;
813         }
814 
815         /**
816          * Return the total number of pairs in the map.
817          */
size()818         private int size() {
819             int size = 0;
820             for (ArrayList<WeakReference<BinderProxy>> a : mMainIndexValues) {
821                 if (a != null) {
822                     size += a.size();
823                 }
824             }
825             return size;
826         }
827 
828         /**
829          * Return the total number of pairs in the map containing values that have
830          * not been cleared. More expensive than the above size function.
831          */
unclearedSize()832         private int unclearedSize() {
833             int size = 0;
834             for (ArrayList<WeakReference<BinderProxy>> a : mMainIndexValues) {
835                 if (a != null) {
836                     for (WeakReference<BinderProxy> ref : a) {
837                         if (ref.get() != null) {
838                             ++size;
839                         }
840                     }
841                 }
842             }
843             return size;
844         }
845 
846         /**
847          * Remove ith entry from the hash bucket indicated by hash.
848          */
remove(int hash, int index)849         private void remove(int hash, int index) {
850             Long[] keyArray = mMainIndexKeys[hash];
851             ArrayList<WeakReference<BinderProxy>> valueArray = mMainIndexValues[hash];
852             int size = valueArray.size();  // KeyArray may have extra elements.
853             // Move last entry into empty slot, and truncate at end.
854             if (index != size - 1) {
855                 keyArray[index] = keyArray[size - 1];
856                 valueArray.set(index, valueArray.get(size - 1));
857             }
858             valueArray.remove(size - 1);
859             // Just leave key array entry; it's unused. We only trust the valueArray size.
860         }
861 
862         /**
863          * Look up the supplied key. If we have a non-cleared entry for it, return it.
864          */
get(long key)865         BinderProxy get(long key) {
866             int myHash = hash(key);
867             Long[] keyArray = mMainIndexKeys[myHash];
868             if (keyArray == null) {
869                 return null;
870             }
871             ArrayList<WeakReference<BinderProxy>> valueArray = mMainIndexValues[myHash];
872             int bucketSize = valueArray.size();
873             for (int i = 0; i < bucketSize; ++i) {
874                 long foundKey = keyArray[i];
875                 if (key == foundKey) {
876                     WeakReference<BinderProxy> wr = valueArray.get(i);
877                     BinderProxy bp = wr.get();
878                     if (bp != null) {
879                         return bp;
880                     } else {
881                         remove(myHash, i);
882                         return null;
883                     }
884                 }
885             }
886             return null;
887         }
888 
889         private int mRandom;  // A counter used to generate a "random" index. World's 2nd worst RNG.
890 
891         /**
892          * Add the key-value pair to the map.
893          * Requires that the indicated key is not already in the map.
894          */
set(long key, @NonNull BinderProxy value)895         void set(long key, @NonNull BinderProxy value) {
896             int myHash = hash(key);
897             ArrayList<WeakReference<BinderProxy>> valueArray = mMainIndexValues[myHash];
898             if (valueArray == null) {
899                 valueArray = mMainIndexValues[myHash] = new ArrayList<>();
900                 mMainIndexKeys[myHash] = new Long[1];
901             }
902             int size = valueArray.size();
903             WeakReference<BinderProxy> newWr = new WeakReference<>(value);
904             // First look for a cleared reference.
905             // This ensures that ArrayList size is bounded by the maximum occupancy of
906             // that bucket.
907             for (int i = 0; i < size; ++i) {
908                 if (valueArray.get(i).get() == null) {
909                     valueArray.set(i, newWr);
910                     Long[] keyArray = mMainIndexKeys[myHash];
911                     keyArray[i] = key;
912                     if (i < size - 1) {
913                         // "Randomly" check one of the remaining entries in [i+1, size), so that
914                         // needlessly long buckets are eventually pruned.
915                         int rnd = Math.floorMod(++mRandom, size - (i + 1));
916                         if (valueArray.get(i + 1 + rnd).get() == null) {
917                             remove(myHash, i + 1 + rnd);
918                         }
919                     }
920                     return;
921                 }
922             }
923             valueArray.add(size, newWr);
924             Long[] keyArray = mMainIndexKeys[myHash];
925             if (keyArray.length == size) {
926                 // size >= 1, since we initially allocated one element
927                 Long[] newArray = new Long[size + size / 2 + 2];
928                 System.arraycopy(keyArray, 0, newArray, 0, size);
929                 newArray[size] = key;
930                 mMainIndexKeys[myHash] = newArray;
931             } else {
932                 keyArray[size] = key;
933             }
934             if (size >= mWarnBucketSize) {
935                 final int totalSize = size();
936                 Log.v(Binder.TAG, "BinderProxy map growth! bucket size = " + size
937                         + " total = " + totalSize);
938                 mWarnBucketSize += WARN_INCREMENT;
939                 if (Build.IS_DEBUGGABLE && totalSize >= CRASH_AT_SIZE) {
940                     // Use the number of uncleared entries to determine whether we should
941                     // really report a histogram and crash. We don't want to fundamentally
942                     // change behavior for a debuggable process, so we GC only if we are
943                     // about to crash.
944                     final int totalUnclearedSize = unclearedSize();
945                     if (totalUnclearedSize >= CRASH_AT_SIZE) {
946                         dumpProxyInterfaceCounts();
947                         dumpPerUidProxyCounts();
948                         Runtime.getRuntime().gc();
949                         throw new AssertionError("Binder ProxyMap has too many entries: "
950                                 + totalSize + " (total), " + totalUnclearedSize + " (uncleared), "
951                                 + unclearedSize() + " (uncleared after GC). BinderProxy leak?");
952                     } else if (totalSize > 3 * totalUnclearedSize / 2) {
953                         Log.v(Binder.TAG, "BinderProxy map has many cleared entries: "
954                                 + (totalSize - totalUnclearedSize) + " of " + totalSize
955                                 + " are cleared");
956                     }
957                 }
958             }
959         }
960 
961         /**
962          * Dump a histogram to the logcat. Used to diagnose abnormally large proxy maps.
963          */
dumpProxyInterfaceCounts()964         private void dumpProxyInterfaceCounts() {
965             Map<String, Integer> counts = new HashMap<>();
966             for (ArrayList<WeakReference<BinderProxy>> a : mMainIndexValues) {
967                 if (a != null) {
968                     for (WeakReference<BinderProxy> weakRef : a) {
969                         BinderProxy bp = weakRef.get();
970                         String key;
971                         if (bp == null) {
972                             key = "<cleared weak-ref>";
973                         } else {
974                             try {
975                                 key = bp.getInterfaceDescriptor();
976                             } catch (Throwable t) {
977                                 key = "<exception during getDescriptor>";
978                             }
979                         }
980                         Integer i = counts.get(key);
981                         if (i == null) {
982                             counts.put(key, 1);
983                         } else {
984                             counts.put(key, i + 1);
985                         }
986                     }
987                 }
988             }
989             Map.Entry<String, Integer>[] sorted = counts.entrySet().toArray(
990                     new Map.Entry[counts.size()]);
991             Arrays.sort(sorted, (Map.Entry<String, Integer> a, Map.Entry<String, Integer> b)
992                     -> b.getValue().compareTo(a.getValue()));
993             Log.v(Binder.TAG, "BinderProxy descriptor histogram (top ten):");
994             int printLength = Math.min(10, sorted.length);
995             for (int i = 0; i < printLength; i++) {
996                 Log.v(Binder.TAG, " #" + (i + 1) + ": " + sorted[i].getKey() + " x"
997                         + sorted[i].getValue());
998             }
999         }
1000 
1001         /**
1002          * Dump per uid binder proxy counts to the logcat.
1003          */
dumpPerUidProxyCounts()1004         private void dumpPerUidProxyCounts() {
1005             SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts();
1006             if (counts.size() == 0) return;
1007             Log.d(Binder.TAG, "Per Uid Binder Proxy Counts:");
1008             for (int i = 0; i < counts.size(); i++) {
1009                 final int uid = counts.keyAt(i);
1010                 final int binderCount = counts.valueAt(i);
1011                 Log.d(Binder.TAG, "UID : " + uid + "  count = " + binderCount);
1012             }
1013         }
1014 
1015         // Corresponding ArrayLists in the following two arrays always have the same size.
1016         // They contain no empty entries. However WeakReferences in the values ArrayLists
1017         // may have been cleared.
1018 
1019         // mMainIndexKeys[i][j] corresponds to mMainIndexValues[i].get(j) .
1020         // The values ArrayList has the proper size(), the corresponding keys array
1021         // is always at least the same size, but may be larger.
1022         // If either a particular keys array, or the corresponding values ArrayList
1023         // are null, then they both are.
1024         private final Long[][] mMainIndexKeys = new Long[MAIN_INDEX_SIZE][];
1025         private final ArrayList<WeakReference<BinderProxy>>[] mMainIndexValues =
1026                 new ArrayList[MAIN_INDEX_SIZE];
1027     }
1028 
1029     private static ProxyMap sProxyMap = new ProxyMap();
1030 
1031     /**
1032       * Dump proxy debug information.
1033       *
1034       * Note: this method is not thread-safe; callers must serialize with other
1035       * accesses to sProxyMap, in particular {@link #getInstance(long, long)}.
1036       *
1037       * @hide
1038       */
dumpProxyDebugInfo()1039     private static void dumpProxyDebugInfo() {
1040         if (Build.IS_DEBUGGABLE) {
1041             sProxyMap.dumpProxyInterfaceCounts();
1042             // Note that we don't call dumpPerUidProxyCounts(); this is because this
1043             // method may be called as part of the uid limit being hit, and calling
1044             // back into the UID tracking code would cause us to try to acquire a mutex
1045             // that is held during that callback.
1046         }
1047     }
1048 
1049     /**
1050      * Return a BinderProxy for IBinder.
1051      * This method is thread-hostile!  The (native) caller serializes getInstance() calls using
1052      * gProxyLock.
1053      * If we previously returned a BinderProxy bp for the same iBinder, and bp is still
1054      * in use, then we return the same bp.
1055      *
1056      * @param nativeData C++ pointer to (possibly still empty) BinderProxyNativeData.
1057      * Takes ownership of nativeData iff <result>.mNativeData == nativeData, or if
1058      * we exit via an exception.  If neither applies, it's the callers responsibility to
1059      * recycle nativeData.
1060      * @param iBinder C++ pointer to IBinder. Does not take ownership of referenced object.
1061      */
getInstance(long nativeData, long iBinder)1062     private static BinderProxy getInstance(long nativeData, long iBinder) {
1063         BinderProxy result;
1064         try {
1065             result = sProxyMap.get(iBinder);
1066             if (result != null) {
1067                 return result;
1068             }
1069             result = new BinderProxy(nativeData);
1070         } catch (Throwable e) {
1071             // We're throwing an exception (probably OOME); don't drop nativeData.
1072             NativeAllocationRegistry.applyFreeFunction(NoImagePreloadHolder.sNativeFinalizer,
1073                     nativeData);
1074             throw e;
1075         }
1076         NoImagePreloadHolder.sRegistry.registerNativeAllocation(result, nativeData);
1077         // The registry now owns nativeData, even if registration threw an exception.
1078         sProxyMap.set(iBinder, result);
1079         return result;
1080     }
1081 
BinderProxy(long nativeData)1082     private BinderProxy(long nativeData) {
1083         mNativeData = nativeData;
1084     }
1085 
1086     /**
1087      * Guestimate of native memory associated with a BinderProxy.
1088      * This includes the underlying IBinder, associated DeathRecipientList, and KeyedVector
1089      * that points back to us. We guess high since it includes a GlobalRef, which
1090      * may be in short supply.
1091      */
1092     private static final int NATIVE_ALLOCATION_SIZE = 1000;
1093 
1094     // Use a Holder to allow static initialization of BinderProxy in the boot image, and
1095     // to avoid some initialization ordering issues.
1096     private static class NoImagePreloadHolder {
1097         public static final long sNativeFinalizer = getNativeFinalizer();
1098         public static final NativeAllocationRegistry sRegistry = new NativeAllocationRegistry(
1099                 BinderProxy.class.getClassLoader(), sNativeFinalizer, NATIVE_ALLOCATION_SIZE);
1100     }
1101 
pingBinder()1102     public native boolean pingBinder();
isBinderAlive()1103     public native boolean isBinderAlive();
1104 
queryLocalInterface(String descriptor)1105     public IInterface queryLocalInterface(String descriptor) {
1106         return null;
1107     }
1108 
transact(int code, Parcel data, Parcel reply, int flags)1109     public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
1110         Binder.checkParcel(this, code, data, "Unreasonably large binder buffer");
1111 
1112         if (mWarnOnBlocking && ((flags & FLAG_ONEWAY) == 0)) {
1113             // For now, avoid spamming the log by disabling after we've logged
1114             // about this interface at least once
1115             mWarnOnBlocking = false;
1116             Log.w(Binder.TAG, "Outgoing transactions from this process must be FLAG_ONEWAY",
1117                     new Throwable());
1118         }
1119 
1120         final boolean tracingEnabled = Binder.isTracingEnabled();
1121         if (tracingEnabled) {
1122             final Throwable tr = new Throwable();
1123             Binder.getTransactionTracker().addTrace(tr);
1124             StackTraceElement stackTraceElement = tr.getStackTrace()[1];
1125             Trace.traceBegin(Trace.TRACE_TAG_ALWAYS,
1126                     stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName());
1127         }
1128         try {
1129             return transactNative(code, data, reply, flags);
1130         } finally {
1131             if (tracingEnabled) {
1132                 Trace.traceEnd(Trace.TRACE_TAG_ALWAYS);
1133             }
1134         }
1135     }
1136 
getNativeFinalizer()1137     private static native long getNativeFinalizer();
getInterfaceDescriptor()1138     public native String getInterfaceDescriptor() throws RemoteException;
transactNative(int code, Parcel data, Parcel reply, int flags)1139     public native boolean transactNative(int code, Parcel data, Parcel reply,
1140             int flags) throws RemoteException;
linkToDeath(DeathRecipient recipient, int flags)1141     public native void linkToDeath(DeathRecipient recipient, int flags)
1142             throws RemoteException;
unlinkToDeath(DeathRecipient recipient, int flags)1143     public native boolean unlinkToDeath(DeathRecipient recipient, int flags);
1144 
dump(FileDescriptor fd, String[] args)1145     public void dump(FileDescriptor fd, String[] args) throws RemoteException {
1146         Parcel data = Parcel.obtain();
1147         Parcel reply = Parcel.obtain();
1148         data.writeFileDescriptor(fd);
1149         data.writeStringArray(args);
1150         try {
1151             transact(DUMP_TRANSACTION, data, reply, 0);
1152             reply.readException();
1153         } finally {
1154             data.recycle();
1155             reply.recycle();
1156         }
1157     }
1158 
dumpAsync(FileDescriptor fd, String[] args)1159     public void dumpAsync(FileDescriptor fd, String[] args) throws RemoteException {
1160         Parcel data = Parcel.obtain();
1161         Parcel reply = Parcel.obtain();
1162         data.writeFileDescriptor(fd);
1163         data.writeStringArray(args);
1164         try {
1165             transact(DUMP_TRANSACTION, data, reply, FLAG_ONEWAY);
1166         } finally {
1167             data.recycle();
1168             reply.recycle();
1169         }
1170     }
1171 
shellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)1172     public void shellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
1173             String[] args, ShellCallback callback,
1174             ResultReceiver resultReceiver) throws RemoteException {
1175         Parcel data = Parcel.obtain();
1176         Parcel reply = Parcel.obtain();
1177         data.writeFileDescriptor(in);
1178         data.writeFileDescriptor(out);
1179         data.writeFileDescriptor(err);
1180         data.writeStringArray(args);
1181         ShellCallback.writeToParcel(callback, data);
1182         resultReceiver.writeToParcel(data, 0);
1183         try {
1184             transact(SHELL_COMMAND_TRANSACTION, data, reply, 0);
1185             reply.readException();
1186         } finally {
1187             data.recycle();
1188             reply.recycle();
1189         }
1190     }
1191 
sendDeathNotice(DeathRecipient recipient)1192     private static final void sendDeathNotice(DeathRecipient recipient) {
1193         if (false) Log.v("JavaBinder", "sendDeathNotice to " + recipient);
1194         try {
1195             recipient.binderDied();
1196         }
1197         catch (RuntimeException exc) {
1198             Log.w("BinderNative", "Uncaught exception from death notification",
1199                     exc);
1200         }
1201     }
1202 
1203     /**
1204      * C++ pointer to BinderProxyNativeData. That consists of strong pointers to the
1205      * native IBinder object, and a DeathRecipientList.
1206      */
1207     private final long mNativeData;
1208 }
1209