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