Binder.java revision d7fdd0228e6abdbc079f9cf08b780e4222dfe7c5
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.os; 18 19import android.util.Log; 20import android.util.Slog; 21import com.android.internal.util.FastPrintWriter; 22 23import java.io.FileDescriptor; 24import java.io.FileOutputStream; 25import java.io.IOException; 26import java.io.PrintWriter; 27import java.lang.ref.WeakReference; 28import java.lang.reflect.Modifier; 29 30/** 31 * Base class for a remotable object, the core part of a lightweight 32 * remote procedure call mechanism defined by {@link IBinder}. 33 * This class is an implementation of IBinder that provides 34 * standard local implementation of such an object. 35 * 36 * <p>Most developers will not implement this class directly, instead using the 37 * <a href="{@docRoot}guide/components/aidl.html">aidl</a> tool to describe the desired 38 * interface, having it generate the appropriate Binder subclass. You can, 39 * however, derive directly from Binder to implement your own custom RPC 40 * protocol or simply instantiate a raw Binder object directly to use as a 41 * token that can be shared across processes. 42 * 43 * <p>This class is just a basic IPC primitive; it has no impact on an application's 44 * lifecycle, and is valid only as long as the process that created it continues to run. 45 * To use this correctly, you must be doing so within the context of a top-level 46 * application component (a {@link android.app.Service}, {@link android.app.Activity}, 47 * or {@link android.content.ContentProvider}) that lets the system know your process 48 * should remain running.</p> 49 * 50 * <p>You must keep in mind the situations in which your process 51 * could go away, and thus require that you later re-create a new Binder and re-attach 52 * it when the process starts again. For example, if you are using this within an 53 * {@link android.app.Activity}, your activity's process may be killed any time the 54 * activity is not started; if the activity is later re-created you will need to 55 * create a new Binder and hand it back to the correct place again; you need to be 56 * aware that your process may be started for another reason (for example to receive 57 * a broadcast) that will not involve re-creating the activity and thus run its code 58 * to create a new Binder.</p> 59 * 60 * @see IBinder 61 */ 62public class Binder implements IBinder { 63 /* 64 * Set this flag to true to detect anonymous, local or member classes 65 * that extend this Binder class and that are not static. These kind 66 * of classes can potentially create leaks. 67 */ 68 private static final boolean FIND_POTENTIAL_LEAKS = false; 69 private static final boolean CHECK_PARCEL_SIZE = false; 70 static final String TAG = "Binder"; 71 72 /** 73 * Control whether dump() calls are allowed. 74 */ 75 private static String sDumpDisabled = null; 76 77 /* mObject is used by native code, do not remove or rename */ 78 private long mObject; 79 private IInterface mOwner; 80 private String mDescriptor; 81 82 /** 83 * Return the ID of the process that sent you the current transaction 84 * that is being processed. This pid can be used with higher-level 85 * system services to determine its identity and check permissions. 86 * If the current thread is not currently executing an incoming transaction, 87 * then its own pid is returned. 88 */ 89 public static final native int getCallingPid(); 90 91 /** 92 * Return the Linux uid assigned to the process that sent you the 93 * current transaction that is being processed. This uid can be used with 94 * higher-level system services to determine its identity and check 95 * permissions. If the current thread is not currently executing an 96 * incoming transaction, then its own uid is returned. 97 */ 98 public static final native int getCallingUid(); 99 100 /** 101 * Return the UserHandle assigned to the process that sent you the 102 * current transaction that is being processed. This is the user 103 * of the caller. It is distinct from {@link #getCallingUid()} in that a 104 * particular user will have multiple distinct apps running under it each 105 * with their own uid. If the current thread is not currently executing an 106 * incoming transaction, then its own UserHandle is returned. 107 */ 108 public static final UserHandle getCallingUserHandle() { 109 return new UserHandle(UserHandle.getUserId(getCallingUid())); 110 } 111 112 /** 113 * Reset the identity of the incoming IPC on the current thread. This can 114 * be useful if, while handling an incoming call, you will be calling 115 * on interfaces of other objects that may be local to your process and 116 * need to do permission checks on the calls coming into them (so they 117 * will check the permission of your own local process, and not whatever 118 * process originally called you). 119 * 120 * @return Returns an opaque token that can be used to restore the 121 * original calling identity by passing it to 122 * {@link #restoreCallingIdentity(long)}. 123 * 124 * @see #getCallingPid() 125 * @see #getCallingUid() 126 * @see #restoreCallingIdentity(long) 127 */ 128 public static final native long clearCallingIdentity(); 129 130 /** 131 * Restore the identity of the incoming IPC on the current thread 132 * back to a previously identity that was returned by {@link 133 * #clearCallingIdentity}. 134 * 135 * @param token The opaque token that was previously returned by 136 * {@link #clearCallingIdentity}. 137 * 138 * @see #clearCallingIdentity 139 */ 140 public static final native void restoreCallingIdentity(long token); 141 142 /** 143 * Sets the native thread-local StrictMode policy mask. 144 * 145 * <p>The StrictMode settings are kept in two places: a Java-level 146 * threadlocal for libcore/Dalvik, and a native threadlocal (set 147 * here) for propagation via Binder calls. This is a little 148 * unfortunate, but necessary to break otherwise more unfortunate 149 * dependencies either of Dalvik on Android, or Android 150 * native-only code on Dalvik. 151 * 152 * @see StrictMode 153 * @hide 154 */ 155 public static final native void setThreadStrictModePolicy(int policyMask); 156 157 /** 158 * Gets the current native thread-local StrictMode policy mask. 159 * 160 * @see #setThreadStrictModePolicy 161 * @hide 162 */ 163 public static final native int getThreadStrictModePolicy(); 164 165 /** 166 * Flush any Binder commands pending in the current thread to the kernel 167 * driver. This can be 168 * useful to call before performing an operation that may block for a long 169 * time, to ensure that any pending object references have been released 170 * in order to prevent the process from holding on to objects longer than 171 * it needs to. 172 */ 173 public static final native void flushPendingCommands(); 174 175 /** 176 * Add the calling thread to the IPC thread pool. This function does 177 * not return until the current process is exiting. 178 */ 179 public static final native void joinThreadPool(); 180 181 /** 182 * Returns true if the specified interface is a proxy. 183 * @hide 184 */ 185 public static final boolean isProxy(IInterface iface) { 186 return iface.asBinder() != iface; 187 } 188 189 /** 190 * Call blocks until the number of executing binder threads is less 191 * than the maximum number of binder threads allowed for this process. 192 */ 193 public static final native void blockUntilThreadAvailable(); 194 195 /** 196 * Default constructor initializes the object. 197 */ 198 public Binder() { 199 init(); 200 201 if (FIND_POTENTIAL_LEAKS) { 202 final Class<? extends Binder> klass = getClass(); 203 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && 204 (klass.getModifiers() & Modifier.STATIC) == 0) { 205 Log.w(TAG, "The following Binder class should be static or leaks might occur: " + 206 klass.getCanonicalName()); 207 } 208 } 209 } 210 211 /** 212 * Convenience method for associating a specific interface with the Binder. 213 * After calling, queryLocalInterface() will be implemented for you 214 * to return the given owner IInterface when the corresponding 215 * descriptor is requested. 216 */ 217 public void attachInterface(IInterface owner, String descriptor) { 218 mOwner = owner; 219 mDescriptor = descriptor; 220 } 221 222 /** 223 * Default implementation returns an empty interface name. 224 */ 225 public String getInterfaceDescriptor() { 226 return mDescriptor; 227 } 228 229 /** 230 * Default implementation always returns true -- if you got here, 231 * the object is alive. 232 */ 233 public boolean pingBinder() { 234 return true; 235 } 236 237 /** 238 * {@inheritDoc} 239 * 240 * Note that if you're calling on a local binder, this always returns true 241 * because your process is alive if you're calling it. 242 */ 243 public boolean isBinderAlive() { 244 return true; 245 } 246 247 /** 248 * Use information supplied to attachInterface() to return the 249 * associated IInterface if it matches the requested 250 * descriptor. 251 */ 252 public IInterface queryLocalInterface(String descriptor) { 253 if (mDescriptor.equals(descriptor)) { 254 return mOwner; 255 } 256 return null; 257 } 258 259 /** 260 * Control disabling of dump calls in this process. This is used by the system 261 * process watchdog to disable incoming dump calls while it has detecting the system 262 * is hung and is reporting that back to the activity controller. This is to 263 * prevent the controller from getting hung up on bug reports at this point. 264 * @hide 265 * 266 * @param msg The message to show instead of the dump; if null, dumps are 267 * re-enabled. 268 */ 269 public static void setDumpDisabled(String msg) { 270 synchronized (Binder.class) { 271 sDumpDisabled = msg; 272 } 273 } 274 275 /** 276 * Default implementation is a stub that returns false. You will want 277 * to override this to do the appropriate unmarshalling of transactions. 278 * 279 * <p>If you want to call this, call transact(). 280 */ 281 protected boolean onTransact(int code, Parcel data, Parcel reply, 282 int flags) throws RemoteException { 283 if (code == INTERFACE_TRANSACTION) { 284 reply.writeString(getInterfaceDescriptor()); 285 return true; 286 } else if (code == DUMP_TRANSACTION) { 287 ParcelFileDescriptor fd = data.readFileDescriptor(); 288 String[] args = data.readStringArray(); 289 if (fd != null) { 290 try { 291 dump(fd.getFileDescriptor(), args); 292 } finally { 293 try { 294 fd.close(); 295 } catch (IOException e) { 296 // swallowed, not propagated back to the caller 297 } 298 } 299 } 300 // Write the StrictMode header. 301 if (reply != null) { 302 reply.writeNoException(); 303 } else { 304 StrictMode.clearGatheredViolations(); 305 } 306 return true; 307 } 308 return false; 309 } 310 311 /** 312 * Implemented to call the more convenient version 313 * {@link #dump(FileDescriptor, PrintWriter, String[])}. 314 */ 315 public void dump(FileDescriptor fd, String[] args) { 316 FileOutputStream fout = new FileOutputStream(fd); 317 PrintWriter pw = new FastPrintWriter(fout); 318 try { 319 final String disabled; 320 synchronized (Binder.class) { 321 disabled = sDumpDisabled; 322 } 323 if (disabled == null) { 324 try { 325 dump(fd, pw, args); 326 } catch (SecurityException e) { 327 pw.println("Security exception: " + e.getMessage()); 328 throw e; 329 } catch (Throwable e) { 330 // Unlike usual calls, in this case if an exception gets thrown 331 // back to us we want to print it back in to the dump data, since 332 // that is where the caller expects all interesting information to 333 // go. 334 pw.println(); 335 pw.println("Exception occurred while dumping:"); 336 e.printStackTrace(pw); 337 } 338 } else { 339 pw.println(sDumpDisabled); 340 } 341 } finally { 342 pw.flush(); 343 } 344 } 345 346 /** 347 * Like {@link #dump(FileDescriptor, String[])}, but ensures the target 348 * executes asynchronously. 349 */ 350 public void dumpAsync(final FileDescriptor fd, final String[] args) { 351 final FileOutputStream fout = new FileOutputStream(fd); 352 final PrintWriter pw = new FastPrintWriter(fout); 353 Thread thr = new Thread("Binder.dumpAsync") { 354 public void run() { 355 try { 356 dump(fd, pw, args); 357 } finally { 358 pw.flush(); 359 } 360 } 361 }; 362 thr.start(); 363 } 364 365 /** 366 * Print the object's state into the given stream. 367 * 368 * @param fd The raw file descriptor that the dump is being sent to. 369 * @param fout The file to which you should dump your state. This will be 370 * closed for you after you return. 371 * @param args additional arguments to the dump request. 372 */ 373 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { 374 } 375 376 /** 377 * Default implementation rewinds the parcels and calls onTransact. On 378 * the remote side, transact calls into the binder to do the IPC. 379 */ 380 public final boolean transact(int code, Parcel data, Parcel reply, 381 int flags) throws RemoteException { 382 if (false) Log.v("Binder", "Transact: " + code + " to " + this); 383 if (data != null) { 384 data.setDataPosition(0); 385 } 386 boolean r = onTransact(code, data, reply, flags); 387 if (reply != null) { 388 reply.setDataPosition(0); 389 } 390 return r; 391 } 392 393 /** 394 * Local implementation is a no-op. 395 */ 396 public void linkToDeath(DeathRecipient recipient, int flags) { 397 } 398 399 /** 400 * Local implementation is a no-op. 401 */ 402 public boolean unlinkToDeath(DeathRecipient recipient, int flags) { 403 return true; 404 } 405 406 protected void finalize() throws Throwable { 407 try { 408 destroy(); 409 } finally { 410 super.finalize(); 411 } 412 } 413 414 static void checkParcel(IBinder obj, int code, Parcel parcel, String msg) { 415 if (CHECK_PARCEL_SIZE && parcel.dataSize() >= 800*1024) { 416 // Trying to send > 800k, this is way too much 417 StringBuilder sb = new StringBuilder(); 418 sb.append(msg); 419 sb.append(": on "); 420 sb.append(obj); 421 sb.append(" calling "); 422 sb.append(code); 423 sb.append(" size "); 424 sb.append(parcel.dataSize()); 425 sb.append(" (data: "); 426 parcel.setDataPosition(0); 427 sb.append(parcel.readInt()); 428 sb.append(", "); 429 sb.append(parcel.readInt()); 430 sb.append(", "); 431 sb.append(parcel.readInt()); 432 sb.append(")"); 433 Slog.wtfStack(TAG, sb.toString()); 434 } 435 } 436 437 private native final void init(); 438 private native final void destroy(); 439 440 // Entry point from android_util_Binder.cpp's onTransact 441 private boolean execTransact(int code, long dataObj, long replyObj, 442 int flags) { 443 Parcel data = Parcel.obtain(dataObj); 444 Parcel reply = Parcel.obtain(replyObj); 445 // theoretically, we should call transact, which will call onTransact, 446 // but all that does is rewind it, and we just got these from an IPC, 447 // so we'll just call it directly. 448 boolean res; 449 // Log any exceptions as warnings, don't silently suppress them. 450 // If the call was FLAG_ONEWAY then these exceptions disappear into the ether. 451 try { 452 res = onTransact(code, data, reply, flags); 453 } catch (RemoteException e) { 454 if ((flags & FLAG_ONEWAY) != 0) { 455 Log.w(TAG, "Binder call failed.", e); 456 } else { 457 reply.setDataPosition(0); 458 reply.writeException(e); 459 } 460 res = true; 461 } catch (RuntimeException e) { 462 if ((flags & FLAG_ONEWAY) != 0) { 463 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e); 464 } else { 465 reply.setDataPosition(0); 466 reply.writeException(e); 467 } 468 res = true; 469 } catch (OutOfMemoryError e) { 470 // Unconditionally log this, since this is generally unrecoverable. 471 Log.e(TAG, "Caught an OutOfMemoryError from the binder stub implementation.", e); 472 RuntimeException re = new RuntimeException("Out of memory", e); 473 reply.setDataPosition(0); 474 reply.writeException(re); 475 res = true; 476 } 477 checkParcel(this, code, reply, "Unreasonably large binder reply buffer"); 478 reply.recycle(); 479 data.recycle(); 480 481 // Just in case -- we are done with the IPC, so there should be no more strict 482 // mode violations that have gathered for this thread. Either they have been 483 // parceled and are now in transport off to the caller, or we are returning back 484 // to the main transaction loop to wait for another incoming transaction. Either 485 // way, strict mode begone! 486 StrictMode.clearGatheredViolations(); 487 488 return res; 489 } 490} 491 492final class BinderProxy implements IBinder { 493 public native boolean pingBinder(); 494 public native boolean isBinderAlive(); 495 496 public IInterface queryLocalInterface(String descriptor) { 497 return null; 498 } 499 500 public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { 501 Binder.checkParcel(this, code, data, "Unreasonably large binder buffer"); 502 return transactNative(code, data, reply, flags); 503 } 504 505 public native String getInterfaceDescriptor() throws RemoteException; 506 public native boolean transactNative(int code, Parcel data, Parcel reply, 507 int flags) throws RemoteException; 508 public native void linkToDeath(DeathRecipient recipient, int flags) 509 throws RemoteException; 510 public native boolean unlinkToDeath(DeathRecipient recipient, int flags); 511 512 public void dump(FileDescriptor fd, String[] args) throws RemoteException { 513 Parcel data = Parcel.obtain(); 514 Parcel reply = Parcel.obtain(); 515 data.writeFileDescriptor(fd); 516 data.writeStringArray(args); 517 try { 518 transact(DUMP_TRANSACTION, data, reply, 0); 519 reply.readException(); 520 } finally { 521 data.recycle(); 522 reply.recycle(); 523 } 524 } 525 526 public void dumpAsync(FileDescriptor fd, String[] args) throws RemoteException { 527 Parcel data = Parcel.obtain(); 528 Parcel reply = Parcel.obtain(); 529 data.writeFileDescriptor(fd); 530 data.writeStringArray(args); 531 try { 532 transact(DUMP_TRANSACTION, data, reply, FLAG_ONEWAY); 533 } finally { 534 data.recycle(); 535 reply.recycle(); 536 } 537 } 538 539 BinderProxy() { 540 mSelf = new WeakReference(this); 541 } 542 543 @Override 544 protected void finalize() throws Throwable { 545 try { 546 destroy(); 547 } finally { 548 super.finalize(); 549 } 550 } 551 552 private native final void destroy(); 553 554 private static final void sendDeathNotice(DeathRecipient recipient) { 555 if (false) Log.v("JavaBinder", "sendDeathNotice to " + recipient); 556 try { 557 recipient.binderDied(); 558 } 559 catch (RuntimeException exc) { 560 Log.w("BinderNative", "Uncaught exception from death notification", 561 exc); 562 } 563 } 564 565 final private WeakReference mSelf; 566 private long mObject; 567 private long mOrgue; 568} 569