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.compat.annotation.UnsupportedAppUsage; 23 import android.util.ExceptionUtils; 24 import android.util.Log; 25 import android.util.Slog; 26 27 import com.android.internal.os.BinderInternal; 28 import com.android.internal.os.BinderInternal.CallSession; 29 import com.android.internal.util.FastPrintWriter; 30 import com.android.internal.util.FunctionalUtils.ThrowingRunnable; 31 import com.android.internal.util.FunctionalUtils.ThrowingSupplier; 32 33 import dalvik.annotation.optimization.CriticalNative; 34 35 import libcore.io.IoUtils; 36 import libcore.util.NativeAllocationRegistry; 37 38 import java.io.FileDescriptor; 39 import java.io.FileOutputStream; 40 import java.io.PrintWriter; 41 import java.lang.reflect.Modifier; 42 43 /** 44 * Base class for a remotable object, the core part of a lightweight 45 * remote procedure call mechanism defined by {@link IBinder}. 46 * This class is an implementation of IBinder that provides 47 * standard local implementation of such an object. 48 * 49 * <p>Most developers will not implement this class directly, instead using the 50 * <a href="{@docRoot}guide/components/aidl.html">aidl</a> tool to describe the desired 51 * interface, having it generate the appropriate Binder subclass. You can, 52 * however, derive directly from Binder to implement your own custom RPC 53 * protocol or simply instantiate a raw Binder object directly to use as a 54 * token that can be shared across processes. 55 * 56 * <p>This class is just a basic IPC primitive; it has no impact on an application's 57 * lifecycle, and is valid only as long as the process that created it continues to run. 58 * To use this correctly, you must be doing so within the context of a top-level 59 * application component (a {@link android.app.Service}, {@link android.app.Activity}, 60 * or {@link android.content.ContentProvider}) that lets the system know your process 61 * should remain running.</p> 62 * 63 * <p>You must keep in mind the situations in which your process 64 * could go away, and thus require that you later re-create a new Binder and re-attach 65 * it when the process starts again. For example, if you are using this within an 66 * {@link android.app.Activity}, your activity's process may be killed any time the 67 * activity is not started; if the activity is later re-created you will need to 68 * create a new Binder and hand it back to the correct place again; you need to be 69 * aware that your process may be started for another reason (for example to receive 70 * a broadcast) that will not involve re-creating the activity and thus run its code 71 * to create a new Binder.</p> 72 * 73 * @see IBinder 74 */ 75 public class Binder implements IBinder { 76 /* 77 * Set this flag to true to detect anonymous, local or member classes 78 * that extend this Binder class and that are not static. These kind 79 * of classes can potentially create leaks. 80 */ 81 private static final boolean FIND_POTENTIAL_LEAKS = false; 82 /** @hide */ 83 public static final boolean CHECK_PARCEL_SIZE = false; 84 static final String TAG = "Binder"; 85 86 /** @hide */ 87 public static boolean LOG_RUNTIME_EXCEPTION = false; // DO NOT SUBMIT WITH TRUE 88 89 /** 90 * Value to represents that a calling work source is not set. 91 * 92 * This constatnt needs to be kept in sync with IPCThreadState::kUnsetWorkSource. 93 * 94 * @hide 95 */ 96 public static final int UNSET_WORKSOURCE = -1; 97 98 /** 99 * Control whether dump() calls are allowed. 100 */ 101 private static volatile String sDumpDisabled = null; 102 103 /** 104 * Global transaction tracker instance for this process. 105 */ 106 private static volatile TransactionTracker sTransactionTracker = null; 107 108 /** 109 * Global observer for this process. 110 */ 111 private static BinderInternal.Observer sObserver = null; 112 113 /** 114 * Guestimate of native memory associated with a Binder. 115 */ 116 private static final int NATIVE_ALLOCATION_SIZE = 500; 117 getNativeFinalizer()118 private static native long getNativeFinalizer(); 119 120 // Use a Holder to allow static initialization of Binder in the boot image, and 121 // possibly to avoid some initialization ordering issues. 122 private static class NoImagePreloadHolder { 123 public static final NativeAllocationRegistry sRegistry = new NativeAllocationRegistry( 124 Binder.class.getClassLoader(), getNativeFinalizer(), NATIVE_ALLOCATION_SIZE); 125 } 126 127 128 // Transaction tracking code. 129 130 /** 131 * Flag indicating whether we should be tracing transact calls. 132 */ 133 private static volatile boolean sTracingEnabled = false; 134 135 /** 136 * Enable Binder IPC tracing. 137 * 138 * @hide 139 */ enableTracing()140 public static void enableTracing() { 141 sTracingEnabled = true; 142 } 143 144 /** 145 * Disable Binder IPC tracing. 146 * 147 * @hide 148 */ disableTracing()149 public static void disableTracing() { 150 sTracingEnabled = false; 151 } 152 153 /** 154 * Check if binder transaction tracing is enabled. 155 * 156 * @hide 157 */ isTracingEnabled()158 public static boolean isTracingEnabled() { 159 return sTracingEnabled; 160 } 161 162 /** 163 * Get the binder transaction tracker for this process. 164 * 165 * @hide 166 */ getTransactionTracker()167 public synchronized static TransactionTracker getTransactionTracker() { 168 if (sTransactionTracker == null) 169 sTransactionTracker = new TransactionTracker(); 170 return sTransactionTracker; 171 } 172 173 /** 174 * Get the binder transaction observer for this process. 175 * 176 * @hide 177 */ setObserver(@ullable BinderInternal.Observer observer)178 public static void setObserver(@Nullable BinderInternal.Observer observer) { 179 sObserver = observer; 180 } 181 182 /** {@hide} */ 183 static volatile boolean sWarnOnBlocking = false; 184 185 /** 186 * Warn if any blocking binder transactions are made out from this process. 187 * This is typically only useful for the system process, to prevent it from 188 * blocking on calls to external untrusted code. Instead, all outgoing calls 189 * that require a result must be sent as {@link IBinder#FLAG_ONEWAY} calls 190 * which deliver results through a callback interface. 191 * 192 * @hide 193 */ setWarnOnBlocking(boolean warnOnBlocking)194 public static void setWarnOnBlocking(boolean warnOnBlocking) { 195 sWarnOnBlocking = warnOnBlocking; 196 } 197 198 /** 199 * Allow blocking calls on the given interface, overriding the requested 200 * value of {@link #setWarnOnBlocking(boolean)}. 201 * <p> 202 * This should only be rarely called when you are <em>absolutely sure</em> 203 * the remote interface is a built-in system component that can never be 204 * upgraded. In particular, this <em>must never</em> be called for 205 * interfaces hosted by package that could be upgraded or replaced, 206 * otherwise you risk system instability if that remote interface wedges. 207 * 208 * @hide 209 */ allowBlocking(IBinder binder)210 public static IBinder allowBlocking(IBinder binder) { 211 try { 212 if (binder instanceof BinderProxy) { 213 ((BinderProxy) binder).mWarnOnBlocking = false; 214 } else if (binder != null && binder.getInterfaceDescriptor() != null 215 && binder.queryLocalInterface(binder.getInterfaceDescriptor()) == null) { 216 Log.w(TAG, "Unable to allow blocking on interface " + binder); 217 } 218 } catch (RemoteException ignored) { 219 } 220 return binder; 221 } 222 223 /** 224 * Reset the given interface back to the default blocking behavior, 225 * reverting any changes made by {@link #allowBlocking(IBinder)}. 226 * 227 * @hide 228 */ defaultBlocking(IBinder binder)229 public static IBinder defaultBlocking(IBinder binder) { 230 if (binder instanceof BinderProxy) { 231 ((BinderProxy) binder).mWarnOnBlocking = sWarnOnBlocking; 232 } 233 return binder; 234 } 235 236 /** 237 * Inherit the current {@link #allowBlocking(IBinder)} value from one given 238 * interface to another. 239 * 240 * @hide 241 */ copyAllowBlocking(IBinder fromBinder, IBinder toBinder)242 public static void copyAllowBlocking(IBinder fromBinder, IBinder toBinder) { 243 if (fromBinder instanceof BinderProxy && toBinder instanceof BinderProxy) { 244 ((BinderProxy) toBinder).mWarnOnBlocking = ((BinderProxy) fromBinder).mWarnOnBlocking; 245 } 246 } 247 248 /** 249 * Raw native pointer to JavaBBinderHolder object. Owned by this Java object. Not null. 250 */ 251 @UnsupportedAppUsage 252 private final long mObject; 253 254 private IInterface mOwner; 255 private String mDescriptor; 256 257 /** 258 * Return the ID of the process that sent you the current transaction 259 * that is being processed. This pid can be used with higher-level 260 * system services to determine its identity and check permissions. 261 * If the current thread is not currently executing an incoming transaction, 262 * then its own pid is returned. 263 * 264 * Warning: oneway transactions do not receive PID. 265 */ 266 @CriticalNative getCallingPid()267 public static final native int getCallingPid(); 268 269 /** 270 * Return the Linux uid assigned to the process that sent you the 271 * current transaction that is being processed. This uid can be used with 272 * higher-level system services to determine its identity and check 273 * permissions. If the current thread is not currently executing an 274 * incoming transaction, then its own uid is returned. 275 */ 276 @CriticalNative getCallingUid()277 public static final native int getCallingUid(); 278 279 /** 280 * Returns {@code true} if the current thread is currently executing an 281 * incoming transaction. 282 * 283 * @hide 284 */ 285 @CriticalNative isHandlingTransaction()286 public static final native boolean isHandlingTransaction(); 287 288 /** 289 * Return the Linux uid assigned to the process that sent the transaction 290 * currently being processed. 291 * 292 * @throws IllegalStateException if the current thread is not currently 293 * executing an incoming transaction. 294 */ getCallingUidOrThrow()295 public static final int getCallingUidOrThrow() { 296 if (!isHandlingTransaction()) { 297 throw new IllegalStateException( 298 "Thread is not in a binder transcation"); 299 } 300 return getCallingUid(); 301 } 302 303 /** 304 * Return the UserHandle assigned to the process that sent you the 305 * current transaction that is being processed. This is the user 306 * of the caller. It is distinct from {@link #getCallingUid()} in that a 307 * particular user will have multiple distinct apps running under it each 308 * with their own uid. If the current thread is not currently executing an 309 * incoming transaction, then its own UserHandle is returned. 310 */ getCallingUserHandle()311 public static final @NonNull UserHandle getCallingUserHandle() { 312 return UserHandle.of(UserHandle.getUserId(getCallingUid())); 313 } 314 315 /** 316 * Reset the identity of the incoming IPC on the current thread. This can 317 * be useful if, while handling an incoming call, you will be calling 318 * on interfaces of other objects that may be local to your process and 319 * need to do permission checks on the calls coming into them (so they 320 * will check the permission of your own local process, and not whatever 321 * process originally called you). 322 * 323 * @return Returns an opaque token that can be used to restore the 324 * original calling identity by passing it to 325 * {@link #restoreCallingIdentity(long)}. 326 * 327 * @see #getCallingPid() 328 * @see #getCallingUid() 329 * @see #restoreCallingIdentity(long) 330 */ 331 @CriticalNative clearCallingIdentity()332 public static final native long clearCallingIdentity(); 333 334 /** 335 * Restore the identity of the incoming IPC on the current thread 336 * back to a previously identity that was returned by {@link 337 * #clearCallingIdentity}. 338 * 339 * @param token The opaque token that was previously returned by 340 * {@link #clearCallingIdentity}. 341 * 342 * @see #clearCallingIdentity 343 */ restoreCallingIdentity(long token)344 public static final native void restoreCallingIdentity(long token); 345 346 /** 347 * Convenience method for running the provided action enclosed in 348 * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity} 349 * 350 * Any exception thrown by the given action will be caught and rethrown after the call to 351 * {@link #restoreCallingIdentity} 352 * 353 * @hide 354 */ withCleanCallingIdentity(@onNull ThrowingRunnable action)355 public static final void withCleanCallingIdentity(@NonNull ThrowingRunnable action) { 356 long callingIdentity = clearCallingIdentity(); 357 Throwable throwableToPropagate = null; 358 try { 359 action.runOrThrow(); 360 } catch (Throwable throwable) { 361 throwableToPropagate = throwable; 362 } finally { 363 restoreCallingIdentity(callingIdentity); 364 if (throwableToPropagate != null) { 365 throw ExceptionUtils.propagate(throwableToPropagate); 366 } 367 } 368 } 369 370 /** 371 * Convenience method for running the provided action enclosed in 372 * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity} returning the result 373 * 374 * Any exception thrown by the given action will be caught and rethrown after the call to 375 * {@link #restoreCallingIdentity} 376 * 377 * @hide 378 */ withCleanCallingIdentity(@onNull ThrowingSupplier<T> action)379 public static final <T> T withCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) { 380 long callingIdentity = clearCallingIdentity(); 381 Throwable throwableToPropagate = null; 382 try { 383 return action.getOrThrow(); 384 } catch (Throwable throwable) { 385 throwableToPropagate = throwable; 386 return null; // overridden by throwing in finally block 387 } finally { 388 restoreCallingIdentity(callingIdentity); 389 if (throwableToPropagate != null) { 390 throw ExceptionUtils.propagate(throwableToPropagate); 391 } 392 } 393 } 394 395 /** 396 * Sets the native thread-local StrictMode policy mask. 397 * 398 * <p>The StrictMode settings are kept in two places: a Java-level 399 * threadlocal for libcore/Dalvik, and a native threadlocal (set 400 * here) for propagation via Binder calls. This is a little 401 * unfortunate, but necessary to break otherwise more unfortunate 402 * dependencies either of Dalvik on Android, or Android 403 * native-only code on Dalvik. 404 * 405 * @see StrictMode 406 * @hide 407 */ 408 @CriticalNative setThreadStrictModePolicy(int policyMask)409 public static final native void setThreadStrictModePolicy(int policyMask); 410 411 /** 412 * Gets the current native thread-local StrictMode policy mask. 413 * 414 * @see #setThreadStrictModePolicy 415 * @hide 416 */ 417 @CriticalNative getThreadStrictModePolicy()418 public static final native int getThreadStrictModePolicy(); 419 420 /** 421 * Sets the work source for this thread. 422 * 423 * <p>All the following binder calls on this thread will use the provided work source. If this 424 * is called during an on-going binder transaction, all the following binder calls will use the 425 * work source until the end of the transaction. 426 * 427 * <p>The concept of worksource is similar to {@link WorkSource}. However, for performance 428 * reasons, we only support one UID. This UID represents the original user responsible for the 429 * binder calls. 430 * 431 * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after setting the 432 * worksource. 433 * 434 * <p>A typical use case would be 435 * <pre> 436 * long token = Binder.setCallingWorkSourceUid(uid); 437 * try { 438 * // Call an API. 439 * } finally { 440 * Binder.restoreCallingWorkSource(token); 441 * } 442 * </pre> 443 * 444 * <p>The work source will be propagated for future outgoing binder transactions 445 * executed on this thread. 446 * 447 * @param workSource The original UID responsible for the binder call. 448 * @return token to restore original work source. 449 **/ 450 @CriticalNative setCallingWorkSourceUid(int workSource)451 public static final native long setCallingWorkSourceUid(int workSource); 452 453 /** 454 * Returns the work source set by the caller. 455 * 456 * Unlike {@link Binder#getCallingUid()}, this result of this method cannot be trusted. The 457 * caller can set the value to whatever they want. Only use this value if you trust the calling 458 * uid. 459 * 460 * @return The original UID responsible for the binder transaction. 461 */ 462 @CriticalNative getCallingWorkSourceUid()463 public static final native int getCallingWorkSourceUid(); 464 465 /** 466 * Clears the work source on this thread. 467 * 468 * <p>The work source will be propagated for future outgoing binder transactions 469 * executed on this thread. 470 * 471 * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after clearing the 472 * worksource. 473 * 474 * <p>A typical use case would be 475 * <pre> 476 * long token = Binder.clearCallingWorkSource(); 477 * try { 478 * // Call an API. 479 * } finally { 480 * Binder.restoreCallingWorkSource(token); 481 * } 482 * </pre> 483 * 484 * @return token to restore original work source. 485 **/ 486 @CriticalNative clearCallingWorkSource()487 public static final native long clearCallingWorkSource(); 488 489 /** 490 * Restores the work source on this thread using a token returned by 491 * {@link #setCallingWorkSourceUid(int) or {@link clearCallingWorkSource()}. 492 * 493 * <p>A typical use case would be 494 * <pre> 495 * long token = Binder.setCallingWorkSourceUid(uid); 496 * try { 497 * // Call an API. 498 * } finally { 499 * Binder.restoreCallingWorkSource(token); 500 * } 501 * </pre> 502 **/ 503 @CriticalNative restoreCallingWorkSource(long token)504 public static final native void restoreCallingWorkSource(long token); 505 506 /** 507 * Mark as being built with VINTF-level stability promise. This API should 508 * only ever be invoked by generated code from the aidl compiler. It means 509 * that the interface represented by this binder is guaranteed to be kept 510 * stable for several years, according to the VINTF compatibility lifecycle, 511 * and the build system also keeps snapshots of these APIs and invokes the 512 * AIDL compiler to make sure that these snapshots are backwards compatible. 513 * Instead of using this API, use the @VintfStability annotation on your 514 * AIDL interface. 515 * 516 * @hide 517 */ 518 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) markVintfStability()519 public final native void markVintfStability(); 520 521 /** 522 * Flush any Binder commands pending in the current thread to the kernel 523 * driver. This can be 524 * useful to call before performing an operation that may block for a long 525 * time, to ensure that any pending object references have been released 526 * in order to prevent the process from holding on to objects longer than 527 * it needs to. 528 */ flushPendingCommands()529 public static final native void flushPendingCommands(); 530 531 /** 532 * Add the calling thread to the IPC thread pool. This function does 533 * not return until the current process is exiting. 534 */ joinThreadPool()535 public static final void joinThreadPool() { 536 BinderInternal.joinThreadPool(); 537 } 538 539 /** 540 * Returns true if the specified interface is a proxy. 541 * @hide 542 */ isProxy(IInterface iface)543 public static final boolean isProxy(IInterface iface) { 544 return iface.asBinder() != iface; 545 } 546 547 /** 548 * Call blocks until the number of executing binder threads is less 549 * than the maximum number of binder threads allowed for this process. 550 * @hide 551 */ blockUntilThreadAvailable()552 public static final native void blockUntilThreadAvailable(); 553 554 /** 555 * Default constructor just initializes the object. 556 * 557 * If you're creating a Binder token (a Binder object without an attached interface), 558 * you should use {@link #Binder(String)} instead. 559 */ Binder()560 public Binder() { 561 this(null); 562 } 563 564 /** 565 * Constructor for creating a raw Binder object (token) along with a descriptor. 566 * 567 * The descriptor of binder objects usually specifies the interface they are implementing. 568 * In case of binder tokens, no interface is implemented, and the descriptor can be used 569 * as a sort of tag to help identify the binder token. This will help identify remote 570 * references to these objects more easily when debugging. 571 * 572 * @param descriptor Used to identify the creator of this token, for example the class name. 573 * Instead of creating multiple tokens with the same descriptor, consider adding a suffix to 574 * help identify them. 575 */ Binder(@ullable String descriptor)576 public Binder(@Nullable String descriptor) { 577 mObject = getNativeBBinderHolder(); 578 NoImagePreloadHolder.sRegistry.registerNativeAllocation(this, mObject); 579 580 if (FIND_POTENTIAL_LEAKS) { 581 final Class<? extends Binder> klass = getClass(); 582 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && 583 (klass.getModifiers() & Modifier.STATIC) == 0) { 584 Log.w(TAG, "The following Binder class should be static or leaks might occur: " + 585 klass.getCanonicalName()); 586 } 587 } 588 mDescriptor = descriptor; 589 } 590 591 /** 592 * Convenience method for associating a specific interface with the Binder. 593 * After calling, queryLocalInterface() will be implemented for you 594 * to return the given owner IInterface when the corresponding 595 * descriptor is requested. 596 */ attachInterface(@ullable IInterface owner, @Nullable String descriptor)597 public void attachInterface(@Nullable IInterface owner, @Nullable String descriptor) { 598 mOwner = owner; 599 mDescriptor = descriptor; 600 } 601 602 /** 603 * Default implementation returns an empty interface name. 604 */ getInterfaceDescriptor()605 public @Nullable String getInterfaceDescriptor() { 606 return mDescriptor; 607 } 608 609 /** 610 * Default implementation always returns true -- if you got here, 611 * the object is alive. 612 */ pingBinder()613 public boolean pingBinder() { 614 return true; 615 } 616 617 /** 618 * {@inheritDoc} 619 * 620 * Note that if you're calling on a local binder, this always returns true 621 * because your process is alive if you're calling it. 622 */ isBinderAlive()623 public boolean isBinderAlive() { 624 return true; 625 } 626 627 /** 628 * Use information supplied to attachInterface() to return the 629 * associated IInterface if it matches the requested 630 * descriptor. 631 */ queryLocalInterface(@onNull String descriptor)632 public @Nullable IInterface queryLocalInterface(@NonNull String descriptor) { 633 if (mDescriptor != null && mDescriptor.equals(descriptor)) { 634 return mOwner; 635 } 636 return null; 637 } 638 639 /** 640 * Control disabling of dump calls in this process. This is used by the system 641 * process watchdog to disable incoming dump calls while it has detecting the system 642 * is hung and is reporting that back to the activity controller. This is to 643 * prevent the controller from getting hung up on bug reports at this point. 644 * @hide 645 * 646 * @param msg The message to show instead of the dump; if null, dumps are 647 * re-enabled. 648 */ setDumpDisabled(String msg)649 public static void setDumpDisabled(String msg) { 650 sDumpDisabled = msg; 651 } 652 653 /** 654 * Listener to be notified about each proxy-side binder call. 655 * 656 * See {@link setProxyTransactListener}. 657 * @hide 658 */ 659 @SystemApi 660 public interface ProxyTransactListener { 661 /** 662 * Called before onTransact. 663 * 664 * @return an object that will be passed back to #onTransactEnded (or null). 665 */ 666 @Nullable onTransactStarted(@onNull IBinder binder, int transactionCode)667 Object onTransactStarted(@NonNull IBinder binder, int transactionCode); 668 669 /** 670 * Called after onTranact (even when an exception is thrown). 671 * 672 * @param session The object return by #onTransactStarted. 673 */ onTransactEnded(@ullable Object session)674 void onTransactEnded(@Nullable Object session); 675 } 676 677 /** 678 * Propagates the work source to binder calls executed by the system server. 679 * 680 * <li>By default, this listener will propagate the worksource if the outgoing call happens on 681 * the same thread as the incoming binder call. 682 * <li>Custom attribution can be done by calling {@link ThreadLocalWorkSource#setUid(int)}. 683 * @hide 684 */ 685 public static class PropagateWorkSourceTransactListener implements ProxyTransactListener { 686 @Override onTransactStarted(IBinder binder, int transactionCode)687 public Object onTransactStarted(IBinder binder, int transactionCode) { 688 // Note that {@link Binder#getCallingUid()} is already set to the UID of the current 689 // process when this method is called. 690 // 691 // We use ThreadLocalWorkSource instead. It also allows feature owners to set 692 // {@link ThreadLocalWorkSource#set(int) manually to attribute resources to a UID. 693 int uid = ThreadLocalWorkSource.getUid(); 694 if (uid != ThreadLocalWorkSource.UID_NONE) { 695 return Binder.setCallingWorkSourceUid(uid); 696 } 697 return null; 698 } 699 700 @Override onTransactEnded(Object session)701 public void onTransactEnded(Object session) { 702 if (session != null) { 703 long token = (long) session; 704 Binder.restoreCallingWorkSource(token); 705 } 706 } 707 } 708 709 /** 710 * Sets a listener for the transact method on the proxy-side. 711 * 712 * <li>The listener is global. Only fast operations should be done to avoid thread 713 * contentions. 714 * <li>The listener implementation needs to handle synchronization if needed. The methods on the 715 * listener can be called concurrently. 716 * <li>Listener set will be used for new transactions. On-going transaction will still use the 717 * previous listener (if already set). 718 * <li>The listener is called on the critical path of the binder transaction so be careful about 719 * performance. 720 * <li>Never execute another binder transaction inside the listener. 721 * @hide 722 */ 723 @SystemApi setProxyTransactListener(@ullable ProxyTransactListener listener)724 public static void setProxyTransactListener(@Nullable ProxyTransactListener listener) { 725 BinderProxy.setTransactListener(listener); 726 } 727 728 /** 729 * Default implementation is a stub that returns false. You will want 730 * to override this to do the appropriate unmarshalling of transactions. 731 * 732 * <p>If you want to call this, call transact(). 733 * 734 * <p>Implementations that are returning a result should generally use 735 * {@link Parcel#writeNoException() Parcel.writeNoException} and 736 * {@link Parcel#writeException(Exception) Parcel.writeException} to propagate 737 * exceptions back to the caller.</p> 738 * 739 * @param code The action to perform. This should 740 * be a number between {@link #FIRST_CALL_TRANSACTION} and 741 * {@link #LAST_CALL_TRANSACTION}. 742 * @param data Marshalled data being received from the caller. 743 * @param reply If the caller is expecting a result back, it should be marshalled 744 * in to here. 745 * @param flags Additional operation flags. Either 0 for a normal 746 * RPC, or {@link #FLAG_ONEWAY} for a one-way RPC. 747 * 748 * @return Return true on a successful call; returning false is generally used to 749 * indicate that you did not understand the transaction code. 750 */ onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags)751 protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply, 752 int flags) throws RemoteException { 753 if (code == INTERFACE_TRANSACTION) { 754 reply.writeString(getInterfaceDescriptor()); 755 return true; 756 } else if (code == DUMP_TRANSACTION) { 757 ParcelFileDescriptor fd = data.readFileDescriptor(); 758 String[] args = data.readStringArray(); 759 if (fd != null) { 760 try { 761 dump(fd.getFileDescriptor(), args); 762 } finally { 763 IoUtils.closeQuietly(fd); 764 } 765 } 766 // Write the StrictMode header. 767 if (reply != null) { 768 reply.writeNoException(); 769 } else { 770 StrictMode.clearGatheredViolations(); 771 } 772 return true; 773 } else if (code == SHELL_COMMAND_TRANSACTION) { 774 ParcelFileDescriptor in = data.readFileDescriptor(); 775 ParcelFileDescriptor out = data.readFileDescriptor(); 776 ParcelFileDescriptor err = data.readFileDescriptor(); 777 String[] args = data.readStringArray(); 778 ShellCallback shellCallback = ShellCallback.CREATOR.createFromParcel(data); 779 ResultReceiver resultReceiver = ResultReceiver.CREATOR.createFromParcel(data); 780 try { 781 if (out != null) { 782 shellCommand(in != null ? in.getFileDescriptor() : null, 783 out.getFileDescriptor(), 784 err != null ? err.getFileDescriptor() : out.getFileDescriptor(), 785 args, shellCallback, resultReceiver); 786 } 787 } finally { 788 IoUtils.closeQuietly(in); 789 IoUtils.closeQuietly(out); 790 IoUtils.closeQuietly(err); 791 // Write the StrictMode header. 792 if (reply != null) { 793 reply.writeNoException(); 794 } else { 795 StrictMode.clearGatheredViolations(); 796 } 797 } 798 return true; 799 } 800 return false; 801 } 802 803 /** 804 * Resolves a transaction code to a human readable name. 805 * 806 * <p>Default implementation is a stub that returns null. 807 * <p>AIDL generated code will return the original method name. 808 * 809 * @param transactionCode The code to resolve. 810 * @return A human readable name. 811 * @hide 812 */ getTransactionName(int transactionCode)813 public @Nullable String getTransactionName(int transactionCode) { 814 return null; 815 } 816 817 /** 818 * Implemented to call the more convenient version 819 * {@link #dump(FileDescriptor, PrintWriter, String[])}. 820 */ dump(@onNull FileDescriptor fd, @Nullable String[] args)821 public void dump(@NonNull FileDescriptor fd, @Nullable String[] args) { 822 FileOutputStream fout = new FileOutputStream(fd); 823 PrintWriter pw = new FastPrintWriter(fout); 824 try { 825 doDump(fd, pw, args); 826 } finally { 827 pw.flush(); 828 } 829 } 830 doDump(FileDescriptor fd, PrintWriter pw, String[] args)831 void doDump(FileDescriptor fd, PrintWriter pw, String[] args) { 832 final String disabled = sDumpDisabled; 833 if (disabled == null) { 834 try { 835 dump(fd, pw, args); 836 } catch (SecurityException e) { 837 pw.println("Security exception: " + e.getMessage()); 838 throw e; 839 } catch (Throwable e) { 840 // Unlike usual calls, in this case if an exception gets thrown 841 // back to us we want to print it back in to the dump data, since 842 // that is where the caller expects all interesting information to 843 // go. 844 pw.println(); 845 pw.println("Exception occurred while dumping:"); 846 e.printStackTrace(pw); 847 } 848 } else { 849 pw.println(sDumpDisabled); 850 } 851 } 852 853 /** 854 * Like {@link #dump(FileDescriptor, String[])}, but ensures the target 855 * executes asynchronously. 856 */ dumpAsync(@onNull final FileDescriptor fd, @Nullable final String[] args)857 public void dumpAsync(@NonNull final FileDescriptor fd, @Nullable final String[] args) { 858 final FileOutputStream fout = new FileOutputStream(fd); 859 final PrintWriter pw = new FastPrintWriter(fout); 860 Thread thr = new Thread("Binder.dumpAsync") { 861 public void run() { 862 try { 863 dump(fd, pw, args); 864 } finally { 865 pw.flush(); 866 } 867 } 868 }; 869 thr.start(); 870 } 871 872 /** 873 * Print the object's state into the given stream. 874 * 875 * @param fd The raw file descriptor that the dump is being sent to. 876 * @param fout The file to which you should dump your state. This will be 877 * closed for you after you return. 878 * @param args additional arguments to the dump request. 879 */ dump(@onNull FileDescriptor fd, @NonNull PrintWriter fout, @Nullable String[] args)880 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter fout, 881 @Nullable String[] args) { 882 } 883 884 /** 885 * @param in The raw file descriptor that an input data stream can be read from. 886 * @param out The raw file descriptor that normal command messages should be written to. 887 * @param err The raw file descriptor that command error messages should be written to. 888 * @param args Command-line arguments. 889 * @param callback Callback through which to interact with the invoking shell. 890 * @param resultReceiver Called when the command has finished executing, with the result code. 891 * @throws RemoteException 892 * @hide 893 */ shellCommand(@ullable FileDescriptor in, @Nullable FileDescriptor out, @Nullable FileDescriptor err, @NonNull String[] args, @Nullable ShellCallback callback, @NonNull ResultReceiver resultReceiver)894 public void shellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out, 895 @Nullable FileDescriptor err, 896 @NonNull String[] args, @Nullable ShellCallback callback, 897 @NonNull ResultReceiver resultReceiver) throws RemoteException { 898 onShellCommand(in, out, err, args, callback, resultReceiver); 899 } 900 901 /** 902 * Handle a call to {@link #shellCommand}. The default implementation simply prints 903 * an error message. Override and replace with your own. 904 * <p class="caution">Note: no permission checking is done before calling this method; you must 905 * apply any security checks as appropriate for the command being executed. 906 * Consider using {@link ShellCommand} to help in the implementation.</p> 907 * @hide 908 */ onShellCommand(@ullable FileDescriptor in, @Nullable FileDescriptor out, @Nullable FileDescriptor err, @NonNull String[] args, @Nullable ShellCallback callback, @NonNull ResultReceiver resultReceiver)909 public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out, 910 @Nullable FileDescriptor err, 911 @NonNull String[] args, @Nullable ShellCallback callback, 912 @NonNull ResultReceiver resultReceiver) throws RemoteException { 913 FileOutputStream fout = new FileOutputStream(err != null ? err : out); 914 PrintWriter pw = new FastPrintWriter(fout); 915 pw.println("No shell command implementation."); 916 pw.flush(); 917 resultReceiver.send(0, null); 918 } 919 920 /** @hide */ 921 @Override getExtension()922 public final native @Nullable IBinder getExtension(); 923 924 /** 925 * Set the binder extension. 926 * This should be called immediately when the object is created. 927 * 928 * @hide 929 */ setExtension(@ullable IBinder extension)930 public final native void setExtension(@Nullable IBinder extension); 931 932 /** 933 * Default implementation rewinds the parcels and calls onTransact. On 934 * the remote side, transact calls into the binder to do the IPC. 935 */ transact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags)936 public final boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply, 937 int flags) throws RemoteException { 938 if (false) Log.v("Binder", "Transact: " + code + " to " + this); 939 940 if (data != null) { 941 data.setDataPosition(0); 942 } 943 boolean r = onTransact(code, data, reply, flags); 944 if (reply != null) { 945 reply.setDataPosition(0); 946 } 947 return r; 948 } 949 950 /** 951 * Local implementation is a no-op. 952 */ linkToDeath(@onNull DeathRecipient recipient, int flags)953 public void linkToDeath(@NonNull DeathRecipient recipient, int flags) { 954 } 955 956 /** 957 * Local implementation is a no-op. 958 */ unlinkToDeath(@onNull DeathRecipient recipient, int flags)959 public boolean unlinkToDeath(@NonNull DeathRecipient recipient, int flags) { 960 return true; 961 } 962 checkParcel(IBinder obj, int code, Parcel parcel, String msg)963 static void checkParcel(IBinder obj, int code, Parcel parcel, String msg) { 964 if (CHECK_PARCEL_SIZE && parcel.dataSize() >= 800*1024) { 965 // Trying to send > 800k, this is way too much 966 StringBuilder sb = new StringBuilder(); 967 sb.append(msg); 968 sb.append(": on "); 969 sb.append(obj); 970 sb.append(" calling "); 971 sb.append(code); 972 sb.append(" size "); 973 sb.append(parcel.dataSize()); 974 sb.append(" (data: "); 975 parcel.setDataPosition(0); 976 sb.append(parcel.readInt()); 977 sb.append(", "); 978 sb.append(parcel.readInt()); 979 sb.append(", "); 980 sb.append(parcel.readInt()); 981 sb.append(")"); 982 Slog.wtfStack(TAG, sb.toString()); 983 } 984 } 985 getNativeBBinderHolder()986 private static native long getNativeBBinderHolder(); getFinalizer()987 private static native long getFinalizer(); 988 989 /** 990 * By default, we use the calling uid since we can always trust it. 991 */ 992 private static volatile BinderInternal.WorkSourceProvider sWorkSourceProvider = 993 (x) -> Binder.getCallingUid(); 994 995 /** 996 * Sets the work source provider. 997 * 998 * <li>The callback is global. Only fast operations should be done to avoid thread 999 * contentions. 1000 * <li>The callback implementation needs to handle synchronization if needed. The methods on the 1001 * callback can be called concurrently. 1002 * <li>The callback is called on the critical path of the binder transaction so be careful about 1003 * performance. 1004 * <li>Never execute another binder transaction inside the callback. 1005 * @hide 1006 */ setWorkSourceProvider(BinderInternal.WorkSourceProvider workSourceProvider)1007 public static void setWorkSourceProvider(BinderInternal.WorkSourceProvider workSourceProvider) { 1008 if (workSourceProvider == null) { 1009 throw new IllegalArgumentException("workSourceProvider cannot be null"); 1010 } 1011 sWorkSourceProvider = workSourceProvider; 1012 } 1013 1014 // Entry point from android_util_Binder.cpp's onTransact 1015 @UnsupportedAppUsage execTransact(int code, long dataObj, long replyObj, int flags)1016 private boolean execTransact(int code, long dataObj, long replyObj, 1017 int flags) { 1018 // At that point, the parcel request headers haven't been parsed so we do not know what 1019 // WorkSource the caller has set. Use calling uid as the default. 1020 final int callingUid = Binder.getCallingUid(); 1021 final long origWorkSource = ThreadLocalWorkSource.setUid(callingUid); 1022 try { 1023 return execTransactInternal(code, dataObj, replyObj, flags, callingUid); 1024 } finally { 1025 ThreadLocalWorkSource.restore(origWorkSource); 1026 } 1027 } 1028 execTransactInternal(int code, long dataObj, long replyObj, int flags, int callingUid)1029 private boolean execTransactInternal(int code, long dataObj, long replyObj, int flags, 1030 int callingUid) { 1031 // Make sure the observer won't change while processing a transaction. 1032 final BinderInternal.Observer observer = sObserver; 1033 final CallSession callSession = 1034 observer != null ? observer.callStarted(this, code, UNSET_WORKSOURCE) : null; 1035 Parcel data = Parcel.obtain(dataObj); 1036 Parcel reply = Parcel.obtain(replyObj); 1037 // theoretically, we should call transact, which will call onTransact, 1038 // but all that does is rewind it, and we just got these from an IPC, 1039 // so we'll just call it directly. 1040 boolean res; 1041 // Log any exceptions as warnings, don't silently suppress them. 1042 // If the call was FLAG_ONEWAY then these exceptions disappear into the ether. 1043 final boolean tracingEnabled = Binder.isTracingEnabled(); 1044 try { 1045 if (tracingEnabled) { 1046 final String transactionName = getTransactionName(code); 1047 Trace.traceBegin(Trace.TRACE_TAG_ALWAYS, getClass().getName() + ":" 1048 + (transactionName != null ? transactionName : code)); 1049 } 1050 res = onTransact(code, data, reply, flags); 1051 } catch (RemoteException|RuntimeException e) { 1052 if (observer != null) { 1053 observer.callThrewException(callSession, e); 1054 } 1055 if (LOG_RUNTIME_EXCEPTION) { 1056 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e); 1057 } 1058 if ((flags & FLAG_ONEWAY) != 0) { 1059 if (e instanceof RemoteException) { 1060 Log.w(TAG, "Binder call failed.", e); 1061 } else { 1062 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e); 1063 } 1064 } else { 1065 // Clear the parcel before writing the exception 1066 reply.setDataSize(0); 1067 reply.setDataPosition(0); 1068 reply.writeException(e); 1069 } 1070 res = true; 1071 } finally { 1072 if (tracingEnabled) { 1073 Trace.traceEnd(Trace.TRACE_TAG_ALWAYS); 1074 } 1075 if (observer != null) { 1076 // The parcel RPC headers have been called during onTransact so we can now access 1077 // the worksource uid from the parcel. 1078 final int workSourceUid = sWorkSourceProvider.resolveWorkSourceUid( 1079 data.readCallingWorkSourceUid()); 1080 observer.callEnded(callSession, data.dataSize(), reply.dataSize(), workSourceUid); 1081 } 1082 } 1083 checkParcel(this, code, reply, "Unreasonably large binder reply buffer"); 1084 reply.recycle(); 1085 data.recycle(); 1086 1087 // Just in case -- we are done with the IPC, so there should be no more strict 1088 // mode violations that have gathered for this thread. Either they have been 1089 // parceled and are now in transport off to the caller, or we are returning back 1090 // to the main transaction loop to wait for another incoming transaction. Either 1091 // way, strict mode begone! 1092 StrictMode.clearGatheredViolations(); 1093 return res; 1094 } 1095 1096 /** 1097 * Returns the specified service from servicemanager. If the service is not running, 1098 * servicemanager will attempt to start it, and this function will wait for it to be ready. 1099 * Returns nullptr only if there are permission problems or fatal errors. 1100 * @hide 1101 */ waitForService(@onNull String serviceName)1102 public static final native @Nullable IBinder waitForService(@NonNull String serviceName) 1103 throws RemoteException; 1104 } 1105