blob: ec39199976039cd415705ae91ae6df339a653254 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Dianne Hackborn4cd650c2017-07-31 17:38:53 -070019import android.annotation.NonNull;
20import android.annotation.Nullable;
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +000021import android.annotation.SystemApi;
Andrei Onea24ec3212019-03-15 17:35:05 +000022import android.annotation.UnsupportedAppUsage;
Philip P. Moltmann2b08aaf2019-06-10 08:49:11 -070023import android.app.AppOpsManager;
Eugene Suslacf00ade2017-04-10 11:51:58 -070024import android.util.ExceptionUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.util.Log;
Dianne Hackborn017c6a22014-09-25 17:41:34 -070026import android.util.Slog;
Eugene Suslacf00ade2017-04-10 11:51:58 -070027
Michael Wachenschwanz58ac2182018-01-30 15:11:19 -080028import com.android.internal.os.BinderInternal;
Olivier Gaillard289ba402018-07-24 18:50:13 +010029import com.android.internal.os.BinderInternal.CallSession;
Dianne Hackborndb4e33f2013-04-01 17:28:16 -070030import com.android.internal.util.FastPrintWriter;
Eugene Suslacf00ade2017-04-10 11:51:58 -070031import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
32import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
33
Olivier Gaillarde4ff3972018-08-16 14:01:58 +010034import dalvik.annotation.optimization.CriticalNative;
35
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070036import libcore.io.IoUtils;
Hans Boehm5e5b13f2017-09-28 18:16:50 -070037import libcore.util.NativeAllocationRegistry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038
39import java.io.FileDescriptor;
Makoto Onuki4c7073b2019-11-04 10:37:15 -080040import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import java.io.FileOutputStream;
Makoto Onuki4c7073b2019-11-04 10:37:15 -080042import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import java.io.PrintWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import java.lang.reflect.Modifier;
45
46/**
47 * Base class for a remotable object, the core part of a lightweight
48 * remote procedure call mechanism defined by {@link IBinder}.
49 * This class is an implementation of IBinder that provides
Dianne Hackbornab4a81b2014-10-09 17:59:38 -070050 * standard local implementation of such an object.
51 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052 * <p>Most developers will not implement this class directly, instead using the
Scott Main40eee612012-08-06 17:48:37 -070053 * <a href="{@docRoot}guide/components/aidl.html">aidl</a> tool to describe the desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054 * interface, having it generate the appropriate Binder subclass. You can,
55 * however, derive directly from Binder to implement your own custom RPC
56 * protocol or simply instantiate a raw Binder object directly to use as a
57 * token that can be shared across processes.
Dianne Hackbornab4a81b2014-10-09 17:59:38 -070058 *
59 * <p>This class is just a basic IPC primitive; it has no impact on an application's
60 * lifecycle, and is valid only as long as the process that created it continues to run.
61 * To use this correctly, you must be doing so within the context of a top-level
62 * application component (a {@link android.app.Service}, {@link android.app.Activity},
63 * or {@link android.content.ContentProvider}) that lets the system know your process
64 * should remain running.</p>
65 *
66 * <p>You must keep in mind the situations in which your process
67 * could go away, and thus require that you later re-create a new Binder and re-attach
68 * it when the process starts again. For example, if you are using this within an
69 * {@link android.app.Activity}, your activity's process may be killed any time the
70 * activity is not started; if the activity is later re-created you will need to
71 * create a new Binder and hand it back to the correct place again; you need to be
72 * aware that your process may be started for another reason (for example to receive
73 * a broadcast) that will not involve re-creating the activity and thus run its code
74 * to create a new Binder.</p>
75 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 * @see IBinder
77 */
78public class Binder implements IBinder {
79 /*
80 * Set this flag to true to detect anonymous, local or member classes
81 * that extend this Binder class and that are not static. These kind
82 * of classes can potentially create leaks.
83 */
84 private static final boolean FIND_POTENTIAL_LEAKS = false;
Jeff Sharkeyf5299f12017-03-17 10:25:07 -060085 /** @hide */
86 public static final boolean CHECK_PARCEL_SIZE = false;
Dianne Hackborn017c6a22014-09-25 17:41:34 -070087 static final String TAG = "Binder";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
Makoto Onukif9b941f2016-03-10 17:19:08 -080089 /** @hide */
90 public static boolean LOG_RUNTIME_EXCEPTION = false; // DO NOT SUBMIT WITH TRUE
91
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -070092 /**
Olivier Gaillardc17d2802018-11-19 17:08:17 +000093 * Value to represents that a calling work source is not set.
94 *
95 * This constatnt needs to be kept in sync with IPCThreadState::kUnsetWorkSource.
96 *
97 * @hide
98 */
99 public static final int UNSET_WORKSOURCE = -1;
100
101 /**
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700102 * Control whether dump() calls are allowed.
103 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600104 private static volatile String sDumpDisabled = null;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700105
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400106 /**
107 * Global transaction tracker instance for this process.
108 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600109 private static volatile TransactionTracker sTransactionTracker = null;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400110
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700111 /**
Olivier Gaillard289ba402018-07-24 18:50:13 +0100112 * Global observer for this process.
113 */
114 private static BinderInternal.Observer sObserver = null;
115
116 /**
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700117 * Guestimate of native memory associated with a Binder.
118 */
119 private static final int NATIVE_ALLOCATION_SIZE = 500;
120
121 private static native long getNativeFinalizer();
122
123 // Use a Holder to allow static initialization of Binder in the boot image, and
124 // possibly to avoid some initialization ordering issues.
125 private static class NoImagePreloadHolder {
126 public static final NativeAllocationRegistry sRegistry = new NativeAllocationRegistry(
127 Binder.class.getClassLoader(), getNativeFinalizer(), NATIVE_ALLOCATION_SIZE);
128 }
129
Olivier Gaillard289ba402018-07-24 18:50:13 +0100130
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400131 // Transaction tracking code.
132
133 /**
134 * Flag indicating whether we should be tracing transact calls.
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400135 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600136 private static volatile boolean sTracingEnabled = false;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400137
138 /**
139 * Enable Binder IPC tracing.
140 *
141 * @hide
142 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600143 public static void enableTracing() {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400144 sTracingEnabled = true;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600145 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400146
147 /**
148 * Disable Binder IPC tracing.
149 *
150 * @hide
151 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600152 public static void disableTracing() {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400153 sTracingEnabled = false;
154 }
155
156 /**
157 * Check if binder transaction tracing is enabled.
158 *
159 * @hide
160 */
161 public static boolean isTracingEnabled() {
162 return sTracingEnabled;
163 }
164
165 /**
166 * Get the binder transaction tracker for this process.
167 *
168 * @hide
169 */
170 public synchronized static TransactionTracker getTransactionTracker() {
171 if (sTransactionTracker == null)
172 sTransactionTracker = new TransactionTracker();
173 return sTransactionTracker;
174 }
175
Olivier Gaillard289ba402018-07-24 18:50:13 +0100176 /**
177 * Get the binder transaction observer for this process.
178 *
179 * @hide
180 */
181 public static void setObserver(@Nullable BinderInternal.Observer observer) {
182 sObserver = observer;
183 }
184
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600185 /** {@hide} */
186 static volatile boolean sWarnOnBlocking = false;
187
188 /**
189 * Warn if any blocking binder transactions are made out from this process.
190 * This is typically only useful for the system process, to prevent it from
191 * blocking on calls to external untrusted code. Instead, all outgoing calls
192 * that require a result must be sent as {@link IBinder#FLAG_ONEWAY} calls
193 * which deliver results through a callback interface.
194 *
195 * @hide
196 */
197 public static void setWarnOnBlocking(boolean warnOnBlocking) {
198 sWarnOnBlocking = warnOnBlocking;
199 }
200
201 /**
202 * Allow blocking calls on the given interface, overriding the requested
203 * value of {@link #setWarnOnBlocking(boolean)}.
204 * <p>
205 * This should only be rarely called when you are <em>absolutely sure</em>
206 * the remote interface is a built-in system component that can never be
207 * upgraded. In particular, this <em>must never</em> be called for
208 * interfaces hosted by package that could be upgraded or replaced,
209 * otherwise you risk system instability if that remote interface wedges.
210 *
211 * @hide
212 */
213 public static IBinder allowBlocking(IBinder binder) {
214 try {
215 if (binder instanceof BinderProxy) {
216 ((BinderProxy) binder).mWarnOnBlocking = false;
Dianne Hackbornc81983a2017-10-20 16:16:32 -0700217 } else if (binder != null && binder.getInterfaceDescriptor() != null
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600218 && binder.queryLocalInterface(binder.getInterfaceDescriptor()) == null) {
219 Log.w(TAG, "Unable to allow blocking on interface " + binder);
220 }
221 } catch (RemoteException ignored) {
222 }
223 return binder;
224 }
225
226 /**
Jeff Sharkey59189482017-11-09 18:13:43 -0700227 * Reset the given interface back to the default blocking behavior,
228 * reverting any changes made by {@link #allowBlocking(IBinder)}.
229 *
230 * @hide
231 */
232 public static IBinder defaultBlocking(IBinder binder) {
233 if (binder instanceof BinderProxy) {
234 ((BinderProxy) binder).mWarnOnBlocking = sWarnOnBlocking;
235 }
236 return binder;
237 }
238
239 /**
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600240 * Inherit the current {@link #allowBlocking(IBinder)} value from one given
241 * interface to another.
242 *
243 * @hide
244 */
245 public static void copyAllowBlocking(IBinder fromBinder, IBinder toBinder) {
246 if (fromBinder instanceof BinderProxy && toBinder instanceof BinderProxy) {
247 ((BinderProxy) toBinder).mWarnOnBlocking = ((BinderProxy) fromBinder).mWarnOnBlocking;
248 }
249 }
250
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700251 /**
252 * Raw native pointer to JavaBBinderHolder object. Owned by this Java object. Not null.
253 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000254 @UnsupportedAppUsage
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700255 private final long mObject;
256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 private IInterface mOwner;
258 private String mDescriptor;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 /**
261 * Return the ID of the process that sent you the current transaction
262 * that is being processed. This pid can be used with higher-level
263 * system services to determine its identity and check permissions.
264 * If the current thread is not currently executing an incoming transaction,
265 * then its own pid is returned.
266 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100267 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 public static final native int getCallingPid();
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 /**
Dianne Hackborn74ee8652012-09-07 18:33:18 -0700271 * Return the Linux uid assigned to the process that sent you the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 * current transaction that is being processed. This uid can be used with
273 * higher-level system services to determine its identity and check
274 * permissions. If the current thread is not currently executing an
275 * incoming transaction, then its own uid is returned.
276 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100277 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 public static final native int getCallingUid();
Amith Yamasani742a6712011-05-04 14:49:28 -0700279
280 /**
Nikita Ioffea929cf02019-01-03 13:35:22 +0000281 * Returns {@code true} if the current thread is currently executing an
282 * incoming transaction.
283 *
284 * @hide
285 */
286 @CriticalNative
287 public static final native boolean isHandlingTransaction();
288
289 /**
290 * Return the Linux uid assigned to the process that sent the transaction
291 * currently being processed.
292 *
293 * @throws IllegalStateException if the current thread is not currently
294 * executing an incoming transaction.
295 */
296 public static final int getCallingUidOrThrow() {
297 if (!isHandlingTransaction()) {
298 throw new IllegalStateException(
299 "Thread is not in a binder transcation");
300 }
301 return getCallingUid();
302 }
303
304 /**
Dianne Hackborn74ee8652012-09-07 18:33:18 -0700305 * Return the UserHandle assigned to the process that sent you the
306 * current transaction that is being processed. This is the user
307 * of the caller. It is distinct from {@link #getCallingUid()} in that a
308 * particular user will have multiple distinct apps running under it each
309 * with their own uid. If the current thread is not currently executing an
310 * incoming transaction, then its own UserHandle is returned.
311 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700312 public static final @NonNull UserHandle getCallingUserHandle() {
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700313 return UserHandle.of(UserHandle.getUserId(getCallingUid()));
Dianne Hackborn74ee8652012-09-07 18:33:18 -0700314 }
315
316 /**
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700317 * Reset the identity of the incoming IPC on the current thread. This can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 * be useful if, while handling an incoming call, you will be calling
319 * on interfaces of other objects that may be local to your process and
320 * need to do permission checks on the calls coming into them (so they
321 * will check the permission of your own local process, and not whatever
322 * process originally called you).
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700323 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 * @return Returns an opaque token that can be used to restore the
325 * original calling identity by passing it to
326 * {@link #restoreCallingIdentity(long)}.
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700327 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 * @see #getCallingPid()
329 * @see #getCallingUid()
330 * @see #restoreCallingIdentity(long)
331 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100332 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 public static final native long clearCallingIdentity();
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 /**
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700336 * Restore the identity of the incoming IPC on the current thread
337 * back to a previously identity that was returned by {@link
338 * #clearCallingIdentity}.
339 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 * @param token The opaque token that was previously returned by
341 * {@link #clearCallingIdentity}.
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700342 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 * @see #clearCallingIdentity
344 */
345 public static final native void restoreCallingIdentity(long token);
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700346
347 /**
Eugene Susla6a7006a2017-03-13 12:57:58 -0700348 * Convenience method for running the provided action enclosed in
349 * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity}
350 *
Eugene Suslacf00ade2017-04-10 11:51:58 -0700351 * Any exception thrown by the given action will be caught and rethrown after the call to
352 * {@link #restoreCallingIdentity}
353 *
Eugene Susla6a7006a2017-03-13 12:57:58 -0700354 * @hide
355 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700356 public static final void withCleanCallingIdentity(@NonNull ThrowingRunnable action) {
Eugene Susla6a7006a2017-03-13 12:57:58 -0700357 long callingIdentity = clearCallingIdentity();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700358 Throwable throwableToPropagate = null;
Eugene Susla6a7006a2017-03-13 12:57:58 -0700359 try {
Eugene Susla2f5ee712017-06-23 17:25:24 -0700360 action.runOrThrow();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700361 } catch (Throwable throwable) {
362 throwableToPropagate = throwable;
Eugene Susla6a7006a2017-03-13 12:57:58 -0700363 } finally {
364 restoreCallingIdentity(callingIdentity);
Eugene Suslacf00ade2017-04-10 11:51:58 -0700365 if (throwableToPropagate != null) {
366 throw ExceptionUtils.propagate(throwableToPropagate);
367 }
Eugene Susla6a7006a2017-03-13 12:57:58 -0700368 }
369 }
370
371 /**
372 * Convenience method for running the provided action enclosed in
373 * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity} returning the result
374 *
Eugene Suslacf00ade2017-04-10 11:51:58 -0700375 * Any exception thrown by the given action will be caught and rethrown after the call to
376 * {@link #restoreCallingIdentity}
377 *
Eugene Susla6a7006a2017-03-13 12:57:58 -0700378 * @hide
379 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700380 public static final <T> T withCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) {
Eugene Susla6a7006a2017-03-13 12:57:58 -0700381 long callingIdentity = clearCallingIdentity();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700382 Throwable throwableToPropagate = null;
Eugene Susla6a7006a2017-03-13 12:57:58 -0700383 try {
Eugene Susla2f5ee712017-06-23 17:25:24 -0700384 return action.getOrThrow();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700385 } catch (Throwable throwable) {
386 throwableToPropagate = throwable;
387 return null; // overridden by throwing in finally block
Eugene Susla6a7006a2017-03-13 12:57:58 -0700388 } finally {
389 restoreCallingIdentity(callingIdentity);
Eugene Suslacf00ade2017-04-10 11:51:58 -0700390 if (throwableToPropagate != null) {
391 throw ExceptionUtils.propagate(throwableToPropagate);
392 }
Eugene Susla6a7006a2017-03-13 12:57:58 -0700393 }
394 }
395
396 /**
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700397 * Sets the native thread-local StrictMode policy mask.
398 *
399 * <p>The StrictMode settings are kept in two places: a Java-level
400 * threadlocal for libcore/Dalvik, and a native threadlocal (set
401 * here) for propagation via Binder calls. This is a little
402 * unfortunate, but necessary to break otherwise more unfortunate
403 * dependencies either of Dalvik on Android, or Android
404 * native-only code on Dalvik.
405 *
406 * @see StrictMode
407 * @hide
408 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100409 @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700410 public static final native void setThreadStrictModePolicy(int policyMask);
411
412 /**
413 * Gets the current native thread-local StrictMode policy mask.
414 *
415 * @see #setThreadStrictModePolicy
416 * @hide
417 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100418 @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700419 public static final native int getThreadStrictModePolicy();
420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 /**
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100422 * Sets the work source for this thread.
423 *
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000424 * <p>All the following binder calls on this thread will use the provided work source. If this
425 * is called during an on-going binder transaction, all the following binder calls will use the
426 * work source until the end of the transaction.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100427 *
428 * <p>The concept of worksource is similar to {@link WorkSource}. However, for performance
429 * reasons, we only support one UID. This UID represents the original user responsible for the
430 * binder calls.
431 *
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000432 * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after setting the
433 * worksource.
434 *
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100435 * <p>A typical use case would be
436 * <pre>
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000437 * long token = Binder.setCallingWorkSourceUid(uid);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100438 * try {
439 * // Call an API.
440 * } finally {
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000441 * Binder.restoreCallingWorkSource(token);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100442 * }
443 * </pre>
444 *
Olivier Gaillard1d724582018-11-19 14:35:37 +0000445 * <p>The work source will be propagated for future outgoing binder transactions
446 * executed on this thread.
447 *
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100448 * @param workSource The original UID responsible for the binder call.
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000449 * @return token to restore original work source.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100450 **/
451 @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000452 public static final native long setCallingWorkSourceUid(int workSource);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100453
454 /**
455 * Returns the work source set by the caller.
456 *
457 * Unlike {@link Binder#getCallingUid()}, this result of this method cannot be trusted. The
Olivier Gaillardf84f4f82019-04-03 11:32:12 +0100458 * caller can set the value to whatever they want. Only use this value if you trust the calling
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100459 * uid.
460 *
461 * @return The original UID responsible for the binder transaction.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100462 */
463 @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000464 public static final native int getCallingWorkSourceUid();
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100465
466 /**
467 * Clears the work source on this thread.
468 *
Olivier Gaillard1d724582018-11-19 14:35:37 +0000469 * <p>The work source will be propagated for future outgoing binder transactions
470 * executed on this thread.
471 *
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000472 * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after clearing the
473 * worksource.
474 *
475 * <p>A typical use case would be
476 * <pre>
477 * long token = Binder.clearCallingWorkSource();
478 * try {
479 * // Call an API.
480 * } finally {
481 * Binder.restoreCallingWorkSource(token);
482 * }
483 * </pre>
484 *
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000485 * @return token to restore original work source.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100486 **/
487 @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000488 public static final native long clearCallingWorkSource();
489
490 /**
491 * Restores the work source on this thread using a token returned by
492 * {@link #setCallingWorkSourceUid(int) or {@link clearCallingWorkSource()}.
493 *
494 * <p>A typical use case would be
495 * <pre>
496 * long token = Binder.setCallingWorkSourceUid(uid);
497 * try {
498 * // Call an API.
499 * } finally {
500 * Binder.restoreCallingWorkSource(token);
501 * }
502 * </pre>
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000503 **/
504 @CriticalNative
505 public static final native void restoreCallingWorkSource(long token);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100506
507 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 * Flush any Binder commands pending in the current thread to the kernel
509 * driver. This can be
510 * useful to call before performing an operation that may block for a long
511 * time, to ensure that any pending object references have been released
512 * in order to prevent the process from holding on to objects longer than
513 * it needs to.
514 */
515 public static final native void flushPendingCommands();
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 /**
518 * Add the calling thread to the IPC thread pool. This function does
519 * not return until the current process is exiting.
520 */
Andreas Gampeacd19872018-03-16 15:58:24 -0700521 public static final void joinThreadPool() {
522 BinderInternal.joinThreadPool();
523 }
Jeff Brown1951ce82013-04-04 22:45:12 -0700524
525 /**
526 * Returns true if the specified interface is a proxy.
527 * @hide
528 */
529 public static final boolean isProxy(IInterface iface) {
530 return iface.asBinder() != iface;
531 }
532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 /**
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700534 * Call blocks until the number of executing binder threads is less
535 * than the maximum number of binder threads allowed for this process.
Wale Ogunwale8d906342015-04-15 09:10:03 -0700536 * @hide
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700537 */
538 public static final native void blockUntilThreadAvailable();
539
540 /**
Martijn Coenend2c86ab2018-07-17 16:30:40 +0200541 * Default constructor just initializes the object.
542 *
543 * If you're creating a Binder token (a Binder object without an attached interface),
544 * you should use {@link #Binder(String)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 */
546 public Binder() {
Martijn Coenend2c86ab2018-07-17 16:30:40 +0200547 this(null);
548 }
549
550 /**
551 * Constructor for creating a raw Binder object (token) along with a descriptor.
552 *
553 * The descriptor of binder objects usually specifies the interface they are implementing.
554 * In case of binder tokens, no interface is implemented, and the descriptor can be used
555 * as a sort of tag to help identify the binder token. This will help identify remote
556 * references to these objects more easily when debugging.
557 *
558 * @param descriptor Used to identify the creator of this token, for example the class name.
559 * Instead of creating multiple tokens with the same descriptor, consider adding a suffix to
560 * help identify them.
561 */
562 public Binder(@Nullable String descriptor) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700563 mObject = getNativeBBinderHolder();
564 NoImagePreloadHolder.sRegistry.registerNativeAllocation(this, mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565
566 if (FIND_POTENTIAL_LEAKS) {
567 final Class<? extends Binder> klass = getClass();
568 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
569 (klass.getModifiers() & Modifier.STATIC) == 0) {
570 Log.w(TAG, "The following Binder class should be static or leaks might occur: " +
571 klass.getCanonicalName());
572 }
573 }
Martijn Coenend2c86ab2018-07-17 16:30:40 +0200574 mDescriptor = descriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 /**
578 * Convenience method for associating a specific interface with the Binder.
579 * After calling, queryLocalInterface() will be implemented for you
580 * to return the given owner IInterface when the corresponding
581 * descriptor is requested.
582 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700583 public void attachInterface(@Nullable IInterface owner, @Nullable String descriptor) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 mOwner = owner;
585 mDescriptor = descriptor;
586 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 /**
589 * Default implementation returns an empty interface name.
590 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700591 public @Nullable String getInterfaceDescriptor() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 return mDescriptor;
593 }
594
595 /**
596 * Default implementation always returns true -- if you got here,
597 * the object is alive.
598 */
599 public boolean pingBinder() {
600 return true;
601 }
602
603 /**
604 * {@inheritDoc}
605 *
606 * Note that if you're calling on a local binder, this always returns true
607 * because your process is alive if you're calling it.
608 */
609 public boolean isBinderAlive() {
610 return true;
611 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 /**
614 * Use information supplied to attachInterface() to return the
615 * associated IInterface if it matches the requested
616 * descriptor.
617 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700618 public @Nullable IInterface queryLocalInterface(@NonNull String descriptor) {
Dianne Hackbornc81983a2017-10-20 16:16:32 -0700619 if (mDescriptor != null && mDescriptor.equals(descriptor)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 return mOwner;
621 }
622 return null;
623 }
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700624
625 /**
626 * Control disabling of dump calls in this process. This is used by the system
627 * process watchdog to disable incoming dump calls while it has detecting the system
628 * is hung and is reporting that back to the activity controller. This is to
629 * prevent the controller from getting hung up on bug reports at this point.
630 * @hide
631 *
632 * @param msg The message to show instead of the dump; if null, dumps are
633 * re-enabled.
634 */
635 public static void setDumpDisabled(String msg) {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600636 sDumpDisabled = msg;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700637 }
638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 /**
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100640 * Listener to be notified about each proxy-side binder call.
641 *
642 * See {@link setProxyTransactListener}.
643 * @hide
644 */
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000645 @SystemApi
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100646 public interface ProxyTransactListener {
647 /**
648 * Called before onTransact.
649 *
650 * @return an object that will be passed back to #onTransactEnded (or null).
Lucas Dupin8968f6a2019-08-09 17:41:15 -0700651 * @hide
652 */
653 @Nullable
654 default Object onTransactStarted(@NonNull IBinder binder, int transactionCode, int flags) {
655 return onTransactStarted(binder, transactionCode);
656 }
657
658 /**
659 * Called before onTransact.
660 *
661 * @return an object that will be passed back to #onTransactEnded (or null).
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100662 */
Olivier Gaillard5a73a512019-03-05 16:32:35 +0000663 @Nullable
664 Object onTransactStarted(@NonNull IBinder binder, int transactionCode);
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100665
666 /**
667 * Called after onTranact (even when an exception is thrown).
668 *
669 * @param session The object return by #onTransactStarted.
670 */
671 void onTransactEnded(@Nullable Object session);
672 }
673
674 /**
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100675 * Propagates the work source to binder calls executed by the system server.
676 *
677 * <li>By default, this listener will propagate the worksource if the outgoing call happens on
678 * the same thread as the incoming binder call.
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000679 * <li>Custom attribution can be done by calling {@link ThreadLocalWorkSource#setUid(int)}.
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100680 * @hide
681 */
682 public static class PropagateWorkSourceTransactListener implements ProxyTransactListener {
683 @Override
684 public Object onTransactStarted(IBinder binder, int transactionCode) {
685 // Note that {@link Binder#getCallingUid()} is already set to the UID of the current
686 // process when this method is called.
687 //
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000688 // We use ThreadLocalWorkSource instead. It also allows feature owners to set
689 // {@link ThreadLocalWorkSource#set(int) manually to attribute resources to a UID.
690 int uid = ThreadLocalWorkSource.getUid();
691 if (uid != ThreadLocalWorkSource.UID_NONE) {
692 return Binder.setCallingWorkSourceUid(uid);
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100693 }
694 return null;
695 }
696
697 @Override
698 public void onTransactEnded(Object session) {
699 if (session != null) {
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000700 long token = (long) session;
701 Binder.restoreCallingWorkSource(token);
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100702 }
703 }
704 }
705
706 /**
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100707 * Sets a listener for the transact method on the proxy-side.
708 *
709 * <li>The listener is global. Only fast operations should be done to avoid thread
710 * contentions.
711 * <li>The listener implementation needs to handle synchronization if needed. The methods on the
712 * listener can be called concurrently.
713 * <li>Listener set will be used for new transactions. On-going transaction will still use the
714 * previous listener (if already set).
715 * <li>The listener is called on the critical path of the binder transaction so be careful about
716 * performance.
717 * <li>Never execute another binder transaction inside the listener.
718 * @hide
719 */
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000720 @SystemApi
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100721 public static void setProxyTransactListener(@Nullable ProxyTransactListener listener) {
722 BinderProxy.setTransactListener(listener);
723 }
724
725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 * Default implementation is a stub that returns false. You will want
727 * to override this to do the appropriate unmarshalling of transactions.
728 *
729 * <p>If you want to call this, call transact().
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700730 *
Dianne Hackborn18482ae2017-08-01 17:41:00 -0700731 * <p>Implementations that are returning a result should generally use
732 * {@link Parcel#writeNoException() Parcel.writeNoException} and
733 * {@link Parcel#writeException(Exception) Parcel.writeException} to propagate
734 * exceptions back to the caller.</p>
735 *
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700736 * @param code The action to perform. This should
737 * be a number between {@link #FIRST_CALL_TRANSACTION} and
738 * {@link #LAST_CALL_TRANSACTION}.
739 * @param data Marshalled data being received from the caller.
740 * @param reply If the caller is expecting a result back, it should be marshalled
741 * in to here.
742 * @param flags Additional operation flags. Either 0 for a normal
743 * RPC, or {@link #FLAG_ONEWAY} for a one-way RPC.
744 *
745 * @return Return true on a successful call; returning false is generally used to
746 * indicate that you did not understand the transaction code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700748 protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 int flags) throws RemoteException {
750 if (code == INTERFACE_TRANSACTION) {
751 reply.writeString(getInterfaceDescriptor());
752 return true;
753 } else if (code == DUMP_TRANSACTION) {
754 ParcelFileDescriptor fd = data.readFileDescriptor();
755 String[] args = data.readStringArray();
756 if (fd != null) {
757 try {
758 dump(fd.getFileDescriptor(), args);
759 } finally {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700760 IoUtils.closeQuietly(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 }
762 }
Brad Fitzpatrickeb75888e2010-07-26 17:47:45 -0700763 // Write the StrictMode header.
764 if (reply != null) {
765 reply.writeNoException();
766 } else {
767 StrictMode.clearGatheredViolations();
768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 return true;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700770 } else if (code == SHELL_COMMAND_TRANSACTION) {
771 ParcelFileDescriptor in = data.readFileDescriptor();
772 ParcelFileDescriptor out = data.readFileDescriptor();
773 ParcelFileDescriptor err = data.readFileDescriptor();
774 String[] args = data.readStringArray();
Dianne Hackborn354736e2016-08-22 17:00:05 -0700775 ShellCallback shellCallback = ShellCallback.CREATOR.createFromParcel(data);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700776 ResultReceiver resultReceiver = ResultReceiver.CREATOR.createFromParcel(data);
777 try {
778 if (out != null) {
779 shellCommand(in != null ? in.getFileDescriptor() : null,
780 out.getFileDescriptor(),
781 err != null ? err.getFileDescriptor() : out.getFileDescriptor(),
Dianne Hackborn354736e2016-08-22 17:00:05 -0700782 args, shellCallback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700783 }
784 } finally {
785 IoUtils.closeQuietly(in);
786 IoUtils.closeQuietly(out);
787 IoUtils.closeQuietly(err);
788 // Write the StrictMode header.
789 if (reply != null) {
790 reply.writeNoException();
791 } else {
792 StrictMode.clearGatheredViolations();
793 }
794 }
795 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
797 return false;
798 }
799
800 /**
Olivier Gaillardd3d065d2018-07-05 15:07:35 +0100801 * Resolves a transaction code to a human readable name.
802 *
803 * <p>Default implementation is a stub that returns null.
804 * <p>AIDL generated code will return the original method name.
805 *
806 * @param transactionCode The code to resolve.
807 * @return A human readable name.
808 * @hide
809 */
810 public @Nullable String getTransactionName(int transactionCode) {
811 return null;
812 }
813
814 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 * Implemented to call the more convenient version
816 * {@link #dump(FileDescriptor, PrintWriter, String[])}.
817 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700818 public void dump(@NonNull FileDescriptor fd, @Nullable String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 FileOutputStream fout = new FileOutputStream(fd);
Dianne Hackborndb4e33f2013-04-01 17:28:16 -0700820 PrintWriter pw = new FastPrintWriter(fout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700822 doDump(fd, pw, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 } finally {
824 pw.flush();
825 }
826 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700827
828 void doDump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600829 final String disabled = sDumpDisabled;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700830 if (disabled == null) {
831 try {
832 dump(fd, pw, args);
833 } catch (SecurityException e) {
834 pw.println("Security exception: " + e.getMessage());
835 throw e;
836 } catch (Throwable e) {
837 // Unlike usual calls, in this case if an exception gets thrown
838 // back to us we want to print it back in to the dump data, since
839 // that is where the caller expects all interesting information to
840 // go.
841 pw.println();
842 pw.println("Exception occurred while dumping:");
843 e.printStackTrace(pw);
844 }
845 } else {
846 pw.println(sDumpDisabled);
847 }
848 }
849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 /**
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700851 * Like {@link #dump(FileDescriptor, String[])}, but ensures the target
852 * executes asynchronously.
853 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700854 public void dumpAsync(@NonNull final FileDescriptor fd, @Nullable final String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700855 final FileOutputStream fout = new FileOutputStream(fd);
Dianne Hackborndb4e33f2013-04-01 17:28:16 -0700856 final PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700857 Thread thr = new Thread("Binder.dumpAsync") {
858 public void run() {
859 try {
860 dump(fd, pw, args);
861 } finally {
862 pw.flush();
863 }
864 }
865 };
866 thr.start();
867 }
868
869 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 * Print the object's state into the given stream.
Olivier Gaillard9429bf52018-05-15 23:25:03 +0100871 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 * @param fd The raw file descriptor that the dump is being sent to.
873 * @param fout The file to which you should dump your state. This will be
874 * closed for you after you return.
875 * @param args additional arguments to the dump request.
876 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700877 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter fout,
878 @Nullable String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 }
880
881 /**
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700882 * @param in The raw file descriptor that an input data stream can be read from.
883 * @param out The raw file descriptor that normal command messages should be written to.
884 * @param err The raw file descriptor that command error messages should be written to.
885 * @param args Command-line arguments.
Dianne Hackborn354736e2016-08-22 17:00:05 -0700886 * @param callback Callback through which to interact with the invoking shell.
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700887 * @param resultReceiver Called when the command has finished executing, with the result code.
888 * @throws RemoteException
889 * @hide
890 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700891 public void shellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
892 @Nullable FileDescriptor err,
893 @NonNull String[] args, @Nullable ShellCallback callback,
894 @NonNull ResultReceiver resultReceiver) throws RemoteException {
Dianne Hackborn354736e2016-08-22 17:00:05 -0700895 onShellCommand(in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700896 }
897
898 /**
899 * Handle a call to {@link #shellCommand}. The default implementation simply prints
900 * an error message. Override and replace with your own.
Dianne Hackborn2e931f52016-01-28 12:21:17 -0800901 * <p class="caution">Note: no permission checking is done before calling this method; you must
902 * apply any security checks as appropriate for the command being executed.
903 * Consider using {@link ShellCommand} to help in the implementation.</p>
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700904 * @hide
905 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700906 public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
907 @Nullable FileDescriptor err,
908 @NonNull String[] args, @Nullable ShellCallback callback,
909 @NonNull ResultReceiver resultReceiver) throws RemoteException {
Makoto Onuki4c7073b2019-11-04 10:37:15 -0800910
911 // First, convert in, out and err to @NonNull, by redirecting any that's null to /dev/null.
912 try {
913 if (in == null) {
914 in = new FileInputStream("/dev/null").getFD();
915 }
916 if (out == null) {
917 out = new FileOutputStream("/dev/null").getFD();
918 }
919 if (err == null) {
920 err = out;
921 }
922 } catch (IOException e) {
923 PrintWriter pw = new FastPrintWriter(new FileOutputStream(err != null ? err : out));
924 pw.println("Failed to open /dev/null: " + e.getMessage());
925 pw.flush();
926 resultReceiver.send(-1, null);
927 return;
928 }
929 // Also make args @NonNull.
930 if (args == null) {
931 args = new String[0];
932 }
933
934 int result = -1;
Makoto Onukib8472182019-11-13 12:03:22 -0800935 try (ParcelFileDescriptor inPfd = ParcelFileDescriptor.dup(in);
936 ParcelFileDescriptor outPfd = ParcelFileDescriptor.dup(out);
937 ParcelFileDescriptor errPfd = ParcelFileDescriptor.dup(err)) {
938 result = handleShellCommand(inPfd, outPfd, errPfd, args);
939 } catch (IOException e) {
940 PrintWriter pw = new FastPrintWriter(new FileOutputStream(err));
941 pw.println("dup() failed: " + e.getMessage());
942 pw.flush();
Makoto Onuki4c7073b2019-11-04 10:37:15 -0800943 } finally {
944 resultReceiver.send(result, null);
945 }
946 }
947
948 /**
949 * System services can implement this method to implement ADB shell commands.
950 *
951 * TODO More Javadoc.
952 * TODO Add a generic way to define subcommands and their permissions.
953 *
954 * @param in standard input.
955 * @param out standard output.
956 * @param err standard error.
957 * @param args arguments passed to the command. Can be empty. The first argument is typically
958 * a subcommand, such as {@code run} for {@code adb shell cmd jobscheduler run}.
959 *
960 * @hide
961 */
962 // @SystemApi TODO Make it a system API.
Makoto Onukib8472182019-11-13 12:03:22 -0800963 protected int handleShellCommand(@NonNull ParcelFileDescriptor in,
964 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
965 @NonNull String[] args) {
966 FileOutputStream ferr = new FileOutputStream(err.getFileDescriptor());
Makoto Onuki4c7073b2019-11-04 10:37:15 -0800967 PrintWriter pw = new FastPrintWriter(ferr);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700968 pw.println("No shell command implementation.");
969 pw.flush();
Makoto Onuki4c7073b2019-11-04 10:37:15 -0800970 return 0;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700971 }
972
973 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 * Default implementation rewinds the parcels and calls onTransact. On
975 * the remote side, transact calls into the binder to do the IPC.
976 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700977 public final boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 int flags) throws RemoteException {
Joe Onorato43a17652011-04-06 19:22:23 -0700979 if (false) Log.v("Binder", "Transact: " + code + " to " + this);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 if (data != null) {
982 data.setDataPosition(0);
983 }
984 boolean r = onTransact(code, data, reply, flags);
985 if (reply != null) {
986 reply.setDataPosition(0);
987 }
988 return r;
989 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 /**
992 * Local implementation is a no-op.
993 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700994 public void linkToDeath(@NonNull DeathRecipient recipient, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 }
996
997 /**
998 * Local implementation is a no-op.
999 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -07001000 public boolean unlinkToDeath(@NonNull DeathRecipient recipient, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 return true;
1002 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -07001003
Dianne Hackbornfad079d2014-09-26 15:46:24 -07001004 static void checkParcel(IBinder obj, int code, Parcel parcel, String msg) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -07001005 if (CHECK_PARCEL_SIZE && parcel.dataSize() >= 800*1024) {
Dianne Hackborn017c6a22014-09-25 17:41:34 -07001006 // Trying to send > 800k, this is way too much
Dianne Hackbornfad079d2014-09-26 15:46:24 -07001007 StringBuilder sb = new StringBuilder();
1008 sb.append(msg);
1009 sb.append(": on ");
1010 sb.append(obj);
1011 sb.append(" calling ");
1012 sb.append(code);
1013 sb.append(" size ");
1014 sb.append(parcel.dataSize());
1015 sb.append(" (data: ");
1016 parcel.setDataPosition(0);
1017 sb.append(parcel.readInt());
1018 sb.append(", ");
1019 sb.append(parcel.readInt());
1020 sb.append(", ");
1021 sb.append(parcel.readInt());
1022 sb.append(")");
1023 Slog.wtfStack(TAG, sb.toString());
Dianne Hackborn017c6a22014-09-25 17:41:34 -07001024 }
1025 }
1026
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001027 private static native long getNativeBBinderHolder();
1028 private static native long getFinalizer();
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001029
Olivier Gaillard76c231d2018-12-05 12:52:08 +00001030 /**
1031 * By default, we use the calling uid since we can always trust it.
1032 */
1033 private static volatile BinderInternal.WorkSourceProvider sWorkSourceProvider =
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001034 (x) -> Binder.getCallingUid();
Olivier Gaillard76c231d2018-12-05 12:52:08 +00001035
1036 /**
1037 * Sets the work source provider.
1038 *
1039 * <li>The callback is global. Only fast operations should be done to avoid thread
1040 * contentions.
1041 * <li>The callback implementation needs to handle synchronization if needed. The methods on the
1042 * callback can be called concurrently.
1043 * <li>The callback is called on the critical path of the binder transaction so be careful about
1044 * performance.
1045 * <li>Never execute another binder transaction inside the callback.
1046 * @hide
1047 */
1048 public static void setWorkSourceProvider(BinderInternal.WorkSourceProvider workSourceProvider) {
1049 if (workSourceProvider == null) {
1050 throw new IllegalArgumentException("workSourceProvider cannot be null");
1051 }
1052 sWorkSourceProvider = workSourceProvider;
1053 }
1054
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001055 // Entry point from android_util_Binder.cpp's onTransact
Andrei Onea24ec3212019-03-15 17:35:05 +00001056 @UnsupportedAppUsage
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001057 private boolean execTransact(int code, long dataObj, long replyObj,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 int flags) {
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001059 // At that point, the parcel request headers haven't been parsed so we do not know what
1060 // WorkSource the caller has set. Use calling uid as the default.
1061 final int callingUid = Binder.getCallingUid();
1062 final long origWorkSource = ThreadLocalWorkSource.setUid(callingUid);
Olivier Gaillard180f91f2018-12-05 15:20:02 +00001063 try {
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001064 return execTransactInternal(code, dataObj, replyObj, flags, callingUid);
Olivier Gaillard180f91f2018-12-05 15:20:02 +00001065 } finally {
1066 ThreadLocalWorkSource.restore(origWorkSource);
1067 }
1068 }
1069
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001070 private boolean execTransactInternal(int code, long dataObj, long replyObj, int flags,
1071 int callingUid) {
Olivier Gaillard289ba402018-07-24 18:50:13 +01001072 // Make sure the observer won't change while processing a transaction.
1073 final BinderInternal.Observer observer = sObserver;
1074 final CallSession callSession =
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001075 observer != null ? observer.callStarted(this, code, UNSET_WORKSOURCE) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 Parcel data = Parcel.obtain(dataObj);
1077 Parcel reply = Parcel.obtain(replyObj);
1078 // theoretically, we should call transact, which will call onTransact,
1079 // but all that does is rewind it, and we just got these from an IPC,
1080 // so we'll just call it directly.
1081 boolean res;
Igor Murashkin7eb6cfe2013-08-16 14:07:11 -07001082 // Log any exceptions as warnings, don't silently suppress them.
1083 // If the call was FLAG_ONEWAY then these exceptions disappear into the ether.
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001084 final boolean tracingEnabled = Binder.isTracingEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 try {
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001086 if (tracingEnabled) {
Olivier Gaillard53f645062018-10-12 15:41:50 +01001087 final String transactionName = getTransactionName(code);
1088 Trace.traceBegin(Trace.TRACE_TAG_ALWAYS, getClass().getName() + ":"
1089 + (transactionName != null ? transactionName : code));
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001090 }
Philip P. Moltmann2b08aaf2019-06-10 08:49:11 -07001091
1092 if ((flags & FLAG_COLLECT_NOTED_APP_OPS) != 0) {
1093 AppOpsManager.startNotedAppOpsCollection(callingUid);
1094 try {
1095 res = onTransact(code, data, reply, flags);
1096 } finally {
1097 AppOpsManager.finishNotedAppOpsCollection();
1098 }
1099 } else {
1100 res = onTransact(code, data, reply, flags);
1101 }
Makoto Onukif9b941f2016-03-10 17:19:08 -08001102 } catch (RemoteException|RuntimeException e) {
Olivier Gaillard289ba402018-07-24 18:50:13 +01001103 if (observer != null) {
1104 observer.callThrewException(callSession, e);
1105 }
Makoto Onukif9b941f2016-03-10 17:19:08 -08001106 if (LOG_RUNTIME_EXCEPTION) {
Igor Murashkin7eb6cfe2013-08-16 14:07:11 -07001107 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
Makoto Onukif9b941f2016-03-10 17:19:08 -08001108 }
1109 if ((flags & FLAG_ONEWAY) != 0) {
1110 if (e instanceof RemoteException) {
1111 Log.w(TAG, "Binder call failed.", e);
1112 } else {
1113 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
1114 }
Dianne Hackbornce92b0d2014-09-30 11:28:18 -07001115 } else {
Michael Wachenschwanz06041db2019-05-15 22:58:15 -07001116 // Clear the parcel before writing the exception
1117 reply.setDataSize(0);
Dianne Hackbornce92b0d2014-09-30 11:28:18 -07001118 reply.setDataPosition(0);
1119 reply.writeException(e);
Igor Murashkin7eb6cfe2013-08-16 14:07:11 -07001120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 res = true;
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001122 } finally {
1123 if (tracingEnabled) {
1124 Trace.traceEnd(Trace.TRACE_TAG_ALWAYS);
1125 }
Olivier Gaillard0e4d61e2018-12-05 15:30:35 +00001126 if (observer != null) {
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001127 // The parcel RPC headers have been called during onTransact so we can now access
1128 // the worksource uid from the parcel.
1129 final int workSourceUid = sWorkSourceProvider.resolveWorkSourceUid(
1130 data.readCallingWorkSourceUid());
Olivier Gaillard76c231d2018-12-05 12:52:08 +00001131 observer.callEnded(callSession, data.dataSize(), reply.dataSize(), workSourceUid);
Olivier Gaillard0e4d61e2018-12-05 15:30:35 +00001132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
Dianne Hackbornfad079d2014-09-26 15:46:24 -07001134 checkParcel(this, code, reply, "Unreasonably large binder reply buffer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 reply.recycle();
1136 data.recycle();
Dianne Hackbornce92b0d2014-09-30 11:28:18 -07001137
1138 // Just in case -- we are done with the IPC, so there should be no more strict
1139 // mode violations that have gathered for this thread. Either they have been
1140 // parceled and are now in transport off to the caller, or we are returning back
1141 // to the main transaction loop to wait for another incoming transaction. Either
1142 // way, strict mode begone!
1143 StrictMode.clearGatheredViolations();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 return res;
1145 }
Jon Spivack9e45fde2019-10-09 17:23:00 -07001146
1147 /**
1148 * Returns the specified service from servicemanager. If the service is not running,
1149 * servicemanager will attempt to start it, and this function will wait for it to be ready.
1150 * Returns nullptr only if there are permission problems or fatal errors.
1151 * @hide
1152 */
1153 public static final native @Nullable IBinder waitForService(@NonNull String serviceName)
1154 throws RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155}