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