blob: 2e6d2cc4a66ab3284676337b096b4e2a4d061491 [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;
Eugene Suslacf00ade2017-04-10 11:51:58 -070023import android.util.ExceptionUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.util.Log;
Dianne Hackborn017c6a22014-09-25 17:41:34 -070025import android.util.Slog;
Eugene Suslacf00ade2017-04-10 11:51:58 -070026
Michael Wachenschwanz58ac2182018-01-30 15:11:19 -080027import com.android.internal.os.BinderInternal;
Olivier Gaillard289ba402018-07-24 18:50:13 +010028import com.android.internal.os.BinderInternal.CallSession;
Dianne Hackborndb4e33f2013-04-01 17:28:16 -070029import com.android.internal.util.FastPrintWriter;
Eugene Suslacf00ade2017-04-10 11:51:58 -070030import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
31import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
32
Olivier Gaillarde4ff3972018-08-16 14:01:58 +010033import dalvik.annotation.optimization.CriticalNative;
34
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070035import libcore.io.IoUtils;
Hans Boehm5e5b13f2017-09-28 18:16:50 -070036import libcore.util.NativeAllocationRegistry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037
38import java.io.FileDescriptor;
39import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import java.io.PrintWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import java.lang.reflect.Modifier;
42
43/**
44 * Base class for a remotable object, the core part of a lightweight
45 * remote procedure call mechanism defined by {@link IBinder}.
46 * This class is an implementation of IBinder that provides
Dianne Hackbornab4a81b2014-10-09 17:59:38 -070047 * standard local implementation of such an object.
48 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049 * <p>Most developers will not implement this class directly, instead using the
Scott Main40eee612012-08-06 17:48:37 -070050 * <a href="{@docRoot}guide/components/aidl.html">aidl</a> tool to describe the desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051 * interface, having it generate the appropriate Binder subclass. You can,
52 * however, derive directly from Binder to implement your own custom RPC
53 * protocol or simply instantiate a raw Binder object directly to use as a
54 * token that can be shared across processes.
Dianne Hackbornab4a81b2014-10-09 17:59:38 -070055 *
56 * <p>This class is just a basic IPC primitive; it has no impact on an application's
57 * lifecycle, and is valid only as long as the process that created it continues to run.
58 * To use this correctly, you must be doing so within the context of a top-level
59 * application component (a {@link android.app.Service}, {@link android.app.Activity},
60 * or {@link android.content.ContentProvider}) that lets the system know your process
61 * should remain running.</p>
62 *
63 * <p>You must keep in mind the situations in which your process
64 * could go away, and thus require that you later re-create a new Binder and re-attach
65 * it when the process starts again. For example, if you are using this within an
66 * {@link android.app.Activity}, your activity's process may be killed any time the
67 * activity is not started; if the activity is later re-created you will need to
68 * create a new Binder and hand it back to the correct place again; you need to be
69 * aware that your process may be started for another reason (for example to receive
70 * a broadcast) that will not involve re-creating the activity and thus run its code
71 * to create a new Binder.</p>
72 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 * @see IBinder
74 */
75public class Binder implements IBinder {
76 /*
77 * Set this flag to true to detect anonymous, local or member classes
78 * that extend this Binder class and that are not static. These kind
79 * of classes can potentially create leaks.
80 */
81 private static final boolean FIND_POTENTIAL_LEAKS = false;
Jeff Sharkeyf5299f12017-03-17 10:25:07 -060082 /** @hide */
83 public static final boolean CHECK_PARCEL_SIZE = false;
Dianne Hackborn017c6a22014-09-25 17:41:34 -070084 static final String TAG = "Binder";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
Makoto Onukif9b941f2016-03-10 17:19:08 -080086 /** @hide */
87 public static boolean LOG_RUNTIME_EXCEPTION = false; // DO NOT SUBMIT WITH TRUE
88
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -070089 /**
Olivier Gaillardc17d2802018-11-19 17:08:17 +000090 * Value to represents that a calling work source is not set.
91 *
92 * This constatnt needs to be kept in sync with IPCThreadState::kUnsetWorkSource.
93 *
94 * @hide
95 */
96 public static final int UNSET_WORKSOURCE = -1;
97
98 /**
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -070099 * Control whether dump() calls are allowed.
100 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600101 private static volatile String sDumpDisabled = null;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700102
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400103 /**
104 * Global transaction tracker instance for this process.
105 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600106 private static volatile TransactionTracker sTransactionTracker = null;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400107
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700108 /**
Olivier Gaillard289ba402018-07-24 18:50:13 +0100109 * Global observer for this process.
110 */
111 private static BinderInternal.Observer sObserver = null;
112
113 /**
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700114 * Guestimate of native memory associated with a Binder.
115 */
116 private static final int NATIVE_ALLOCATION_SIZE = 500;
117
118 private static native long getNativeFinalizer();
119
120 // Use a Holder to allow static initialization of Binder in the boot image, and
121 // possibly to avoid some initialization ordering issues.
122 private static class NoImagePreloadHolder {
123 public static final NativeAllocationRegistry sRegistry = new NativeAllocationRegistry(
124 Binder.class.getClassLoader(), getNativeFinalizer(), NATIVE_ALLOCATION_SIZE);
125 }
126
Olivier Gaillard289ba402018-07-24 18:50:13 +0100127
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400128 // Transaction tracking code.
129
130 /**
131 * Flag indicating whether we should be tracing transact calls.
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400132 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600133 private static volatile boolean sTracingEnabled = false;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400134
135 /**
136 * Enable Binder IPC tracing.
137 *
138 * @hide
139 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600140 public static void enableTracing() {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400141 sTracingEnabled = true;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600142 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400143
144 /**
145 * Disable Binder IPC tracing.
146 *
147 * @hide
148 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600149 public static void disableTracing() {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400150 sTracingEnabled = false;
151 }
152
153 /**
154 * Check if binder transaction tracing is enabled.
155 *
156 * @hide
157 */
158 public static boolean isTracingEnabled() {
159 return sTracingEnabled;
160 }
161
162 /**
163 * Get the binder transaction tracker for this process.
164 *
165 * @hide
166 */
167 public synchronized static TransactionTracker getTransactionTracker() {
168 if (sTransactionTracker == null)
169 sTransactionTracker = new TransactionTracker();
170 return sTransactionTracker;
171 }
172
Olivier Gaillard289ba402018-07-24 18:50:13 +0100173 /**
174 * Get the binder transaction observer for this process.
175 *
176 * @hide
177 */
178 public static void setObserver(@Nullable BinderInternal.Observer observer) {
179 sObserver = observer;
180 }
181
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600182 /** {@hide} */
183 static volatile boolean sWarnOnBlocking = false;
184
185 /**
186 * Warn if any blocking binder transactions are made out from this process.
187 * This is typically only useful for the system process, to prevent it from
188 * blocking on calls to external untrusted code. Instead, all outgoing calls
189 * that require a result must be sent as {@link IBinder#FLAG_ONEWAY} calls
190 * which deliver results through a callback interface.
191 *
192 * @hide
193 */
194 public static void setWarnOnBlocking(boolean warnOnBlocking) {
195 sWarnOnBlocking = warnOnBlocking;
196 }
197
198 /**
199 * Allow blocking calls on the given interface, overriding the requested
200 * value of {@link #setWarnOnBlocking(boolean)}.
201 * <p>
202 * This should only be rarely called when you are <em>absolutely sure</em>
203 * the remote interface is a built-in system component that can never be
204 * upgraded. In particular, this <em>must never</em> be called for
205 * interfaces hosted by package that could be upgraded or replaced,
206 * otherwise you risk system instability if that remote interface wedges.
207 *
208 * @hide
209 */
210 public static IBinder allowBlocking(IBinder binder) {
211 try {
212 if (binder instanceof BinderProxy) {
213 ((BinderProxy) binder).mWarnOnBlocking = false;
Dianne Hackbornc81983a2017-10-20 16:16:32 -0700214 } else if (binder != null && binder.getInterfaceDescriptor() != null
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600215 && binder.queryLocalInterface(binder.getInterfaceDescriptor()) == null) {
216 Log.w(TAG, "Unable to allow blocking on interface " + binder);
217 }
218 } catch (RemoteException ignored) {
219 }
220 return binder;
221 }
222
223 /**
Jeff Sharkey59189482017-11-09 18:13:43 -0700224 * Reset the given interface back to the default blocking behavior,
225 * reverting any changes made by {@link #allowBlocking(IBinder)}.
226 *
227 * @hide
228 */
229 public static IBinder defaultBlocking(IBinder binder) {
230 if (binder instanceof BinderProxy) {
231 ((BinderProxy) binder).mWarnOnBlocking = sWarnOnBlocking;
232 }
233 return binder;
234 }
235
236 /**
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600237 * Inherit the current {@link #allowBlocking(IBinder)} value from one given
238 * interface to another.
239 *
240 * @hide
241 */
242 public static void copyAllowBlocking(IBinder fromBinder, IBinder toBinder) {
243 if (fromBinder instanceof BinderProxy && toBinder instanceof BinderProxy) {
244 ((BinderProxy) toBinder).mWarnOnBlocking = ((BinderProxy) fromBinder).mWarnOnBlocking;
245 }
246 }
247
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700248 /**
249 * Raw native pointer to JavaBBinderHolder object. Owned by this Java object. Not null.
250 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000251 @UnsupportedAppUsage
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700252 private final long mObject;
253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 private IInterface mOwner;
255 private String mDescriptor;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 /**
258 * Return the ID of the process that sent you the current transaction
259 * that is being processed. This pid can be used with higher-level
260 * system services to determine its identity and check permissions.
261 * If the current thread is not currently executing an incoming transaction,
262 * then its own pid is returned.
263 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100264 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 public static final native int getCallingPid();
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 /**
Dianne Hackborn74ee8652012-09-07 18:33:18 -0700268 * Return the Linux uid assigned to the process that sent you the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 * current transaction that is being processed. This uid can be used with
270 * higher-level system services to determine its identity and check
271 * permissions. If the current thread is not currently executing an
272 * incoming transaction, then its own uid is returned.
273 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100274 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 public static final native int getCallingUid();
Amith Yamasani742a6712011-05-04 14:49:28 -0700276
277 /**
Nikita Ioffea929cf02019-01-03 13:35:22 +0000278 * Returns {@code true} if the current thread is currently executing an
279 * incoming transaction.
280 *
281 * @hide
282 */
283 @CriticalNative
284 public static final native boolean isHandlingTransaction();
285
286 /**
287 * Return the Linux uid assigned to the process that sent the transaction
288 * currently being processed.
289 *
290 * @throws IllegalStateException if the current thread is not currently
291 * executing an incoming transaction.
292 */
293 public static final int getCallingUidOrThrow() {
294 if (!isHandlingTransaction()) {
295 throw new IllegalStateException(
296 "Thread is not in a binder transcation");
297 }
298 return getCallingUid();
299 }
300
301 /**
Dianne Hackborn74ee8652012-09-07 18:33:18 -0700302 * Return the UserHandle assigned to the process that sent you the
303 * current transaction that is being processed. This is the user
304 * of the caller. It is distinct from {@link #getCallingUid()} in that a
305 * particular user will have multiple distinct apps running under it each
306 * with their own uid. If the current thread is not currently executing an
307 * incoming transaction, then its own UserHandle is returned.
308 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700309 public static final @NonNull UserHandle getCallingUserHandle() {
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700310 return UserHandle.of(UserHandle.getUserId(getCallingUid()));
Dianne Hackborn74ee8652012-09-07 18:33:18 -0700311 }
312
313 /**
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700314 * Reset the identity of the incoming IPC on the current thread. This can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 * be useful if, while handling an incoming call, you will be calling
316 * on interfaces of other objects that may be local to your process and
317 * need to do permission checks on the calls coming into them (so they
318 * will check the permission of your own local process, and not whatever
319 * process originally called you).
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700320 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 * @return Returns an opaque token that can be used to restore the
322 * original calling identity by passing it to
323 * {@link #restoreCallingIdentity(long)}.
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700324 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 * @see #getCallingPid()
326 * @see #getCallingUid()
327 * @see #restoreCallingIdentity(long)
328 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100329 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 public static final native long clearCallingIdentity();
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 /**
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700333 * Restore the identity of the incoming IPC on the current thread
334 * back to a previously identity that was returned by {@link
335 * #clearCallingIdentity}.
336 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 * @param token The opaque token that was previously returned by
338 * {@link #clearCallingIdentity}.
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700339 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 * @see #clearCallingIdentity
341 */
342 public static final native void restoreCallingIdentity(long token);
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700343
344 /**
Eugene Susla6a7006a2017-03-13 12:57:58 -0700345 * Convenience method for running the provided action enclosed in
346 * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity}
347 *
Eugene Suslacf00ade2017-04-10 11:51:58 -0700348 * Any exception thrown by the given action will be caught and rethrown after the call to
349 * {@link #restoreCallingIdentity}
350 *
Eugene Susla6a7006a2017-03-13 12:57:58 -0700351 * @hide
352 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700353 public static final void withCleanCallingIdentity(@NonNull ThrowingRunnable action) {
Eugene Susla6a7006a2017-03-13 12:57:58 -0700354 long callingIdentity = clearCallingIdentity();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700355 Throwable throwableToPropagate = null;
Eugene Susla6a7006a2017-03-13 12:57:58 -0700356 try {
Eugene Susla2f5ee712017-06-23 17:25:24 -0700357 action.runOrThrow();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700358 } catch (Throwable throwable) {
359 throwableToPropagate = throwable;
Eugene Susla6a7006a2017-03-13 12:57:58 -0700360 } finally {
361 restoreCallingIdentity(callingIdentity);
Eugene Suslacf00ade2017-04-10 11:51:58 -0700362 if (throwableToPropagate != null) {
363 throw ExceptionUtils.propagate(throwableToPropagate);
364 }
Eugene Susla6a7006a2017-03-13 12:57:58 -0700365 }
366 }
367
368 /**
369 * Convenience method for running the provided action enclosed in
370 * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity} returning the result
371 *
Eugene Suslacf00ade2017-04-10 11:51:58 -0700372 * Any exception thrown by the given action will be caught and rethrown after the call to
373 * {@link #restoreCallingIdentity}
374 *
Eugene Susla6a7006a2017-03-13 12:57:58 -0700375 * @hide
376 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700377 public static final <T> T withCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) {
Eugene Susla6a7006a2017-03-13 12:57:58 -0700378 long callingIdentity = clearCallingIdentity();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700379 Throwable throwableToPropagate = null;
Eugene Susla6a7006a2017-03-13 12:57:58 -0700380 try {
Eugene Susla2f5ee712017-06-23 17:25:24 -0700381 return action.getOrThrow();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700382 } catch (Throwable throwable) {
383 throwableToPropagate = throwable;
384 return null; // overridden by throwing in finally block
Eugene Susla6a7006a2017-03-13 12:57:58 -0700385 } finally {
386 restoreCallingIdentity(callingIdentity);
Eugene Suslacf00ade2017-04-10 11:51:58 -0700387 if (throwableToPropagate != null) {
388 throw ExceptionUtils.propagate(throwableToPropagate);
389 }
Eugene Susla6a7006a2017-03-13 12:57:58 -0700390 }
391 }
392
393 /**
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700394 * Sets the native thread-local StrictMode policy mask.
395 *
396 * <p>The StrictMode settings are kept in two places: a Java-level
397 * threadlocal for libcore/Dalvik, and a native threadlocal (set
398 * here) for propagation via Binder calls. This is a little
399 * unfortunate, but necessary to break otherwise more unfortunate
400 * dependencies either of Dalvik on Android, or Android
401 * native-only code on Dalvik.
402 *
403 * @see StrictMode
404 * @hide
405 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100406 @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700407 public static final native void setThreadStrictModePolicy(int policyMask);
408
409 /**
410 * Gets the current native thread-local StrictMode policy mask.
411 *
412 * @see #setThreadStrictModePolicy
413 * @hide
414 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100415 @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700416 public static final native int getThreadStrictModePolicy();
417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 /**
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100419 * Sets the work source for this thread.
420 *
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000421 * <p>All the following binder calls on this thread will use the provided work source. If this
422 * is called during an on-going binder transaction, all the following binder calls will use the
423 * work source until the end of the transaction.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100424 *
425 * <p>The concept of worksource is similar to {@link WorkSource}. However, for performance
426 * reasons, we only support one UID. This UID represents the original user responsible for the
427 * binder calls.
428 *
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000429 * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after setting the
430 * worksource.
431 *
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100432 * <p>A typical use case would be
433 * <pre>
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000434 * long token = Binder.setCallingWorkSourceUid(uid);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100435 * try {
436 * // Call an API.
437 * } finally {
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000438 * Binder.restoreCallingWorkSource(token);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100439 * }
440 * </pre>
441 *
Olivier Gaillard1d724582018-11-19 14:35:37 +0000442 * <p>The work source will be propagated for future outgoing binder transactions
443 * executed on this thread.
444 *
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100445 * @param workSource The original UID responsible for the binder call.
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000446 * @return token to restore original work source.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100447 **/
448 @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000449 public static final native long setCallingWorkSourceUid(int workSource);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100450
451 /**
452 * Returns the work source set by the caller.
453 *
454 * Unlike {@link Binder#getCallingUid()}, this result of this method cannot be trusted. The
Olivier Gaillardf84f4f82019-04-03 11:32:12 +0100455 * 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 +0100456 * uid.
457 *
458 * @return The original UID responsible for the binder transaction.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100459 */
460 @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000461 public static final native int getCallingWorkSourceUid();
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100462
463 /**
464 * Clears the work source on this thread.
465 *
Olivier Gaillard1d724582018-11-19 14:35:37 +0000466 * <p>The work source will be propagated for future outgoing binder transactions
467 * executed on this thread.
468 *
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000469 * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after clearing the
470 * worksource.
471 *
472 * <p>A typical use case would be
473 * <pre>
474 * long token = Binder.clearCallingWorkSource();
475 * try {
476 * // Call an API.
477 * } finally {
478 * Binder.restoreCallingWorkSource(token);
479 * }
480 * </pre>
481 *
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000482 * @return token to restore original work source.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100483 **/
484 @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000485 public static final native long clearCallingWorkSource();
486
487 /**
488 * Restores the work source on this thread using a token returned by
489 * {@link #setCallingWorkSourceUid(int) or {@link clearCallingWorkSource()}.
490 *
491 * <p>A typical use case would be
492 * <pre>
493 * long token = Binder.setCallingWorkSourceUid(uid);
494 * try {
495 * // Call an API.
496 * } finally {
497 * Binder.restoreCallingWorkSource(token);
498 * }
499 * </pre>
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000500 **/
501 @CriticalNative
502 public static final native void restoreCallingWorkSource(long token);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100503
504 /**
Steven Morelandd587a552019-11-27 18:15:33 -0800505 * Mark as being built with VINTF-level stability promise. This API should
506 * only ever be invoked by the build system. It means that the interface
507 * represented by this binder is guaranteed to be kept stable for several
508 * years, and the build system also keeps snapshots of these APIs and
509 * invokes the AIDL compiler to make sure that these snapshots are
510 * backwards compatible. Instead of using this API, use an @VintfStability
511 * interface.
512 *
513 * @hide
514 */
515 public final native void markVintfStability();
516
517 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 * Flush any Binder commands pending in the current thread to the kernel
519 * driver. This can be
520 * useful to call before performing an operation that may block for a long
521 * time, to ensure that any pending object references have been released
522 * in order to prevent the process from holding on to objects longer than
523 * it needs to.
524 */
525 public static final native void flushPendingCommands();
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 /**
528 * Add the calling thread to the IPC thread pool. This function does
529 * not return until the current process is exiting.
530 */
Andreas Gampeacd19872018-03-16 15:58:24 -0700531 public static final void joinThreadPool() {
532 BinderInternal.joinThreadPool();
533 }
Jeff Brown1951ce82013-04-04 22:45:12 -0700534
535 /**
536 * Returns true if the specified interface is a proxy.
537 * @hide
538 */
539 public static final boolean isProxy(IInterface iface) {
540 return iface.asBinder() != iface;
541 }
542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 /**
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700544 * Call blocks until the number of executing binder threads is less
545 * than the maximum number of binder threads allowed for this process.
Wale Ogunwale8d906342015-04-15 09:10:03 -0700546 * @hide
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700547 */
548 public static final native void blockUntilThreadAvailable();
549
550 /**
Martijn Coenend2c86ab2018-07-17 16:30:40 +0200551 * Default constructor just initializes the object.
552 *
553 * If you're creating a Binder token (a Binder object without an attached interface),
554 * you should use {@link #Binder(String)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 */
556 public Binder() {
Martijn Coenend2c86ab2018-07-17 16:30:40 +0200557 this(null);
558 }
559
560 /**
561 * Constructor for creating a raw Binder object (token) along with a descriptor.
562 *
563 * The descriptor of binder objects usually specifies the interface they are implementing.
564 * In case of binder tokens, no interface is implemented, and the descriptor can be used
565 * as a sort of tag to help identify the binder token. This will help identify remote
566 * references to these objects more easily when debugging.
567 *
568 * @param descriptor Used to identify the creator of this token, for example the class name.
569 * Instead of creating multiple tokens with the same descriptor, consider adding a suffix to
570 * help identify them.
571 */
572 public Binder(@Nullable String descriptor) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700573 mObject = getNativeBBinderHolder();
574 NoImagePreloadHolder.sRegistry.registerNativeAllocation(this, mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575
576 if (FIND_POTENTIAL_LEAKS) {
577 final Class<? extends Binder> klass = getClass();
578 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
579 (klass.getModifiers() & Modifier.STATIC) == 0) {
580 Log.w(TAG, "The following Binder class should be static or leaks might occur: " +
581 klass.getCanonicalName());
582 }
583 }
Martijn Coenend2c86ab2018-07-17 16:30:40 +0200584 mDescriptor = descriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 /**
588 * Convenience method for associating a specific interface with the Binder.
589 * After calling, queryLocalInterface() will be implemented for you
590 * to return the given owner IInterface when the corresponding
591 * descriptor is requested.
592 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700593 public void attachInterface(@Nullable IInterface owner, @Nullable String descriptor) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 mOwner = owner;
595 mDescriptor = descriptor;
596 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 /**
599 * Default implementation returns an empty interface name.
600 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700601 public @Nullable String getInterfaceDescriptor() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 return mDescriptor;
603 }
604
605 /**
606 * Default implementation always returns true -- if you got here,
607 * the object is alive.
608 */
609 public boolean pingBinder() {
610 return true;
611 }
612
613 /**
614 * {@inheritDoc}
615 *
616 * Note that if you're calling on a local binder, this always returns true
617 * because your process is alive if you're calling it.
618 */
619 public boolean isBinderAlive() {
620 return true;
621 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 /**
624 * Use information supplied to attachInterface() to return the
625 * associated IInterface if it matches the requested
626 * descriptor.
627 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700628 public @Nullable IInterface queryLocalInterface(@NonNull String descriptor) {
Dianne Hackbornc81983a2017-10-20 16:16:32 -0700629 if (mDescriptor != null && mDescriptor.equals(descriptor)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 return mOwner;
631 }
632 return null;
633 }
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700634
635 /**
636 * Control disabling of dump calls in this process. This is used by the system
637 * process watchdog to disable incoming dump calls while it has detecting the system
638 * is hung and is reporting that back to the activity controller. This is to
639 * prevent the controller from getting hung up on bug reports at this point.
640 * @hide
641 *
642 * @param msg The message to show instead of the dump; if null, dumps are
643 * re-enabled.
644 */
645 public static void setDumpDisabled(String msg) {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600646 sDumpDisabled = msg;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700647 }
648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 /**
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100650 * Listener to be notified about each proxy-side binder call.
651 *
652 * See {@link setProxyTransactListener}.
653 * @hide
654 */
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000655 @SystemApi
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100656 public interface ProxyTransactListener {
657 /**
658 * Called before onTransact.
659 *
660 * @return an object that will be passed back to #onTransactEnded (or null).
661 */
Olivier Gaillard5a73a512019-03-05 16:32:35 +0000662 @Nullable
663 Object onTransactStarted(@NonNull IBinder binder, int transactionCode);
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100664
665 /**
666 * Called after onTranact (even when an exception is thrown).
667 *
668 * @param session The object return by #onTransactStarted.
669 */
670 void onTransactEnded(@Nullable Object session);
671 }
672
673 /**
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100674 * Propagates the work source to binder calls executed by the system server.
675 *
676 * <li>By default, this listener will propagate the worksource if the outgoing call happens on
677 * the same thread as the incoming binder call.
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000678 * <li>Custom attribution can be done by calling {@link ThreadLocalWorkSource#setUid(int)}.
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100679 * @hide
680 */
681 public static class PropagateWorkSourceTransactListener implements ProxyTransactListener {
682 @Override
683 public Object onTransactStarted(IBinder binder, int transactionCode) {
684 // Note that {@link Binder#getCallingUid()} is already set to the UID of the current
685 // process when this method is called.
686 //
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000687 // We use ThreadLocalWorkSource instead. It also allows feature owners to set
688 // {@link ThreadLocalWorkSource#set(int) manually to attribute resources to a UID.
689 int uid = ThreadLocalWorkSource.getUid();
690 if (uid != ThreadLocalWorkSource.UID_NONE) {
691 return Binder.setCallingWorkSourceUid(uid);
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100692 }
693 return null;
694 }
695
696 @Override
697 public void onTransactEnded(Object session) {
698 if (session != null) {
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000699 long token = (long) session;
700 Binder.restoreCallingWorkSource(token);
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100701 }
702 }
703 }
704
705 /**
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100706 * Sets a listener for the transact method on the proxy-side.
707 *
708 * <li>The listener is global. Only fast operations should be done to avoid thread
709 * contentions.
710 * <li>The listener implementation needs to handle synchronization if needed. The methods on the
711 * listener can be called concurrently.
712 * <li>Listener set will be used for new transactions. On-going transaction will still use the
713 * previous listener (if already set).
714 * <li>The listener is called on the critical path of the binder transaction so be careful about
715 * performance.
716 * <li>Never execute another binder transaction inside the listener.
717 * @hide
718 */
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000719 @SystemApi
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100720 public static void setProxyTransactListener(@Nullable ProxyTransactListener listener) {
721 BinderProxy.setTransactListener(listener);
722 }
723
724 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 * Default implementation is a stub that returns false. You will want
726 * to override this to do the appropriate unmarshalling of transactions.
727 *
728 * <p>If you want to call this, call transact().
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700729 *
Dianne Hackborn18482ae2017-08-01 17:41:00 -0700730 * <p>Implementations that are returning a result should generally use
731 * {@link Parcel#writeNoException() Parcel.writeNoException} and
732 * {@link Parcel#writeException(Exception) Parcel.writeException} to propagate
733 * exceptions back to the caller.</p>
734 *
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700735 * @param code The action to perform. This should
736 * be a number between {@link #FIRST_CALL_TRANSACTION} and
737 * {@link #LAST_CALL_TRANSACTION}.
738 * @param data Marshalled data being received from the caller.
739 * @param reply If the caller is expecting a result back, it should be marshalled
740 * in to here.
741 * @param flags Additional operation flags. Either 0 for a normal
742 * RPC, or {@link #FLAG_ONEWAY} for a one-way RPC.
743 *
744 * @return Return true on a successful call; returning false is generally used to
745 * indicate that you did not understand the transaction code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700747 protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 int flags) throws RemoteException {
749 if (code == INTERFACE_TRANSACTION) {
750 reply.writeString(getInterfaceDescriptor());
751 return true;
752 } else if (code == DUMP_TRANSACTION) {
753 ParcelFileDescriptor fd = data.readFileDescriptor();
754 String[] args = data.readStringArray();
755 if (fd != null) {
756 try {
757 dump(fd.getFileDescriptor(), args);
758 } finally {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700759 IoUtils.closeQuietly(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 }
761 }
Brad Fitzpatrickeb75888e2010-07-26 17:47:45 -0700762 // Write the StrictMode header.
763 if (reply != null) {
764 reply.writeNoException();
765 } else {
766 StrictMode.clearGatheredViolations();
767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 return true;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700769 } else if (code == SHELL_COMMAND_TRANSACTION) {
770 ParcelFileDescriptor in = data.readFileDescriptor();
771 ParcelFileDescriptor out = data.readFileDescriptor();
772 ParcelFileDescriptor err = data.readFileDescriptor();
773 String[] args = data.readStringArray();
Dianne Hackborn354736e2016-08-22 17:00:05 -0700774 ShellCallback shellCallback = ShellCallback.CREATOR.createFromParcel(data);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700775 ResultReceiver resultReceiver = ResultReceiver.CREATOR.createFromParcel(data);
776 try {
777 if (out != null) {
778 shellCommand(in != null ? in.getFileDescriptor() : null,
779 out.getFileDescriptor(),
780 err != null ? err.getFileDescriptor() : out.getFileDescriptor(),
Dianne Hackborn354736e2016-08-22 17:00:05 -0700781 args, shellCallback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700782 }
783 } finally {
784 IoUtils.closeQuietly(in);
785 IoUtils.closeQuietly(out);
786 IoUtils.closeQuietly(err);
787 // Write the StrictMode header.
788 if (reply != null) {
789 reply.writeNoException();
790 } else {
791 StrictMode.clearGatheredViolations();
792 }
793 }
794 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 }
796 return false;
797 }
798
799 /**
Olivier Gaillardd3d065d2018-07-05 15:07:35 +0100800 * Resolves a transaction code to a human readable name.
801 *
802 * <p>Default implementation is a stub that returns null.
803 * <p>AIDL generated code will return the original method name.
804 *
805 * @param transactionCode The code to resolve.
806 * @return A human readable name.
807 * @hide
808 */
809 public @Nullable String getTransactionName(int transactionCode) {
810 return null;
811 }
812
813 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 * Implemented to call the more convenient version
815 * {@link #dump(FileDescriptor, PrintWriter, String[])}.
816 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700817 public void dump(@NonNull FileDescriptor fd, @Nullable String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 FileOutputStream fout = new FileOutputStream(fd);
Dianne Hackborndb4e33f2013-04-01 17:28:16 -0700819 PrintWriter pw = new FastPrintWriter(fout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700821 doDump(fd, pw, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 } finally {
823 pw.flush();
824 }
825 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700826
827 void doDump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600828 final String disabled = sDumpDisabled;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700829 if (disabled == null) {
830 try {
831 dump(fd, pw, args);
832 } catch (SecurityException e) {
833 pw.println("Security exception: " + e.getMessage());
834 throw e;
835 } catch (Throwable e) {
836 // Unlike usual calls, in this case if an exception gets thrown
837 // back to us we want to print it back in to the dump data, since
838 // that is where the caller expects all interesting information to
839 // go.
840 pw.println();
841 pw.println("Exception occurred while dumping:");
842 e.printStackTrace(pw);
843 }
844 } else {
845 pw.println(sDumpDisabled);
846 }
847 }
848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 /**
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700850 * Like {@link #dump(FileDescriptor, String[])}, but ensures the target
851 * executes asynchronously.
852 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700853 public void dumpAsync(@NonNull final FileDescriptor fd, @Nullable final String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700854 final FileOutputStream fout = new FileOutputStream(fd);
Dianne Hackborndb4e33f2013-04-01 17:28:16 -0700855 final PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700856 Thread thr = new Thread("Binder.dumpAsync") {
857 public void run() {
858 try {
859 dump(fd, pw, args);
860 } finally {
861 pw.flush();
862 }
863 }
864 };
865 thr.start();
866 }
867
868 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 * Print the object's state into the given stream.
Olivier Gaillard9429bf52018-05-15 23:25:03 +0100870 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 * @param fd The raw file descriptor that the dump is being sent to.
872 * @param fout The file to which you should dump your state. This will be
873 * closed for you after you return.
874 * @param args additional arguments to the dump request.
875 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700876 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter fout,
877 @Nullable String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
879
880 /**
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700881 * @param in The raw file descriptor that an input data stream can be read from.
882 * @param out The raw file descriptor that normal command messages should be written to.
883 * @param err The raw file descriptor that command error messages should be written to.
884 * @param args Command-line arguments.
Dianne Hackborn354736e2016-08-22 17:00:05 -0700885 * @param callback Callback through which to interact with the invoking shell.
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700886 * @param resultReceiver Called when the command has finished executing, with the result code.
887 * @throws RemoteException
888 * @hide
889 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700890 public void shellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
891 @Nullable FileDescriptor err,
892 @NonNull String[] args, @Nullable ShellCallback callback,
893 @NonNull ResultReceiver resultReceiver) throws RemoteException {
Dianne Hackborn354736e2016-08-22 17:00:05 -0700894 onShellCommand(in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700895 }
896
897 /**
898 * Handle a call to {@link #shellCommand}. The default implementation simply prints
899 * an error message. Override and replace with your own.
Dianne Hackborn2e931f52016-01-28 12:21:17 -0800900 * <p class="caution">Note: no permission checking is done before calling this method; you must
901 * apply any security checks as appropriate for the command being executed.
902 * Consider using {@link ShellCommand} to help in the implementation.</p>
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700903 * @hide
904 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700905 public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
906 @Nullable FileDescriptor err,
907 @NonNull String[] args, @Nullable ShellCallback callback,
908 @NonNull ResultReceiver resultReceiver) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700909 FileOutputStream fout = new FileOutputStream(err != null ? err : out);
910 PrintWriter pw = new FastPrintWriter(fout);
911 pw.println("No shell command implementation.");
912 pw.flush();
913 resultReceiver.send(0, null);
914 }
915
916 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 * Default implementation rewinds the parcels and calls onTransact. On
918 * the remote side, transact calls into the binder to do the IPC.
919 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700920 public final boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 int flags) throws RemoteException {
Joe Onorato43a17652011-04-06 19:22:23 -0700922 if (false) Log.v("Binder", "Transact: " + code + " to " + this);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 if (data != null) {
925 data.setDataPosition(0);
926 }
927 boolean r = onTransact(code, data, reply, flags);
928 if (reply != null) {
929 reply.setDataPosition(0);
930 }
931 return r;
932 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 /**
935 * Local implementation is a no-op.
936 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700937 public void linkToDeath(@NonNull DeathRecipient recipient, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 }
939
940 /**
941 * Local implementation is a no-op.
942 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700943 public boolean unlinkToDeath(@NonNull DeathRecipient recipient, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 return true;
945 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700946
Dianne Hackbornfad079d2014-09-26 15:46:24 -0700947 static void checkParcel(IBinder obj, int code, Parcel parcel, String msg) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -0700948 if (CHECK_PARCEL_SIZE && parcel.dataSize() >= 800*1024) {
Dianne Hackborn017c6a22014-09-25 17:41:34 -0700949 // Trying to send > 800k, this is way too much
Dianne Hackbornfad079d2014-09-26 15:46:24 -0700950 StringBuilder sb = new StringBuilder();
951 sb.append(msg);
952 sb.append(": on ");
953 sb.append(obj);
954 sb.append(" calling ");
955 sb.append(code);
956 sb.append(" size ");
957 sb.append(parcel.dataSize());
958 sb.append(" (data: ");
959 parcel.setDataPosition(0);
960 sb.append(parcel.readInt());
961 sb.append(", ");
962 sb.append(parcel.readInt());
963 sb.append(", ");
964 sb.append(parcel.readInt());
965 sb.append(")");
966 Slog.wtfStack(TAG, sb.toString());
Dianne Hackborn017c6a22014-09-25 17:41:34 -0700967 }
968 }
969
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700970 private static native long getNativeBBinderHolder();
971 private static native long getFinalizer();
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700972
Olivier Gaillard76c231d2018-12-05 12:52:08 +0000973 /**
974 * By default, we use the calling uid since we can always trust it.
975 */
976 private static volatile BinderInternal.WorkSourceProvider sWorkSourceProvider =
Olivier Gaillardbab444a2019-01-30 17:11:40 +0000977 (x) -> Binder.getCallingUid();
Olivier Gaillard76c231d2018-12-05 12:52:08 +0000978
979 /**
980 * Sets the work source provider.
981 *
982 * <li>The callback is global. Only fast operations should be done to avoid thread
983 * contentions.
984 * <li>The callback implementation needs to handle synchronization if needed. The methods on the
985 * callback can be called concurrently.
986 * <li>The callback is called on the critical path of the binder transaction so be careful about
987 * performance.
988 * <li>Never execute another binder transaction inside the callback.
989 * @hide
990 */
991 public static void setWorkSourceProvider(BinderInternal.WorkSourceProvider workSourceProvider) {
992 if (workSourceProvider == null) {
993 throw new IllegalArgumentException("workSourceProvider cannot be null");
994 }
995 sWorkSourceProvider = workSourceProvider;
996 }
997
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700998 // Entry point from android_util_Binder.cpp's onTransact
Andrei Onea24ec3212019-03-15 17:35:05 +0000999 @UnsupportedAppUsage
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001000 private boolean execTransact(int code, long dataObj, long replyObj,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 int flags) {
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001002 // At that point, the parcel request headers haven't been parsed so we do not know what
1003 // WorkSource the caller has set. Use calling uid as the default.
1004 final int callingUid = Binder.getCallingUid();
1005 final long origWorkSource = ThreadLocalWorkSource.setUid(callingUid);
Olivier Gaillard180f91f2018-12-05 15:20:02 +00001006 try {
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001007 return execTransactInternal(code, dataObj, replyObj, flags, callingUid);
Olivier Gaillard180f91f2018-12-05 15:20:02 +00001008 } finally {
1009 ThreadLocalWorkSource.restore(origWorkSource);
1010 }
1011 }
1012
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001013 private boolean execTransactInternal(int code, long dataObj, long replyObj, int flags,
1014 int callingUid) {
Olivier Gaillard289ba402018-07-24 18:50:13 +01001015 // Make sure the observer won't change while processing a transaction.
1016 final BinderInternal.Observer observer = sObserver;
1017 final CallSession callSession =
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001018 observer != null ? observer.callStarted(this, code, UNSET_WORKSOURCE) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 Parcel data = Parcel.obtain(dataObj);
1020 Parcel reply = Parcel.obtain(replyObj);
1021 // theoretically, we should call transact, which will call onTransact,
1022 // but all that does is rewind it, and we just got these from an IPC,
1023 // so we'll just call it directly.
1024 boolean res;
Igor Murashkin7eb6cfe2013-08-16 14:07:11 -07001025 // Log any exceptions as warnings, don't silently suppress them.
1026 // If the call was FLAG_ONEWAY then these exceptions disappear into the ether.
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001027 final boolean tracingEnabled = Binder.isTracingEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 try {
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001029 if (tracingEnabled) {
Olivier Gaillard53f645062018-10-12 15:41:50 +01001030 final String transactionName = getTransactionName(code);
1031 Trace.traceBegin(Trace.TRACE_TAG_ALWAYS, getClass().getName() + ":"
1032 + (transactionName != null ? transactionName : code));
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 res = onTransact(code, data, reply, flags);
Makoto Onukif9b941f2016-03-10 17:19:08 -08001035 } catch (RemoteException|RuntimeException e) {
Olivier Gaillard289ba402018-07-24 18:50:13 +01001036 if (observer != null) {
1037 observer.callThrewException(callSession, e);
1038 }
Makoto Onukif9b941f2016-03-10 17:19:08 -08001039 if (LOG_RUNTIME_EXCEPTION) {
Igor Murashkin7eb6cfe2013-08-16 14:07:11 -07001040 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
Makoto Onukif9b941f2016-03-10 17:19:08 -08001041 }
1042 if ((flags & FLAG_ONEWAY) != 0) {
1043 if (e instanceof RemoteException) {
1044 Log.w(TAG, "Binder call failed.", e);
1045 } else {
1046 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
1047 }
Dianne Hackbornce92b0d2014-09-30 11:28:18 -07001048 } else {
Michael Wachenschwanz06041db2019-05-15 22:58:15 -07001049 // Clear the parcel before writing the exception
1050 reply.setDataSize(0);
Dianne Hackbornce92b0d2014-09-30 11:28:18 -07001051 reply.setDataPosition(0);
1052 reply.writeException(e);
Igor Murashkin7eb6cfe2013-08-16 14:07:11 -07001053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 res = true;
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001055 } finally {
1056 if (tracingEnabled) {
1057 Trace.traceEnd(Trace.TRACE_TAG_ALWAYS);
1058 }
Olivier Gaillard0e4d61e2018-12-05 15:30:35 +00001059 if (observer != null) {
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001060 // The parcel RPC headers have been called during onTransact so we can now access
1061 // the worksource uid from the parcel.
1062 final int workSourceUid = sWorkSourceProvider.resolveWorkSourceUid(
1063 data.readCallingWorkSourceUid());
Olivier Gaillard76c231d2018-12-05 12:52:08 +00001064 observer.callEnded(callSession, data.dataSize(), reply.dataSize(), workSourceUid);
Olivier Gaillard0e4d61e2018-12-05 15:30:35 +00001065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
Dianne Hackbornfad079d2014-09-26 15:46:24 -07001067 checkParcel(this, code, reply, "Unreasonably large binder reply buffer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 reply.recycle();
1069 data.recycle();
Dianne Hackbornce92b0d2014-09-30 11:28:18 -07001070
1071 // Just in case -- we are done with the IPC, so there should be no more strict
1072 // mode violations that have gathered for this thread. Either they have been
1073 // parceled and are now in transport off to the caller, or we are returning back
1074 // to the main transaction loop to wait for another incoming transaction. Either
1075 // way, strict mode begone!
1076 StrictMode.clearGatheredViolations();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 return res;
1078 }
Jon Spivack9e45fde2019-10-09 17:23:00 -07001079
1080 /**
1081 * Returns the specified service from servicemanager. If the service is not running,
1082 * servicemanager will attempt to start it, and this function will wait for it to be ready.
1083 * Returns nullptr only if there are permission problems or fatal errors.
1084 * @hide
1085 */
1086 public static final native @Nullable IBinder waitForService(@NonNull String serviceName)
1087 throws RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088}