Rahul Ravikumar | 0533600 | 2019-10-14 15:04:32 -0700 | [diff] [blame] | 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.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 | |
| 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 | */ |
| 140 | public static void enableTracing() { |
| 141 | sTracingEnabled = true; |
| 142 | } |
| 143 | |
| 144 | /** |
| 145 | * Disable Binder IPC tracing. |
| 146 | * |
| 147 | * @hide |
| 148 | */ |
| 149 | public static void disableTracing() { |
| 150 | sTracingEnabled = false; |
| 151 | } |
| 152 | |
| 153 | /** |
| 154 | * Check if binder transaction tracing is enabled. |
| 155 | * |
| 156 | * @hide |
| 157 | */ |
| 158 | public static boolean isTracingEnabled() { |
| 159 | return sTracingEnabled; |
| 160 | } |
| 161 | |
| 162 | /** |
| 163 | * Get the binder transaction tracker for this process. |
| 164 | * |
| 165 | * @hide |
| 166 | */ |
| 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 | */ |
| 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 | */ |
| 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 | */ |
| 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 | */ |
| 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 | */ |
| 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 | @CriticalNative |
| 265 | public static final native int getCallingPid(); |
| 266 | |
| 267 | /** |
| 268 | * Return the Linux uid assigned to the process that sent you the |
| 269 | * current transaction that is being processed. This uid can be used with |
| 270 | * higher-level system services to determine its identity and check |
| 271 | * permissions. If the current thread is not currently executing an |
| 272 | * incoming transaction, then its own uid is returned. |
| 273 | */ |
| 274 | @CriticalNative |
| 275 | public static final native int getCallingUid(); |
| 276 | |
| 277 | /** |
| 278 | * Returns {@code true} if the current thread is currently executing an |
| 279 | * incoming transaction. |
| 280 | * |
| 281 | * @hide |
| 282 | */ |
| 283 | @CriticalNative |
| 284 | public static final native boolean isHandlingTransaction(); |
| 285 | |
| 286 | /** |
| 287 | * Return the Linux uid assigned to the process that sent the transaction |
| 288 | * currently being processed. |
| 289 | * |
| 290 | * @throws IllegalStateException if the current thread is not currently |
| 291 | * executing an incoming transaction. |
| 292 | */ |
| 293 | public static final int getCallingUidOrThrow() { |
| 294 | if (!isHandlingTransaction()) { |
| 295 | throw new IllegalStateException( |
| 296 | "Thread is not in a binder transcation"); |
| 297 | } |
| 298 | return getCallingUid(); |
| 299 | } |
| 300 | |
| 301 | /** |
| 302 | * Return the UserHandle assigned to the process that sent you the |
| 303 | * current transaction that is being processed. This is the user |
| 304 | * of the caller. It is distinct from {@link #getCallingUid()} in that a |
| 305 | * particular user will have multiple distinct apps running under it each |
| 306 | * with their own uid. If the current thread is not currently executing an |
| 307 | * incoming transaction, then its own UserHandle is returned. |
| 308 | */ |
| 309 | public static final @NonNull UserHandle getCallingUserHandle() { |
| 310 | return UserHandle.of(UserHandle.getUserId(getCallingUid())); |
| 311 | } |
| 312 | |
| 313 | /** |
| 314 | * Reset the identity of the incoming IPC on the current thread. This can |
| 315 | * be useful if, while handling an incoming call, you will be calling |
| 316 | * on interfaces of other objects that may be local to your process and |
| 317 | * need to do permission checks on the calls coming into them (so they |
| 318 | * will check the permission of your own local process, and not whatever |
| 319 | * process originally called you). |
| 320 | * |
| 321 | * @return Returns an opaque token that can be used to restore the |
| 322 | * original calling identity by passing it to |
| 323 | * {@link #restoreCallingIdentity(long)}. |
| 324 | * |
| 325 | * @see #getCallingPid() |
| 326 | * @see #getCallingUid() |
| 327 | * @see #restoreCallingIdentity(long) |
| 328 | */ |
| 329 | @CriticalNative |
| 330 | public static final native long clearCallingIdentity(); |
| 331 | |
| 332 | /** |
| 333 | * Restore the identity of the incoming IPC on the current thread |
| 334 | * back to a previously identity that was returned by {@link |
| 335 | * #clearCallingIdentity}. |
| 336 | * |
| 337 | * @param token The opaque token that was previously returned by |
| 338 | * {@link #clearCallingIdentity}. |
| 339 | * |
| 340 | * @see #clearCallingIdentity |
| 341 | */ |
| 342 | public static final native void restoreCallingIdentity(long token); |
| 343 | |
| 344 | /** |
| 345 | * Convenience method for running the provided action enclosed in |
| 346 | * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity} |
| 347 | * |
| 348 | * Any exception thrown by the given action will be caught and rethrown after the call to |
| 349 | * {@link #restoreCallingIdentity} |
| 350 | * |
| 351 | * @hide |
| 352 | */ |
| 353 | public static final void withCleanCallingIdentity(@NonNull ThrowingRunnable action) { |
| 354 | long callingIdentity = clearCallingIdentity(); |
| 355 | Throwable throwableToPropagate = null; |
| 356 | try { |
| 357 | action.runOrThrow(); |
| 358 | } catch (Throwable throwable) { |
| 359 | throwableToPropagate = throwable; |
| 360 | } finally { |
| 361 | restoreCallingIdentity(callingIdentity); |
| 362 | if (throwableToPropagate != null) { |
| 363 | throw ExceptionUtils.propagate(throwableToPropagate); |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | /** |
| 369 | * Convenience method for running the provided action enclosed in |
| 370 | * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity} returning the result |
| 371 | * |
| 372 | * Any exception thrown by the given action will be caught and rethrown after the call to |
| 373 | * {@link #restoreCallingIdentity} |
| 374 | * |
| 375 | * @hide |
| 376 | */ |
| 377 | public static final <T> T withCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) { |
| 378 | long callingIdentity = clearCallingIdentity(); |
| 379 | Throwable throwableToPropagate = null; |
| 380 | try { |
| 381 | return action.getOrThrow(); |
| 382 | } catch (Throwable throwable) { |
| 383 | throwableToPropagate = throwable; |
| 384 | return null; // overridden by throwing in finally block |
| 385 | } finally { |
| 386 | restoreCallingIdentity(callingIdentity); |
| 387 | if (throwableToPropagate != null) { |
| 388 | throw ExceptionUtils.propagate(throwableToPropagate); |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | /** |
| 394 | * Sets the native thread-local StrictMode policy mask. |
| 395 | * |
| 396 | * <p>The StrictMode settings are kept in two places: a Java-level |
| 397 | * threadlocal for libcore/Dalvik, and a native threadlocal (set |
| 398 | * here) for propagation via Binder calls. This is a little |
| 399 | * unfortunate, but necessary to break otherwise more unfortunate |
| 400 | * dependencies either of Dalvik on Android, or Android |
| 401 | * native-only code on Dalvik. |
| 402 | * |
| 403 | * @see StrictMode |
| 404 | * @hide |
| 405 | */ |
| 406 | @CriticalNative |
| 407 | public static final native void setThreadStrictModePolicy(int policyMask); |
| 408 | |
| 409 | /** |
| 410 | * Gets the current native thread-local StrictMode policy mask. |
| 411 | * |
| 412 | * @see #setThreadStrictModePolicy |
| 413 | * @hide |
| 414 | */ |
| 415 | @CriticalNative |
| 416 | public static final native int getThreadStrictModePolicy(); |
| 417 | |
| 418 | /** |
| 419 | * Sets the work source for this thread. |
| 420 | * |
| 421 | * <p>All the following binder calls on this thread will use the provided work source. If this |
| 422 | * is called during an on-going binder transaction, all the following binder calls will use the |
| 423 | * work source until the end of the transaction. |
| 424 | * |
| 425 | * <p>The concept of worksource is similar to {@link WorkSource}. However, for performance |
| 426 | * reasons, we only support one UID. This UID represents the original user responsible for the |
| 427 | * binder calls. |
| 428 | * |
| 429 | * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after setting the |
| 430 | * worksource. |
| 431 | * |
| 432 | * <p>A typical use case would be |
| 433 | * <pre> |
| 434 | * long token = Binder.setCallingWorkSourceUid(uid); |
| 435 | * try { |
| 436 | * // Call an API. |
| 437 | * } finally { |
| 438 | * Binder.restoreCallingWorkSource(token); |
| 439 | * } |
| 440 | * </pre> |
| 441 | * |
| 442 | * <p>The work source will be propagated for future outgoing binder transactions |
| 443 | * executed on this thread. |
| 444 | * |
| 445 | * @param workSource The original UID responsible for the binder call. |
| 446 | * @return token to restore original work source. |
| 447 | **/ |
| 448 | @CriticalNative |
| 449 | public static final native long setCallingWorkSourceUid(int workSource); |
| 450 | |
| 451 | /** |
| 452 | * Returns the work source set by the caller. |
| 453 | * |
| 454 | * Unlike {@link Binder#getCallingUid()}, this result of this method cannot be trusted. The |
| 455 | * caller can set the value to whatever they want. Only use this value if you trust the calling |
| 456 | * uid. |
| 457 | * |
| 458 | * @return The original UID responsible for the binder transaction. |
| 459 | */ |
| 460 | @CriticalNative |
| 461 | public static final native int getCallingWorkSourceUid(); |
| 462 | |
| 463 | /** |
| 464 | * Clears the work source on this thread. |
| 465 | * |
| 466 | * <p>The work source will be propagated for future outgoing binder transactions |
| 467 | * executed on this thread. |
| 468 | * |
| 469 | * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after clearing the |
| 470 | * worksource. |
| 471 | * |
| 472 | * <p>A typical use case would be |
| 473 | * <pre> |
| 474 | * long token = Binder.clearCallingWorkSource(); |
| 475 | * try { |
| 476 | * // Call an API. |
| 477 | * } finally { |
| 478 | * Binder.restoreCallingWorkSource(token); |
| 479 | * } |
| 480 | * </pre> |
| 481 | * |
| 482 | * @return token to restore original work source. |
| 483 | **/ |
| 484 | @CriticalNative |
| 485 | public static final native long clearCallingWorkSource(); |
| 486 | |
| 487 | /** |
| 488 | * Restores the work source on this thread using a token returned by |
| 489 | * {@link #setCallingWorkSourceUid(int) or {@link clearCallingWorkSource()}. |
| 490 | * |
| 491 | * <p>A typical use case would be |
| 492 | * <pre> |
| 493 | * long token = Binder.setCallingWorkSourceUid(uid); |
| 494 | * try { |
| 495 | * // Call an API. |
| 496 | * } finally { |
| 497 | * Binder.restoreCallingWorkSource(token); |
| 498 | * } |
| 499 | * </pre> |
| 500 | **/ |
| 501 | @CriticalNative |
| 502 | public static final native void restoreCallingWorkSource(long token); |
| 503 | |
| 504 | /** |
| 505 | * Flush any Binder commands pending in the current thread to the kernel |
| 506 | * driver. This can be |
| 507 | * useful to call before performing an operation that may block for a long |
| 508 | * time, to ensure that any pending object references have been released |
| 509 | * in order to prevent the process from holding on to objects longer than |
| 510 | * it needs to. |
| 511 | */ |
| 512 | public static final native void flushPendingCommands(); |
| 513 | |
| 514 | /** |
| 515 | * Add the calling thread to the IPC thread pool. This function does |
| 516 | * not return until the current process is exiting. |
| 517 | */ |
| 518 | public static final void joinThreadPool() { |
| 519 | BinderInternal.joinThreadPool(); |
| 520 | } |
| 521 | |
| 522 | /** |
| 523 | * Returns true if the specified interface is a proxy. |
| 524 | * @hide |
| 525 | */ |
| 526 | public static final boolean isProxy(IInterface iface) { |
| 527 | return iface.asBinder() != iface; |
| 528 | } |
| 529 | |
| 530 | /** |
| 531 | * Call blocks until the number of executing binder threads is less |
| 532 | * than the maximum number of binder threads allowed for this process. |
| 533 | * @hide |
| 534 | */ |
| 535 | public static final native void blockUntilThreadAvailable(); |
| 536 | |
| 537 | /** |
| 538 | * Default constructor just initializes the object. |
| 539 | * |
| 540 | * If you're creating a Binder token (a Binder object without an attached interface), |
| 541 | * you should use {@link #Binder(String)} instead. |
| 542 | */ |
| 543 | public Binder() { |
| 544 | this(null); |
| 545 | } |
| 546 | |
| 547 | /** |
| 548 | * Constructor for creating a raw Binder object (token) along with a descriptor. |
| 549 | * |
| 550 | * The descriptor of binder objects usually specifies the interface they are implementing. |
| 551 | * In case of binder tokens, no interface is implemented, and the descriptor can be used |
| 552 | * as a sort of tag to help identify the binder token. This will help identify remote |
| 553 | * references to these objects more easily when debugging. |
| 554 | * |
| 555 | * @param descriptor Used to identify the creator of this token, for example the class name. |
| 556 | * Instead of creating multiple tokens with the same descriptor, consider adding a suffix to |
| 557 | * help identify them. |
| 558 | */ |
| 559 | public Binder(@Nullable String descriptor) { |
| 560 | mObject = getNativeBBinderHolder(); |
| 561 | NoImagePreloadHolder.sRegistry.registerNativeAllocation(this, mObject); |
| 562 | |
| 563 | if (FIND_POTENTIAL_LEAKS) { |
| 564 | final Class<? extends Binder> klass = getClass(); |
| 565 | if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && |
| 566 | (klass.getModifiers() & Modifier.STATIC) == 0) { |
| 567 | Log.w(TAG, "The following Binder class should be static or leaks might occur: " + |
| 568 | klass.getCanonicalName()); |
| 569 | } |
| 570 | } |
| 571 | mDescriptor = descriptor; |
| 572 | } |
| 573 | |
| 574 | /** |
| 575 | * Convenience method for associating a specific interface with the Binder. |
| 576 | * After calling, queryLocalInterface() will be implemented for you |
| 577 | * to return the given owner IInterface when the corresponding |
| 578 | * descriptor is requested. |
| 579 | */ |
| 580 | public void attachInterface(@Nullable IInterface owner, @Nullable String descriptor) { |
| 581 | mOwner = owner; |
| 582 | mDescriptor = descriptor; |
| 583 | } |
| 584 | |
| 585 | /** |
| 586 | * Default implementation returns an empty interface name. |
| 587 | */ |
| 588 | public @Nullable String getInterfaceDescriptor() { |
| 589 | return mDescriptor; |
| 590 | } |
| 591 | |
| 592 | /** |
| 593 | * Default implementation always returns true -- if you got here, |
| 594 | * the object is alive. |
| 595 | */ |
| 596 | public boolean pingBinder() { |
| 597 | return true; |
| 598 | } |
| 599 | |
| 600 | /** |
| 601 | * {@inheritDoc} |
| 602 | * |
| 603 | * Note that if you're calling on a local binder, this always returns true |
| 604 | * because your process is alive if you're calling it. |
| 605 | */ |
| 606 | public boolean isBinderAlive() { |
| 607 | return true; |
| 608 | } |
| 609 | |
| 610 | /** |
| 611 | * Use information supplied to attachInterface() to return the |
| 612 | * associated IInterface if it matches the requested |
| 613 | * descriptor. |
| 614 | */ |
| 615 | public @Nullable IInterface queryLocalInterface(@NonNull String descriptor) { |
| 616 | if (mDescriptor != null && mDescriptor.equals(descriptor)) { |
| 617 | return mOwner; |
| 618 | } |
| 619 | return null; |
| 620 | } |
| 621 | |
| 622 | /** |
| 623 | * Control disabling of dump calls in this process. This is used by the system |
| 624 | * process watchdog to disable incoming dump calls while it has detecting the system |
| 625 | * is hung and is reporting that back to the activity controller. This is to |
| 626 | * prevent the controller from getting hung up on bug reports at this point. |
| 627 | * @hide |
| 628 | * |
| 629 | * @param msg The message to show instead of the dump; if null, dumps are |
| 630 | * re-enabled. |
| 631 | */ |
| 632 | public static void setDumpDisabled(String msg) { |
| 633 | sDumpDisabled = msg; |
| 634 | } |
| 635 | |
| 636 | /** |
| 637 | * Listener to be notified about each proxy-side binder call. |
| 638 | * |
| 639 | * See {@link setProxyTransactListener}. |
| 640 | * @hide |
| 641 | */ |
| 642 | @SystemApi |
| 643 | public interface ProxyTransactListener { |
| 644 | /** |
| 645 | * Called before onTransact. |
| 646 | * |
| 647 | * @return an object that will be passed back to #onTransactEnded (or null). |
| 648 | */ |
| 649 | @Nullable |
| 650 | Object onTransactStarted(@NonNull IBinder binder, int transactionCode); |
| 651 | |
| 652 | /** |
| 653 | * Called after onTranact (even when an exception is thrown). |
| 654 | * |
| 655 | * @param session The object return by #onTransactStarted. |
| 656 | */ |
| 657 | void onTransactEnded(@Nullable Object session); |
| 658 | } |
| 659 | |
| 660 | /** |
| 661 | * Propagates the work source to binder calls executed by the system server. |
| 662 | * |
| 663 | * <li>By default, this listener will propagate the worksource if the outgoing call happens on |
| 664 | * the same thread as the incoming binder call. |
| 665 | * <li>Custom attribution can be done by calling {@link ThreadLocalWorkSource#setUid(int)}. |
| 666 | * @hide |
| 667 | */ |
| 668 | public static class PropagateWorkSourceTransactListener implements ProxyTransactListener { |
| 669 | @Override |
| 670 | public Object onTransactStarted(IBinder binder, int transactionCode) { |
| 671 | // Note that {@link Binder#getCallingUid()} is already set to the UID of the current |
| 672 | // process when this method is called. |
| 673 | // |
| 674 | // We use ThreadLocalWorkSource instead. It also allows feature owners to set |
| 675 | // {@link ThreadLocalWorkSource#set(int) manually to attribute resources to a UID. |
| 676 | int uid = ThreadLocalWorkSource.getUid(); |
| 677 | if (uid != ThreadLocalWorkSource.UID_NONE) { |
| 678 | return Binder.setCallingWorkSourceUid(uid); |
| 679 | } |
| 680 | return null; |
| 681 | } |
| 682 | |
| 683 | @Override |
| 684 | public void onTransactEnded(Object session) { |
| 685 | if (session != null) { |
| 686 | long token = (long) session; |
| 687 | Binder.restoreCallingWorkSource(token); |
| 688 | } |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | /** |
| 693 | * Sets a listener for the transact method on the proxy-side. |
| 694 | * |
| 695 | * <li>The listener is global. Only fast operations should be done to avoid thread |
| 696 | * contentions. |
| 697 | * <li>The listener implementation needs to handle synchronization if needed. The methods on the |
| 698 | * listener can be called concurrently. |
| 699 | * <li>Listener set will be used for new transactions. On-going transaction will still use the |
| 700 | * previous listener (if already set). |
| 701 | * <li>The listener is called on the critical path of the binder transaction so be careful about |
| 702 | * performance. |
| 703 | * <li>Never execute another binder transaction inside the listener. |
| 704 | * @hide |
| 705 | */ |
| 706 | @SystemApi |
| 707 | public static void setProxyTransactListener(@Nullable ProxyTransactListener listener) { |
| 708 | BinderProxy.setTransactListener(listener); |
| 709 | } |
| 710 | |
| 711 | /** |
| 712 | * Default implementation is a stub that returns false. You will want |
| 713 | * to override this to do the appropriate unmarshalling of transactions. |
| 714 | * |
| 715 | * <p>If you want to call this, call transact(). |
| 716 | * |
| 717 | * <p>Implementations that are returning a result should generally use |
| 718 | * {@link Parcel#writeNoException() Parcel.writeNoException} and |
| 719 | * {@link Parcel#writeException(Exception) Parcel.writeException} to propagate |
| 720 | * exceptions back to the caller.</p> |
| 721 | * |
| 722 | * @param code The action to perform. This should |
| 723 | * be a number between {@link #FIRST_CALL_TRANSACTION} and |
| 724 | * {@link #LAST_CALL_TRANSACTION}. |
| 725 | * @param data Marshalled data being received from the caller. |
| 726 | * @param reply If the caller is expecting a result back, it should be marshalled |
| 727 | * in to here. |
| 728 | * @param flags Additional operation flags. Either 0 for a normal |
| 729 | * RPC, or {@link #FLAG_ONEWAY} for a one-way RPC. |
| 730 | * |
| 731 | * @return Return true on a successful call; returning false is generally used to |
| 732 | * indicate that you did not understand the transaction code. |
| 733 | */ |
| 734 | protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply, |
| 735 | int flags) throws RemoteException { |
| 736 | if (code == INTERFACE_TRANSACTION) { |
| 737 | reply.writeString(getInterfaceDescriptor()); |
| 738 | return true; |
| 739 | } else if (code == DUMP_TRANSACTION) { |
| 740 | ParcelFileDescriptor fd = data.readFileDescriptor(); |
| 741 | String[] args = data.readStringArray(); |
| 742 | if (fd != null) { |
| 743 | try { |
| 744 | dump(fd.getFileDescriptor(), args); |
| 745 | } finally { |
| 746 | IoUtils.closeQuietly(fd); |
| 747 | } |
| 748 | } |
| 749 | // Write the StrictMode header. |
| 750 | if (reply != null) { |
| 751 | reply.writeNoException(); |
| 752 | } else { |
| 753 | StrictMode.clearGatheredViolations(); |
| 754 | } |
| 755 | return true; |
| 756 | } else if (code == SHELL_COMMAND_TRANSACTION) { |
| 757 | ParcelFileDescriptor in = data.readFileDescriptor(); |
| 758 | ParcelFileDescriptor out = data.readFileDescriptor(); |
| 759 | ParcelFileDescriptor err = data.readFileDescriptor(); |
| 760 | String[] args = data.readStringArray(); |
| 761 | ShellCallback shellCallback = ShellCallback.CREATOR.createFromParcel(data); |
| 762 | ResultReceiver resultReceiver = ResultReceiver.CREATOR.createFromParcel(data); |
| 763 | try { |
| 764 | if (out != null) { |
| 765 | shellCommand(in != null ? in.getFileDescriptor() : null, |
| 766 | out.getFileDescriptor(), |
| 767 | err != null ? err.getFileDescriptor() : out.getFileDescriptor(), |
| 768 | args, shellCallback, resultReceiver); |
| 769 | } |
| 770 | } finally { |
| 771 | IoUtils.closeQuietly(in); |
| 772 | IoUtils.closeQuietly(out); |
| 773 | IoUtils.closeQuietly(err); |
| 774 | // Write the StrictMode header. |
| 775 | if (reply != null) { |
| 776 | reply.writeNoException(); |
| 777 | } else { |
| 778 | StrictMode.clearGatheredViolations(); |
| 779 | } |
| 780 | } |
| 781 | return true; |
| 782 | } |
| 783 | return false; |
| 784 | } |
| 785 | |
| 786 | /** |
| 787 | * Resolves a transaction code to a human readable name. |
| 788 | * |
| 789 | * <p>Default implementation is a stub that returns null. |
| 790 | * <p>AIDL generated code will return the original method name. |
| 791 | * |
| 792 | * @param transactionCode The code to resolve. |
| 793 | * @return A human readable name. |
| 794 | * @hide |
| 795 | */ |
| 796 | public @Nullable String getTransactionName(int transactionCode) { |
| 797 | return null; |
| 798 | } |
| 799 | |
| 800 | /** |
| 801 | * Implemented to call the more convenient version |
| 802 | * {@link #dump(FileDescriptor, PrintWriter, String[])}. |
| 803 | */ |
| 804 | public void dump(@NonNull FileDescriptor fd, @Nullable String[] args) { |
| 805 | FileOutputStream fout = new FileOutputStream(fd); |
| 806 | PrintWriter pw = new FastPrintWriter(fout); |
| 807 | try { |
| 808 | doDump(fd, pw, args); |
| 809 | } finally { |
| 810 | pw.flush(); |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | void doDump(FileDescriptor fd, PrintWriter pw, String[] args) { |
| 815 | final String disabled = sDumpDisabled; |
| 816 | if (disabled == null) { |
| 817 | try { |
| 818 | dump(fd, pw, args); |
| 819 | } catch (SecurityException e) { |
| 820 | pw.println("Security exception: " + e.getMessage()); |
| 821 | throw e; |
| 822 | } catch (Throwable e) { |
| 823 | // Unlike usual calls, in this case if an exception gets thrown |
| 824 | // back to us we want to print it back in to the dump data, since |
| 825 | // that is where the caller expects all interesting information to |
| 826 | // go. |
| 827 | pw.println(); |
| 828 | pw.println("Exception occurred while dumping:"); |
| 829 | e.printStackTrace(pw); |
| 830 | } |
| 831 | } else { |
| 832 | pw.println(sDumpDisabled); |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | /** |
| 837 | * Like {@link #dump(FileDescriptor, String[])}, but ensures the target |
| 838 | * executes asynchronously. |
| 839 | */ |
| 840 | public void dumpAsync(@NonNull final FileDescriptor fd, @Nullable final String[] args) { |
| 841 | final FileOutputStream fout = new FileOutputStream(fd); |
| 842 | final PrintWriter pw = new FastPrintWriter(fout); |
| 843 | Thread thr = new Thread("Binder.dumpAsync") { |
| 844 | public void run() { |
| 845 | try { |
| 846 | dump(fd, pw, args); |
| 847 | } finally { |
| 848 | pw.flush(); |
| 849 | } |
| 850 | } |
| 851 | }; |
| 852 | thr.start(); |
| 853 | } |
| 854 | |
| 855 | /** |
| 856 | * Print the object's state into the given stream. |
| 857 | * |
| 858 | * @param fd The raw file descriptor that the dump is being sent to. |
| 859 | * @param fout The file to which you should dump your state. This will be |
| 860 | * closed for you after you return. |
| 861 | * @param args additional arguments to the dump request. |
| 862 | */ |
| 863 | protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter fout, |
| 864 | @Nullable String[] args) { |
| 865 | } |
| 866 | |
| 867 | /** |
| 868 | * @param in The raw file descriptor that an input data stream can be read from. |
| 869 | * @param out The raw file descriptor that normal command messages should be written to. |
| 870 | * @param err The raw file descriptor that command error messages should be written to. |
| 871 | * @param args Command-line arguments. |
| 872 | * @param callback Callback through which to interact with the invoking shell. |
| 873 | * @param resultReceiver Called when the command has finished executing, with the result code. |
| 874 | * @throws RemoteException |
| 875 | * @hide |
| 876 | */ |
| 877 | public void shellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out, |
| 878 | @Nullable FileDescriptor err, |
| 879 | @NonNull String[] args, @Nullable ShellCallback callback, |
| 880 | @NonNull ResultReceiver resultReceiver) throws RemoteException { |
| 881 | onShellCommand(in, out, err, args, callback, resultReceiver); |
| 882 | } |
| 883 | |
| 884 | /** |
| 885 | * Handle a call to {@link #shellCommand}. The default implementation simply prints |
| 886 | * an error message. Override and replace with your own. |
| 887 | * <p class="caution">Note: no permission checking is done before calling this method; you must |
| 888 | * apply any security checks as appropriate for the command being executed. |
| 889 | * Consider using {@link ShellCommand} to help in the implementation.</p> |
| 890 | * @hide |
| 891 | */ |
| 892 | public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out, |
| 893 | @Nullable FileDescriptor err, |
| 894 | @NonNull String[] args, @Nullable ShellCallback callback, |
| 895 | @NonNull ResultReceiver resultReceiver) throws RemoteException { |
| 896 | FileOutputStream fout = new FileOutputStream(err != null ? err : out); |
| 897 | PrintWriter pw = new FastPrintWriter(fout); |
| 898 | pw.println("No shell command implementation."); |
| 899 | pw.flush(); |
| 900 | resultReceiver.send(0, null); |
| 901 | } |
| 902 | |
| 903 | /** |
| 904 | * Default implementation rewinds the parcels and calls onTransact. On |
| 905 | * the remote side, transact calls into the binder to do the IPC. |
| 906 | */ |
| 907 | public final boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply, |
| 908 | int flags) throws RemoteException { |
| 909 | if (false) Log.v("Binder", "Transact: " + code + " to " + this); |
| 910 | |
| 911 | if (data != null) { |
| 912 | data.setDataPosition(0); |
| 913 | } |
| 914 | boolean r = onTransact(code, data, reply, flags); |
| 915 | if (reply != null) { |
| 916 | reply.setDataPosition(0); |
| 917 | } |
| 918 | return r; |
| 919 | } |
| 920 | |
| 921 | /** |
| 922 | * Local implementation is a no-op. |
| 923 | */ |
| 924 | public void linkToDeath(@NonNull DeathRecipient recipient, int flags) { |
| 925 | } |
| 926 | |
| 927 | /** |
| 928 | * Local implementation is a no-op. |
| 929 | */ |
| 930 | public boolean unlinkToDeath(@NonNull DeathRecipient recipient, int flags) { |
| 931 | return true; |
| 932 | } |
| 933 | |
| 934 | static void checkParcel(IBinder obj, int code, Parcel parcel, String msg) { |
| 935 | if (CHECK_PARCEL_SIZE && parcel.dataSize() >= 800*1024) { |
| 936 | // Trying to send > 800k, this is way too much |
| 937 | StringBuilder sb = new StringBuilder(); |
| 938 | sb.append(msg); |
| 939 | sb.append(": on "); |
| 940 | sb.append(obj); |
| 941 | sb.append(" calling "); |
| 942 | sb.append(code); |
| 943 | sb.append(" size "); |
| 944 | sb.append(parcel.dataSize()); |
| 945 | sb.append(" (data: "); |
| 946 | parcel.setDataPosition(0); |
| 947 | sb.append(parcel.readInt()); |
| 948 | sb.append(", "); |
| 949 | sb.append(parcel.readInt()); |
| 950 | sb.append(", "); |
| 951 | sb.append(parcel.readInt()); |
| 952 | sb.append(")"); |
| 953 | Slog.wtfStack(TAG, sb.toString()); |
| 954 | } |
| 955 | } |
| 956 | |
| 957 | private static native long getNativeBBinderHolder(); |
| 958 | private static native long getFinalizer(); |
| 959 | |
| 960 | /** |
| 961 | * By default, we use the calling uid since we can always trust it. |
| 962 | */ |
| 963 | private static volatile BinderInternal.WorkSourceProvider sWorkSourceProvider = |
| 964 | (x) -> Binder.getCallingUid(); |
| 965 | |
| 966 | /** |
| 967 | * Sets the work source provider. |
| 968 | * |
| 969 | * <li>The callback is global. Only fast operations should be done to avoid thread |
| 970 | * contentions. |
| 971 | * <li>The callback implementation needs to handle synchronization if needed. The methods on the |
| 972 | * callback can be called concurrently. |
| 973 | * <li>The callback is called on the critical path of the binder transaction so be careful about |
| 974 | * performance. |
| 975 | * <li>Never execute another binder transaction inside the callback. |
| 976 | * @hide |
| 977 | */ |
| 978 | public static void setWorkSourceProvider(BinderInternal.WorkSourceProvider workSourceProvider) { |
| 979 | if (workSourceProvider == null) { |
| 980 | throw new IllegalArgumentException("workSourceProvider cannot be null"); |
| 981 | } |
| 982 | sWorkSourceProvider = workSourceProvider; |
| 983 | } |
| 984 | |
| 985 | // Entry point from android_util_Binder.cpp's onTransact |
| 986 | @UnsupportedAppUsage |
| 987 | private boolean execTransact(int code, long dataObj, long replyObj, |
| 988 | int flags) { |
| 989 | // At that point, the parcel request headers haven't been parsed so we do not know what |
| 990 | // WorkSource the caller has set. Use calling uid as the default. |
| 991 | final int callingUid = Binder.getCallingUid(); |
| 992 | final long origWorkSource = ThreadLocalWorkSource.setUid(callingUid); |
| 993 | try { |
| 994 | return execTransactInternal(code, dataObj, replyObj, flags, callingUid); |
| 995 | } finally { |
| 996 | ThreadLocalWorkSource.restore(origWorkSource); |
| 997 | } |
| 998 | } |
| 999 | |
| 1000 | private boolean execTransactInternal(int code, long dataObj, long replyObj, int flags, |
| 1001 | int callingUid) { |
| 1002 | // Make sure the observer won't change while processing a transaction. |
| 1003 | final BinderInternal.Observer observer = sObserver; |
| 1004 | final CallSession callSession = |
| 1005 | observer != null ? observer.callStarted(this, code, UNSET_WORKSOURCE) : null; |
| 1006 | Parcel data = Parcel.obtain(dataObj); |
| 1007 | Parcel reply = Parcel.obtain(replyObj); |
| 1008 | // theoretically, we should call transact, which will call onTransact, |
| 1009 | // but all that does is rewind it, and we just got these from an IPC, |
| 1010 | // so we'll just call it directly. |
| 1011 | boolean res; |
| 1012 | // Log any exceptions as warnings, don't silently suppress them. |
| 1013 | // If the call was FLAG_ONEWAY then these exceptions disappear into the ether. |
| 1014 | final boolean tracingEnabled = Binder.isTracingEnabled(); |
| 1015 | try { |
| 1016 | if (tracingEnabled) { |
| 1017 | final String transactionName = getTransactionName(code); |
| 1018 | Trace.traceBegin(Trace.TRACE_TAG_ALWAYS, getClass().getName() + ":" |
| 1019 | + (transactionName != null ? transactionName : code)); |
| 1020 | } |
| 1021 | res = onTransact(code, data, reply, flags); |
| 1022 | } catch (RemoteException|RuntimeException e) { |
| 1023 | if (observer != null) { |
| 1024 | observer.callThrewException(callSession, e); |
| 1025 | } |
| 1026 | if (LOG_RUNTIME_EXCEPTION) { |
| 1027 | Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e); |
| 1028 | } |
| 1029 | if ((flags & FLAG_ONEWAY) != 0) { |
| 1030 | if (e instanceof RemoteException) { |
| 1031 | Log.w(TAG, "Binder call failed.", e); |
| 1032 | } else { |
| 1033 | Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e); |
| 1034 | } |
| 1035 | } else { |
| 1036 | // Clear the parcel before writing the exception |
| 1037 | reply.setDataSize(0); |
| 1038 | reply.setDataPosition(0); |
| 1039 | reply.writeException(e); |
| 1040 | } |
| 1041 | res = true; |
| 1042 | } finally { |
| 1043 | if (tracingEnabled) { |
| 1044 | Trace.traceEnd(Trace.TRACE_TAG_ALWAYS); |
| 1045 | } |
| 1046 | if (observer != null) { |
| 1047 | // The parcel RPC headers have been called during onTransact so we can now access |
| 1048 | // the worksource uid from the parcel. |
| 1049 | final int workSourceUid = sWorkSourceProvider.resolveWorkSourceUid( |
| 1050 | data.readCallingWorkSourceUid()); |
| 1051 | observer.callEnded(callSession, data.dataSize(), reply.dataSize(), workSourceUid); |
| 1052 | } |
| 1053 | } |
| 1054 | checkParcel(this, code, reply, "Unreasonably large binder reply buffer"); |
| 1055 | reply.recycle(); |
| 1056 | data.recycle(); |
| 1057 | |
| 1058 | // Just in case -- we are done with the IPC, so there should be no more strict |
| 1059 | // mode violations that have gathered for this thread. Either they have been |
| 1060 | // parceled and are now in transport off to the caller, or we are returning back |
| 1061 | // to the main transaction loop to wait for another incoming transaction. Either |
| 1062 | // way, strict mode begone! |
| 1063 | StrictMode.clearGatheredViolations(); |
| 1064 | return res; |
| 1065 | } |
| 1066 | } |