Debian Codegraph @

core/java/android/os/Binder.java

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