Home | History | Annotate | Download | only in os
      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 
    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      */
    127     public static void enableTracing() {
    128         sTracingEnabled = true;
    129     }
    130 
    131     /**
    132      * Disable Binder IPC tracing.
    133      *
    134      * @hide
    135      */
    136     public static void disableTracing() {
    137         sTracingEnabled = false;
    138     }
    139 
    140     /**
    141      * Check if binder transaction tracing is enabled.
    142      *
    143      * @hide
    144      */
    145     public static boolean isTracingEnabled() {
    146         return sTracingEnabled;
    147     }
    148 
    149     /**
    150      * Get the binder transaction tracker for this process.
    151      *
    152      * @hide
    153      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    397     public static final native void blockUntilThreadAvailable();
    398 
    399     /**
    400      * Default constructor initializes the object.
    401      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    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 
    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      */
    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      */
    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      */
    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      */
    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      */
    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      */
    677     public void linkToDeath(@NonNull DeathRecipient recipient, int flags) {
    678     }
    679 
    680     /**
    681      * Local implementation is a no-op.
    682      */
    683     public boolean unlinkToDeath(@NonNull DeathRecipient recipient, int flags) {
    684         return true;
    685     }
    686 
    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 
    710     private static native long getNativeBBinderHolder();
    711     private static native long getFinalizer();
    712 
    713     // Entry point from android_util_Binder.cpp's onTransact
    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                 reply.setDataPosition(0);
    744                 reply.writeException(e);
    745             }
    746             res = true;
    747         } finally {
    748             if (tracingEnabled) {
    749                 Trace.traceEnd(Trace.TRACE_TAG_ALWAYS);
    750             }
    751         }
    752         checkParcel(this, code, reply, "Unreasonably large binder reply buffer");
    753         reply.recycle();
    754         data.recycle();
    755 
    756         // Just in case -- we are done with the IPC, so there should be no more strict
    757         // mode violations that have gathered for this thread.  Either they have been
    758         // parceled and are now in transport off to the caller, or we are returning back
    759         // to the main transaction loop to wait for another incoming transaction.  Either
    760         // way, strict mode begone!
    761         StrictMode.clearGatheredViolations();
    762         binderCallsStats.callEnded(callSession);
    763 
    764         return res;
    765     }
    766 }
    767 
    768 /**
    769  * Java proxy for a native IBinder object.
    770  * Allocated and constructed by the native javaObjectforIBinder function. Never allocated
    771  * directly from Java code.
    772  */
    773 final class BinderProxy implements IBinder {
    774     // See android_util_Binder.cpp for the native half of this.
    775 
    776     // Assume the process-wide default value when created
    777     volatile boolean mWarnOnBlocking = Binder.sWarnOnBlocking;
    778 
    779     /*
    780      * Map from longs to BinderProxy, retaining only a WeakReference to the BinderProxies.
    781      * We roll our own only because we need to lazily remove WeakReferences during accesses
    782      * to avoid accumulating junk WeakReference objects. WeakHashMap isn't easily usable
    783      * because we want weak values, not keys.
    784      * Our hash table is never resized, but the number of entries is unlimited;
    785      * performance degrades as occupancy increases significantly past MAIN_INDEX_SIZE.
    786      * Not thread-safe. Client ensures there's a single access at a time.
    787      */
    788     private static final class ProxyMap {
    789         private static final int LOG_MAIN_INDEX_SIZE = 8;
    790         private static final int MAIN_INDEX_SIZE = 1 <<  LOG_MAIN_INDEX_SIZE;
    791         private static final int MAIN_INDEX_MASK = MAIN_INDEX_SIZE - 1;
    792         // Debuggable builds will throw an AssertionError if the number of map entries exceeds:
    793         private static final int CRASH_AT_SIZE = 20_000;
    794 
    795         /**
    796          * We next warn when we exceed this bucket size.
    797          */
    798         private int mWarnBucketSize = 20;
    799 
    800         /**
    801          * Increment mWarnBucketSize by WARN_INCREMENT each time we warn.
    802          */
    803         private static final int WARN_INCREMENT = 10;
    804 
    805         /**
    806          * Hash function tailored to native pointers.
    807          * Returns a value < MAIN_INDEX_SIZE.
    808          */
    809         private static int hash(long arg) {
    810             return ((int) ((arg >> 2) ^ (arg >> (2 + LOG_MAIN_INDEX_SIZE)))) & MAIN_INDEX_MASK;
    811         }
    812 
    813         /**
    814          * Return the total number of pairs in the map.
    815          */
    816         private int size() {
    817             int size = 0;
    818             for (ArrayList<WeakReference<BinderProxy>> a : mMainIndexValues) {
    819                 if (a != null) {
    820                     size += a.size();
    821                 }
    822             }
    823             return size;
    824         }
    825 
    826         /**
    827          * Return the total number of pairs in the map containing values that have
    828          * not been cleared. More expensive than the above size function.
    829          */
    830         private int unclearedSize() {
    831             int size = 0;
    832             for (ArrayList<WeakReference<BinderProxy>> a : mMainIndexValues) {
    833                 if (a != null) {
    834                     for (WeakReference<BinderProxy> ref : a) {
    835                         if (ref.get() != null) {
    836                             ++size;
    837                         }
    838                     }
    839                 }
    840             }
    841             return size;
    842         }
    843 
    844         /**
    845          * Remove ith entry from the hash bucket indicated by hash.
    846          */
    847         private void remove(int hash, int index) {
    848             Long[] keyArray = mMainIndexKeys[hash];
    849             ArrayList<WeakReference<BinderProxy>> valueArray = mMainIndexValues[hash];
    850             int size = valueArray.size();  // KeyArray may have extra elements.
    851             // Move last entry into empty slot, and truncate at end.
    852             if (index != size - 1) {
    853                 keyArray[index] = keyArray[size - 1];
    854                 valueArray.set(index, valueArray.get(size - 1));
    855             }
    856             valueArray.remove(size - 1);
    857             // Just leave key array entry; it's unused. We only trust the valueArray size.
    858         }
    859 
    860         /**
    861          * Look up the supplied key. If we have a non-cleared entry for it, return it.
    862          */
    863         BinderProxy get(long key) {
    864             int myHash = hash(key);
    865             Long[] keyArray = mMainIndexKeys[myHash];
    866             if (keyArray == null) {
    867                 return null;
    868             }
    869             ArrayList<WeakReference<BinderProxy>> valueArray = mMainIndexValues[myHash];
    870             int bucketSize = valueArray.size();
    871             for (int i = 0; i < bucketSize; ++i) {
    872                 long foundKey = keyArray[i];
    873                 if (key == foundKey) {
    874                     WeakReference<BinderProxy> wr = valueArray.get(i);
    875                     BinderProxy bp = wr.get();
    876                     if (bp != null) {
    877                         return bp;
    878                     } else {
    879                         remove(myHash, i);
    880                         return null;
    881                     }
    882                 }
    883             }
    884             return null;
    885         }
    886 
    887         private int mRandom;  // A counter used to generate a "random" index. World's 2nd worst RNG.
    888 
    889         /**
    890          * Add the key-value pair to the map.
    891          * Requires that the indicated key is not already in the map.
    892          */
    893         void set(long key, @NonNull BinderProxy value) {
    894             int myHash = hash(key);
    895             ArrayList<WeakReference<BinderProxy>> valueArray = mMainIndexValues[myHash];
    896             if (valueArray == null) {
    897                 valueArray = mMainIndexValues[myHash] = new ArrayList<>();
    898                 mMainIndexKeys[myHash] = new Long[1];
    899             }
    900             int size = valueArray.size();
    901             WeakReference<BinderProxy> newWr = new WeakReference<>(value);
    902             // First look for a cleared reference.
    903             // This ensures that ArrayList size is bounded by the maximum occupancy of
    904             // that bucket.
    905             for (int i = 0; i < size; ++i) {
    906                 if (valueArray.get(i).get() == null) {
    907                     valueArray.set(i, newWr);
    908                     Long[] keyArray = mMainIndexKeys[myHash];
    909                     keyArray[i] = key;
    910                     if (i < size - 1) {
    911                         // "Randomly" check one of the remaining entries in [i+1, size), so that
    912                         // needlessly long buckets are eventually pruned.
    913                         int rnd = Math.floorMod(++mRandom, size - (i + 1));
    914                         if (valueArray.get(i + 1 + rnd).get() == null) {
    915                             remove(myHash, i + 1 + rnd);
    916                         }
    917                     }
    918                     return;
    919                 }
    920             }
    921             valueArray.add(size, newWr);
    922             Long[] keyArray = mMainIndexKeys[myHash];
    923             if (keyArray.length == size) {
    924                 // size >= 1, since we initially allocated one element
    925                 Long[] newArray = new Long[size + size / 2 + 2];
    926                 System.arraycopy(keyArray, 0, newArray, 0, size);
    927                 newArray[size] = key;
    928                 mMainIndexKeys[myHash] = newArray;
    929             } else {
    930                 keyArray[size] = key;
    931             }
    932             if (size >= mWarnBucketSize) {
    933                 final int totalSize = size();
    934                 Log.v(Binder.TAG, "BinderProxy map growth! bucket size = " + size
    935                         + " total = " + totalSize);
    936                 mWarnBucketSize += WARN_INCREMENT;
    937                 if (Build.IS_DEBUGGABLE && totalSize >= CRASH_AT_SIZE) {
    938                     // Use the number of uncleared entries to determine whether we should
    939                     // really report a histogram and crash. We don't want to fundamentally
    940                     // change behavior for a debuggable process, so we GC only if we are
    941                     // about to crash.
    942                     final int totalUnclearedSize = unclearedSize();
    943                     if (totalUnclearedSize >= CRASH_AT_SIZE) {
    944                         dumpProxyInterfaceCounts();
    945                         dumpPerUidProxyCounts();
    946                         Runtime.getRuntime().gc();
    947                         throw new AssertionError("Binder ProxyMap has too many entries: "
    948                                 + totalSize + " (total), " + totalUnclearedSize + " (uncleared), "
    949                                 + unclearedSize() + " (uncleared after GC). BinderProxy leak?");
    950                     } else if (totalSize > 3 * totalUnclearedSize / 2) {
    951                         Log.v(Binder.TAG, "BinderProxy map has many cleared entries: "
    952                                 + (totalSize - totalUnclearedSize) + " of " + totalSize
    953                                 + " are cleared");
    954                     }
    955                 }
    956             }
    957         }
    958 
    959         /**
    960          * Dump a histogram to the logcat. Used to diagnose abnormally large proxy maps.
    961          */
    962         private void dumpProxyInterfaceCounts() {
    963             Map<String, Integer> counts = new HashMap<>();
    964             for (ArrayList<WeakReference<BinderProxy>> a : mMainIndexValues) {
    965                 if (a != null) {
    966                     for (WeakReference<BinderProxy> weakRef : a) {
    967                         BinderProxy bp = weakRef.get();
    968                         String key;
    969                         if (bp == null) {
    970                             key = "<cleared weak-ref>";
    971                         } else {
    972                             try {
    973                                 key = bp.getInterfaceDescriptor();
    974                             } catch (Throwable t) {
    975                                 key = "<exception during getDescriptor>";
    976                             }
    977                         }
    978                         Integer i = counts.get(key);
    979                         if (i == null) {
    980                             counts.put(key, 1);
    981                         } else {
    982                             counts.put(key, i + 1);
    983                         }
    984                     }
    985                 }
    986             }
    987             Map.Entry<String, Integer>[] sorted = counts.entrySet().toArray(
    988                     new Map.Entry[counts.size()]);
    989             Arrays.sort(sorted, (Map.Entry<String, Integer> a, Map.Entry<String, Integer> b)
    990                     -> b.getValue().compareTo(a.getValue()));
    991             Log.v(Binder.TAG, "BinderProxy descriptor histogram (top ten):");
    992             int printLength = Math.min(10, sorted.length);
    993             for (int i = 0; i < printLength; i++) {
    994                 Log.v(Binder.TAG, " #" + (i + 1) + ": " + sorted[i].getKey() + " x"
    995                         + sorted[i].getValue());
    996             }
    997         }
    998 
    999         /**
   1000          * Dump per uid binder proxy counts to the logcat.
   1001          */
   1002         private void dumpPerUidProxyCounts() {
   1003             SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts();
   1004             if (counts.size() == 0) return;
   1005             Log.d(Binder.TAG, "Per Uid Binder Proxy Counts:");
   1006             for (int i = 0; i < counts.size(); i++) {
   1007                 final int uid = counts.keyAt(i);
   1008                 final int binderCount = counts.valueAt(i);
   1009                 Log.d(Binder.TAG, "UID : " + uid + "  count = " + binderCount);
   1010             }
   1011         }
   1012 
   1013         // Corresponding ArrayLists in the following two arrays always have the same size.
   1014         // They contain no empty entries. However WeakReferences in the values ArrayLists
   1015         // may have been cleared.
   1016 
   1017         // mMainIndexKeys[i][j] corresponds to mMainIndexValues[i].get(j) .
   1018         // The values ArrayList has the proper size(), the corresponding keys array
   1019         // is always at least the same size, but may be larger.
   1020         // If either a particular keys array, or the corresponding values ArrayList
   1021         // are null, then they both are.
   1022         private final Long[][] mMainIndexKeys = new Long[MAIN_INDEX_SIZE][];
   1023         private final ArrayList<WeakReference<BinderProxy>>[] mMainIndexValues =
   1024                 new ArrayList[MAIN_INDEX_SIZE];
   1025     }
   1026 
   1027     private static ProxyMap sProxyMap = new ProxyMap();
   1028 
   1029     /**
   1030       * Dump proxy debug information.
   1031       *
   1032       * Note: this method is not thread-safe; callers must serialize with other
   1033       * accesses to sProxyMap, in particular {@link #getInstance(long, long)}.
   1034       *
   1035       * @hide
   1036       */
   1037     private static void dumpProxyDebugInfo() {
   1038         if (Build.IS_DEBUGGABLE) {
   1039             sProxyMap.dumpProxyInterfaceCounts();
   1040             // Note that we don't call dumpPerUidProxyCounts(); this is because this
   1041             // method may be called as part of the uid limit being hit, and calling
   1042             // back into the UID tracking code would cause us to try to acquire a mutex
   1043             // that is held during that callback.
   1044         }
   1045     }
   1046 
   1047     /**
   1048      * Return a BinderProxy for IBinder.
   1049      * This method is thread-hostile!  The (native) caller serializes getInstance() calls using
   1050      * gProxyLock.
   1051      * If we previously returned a BinderProxy bp for the same iBinder, and bp is still
   1052      * in use, then we return the same bp.
   1053      *
   1054      * @param nativeData C++ pointer to (possibly still empty) BinderProxyNativeData.
   1055      * Takes ownership of nativeData iff <result>.mNativeData == nativeData, or if
   1056      * we exit via an exception.  If neither applies, it's the callers responsibility to
   1057      * recycle nativeData.
   1058      * @param iBinder C++ pointer to IBinder. Does not take ownership of referenced object.
   1059      */
   1060     private static BinderProxy getInstance(long nativeData, long iBinder) {
   1061         BinderProxy result;
   1062         try {
   1063             result = sProxyMap.get(iBinder);
   1064             if (result != null) {
   1065                 return result;
   1066             }
   1067             result = new BinderProxy(nativeData);
   1068         } catch (Throwable e) {
   1069             // We're throwing an exception (probably OOME); don't drop nativeData.
   1070             NativeAllocationRegistry.applyFreeFunction(NoImagePreloadHolder.sNativeFinalizer,
   1071                     nativeData);
   1072             throw e;
   1073         }
   1074         NoImagePreloadHolder.sRegistry.registerNativeAllocation(result, nativeData);
   1075         // The registry now owns nativeData, even if registration threw an exception.
   1076         sProxyMap.set(iBinder, result);
   1077         return result;
   1078     }
   1079 
   1080     private BinderProxy(long nativeData) {
   1081         mNativeData = nativeData;
   1082     }
   1083 
   1084     /**
   1085      * Guestimate of native memory associated with a BinderProxy.
   1086      * This includes the underlying IBinder, associated DeathRecipientList, and KeyedVector
   1087      * that points back to us. We guess high since it includes a GlobalRef, which
   1088      * may be in short supply.
   1089      */
   1090     private static final int NATIVE_ALLOCATION_SIZE = 1000;
   1091 
   1092     // Use a Holder to allow static initialization of BinderProxy in the boot image, and
   1093     // to avoid some initialization ordering issues.
   1094     private static class NoImagePreloadHolder {
   1095         public static final long sNativeFinalizer = getNativeFinalizer();
   1096         public static final NativeAllocationRegistry sRegistry = new NativeAllocationRegistry(
   1097                 BinderProxy.class.getClassLoader(), sNativeFinalizer, NATIVE_ALLOCATION_SIZE);
   1098     }
   1099 
   1100     public native boolean pingBinder();
   1101     public native boolean isBinderAlive();
   1102 
   1103     public IInterface queryLocalInterface(String descriptor) {
   1104         return null;
   1105     }
   1106 
   1107     public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
   1108         Binder.checkParcel(this, code, data, "Unreasonably large binder buffer");
   1109 
   1110         if (mWarnOnBlocking && ((flags & FLAG_ONEWAY) == 0)) {
   1111             // For now, avoid spamming the log by disabling after we've logged
   1112             // about this interface at least once
   1113             mWarnOnBlocking = false;
   1114             Log.w(Binder.TAG, "Outgoing transactions from this process must be FLAG_ONEWAY",
   1115                     new Throwable());
   1116         }
   1117 
   1118         final boolean tracingEnabled = Binder.isTracingEnabled();
   1119         if (tracingEnabled) {
   1120             final Throwable tr = new Throwable();
   1121             Binder.getTransactionTracker().addTrace(tr);
   1122             StackTraceElement stackTraceElement = tr.getStackTrace()[1];
   1123             Trace.traceBegin(Trace.TRACE_TAG_ALWAYS,
   1124                     stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName());
   1125         }
   1126         try {
   1127             return transactNative(code, data, reply, flags);
   1128         } finally {
   1129             if (tracingEnabled) {
   1130                 Trace.traceEnd(Trace.TRACE_TAG_ALWAYS);
   1131             }
   1132         }
   1133     }
   1134 
   1135     private static native long getNativeFinalizer();
   1136     public native String getInterfaceDescriptor() throws RemoteException;
   1137     public native boolean transactNative(int code, Parcel data, Parcel reply,
   1138             int flags) throws RemoteException;
   1139     public native void linkToDeath(DeathRecipient recipient, int flags)
   1140             throws RemoteException;
   1141     public native boolean unlinkToDeath(DeathRecipient recipient, int flags);
   1142 
   1143     public void dump(FileDescriptor fd, String[] args) throws RemoteException {
   1144         Parcel data = Parcel.obtain();
   1145         Parcel reply = Parcel.obtain();
   1146         data.writeFileDescriptor(fd);
   1147         data.writeStringArray(args);
   1148         try {
   1149             transact(DUMP_TRANSACTION, data, reply, 0);
   1150             reply.readException();
   1151         } finally {
   1152             data.recycle();
   1153             reply.recycle();
   1154         }
   1155     }
   1156 
   1157     public void dumpAsync(FileDescriptor fd, String[] args) throws RemoteException {
   1158         Parcel data = Parcel.obtain();
   1159         Parcel reply = Parcel.obtain();
   1160         data.writeFileDescriptor(fd);
   1161         data.writeStringArray(args);
   1162         try {
   1163             transact(DUMP_TRANSACTION, data, reply, FLAG_ONEWAY);
   1164         } finally {
   1165             data.recycle();
   1166             reply.recycle();
   1167         }
   1168     }
   1169 
   1170     public void shellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
   1171             String[] args, ShellCallback callback,
   1172             ResultReceiver resultReceiver) throws RemoteException {
   1173         Parcel data = Parcel.obtain();
   1174         Parcel reply = Parcel.obtain();
   1175         data.writeFileDescriptor(in);
   1176         data.writeFileDescriptor(out);
   1177         data.writeFileDescriptor(err);
   1178         data.writeStringArray(args);
   1179         ShellCallback.writeToParcel(callback, data);
   1180         resultReceiver.writeToParcel(data, 0);
   1181         try {
   1182             transact(SHELL_COMMAND_TRANSACTION, data, reply, 0);
   1183             reply.readException();
   1184         } finally {
   1185             data.recycle();
   1186             reply.recycle();
   1187         }
   1188     }
   1189 
   1190     private static final void sendDeathNotice(DeathRecipient recipient) {
   1191         if (false) Log.v("JavaBinder", "sendDeathNotice to " + recipient);
   1192         try {
   1193             recipient.binderDied();
   1194         }
   1195         catch (RuntimeException exc) {
   1196             Log.w("BinderNative", "Uncaught exception from death notification",
   1197                     exc);
   1198         }
   1199     }
   1200 
   1201     /**
   1202      * C++ pointer to BinderProxyNativeData. That consists of strong pointers to the
   1203      * native IBinder object, and a DeathRecipientList.
   1204      */
   1205     private final long mNativeData;
   1206 }
   1207