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.CallbackExecutor; 20 import android.annotation.FlaggedApi; 21 import android.annotation.IntDef; 22 import android.annotation.NonNull; 23 import android.annotation.Nullable; 24 import android.compat.annotation.UnsupportedAppUsage; 25 26 import java.io.FileDescriptor; 27 import java.lang.annotation.Retention; 28 import java.lang.annotation.RetentionPolicy; 29 import java.util.concurrent.Executor; 30 31 /** 32 * Base interface for a remotable object, the core part of a lightweight 33 * remote procedure call mechanism designed for high performance when 34 * performing in-process and cross-process calls. This 35 * interface describes the abstract protocol for interacting with a 36 * remotable object. Do not implement this interface directly, instead 37 * extend from {@link Binder}. 38 * 39 * <p>The key IBinder API is {@link #transact transact()} matched by 40 * {@link Binder#onTransact Binder.onTransact()}. These 41 * methods allow you to send a call to an IBinder object and receive a 42 * call coming in to a Binder object, respectively. This transaction API 43 * is synchronous, such that a call to {@link #transact transact()} does not 44 * return until the target has returned from 45 * {@link Binder#onTransact Binder.onTransact()}; this is the 46 * expected behavior when calling an object that exists in the local 47 * process, and the underlying inter-process communication (IPC) mechanism 48 * ensures that these same semantics apply when going across processes. 49 * 50 * <p>The data sent through transact() is a {@link Parcel}, a generic buffer 51 * of data that also maintains some meta-data about its contents. The meta 52 * data is used to manage IBinder object references in the buffer, so that those 53 * references can be maintained as the buffer moves across processes. This 54 * mechanism ensures that when an IBinder is written into a Parcel and sent to 55 * another process, if that other process sends a reference to that same IBinder 56 * back to the original process, then the original process will receive the 57 * same IBinder object back. These semantics allow IBinder/Binder objects to 58 * be used as a unique identity (to serve as a token or for other purposes) 59 * that can be managed across processes. 60 * 61 * <p>The system maintains a pool of transaction threads in each process that 62 * it runs in. These threads are used to dispatch all 63 * IPCs coming in from other processes. For example, when an IPC is made from 64 * process A to process B, the calling thread in A blocks in transact() as 65 * it sends the transaction to process B. The next available pool thread in 66 * B receives the incoming transaction, calls Binder.onTransact() on the target 67 * object, and replies with the result Parcel. Upon receiving its result, the 68 * thread in process A returns to allow its execution to continue. In effect, 69 * other processes appear to use as additional threads that you did not create 70 * executing in your own process. 71 * 72 * <p>The Binder system also supports recursion across processes. For example 73 * if process A performs a transaction to process B, and process B while 74 * handling that transaction calls transact() on an IBinder that is implemented 75 * in A, then the thread in A that is currently waiting for the original 76 * transaction to finish will take care of calling Binder.onTransact() on the 77 * object being called by B. This ensures that the recursion semantics when 78 * calling remote binder object are the same as when calling local objects. 79 * 80 * <p>When working with remote objects, you often want to find out when they 81 * are no longer valid. There are three ways this can be determined: 82 * <ul> 83 * <li> The {@link #transact transact()} method will throw a 84 * {@link RemoteException} exception if you try to call it on an IBinder 85 * whose process no longer exists. 86 * <li> The {@link #pingBinder()} method can be called, and will return false 87 * if the remote process no longer exists. 88 * <li> The {@link #linkToDeath linkToDeath()} method can be used to register 89 * a {@link DeathRecipient} with the IBinder, which will be called when its 90 * containing process goes away. 91 * </ul> 92 * 93 * @see Binder 94 */ 95 public interface IBinder { 96 /** 97 * The first transaction code available for user commands. 98 */ 99 int FIRST_CALL_TRANSACTION = 0x00000001; 100 /** 101 * The last transaction code available for user commands. 102 */ 103 int LAST_CALL_TRANSACTION = 0x00ffffff; 104 105 /** 106 * IBinder protocol transaction code: pingBinder(). 107 */ 108 int PING_TRANSACTION = ('_'<<24)|('P'<<16)|('N'<<8)|'G'; 109 110 /** 111 * IBinder protocol transaction code: dump internal state. 112 */ 113 int DUMP_TRANSACTION = ('_'<<24)|('D'<<16)|('M'<<8)|'P'; 114 115 /** 116 * IBinder protocol transaction code: execute a shell command. 117 * @hide 118 */ 119 int SHELL_COMMAND_TRANSACTION = ('_'<<24)|('C'<<16)|('M'<<8)|'D'; 120 121 /** 122 * IBinder protocol transaction code: interrogate the recipient side 123 * of the transaction for its canonical interface descriptor. 124 */ 125 int INTERFACE_TRANSACTION = ('_'<<24)|('N'<<16)|('T'<<8)|'F'; 126 127 /** 128 * IBinder protocol transaction code: send a tweet to the target 129 * object. The data in the parcel is intended to be delivered to 130 * a shared messaging service associated with the object; it can be 131 * anything, as long as it is not more than 130 UTF-8 characters to 132 * conservatively fit within common messaging services. As part of 133 * {@link Build.VERSION_CODES#HONEYCOMB_MR2}, all Binder objects are 134 * expected to support this protocol for fully integrated tweeting 135 * across the platform. To support older code, the default implementation 136 * logs the tweet to the main log as a simple emulation of broadcasting 137 * it publicly over the Internet. 138 * 139 * <p>Also, upon completing the dispatch, the object must make a cup 140 * of tea, return it to the caller, and exclaim "jolly good message 141 * old boy!". 142 */ 143 int TWEET_TRANSACTION = ('_'<<24)|('T'<<16)|('W'<<8)|'T'; 144 145 /** 146 * IBinder protocol transaction code: tell an app asynchronously that the 147 * caller likes it. The app is responsible for incrementing and maintaining 148 * its own like counter, and may display this value to the user to indicate the 149 * quality of the app. This is an optional command that applications do not 150 * need to handle, so the default implementation is to do nothing. 151 * 152 * <p>There is no response returned and nothing about the 153 * system will be functionally affected by it, but it will improve the 154 * app's self-esteem. 155 */ 156 int LIKE_TRANSACTION = ('_'<<24)|('L'<<16)|('I'<<8)|'K'; 157 158 /** @hide */ 159 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 160 int SYSPROPS_TRANSACTION = ('_'<<24)|('S'<<16)|('P'<<8)|'R'; 161 162 /** 163 * Flag to {@link #transact}: this is a one-way call, meaning that the 164 * caller returns immediately, without waiting for a result from the 165 * callee. Applies only if the caller and callee are in different 166 * processes. 167 * 168 * <p>The system provides special ordering semantics for multiple oneway calls 169 * being made to the same IBinder object: these calls will be dispatched in the 170 * other process one at a time, with the same order as the original calls. These 171 * are still dispatched by the IPC thread pool, so may execute on different threads, 172 * but the next one will not be dispatched until the previous one completes. This 173 * ordering is not guaranteed for calls on different IBinder objects or when mixing 174 * oneway and non-oneway calls on the same IBinder object.</p> 175 */ 176 int FLAG_ONEWAY = 0x00000001; 177 178 /** 179 * Flag to {@link #transact}: request binder driver to clear transaction data. 180 * 181 * Be very careful when using this flag in Java, since Java objects read from a Java 182 * Parcel may be non-trivial to clear. 183 * @hide 184 */ 185 int FLAG_CLEAR_BUF = 0x00000020; 186 187 /** 188 * @hide 189 */ 190 int FLAG_COLLECT_NOTED_APP_OPS = 0x00000002; 191 192 /** 193 * Limit that should be placed on IPC sizes to keep them safely under the 194 * transaction buffer limit. This is a recommendation, and is not the real 195 * limit. Transactions should be preferred to be even smaller than this. 196 * @hide 197 */ 198 public static final int MAX_IPC_SIZE = 64 * 1024; 199 200 /** 201 * Limit that should be placed on IPC sizes, in bytes, to keep them safely under the transaction 202 * buffer limit. 203 */ 204 @android.ravenwood.annotation.RavenwoodKeep getSuggestedMaxIpcSizeBytes()205 static int getSuggestedMaxIpcSizeBytes() { 206 return MAX_IPC_SIZE; 207 } 208 209 /** 210 * Get the canonical name of the interface supported by this binder. 211 */ getInterfaceDescriptor()212 public @Nullable String getInterfaceDescriptor() throws RemoteException; 213 214 /** 215 * Check to see if the object still exists. 216 * 217 * @return Returns false if the 218 * hosting process is gone, otherwise the result (always by default 219 * true) returned by the pingBinder() implementation on the other 220 * side. 221 */ pingBinder()222 public boolean pingBinder(); 223 224 /** 225 * Check to see if the process that the binder is in is still alive. 226 * 227 * @return false if the process is not alive. Note that if it returns 228 * true, the process may have died while the call is returning. 229 */ isBinderAlive()230 public boolean isBinderAlive(); 231 232 /** 233 * Attempt to retrieve a local implementation of an interface 234 * for this Binder object. If null is returned, you will need 235 * to instantiate a proxy class to marshall calls through 236 * the transact() method. 237 */ queryLocalInterface(@onNull String descriptor)238 public @Nullable IInterface queryLocalInterface(@NonNull String descriptor); 239 240 /** 241 * Print the object's state into the given stream. 242 * 243 * @param fd The raw file descriptor that the dump is being sent to. 244 * @param args additional arguments to the dump request. 245 */ dump(@onNull FileDescriptor fd, @Nullable String[] args)246 public void dump(@NonNull FileDescriptor fd, @Nullable String[] args) throws RemoteException; 247 248 /** 249 * Like {@link #dump(FileDescriptor, String[])} but always executes 250 * asynchronously. If the object is local, a new thread is created 251 * to perform the dump. 252 * 253 * @param fd The raw file descriptor that the dump is being sent to. 254 * @param args additional arguments to the dump request. 255 */ dumpAsync(@onNull FileDescriptor fd, @Nullable String[] args)256 public void dumpAsync(@NonNull FileDescriptor fd, @Nullable String[] args) 257 throws RemoteException; 258 259 /** 260 * Execute a shell command on this object. This may be performed asynchrously from the caller; 261 * the implementation must always call resultReceiver when finished. 262 * 263 * @param in The raw file descriptor that an input data stream can be read from. 264 * @param out The raw file descriptor that normal command messages should be written to. 265 * @param err The raw file descriptor that command error messages should be written to. 266 * @param args Command-line arguments. 267 * @param shellCallback Optional callback to the caller's shell to perform operations in it. 268 * @param resultReceiver Called when the command has finished executing, with the result code. 269 * @hide 270 */ shellCommand(@ullable FileDescriptor in, @Nullable FileDescriptor out, @Nullable FileDescriptor err, @NonNull String[] args, @Nullable ShellCallback shellCallback, @NonNull ResultReceiver resultReceiver)271 public void shellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out, 272 @Nullable FileDescriptor err, 273 @NonNull String[] args, @Nullable ShellCallback shellCallback, 274 @NonNull ResultReceiver resultReceiver) throws RemoteException; 275 276 /** 277 * Get the binder extension of this binder interface. 278 * This allows one to customize an interface without having to modify the original interface. 279 * 280 * @return null if don't have binder extension 281 * @throws RemoteException 282 * @hide 283 */ getExtension()284 public default @Nullable IBinder getExtension() throws RemoteException { 285 throw new IllegalStateException("Method is not implemented"); 286 } 287 288 /** 289 * Perform a generic operation with the object. 290 * 291 * @param code The action to perform. This should 292 * be a number between {@link #FIRST_CALL_TRANSACTION} and 293 * {@link #LAST_CALL_TRANSACTION}. 294 * @param data Marshalled data to send to the target. Must not be null. 295 * If you are not sending any data, you must create an empty Parcel 296 * that is given here. 297 * @param reply Marshalled data to be received from the target. May be 298 * null if you are not interested in the return value. 299 * @param flags Additional operation flags. Either 0 for a normal 300 * RPC, or {@link #FLAG_ONEWAY} for a one-way RPC. 301 * 302 * @return Returns the result from {@link Binder#onTransact}. A successful call 303 * generally returns true; false generally means the transaction code was not 304 * understood. For a oneway call to a different process false should never be 305 * returned. If a oneway call is made to code in the same process (usually to 306 * a C++ or Rust implementation), then there are no oneway semantics, and 307 * false can still be returned. 308 */ transact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags)309 public boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags) 310 throws RemoteException; 311 312 /** 313 * Interface for receiving a callback when the process hosting an IBinder 314 * has gone away. 315 * 316 * @see #linkToDeath 317 */ 318 public interface DeathRecipient { binderDied()319 public void binderDied(); 320 321 /** 322 * The function called when the process hosting an IBinder 323 * has gone away. 324 * 325 * This callback will be called from any binder thread like any other binder 326 * transaction. If the process receiving this notification is multithreaded 327 * then synchronization may be required because other threads may be executing 328 * at the same time. 329 * 330 * No locks are held in libbinder when {@link binderDied} is called. 331 * 332 * There is no need to call {@link unlinkToDeath} in the binderDied callback. 333 * The binder is already dead so {@link unlinkToDeath} is a no-op. 334 * It will be unlinked when the last local reference of that binder proxy is 335 * dropped. 336 * 337 * @param who The IBinder that has become invalid 338 */ binderDied(@onNull IBinder who)339 default void binderDied(@NonNull IBinder who) { 340 binderDied(); 341 } 342 } 343 344 /** 345 * Register the recipient for a notification if this binder 346 * goes away. If this binder object unexpectedly goes away 347 * (typically because its hosting process has been killed), 348 * then the given {@link DeathRecipient}'s 349 * {@link DeathRecipient#binderDied DeathRecipient.binderDied()} method 350 * will be called. 351 * 352 * <p>This will automatically be unlinked when all references to the linked 353 * binder proxy are dropped.</p> 354 * 355 * <p>You will only receive death notifications for remote binders, 356 * as local binders by definition can't die without you dying as well.</p> 357 * 358 * @throws RemoteException if the target IBinder's 359 * process has already died. 360 * 361 * @see #unlinkToDeath 362 */ linkToDeath(@onNull DeathRecipient recipient, int flags)363 public void linkToDeath(@NonNull DeathRecipient recipient, int flags) 364 throws RemoteException; 365 366 /** 367 * Remove a previously registered death notification. 368 * The recipient will no longer be called if this object 369 * dies. 370 * 371 * @return {@code true} if the <var>recipient</var> is successfully 372 * unlinked, assuring you that its 373 * {@link DeathRecipient#binderDied DeathRecipient.binderDied()} method 374 * will not be called; {@code false} if the target IBinder has already 375 * died, meaning the method has been (or soon will be) called. 376 * 377 * @throws java.util.NoSuchElementException if the given 378 * <var>recipient</var> has not been registered with the IBinder, and 379 * the IBinder is still alive. Note that if the <var>recipient</var> 380 * was never registered, but the IBinder has already died, then this 381 * exception will <em>not</em> be thrown, and you will receive a false 382 * return value instead. 383 */ unlinkToDeath(@onNull DeathRecipient recipient, int flags)384 public boolean unlinkToDeath(@NonNull DeathRecipient recipient, int flags); 385 386 /** 387 * A callback interface for receiving frozen state change events. 388 */ 389 @FlaggedApi(Flags.FLAG_BINDER_FROZEN_STATE_CHANGE_CALLBACK) 390 interface FrozenStateChangeCallback { 391 /** 392 * @hide 393 */ 394 @IntDef(prefix = {"STATE_"}, value = { 395 STATE_FROZEN, 396 STATE_UNFROZEN, 397 }) 398 @Retention(RetentionPolicy.SOURCE) 399 @interface State { 400 } 401 402 /** 403 * Represents the frozen state of the remote process. 404 * 405 * While in this state, the remote process won't be able to receive and handle a 406 * transaction. Therefore, any asynchronous transactions will be buffered and delivered when 407 * the process is unfrozen, and any synchronous transactions will result in an error. 408 * 409 * Buffered transactions may be stale by the time that the process is unfrozen and handles 410 * them. To avoid overwhelming the remote process with stale events or overflowing their 411 * buffers, it's best to avoid sending binder transactions to a frozen process. 412 */ 413 int STATE_FROZEN = 0; 414 415 /** 416 * Represents the unfrozen state of the remote process. 417 * 418 * In this state, the process hosting the object can execute and is not restricted 419 * by the freezer from using the CPU or responding to binder transactions. 420 */ 421 int STATE_UNFROZEN = 1; 422 423 /** 424 * Interface for receiving a callback when the process hosting an IBinder 425 * has changed its frozen state. 426 * 427 * @param who The IBinder whose hosting process has changed state. 428 * @param state The latest state. 429 */ onFrozenStateChanged(@onNull IBinder who, @State int state)430 void onFrozenStateChanged(@NonNull IBinder who, @State int state); 431 } 432 433 /** 434 * This method provides a callback mechanism to notify about process frozen/unfrozen events. 435 * Upon registration and any subsequent state changes, the callback is invoked with the latest 436 * process frozen state. 437 * 438 * <p>If the listener process (the one using this API) is itself frozen, state change events 439 * might be combined into a single one with the latest frozen state. This single event would 440 * then be delivered when the listener process becomes unfrozen. Similarly, if an event happens 441 * before the previous event is consumed, they might be combined. This means the callback might 442 * not be called for every single state change, so don't rely on this API to count how many 443 * times the state has changed.</p> 444 * 445 * <p>The callback is automatically removed when all references to the binder proxy are 446 * dropped.</p> 447 * 448 * <p>You will only receive state change notifications for remote binders, as local binders by 449 * definition can't be frozen without you being frozen too.</p> 450 * 451 * @param executor The executor on which to run the callback. 452 * @param callback The callback used to deliver state change notifications. 453 * 454 * @throws {@link UnsupportedOperationException} if the kernel binder driver does not support 455 * this feature. 456 */ 457 @FlaggedApi(Flags.FLAG_BINDER_FROZEN_STATE_CHANGE_CALLBACK) addFrozenStateChangeCallback( @onNull @allbackExecutor Executor executor, @NonNull FrozenStateChangeCallback callback)458 default void addFrozenStateChangeCallback( 459 @NonNull @CallbackExecutor Executor executor, 460 @NonNull FrozenStateChangeCallback callback) 461 throws RemoteException { 462 throw new UnsupportedOperationException(); 463 } 464 465 /** 466 * Same as {@link #addFrozenStateChangeCallback(Executor, FrozenStateChangeCallback)} except 467 * that callbacks are invoked on a binder thread. 468 * 469 * @hide 470 */ addFrozenStateChangeCallback(@onNull FrozenStateChangeCallback callback)471 default void addFrozenStateChangeCallback(@NonNull FrozenStateChangeCallback callback) 472 throws RemoteException { 473 addFrozenStateChangeCallback(Runnable::run, callback); 474 } 475 476 /** 477 * Unregister a {@link FrozenStateChangeCallback}. The callback will no longer be invoked when 478 * the hosting process changes its frozen state. 479 */ 480 @FlaggedApi(Flags.FLAG_BINDER_FROZEN_STATE_CHANGE_CALLBACK) removeFrozenStateChangeCallback(@onNull FrozenStateChangeCallback callback)481 default boolean removeFrozenStateChangeCallback(@NonNull FrozenStateChangeCallback callback) { 482 throw new UnsupportedOperationException(); 483 } 484 } 485