blob: b28c2f462db2198333a804a9dd89d097b6c47cba [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;
Eugene Suslacf00ade2017-04-10 11:51:58 -070022import android.util.ExceptionUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.util.Log;
Dianne Hackborn017c6a22014-09-25 17:41:34 -070024import android.util.Slog;
Eugene Suslacf00ade2017-04-10 11:51:58 -070025
Michael Wachenschwanz58ac2182018-01-30 15:11:19 -080026import com.android.internal.os.BinderInternal;
Olivier Gaillard289ba402018-07-24 18:50:13 +010027import com.android.internal.os.BinderInternal.CallSession;
Dianne Hackborndb4e33f2013-04-01 17:28:16 -070028import com.android.internal.util.FastPrintWriter;
Eugene Suslacf00ade2017-04-10 11:51:58 -070029import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
30import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
31
Olivier Gaillarde4ff3972018-08-16 14:01:58 +010032import dalvik.annotation.optimization.CriticalNative;
33
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070034import libcore.io.IoUtils;
Hans Boehm5e5b13f2017-09-28 18:16:50 -070035import libcore.util.NativeAllocationRegistry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036
37import java.io.FileDescriptor;
38import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import java.io.PrintWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import java.lang.reflect.Modifier;
41
42/**
43 * Base class for a remotable object, the core part of a lightweight
44 * remote procedure call mechanism defined by {@link IBinder}.
45 * This class is an implementation of IBinder that provides
Dianne Hackbornab4a81b2014-10-09 17:59:38 -070046 * standard local implementation of such an object.
47 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048 * <p>Most developers will not implement this class directly, instead using the
Scott Main40eee612012-08-06 17:48:37 -070049 * <a href="{@docRoot}guide/components/aidl.html">aidl</a> tool to describe the desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050 * interface, having it generate the appropriate Binder subclass. You can,
51 * however, derive directly from Binder to implement your own custom RPC
52 * protocol or simply instantiate a raw Binder object directly to use as a
53 * token that can be shared across processes.
Dianne Hackbornab4a81b2014-10-09 17:59:38 -070054 *
55 * <p>This class is just a basic IPC primitive; it has no impact on an application's
56 * lifecycle, and is valid only as long as the process that created it continues to run.
57 * To use this correctly, you must be doing so within the context of a top-level
58 * application component (a {@link android.app.Service}, {@link android.app.Activity},
59 * or {@link android.content.ContentProvider}) that lets the system know your process
60 * should remain running.</p>
61 *
62 * <p>You must keep in mind the situations in which your process
63 * could go away, and thus require that you later re-create a new Binder and re-attach
64 * it when the process starts again. For example, if you are using this within an
65 * {@link android.app.Activity}, your activity's process may be killed any time the
66 * activity is not started; if the activity is later re-created you will need to
67 * create a new Binder and hand it back to the correct place again; you need to be
68 * aware that your process may be started for another reason (for example to receive
69 * a broadcast) that will not involve re-creating the activity and thus run its code
70 * to create a new Binder.</p>
71 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 * @see IBinder
73 */
74public class Binder implements IBinder {
75 /*
76 * Set this flag to true to detect anonymous, local or member classes
77 * that extend this Binder class and that are not static. These kind
78 * of classes can potentially create leaks.
79 */
80 private static final boolean FIND_POTENTIAL_LEAKS = false;
Jeff Sharkeyf5299f12017-03-17 10:25:07 -060081 /** @hide */
82 public static final boolean CHECK_PARCEL_SIZE = false;
Dianne Hackborn017c6a22014-09-25 17:41:34 -070083 static final String TAG = "Binder";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084
Makoto Onukif9b941f2016-03-10 17:19:08 -080085 /** @hide */
86 public static boolean LOG_RUNTIME_EXCEPTION = false; // DO NOT SUBMIT WITH TRUE
87
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -070088 /**
Olivier Gaillardc17d2802018-11-19 17:08:17 +000089 * Value to represents that a calling work source is not set.
90 *
91 * This constatnt needs to be kept in sync with IPCThreadState::kUnsetWorkSource.
92 *
93 * @hide
94 */
95 public static final int UNSET_WORKSOURCE = -1;
96
97 /**
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -070098 * Control whether dump() calls are allowed.
99 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600100 private static volatile String sDumpDisabled = null;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700101
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400102 /**
103 * Global transaction tracker instance for this process.
104 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600105 private static volatile TransactionTracker sTransactionTracker = null;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400106
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700107 /**
Olivier Gaillard289ba402018-07-24 18:50:13 +0100108 * Global observer for this process.
109 */
110 private static BinderInternal.Observer sObserver = null;
111
112 /**
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700113 * Guestimate of native memory associated with a Binder.
114 */
115 private static final int NATIVE_ALLOCATION_SIZE = 500;
116
117 private static native long getNativeFinalizer();
118
119 // Use a Holder to allow static initialization of Binder in the boot image, and
120 // possibly to avoid some initialization ordering issues.
121 private static class NoImagePreloadHolder {
122 public static final NativeAllocationRegistry sRegistry = new NativeAllocationRegistry(
123 Binder.class.getClassLoader(), getNativeFinalizer(), NATIVE_ALLOCATION_SIZE);
124 }
125
Olivier Gaillard289ba402018-07-24 18:50:13 +0100126
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400127 // Transaction tracking code.
128
129 /**
130 * Flag indicating whether we should be tracing transact calls.
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400131 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600132 private static volatile boolean sTracingEnabled = false;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400133
134 /**
135 * Enable Binder IPC tracing.
136 *
137 * @hide
138 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600139 public static void enableTracing() {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400140 sTracingEnabled = true;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600141 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400142
143 /**
144 * Disable Binder IPC tracing.
145 *
146 * @hide
147 */
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600148 public static void disableTracing() {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400149 sTracingEnabled = false;
150 }
151
152 /**
153 * Check if binder transaction tracing is enabled.
154 *
155 * @hide
156 */
157 public static boolean isTracingEnabled() {
158 return sTracingEnabled;
159 }
160
161 /**
162 * Get the binder transaction tracker for this process.
163 *
164 * @hide
165 */
166 public synchronized static TransactionTracker getTransactionTracker() {
167 if (sTransactionTracker == null)
168 sTransactionTracker = new TransactionTracker();
169 return sTransactionTracker;
170 }
171
Olivier Gaillard289ba402018-07-24 18:50:13 +0100172 /**
173 * Get the binder transaction observer for this process.
174 *
175 * @hide
176 */
177 public static void setObserver(@Nullable BinderInternal.Observer observer) {
178 sObserver = observer;
179 }
180
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600181 /** {@hide} */
182 static volatile boolean sWarnOnBlocking = false;
183
184 /**
185 * Warn if any blocking binder transactions are made out from this process.
186 * This is typically only useful for the system process, to prevent it from
187 * blocking on calls to external untrusted code. Instead, all outgoing calls
188 * that require a result must be sent as {@link IBinder#FLAG_ONEWAY} calls
189 * which deliver results through a callback interface.
190 *
191 * @hide
192 */
193 public static void setWarnOnBlocking(boolean warnOnBlocking) {
194 sWarnOnBlocking = warnOnBlocking;
195 }
196
197 /**
198 * Allow blocking calls on the given interface, overriding the requested
199 * value of {@link #setWarnOnBlocking(boolean)}.
200 * <p>
201 * This should only be rarely called when you are <em>absolutely sure</em>
202 * the remote interface is a built-in system component that can never be
203 * upgraded. In particular, this <em>must never</em> be called for
204 * interfaces hosted by package that could be upgraded or replaced,
205 * otherwise you risk system instability if that remote interface wedges.
206 *
207 * @hide
208 */
209 public static IBinder allowBlocking(IBinder binder) {
210 try {
211 if (binder instanceof BinderProxy) {
212 ((BinderProxy) binder).mWarnOnBlocking = false;
Dianne Hackbornc81983a2017-10-20 16:16:32 -0700213 } else if (binder != null && binder.getInterfaceDescriptor() != null
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600214 && binder.queryLocalInterface(binder.getInterfaceDescriptor()) == null) {
215 Log.w(TAG, "Unable to allow blocking on interface " + binder);
216 }
217 } catch (RemoteException ignored) {
218 }
219 return binder;
220 }
221
222 /**
Jeff Sharkey59189482017-11-09 18:13:43 -0700223 * Reset the given interface back to the default blocking behavior,
224 * reverting any changes made by {@link #allowBlocking(IBinder)}.
225 *
226 * @hide
227 */
228 public static IBinder defaultBlocking(IBinder binder) {
229 if (binder instanceof BinderProxy) {
230 ((BinderProxy) binder).mWarnOnBlocking = sWarnOnBlocking;
231 }
232 return binder;
233 }
234
235 /**
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600236 * Inherit the current {@link #allowBlocking(IBinder)} value from one given
237 * interface to another.
238 *
239 * @hide
240 */
241 public static void copyAllowBlocking(IBinder fromBinder, IBinder toBinder) {
242 if (fromBinder instanceof BinderProxy && toBinder instanceof BinderProxy) {
243 ((BinderProxy) toBinder).mWarnOnBlocking = ((BinderProxy) fromBinder).mWarnOnBlocking;
244 }
245 }
246
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700247 /**
248 * Raw native pointer to JavaBBinderHolder object. Owned by this Java object. Not null.
249 */
250 private final long mObject;
251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 private IInterface mOwner;
253 private String mDescriptor;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 /**
256 * Return the ID of the process that sent you the current transaction
257 * that is being processed. This pid can be used with higher-level
258 * system services to determine its identity and check permissions.
259 * If the current thread is not currently executing an incoming transaction,
260 * then its own pid is returned.
261 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100262 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 public static final native int getCallingPid();
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 /**
Dianne Hackborn74ee8652012-09-07 18:33:18 -0700266 * Return the Linux uid assigned to the process that sent you the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 * current transaction that is being processed. This uid can be used with
268 * higher-level system services to determine its identity and check
269 * permissions. If the current thread is not currently executing an
270 * incoming transaction, then its own uid is returned.
271 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100272 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 public static final native int getCallingUid();
Amith Yamasani742a6712011-05-04 14:49:28 -0700274
275 /**
Nikita Ioffea929cf02019-01-03 13:35:22 +0000276 * Returns {@code true} if the current thread is currently executing an
277 * incoming transaction.
278 *
279 * @hide
280 */
281 @CriticalNative
282 public static final native boolean isHandlingTransaction();
283
284 /**
285 * Return the Linux uid assigned to the process that sent the transaction
286 * currently being processed.
287 *
288 * @throws IllegalStateException if the current thread is not currently
289 * executing an incoming transaction.
290 */
291 public static final int getCallingUidOrThrow() {
292 if (!isHandlingTransaction()) {
293 throw new IllegalStateException(
294 "Thread is not in a binder transcation");
295 }
296 return getCallingUid();
297 }
298
299 /**
Dianne Hackborn74ee8652012-09-07 18:33:18 -0700300 * Return the UserHandle assigned to the process that sent you the
301 * current transaction that is being processed. This is the user
302 * of the caller. It is distinct from {@link #getCallingUid()} in that a
303 * particular user will have multiple distinct apps running under it each
304 * with their own uid. If the current thread is not currently executing an
305 * incoming transaction, then its own UserHandle is returned.
306 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700307 public static final @NonNull UserHandle getCallingUserHandle() {
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700308 return UserHandle.of(UserHandle.getUserId(getCallingUid()));
Dianne Hackborn74ee8652012-09-07 18:33:18 -0700309 }
310
311 /**
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700312 * Reset the identity of the incoming IPC on the current thread. This can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 * be useful if, while handling an incoming call, you will be calling
314 * on interfaces of other objects that may be local to your process and
315 * need to do permission checks on the calls coming into them (so they
316 * will check the permission of your own local process, and not whatever
317 * process originally called you).
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700318 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 * @return Returns an opaque token that can be used to restore the
320 * original calling identity by passing it to
321 * {@link #restoreCallingIdentity(long)}.
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700322 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 * @see #getCallingPid()
324 * @see #getCallingUid()
325 * @see #restoreCallingIdentity(long)
326 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100327 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 public static final native long clearCallingIdentity();
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 /**
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700331 * Restore the identity of the incoming IPC on the current thread
332 * back to a previously identity that was returned by {@link
333 * #clearCallingIdentity}.
334 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 * @param token The opaque token that was previously returned by
336 * {@link #clearCallingIdentity}.
Brad Fitzpatricka0527f22010-03-25 20:40:34 -0700337 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 * @see #clearCallingIdentity
339 */
340 public static final native void restoreCallingIdentity(long token);
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700341
342 /**
Eugene Susla6a7006a2017-03-13 12:57:58 -0700343 * Convenience method for running the provided action enclosed in
344 * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity}
345 *
Eugene Suslacf00ade2017-04-10 11:51:58 -0700346 * Any exception thrown by the given action will be caught and rethrown after the call to
347 * {@link #restoreCallingIdentity}
348 *
Eugene Susla6a7006a2017-03-13 12:57:58 -0700349 * @hide
350 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700351 public static final void withCleanCallingIdentity(@NonNull ThrowingRunnable action) {
Eugene Susla6a7006a2017-03-13 12:57:58 -0700352 long callingIdentity = clearCallingIdentity();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700353 Throwable throwableToPropagate = null;
Eugene Susla6a7006a2017-03-13 12:57:58 -0700354 try {
Eugene Susla2f5ee712017-06-23 17:25:24 -0700355 action.runOrThrow();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700356 } catch (Throwable throwable) {
357 throwableToPropagate = throwable;
Eugene Susla6a7006a2017-03-13 12:57:58 -0700358 } finally {
359 restoreCallingIdentity(callingIdentity);
Eugene Suslacf00ade2017-04-10 11:51:58 -0700360 if (throwableToPropagate != null) {
361 throw ExceptionUtils.propagate(throwableToPropagate);
362 }
Eugene Susla6a7006a2017-03-13 12:57:58 -0700363 }
364 }
365
366 /**
367 * Convenience method for running the provided action enclosed in
368 * {@link #clearCallingIdentity}/{@link #restoreCallingIdentity} returning the result
369 *
Eugene Suslacf00ade2017-04-10 11:51:58 -0700370 * Any exception thrown by the given action will be caught and rethrown after the call to
371 * {@link #restoreCallingIdentity}
372 *
Eugene Susla6a7006a2017-03-13 12:57:58 -0700373 * @hide
374 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700375 public static final <T> T withCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) {
Eugene Susla6a7006a2017-03-13 12:57:58 -0700376 long callingIdentity = clearCallingIdentity();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700377 Throwable throwableToPropagate = null;
Eugene Susla6a7006a2017-03-13 12:57:58 -0700378 try {
Eugene Susla2f5ee712017-06-23 17:25:24 -0700379 return action.getOrThrow();
Eugene Suslacf00ade2017-04-10 11:51:58 -0700380 } catch (Throwable throwable) {
381 throwableToPropagate = throwable;
382 return null; // overridden by throwing in finally block
Eugene Susla6a7006a2017-03-13 12:57:58 -0700383 } finally {
384 restoreCallingIdentity(callingIdentity);
Eugene Suslacf00ade2017-04-10 11:51:58 -0700385 if (throwableToPropagate != null) {
386 throw ExceptionUtils.propagate(throwableToPropagate);
387 }
Eugene Susla6a7006a2017-03-13 12:57:58 -0700388 }
389 }
390
391 /**
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700392 * Sets the native thread-local StrictMode policy mask.
393 *
394 * <p>The StrictMode settings are kept in two places: a Java-level
395 * threadlocal for libcore/Dalvik, and a native threadlocal (set
396 * here) for propagation via Binder calls. This is a little
397 * unfortunate, but necessary to break otherwise more unfortunate
398 * dependencies either of Dalvik on Android, or Android
399 * native-only code on Dalvik.
400 *
401 * @see StrictMode
402 * @hide
403 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100404 @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700405 public static final native void setThreadStrictModePolicy(int policyMask);
406
407 /**
408 * Gets the current native thread-local StrictMode policy mask.
409 *
410 * @see #setThreadStrictModePolicy
411 * @hide
412 */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100413 @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700414 public static final native int getThreadStrictModePolicy();
415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 /**
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100417 * Sets the work source for this thread.
418 *
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000419 * <p>All the following binder calls on this thread will use the provided work source. If this
420 * is called during an on-going binder transaction, all the following binder calls will use the
421 * work source until the end of the transaction.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100422 *
423 * <p>The concept of worksource is similar to {@link WorkSource}. However, for performance
424 * reasons, we only support one UID. This UID represents the original user responsible for the
425 * binder calls.
426 *
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000427 * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after setting the
428 * worksource.
429 *
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100430 * <p>A typical use case would be
431 * <pre>
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000432 * long token = Binder.setCallingWorkSourceUid(uid);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100433 * try {
434 * // Call an API.
435 * } finally {
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000436 * Binder.restoreCallingWorkSource(token);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100437 * }
438 * </pre>
439 *
Olivier Gaillard1d724582018-11-19 14:35:37 +0000440 * <p>The work source will be propagated for future outgoing binder transactions
441 * executed on this thread.
442 *
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100443 * @param workSource The original UID responsible for the binder call.
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000444 * @return token to restore original work source.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100445 * @hide
446 **/
447 @CriticalNative
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000448 @SystemApi
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
455 * caller can set the value to whatever he wants. Only use this value if you trust the calling
456 * uid.
457 *
458 * @return The original UID responsible for the binder transaction.
459 * @hide
460 */
461 @CriticalNative
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000462 @SystemApi
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000463 public static final native int getCallingWorkSourceUid();
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100464
465 /**
466 * Clears the work source on this thread.
467 *
Olivier Gaillard1d724582018-11-19 14:35:37 +0000468 * <p>The work source will be propagated for future outgoing binder transactions
469 * executed on this thread.
470 *
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000471 * <p>{@link Binder#restoreCallingWorkSource(long)} must always be called after clearing the
472 * worksource.
473 *
474 * <p>A typical use case would be
475 * <pre>
476 * long token = Binder.clearCallingWorkSource();
477 * try {
478 * // Call an API.
479 * } finally {
480 * Binder.restoreCallingWorkSource(token);
481 * }
482 * </pre>
483 *
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000484 * @return token to restore original work source.
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100485 * @hide
486 **/
487 @CriticalNative
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000488 @SystemApi
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000489 public static final native long clearCallingWorkSource();
490
491 /**
492 * Restores the work source on this thread using a token returned by
493 * {@link #setCallingWorkSourceUid(int) or {@link clearCallingWorkSource()}.
494 *
495 * <p>A typical use case would be
496 * <pre>
497 * long token = Binder.setCallingWorkSourceUid(uid);
498 * try {
499 * // Call an API.
500 * } finally {
501 * Binder.restoreCallingWorkSource(token);
502 * }
503 * </pre>
Olivier Gaillard1d724582018-11-19 14:35:37 +0000504 *
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000505 * @hide
506 **/
507 @CriticalNative
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000508 @SystemApi
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000509 public static final native void restoreCallingWorkSource(long token);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100510
511 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 * Flush any Binder commands pending in the current thread to the kernel
513 * driver. This can be
514 * useful to call before performing an operation that may block for a long
515 * time, to ensure that any pending object references have been released
516 * in order to prevent the process from holding on to objects longer than
517 * it needs to.
518 */
519 public static final native void flushPendingCommands();
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 /**
522 * Add the calling thread to the IPC thread pool. This function does
523 * not return until the current process is exiting.
524 */
Andreas Gampeacd19872018-03-16 15:58:24 -0700525 public static final void joinThreadPool() {
526 BinderInternal.joinThreadPool();
527 }
Jeff Brown1951ce82013-04-04 22:45:12 -0700528
529 /**
530 * Returns true if the specified interface is a proxy.
531 * @hide
532 */
533 public static final boolean isProxy(IInterface iface) {
534 return iface.asBinder() != iface;
535 }
536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 /**
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700538 * Call blocks until the number of executing binder threads is less
539 * than the maximum number of binder threads allowed for this process.
Wale Ogunwale8d906342015-04-15 09:10:03 -0700540 * @hide
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700541 */
542 public static final native void blockUntilThreadAvailable();
543
544 /**
Martijn Coenend2c86ab2018-07-17 16:30:40 +0200545 * Default constructor just initializes the object.
546 *
547 * If you're creating a Binder token (a Binder object without an attached interface),
548 * you should use {@link #Binder(String)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 */
550 public Binder() {
Martijn Coenend2c86ab2018-07-17 16:30:40 +0200551 this(null);
552 }
553
554 /**
555 * Constructor for creating a raw Binder object (token) along with a descriptor.
556 *
557 * The descriptor of binder objects usually specifies the interface they are implementing.
558 * In case of binder tokens, no interface is implemented, and the descriptor can be used
559 * as a sort of tag to help identify the binder token. This will help identify remote
560 * references to these objects more easily when debugging.
561 *
562 * @param descriptor Used to identify the creator of this token, for example the class name.
563 * Instead of creating multiple tokens with the same descriptor, consider adding a suffix to
564 * help identify them.
565 */
566 public Binder(@Nullable String descriptor) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700567 mObject = getNativeBBinderHolder();
568 NoImagePreloadHolder.sRegistry.registerNativeAllocation(this, mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569
570 if (FIND_POTENTIAL_LEAKS) {
571 final Class<? extends Binder> klass = getClass();
572 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
573 (klass.getModifiers() & Modifier.STATIC) == 0) {
574 Log.w(TAG, "The following Binder class should be static or leaks might occur: " +
575 klass.getCanonicalName());
576 }
577 }
Martijn Coenend2c86ab2018-07-17 16:30:40 +0200578 mDescriptor = descriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 /**
582 * Convenience method for associating a specific interface with the Binder.
583 * After calling, queryLocalInterface() will be implemented for you
584 * to return the given owner IInterface when the corresponding
585 * descriptor is requested.
586 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700587 public void attachInterface(@Nullable IInterface owner, @Nullable String descriptor) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 mOwner = owner;
589 mDescriptor = descriptor;
590 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 /**
593 * Default implementation returns an empty interface name.
594 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700595 public @Nullable String getInterfaceDescriptor() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 return mDescriptor;
597 }
598
599 /**
600 * Default implementation always returns true -- if you got here,
601 * the object is alive.
602 */
603 public boolean pingBinder() {
604 return true;
605 }
606
607 /**
608 * {@inheritDoc}
609 *
610 * Note that if you're calling on a local binder, this always returns true
611 * because your process is alive if you're calling it.
612 */
613 public boolean isBinderAlive() {
614 return true;
615 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 /**
618 * Use information supplied to attachInterface() to return the
619 * associated IInterface if it matches the requested
620 * descriptor.
621 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700622 public @Nullable IInterface queryLocalInterface(@NonNull String descriptor) {
Dianne Hackbornc81983a2017-10-20 16:16:32 -0700623 if (mDescriptor != null && mDescriptor.equals(descriptor)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 return mOwner;
625 }
626 return null;
627 }
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700628
629 /**
630 * Control disabling of dump calls in this process. This is used by the system
631 * process watchdog to disable incoming dump calls while it has detecting the system
632 * is hung and is reporting that back to the activity controller. This is to
633 * prevent the controller from getting hung up on bug reports at this point.
634 * @hide
635 *
636 * @param msg The message to show instead of the dump; if null, dumps are
637 * re-enabled.
638 */
639 public static void setDumpDisabled(String msg) {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600640 sDumpDisabled = msg;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700641 }
642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 /**
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100644 * Listener to be notified about each proxy-side binder call.
645 *
646 * See {@link setProxyTransactListener}.
647 * @hide
648 */
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000649 @SystemApi
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100650 public interface ProxyTransactListener {
651 /**
652 * Called before onTransact.
653 *
654 * @return an object that will be passed back to #onTransactEnded (or null).
655 */
656 Object onTransactStarted(IBinder binder, int transactionCode);
657
658 /**
659 * Called after onTranact (even when an exception is thrown).
660 *
661 * @param session The object return by #onTransactStarted.
662 */
663 void onTransactEnded(@Nullable Object session);
664 }
665
666 /**
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100667 * Propagates the work source to binder calls executed by the system server.
668 *
669 * <li>By default, this listener will propagate the worksource if the outgoing call happens on
670 * the same thread as the incoming binder call.
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000671 * <li>Custom attribution can be done by calling {@link ThreadLocalWorkSource#setUid(int)}.
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100672 * @hide
673 */
674 public static class PropagateWorkSourceTransactListener implements ProxyTransactListener {
675 @Override
676 public Object onTransactStarted(IBinder binder, int transactionCode) {
677 // Note that {@link Binder#getCallingUid()} is already set to the UID of the current
678 // process when this method is called.
679 //
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000680 // We use ThreadLocalWorkSource instead. It also allows feature owners to set
681 // {@link ThreadLocalWorkSource#set(int) manually to attribute resources to a UID.
682 int uid = ThreadLocalWorkSource.getUid();
683 if (uid != ThreadLocalWorkSource.UID_NONE) {
684 return Binder.setCallingWorkSourceUid(uid);
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100685 }
686 return null;
687 }
688
689 @Override
690 public void onTransactEnded(Object session) {
691 if (session != null) {
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000692 long token = (long) session;
693 Binder.restoreCallingWorkSource(token);
Olivier Gaillarddef1b902018-10-17 17:10:41 +0100694 }
695 }
696 }
697
698 /**
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100699 * Sets a listener for the transact method on the proxy-side.
700 *
701 * <li>The listener is global. Only fast operations should be done to avoid thread
702 * contentions.
703 * <li>The listener implementation needs to handle synchronization if needed. The methods on the
704 * listener can be called concurrently.
705 * <li>Listener set will be used for new transactions. On-going transaction will still use the
706 * previous listener (if already set).
707 * <li>The listener is called on the critical path of the binder transaction so be careful about
708 * performance.
709 * <li>Never execute another binder transaction inside the listener.
710 * @hide
711 */
Olivier Gaillard6dfdcf42018-12-03 17:51:46 +0000712 @SystemApi
Olivier Gaillard510cdfc2018-09-17 09:35:32 +0100713 public static void setProxyTransactListener(@Nullable ProxyTransactListener listener) {
714 BinderProxy.setTransactListener(listener);
715 }
716
717 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 * Default implementation is a stub that returns false. You will want
719 * to override this to do the appropriate unmarshalling of transactions.
720 *
721 * <p>If you want to call this, call transact().
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700722 *
Dianne Hackborn18482ae2017-08-01 17:41:00 -0700723 * <p>Implementations that are returning a result should generally use
724 * {@link Parcel#writeNoException() Parcel.writeNoException} and
725 * {@link Parcel#writeException(Exception) Parcel.writeException} to propagate
726 * exceptions back to the caller.</p>
727 *
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700728 * @param code The action to perform. This should
729 * be a number between {@link #FIRST_CALL_TRANSACTION} and
730 * {@link #LAST_CALL_TRANSACTION}.
731 * @param data Marshalled data being received from the caller.
732 * @param reply If the caller is expecting a result back, it should be marshalled
733 * in to here.
734 * @param flags Additional operation flags. Either 0 for a normal
735 * RPC, or {@link #FLAG_ONEWAY} for a one-way RPC.
736 *
737 * @return Return true on a successful call; returning false is generally used to
738 * indicate that you did not understand the transaction code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700740 protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 int flags) throws RemoteException {
742 if (code == INTERFACE_TRANSACTION) {
743 reply.writeString(getInterfaceDescriptor());
744 return true;
745 } else if (code == DUMP_TRANSACTION) {
746 ParcelFileDescriptor fd = data.readFileDescriptor();
747 String[] args = data.readStringArray();
748 if (fd != null) {
749 try {
750 dump(fd.getFileDescriptor(), args);
751 } finally {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700752 IoUtils.closeQuietly(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 }
754 }
Brad Fitzpatrickeb75888e2010-07-26 17:47:45 -0700755 // Write the StrictMode header.
756 if (reply != null) {
757 reply.writeNoException();
758 } else {
759 StrictMode.clearGatheredViolations();
760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 return true;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700762 } else if (code == SHELL_COMMAND_TRANSACTION) {
763 ParcelFileDescriptor in = data.readFileDescriptor();
764 ParcelFileDescriptor out = data.readFileDescriptor();
765 ParcelFileDescriptor err = data.readFileDescriptor();
766 String[] args = data.readStringArray();
Dianne Hackborn354736e2016-08-22 17:00:05 -0700767 ShellCallback shellCallback = ShellCallback.CREATOR.createFromParcel(data);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700768 ResultReceiver resultReceiver = ResultReceiver.CREATOR.createFromParcel(data);
769 try {
770 if (out != null) {
771 shellCommand(in != null ? in.getFileDescriptor() : null,
772 out.getFileDescriptor(),
773 err != null ? err.getFileDescriptor() : out.getFileDescriptor(),
Dianne Hackborn354736e2016-08-22 17:00:05 -0700774 args, shellCallback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700775 }
776 } finally {
777 IoUtils.closeQuietly(in);
778 IoUtils.closeQuietly(out);
779 IoUtils.closeQuietly(err);
780 // Write the StrictMode header.
781 if (reply != null) {
782 reply.writeNoException();
783 } else {
784 StrictMode.clearGatheredViolations();
785 }
786 }
787 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 }
789 return false;
790 }
791
792 /**
Olivier Gaillardd3d065d2018-07-05 15:07:35 +0100793 * Resolves a transaction code to a human readable name.
794 *
795 * <p>Default implementation is a stub that returns null.
796 * <p>AIDL generated code will return the original method name.
797 *
798 * @param transactionCode The code to resolve.
799 * @return A human readable name.
800 * @hide
801 */
802 public @Nullable String getTransactionName(int transactionCode) {
803 return null;
804 }
805
806 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 * Implemented to call the more convenient version
808 * {@link #dump(FileDescriptor, PrintWriter, String[])}.
809 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700810 public void dump(@NonNull FileDescriptor fd, @Nullable String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 FileOutputStream fout = new FileOutputStream(fd);
Dianne Hackborndb4e33f2013-04-01 17:28:16 -0700812 PrintWriter pw = new FastPrintWriter(fout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700814 doDump(fd, pw, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 } finally {
816 pw.flush();
817 }
818 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700819
820 void doDump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600821 final String disabled = sDumpDisabled;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700822 if (disabled == null) {
823 try {
824 dump(fd, pw, args);
825 } catch (SecurityException e) {
826 pw.println("Security exception: " + e.getMessage());
827 throw e;
828 } catch (Throwable e) {
829 // Unlike usual calls, in this case if an exception gets thrown
830 // back to us we want to print it back in to the dump data, since
831 // that is where the caller expects all interesting information to
832 // go.
833 pw.println();
834 pw.println("Exception occurred while dumping:");
835 e.printStackTrace(pw);
836 }
837 } else {
838 pw.println(sDumpDisabled);
839 }
840 }
841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 /**
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700843 * Like {@link #dump(FileDescriptor, String[])}, but ensures the target
844 * executes asynchronously.
845 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700846 public void dumpAsync(@NonNull final FileDescriptor fd, @Nullable final String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700847 final FileOutputStream fout = new FileOutputStream(fd);
Dianne Hackborndb4e33f2013-04-01 17:28:16 -0700848 final PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700849 Thread thr = new Thread("Binder.dumpAsync") {
850 public void run() {
851 try {
852 dump(fd, pw, args);
853 } finally {
854 pw.flush();
855 }
856 }
857 };
858 thr.start();
859 }
860
861 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 * Print the object's state into the given stream.
Olivier Gaillard9429bf52018-05-15 23:25:03 +0100863 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 * @param fd The raw file descriptor that the dump is being sent to.
865 * @param fout The file to which you should dump your state. This will be
866 * closed for you after you return.
867 * @param args additional arguments to the dump request.
868 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700869 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter fout,
870 @Nullable String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 }
872
873 /**
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700874 * @param in The raw file descriptor that an input data stream can be read from.
875 * @param out The raw file descriptor that normal command messages should be written to.
876 * @param err The raw file descriptor that command error messages should be written to.
877 * @param args Command-line arguments.
Dianne Hackborn354736e2016-08-22 17:00:05 -0700878 * @param callback Callback through which to interact with the invoking shell.
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700879 * @param resultReceiver Called when the command has finished executing, with the result code.
880 * @throws RemoteException
881 * @hide
882 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700883 public void shellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
884 @Nullable FileDescriptor err,
885 @NonNull String[] args, @Nullable ShellCallback callback,
886 @NonNull ResultReceiver resultReceiver) throws RemoteException {
Dianne Hackborn354736e2016-08-22 17:00:05 -0700887 onShellCommand(in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700888 }
889
890 /**
891 * Handle a call to {@link #shellCommand}. The default implementation simply prints
892 * an error message. Override and replace with your own.
Dianne Hackborn2e931f52016-01-28 12:21:17 -0800893 * <p class="caution">Note: no permission checking is done before calling this method; you must
894 * apply any security checks as appropriate for the command being executed.
895 * Consider using {@link ShellCommand} to help in the implementation.</p>
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700896 * @hide
897 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700898 public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
899 @Nullable FileDescriptor err,
900 @NonNull String[] args, @Nullable ShellCallback callback,
901 @NonNull ResultReceiver resultReceiver) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -0700902 FileOutputStream fout = new FileOutputStream(err != null ? err : out);
903 PrintWriter pw = new FastPrintWriter(fout);
904 pw.println("No shell command implementation.");
905 pw.flush();
906 resultReceiver.send(0, null);
907 }
908
909 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 * Default implementation rewinds the parcels and calls onTransact. On
911 * the remote side, transact calls into the binder to do the IPC.
912 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700913 public final boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 int flags) throws RemoteException {
Joe Onorato43a17652011-04-06 19:22:23 -0700915 if (false) Log.v("Binder", "Transact: " + code + " to " + this);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 if (data != null) {
918 data.setDataPosition(0);
919 }
920 boolean r = onTransact(code, data, reply, flags);
921 if (reply != null) {
922 reply.setDataPosition(0);
923 }
924 return r;
925 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 /**
928 * Local implementation is a no-op.
929 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700930 public void linkToDeath(@NonNull DeathRecipient recipient, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
932
933 /**
934 * Local implementation is a no-op.
935 */
Dianne Hackborn4cd650c2017-07-31 17:38:53 -0700936 public boolean unlinkToDeath(@NonNull DeathRecipient recipient, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 return true;
938 }
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700939
Dianne Hackbornfad079d2014-09-26 15:46:24 -0700940 static void checkParcel(IBinder obj, int code, Parcel parcel, String msg) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -0700941 if (CHECK_PARCEL_SIZE && parcel.dataSize() >= 800*1024) {
Dianne Hackborn017c6a22014-09-25 17:41:34 -0700942 // Trying to send > 800k, this is way too much
Dianne Hackbornfad079d2014-09-26 15:46:24 -0700943 StringBuilder sb = new StringBuilder();
944 sb.append(msg);
945 sb.append(": on ");
946 sb.append(obj);
947 sb.append(" calling ");
948 sb.append(code);
949 sb.append(" size ");
950 sb.append(parcel.dataSize());
951 sb.append(" (data: ");
952 parcel.setDataPosition(0);
953 sb.append(parcel.readInt());
954 sb.append(", ");
955 sb.append(parcel.readInt());
956 sb.append(", ");
957 sb.append(parcel.readInt());
958 sb.append(")");
959 Slog.wtfStack(TAG, sb.toString());
Dianne Hackborn017c6a22014-09-25 17:41:34 -0700960 }
961 }
962
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700963 private static native long getNativeBBinderHolder();
964 private static native long getFinalizer();
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700965
Olivier Gaillard76c231d2018-12-05 12:52:08 +0000966 /**
967 * By default, we use the calling uid since we can always trust it.
968 */
969 private static volatile BinderInternal.WorkSourceProvider sWorkSourceProvider =
Olivier Gaillardbab444a2019-01-30 17:11:40 +0000970 (x) -> Binder.getCallingUid();
Olivier Gaillard76c231d2018-12-05 12:52:08 +0000971
972 /**
973 * Sets the work source provider.
974 *
975 * <li>The callback is global. Only fast operations should be done to avoid thread
976 * contentions.
977 * <li>The callback implementation needs to handle synchronization if needed. The methods on the
978 * callback can be called concurrently.
979 * <li>The callback is called on the critical path of the binder transaction so be careful about
980 * performance.
981 * <li>Never execute another binder transaction inside the callback.
982 * @hide
983 */
984 public static void setWorkSourceProvider(BinderInternal.WorkSourceProvider workSourceProvider) {
985 if (workSourceProvider == null) {
986 throw new IllegalArgumentException("workSourceProvider cannot be null");
987 }
988 sWorkSourceProvider = workSourceProvider;
989 }
990
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700991 // Entry point from android_util_Binder.cpp's onTransact
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000992 private boolean execTransact(int code, long dataObj, long replyObj,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 int flags) {
Olivier Gaillardbab444a2019-01-30 17:11:40 +0000994 // At that point, the parcel request headers haven't been parsed so we do not know what
995 // WorkSource the caller has set. Use calling uid as the default.
996 final int callingUid = Binder.getCallingUid();
997 final long origWorkSource = ThreadLocalWorkSource.setUid(callingUid);
Olivier Gaillard180f91f2018-12-05 15:20:02 +0000998 try {
Olivier Gaillardbab444a2019-01-30 17:11:40 +0000999 return execTransactInternal(code, dataObj, replyObj, flags, callingUid);
Olivier Gaillard180f91f2018-12-05 15:20:02 +00001000 } finally {
1001 ThreadLocalWorkSource.restore(origWorkSource);
1002 }
1003 }
1004
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001005 private boolean execTransactInternal(int code, long dataObj, long replyObj, int flags,
1006 int callingUid) {
Olivier Gaillard289ba402018-07-24 18:50:13 +01001007 // Make sure the observer won't change while processing a transaction.
1008 final BinderInternal.Observer observer = sObserver;
1009 final CallSession callSession =
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001010 observer != null ? observer.callStarted(this, code, UNSET_WORKSOURCE) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 Parcel data = Parcel.obtain(dataObj);
1012 Parcel reply = Parcel.obtain(replyObj);
1013 // theoretically, we should call transact, which will call onTransact,
1014 // but all that does is rewind it, and we just got these from an IPC,
1015 // so we'll just call it directly.
1016 boolean res;
Igor Murashkin7eb6cfe2013-08-16 14:07:11 -07001017 // Log any exceptions as warnings, don't silently suppress them.
1018 // If the call was FLAG_ONEWAY then these exceptions disappear into the ether.
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001019 final boolean tracingEnabled = Binder.isTracingEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 try {
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001021 if (tracingEnabled) {
Olivier Gaillard53f645062018-10-12 15:41:50 +01001022 final String transactionName = getTransactionName(code);
1023 Trace.traceBegin(Trace.TRACE_TAG_ALWAYS, getClass().getName() + ":"
1024 + (transactionName != null ? transactionName : code));
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 res = onTransact(code, data, reply, flags);
Makoto Onukif9b941f2016-03-10 17:19:08 -08001027 } catch (RemoteException|RuntimeException e) {
Olivier Gaillard289ba402018-07-24 18:50:13 +01001028 if (observer != null) {
1029 observer.callThrewException(callSession, e);
1030 }
Makoto Onukif9b941f2016-03-10 17:19:08 -08001031 if (LOG_RUNTIME_EXCEPTION) {
Igor Murashkin7eb6cfe2013-08-16 14:07:11 -07001032 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
Makoto Onukif9b941f2016-03-10 17:19:08 -08001033 }
1034 if ((flags & FLAG_ONEWAY) != 0) {
1035 if (e instanceof RemoteException) {
1036 Log.w(TAG, "Binder call failed.", e);
1037 } else {
1038 Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
1039 }
Dianne Hackbornce92b0d2014-09-30 11:28:18 -07001040 } else {
1041 reply.setDataPosition(0);
1042 reply.writeException(e);
Igor Murashkin7eb6cfe2013-08-16 14:07:11 -07001043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 res = true;
Jorim Jaggi25ee0bc2016-11-01 16:17:22 -07001045 } finally {
1046 if (tracingEnabled) {
1047 Trace.traceEnd(Trace.TRACE_TAG_ALWAYS);
1048 }
Olivier Gaillard0e4d61e2018-12-05 15:30:35 +00001049 if (observer != null) {
Olivier Gaillardbab444a2019-01-30 17:11:40 +00001050 // The parcel RPC headers have been called during onTransact so we can now access
1051 // the worksource uid from the parcel.
1052 final int workSourceUid = sWorkSourceProvider.resolveWorkSourceUid(
1053 data.readCallingWorkSourceUid());
Olivier Gaillard76c231d2018-12-05 12:52:08 +00001054 observer.callEnded(callSession, data.dataSize(), reply.dataSize(), workSourceUid);
Olivier Gaillard0e4d61e2018-12-05 15:30:35 +00001055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
Dianne Hackbornfad079d2014-09-26 15:46:24 -07001057 checkParcel(this, code, reply, "Unreasonably large binder reply buffer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 reply.recycle();
1059 data.recycle();
Dianne Hackbornce92b0d2014-09-30 11:28:18 -07001060
1061 // Just in case -- we are done with the IPC, so there should be no more strict
1062 // mode violations that have gathered for this thread. Either they have been
1063 // parceled and are now in transport off to the caller, or we are returning back
1064 // to the main transaction loop to wait for another incoming transaction. Either
1065 // way, strict mode begone!
1066 StrictMode.clearGatheredViolations();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 return res;
1068 }
1069}