Debian Codegraph @

core/java/android/os/Parcel.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.os;
18
19 import static com.android.internal.util.Preconditions.checkArgument;
20
21 import static java.util.Objects.requireNonNull;
22
23 import android.annotation.IntDef;
24 import android.annotation.NonNull;
25 import android.annotation.Nullable;
26 import android.annotation.SuppressLint;
27 import android.annotation.TestApi;
28 import android.app.AppOpsManager;
29 import android.compat.annotation.UnsupportedAppUsage;
30 import android.text.TextUtils;
31 import android.util.ArrayMap;
32 import android.util.ArraySet;
33 import android.util.ExceptionUtils;
34 import android.util.Log;
35 import android.util.MathUtils;
36 import android.util.Pair;
37 import android.util.Size;
38 import android.util.SizeF;
39 import android.util.Slog;
40 import android.util.SparseArray;
41 import android.util.SparseBooleanArray;
42 import android.util.SparseIntArray;
43
44 import com.android.internal.annotations.GuardedBy;
45 import com.android.internal.util.ArrayUtils;
46
47 import dalvik.annotation.optimization.CriticalNative;
48 import dalvik.annotation.optimization.FastNative;
49
50 import libcore.util.SneakyThrow;
51
52 import java.io.ByteArrayInputStream;
53 import java.io.ByteArrayOutputStream;
54 import java.io.FileDescriptor;
55 import java.io.IOException;
56 import java.io.ObjectInputStream;
57 import java.io.ObjectOutputStream;
58 import java.io.ObjectStreamClass;
59 import java.io.Serializable;
60 import java.lang.annotation.Retention;
61 import java.lang.annotation.RetentionPolicy;
62 import java.lang.reflect.Array;
63 import java.lang.reflect.Field;
64 import java.lang.reflect.Modifier;
65 import java.util.ArrayList;
66 import java.util.HashMap;
67 import java.util.List;
68 import java.util.Map;
69 import java.util.Objects;
70 import java.util.Set;
71 import java.util.function.BiFunction;
72 import java.util.function.Function;
73 import java.util.function.IntFunction;
74 import java.util.function.Supplier;
75
76 /**
77 * Container for a message (data and object references) that can
78 * be sent through an IBinder. A Parcel can contain both flattened data
79 * that will be unflattened on the other side of the IPC (using the various
80 * methods here for writing specific types, or the general
81 * {@link Parcelable} interface), and references to live {@link IBinder}
82 * objects that will result in the other side receiving a proxy IBinder
83 * connected with the original IBinder in the Parcel.
84 *
85 * <p class="note">Parcel is <strong>not</strong> a general-purpose
86 * serialization mechanism. This class (and the corresponding
87 * {@link Parcelable} API for placing arbitrary objects into a Parcel) is
88 * designed as a high-performance IPC transport. As such, it is not
89 * appropriate to place any Parcel data in to persistent storage: changes
90 * in the underlying implementation of any of the data in the Parcel can
91 * render older data unreadable.</p>
92 *
93 * <p>The bulk of the Parcel API revolves around reading and writing data
94 * of various types. There are six major classes of such functions available.</p>
95 *
96 * <h3>Primitives</h3>
97 *
98 * <p>The most basic data functions are for writing and reading primitive
99 * data types: {@link #writeByte}, {@link #readByte}, {@link #writeDouble},
100 * {@link #readDouble}, {@link #writeFloat}, {@link #readFloat}, {@link #writeInt},
101 * {@link #readInt}, {@link #writeLong}, {@link #readLong},
102 * {@link #writeString}, {@link #readString}. Most other
103 * data operations are built on top of these. The given data is written and
104 * read using the endianess of the host CPU.</p>
105 *
106 * <h3>Primitive Arrays</h3>
107 *
108 * <p>There are a variety of methods for reading and writing raw arrays
109 * of primitive objects, which generally result in writing a 4-byte length
110 * followed by the primitive data items. The methods for reading can either
111 * read the data into an existing array, or create and return a new array.
112 * These available types are:</p>
113 *
114 * <ul>
115 * <li> {@link #writeBooleanArray(boolean[])},
116 * {@link #readBooleanArray(boolean[])}, {@link #createBooleanArray()}
117 * <li> {@link #writeByteArray(byte[])},
118 * {@link #writeByteArray(byte[], int, int)}, {@link #readByteArray(byte[])},
119 * {@link #createByteArray()}
120 * <li> {@link #writeCharArray(char[])}, {@link #readCharArray(char[])},
121 * {@link #createCharArray()}
122 * <li> {@link #writeDoubleArray(double[])}, {@link #readDoubleArray(double[])},
123 * {@link #createDoubleArray()}
124 * <li> {@link #writeFloatArray(float[])}, {@link #readFloatArray(float[])},
125 * {@link #createFloatArray()}
126 * <li> {@link #writeIntArray(int[])}, {@link #readIntArray(int[])},
127 * {@link #createIntArray()}
128 * <li> {@link #writeLongArray(long[])}, {@link #readLongArray(long[])},
129 * {@link #createLongArray()}
130 * <li> {@link #writeStringArray(String[])}, {@link #readStringArray(String[])},
131 * {@link #createStringArray()}.
132 * <li> {@link #writeSparseBooleanArray(SparseBooleanArray)},
133 * {@link #readSparseBooleanArray()}.
134 * </ul>
135 *
136 * <h3>Parcelables</h3>
137 *
138 * <p>The {@link Parcelable} protocol provides an extremely efficient (but
139 * low-level) protocol for objects to write and read themselves from Parcels.
140 * You can use the direct methods {@link #writeParcelable(Parcelable, int)}
141 * and {@link #readParcelable(ClassLoader)} or
142 * {@link #writeParcelableArray} and
143 * {@link #readParcelableArray(ClassLoader)} to write or read. These
144 * methods write both the class type and its data to the Parcel, allowing
145 * that class to be reconstructed from the appropriate class loader when
146 * later reading.</p>
147 *
148 * <p>There are also some methods that provide a more efficient way to work
149 * with Parcelables: {@link #writeTypedObject}, {@link #writeTypedArray},
150 * {@link #writeTypedList}, {@link #readTypedObject},
151 * {@link #createTypedArray} and {@link #createTypedArrayList}. These methods
152 * do not write the class information of the original object: instead, the
153 * caller of the read function must know what type to expect and pass in the
154 * appropriate {@link Parcelable.Creator Parcelable.Creator} instead to
155 * properly construct the new object and read its data. (To more efficient
156 * write and read a single Parcelable object that is not null, you can directly
157 * call {@link Parcelable#writeToParcel Parcelable.writeToParcel} and
158 * {@link Parcelable.Creator#createFromParcel Parcelable.Creator.createFromParcel}
159 * yourself.)</p>
160 *
161 * <h3>Bundles</h3>
162 *
163 * <p>A special type-safe container, called {@link Bundle}, is available
164 * for key/value maps of heterogeneous values. This has many optimizations
165 * for improved performance when reading and writing data, and its type-safe
166 * API avoids difficult to debug type errors when finally marshalling the
167 * data contents into a Parcel. The methods to use are
168 * {@link #writeBundle(Bundle)}, {@link #readBundle()}, and
169 * {@link #readBundle(ClassLoader)}.
170 *
171 * <h3>Active Objects</h3>
172 *
173 * <p>An unusual feature of Parcel is the ability to read and write active
174 * objects. For these objects the actual contents of the object is not
175 * written, rather a special token referencing the object is written. When
176 * reading the object back from the Parcel, you do not get a new instance of
177 * the object, but rather a handle that operates on the exact same object that
178 * was originally written. There are two forms of active objects available.</p>
179 *
180 * <p>{@link Binder} objects are a core facility of Android's general cross-process
181 * communication system. The {@link IBinder} interface describes an abstract
182 * protocol with a Binder object. Any such interface can be written in to
183 * a Parcel, and upon reading you will receive either the original object
184 * implementing that interface or a special proxy implementation
185 * that communicates calls back to the original object. The methods to use are
186 * {@link #writeStrongBinder(IBinder)},
187 * {@link #writeStrongInterface(IInterface)}, {@link #readStrongBinder()},
188 * {@link #writeBinderArray(IBinder[])}, {@link #readBinderArray(IBinder[])},
189 * {@link #createBinderArray()},
190 * {@link #writeInterfaceArray(T[])}, {@link #readInterfaceArray(T[], Function)},
191 * {@link #createInterfaceArray(IntFunction, Function)},
192 * {@link #writeBinderList(List)}, {@link #readBinderList(List)},
193 * {@link #createBinderArrayList()},
194 * {@link #writeInterfaceList(List)}, {@link #readInterfaceList(List, Function)},
195 * {@link #createInterfaceArrayList(Function)}.</p>
196 *
197 * <p>FileDescriptor objects, representing raw Linux file descriptor identifiers,
198 * can be written and {@link ParcelFileDescriptor} objects returned to operate
199 * on the original file descriptor. The returned file descriptor is a dup
200 * of the original file descriptor: the object and fd is different, but
201 * operating on the same underlying file stream, with the same position, etc.
202 * The methods to use are {@link #writeFileDescriptor(FileDescriptor)},
203 * {@link #readFileDescriptor()}.
204 *
205 * <h3>Parcelable Containers</h3>
206 *
207 * <p>A final class of methods are for writing and reading standard Java
208 * containers of arbitrary types. These all revolve around the
209 * {@link #writeValue(Object)} and {@link #readValue(ClassLoader)} methods
210 * which define the types of objects allowed. The container methods are
211 * {@link #writeArray(Object[])}, {@link #readArray(ClassLoader)},
212 * {@link #writeList(List)}, {@link #readList(List, ClassLoader)},
213 * {@link #readArrayList(ClassLoader)},
214 * {@link #writeMap(Map)}, {@link #readMap(Map, ClassLoader)},
215 * {@link #writeSparseArray(SparseArray)},
216 * {@link #readSparseArray(ClassLoader)}.
217 *
218 * <h3>Restricted Parcelable Containers</h3>
219 *
220 * <p>A final class of methods are for reading standard Java containers of restricted types.
221 * These methods replace methods for reading containers of arbitrary types from previous section
222 * starting from Android {@link Build.VERSION_CODES#TIRAMISU}. The pairing writing methods are
223 * still the same from previous section.
224 * These methods accepts additional {@code clazz} parameters as the required types.
225 * The Restricted Parcelable container methods are {@link #readArray(ClassLoader, Class)},
226 * {@link #readList(List, ClassLoader, Class)},
227 * {@link #readArrayList(ClassLoader, Class)},
228 * {@link #readMap(Map, ClassLoader, Class, Class)},
229 * {@link #readSparseArray(ClassLoader, Class)}.
230 */
231 public final class Parcel {
232
233 private static final boolean DEBUG_RECYCLE = false;
234 private static final boolean DEBUG_ARRAY_MAP = false;
235 private static final String TAG = "Parcel";
236
237 @UnsupportedAppUsage
238 @SuppressWarnings({"UnusedDeclaration"})
239 private long mNativePtr; // used by native code
240
241 /**
242 * Flag indicating if {@link #mNativePtr} was allocated by this object,
243 * indicating that we're responsible for its lifecycle.
244 */
245 private boolean mOwnsNativeParcelObject;
246 private long mNativeSize;
247
248 private ArrayMap<Class, Object> mClassCookies;
249
250 private RuntimeException mStack;
251 private boolean mRecycled = false;
252
253 /** @hide */
254 @TestApi
255 public static final int FLAG_IS_REPLY_FROM_BLOCKING_ALLOWED_OBJECT = 1 << 0;
256
257 /** @hide */
258 @TestApi
259 public static final int FLAG_PROPAGATE_ALLOW_BLOCKING = 1 << 1;
260
261 /** @hide */
262 @IntDef(flag = true, prefix = { "FLAG_" }, value = {
263 FLAG_IS_REPLY_FROM_BLOCKING_ALLOWED_OBJECT,
264 FLAG_PROPAGATE_ALLOW_BLOCKING,
265 })
266 @Retention(RetentionPolicy.SOURCE)
267 public @interface ParcelFlags {}
268
269 @ParcelFlags
270 private int mFlags;
271
272 /**
273 * Whether or not to parcel the stack trace of an exception. This has a performance
274 * impact, so should only be included in specific processes and only on debug builds.
275 */
276 private static boolean sParcelExceptionStackTrace;
277
278 private static final Object sPoolSync = new Object();
279
280 /** Next item in the linked list pool, if any */
281 @GuardedBy("sPoolSync")
282 private Parcel mPoolNext;
283
284 /** Head of a linked list pool of {@link Parcel} objects */
285 @GuardedBy("sPoolSync")
286 private static Parcel sOwnedPool;
287 /** Head of a linked list pool of {@link Parcel} objects */
288 @GuardedBy("sPoolSync")
289 private static Parcel sHolderPool;
290
291 /** Total size of pool with head at {@link #sOwnedPool} */
292 @GuardedBy("sPoolSync")
293 private static int sOwnedPoolSize = 0;
294 /** Total size of pool with head at {@link #sHolderPool} */
295 @GuardedBy("sPoolSync")
296 private static int sHolderPoolSize = 0;
297
298 /**
299 * We're willing to pool up to 32 objects, which is sized to accommodate
300 * both a data and reply Parcel for the maximum of 16 Binder threads.
301 */
302 private static final int POOL_SIZE = 32;
303
304 // Keep in sync with frameworks/native/include/private/binder/ParcelValTypes.h.
305 private static final int VAL_NULL = -1;
306 private static final int VAL_STRING = 0;
307 private static final int VAL_INTEGER = 1;
308 private static final int VAL_MAP = 2; // length-prefixed
309 private static final int VAL_BUNDLE = 3;
310 private static final int VAL_PARCELABLE = 4; // length-prefixed
311 private static final int VAL_SHORT = 5;
312 private static final int VAL_LONG = 6;
313 private static final int VAL_FLOAT = 7;
314 private static final int VAL_DOUBLE = 8;
315 private static final int VAL_BOOLEAN = 9;
316 private static final int VAL_CHARSEQUENCE = 10;
317 private static final int VAL_LIST = 11; // length-prefixed
318 private static final int VAL_SPARSEARRAY = 12; // length-prefixed
319 private static final int VAL_BYTEARRAY = 13;
320 private static final int VAL_STRINGARRAY = 14;
321 private static final int VAL_IBINDER = 15;
322 private static final int VAL_PARCELABLEARRAY = 16; // length-prefixed
323 private static final int VAL_OBJECTARRAY = 17; // length-prefixed
324 private static final int VAL_INTARRAY = 18;
325 private static final int VAL_LONGARRAY = 19;
326 private static final int VAL_BYTE = 20;
327 private static final int VAL_SERIALIZABLE = 21; // length-prefixed
328 private static final int VAL_SPARSEBOOLEANARRAY = 22;
329 private static final int VAL_BOOLEANARRAY = 23;
330 private static final int VAL_CHARSEQUENCEARRAY = 24;
331 private static final int VAL_PERSISTABLEBUNDLE = 25;
332 private static final int VAL_SIZE = 26;
333 private static final int VAL_SIZEF = 27;
334 private static final int VAL_DOUBLEARRAY = 28;
335 private static final int VAL_CHAR = 29;
336 private static final int VAL_SHORTARRAY = 30;
337 private static final int VAL_CHARARRAY = 31;
338 private static final int VAL_FLOATARRAY = 32;
339
340 // The initial int32 in a Binder call's reply Parcel header:
341 // Keep these in sync with libbinder's binder/Status.h.
342 private static final int EX_SECURITY = -1;
343 private static final int EX_BAD_PARCELABLE = -2;
344 private static final int EX_ILLEGAL_ARGUMENT = -3;
345 private static final int EX_NULL_POINTER = -4;
346 private static final int EX_ILLEGAL_STATE = -5;
347 private static final int EX_NETWORK_MAIN_THREAD = -6;
348 private static final int EX_UNSUPPORTED_OPERATION = -7;
349 private static final int EX_SERVICE_SPECIFIC = -8;
350 private static final int EX_PARCELABLE = -9;
351 /** @hide */
352 // WARNING: DO NOT add more 'reply' headers. These also need to add work to native
353 // code and this encodes extra information in object statuses. If we need to expand
354 // this design, we should add a generic way to attach parcelables/structured parcelables
355 // to transactions which can work across languages.
356 public static final int EX_HAS_NOTED_APPOPS_REPLY_HEADER = -127; // special; see below
357 // WARNING: DO NOT add more 'reply' headers. These also need to add work to native
358 // code and this encodes extra information in object statuses. If we need to expand
359 // this design, we should add a generic way to attach parcelables/structured parcelables
360 // to transactions which can work across languages.
361 private static final int EX_HAS_STRICTMODE_REPLY_HEADER = -128; // special; see below
362 // EX_TRANSACTION_FAILED is used exclusively in native code.
363 // see libbinder's binder/Status.h
364 private static final int EX_TRANSACTION_FAILED = -129;
365
366 @CriticalNative
367 private static native void nativeMarkSensitive(long nativePtr);
368 @FastNative
369 private static native void nativeMarkForBinder(long nativePtr, IBinder binder);
370 @CriticalNative
371 private static native boolean nativeIsForRpc(long nativePtr);
372 @CriticalNative
373 private static native int nativeDataSize(long nativePtr);
374 @CriticalNative
375 private static native int nativeDataAvail(long nativePtr);
376 @CriticalNative
377 private static native int nativeDataPosition(long nativePtr);
378 @CriticalNative
379 private static native int nativeDataCapacity(long nativePtr);
380 @FastNative
381 private static native void nativeSetDataSize(long nativePtr, int size);
382 @CriticalNative
383 private static native void nativeSetDataPosition(long nativePtr, int pos);
384 @FastNative
385 private static native void nativeSetDataCapacity(long nativePtr, int size);
386
387 @CriticalNative
388 private static native boolean nativePushAllowFds(long nativePtr, boolean allowFds);
389 @CriticalNative
390 private static native void nativeRestoreAllowFds(long nativePtr, boolean lastValue);
391
392 private static native void nativeWriteByteArray(long nativePtr, byte[] b, int offset, int len);
393 private static native void nativeWriteBlob(long nativePtr, byte[] b, int offset, int len);
394 @CriticalNative
395 private static native int nativeWriteInt(long nativePtr, int val);
396 @CriticalNative
397 private static native int nativeWriteLong(long nativePtr, long val);
398 @CriticalNative
399 private static native int nativeWriteFloat(long nativePtr, float val);
400 @CriticalNative
401 private static native int nativeWriteDouble(long nativePtr, double val);
402 private static native void nativeSignalExceptionForError(int error);
403 @FastNative
404 private static native void nativeWriteString8(long nativePtr, String val);
405 @FastNative
406 private static native void nativeWriteString16(long nativePtr, String val);
407 @FastNative
408 private static native void nativeWriteStrongBinder(long nativePtr, IBinder val);
409 @FastNative
410 private static native void nativeWriteFileDescriptor(long nativePtr, FileDescriptor val);
411
412 private static native byte[] nativeCreateByteArray(long nativePtr);
413 private static native boolean nativeReadByteArray(long nativePtr, byte[] dest, int destLen);
414 private static native byte[] nativeReadBlob(long nativePtr);
415 @CriticalNative
416 private static native int nativeReadInt(long nativePtr);
417 @CriticalNative
418 private static native long nativeReadLong(long nativePtr);
419 @CriticalNative
420 private static native float nativeReadFloat(long nativePtr);
421 @CriticalNative
422 private static native double nativeReadDouble(long nativePtr);
423 @FastNative
424 private static native String nativeReadString8(long nativePtr);
425 @FastNative
426 private static native String nativeReadString16(long nativePtr);
427 @FastNative
428 private static native IBinder nativeReadStrongBinder(long nativePtr);
429 @FastNative
430 private static native FileDescriptor nativeReadFileDescriptor(long nativePtr);
431
432 private static native long nativeCreate();
433 private static native void nativeFreeBuffer(long nativePtr);
434 private static native void nativeDestroy(long nativePtr);
435
436 private static native byte[] nativeMarshall(long nativePtr);
437 private static native void nativeUnmarshall(
438 long nativePtr, byte[] data, int offset, int length);
439 private static native int nativeCompareData(long thisNativePtr, long otherNativePtr);
440 private static native boolean nativeCompareDataInRange(
441 long ptrA, int offsetA, long ptrB, int offsetB, int length);
442 private static native void nativeAppendFrom(
443 long thisNativePtr, long otherNativePtr, int offset, int length);
444 @CriticalNative
445 private static native boolean nativeHasFileDescriptors(long nativePtr);
446 private static native boolean nativeHasFileDescriptorsInRange(
447 long nativePtr, int offset, int length);
448 private static native void nativeWriteInterfaceToken(long nativePtr, String interfaceName);
449 private static native void nativeEnforceInterface(long nativePtr, String interfaceName);
450
451 @CriticalNative
452 private static native boolean nativeReplaceCallingWorkSourceUid(
453 long nativePtr, int workSourceUid);
454 @CriticalNative
455 private static native int nativeReadCallingWorkSourceUid(long nativePtr);
456
457 /** Last time exception with a stack trace was written */
458 private static volatile long sLastWriteExceptionStackTrace;
459 /** Used for throttling of writing stack trace, which is costly */
460 private static final int WRITE_EXCEPTION_STACK_TRACE_THRESHOLD_MS = 1000;
461
462 @CriticalNative
463 private static native long nativeGetOpenAshmemSize(long nativePtr);
464
465 public final static Parcelable.Creator<String> STRING_CREATOR
466 = new Parcelable.Creator<String>() {
467 public String createFromParcel(Parcel source) {
468 return source.readString();
469 }
470 public String[] newArray(int size) {
471 return new String[size];
472 }
473 };
474
475 /**
476 * @hide
477 */
478 public static class ReadWriteHelper {
479
480 @UnsupportedAppUsage
481 public ReadWriteHelper() {
482 }
483
484 public static final ReadWriteHelper DEFAULT = new ReadWriteHelper();
485
486 /**
487 * Called when writing a string to a parcel. Subclasses wanting to write a string
488 * must use {@link #writeStringNoHelper(String)} to avoid
489 * infinity recursive calls.
490 */
491 public void writeString8(Parcel p, String s) {
492 p.writeString8NoHelper(s);
493 }
494
495 public void writeString16(Parcel p, String s) {
496 p.writeString16NoHelper(s);
497 }
498
499 /**
500 * Called when reading a string to a parcel. Subclasses wanting to read a string
501 * must use {@link #readStringNoHelper()} to avoid
502 * infinity recursive calls.
503 */
504 public String readString8(Parcel p) {
505 return p.readString8NoHelper();
506 }
507
508 public String readString16(Parcel p) {
509 return p.readString16NoHelper();
510 }
511 }
512
513 private ReadWriteHelper mReadWriteHelper = ReadWriteHelper.DEFAULT;
514
515 /**
516 * Retrieve a new Parcel object from the pool.
517 */
518 @NonNull
519 public static Parcel obtain() {
520 Parcel res = null;
521 synchronized (sPoolSync) {
522 if (sOwnedPool != null) {
523 res = sOwnedPool;
524 sOwnedPool = res.mPoolNext;
525 res.mPoolNext = null;
526 sOwnedPoolSize--;
527 }
528 }
529
530 // When no cache found above, create from scratch; otherwise prepare the
531 // cached object to be used
532 if (res == null) {
533 res = new Parcel(0);
534 } else {
535 res.mRecycled = false;
536 if (DEBUG_RECYCLE) {
537 res.mStack = new RuntimeException();
538 }
539 res.mReadWriteHelper = ReadWriteHelper.DEFAULT;
540 }
541 return res;
542 }
543
544 /**
545 * Retrieve a new Parcel object from the pool for use with a specific binder.
546 *
547 * Associate this parcel with a binder object. This marks the parcel as being prepared for a
548 * transaction on this specific binder object. Based on this, the format of the wire binder
549 * protocol may change. For future compatibility, it is recommended to use this for all
550 * Parcels.
551 */
552 @NonNull
553 public static Parcel obtain(@NonNull IBinder binder) {
554 Parcel parcel = Parcel.obtain();
555 parcel.markForBinder(binder);
556 return parcel;
557 }
558
559 /**
560 * Put a Parcel object back into the pool. You must not touch
561 * the object after this call.
562 */
563 public final void recycle() {
564 if (mRecycled) {
565 Log.wtf(TAG, "Recycle called on unowned Parcel. (recycle twice?) Here: "
566 + Log.getStackTraceString(new Throwable())
567 + " Original recycle call (if DEBUG_RECYCLE): ", mStack);
568
569 return;
570 }
571 mRecycled = true;
572
573 // We try to reset the entire object here, but in order to be
574 // able to print a stack when a Parcel is recycled twice, that
575 // is cleared in obtain instead.
576
577 mClassCookies = null;
578 freeBuffer();
579
580 if (mOwnsNativeParcelObject) {
581 synchronized (sPoolSync) {
582 if (sOwnedPoolSize < POOL_SIZE) {
583 mPoolNext = sOwnedPool;
584 sOwnedPool = this;
585 sOwnedPoolSize++;
586 }
587 }
588 } else {
589 mNativePtr = 0;
590 synchronized (sPoolSync) {
591 if (sHolderPoolSize < POOL_SIZE) {
592 mPoolNext = sHolderPool;
593 sHolderPool = this;
594 sHolderPoolSize++;
595 }
596 }
597 }
598 }
599
600 /**
601 * Set a {@link ReadWriteHelper}, which can be used to avoid having duplicate strings, for
602 * example.
603 *
604 * @hide
605 */
606 public void setReadWriteHelper(@Nullable ReadWriteHelper helper) {
607 mReadWriteHelper = helper != null ? helper : ReadWriteHelper.DEFAULT;
608 }
609
610 /**
611 * @return whether this parcel has a {@link ReadWriteHelper}.
612 *
613 * @hide
614 */
615 public boolean hasReadWriteHelper() {
616 return (mReadWriteHelper != null) && (mReadWriteHelper != ReadWriteHelper.DEFAULT);
617 }
618
619 /** @hide */
620 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
621 public static native long getGlobalAllocSize();
622
623 /** @hide */
624 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
625 public static native long getGlobalAllocCount();
626
627 /**
628 * Parcel data should be zero'd before realloc'd or deleted.
629 *
630 * Note: currently this feature requires multiple things to work in concert:
631 * - markSensitive must be called on every relative Parcel
632 * - FLAG_CLEAR_BUF must be passed into the kernel
633 * This requires having code which does the right thing in every method and in every backend
634 * of AIDL. Rather than exposing this API, it should be replaced with a single API on
635 * IBinder objects which can be called once, and the information should be fed into the
636 * Parcel using markForBinder APIs. In terms of code size and number of API calls, this is
637 * much more extensible.
638 *
639 * @hide
640 */
641 public final void markSensitive() {
642 nativeMarkSensitive(mNativePtr);
643 }
644
645 /**
646 * @hide
647 */
648 private void markForBinder(@NonNull IBinder binder) {
649 nativeMarkForBinder(mNativePtr, binder);
650 }
651
652 /**
653 * Whether this Parcel is written for an RPC transaction.
654 *
655 * @hide
656 */
657 public final boolean isForRpc() {
658 return nativeIsForRpc(mNativePtr);
659 }
660
661 /** @hide */
662 @ParcelFlags
663 @TestApi
664 public int getFlags() {
665 return mFlags;
666 }
667
668 /** @hide */
669 public void setFlags(@ParcelFlags int flags) {
670 mFlags = flags;
671 }
672
673 /** @hide */
674 public void addFlags(@ParcelFlags int flags) {
675 mFlags |= flags;
676 }
677
678 /** @hide */
679 private boolean hasFlags(@ParcelFlags int flags) {
680 return (mFlags & flags) == flags;
681 }
682
683 /**
684 * This method is used by the AIDL compiler for system components. Not intended to be
685 * used by non-system apps.
686 */
687 // Note: Ideally this method should be @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES),
688 // but we need to make this method public due to the way the aidl compiler is compiled.
689 // We don't really need to protect it; even if 3p / non-system apps, nothing would happen.
690 // This would only work when used on a reply parcel by a binder object that's allowed-blocking.
691 public void setPropagateAllowBlocking() {
692 addFlags(FLAG_PROPAGATE_ALLOW_BLOCKING);
693 }
694
695 /**
696 * Returns the total amount of data contained in the parcel.
697 */
698 public int dataSize() {
699 return nativeDataSize(mNativePtr);
700 }
701
702 /**
703 * Returns the amount of data remaining to be read from the
704 * parcel. That is, {@link #dataSize}-{@link #dataPosition}.
705 */
706 public final int dataAvail() {
707 return nativeDataAvail(mNativePtr);
708 }
709
710 /**
711 * Returns the current position in the parcel data. Never
712 * more than {@link #dataSize}.
713 */
714 public final int dataPosition() {
715 return nativeDataPosition(mNativePtr);
716 }
717
718 /**
719 * Returns the total amount of space in the parcel. This is always
720 * >= {@link #dataSize}. The difference between it and dataSize() is the
721 * amount of room left until the parcel needs to re-allocate its
722 * data buffer.
723 */
724 public final int dataCapacity() {
725 return nativeDataCapacity(mNativePtr);
726 }
727
728 /**
729 * Change the amount of data in the parcel. Can be either smaller or
730 * larger than the current size. If larger than the current capacity,
731 * more memory will be allocated.
732 *
733 * @param size The new number of bytes in the Parcel.
734 */
735 public final void setDataSize(int size) {
736 nativeSetDataSize(mNativePtr, size);
737 }
738
739 /**
740 * Move the current read/write position in the parcel.
741 * @param pos New offset in the parcel; must be between 0 and
742 * {@link #dataSize}.
743 */
744 public final void setDataPosition(int pos) {
745 nativeSetDataPosition(mNativePtr, pos);
746 }
747
748 /**
749 * Change the capacity (current available space) of the parcel.
750 *
751 * @param size The new capacity of the parcel, in bytes. Can not be
752 * less than {@link #dataSize} -- that is, you can not drop existing data
753 * with this method.
754 */
755 public final void setDataCapacity(int size) {
756 nativeSetDataCapacity(mNativePtr, size);
757 }
758
759 /** @hide */
760 public final boolean pushAllowFds(boolean allowFds) {
761 return nativePushAllowFds(mNativePtr, allowFds);
762 }
763
764 /** @hide */
765 public final void restoreAllowFds(boolean lastValue) {
766 nativeRestoreAllowFds(mNativePtr, lastValue);
767 }
768
769 /**
770 * Returns the raw bytes of the parcel.
771 *
772 * <p class="note">The data you retrieve here <strong>must not</strong>
773 * be placed in any kind of persistent storage (on local disk, across
774 * a network, etc). For that, you should use standard serialization
775 * or another kind of general serialization mechanism. The Parcel
776 * marshalled representation is highly optimized for local IPC, and as
777 * such does not attempt to maintain compatibility with data created
778 * in different versions of the platform.
779 */
780 public final byte[] marshall() {
781 return nativeMarshall(mNativePtr);
782 }
783
784 /**
785 * Fills the raw bytes of this Parcel with the supplied data.
786 */
787 public final void unmarshall(@NonNull byte[] data, int offset, int length) {
788 nativeUnmarshall(mNativePtr, data, offset, length);
789 }
790
791 public final void appendFrom(Parcel parcel, int offset, int length) {
792 nativeAppendFrom(mNativePtr, parcel.mNativePtr, offset, length);
793 }
794
795 /** @hide */
796 public int compareData(Parcel other) {
797 return nativeCompareData(mNativePtr, other.mNativePtr);
798 }
799
800 /** @hide */
801 public static boolean compareData(Parcel a, int offsetA, Parcel b, int offsetB, int length) {
802 return nativeCompareDataInRange(a.mNativePtr, offsetA, b.mNativePtr, offsetB, length);
803 }
804
805 /** @hide */
806 public final void setClassCookie(Class clz, Object cookie) {
807 if (mClassCookies == null) {
808 mClassCookies = new ArrayMap<>();
809 }
810 mClassCookies.put(clz, cookie);
811 }
812
813 /** @hide */
814 @Nullable
815 public final Object getClassCookie(Class clz) {
816 return mClassCookies != null ? mClassCookies.get(clz) : null;
817 }
818
819 /** @hide */
820 public final void adoptClassCookies(Parcel from) {
821 mClassCookies = from.mClassCookies;
822 }
823
824 /** @hide */
825 public Map<Class, Object> copyClassCookies() {
826 return new ArrayMap<>(mClassCookies);
827 }
828
829 /** @hide */
830 public void putClassCookies(Map<Class, Object> cookies) {
831 if (cookies == null) {
832 return;
833 }
834 if (mClassCookies == null) {
835 mClassCookies = new ArrayMap<>();
836 }
837 mClassCookies.putAll(cookies);
838 }
839
840 /**
841 * Report whether the parcel contains any marshalled file descriptors.
842 */
843 public boolean hasFileDescriptors() {
844 return nativeHasFileDescriptors(mNativePtr);
845 }
846
847 /**
848 * Report whether the parcel contains any marshalled file descriptors in the range defined by
849 * {@code offset} and {@code length}.
850 *
851 * @param offset The offset from which the range starts. Should be between 0 and
852 * {@link #dataSize()}.
853 * @param length The length of the range. Should be between 0 and {@link #dataSize()} - {@code
854 * offset}.
855 * @return whether there are file descriptors or not.
856 * @throws IllegalArgumentException if the parameters are out of the permitted ranges.
857 */
858 public boolean hasFileDescriptors(int offset, int length) {
859 return nativeHasFileDescriptorsInRange(mNativePtr, offset, length);
860 }
861
862 /**
863 * Check if the object has file descriptors.
864 *
865 * <p>Objects supported are {@link Parcel} and objects that can be passed to {@link
866 * #writeValue(Object)}}
867 *
868 * <p>For most cases, it will use the self-reported {@link Parcelable#describeContents()} method
869 * for that.
870 *
871 * @throws IllegalArgumentException if you provide any object not supported by above methods
872 * (including if the unsupported object is inside a nested container).
873 *
874 * @hide
875 */
876 public static boolean hasFileDescriptors(Object value) {
877 if (value instanceof Parcel) {
878 Parcel parcel = (Parcel) value;
879 if (parcel.hasFileDescriptors()) {
880 return true;
881 }
882 } else if (value instanceof LazyValue) {
883 LazyValue lazy = (LazyValue) value;
884 if (lazy.hasFileDescriptors()) {
885 return true;
886 }
887 } else if (value instanceof Parcelable) {
888 Parcelable parcelable = (Parcelable) value;
889 if ((parcelable.describeContents() & Parcelable.CONTENTS_FILE_DESCRIPTOR) != 0) {
890 return true;
891 }
892 } else if (value instanceof ArrayMap<?, ?>) {
893 ArrayMap<?, ?> map = (ArrayMap<?, ?>) value;
894 for (int i = 0, n = map.size(); i < n; i++) {
895 if (hasFileDescriptors(map.keyAt(i))
896 || hasFileDescriptors(map.valueAt(i))) {
897 return true;
898 }
899 }
900 } else if (value instanceof Map<?, ?>) {
901 Map<?, ?> map = (Map<?, ?>) value;
902 for (Map.Entry<?, ?> entry : map.entrySet()) {
903 if (hasFileDescriptors(entry.getKey())
904 || hasFileDescriptors(entry.getValue())) {
905 return true;
906 }
907 }
908 } else if (value instanceof List<?>) {
909 List<?> list = (List<?>) value;
910 for (int i = 0, n = list.size(); i < n; i++) {
911 if (hasFileDescriptors(list.get(i))) {
912 return true;
913 }
914 }
915 } else if (value instanceof SparseArray<?>) {
916 SparseArray<?> array = (SparseArray<?>) value;
917 for (int i = 0, n = array.size(); i < n; i++) {
918 if (hasFileDescriptors(array.valueAt(i))) {
919 return true;
920 }
921 }
922 } else if (value instanceof Object[]) {
923 Object[] array = (Object[]) value;
924 for (int i = 0, n = array.length; i < n; i++) {
925 if (hasFileDescriptors(array[i])) {
926 return true;
927 }
928 }
929 } else {
930 getValueType(value); // Will throw if value is not supported
931 }
932 return false;
933 }
934
935 /**
936 * Store or read an IBinder interface token in the parcel at the current
937 * {@link #dataPosition}. This is used to validate that the marshalled
938 * transaction is intended for the target interface. This is typically written
939 * at the beginning of transactions as a header.
940 */
941 public final void writeInterfaceToken(@NonNull String interfaceName) {
942 nativeWriteInterfaceToken(mNativePtr, interfaceName);
943 }
944
945 /**
946 * Read the header written by writeInterfaceToken and verify it matches
947 * the interface name in question. If the wrong interface type is present,
948 * {@link SecurityException} is thrown. When used over binder, this exception
949 * should propagate to the caller.
950 */
951 public final void enforceInterface(@NonNull String interfaceName) {
952 nativeEnforceInterface(mNativePtr, interfaceName);
953 }
954
955 /**
956 * Verify there are no bytes left to be read on the Parcel.
957 *
958 * @throws BadParcelableException If the current position hasn't reached the end of the Parcel.
959 * When used over binder, this exception should propagate to the caller.
960 */
961 public void enforceNoDataAvail() {
962 final int n = dataAvail();
963 if (n > 0) {
964 throw new BadParcelableException("Parcel data not fully consumed, unread size: " + n);
965 }
966 }
967
968 /**
969 * Writes the work source uid to the request headers.
970 *
971 * <p>It requires the headers to have been written/read already to replace the work source.
972 *
973 * @return true if the request headers have been updated.
974 *
975 * @hide
976 */
977 public boolean replaceCallingWorkSourceUid(int workSourceUid) {
978 return nativeReplaceCallingWorkSourceUid(mNativePtr, workSourceUid);
979 }
980
981 /**
982 * Reads the work source uid from the request headers.
983 *
984 * <p>Unlike other read methods, this method does not read the parcel at the current
985 * {@link #dataPosition}. It will set the {@link #dataPosition} before the read and restore the
986 * position after reading the request header.
987 *
988 * @return the work source uid or {@link Binder#UNSET_WORKSOURCE} if headers have not been
989 * written/parsed yet.
990 *
991 * @hide
992 */
993 public int readCallingWorkSourceUid() {
994 return nativeReadCallingWorkSourceUid(mNativePtr);
995 }
996
997 /**
998 * Write a byte array into the parcel at the current {@link #dataPosition},
999 * growing {@link #dataCapacity} if needed.
1000 * @param b Bytes to place into the parcel.
1001 */
1002 public final void writeByteArray(@Nullable byte[] b) {
1003 writeByteArray(b, 0, (b != null) ? b.length : 0);
1004 }
1005
1006 /**
1007 * Write a byte array into the parcel at the current {@link #dataPosition},
1008 * growing {@link #dataCapacity} if needed.
1009 * @param b Bytes to place into the parcel.
1010 * @param offset Index of first byte to be written.
1011 * @param len Number of bytes to write.
1012 */
1013 public final void writeByteArray(@Nullable byte[] b, int offset, int len) {
1014 if (b == null) {
1015 writeInt(-1);
1016 return;
1017 }
1018 ArrayUtils.throwsIfOutOfBounds(b.length, offset, len);
1019 nativeWriteByteArray(mNativePtr, b, offset, len);
1020 }
1021
1022 /**
1023 * Write a blob of data into the parcel at the current {@link #dataPosition},
1024 * growing {@link #dataCapacity} if needed.
1025 *
1026 * <p> If the blob is small, then it is stored in-place, otherwise it is transferred by way of
1027 * an anonymous shared memory region. If you prefer send in-place, please use
1028 * {@link #writeByteArray(byte[])}.
1029 *
1030 * @param b Bytes to place into the parcel.
1031 *
1032 * @see #readBlob()
1033 */
1034 public final void writeBlob(@Nullable byte[] b) {
1035 writeBlob(b, 0, (b != null) ? b.length : 0);
1036 }
1037
1038 /**
1039 * Write a blob of data into the parcel at the current {@link #dataPosition},
1040 * growing {@link #dataCapacity} if needed.
1041 *
1042 * <p> If the blob is small, then it is stored in-place, otherwise it is transferred by way of
1043 * an anonymous shared memory region. If you prefer send in-place, please use
1044 * {@link #writeByteArray(byte[], int, int)}.
1045 *
1046 * @param b Bytes to place into the parcel.
1047 * @param offset Index of first byte to be written.
1048 * @param len Number of bytes to write.
1049 *
1050 * @see #readBlob()
1051 */
1052 public final void writeBlob(@Nullable byte[] b, int offset, int len) {
1053 if (b == null) {
1054 writeInt(-1);
1055 return;
1056 }
1057 ArrayUtils.throwsIfOutOfBounds(b.length, offset, len);
1058 nativeWriteBlob(mNativePtr, b, offset, len);
1059 }
1060
1061 // The OK status from system/core/libutils/include/utils/Errors.h .
1062 // We shall pass all other error codes back to native for throwing exceptions. The error
1063 // check is done in Java to allow using @CriticalNative calls for the success path.
1064 private static final int OK = 0;
1065
1066 /**
1067 * Write an integer value into the parcel at the current dataPosition(),
1068 * growing dataCapacity() if needed.
1069 */
1070 public final void writeInt(int val) {
1071 int err = nativeWriteInt(mNativePtr, val);
1072 if (err != OK) {
1073 nativeSignalExceptionForError(err);
1074 }
1075 }
1076
1077 /**
1078 * Write a long integer value into the parcel at the current dataPosition(),
1079 * growing dataCapacity() if needed.
1080 */
1081 public final void writeLong(long val) {
1082 int err = nativeWriteLong(mNativePtr, val);
1083 if (err != OK) {
1084 nativeSignalExceptionForError(err);
1085 }
1086 }
1087
1088 /**
1089 * Write a floating point value into the parcel at the current
1090 * dataPosition(), growing dataCapacity() if needed.
1091 */
1092 public final void writeFloat(float val) {
1093 int err = nativeWriteFloat(mNativePtr, val);
1094 if (err != OK) {
1095 nativeSignalExceptionForError(err);
1096 }
1097 }
1098
1099 /**
1100 * Write a double precision floating point value into the parcel at the
1101 * current dataPosition(), growing dataCapacity() if needed.
1102 */
1103 public final void writeDouble(double val) {
1104 int err = nativeWriteDouble(mNativePtr, val);
1105 if (err != OK) {
1106 nativeSignalExceptionForError(err);
1107 }
1108 }
1109
1110 /**
1111 * Write a string value into the parcel at the current dataPosition(),
1112 * growing dataCapacity() if needed.
1113 */
1114 public final void writeString(@Nullable String val) {
1115 writeString16(val);
1116 }
1117
1118 /** {@hide} */
1119 public final void writeString8(@Nullable String val) {
1120 mReadWriteHelper.writeString8(this, val);
1121 }
1122
1123 /** {@hide} */
1124 public final void writeString16(@Nullable String val) {
1125 mReadWriteHelper.writeString16(this, val);
1126 }
1127
1128 /**
1129 * Write a string without going though a {@link ReadWriteHelper}. Subclasses of
1130 * {@link ReadWriteHelper} must use this method instead of {@link #writeString} to avoid
1131 * infinity recursive calls.
1132 *
1133 * @hide
1134 */
1135 public void writeStringNoHelper(@Nullable String val) {
1136 writeString16NoHelper(val);
1137 }
1138
1139 /** {@hide} */
1140 public void writeString8NoHelper(@Nullable String val) {
1141 nativeWriteString8(mNativePtr, val);
1142 }
1143
1144 /** {@hide} */
1145 public void writeString16NoHelper(@Nullable String val) {
1146 nativeWriteString16(mNativePtr, val);
1147 }
1148
1149 /**
1150 * Write a boolean value into the parcel at the current dataPosition(),
1151 * growing dataCapacity() if needed.
1152 *
1153 * <p>Note: This method currently delegates to writeInt with a value of 1 or 0
1154 * for true or false, respectively, but may change in the future.
1155 */
1156 public final void writeBoolean(boolean val) {
1157 writeInt(val ? 1 : 0);
1158 }
1159
1160 /**
1161 * Write a CharSequence value into the parcel at the current dataPosition(),
1162 * growing dataCapacity() if needed.
1163 * @hide
1164 */
1165 @UnsupportedAppUsage
1166 public final void writeCharSequence(@Nullable CharSequence val) {
1167 TextUtils.writeToParcel(val, this, 0);
1168 }
1169
1170 /**
1171 * Write an object into the parcel at the current dataPosition(),
1172 * growing dataCapacity() if needed.
1173 */
1174 public final void writeStrongBinder(IBinder val) {
1175 nativeWriteStrongBinder(mNativePtr, val);
1176 }
1177
1178 /**
1179 * Write an object into the parcel at the current dataPosition(),
1180 * growing dataCapacity() if needed.
1181 */
1182 public final void writeStrongInterface(IInterface val) {
1183 writeStrongBinder(val == null ? null : val.asBinder());
1184 }
1185
1186 /**
1187 * Write a FileDescriptor into the parcel at the current dataPosition(),
1188 * growing dataCapacity() if needed.
1189 *
1190 * <p class="caution">The file descriptor will not be closed, which may
1191 * result in file descriptor leaks when objects are returned from Binder
1192 * calls. Use {@link ParcelFileDescriptor#writeToParcel} instead, which
1193 * accepts contextual flags and will close the original file descriptor
1194 * if {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set.</p>
1195 */
1196 public final void writeFileDescriptor(@NonNull FileDescriptor val) {
1197 nativeWriteFileDescriptor(mNativePtr, val);
1198 }
1199
1200 /**
1201 * {@hide}
1202 * This will be the new name for writeFileDescriptor, for consistency.
1203 **/
1204 public final void writeRawFileDescriptor(@NonNull FileDescriptor val) {
1205 nativeWriteFileDescriptor(mNativePtr, val);
1206 }
1207
1208 /**
1209 * {@hide}
1210 * Write an array of FileDescriptor objects into the Parcel.
1211 *
1212 * @param value The array of objects to be written.
1213 */
1214 public final void writeRawFileDescriptorArray(@Nullable FileDescriptor[] value) {
1215 if (value != null) {
1216 int N = value.length;
1217 writeInt(N);
1218 for (int i=0; i<N; i++) {
1219 writeRawFileDescriptor(value[i]);
1220 }
1221 } else {
1222 writeInt(-1);
1223 }
1224 }
1225
1226 /**
1227 * Write a byte value into the parcel at the current dataPosition(),
1228 * growing dataCapacity() if needed.
1229 *
1230 * <p>Note: This method currently delegates to writeInt but may change in
1231 * the future.
1232 */
1233 public final void writeByte(byte val) {
1234 writeInt(val);
1235 }
1236
1237 /**
1238 * Please use {@link #writeBundle} instead. Flattens a Map into the parcel
1239 * at the current dataPosition(),
1240 * growing dataCapacity() if needed. The Map keys must be String objects.
1241 * The Map values are written using {@link #writeValue} and must follow
1242 * the specification there.
1243 *
1244 * <p>It is strongly recommended to use {@link #writeBundle} instead of
1245 * this method, since the Bundle class provides a type-safe API that
1246 * allows you to avoid mysterious type errors at the point of marshalling.
1247 */
1248 public final void writeMap(@Nullable Map val) {
1249 writeMapInternal((Map<String, Object>) val);
1250 }
1251
1252 /**
1253 * Flatten a Map into the parcel at the current dataPosition(),
1254 * growing dataCapacity() if needed. The Map keys must be String objects.
1255 */
1256 /* package */ void writeMapInternal(@Nullable Map<String,Object> val) {
1257 if (val == null) {
1258 writeInt(-1);
1259 return;
1260 }
1261 Set<Map.Entry<String,Object>> entries = val.entrySet();
1262 int size = entries.size();
1263 writeInt(size);
1264
1265 for (Map.Entry<String,Object> e : entries) {
1266 writeValue(e.getKey());
1267 writeValue(e.getValue());
1268 size--;
1269 }
1270
1271 if (size != 0) {
1272 throw new BadParcelableException("Map size does not match number of entries!");
1273 }
1274
1275 }
1276
1277 /**
1278 * Flatten an ArrayMap into the parcel at the current dataPosition(),
1279 * growing dataCapacity() if needed. The Map keys must be String objects.
1280 */
1281 /* package */ void writeArrayMapInternal(@Nullable ArrayMap<String, Object> val) {
1282 if (val == null) {
1283 writeInt(-1);
1284 return;
1285 }
1286 // Keep the format of this Parcel in sync with writeToParcelInner() in
1287 // frameworks/native/libs/binder/PersistableBundle.cpp.
1288 final int N = val.size();
1289 writeInt(N);
1290 if (DEBUG_ARRAY_MAP) {
1291 RuntimeException here = new RuntimeException("here");
1292 here.fillInStackTrace();
1293 Log.d(TAG, "Writing " + N + " ArrayMap entries", here);
1294 }
1295 int startPos;
1296 for (int i=0; i<N; i++) {
1297 if (DEBUG_ARRAY_MAP) startPos = dataPosition();
1298 writeString(val.keyAt(i));
1299 writeValue(val.valueAt(i));
1300 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Write #" + i + " "
1301 + (dataPosition()-startPos) + " bytes: key=0x"
1302 + Integer.toHexString(val.keyAt(i) != null ? val.keyAt(i).hashCode() : 0)
1303 + " " + val.keyAt(i));
1304 }
1305 }
1306
1307 /**
1308 * @hide For testing only.
1309 */
1310 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1311 public void writeArrayMap(@Nullable ArrayMap<String, Object> val) {
1312 writeArrayMapInternal(val);
1313 }
1314
1315 /**
1316 * Flatten an {@link ArrayMap} with string keys containing a particular object
1317 * type into the parcel at the current dataPosition() and growing dataCapacity()
1318 * if needed. The type of the objects in the array must be one that implements
1319 * Parcelable. Only the raw data of the objects is written and not their type,
1320 * so you must use the corresponding {@link #createTypedArrayMap(Parcelable.Creator)}
1321 *
1322 * @param val The map of objects to be written.
1323 * @param parcelableFlags The parcelable flags to use.
1324 *
1325 * @see #createTypedArrayMap(Parcelable.Creator)
1326 * @see Parcelable
1327 */
1328 public <T extends Parcelable> void writeTypedArrayMap(@Nullable ArrayMap<String, T> val,
1329 int parcelableFlags) {
1330 if (val == null) {
1331 writeInt(-1);
1332 return;
1333 }
1334 final int count = val.size();
1335 writeInt(count);
1336 for (int i = 0; i < count; i++) {
1337 writeString(val.keyAt(i));
1338 writeTypedObject(val.valueAt(i), parcelableFlags);
1339 }
1340 }
1341
1342 /**
1343 * Write an array set to the parcel.
1344 *
1345 * @param val The array set to write.
1346 *
1347 * @hide
1348 */
1349 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1350 public void writeArraySet(@Nullable ArraySet<? extends Object> val) {
1351 final int size = (val != null) ? val.size() : -1;
1352 writeInt(size);
1353 for (int i = 0; i < size; i++) {
1354 writeValue(val.valueAt(i));
1355 }
1356 }
1357
1358 /**
1359 * Flatten a Bundle into the parcel at the current dataPosition(),
1360 * growing dataCapacity() if needed.
1361 */
1362 public final void writeBundle(@Nullable Bundle val) {
1363 if (val == null) {
1364 writeInt(-1);
1365 return;
1366 }
1367
1368 val.writeToParcel(this, 0);
1369 }
1370
1371 /**
1372 * Flatten a PersistableBundle into the parcel at the current dataPosition(),
1373 * growing dataCapacity() if needed.
1374 */
1375 public final void writePersistableBundle(@Nullable PersistableBundle val) {
1376 if (val == null) {
1377 writeInt(-1);
1378 return;
1379 }
1380
1381 val.writeToParcel(this, 0);
1382 }
1383
1384 /**
1385 * Flatten a Size into the parcel at the current dataPosition(),
1386 * growing dataCapacity() if needed.
1387 */
1388 public final void writeSize(@NonNull Size val) {
1389 writeInt(val.getWidth());
1390 writeInt(val.getHeight());
1391 }
1392
1393 /**
1394 * Flatten a SizeF into the parcel at the current dataPosition(),
1395 * growing dataCapacity() if needed.
1396 */
1397 public final void writeSizeF(@NonNull SizeF val) {
1398 writeFloat(val.getWidth());
1399 writeFloat(val.getHeight());
1400 }
1401
1402 /**
1403 * Flatten a List into the parcel at the current dataPosition(), growing
1404 * dataCapacity() if needed. The List values are written using
1405 * {@link #writeValue} and must follow the specification there.
1406 */
1407 public final void writeList(@Nullable List val) {
1408 if (val == null) {
1409 writeInt(-1);
1410 return;
1411 }
1412 int N = val.size();
1413 int i=0;
1414 writeInt(N);
1415 while (i < N) {
1416 writeValue(val.get(i));
1417 i++;
1418 }
1419 }
1420
1421 /**
1422 * Flatten an Object array into the parcel at the current dataPosition(),
1423 * growing dataCapacity() if needed. The array values are written using
1424 * {@link #writeValue} and must follow the specification there.
1425 */
1426 public final void writeArray(@Nullable Object[] val) {
1427 if (val == null) {
1428 writeInt(-1);
1429 return;
1430 }
1431 int N = val.length;
1432 int i=0;
1433 writeInt(N);
1434 while (i < N) {
1435 writeValue(val[i]);
1436 i++;
1437 }
1438 }
1439
1440 /**
1441 * Flatten a generic SparseArray into the parcel at the current
1442 * dataPosition(), growing dataCapacity() if needed. The SparseArray
1443 * values are written using {@link #writeValue} and must follow the
1444 * specification there.
1445 */
1446 public final <T> void writeSparseArray(@Nullable SparseArray<T> val) {
1447 if (val == null) {
1448 writeInt(-1);
1449 return;
1450 }
1451 int N = val.size();
1452 writeInt(N);
1453 int i=0;
1454 while (i < N) {
1455 writeInt(val.keyAt(i));
1456 writeValue(val.valueAt(i));
1457 i++;
1458 }
1459 }
1460
1461 public final void writeSparseBooleanArray(@Nullable SparseBooleanArray val) {
1462 if (val == null) {
1463 writeInt(-1);
1464 return;
1465 }
1466 int N = val.size();
1467 writeInt(N);
1468 int i=0;
1469 while (i < N) {
1470 writeInt(val.keyAt(i));
1471 writeByte((byte)(val.valueAt(i) ? 1 : 0));
1472 i++;
1473 }
1474 }
1475
1476 /**
1477 * @hide
1478 */
1479 public final void writeSparseIntArray(@Nullable SparseIntArray val) {
1480 if (val == null) {
1481 writeInt(-1);
1482 return;
1483 }
1484 int N = val.size();
1485 writeInt(N);
1486 int i=0;
1487 while (i < N) {
1488 writeInt(val.keyAt(i));
1489 writeInt(val.valueAt(i));
1490 i++;
1491 }
1492 }
1493
1494 public final void writeBooleanArray(@Nullable boolean[] val) {
1495 if (val != null) {
1496 int N = val.length;
1497 writeInt(N);
1498 for (int i=0; i<N; i++) {
1499 writeInt(val[i] ? 1 : 0);
1500 }
1501 } else {
1502 writeInt(-1);
1503 }
1504 }
1505
1506 @Nullable
1507 public final boolean[] createBooleanArray() {
1508 int N = readInt();
1509 // >>2 as a fast divide-by-4 works in the create*Array() functions
1510 // because dataAvail() will never return a negative number. 4 is
1511 // the size of a stored boolean in the stream.
1512 if (N >= 0 && N <= (dataAvail() >> 2)) {
1513 boolean[] val = new boolean[N];
1514 for (int i=0; i<N; i++) {
1515 val[i] = readInt() != 0;
1516 }
1517 return val;
1518 } else {
1519 return null;
1520 }
1521 }
1522
1523 public final void readBooleanArray(@NonNull boolean[] val) {
1524 int N = readInt();
1525 if (N == val.length) {
1526 for (int i=0; i<N; i++) {
1527 val[i] = readInt() != 0;
1528 }
1529 } else {
1530 throw new RuntimeException("bad array lengths");
1531 }
1532 }
1533
1534 /** @hide */
1535 public void writeShortArray(@Nullable short[] val) {
1536 if (val != null) {
1537 int n = val.length;
1538 writeInt(n);
1539 for (int i = 0; i < n; i++) {
1540 writeInt(val[i]);
1541 }
1542 } else {
1543 writeInt(-1);
1544 }
1545 }
1546
1547 /** @hide */
1548 @Nullable
1549 public short[] createShortArray() {
1550 int n = readInt();
1551 if (n >= 0 && n <= (dataAvail() >> 2)) {
1552 short[] val = new short[n];
1553 for (int i = 0; i < n; i++) {
1554 val[i] = (short) readInt();
1555 }
1556 return val;
1557 } else {
1558 return null;
1559 }
1560 }
1561
1562 /** @hide */
1563 public void readShortArray(@NonNull short[] val) {
1564 int n = readInt();
1565 if (n == val.length) {
1566 for (int i = 0; i < n; i++) {
1567 val[i] = (short) readInt();
1568 }
1569 } else {
1570 throw new RuntimeException("bad array lengths");
1571 }
1572 }
1573
1574 public final void writeCharArray(@Nullable char[] val) {
1575 if (val != null) {
1576 int N = val.length;
1577 writeInt(N);
1578 for (int i=0; i<N; i++) {
1579 writeInt((int)val[i]);
1580 }
1581 } else {
1582 writeInt(-1);
1583 }
1584 }
1585
1586 @Nullable
1587 public final char[] createCharArray() {
1588 int N = readInt();
1589 if (N >= 0 && N <= (dataAvail() >> 2)) {
1590 char[] val = new char[N];
1591 for (int i=0; i<N; i++) {
1592 val[i] = (char)readInt();
1593 }
1594 return val;
1595 } else {
1596 return null;
1597 }
1598 }
1599
1600 public final void readCharArray(@NonNull char[] val) {
1601 int N = readInt();
1602 if (N == val.length) {
1603 for (int i=0; i<N; i++) {
1604 val[i] = (char)readInt();
1605 }
1606 } else {
1607 throw new RuntimeException("bad array lengths");
1608 }
1609 }
1610
1611 public final void writeIntArray(@Nullable int[] val) {
1612 if (val != null) {
1613 int N = val.length;
1614 writeInt(N);
1615 for (int i=0; i<N; i++) {
1616 writeInt(val[i]);
1617 }
1618 } else {
1619 writeInt(-1);
1620 }
1621 }
1622
1623 @Nullable
1624 public final int[] createIntArray() {
1625 int N = readInt();
1626 if (N >= 0 && N <= (dataAvail() >> 2)) {
1627 int[] val = new int[N];
1628 for (int i=0; i<N; i++) {
1629 val[i] = readInt();
1630 }
1631 return val;
1632 } else {
1633 return null;
1634 }
1635 }
1636
1637 public final void readIntArray(@NonNull int[] val) {
1638 int N = readInt();
1639 if (N == val.length) {
1640 for (int i=0; i<N; i++) {
1641 val[i] = readInt();
1642 }
1643 } else {
1644 throw new RuntimeException("bad array lengths");
1645 }
1646 }
1647
1648 public final void writeLongArray(@Nullable long[] val) {
1649 if (val != null) {
1650 int N = val.length;
1651 writeInt(N);
1652 for (int i=0; i<N; i++) {
1653 writeLong(val[i]);
1654 }
1655 } else {
1656 writeInt(-1);
1657 }
1658 }
1659
1660 @Nullable
1661 public final long[] createLongArray() {
1662 int N = readInt();
1663 // >>3 because stored longs are 64 bits
1664 if (N >= 0 && N <= (dataAvail() >> 3)) {
1665 long[] val = new long[N];
1666 for (int i=0; i<N; i++) {
1667 val[i] = readLong();
1668 }
1669 return val;
1670 } else {
1671 return null;
1672 }
1673 }
1674
1675 public final void readLongArray(@NonNull long[] val) {
1676 int N = readInt();
1677 if (N == val.length) {
1678 for (int i=0; i<N; i++) {
1679 val[i] = readLong();
1680 }
1681 } else {
1682 throw new RuntimeException("bad array lengths");
1683 }
1684 }
1685
1686 public final void writeFloatArray(@Nullable float[] val) {
1687 if (val != null) {
1688 int N = val.length;
1689 writeInt(N);
1690 for (int i=0; i<N; i++) {
1691 writeFloat(val[i]);
1692 }
1693 } else {
1694 writeInt(-1);
1695 }
1696 }
1697
1698 @Nullable
1699 public final float[] createFloatArray() {
1700 int N = readInt();
1701 // >>2 because stored floats are 4 bytes
1702 if (N >= 0 && N <= (dataAvail() >> 2)) {
1703 float[] val = new float[N];
1704 for (int i=0; i<N; i++) {
1705 val[i] = readFloat();
1706 }
1707 return val;
1708 } else {
1709 return null;
1710 }
1711 }
1712
1713 public final void readFloatArray(@NonNull float[] val) {
1714 int N = readInt();
1715 if (N == val.length) {
1716 for (int i=0; i<N; i++) {
1717 val[i] = readFloat();
1718 }
1719 } else {
1720 throw new RuntimeException("bad array lengths");
1721 }
1722 }
1723
1724 public final void writeDoubleArray(@Nullable double[] val) {
1725 if (val != null) {
1726 int N = val.length;
1727 writeInt(N);
1728 for (int i=0; i<N; i++) {
1729 writeDouble(val[i]);
1730 }
1731 } else {
1732 writeInt(-1);
1733 }
1734 }
1735
1736 @Nullable
1737 public final double[] createDoubleArray() {
1738 int N = readInt();
1739 // >>3 because stored doubles are 8 bytes
1740 if (N >= 0 && N <= (dataAvail() >> 3)) {
1741 double[] val = new double[N];
1742 for (int i=0; i<N; i++) {
1743 val[i] = readDouble();
1744 }
1745 return val;
1746 } else {
1747 return null;
1748 }
1749 }
1750
1751 public final void readDoubleArray(@NonNull double[] val) {
1752 int N = readInt();
1753 if (N == val.length) {
1754 for (int i=0; i<N; i++) {
1755 val[i] = readDouble();
1756 }
1757 } else {
1758 throw new RuntimeException("bad array lengths");
1759 }
1760 }
1761
1762 public final void writeStringArray(@Nullable String[] val) {
1763 writeString16Array(val);
1764 }
1765
1766 @Nullable
1767 public final String[] createStringArray() {
1768 return createString16Array();
1769 }
1770
1771 public final void readStringArray(@NonNull String[] val) {
1772 readString16Array(val);
1773 }
1774
1775 /** {@hide} */
1776 public final void writeString8Array(@Nullable String[] val) {
1777 if (val != null) {
1778 int N = val.length;
1779 writeInt(N);
1780 for (int i=0; i<N; i++) {
1781 writeString8(val[i]);
1782 }
1783 } else {
1784 writeInt(-1);
1785 }
1786 }
1787
1788 /** {@hide} */
1789 @Nullable
1790 public final String[] createString8Array() {
1791 int N = readInt();
1792 if (N >= 0) {
1793 String[] val = new String[N];
1794 for (int i=0; i<N; i++) {
1795 val[i] = readString8();
1796 }
1797 return val;
1798 } else {
1799 return null;
1800 }
1801 }
1802
1803 /** {@hide} */
1804 public final void readString8Array(@NonNull String[] val) {
1805 int N = readInt();
1806 if (N == val.length) {
1807 for (int i=0; i<N; i++) {
1808 val[i] = readString8();
1809 }
1810 } else {
1811 throw new RuntimeException("bad array lengths");
1812 }
1813 }
1814
1815 /** {@hide} */
1816 public final void writeString16Array(@Nullable String[] val) {
1817 if (val != null) {
1818 int N = val.length;
1819 writeInt(N);
1820 for (int i=0; i<N; i++) {
1821 writeString16(val[i]);
1822 }
1823 } else {
1824 writeInt(-1);
1825 }
1826 }
1827
1828 /** {@hide} */
1829 @Nullable
1830 public final String[] createString16Array() {
1831 int N = readInt();
1832 if (N >= 0) {
1833 String[] val = new String[N];
1834 for (int i=0; i<N; i++) {
1835 val[i] = readString16();
1836 }
1837 return val;
1838 } else {
1839 return null;
1840 }
1841 }
1842
1843 /** {@hide} */
1844 public final void readString16Array(@NonNull String[] val) {
1845 int N = readInt();
1846 if (N == val.length) {
1847 for (int i=0; i<N; i++) {
1848 val[i] = readString16();
1849 }
1850 } else {
1851 throw new RuntimeException("bad array lengths");
1852 }
1853 }
1854
1855 public final void writeBinderArray(@Nullable IBinder[] val) {
1856 if (val != null) {
1857 int N = val.length;
1858 writeInt(N);
1859 for (int i=0; i<N; i++) {
1860 writeStrongBinder(val[i]);
1861 }
1862 } else {
1863 writeInt(-1);
1864 }
1865 }
1866
1867 /**
1868 * Flatten a homogeneous array containing an IInterface type into the parcel,
1869 * at the current dataPosition() and growing dataCapacity() if needed. The
1870 * type of the objects in the array must be one that implements IInterface.
1871 *
1872 * @param val The array of objects to be written.
1873 *
1874 * @see #createInterfaceArray
1875 * @see #readInterfaceArray
1876 * @see IInterface
1877 */
1878 public final <T extends IInterface> void writeInterfaceArray(
1879 @SuppressLint("ArrayReturn") @Nullable T[] val) {
1880 if (val != null) {
1881 int N = val.length;
1882 writeInt(N);
1883 for (int i=0; i<N; i++) {
1884 writeStrongInterface(val[i]);
1885 }
1886 } else {
1887 writeInt(-1);
1888 }
1889 }
1890
1891 /**
1892 * @hide
1893 */
1894 public final void writeCharSequenceArray(@Nullable CharSequence[] val) {
1895 if (val != null) {
1896 int N = val.length;
1897 writeInt(N);
1898 for (int i=0; i<N; i++) {
1899 writeCharSequence(val[i]);
1900 }
1901 } else {
1902 writeInt(-1);
1903 }
1904 }
1905
1906 /**
1907 * @hide
1908 */
1909 public final void writeCharSequenceList(@Nullable ArrayList<CharSequence> val) {
1910 if (val != null) {
1911 int N = val.size();
1912 writeInt(N);
1913 for (int i=0; i<N; i++) {
1914 writeCharSequence(val.get(i));
1915 }
1916 } else {
1917 writeInt(-1);
1918 }
1919 }
1920
1921 @Nullable
1922 public final IBinder[] createBinderArray() {
1923 int N = readInt();
1924 if (N >= 0) {
1925 IBinder[] val = new IBinder[N];
1926 for (int i=0; i<N; i++) {
1927 val[i] = readStrongBinder();
1928 }
1929 return val;
1930 } else {
1931 return null;
1932 }
1933 }
1934
1935 public final void readBinderArray(@NonNull IBinder[] val) {
1936 int N = readInt();
1937 if (N == val.length) {
1938 for (int i=0; i<N; i++) {
1939 val[i] = readStrongBinder();
1940 }
1941 } else {
1942 throw new RuntimeException("bad array lengths");
1943 }
1944 }
1945
1946 /**
1947 * Read and return a new array of T (IInterface) from the parcel.
1948 *
1949 * @return the IInterface array of type T
1950 * @param newArray a function to create an array of T with a given length
1951 * @param asInterface a function to convert IBinder object into T (IInterface)
1952 */
1953 @SuppressLint({"ArrayReturn", "NullableCollection", "SamShouldBeLast"})
1954 @Nullable
1955 public final <T extends IInterface> T[] createInterfaceArray(
1956 @NonNull IntFunction<T[]> newArray, @NonNull Function<IBinder, T> asInterface) {
1957 int N = readInt();
1958 if (N >= 0) {
1959 T[] val = newArray.apply(N);
1960 for (int i=0; i<N; i++) {
1961 val[i] = asInterface.apply(readStrongBinder());
1962 }
1963 return val;
1964 } else {
1965 return null;
1966 }
1967 }
1968
1969 /**
1970 * Read an array of T (IInterface) from a parcel.
1971 *
1972 * @param asInterface a function to convert IBinder object into T (IInterface)
1973 *
1974 * @throws BadParcelableException Throws BadParcelableException if the length of `val`
1975 * mismatches the number of items in the parcel.
1976 */
1977 public final <T extends IInterface> void readInterfaceArray(
1978 @SuppressLint("ArrayReturn") @NonNull T[] val,
1979 @NonNull Function<IBinder, T> asInterface) {
1980 int N = readInt();
1981 if (N == val.length) {
1982 for (int i=0; i<N; i++) {
1983 val[i] = asInterface.apply(readStrongBinder());
1984 }
1985 } else {
1986 throw new BadParcelableException("bad array lengths");
1987 }
1988 }
1989
1990 /**
1991 * Flatten a List containing a particular object type into the parcel, at
1992 * the current dataPosition() and growing dataCapacity() if needed. The
1993 * type of the objects in the list must be one that implements Parcelable.
1994 * Unlike the generic writeList() method, however, only the raw data of the
1995 * objects is written and not their type, so you must use the corresponding
1996 * readTypedList() to unmarshall them.
1997 *
1998 * @param val The list of objects to be written.
1999 *
2000 * @see #createTypedArrayList
2001 * @see #readTypedList
2002 * @see Parcelable
2003 */
2004 public final <T extends Parcelable> void writeTypedList(@Nullable List<T> val) {
2005 writeTypedList(val, 0);
2006 }
2007
2008 /**
2009 * Flatten a {@link SparseArray} containing a particular object type into the parcel
2010 * at the current dataPosition() and growing dataCapacity() if needed. The
2011 * type of the objects in the array must be one that implements Parcelable.
2012 * Unlike the generic {@link #writeSparseArray(SparseArray)} method, however, only
2013 * the raw data of the objects is written and not their type, so you must use the
2014 * corresponding {@link #createTypedSparseArray(Parcelable.Creator)}.
2015 *
2016 * @param val The list of objects to be written.
2017 * @param parcelableFlags The parcelable flags to use.
2018 *
2019 * @see #createTypedSparseArray(Parcelable.Creator)
2020 * @see Parcelable
2021 */
2022 public final <T extends Parcelable> void writeTypedSparseArray(@Nullable SparseArray<T> val,
2023 int parcelableFlags) {
2024 if (val == null) {
2025 writeInt(-1);
2026 return;
2027 }
2028 final int count = val.size();
2029 writeInt(count);
2030 for (int i = 0; i < count; i++) {
2031 writeInt(val.keyAt(i));
2032 writeTypedObject(val.valueAt(i), parcelableFlags);
2033 }
2034 }
2035
2036 /**
2037 * Flatten a List containing a particular object type into the parcel, at
2038 * the current dataPosition() and growing dataCapacity() if needed. The
2039 * type of the objects in the list must be one that implements Parcelable.
2040 * Unlike the generic writeList() method, however, only the raw data of the
2041 * objects is written and not their type, so you must use the corresponding
2042 * readTypedList() to unmarshall them.
2043 *
2044 * @param val The list of objects to be written.
2045 * @param parcelableFlags Contextual flags as per
2046 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2047 *
2048 * @see #createTypedArrayList
2049 * @see #readTypedList
2050 * @see Parcelable
2051 */
2052 public <T extends Parcelable> void writeTypedList(@Nullable List<T> val, int parcelableFlags) {
2053 if (val == null) {
2054 writeInt(-1);
2055 return;
2056 }
2057 int N = val.size();
2058 int i=0;
2059 writeInt(N);
2060 while (i < N) {
2061 writeTypedObject(val.get(i), parcelableFlags);
2062 i++;
2063 }
2064 }
2065
2066 /**
2067 * Flatten a List containing String objects into the parcel, at
2068 * the current dataPosition() and growing dataCapacity() if needed. They
2069 * can later be retrieved with {@link #createStringArrayList} or
2070 * {@link #readStringList}.
2071 *
2072 * @param val The list of strings to be written.
2073 *
2074 * @see #createStringArrayList
2075 * @see #readStringList
2076 */
2077 public final void writeStringList(@Nullable List<String> val) {
2078 if (val == null) {
2079 writeInt(-1);
2080 return;
2081 }
2082 int N = val.size();
2083 int i=0;
2084 writeInt(N);
2085 while (i < N) {
2086 writeString(val.get(i));
2087 i++;
2088 }
2089 }
2090
2091 /**
2092 * Flatten a List containing IBinder objects into the parcel, at
2093 * the current dataPosition() and growing dataCapacity() if needed. They
2094 * can later be retrieved with {@link #createBinderArrayList} or
2095 * {@link #readBinderList}.
2096 *
2097 * @param val The list of strings to be written.
2098 *
2099 * @see #createBinderArrayList
2100 * @see #readBinderList
2101 */
2102 public final void writeBinderList(@Nullable List<IBinder> val) {
2103 if (val == null) {
2104 writeInt(-1);
2105 return;
2106 }
2107 int N = val.size();
2108 int i=0;
2109 writeInt(N);
2110 while (i < N) {
2111 writeStrongBinder(val.get(i));
2112 i++;
2113 }
2114 }
2115
2116 /**
2117 * Flatten a {@code List} containing T (IInterface) objects into this parcel
2118 * at the current position. They can later be retrieved with
2119 * {@link #createInterfaceArrayList} or {@link #readInterfaceList}.
2120 *
2121 * @see #createInterfaceArrayList
2122 * @see #readInterfaceList
2123 */
2124 public final <T extends IInterface> void writeInterfaceList(@Nullable List<T> val) {
2125 if (val == null) {
2126 writeInt(-1);
2127 return;
2128 }
2129 int N = val.size();
2130 int i=0;
2131 writeInt(N);
2132 while (i < N) {
2133 writeStrongInterface(val.get(i));
2134 i++;
2135 }
2136 }
2137
2138 /**
2139 * Flatten a {@code List} containing arbitrary {@code Parcelable} objects into this parcel
2140 * at the current position. They can later be retrieved using
2141 * {@link #readParcelableList(List, ClassLoader)} if required.
2142 *
2143 * @see #readParcelableList(List, ClassLoader)
2144 */
2145 public final <T extends Parcelable> void writeParcelableList(@Nullable List<T> val, int flags) {
2146 if (val == null) {
2147 writeInt(-1);
2148 return;
2149 }
2150
2151 int N = val.size();
2152 int i=0;
2153 writeInt(N);
2154 while (i < N) {
2155 writeParcelable(val.get(i), flags);
2156 i++;
2157 }
2158 }
2159
2160 /**
2161 * Flatten a homogeneous array containing a particular object type into
2162 * the parcel, at
2163 * the current dataPosition() and growing dataCapacity() if needed. The
2164 * type of the objects in the array must be one that implements Parcelable.
2165 * Unlike the {@link #writeParcelableArray} method, however, only the
2166 * raw data of the objects is written and not their type, so you must use
2167 * {@link #readTypedArray} with the correct corresponding
2168 * {@link Parcelable.Creator} implementation to unmarshall them.
2169 *
2170 * @param val The array of objects to be written.
2171 * @param parcelableFlags Contextual flags as per
2172 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2173 *
2174 * @see #readTypedArray
2175 * @see #writeParcelableArray
2176 * @see Parcelable.Creator
2177 */
2178 public final <T extends Parcelable> void writeTypedArray(@Nullable T[] val,
2179 int parcelableFlags) {
2180 if (val != null) {
2181 int N = val.length;
2182 writeInt(N);
2183 for (int i = 0; i < N; i++) {
2184 writeTypedObject(val[i], parcelableFlags);
2185 }
2186 } else {
2187 writeInt(-1);
2188 }
2189 }
2190
2191 /**
2192 * Flatten the Parcelable object into the parcel.
2193 *
2194 * @param val The Parcelable object to be written.
2195 * @param parcelableFlags Contextual flags as per
2196 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2197 *
2198 * @see #readTypedObject
2199 */
2200 public final <T extends Parcelable> void writeTypedObject(@Nullable T val,
2201 int parcelableFlags) {
2202 if (val != null) {
2203 writeInt(1);
2204 val.writeToParcel(this, parcelableFlags);
2205 } else {
2206 writeInt(0);
2207 }
2208 }
2209
2210 /**
2211 * Flatten a homogeneous multi-dimensional array with fixed-size. This delegates to other
2212 * APIs to write a one-dimensional array. Use {@link #readFixedArray(Object)} or
2213 * {@link #createFixedArray(Class, int[])} with the same dimensions to unmarshal.
2214 *
2215 * @param val The array to be written.
2216 * @param parcelableFlags Contextual flags as per
2217 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2218 * Used only if val is an array of Parcelable objects.
2219 * @param dimensions an array of int representing length of each dimension. The array should be
2220 * sized with the exact size of dimensions.
2221 *
2222 * @see #readFixedArray
2223 * @see #createFixedArray createFixedArray(Class&lt;T&gt;, Parcelable.Creator&lt;S&gt;, int...)
2224 * @see #writeBooleanArray
2225 * @see #writeByteArray
2226 * @see #writeCharArray
2227 * @see #writeIntArray
2228 * @see #writeLongArray
2229 * @see #writeFloatArray
2230 * @see #writeDoubleArray
2231 * @see #writeBinderArray
2232 * @see #writeInterfaceArray
2233 * @see #writeTypedArray
2234 * @throws BadParcelableException If the array's component type is not supported or if its
2235 * size doesn't match with the given dimensions.
2236 */
2237 public <T> void writeFixedArray(@Nullable T val, int parcelableFlags,
2238 @NonNull int... dimensions) {
2239 if (val == null) {
2240 writeInt(-1);
2241 return;
2242 }
2243 writeFixedArrayInternal(val, parcelableFlags, /*index=*/0, dimensions);
2244 }
2245
2246 private <T> void writeFixedArrayInternal(T val, int parcelableFlags, int index,
2247 int[] dimensions) {
2248 if (index >= dimensions.length) {
2249 throw new BadParcelableException("Array has more dimensions than expected: "
2250 + dimensions.length);
2251 }
2252
2253 int length = dimensions[index];
2254
2255 // val should be an array of length N
2256 if (val == null) {
2257 throw new BadParcelableException("Non-null array shouldn't have a null array.");
2258 }
2259 if (!val.getClass().isArray()) {
2260 throw new BadParcelableException("Not an array: " + val);
2261 }
2262 if (Array.getLength(val) != length) {
2263 throw new BadParcelableException("bad length: expected " + length + ", but got "
2264 + Array.getLength(val));
2265 }
2266
2267 // Delegates to other writers if this is a one-dimensional array.
2268 // Otherwise, write component arrays with recursive calls.
2269
2270 final Class<?> componentType = val.getClass().getComponentType();
2271 if (!componentType.isArray() && index + 1 != dimensions.length) {
2272 throw new BadParcelableException("Array has fewer dimensions than expected: "
2273 + dimensions.length);
2274 }
2275 if (componentType == boolean.class) {
2276 writeBooleanArray((boolean[]) val);
2277 } else if (componentType == byte.class) {
2278 writeByteArray((byte[]) val);
2279 } else if (componentType == char.class) {
2280 writeCharArray((char[]) val);
2281 } else if (componentType == int.class) {
2282 writeIntArray((int[]) val);
2283 } else if (componentType == long.class) {
2284 writeLongArray((long[]) val);
2285 } else if (componentType == float.class) {
2286 writeFloatArray((float[]) val);
2287 } else if (componentType == double.class) {
2288 writeDoubleArray((double[]) val);
2289 } else if (componentType == IBinder.class) {
2290 writeBinderArray((IBinder[]) val);
2291 } else if (IInterface.class.isAssignableFrom(componentType)) {
2292 writeInterfaceArray((IInterface[]) val);
2293 } else if (Parcelable.class.isAssignableFrom(componentType)) {
2294 writeTypedArray((Parcelable[]) val, parcelableFlags);
2295 } else if (componentType.isArray()) {
2296 writeInt(length);
2297 for (int i = 0; i < length; i++) {
2298 writeFixedArrayInternal(Array.get(val, i), parcelableFlags, index + 1,
2299 dimensions);
2300 }
2301 } else {
2302 throw new BadParcelableException("unknown type for fixed-size array: " + componentType);
2303 }
2304 }
2305
2306 /**
2307 * Flatten a generic object in to a parcel. The given Object value may
2308 * currently be one of the following types:
2309 *
2310 * <ul>
2311 * <li> null
2312 * <li> String
2313 * <li> Byte
2314 * <li> Short
2315 * <li> Integer
2316 * <li> Long
2317 * <li> Float
2318 * <li> Double
2319 * <li> Boolean
2320 * <li> String[]
2321 * <li> boolean[]
2322 * <li> byte[]
2323 * <li> int[]
2324 * <li> long[]
2325 * <li> Object[] (supporting objects of the same type defined here).
2326 * <li> {@link Bundle}
2327 * <li> Map (as supported by {@link #writeMap}).
2328 * <li> Any object that implements the {@link Parcelable} protocol.
2329 * <li> Parcelable[]
2330 * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
2331 * <li> List (as supported by {@link #writeList}).
2332 * <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}).
2333 * <li> {@link IBinder}
2334 * <li> Any object that implements Serializable (but see
2335 * {@link #writeSerializable} for caveats). Note that all of the
2336 * previous types have relatively efficient implementations for
2337 * writing to a Parcel; having to rely on the generic serialization
2338 * approach is much less efficient and should be avoided whenever
2339 * possible.
2340 * </ul>
2341 *
2342 * <p class="caution">{@link Parcelable} objects are written with
2343 * {@link Parcelable#writeToParcel} using contextual flags of 0. When
2344 * serializing objects containing {@link ParcelFileDescriptor}s,
2345 * this may result in file descriptor leaks when they are returned from
2346 * Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE}
2347 * should be used).</p>
2348 */
2349 public final void writeValue(@Nullable Object v) {
2350 if (v instanceof LazyValue) {
2351 LazyValue value = (LazyValue) v;
2352 value.writeToParcel(this);
2353 return;
2354 }
2355 int type = getValueType(v);
2356 writeInt(type);
2357 if (isLengthPrefixed(type)) {
2358 // Length
2359 int length = dataPosition();
2360 writeInt(-1); // Placeholder
2361 // Object
2362 int start = dataPosition();
2363 writeValue(type, v);
2364 int end = dataPosition();
2365 // Backpatch length
2366 setDataPosition(length);
2367 writeInt(end - start);
2368 setDataPosition(end);
2369 } else {
2370 writeValue(type, v);
2371 }
2372 }
2373
2374 /** @hide */
2375 public static int getValueType(@Nullable Object v) {
2376 if (v == null) {
2377 return VAL_NULL;
2378 } else if (v instanceof String) {
2379 return VAL_STRING;
2380 } else if (v instanceof Integer) {
2381 return VAL_INTEGER;
2382 } else if (v instanceof Map) {
2383 return VAL_MAP;
2384 } else if (v instanceof Bundle) {
2385 // Must be before Parcelable
2386 return VAL_BUNDLE;
2387 } else if (v instanceof PersistableBundle) {
2388 // Must be before Parcelable
2389 return VAL_PERSISTABLEBUNDLE;
2390 } else if (v instanceof SizeF) {
2391 // Must be before Parcelable
2392 return VAL_SIZEF;
2393 } else if (v instanceof Parcelable) {
2394 // IMPOTANT: cases for classes that implement Parcelable must
2395 // come before the Parcelable case, so that their speci fic VAL_*
2396 // types will be written.
2397 return VAL_PARCELABLE;
2398 } else if (v instanceof Short) {
2399 return VAL_SHORT;
2400 } else if (v instanceof Long) {
2401 return VAL_LONG;
2402 } else if (v instanceof Float) {
2403 return VAL_FLOAT;
2404 } else if (v instanceof Double) {
2405 return VAL_DOUBLE;
2406 } else if (v instanceof Boolean) {
2407 return VAL_BOOLEAN;
2408 } else if (v instanceof CharSequence) {
2409 // Must be after String
2410 return VAL_CHARSEQUENCE;
2411 } else if (v instanceof List) {
2412 return VAL_LIST;
2413 } else if (v instanceof SparseArray) {
2414 return VAL_SPARSEARRAY;
2415 } else if (v instanceof boolean[]) {
2416 return VAL_BOOLEANARRAY;
2417 } else if (v instanceof byte[]) {
2418 return VAL_BYTEARRAY;
2419 } else if (v instanceof String[]) {
2420 return VAL_STRINGARRAY;
2421 } else if (v instanceof CharSequence[]) {
2422 // Must be after String[] and before Object[]
2423 return VAL_CHARSEQUENCEARRAY;
2424 } else if (v instanceof IBinder) {
2425 return VAL_IBINDER;
2426 } else if (v instanceof Parcelable[]) {
2427 return VAL_PARCELABLEARRAY;
2428 } else if (v instanceof int[]) {
2429 return VAL_INTARRAY;
2430 } else if (v instanceof long[]) {
2431 return VAL_LONGARRAY;
2432 } else if (v instanceof Byte) {
2433 return VAL_BYTE;
2434 } else if (v instanceof Size) {
2435 return VAL_SIZE;
2436 } else if (v instanceof double[]) {
2437 return VAL_DOUBLEARRAY;
2438 } else if (v instanceof Character) {
2439 return VAL_CHAR;
2440 } else if (v instanceof short[]) {
2441 return VAL_SHORTARRAY;
2442 } else if (v instanceof char[]) {
2443 return VAL_CHARARRAY;
2444 } else if (v instanceof float[]) {
2445 return VAL_FLOATARRAY;
2446 } else {
2447 Class<?> clazz = v.getClass();
2448 if (clazz.isArray() && clazz.getComponentType() == Object.class) {
2449 // Only pure Object[] are written here, Other arrays of non-primitive types are
2450 // handled by serialization as this does not record the component type.
2451 return VAL_OBJECTARRAY;
2452 } else if (v instanceof Serializable) {
2453 // Must be last
2454 return VAL_SERIALIZABLE;
2455 } else {
2456 throw new IllegalArgumentException("Parcel: unknown type for value " + v);
2457 }
2458 }
2459 }
2460 /**
2461 * Writes value {@code v} in the parcel. This does NOT write the int representing the type
2462 * first.
2463 *
2464 * @hide
2465 */
2466 public void writeValue(int type, @Nullable Object v) {
2467 switch (type) {
2468 case VAL_NULL:
2469 break;
2470 case VAL_STRING:
2471 writeString((String) v);
2472 break;
2473 case VAL_INTEGER:
2474 writeInt((Integer) v);
2475 break;
2476 case VAL_MAP:
2477 writeMap((Map) v);
2478 break;
2479 case VAL_BUNDLE:
2480 writeBundle((Bundle) v);
2481 break;
2482 case VAL_PERSISTABLEBUNDLE:
2483 writePersistableBundle((PersistableBundle) v);
2484 break;
2485 case VAL_PARCELABLE:
2486 writeParcelable((Parcelable) v, 0);
2487 break;
2488 case VAL_SHORT:
2489 writeInt(((Short) v).intValue());
2490 break;
2491 case VAL_LONG:
2492 writeLong((Long) v);
2493 break;
2494 case VAL_FLOAT:
2495 writeFloat((Float) v);
2496 break;
2497 case VAL_DOUBLE:
2498 writeDouble((Double) v);
2499 break;
2500 case VAL_BOOLEAN:
2501 writeInt((Boolean) v ? 1 : 0);
2502 break;
2503 case VAL_CHARSEQUENCE:
2504 writeCharSequence((CharSequence) v);
2505 break;
2506 case VAL_LIST:
2507 writeList((List) v);
2508 break;
2509 case VAL_SPARSEARRAY:
2510 writeSparseArray((SparseArray) v);
2511 break;
2512 case VAL_BOOLEANARRAY:
2513 writeBooleanArray((boolean[]) v);
2514 break;
2515 case VAL_BYTEARRAY:
2516 writeByteArray((byte[]) v);
2517 break;
2518 case VAL_STRINGARRAY:
2519 writeStringArray((String[]) v);
2520 break;
2521 case VAL_CHARSEQUENCEARRAY:
2522 writeCharSequenceArray((CharSequence[]) v);
2523 break;
2524 case VAL_IBINDER:
2525 writeStrongBinder((IBinder) v);
2526 break;
2527 case VAL_PARCELABLEARRAY:
2528 writeParcelableArray((Parcelable[]) v, 0);
2529 break;
2530 case VAL_INTARRAY:
2531 writeIntArray((int[]) v);
2532 break;
2533 case VAL_LONGARRAY:
2534 writeLongArray((long[]) v);
2535 break;
2536 case VAL_BYTE:
2537 writeInt((Byte) v);
2538 break;
2539 case VAL_SIZE:
2540 writeSize((Size) v);
2541 break;
2542 case VAL_SIZEF:
2543 writeSizeF((SizeF) v);
2544 break;
2545 case VAL_DOUBLEARRAY:
2546 writeDoubleArray((double[]) v);
2547 break;
2548 case VAL_CHAR:
2549 writeInt((Character) v);
2550 break;
2551 case VAL_SHORTARRAY:
2552 writeShortArray((short[]) v);
2553 break;
2554 case VAL_CHARARRAY:
2555 writeCharArray((char[]) v);
2556 break;
2557 case VAL_FLOATARRAY:
2558 writeFloatArray((float[]) v);
2559 break;
2560 case VAL_OBJECTARRAY:
2561 writeArray((Object[]) v);
2562 break;
2563 case VAL_SERIALIZABLE:
2564 writeSerializable((Serializable) v);
2565 break;
2566 default:
2567 throw new RuntimeException("Parcel: unable to marshal value " + v);
2568 }
2569 }
2570
2571 /**
2572 * Flatten the name of the class of the Parcelable and its contents
2573 * into the parcel.
2574 *
2575 * @param p The Parcelable object to be written.
2576 * @param parcelableFlags Contextual flags as per
2577 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2578 */
2579 public final void writeParcelable(@Nullable Parcelable p, int parcelableFlags) {
2580 if (p == null) {
2581 writeString(null);
2582 return;
2583 }
2584 writeParcelableCreator(p);
2585 p.writeToParcel(this, parcelableFlags);
2586 }
2587
2588 /**
2589 * Flatten the name of the class of the Parcelable into this Parcel.
2590 *
2591 * @param p The Parcelable object to be written.
2592 * @see #readParcelableCreator
2593 */
2594 public final void writeParcelableCreator(@NonNull Parcelable p) {
2595 String name = p.getClass().getName();
2596 writeString(name);
2597 }
2598
2599 /**
2600 * A map used by {@link #maybeWriteSquashed} to keep track of what parcelables have
2601 * been seen, and what positions they were written. The value is the absolute position of
2602 * each parcelable.
2603 */
2604 private ArrayMap<Parcelable, Integer> mWrittenSquashableParcelables;
2605
2606 private void ensureWrittenSquashableParcelables() {
2607 if (mWrittenSquashableParcelables != null) {
2608 return;
2609 }
2610 mWrittenSquashableParcelables = new ArrayMap<>();
2611 }
2612
2613 private boolean mAllowSquashing = false;
2614
2615 /**
2616 * Allow "squashing" writes in {@link #maybeWriteSquashed}. This allows subsequent calls to
2617 * {@link #maybeWriteSquashed(Parcelable)} to "squash" the same instances into one in a Parcel.
2618 *
2619 * Typically, this method is called at the beginning of {@link Parcelable#writeToParcel}. The
2620 * caller must retain the return value from this method and call {@link #restoreAllowSquashing}
2621 * with it.
2622 *
2623 * See {@link #maybeWriteSquashed(Parcelable)} for the details.
2624 *
2625 * @see #restoreAllowSquashing(boolean)
2626 * @see #maybeWriteSquashed(Parcelable)
2627 * @see #readSquashed(SquashReadHelper)
2628 *
2629 * @hide
2630 */
2631 @TestApi
2632 public boolean allowSquashing() {
2633 boolean previous = mAllowSquashing;
2634 mAllowSquashing = true;
2635 return previous;
2636 }
2637
2638 /**
2639 * @see #allowSquashing()
2640 * @hide
2641 */
2642 @TestApi
2643 public void restoreAllowSquashing(boolean previous) {
2644 mAllowSquashing = previous;
2645 if (!mAllowSquashing) {
2646 mWrittenSquashableParcelables = null;
2647 }
2648 }
2649
2650 private void resetSqaushingState() {
2651 if (mAllowSquashing) {
2652 Slog.wtf(TAG, "allowSquashing wasn't restored.");
2653 }
2654 mWrittenSquashableParcelables = null;
2655 mReadSquashableParcelables = null;
2656 mAllowSquashing = false;
2657 }
2658
2659 /**
2660 * A map used by {@link #readSquashed} to cache parcelables. It's a map from
2661 * an absolute position in a Parcel to the parcelable stored at the position.
2662 */
2663 private SparseArray<Parcelable> mReadSquashableParcelables;
2664
2665 private void ensureReadSquashableParcelables() {
2666 if (mReadSquashableParcelables != null) {
2667 return;
2668 }
2669 mReadSquashableParcelables = new SparseArray<>();
2670 }
2671
2672 /**
2673 * Write a parcelable with "squash" -- that is, when the same instance is written to the
2674 * same Parcelable multiple times, instead of writing the entire instance multiple times,
2675 * only write it once, and in subsequent writes we'll only write the offset to the original
2676 * object.
2677 *
2678 * This approach does not work of the resulting Parcel is copied with {@link #appendFrom} with
2679 * a non-zero offset, so we do not enable this behavior by default. Instead, we only enable
2680 * it between {@link #allowSquashing} and {@link #restoreAllowSquashing}, in order to make sure
2681 * we only do so within each "top level" Parcelable.
2682 *
2683 * Usage: Use this method in {@link Parcelable#writeToParcel}.
2684 * If this method returns TRUE, it's a subsequent call, and the offset is already written,
2685 * so the caller doesn't have to do anything. If this method returns FALSE, it's the first
2686 * time for the instance to be written to this parcel. The caller has to proceed with its
2687 * {@link Parcelable#writeToParcel}.
2688 *
2689 * (See {@code ApplicationInfo} for the example.)
2690 *
2691 * @param p the target Parcelable to write.
2692 *
2693 * @see #allowSquashing()
2694 * @see #restoreAllowSquashing(boolean)
2695 * @see #readSquashed(SquashReadHelper)
2696 *
2697 * @hide
2698 */
2699 public boolean maybeWriteSquashed(@NonNull Parcelable p) {
2700 if (!mAllowSquashing) {
2701 // Don't squash, and don't put it in the map either.
2702 writeInt(0);
2703 return false;
2704 }
2705 ensureWrittenSquashableParcelables();
2706 final Integer firstPos = mWrittenSquashableParcelables.get(p);
2707 if (firstPos != null) {
2708 // Already written.
2709 // Write the relative offset from the current position to the first position.
2710 final int pos = dataPosition();
2711
2712 // We want the offset from the next byte of this integer, so we need to +4.
2713 writeInt(pos - firstPos + 4);
2714 return true;
2715 }
2716 // First time seen, write a marker.
2717 writeInt(0);
2718
2719 // Remember the position.
2720 final int pos = dataPosition();
2721 mWrittenSquashableParcelables.put(p, pos);
2722
2723 // Return false and let the caller actually write the content.
2724 return false;
2725 }
2726
2727 /**
2728 * Helper function that's used by {@link #readSquashed(SquashReadHelper)}
2729 * @hide
2730 */
2731 public interface SquashReadHelper<T> {
2732 /** Read and instantiate {@code T} from a Parcel. */
2733 @NonNull
2734 T readRawParceled(@NonNull Parcel p);
2735 }
2736
2737 /**
2738 * Read a {@link Parcelable} that's written with {@link #maybeWriteSquashed}.
2739 *
2740 * @param reader a callback function that instantiates an instance from a parcel.
2741 * Typicallly, a lambda to the instructor that takes a {@link Parcel} is passed.
2742 *
2743 * @see #maybeWriteSquashed(Parcelable)
2744 *
2745 * @hide
2746 */
2747 @SuppressWarnings("unchecked")
2748 @Nullable
2749 public <T extends Parcelable> T readSquashed(SquashReadHelper<T> reader) {
2750 final int offset = readInt();
2751 final int pos = dataPosition();
2752
2753 if (offset == 0) {
2754 // First time read. Unparcel, and remember it.
2755 final T p = reader.readRawParceled(this);
2756 ensureReadSquashableParcelables();
2757 mReadSquashableParcelables.put(pos, p);
2758 return p;
2759 }
2760 // Subsequent read.
2761 final int firstAbsolutePos = pos - offset;
2762
2763 final Parcelable p = mReadSquashableParcelables.get(firstAbsolutePos);
2764 if (p == null) {
2765 final StringBuilder sb = new StringBuilder();
2766 for (int i = 0; i < mReadSquashableParcelables.size(); i++) {
2767 sb.append(mReadSquashableParcelables.keyAt(i)).append(' ');
2768 }
2769 Slog.wtfStack(TAG, "Map doesn't contain offset "
2770 + firstAbsolutePos
2771 + " : contains=" + sb.toString());
2772 }
2773 return (T) p;
2774 }
2775
2776 /**
2777 * Write a generic serializable object in to a Parcel. It is strongly
2778 * recommended that this method be avoided, since the serialization
2779 * overhead is extremely large, and this approach will be much slower than
2780 * using the other approaches to writing data in to a Parcel.
2781 */
2782 public final void writeSerializable(@Nullable Serializable s) {
2783 if (s == null) {
2784 writeString(null);
2785 return;
2786 }
2787 String name = s.getClass().getName();
2788 writeString(name);
2789
2790 ByteArrayOutputStream baos = new ByteArrayOutputStream();
2791 try {
2792 ObjectOutputStream oos = new ObjectOutputStream(baos);
2793 oos.writeObject(s);
2794 oos.close();
2795
2796 writeByteArray(baos.toByteArray());
2797 } catch (IOException ioe) {
2798 throw new BadParcelableException("Parcelable encountered "
2799 + "IOException writing serializable object (name = "
2800 + name + ")", ioe);
2801 }
2802 }
2803
2804 /** @hide For debugging purposes */
2805 public static void setStackTraceParceling(boolean enabled) {
2806 sParcelExceptionStackTrace = enabled;
2807 }
2808
2809 /**
2810 * Special function for writing an exception result at the header of
2811 * a parcel, to be used when returning an exception from a transaction.
2812 * Note that this currently only supports a few exception types; any other
2813 * exception will be re-thrown by this function as a RuntimeException
2814 * (to be caught by the system's last-resort exception handling when
2815 * dispatching a transaction).
2816 *
2817 * <p>The supported exception types are:
2818 * <ul>
2819 * <li>{@link BadParcelableException}
2820 * <li>{@link IllegalArgumentException}
2821 * <li>{@link IllegalStateException}
2822 * <li>{@link NullPointerException}
2823 * <li>{@link SecurityException}
2824 * <li>{@link UnsupportedOperationException}
2825 * <li>{@link NetworkOnMainThreadException}
2826 * </ul>
2827 *
2828 * @param e The Exception to be written.
2829 *
2830 * @see #writeNoException
2831 * @see #readException
2832 */
2833 public final void writeException(@NonNull Exception e) {
2834 AppOpsManager.prefixParcelWithAppOpsIfNeeded(this);
2835
2836 int code = getExceptionCode(e);
2837 writeInt(code);
2838 StrictMode.clearGatheredViolations();
2839 if (code == 0) {
2840 if (e instanceof RuntimeException) {
2841 throw (RuntimeException) e;
2842 }
2843 throw new RuntimeException(e);
2844 }
2845 writeString(e.getMessage());
2846 final long timeNow = sParcelExceptionStackTrace ? SystemClock.elapsedRealtime() : 0;
2847 if (sParcelExceptionStackTrace && (timeNow - sLastWriteExceptionStackTrace
2848 > WRITE_EXCEPTION_STACK_TRACE_THRESHOLD_MS)) {
2849 sLastWriteExceptionStackTrace = timeNow;
2850 writeStackTrace(e);
2851 } else {
2852 writeInt(0);
2853 }
2854 switch (code) {
2855 case EX_SERVICE_SPECIFIC:
2856 writeInt(((ServiceSpecificException) e).errorCode);
2857 break;
2858 case EX_PARCELABLE:
2859 // Write parceled exception prefixed by length
2860 final int sizePosition = dataPosition();
2861 writeInt(0);
2862 writeParcelable((Parcelable) e, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
2863 final int payloadPosition = dataPosition();
2864 setDataPosition(sizePosition);
2865 writeInt(payloadPosition - sizePosition);
2866 setDataPosition(payloadPosition);
2867 break;
2868 }
2869 }
2870
2871 /** @hide */
2872 public static int getExceptionCode(@NonNull Throwable e) {
2873 int code = 0;
2874 if (e instanceof Parcelable
2875 && (e.getClass().getClassLoader() == Parcelable.class.getClassLoader())) {
2876 // We only send Parcelable exceptions that are in the
2877 // BootClassLoader to ensure that the receiver can unpack them
2878 code = EX_PARCELABLE;
2879 } else if (e instanceof SecurityException) {
2880 code = EX_SECURITY;
2881 } else if (e instanceof BadParcelableException) {
2882 code = EX_BAD_PARCELABLE;
2883 } else if (e instanceof IllegalArgumentException) {
2884 code = EX_ILLEGAL_ARGUMENT;
2885 } else if (e instanceof NullPointerException) {
2886 code = EX_NULL_POINTER;
2887 } else if (e instanceof IllegalStateException) {
2888 code = EX_ILLEGAL_STATE;
2889 } else if (e instanceof NetworkOnMainThreadException) {
2890 code = EX_NETWORK_MAIN_THREAD;
2891 } else if (e instanceof UnsupportedOperationException) {
2892 code = EX_UNSUPPORTED_OPERATION;
2893 } else if (e instanceof ServiceSpecificException) {
2894 code = EX_SERVICE_SPECIFIC;
2895 }
2896 return code;
2897 }
2898
2899 /** @hide */
2900 public void writeStackTrace(@NonNull Throwable e) {
2901 final int sizePosition = dataPosition();
2902 writeInt(0); // Header size will be filled in later
2903 StackTraceElement[] stackTrace = e.getStackTrace();
2904 final int truncatedSize = Math.min(stackTrace.length, 5);
2905 StringBuilder sb = new StringBuilder();
2906 for (int i = 0; i < truncatedSize; i++) {
2907 sb.append("\tat ").append(stackTrace[i]).append('\n');
2908 }
2909 writeString(sb.toString());
2910 final int payloadPosition = dataPosition();
2911 setDataPosition(sizePosition);
2912 // Write stack trace header size. Used in native side to skip the header
2913 writeInt(payloadPosition - sizePosition);
2914 setDataPosition(payloadPosition);
2915 }
2916
2917 /**
2918 * Special function for writing information at the front of the Parcel
2919 * indicating that no exception occurred.
2920 *
2921 * @see #writeException
2922 * @see #readException
2923 */
2924 public final void writeNoException() {
2925 AppOpsManager.prefixParcelWithAppOpsIfNeeded(this);
2926
2927 // Despite the name of this function ("write no exception"),
2928 // it should instead be thought of as "write the RPC response
2929 // header", but because this function name is written out by
2930 // the AIDL compiler, we're not going to rename it.
2931 //
2932 // The response header, in the non-exception case (see also
2933 // writeException above, also called by the AIDL compiler), is
2934 // either a 0 (the default case), or EX_HAS_STRICTMODE_REPLY_HEADER if
2935 // StrictMode has gathered up violations that have occurred
2936 // during a Binder call, in which case we write out the number
2937 // of violations and their details, serialized, before the
2938 // actual RPC respons data. The receiving end of this is
2939 // readException(), below.
2940 if (StrictMode.hasGatheredViolations()) {
2941 writeInt(EX_HAS_STRICTMODE_REPLY_HEADER);
2942 final int sizePosition = dataPosition();
2943 writeInt(0); // total size of fat header, to be filled in later
2944 StrictMode.writeGatheredViolationsToParcel(this);
2945 final int payloadPosition = dataPosition();
2946 setDataPosition(sizePosition);
2947 writeInt(payloadPosition - sizePosition); // header size
2948 setDataPosition(payloadPosition);
2949 } else {
2950 writeInt(0);
2951 }
2952 }
2953
2954 /**
2955 * Special function for reading an exception result from the header of
2956 * a parcel, to be used after receiving the result of a transaction. This
2957 * will throw the exception for you if it had been written to the Parcel,
2958 * otherwise return and let you read the normal result data from the Parcel.
2959 *
2960 * @see #writeException
2961 * @see #writeNoException
2962 */
2963 public final void readException() {
2964 int code = readExceptionCode();
2965 if (code != 0) {
2966 String msg = readString();
2967 readException(code, msg);
2968 }
2969 }
2970
2971 /**
2972 * Parses the header of a Binder call's response Parcel and
2973 * returns the exception code. Deals with lite or fat headers.
2974 * In the common successful case, this header is generally zero.
2975 * In less common cases, it's a small negative number and will be
2976 * followed by an error string.
2977 *
2978 * This exists purely for android.database.DatabaseUtils and
2979 * insulating it from having to handle fat headers as returned by
2980 * e.g. StrictMode-induced RPC responses.
2981 *
2982 * @hide
2983 */
2984 @UnsupportedAppUsage
2985 @TestApi
2986 public final int readExceptionCode() {
2987 int code = readInt();
2988 if (code == EX_HAS_NOTED_APPOPS_REPLY_HEADER) {
2989 AppOpsManager.readAndLogNotedAppops(this);
2990 // Read next header or real exception if there is no more header
2991 code = readInt();
2992 }
2993
2994 if (code == EX_HAS_STRICTMODE_REPLY_HEADER) {
2995 int headerSize = readInt();
2996 if (headerSize == 0) {
2997 Log.e(TAG, "Unexpected zero-sized Parcel reply header.");
2998 } else {
2999 // Currently the only thing in the header is StrictMode stacks,
3000 // but discussions around event/RPC tracing suggest we might
3001 // put that here too. If so, switch on sub-header tags here.
3002 // But for now, just parse out the StrictMode stuff.
3003 StrictMode.readAndHandleBinderCallViolations(this);
3004 }
3005 // And fat response headers are currently only used when
3006 // there are no exceptions, so return no error:
3007 return 0;
3008 }
3009 return code;
3010 }
3011
3012 /**
3013 * Throw an exception with the given message. Not intended for use
3014 * outside the Parcel class.
3015 *
3016 * @param code Used to determine which exception class to throw.
3017 * @param msg The exception message.
3018 */
3019 public final void readException(int code, String msg) {
3020 String remoteStackTrace = null;
3021 final int remoteStackPayloadSize = readInt();
3022 if (remoteStackPayloadSize > 0) {
3023 remoteStackTrace = readString();
3024 }
3025 Exception e = createException(code, msg);
3026 // Attach remote stack trace if availalble
3027 if (remoteStackTrace != null) {
3028 RemoteException cause = new RemoteException(
3029 "Remote stack trace:\n" + remoteStackTrace, null, false, false);
3030 ExceptionUtils.appendCause(e, cause);
3031 }
3032 SneakyThrow.sneakyThrow(e);
3033 }
3034
3035 /**
3036 * Creates an exception with the given message.
3037 *
3038 * @param code Used to determine which exception class to throw.
3039 * @param msg The exception message.
3040 */
3041 private Exception createException(int code, String msg) {
3042 Exception exception = createExceptionOrNull(code, msg);
3043 return exception != null
3044 ? exception
3045 : new RuntimeException("Unknown exception code: " + code + " msg " + msg);
3046 }
3047
3048 /** @hide */
3049 public Exception createExceptionOrNull(int code, String msg) {
3050 switch (code) {
3051 case EX_PARCELABLE:
3052 if (readInt() > 0) {
3053 return (Exception) readParcelable(Parcelable.class.getClassLoader());
3054 } else {
3055 return new RuntimeException(msg + " [missing Parcelable]");
3056 }
3057 case EX_SECURITY:
3058 return new SecurityException(msg);
3059 case EX_BAD_PARCELABLE:
3060 return new BadParcelableException(msg);
3061 case EX_ILLEGAL_ARGUMENT:
3062 return new IllegalArgumentException(msg);
3063 case EX_NULL_POINTER:
3064 return new NullPointerException(msg);
3065 case EX_ILLEGAL_STATE:
3066 return new IllegalStateException(msg);
3067 case EX_NETWORK_MAIN_THREAD:
3068 return new NetworkOnMainThreadException();
3069 case EX_UNSUPPORTED_OPERATION:
3070 return new UnsupportedOperationException(msg);
3071 case EX_SERVICE_SPECIFIC:
3072 return new ServiceSpecificException(readInt(), msg);
3073 default:
3074 return null;
3075 }
3076 }
3077
3078 /**
3079 * Read an integer value from the parcel at the current dataPosition().
3080 */
3081 public final int readInt() {
3082 return nativeReadInt(mNativePtr);
3083 }
3084
3085 /**
3086 * Read a long integer value from the parcel at the current dataPosition().
3087 */
3088 public final long readLong() {
3089 return nativeReadLong(mNativePtr);
3090 }
3091
3092 /**
3093 * Read a floating point value from the parcel at the current
3094 * dataPosition().
3095 */
3096 public final float readFloat() {
3097 return nativeReadFloat(mNativePtr);
3098 }
3099
3100 /**
3101 * Read a double precision floating point value from the parcel at the
3102 * current dataPosition().
3103 */
3104 public final double readDouble() {
3105 return nativeReadDouble(mNativePtr);
3106 }
3107
3108 /**
3109 * Read a string value from the parcel at the current dataPosition().
3110 */
3111 @Nullable
3112 public final String readString() {
3113 return readString16();
3114 }
3115
3116 /** {@hide} */
3117 public final @Nullable String readString8() {
3118 return mReadWriteHelper.readString8(this);
3119 }
3120
3121 /** {@hide} */
3122 public final @Nullable String readString16() {
3123 return mReadWriteHelper.readString16(this);
3124 }
3125
3126 /**
3127 * Read a string without going though a {@link ReadWriteHelper}. Subclasses of
3128 * {@link ReadWriteHelper} must use this method instead of {@link #readString} to avoid
3129 * infinity recursive calls.
3130 *
3131 * @hide
3132 */
3133 public @Nullable String readStringNoHelper() {
3134 return readString16NoHelper();
3135 }
3136
3137 /** {@hide} */
3138 public @Nullable String readString8NoHelper() {
3139 return nativeReadString8(mNativePtr);
3140 }
3141
3142 /** {@hide} */
3143 public @Nullable String readString16NoHelper() {
3144 return nativeReadString16(mNativePtr);
3145 }
3146
3147 /**
3148 * Read a boolean value from the parcel at the current dataPosition().
3149 */
3150 public final boolean readBoolean() {
3151 return readInt() != 0;
3152 }
3153
3154 /**
3155 * Read a CharSequence value from the parcel at the current dataPosition().
3156 * @hide
3157 */
3158 @UnsupportedAppUsage
3159 @Nullable
3160 public final CharSequence readCharSequence() {
3161 return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
3162 }
3163
3164 /**
3165 * Read an object from the parcel at the current dataPosition().
3166 */
3167 public final IBinder readStrongBinder() {
3168 final IBinder result = nativeReadStrongBinder(mNativePtr);
3169
3170 // If it's a reply from a method with @PropagateAllowBlocking, then inherit allow-blocking
3171 // from the object that returned it.
3172 if (result != null && hasFlags(
3173 FLAG_IS_REPLY_FROM_BLOCKING_ALLOWED_OBJECT | FLAG_PROPAGATE_ALLOW_BLOCKING)) {
3174 Binder.allowBlocking(result);
3175 }
3176 return result;
3177 }
3178
3179 /**
3180 * Read a FileDescriptor from the parcel at the current dataPosition().
3181 */
3182 public final ParcelFileDescriptor readFileDescriptor() {
3183 FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
3184 return fd != null ? new ParcelFileDescriptor(fd) : null;
3185 }
3186
3187 /** {@hide} */
3188 @UnsupportedAppUsage
3189 public final FileDescriptor readRawFileDescriptor() {
3190 return nativeReadFileDescriptor(mNativePtr);
3191 }
3192
3193 /**
3194 * {@hide}
3195 * Read and return a new array of FileDescriptors from the parcel.
3196 * @return the FileDescriptor array, or null if the array is null.
3197 **/
3198 @Nullable
3199 public final FileDescriptor[] createRawFileDescriptorArray() {
3200 int N = readInt();
3201 if (N < 0) {
3202 return null;
3203 }
3204 FileDescriptor[] f = new FileDescriptor[N];
3205 for (int i = 0; i < N; i++) {
3206 f[i] = readRawFileDescriptor();
3207 }
3208 return f;
3209 }
3210
3211 /**
3212 * {@hide}
3213 * Read an array of FileDescriptors from a parcel.
3214 * The passed array must be exactly the length of the array in the parcel.
3215 * @return the FileDescriptor array, or null if the array is null.
3216 **/
3217 public final void readRawFileDescriptorArray(FileDescriptor[] val) {
3218 int N = readInt();
3219 if (N == val.length) {
3220 for (int i=0; i<N; i++) {
3221 val[i] = readRawFileDescriptor();
3222 }
3223 } else {
3224 throw new RuntimeException("bad array lengths");
3225 }
3226 }
3227
3228 /**
3229 * Read a byte value from the parcel at the current dataPosition().
3230 */
3231 public final byte readByte() {
3232 return (byte)(readInt() & 0xff);
3233 }
3234
3235 /**
3236 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
3237 * been written with {@link #writeBundle}. Read into an existing Map object
3238 * from the parcel at the current dataPosition().
3239 *
3240 * @deprecated Consider using {@link #readBundle(ClassLoader)} as stated above, in case this
3241 * method is still preferred use the type-safer version {@link #readMap(Map, ClassLoader,
3242 * Class, Class)} starting from Android {@link Build.VERSION_CODES#TIRAMISU}.
3243 */
3244 @Deprecated
3245 public final void readMap(@NonNull Map outVal, @Nullable ClassLoader loader) {
3246 readMapInternal(outVal, loader, /* clazzKey */ null, /* clazzValue */ null);
3247 }
3248
3249 /**
3250 * Same as {@link #readMap(Map, ClassLoader)} but accepts {@code clazzKey} and
3251 * {@code clazzValue} parameter as the types required for each key and value pair.
3252 *
3253 * @throws BadParcelableException If the item to be deserialized is not an instance of that
3254 * class or any of its children class
3255 */
3256 public <K, V> void readMap(@NonNull Map<? super K, ? super V> outVal,
3257 @Nullable ClassLoader loader, @NonNull Class<K> clazzKey,
3258 @NonNull Class<V> clazzValue) {
3259 Objects.requireNonNull(clazzKey);
3260 Objects.requireNonNull(clazzValue);
3261 readMapInternal(outVal, loader, clazzKey, clazzValue);
3262 }
3263
3264 /**
3265 * Read into an existing List object from the parcel at the current
3266 * dataPosition(), using the given class loader to load any enclosed
3267 * Parcelables. If it is null, the default class loader is used.
3268 *
3269 * @deprecated Use the type-safer version {@link #readList(List, ClassLoader, Class)} starting
3270 * from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the format to
3271 * use {@link #readTypedList(List, Parcelable.Creator)} if possible (eg. if the items'
3272 * class is final) since this is also more performant. Note that changing to the latter
3273 * also requires changing the writes.
3274 */
3275 @Deprecated
3276 public final void readList(@NonNull List outVal, @Nullable ClassLoader loader) {
3277 int N = readInt();
3278 readListInternal(outVal, N, loader, /* clazz */ null);
3279 }
3280
3281 /**
3282 * Same as {@link #readList(List, ClassLoader)} but accepts {@code clazz} parameter as
3283 * the type required for each item.
3284 *
3285 * <p><b>Warning: </b> if the list contains items implementing the {@link Parcelable} interface,
3286 * the class that implements {@link Parcelable} has to be the immediately
3287 * enclosing class of the runtime type of its CREATOR field (that is,
3288 * {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
3289 * otherwise this method might throw an exception. If the Parcelable class does not enclose the
3290 * CREATOR, use the deprecated {@link #readList(List, ClassLoader)} instead.
3291 *
3292 * @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
3293 * is not an instance of that class or any of its children classes or there was an error
3294 * trying to instantiate an element.
3295 */
3296 public <T> void readList(@NonNull List<? super T> outVal,
3297 @Nullable ClassLoader loader, @NonNull Class<T> clazz) {
3298 Objects.requireNonNull(clazz);
3299 int n = readInt();
3300 readListInternal(outVal, n, loader, clazz);
3301 }
3302
3303 /**
3304 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
3305 * been written with {@link #writeBundle}. Read and return a new HashMap
3306 * object from the parcel at the current dataPosition(), using the given
3307 * class loader to load any enclosed Parcelables. Returns null if
3308 * the previously written map object was null.
3309 *
3310 * @deprecated Consider using {@link #readBundle(ClassLoader)} as stated above, in case this
3311 * method is still preferred use the type-safer version {@link #readHashMap(ClassLoader,
3312 * Class, Class)} starting from Android {@link Build.VERSION_CODES#TIRAMISU}.
3313 */
3314 @Deprecated
3315 @Nullable
3316 public HashMap readHashMap(@Nullable ClassLoader loader) {
3317 return readHashMapInternal(loader, /* clazzKey */ null, /* clazzValue */ null);
3318 }
3319
3320 /**
3321 * Same as {@link #readHashMap(ClassLoader)} but accepts {@code clazzKey} and
3322 * {@code clazzValue} parameter as the types required for each key and value pair.
3323 *
3324 * @throws BadParcelableException if the item to be deserialized is not an instance of that
3325 * class or any of its children class
3326 */
3327 @SuppressLint({"ConcreteCollection", "NullableCollection"})
3328 @Nullable
3329 public <K, V> HashMap<K, V> readHashMap(@Nullable ClassLoader loader,
3330 @NonNull Class<? extends K> clazzKey, @NonNull Class<? extends V> clazzValue) {
3331 Objects.requireNonNull(clazzKey);
3332 Objects.requireNonNull(clazzValue);
3333 return readHashMapInternal(loader, clazzKey, clazzValue);
3334 }
3335
3336 /**
3337 * Read and return a new Bundle object from the parcel at the current
3338 * dataPosition(). Returns null if the previously written Bundle object was
3339 * null.
3340 */
3341 @Nullable
3342 public final Bundle readBundle() {
3343 return readBundle(null);
3344 }
3345
3346 /**
3347 * Read and return a new Bundle object from the parcel at the current
3348 * dataPosition(), using the given class loader to initialize the class
3349 * loader of the Bundle for later retrieval of Parcelable objects.
3350 * Returns null if the previously written Bundle object was null.
3351 */
3352 @Nullable
3353 public final Bundle readBundle(@Nullable ClassLoader loader) {
3354 int length = readInt();
3355 if (length < 0) {
3356 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
3357 return null;
3358 }
3359
3360 final Bundle bundle = new Bundle(this, length);
3361 if (loader != null) {
3362 bundle.setClassLoader(loader);
3363 }
3364 return bundle;
3365 }
3366
3367 /**
3368 * Read and return a new Bundle object from the parcel at the current
3369 * dataPosition(). Returns null if the previously written Bundle object was
3370 * null.
3371 */
3372 @Nullable
3373 public final PersistableBundle readPersistableBundle() {
3374 return readPersistableBundle(null);
3375 }
3376
3377 /**
3378 * Read and return a new Bundle object from the parcel at the current
3379 * dataPosition(), using the given class loader to initialize the class
3380 * loader of the Bundle for later retrieval of Parcelable objects.
3381 * Returns null if the previously written Bundle object was null.
3382 */
3383 @Nullable
3384 public final PersistableBundle readPersistableBundle(@Nullable ClassLoader loader) {
3385 int length = readInt();
3386 if (length < 0) {
3387 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
3388 return null;
3389 }
3390
3391 final PersistableBundle bundle = new PersistableBundle(this, length);
3392 if (loader != null) {
3393 bundle.setClassLoader(loader);
3394 }
3395 return bundle;
3396 }
3397
3398 /**
3399 * Read a Size from the parcel at the current dataPosition().
3400 */
3401 @NonNull
3402 public final Size readSize() {
3403 final int width = readInt();
3404 final int height = readInt();
3405 return new Size(width, height);
3406 }
3407
3408 /**
3409 * Read a SizeF from the parcel at the current dataPosition().
3410 */
3411 @NonNull
3412 public final SizeF readSizeF() {
3413 final float width = readFloat();
3414 final float height = readFloat();
3415 return new SizeF(width, height);
3416 }
3417
3418 /**
3419 * Read and return a byte[] object from the parcel.
3420 */
3421 @Nullable
3422 public final byte[] createByteArray() {
3423 return nativeCreateByteArray(mNativePtr);
3424 }
3425
3426 /**
3427 * Read a byte[] object from the parcel and copy it into the
3428 * given byte array.
3429 */
3430 public final void readByteArray(@NonNull byte[] val) {
3431 boolean valid = nativeReadByteArray(mNativePtr, val, (val != null) ? val.length : 0);
3432 if (!valid) {
3433 throw new RuntimeException("bad array lengths");
3434 }
3435 }
3436
3437 /**
3438 * Read a blob of data from the parcel and return it as a byte array.
3439 * @see #writeBlob(byte[], int, int)
3440 */
3441 @Nullable
3442 public final byte[] readBlob() {
3443 return nativeReadBlob(mNativePtr);
3444 }
3445
3446 /**
3447 * Read and return a String[] object from the parcel.
3448 * {@hide}
3449 */
3450 @UnsupportedAppUsage
3451 @Nullable
3452 public final String[] readStringArray() {
3453 return createString16Array();
3454 }
3455
3456 /**
3457 * Read and return a CharSequence[] object from the parcel.
3458 * {@hide}
3459 */
3460 @Nullable
3461 public final CharSequence[] readCharSequenceArray() {
3462 CharSequence[] array = null;
3463
3464 int length = readInt();
3465 if (length >= 0)
3466 {
3467 array = new CharSequence[length];
3468
3469 for (int i = 0 ; i < length ; i++)
3470 {
3471 array[i] = readCharSequence();
3472 }
3473 }
3474
3475 return array;
3476 }
3477
3478 /**
3479 * Read and return an ArrayList&lt;CharSequence&gt; object from the parcel.
3480 * {@hide}
3481 */
3482 @Nullable
3483 public final ArrayList<CharSequence> readCharSequenceList() {
3484 ArrayList<CharSequence> array = null;
3485
3486 int length = readInt();
3487 if (length >= 0) {
3488 array = new ArrayList<CharSequence>(length);
3489
3490 for (int i = 0 ; i < length ; i++) {
3491 array.add(readCharSequence());
3492 }
3493 }
3494
3495 return array;
3496 }
3497
3498 /**
3499 * Read and return a new ArrayList object from the parcel at the current
3500 * dataPosition(). Returns null if the previously written list object was
3501 * null. The given class loader will be used to load any enclosed
3502 * Parcelables.
3503 *
3504 * @deprecated Use the type-safer version {@link #readArrayList(ClassLoader, Class)} starting
3505 * from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the format to
3506 * use {@link #createTypedArrayList(Parcelable.Creator)} if possible (eg. if the items'
3507 * class is final) since this is also more performant. Note that changing to the latter
3508 * also requires changing the writes.
3509 */
3510 @Deprecated
3511 @Nullable
3512 public ArrayList readArrayList(@Nullable ClassLoader loader) {
3513 return readArrayListInternal(loader, /* clazz */ null);
3514 }
3515
3516 /**
3517 * Same as {@link #readArrayList(ClassLoader)} but accepts {@code clazz} parameter as
3518 * the type required for each item.
3519 *
3520 * <p><b>Warning: </b> if the list contains items implementing the {@link Parcelable} interface,
3521 * the class that implements {@link Parcelable} has to be the immediately
3522 * enclosing class of the runtime type of its CREATOR field (that is,
3523 * {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
3524 * otherwise this method might throw an exception. If the Parcelable class does not enclose the
3525 * CREATOR, use the deprecated {@link #readArrayList(ClassLoader)} instead.
3526 *
3527 * @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
3528 * is not an instance of that class or any of its children classes or there was an error
3529 * trying to instantiate an element.
3530 */
3531 @SuppressLint({"ConcreteCollection", "NullableCollection"})
3532 @Nullable
3533 public <T> ArrayList<T> readArrayList(@Nullable ClassLoader loader,
3534 @NonNull Class<? extends T> clazz) {
3535 Objects.requireNonNull(clazz);
3536 return readArrayListInternal(loader, clazz);
3537 }
3538
3539 /**
3540 * Read and return a new Object array from the parcel at the current
3541 * dataPosition(). Returns null if the previously written array was
3542 * null. The given class loader will be used to load any enclosed
3543 * Parcelables.
3544 *
3545 * @deprecated Use the type-safer version {@link #readArray(ClassLoader, Class)} starting from
3546 * Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the format to use
3547 * {@link #createTypedArray(Parcelable.Creator)} if possible (eg. if the items' class is
3548 * final) since this is also more performant. Note that changing to the latter also
3549 * requires changing the writes.
3550 */
3551 @Deprecated
3552 @Nullable
3553 public Object[] readArray(@Nullable ClassLoader loader) {
3554 return readArrayInternal(loader, /* clazz */ null);
3555 }
3556
3557 /**
3558 * Same as {@link #readArray(ClassLoader)} but accepts {@code clazz} parameter as
3559 * the type required for each item.
3560 *
3561 * <p><b>Warning: </b> if the list contains items implementing the {@link Parcelable} interface,
3562 * the class that implements {@link Parcelable} has to be the immediately
3563 * enclosing class of the runtime type of its CREATOR field (that is,
3564 * {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
3565 * otherwise this method might throw an exception. If the Parcelable class does not enclose the
3566 * CREATOR, use the deprecated {@link #readArray(ClassLoader)} instead.
3567 *
3568 * @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
3569 * is not an instance of that class or any of its children classes or there was an error
3570 * trying to instantiate an element.
3571 */
3572 @SuppressLint({"ArrayReturn", "NullableCollection"})
3573 @Nullable
3574 public <T> T[] readArray(@Nullable ClassLoader loader, @NonNull Class<T> clazz) {
3575 Objects.requireNonNull(clazz);
3576 return readArrayInternal(loader, clazz);
3577 }
3578
3579 /**
3580 * Read and return a new SparseArray object from the parcel at the current
3581 * dataPosition(). Returns null if the previously written list object was
3582 * null. The given class loader will be used to load any enclosed
3583 * Parcelables.
3584 *
3585 * @deprecated Use the type-safer version {@link #readSparseArray(ClassLoader, Class)} starting
3586 * from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the format to
3587 * use {@link #createTypedSparseArray(Parcelable.Creator)} if possible (eg. if the items'
3588 * class is final) since this is also more performant. Note that changing to the latter
3589 * also requires changing the writes.
3590 */
3591 @Deprecated
3592 @Nullable
3593 public <T> SparseArray<T> readSparseArray(@Nullable ClassLoader loader) {
3594 return readSparseArrayInternal(loader, /* clazz */ null);
3595 }
3596
3597 /**
3598 * Same as {@link #readSparseArray(ClassLoader)} but accepts {@code clazz} parameter as
3599 * the type required for each item.
3600 *
3601 * <p><b>Warning: </b> if the list contains items implementing the {@link Parcelable} interface,
3602 * the class that implements {@link Parcelable} has to be the immediately
3603 * enclosing class of the runtime type of its CREATOR field (that is,
3604 * {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
3605 * otherwise this method might throw an exception. If the Parcelable class does not enclose the
3606 * CREATOR, use the deprecated {@link #readSparseArray(ClassLoader)} instead.
3607 *
3608 * @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
3609 * is not an instance of that class or any of its children classes or there was an error
3610 * trying to instantiate an element.
3611 */
3612 @Nullable
3613 public <T> SparseArray<T> readSparseArray(@Nullable ClassLoader loader,
3614 @NonNull Class<? extends T> clazz) {
3615 Objects.requireNonNull(clazz);
3616 return readSparseArrayInternal(loader, clazz);
3617 }
3618
3619 /**
3620 * Read and return a new SparseBooleanArray object from the parcel at the current
3621 * dataPosition(). Returns null if the previously written list object was
3622 * null.
3623 */
3624 @Nullable
3625 public final SparseBooleanArray readSparseBooleanArray() {
3626 int N = readInt();
3627 if (N < 0) {
3628 return null;
3629 }
3630 SparseBooleanArray sa = new SparseBooleanArray(N);
3631 readSparseBooleanArrayInternal(sa, N);
3632 return sa;
3633 }
3634
3635 /**
3636 * Read and return a new SparseIntArray object from the parcel at the current
3637 * dataPosition(). Returns null if the previously written array object was null.
3638 * @hide
3639 */
3640 @Nullable
3641 public final SparseIntArray readSparseIntArray() {
3642 int N = readInt();
3643 if (N < 0) {
3644 return null;
3645 }
3646 SparseIntArray sa = new SparseIntArray(N);
3647 readSparseIntArrayInternal(sa, N);
3648 return sa;
3649 }
3650
3651 /**
3652 * Read and return a new ArrayList containing a particular object type from
3653 * the parcel that was written with {@link #writeTypedList} at the
3654 * current dataPosition(). Returns null if the
3655 * previously written list object was null. The list <em>must</em> have
3656 * previously been written via {@link #writeTypedList} with the same object
3657 * type.
3658 *
3659 * @return A newly created ArrayList containing objects with the same data
3660 * as those that were previously written.
3661 *
3662 * @see #writeTypedList
3663 */
3664 @Nullable
3665 public final <T> ArrayList<T> createTypedArrayList(@NonNull Parcelable.Creator<T> c) {
3666 int N = readInt();
3667 if (N < 0) {
3668 return null;
3669 }
3670 ArrayList<T> l = new ArrayList<T>(N);
3671 while (N > 0) {
3672 l.add(readTypedObject(c));
3673 N--;
3674 }
3675 return l;
3676 }
3677
3678 /**
3679 * Read into the given List items containing a particular object type
3680 * that were written with {@link #writeTypedList} at the
3681 * current dataPosition(). The list <em>must</em> have
3682 * previously been written via {@link #writeTypedList} with the same object
3683 * type.
3684 *
3685 * @return A newly created ArrayList containing objects with the same data
3686 * as those that were previously written.
3687 *
3688 * @see #writeTypedList
3689 */
3690 public final <T> void readTypedList(@NonNull List<T> list, @NonNull Parcelable.Creator<T> c) {
3691 int M = list.size();
3692 int N = readInt();
3693 int i = 0;
3694 for (; i < M && i < N; i++) {
3695 list.set(i, readTypedObject(c));
3696 }
3697 for (; i<N; i++) {
3698 list.add(readTypedObject(c));
3699 }
3700 for (; i<M; i++) {
3701 list.remove(N);
3702 }
3703 }
3704
3705 /**
3706 * Read into a new {@link SparseArray} items containing a particular object type
3707 * that were written with {@link #writeTypedSparseArray(SparseArray, int)} at the
3708 * current dataPosition(). The list <em>must</em> have previously been written
3709 * via {@link #writeTypedSparseArray(SparseArray, int)} with the same object type.
3710 *
3711 * @param creator The creator to use when for instantiation.
3712 *
3713 * @return A newly created {@link SparseArray} containing objects with the same data
3714 * as those that were previously written.
3715 *
3716 * @see #writeTypedSparseArray(SparseArray, int)
3717 */
3718 public final @Nullable <T extends Parcelable> SparseArray<T> createTypedSparseArray(
3719 @NonNull Parcelable.Creator<T> creator) {
3720 final int count = readInt();
3721 if (count < 0) {
3722 return null;
3723 }
3724 final SparseArray<T> array = new SparseArray<>(count);
3725 for (int i = 0; i < count; i++) {
3726 final int index = readInt();
3727 final T value = readTypedObject(creator);
3728 array.append(index, value);
3729 }
3730 return array;
3731 }
3732
3733 /**
3734 * Read into a new {@link ArrayMap} with string keys items containing a particular
3735 * object type that were written with {@link #writeTypedArrayMap(ArrayMap, int)} at the
3736 * current dataPosition(). The list <em>must</em> have previously been written
3737 * via {@link #writeTypedArrayMap(ArrayMap, int)} with the same object type.
3738 *
3739 * @param creator The creator to use when for instantiation.
3740 *
3741 * @return A newly created {@link ArrayMap} containing objects with the same data
3742 * as those that were previously written.
3743 *
3744 * @see #writeTypedArrayMap(ArrayMap, int)
3745 */
3746 public final @Nullable <T extends Parcelable> ArrayMap<String, T> createTypedArrayMap(
3747 @NonNull Parcelable.Creator<T> creator) {
3748 final int count = readInt();
3749 if (count < 0) {
3750 return null;
3751 }
3752 final ArrayMap<String, T> map = new ArrayMap<>(count);
3753 for (int i = 0; i < count; i++) {
3754 final String key = readString();
3755 final T value = readTypedObject(creator);
3756 map.append(key, value);
3757 }
3758 return map;
3759 }
3760
3761 /**
3762 * Read and return a new ArrayList containing String objects from
3763 * the parcel that was written with {@link #writeStringList} at the
3764 * current dataPosition(). Returns null if the
3765 * previously written list object was null.
3766 *
3767 * @return A newly created ArrayList containing strings with the same data
3768 * as those that were previously written.
3769 *
3770 * @see #writeStringList
3771 */
3772 @Nullable
3773 public final ArrayList<String> createStringArrayList() {
3774 int N = readInt();
3775 if (N < 0) {
3776 return null;
3777 }
3778 ArrayList<String> l = new ArrayList<String>(N);
3779 while (N > 0) {
3780 l.add(readString());
3781 N--;
3782 }
3783 return l;
3784 }
3785
3786 /**
3787 * Read and return a new ArrayList containing IBinder objects from
3788 * the parcel that was written with {@link #writeBinderList} at the
3789 * current dataPosition(). Returns null if the
3790 * previously written list object was null.
3791 *
3792 * @return A newly created ArrayList containing strings with the same data
3793 * as those that were previously written.
3794 *
3795 * @see #writeBinderList
3796 */
3797 @Nullable
3798 public final ArrayList<IBinder> createBinderArrayList() {
3799 int N = readInt();
3800 if (N < 0) {
3801 return null;
3802 }
3803 ArrayList<IBinder> l = new ArrayList<IBinder>(N);
3804 while (N > 0) {
3805 l.add(readStrongBinder());
3806 N--;
3807 }
3808 return l;
3809 }
3810
3811 /**
3812 * Read and return a new ArrayList containing T (IInterface) objects from
3813 * the parcel that was written with {@link #writeInterfaceList} at the
3814 * current dataPosition(). Returns null if the
3815 * previously written list object was null.
3816 *
3817 * @return A newly created ArrayList containing T (IInterface)
3818 *
3819 * @see #writeInterfaceList
3820 */
3821 @SuppressLint({"ConcreteCollection", "NullableCollection"})
3822 @Nullable
3823 public final <T extends IInterface> ArrayList<T> createInterfaceArrayList(
3824 @NonNull Function<IBinder, T> asInterface) {
3825 int N = readInt();
3826 if (N < 0) {
3827 return null;
3828 }
3829 ArrayList<T> l = new ArrayList<T>(N);
3830 while (N > 0) {
3831 l.add(asInterface.apply(readStrongBinder()));
3832 N--;
3833 }
3834 return l;
3835 }
3836
3837 /**
3838 * Read into the given List items String objects that were written with
3839 * {@link #writeStringList} at the current dataPosition().
3840 *
3841 * @see #writeStringList
3842 */
3843 public final void readStringList(@NonNull List<String> list) {
3844 int M = list.size();
3845 int N = readInt();
3846 int i = 0;
3847 for (; i < M && i < N; i++) {
3848 list.set(i, readString());
3849 }
3850 for (; i<N; i++) {
3851 list.add(readString());
3852 }
3853 for (; i<M; i++) {
3854 list.remove(N);
3855 }
3856 }
3857
3858 /**
3859 * Read into the given List items IBinder objects that were written with
3860 * {@link #writeBinderList} at the current dataPosition().
3861 *
3862 * @see #writeBinderList
3863 */
3864 public final void readBinderList(@NonNull List<IBinder> list) {
3865 int M = list.size();
3866 int N = readInt();
3867 int i = 0;
3868 for (; i < M && i < N; i++) {
3869 list.set(i, readStrongBinder());
3870 }
3871 for (; i<N; i++) {
3872 list.add(readStrongBinder());
3873 }
3874 for (; i<M; i++) {
3875 list.remove(N);
3876 }
3877 }
3878
3879 /**
3880 * Read into the given List items IInterface objects that were written with
3881 * {@link #writeInterfaceList} at the current dataPosition().
3882 *
3883 * @see #writeInterfaceList
3884 */
3885 public final <T extends IInterface> void readInterfaceList(@NonNull List<T> list,
3886 @NonNull Function<IBinder, T> asInterface) {
3887 int M = list.size();
3888 int N = readInt();
3889 int i = 0;
3890 for (; i < M && i < N; i++) {
3891 list.set(i, asInterface.apply(readStrongBinder()));
3892 }
3893 for (; i<N; i++) {
3894 list.add(asInterface.apply(readStrongBinder()));
3895 }
3896 for (; i<M; i++) {
3897 list.remove(N);
3898 }
3899 }
3900
3901 /**
3902 * Read the list of {@code Parcelable} objects at the current data position into the
3903 * given {@code list}. The contents of the {@code list} are replaced. If the serialized
3904 * list was {@code null}, {@code list} is cleared.
3905 *
3906 * @see #writeParcelableList(List, int)
3907 *
3908 * @deprecated Use the type-safer version {@link #readParcelableList(List, ClassLoader, Class)}
3909 * starting from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the
3910 * format to use {@link #readTypedList(List, Parcelable.Creator)} if possible (eg. if the
3911 * items' class is final) since this is also more performant. Note that changing to the
3912 * latter also requires changing the writes.
3913 */
3914 @Deprecated
3915 @NonNull
3916 public final <T extends Parcelable> List<T> readParcelableList(@NonNull List<T> list,
3917 @Nullable ClassLoader cl) {
3918 return readParcelableListInternal(list, cl, /*clazz*/ null);
3919 }
3920
3921 /**
3922 * Same as {@link #readParcelableList(List, ClassLoader)} but accepts {@code clazz} parameter as
3923 * the type required for each item.
3924 *
3925 * <p><b>Warning: </b> if the list contains items implementing the {@link Parcelable} interface,
3926 * the class that implements {@link Parcelable} has to be the immediately
3927 * enclosing class of the runtime type of its CREATOR field (that is,
3928 * {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
3929 * otherwise this method might throw an exception. If the Parcelable class does not enclose the
3930 * CREATOR, use the deprecated {@link #readParcelableList(List, ClassLoader)} instead.
3931 *
3932 * @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
3933 * is not an instance of that class or any of its children classes or there was an error
3934 * trying to instantiate an element.
3935 */
3936 @NonNull
3937 public <T> List<T> readParcelableList(@NonNull List<T> list,
3938 @Nullable ClassLoader cl, @NonNull Class<? extends T> clazz) {
3939 Objects.requireNonNull(list);
3940 Objects.requireNonNull(clazz);
3941 return readParcelableListInternal(list, cl, clazz);
3942 }
3943
3944 /**
3945 * @param clazz The type of the object expected or {@code null} for performing no checks.
3946 */
3947 @NonNull
3948 private <T> List<T> readParcelableListInternal(@NonNull List<T> list,
3949 @Nullable ClassLoader cl, @Nullable Class<? extends T> clazz) {
3950 final int n = readInt();
3951 if (n == -1) {
3952 list.clear();
3953 return list;
3954 }
3955
3956 final int m = list.size();
3957 int i = 0;
3958 for (; i < m && i < n; i++) {
3959 list.set(i, (T) readParcelableInternal(cl, clazz));
3960 }
3961 for (; i < n; i++) {
3962 list.add((T) readParcelableInternal(cl, clazz));
3963 }
3964 for (; i < m; i++) {
3965 list.remove(n);
3966 }
3967 return list;
3968 }
3969
3970 /**
3971 * Read and return a new array containing a particular object type from
3972 * the parcel at the current dataPosition(). Returns null if the
3973 * previously written array was null. The array <em>must</em> have
3974 * previously been written via {@link #writeTypedArray} with the same
3975 * object type.
3976 *
3977 * @return A newly created array containing objects with the same data
3978 * as those that were previously written.
3979 *
3980 * @see #writeTypedArray
3981 */
3982 @Nullable
3983 public final <T> T[] createTypedArray(@NonNull Parcelable.Creator<T> c) {
3984 int N = readInt();
3985 if (N < 0) {
3986 return null;
3987 }
3988 T[] l = c.newArray(N);
3989 for (int i=0; i<N; i++) {
3990 l[i] = readTypedObject(c);
3991 }
3992 return l;
3993 }
3994
3995 public final <T> void readTypedArray(@NonNull T[] val, @NonNull Parcelable.Creator<T> c) {
3996 int N = readInt();
3997 if (N == val.length) {
3998 for (int i=0; i<N; i++) {
3999 val[i] = readTypedObject(c);
4000 }
4001 } else {
4002 throw new RuntimeException("bad array lengths");
4003 }
4004 }
4005
4006 /**
4007 * @deprecated
4008 * @hide
4009 */
4010 @Deprecated
4011 public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
4012 return createTypedArray(c);
4013 }
4014
4015 /**
4016 * Read and return a typed Parcelable object from a parcel.
4017 * Returns null if the previous written object was null.
4018 * The object <em>must</em> have previous been written via
4019 * {@link #writeTypedObject} with the same object type.
4020 *
4021 * @return A newly created object of the type that was previously
4022 * written.
4023 *
4024 * @see #writeTypedObject
4025 */
4026 @Nullable
4027 public final <T> T readTypedObject(@NonNull Parcelable.Creator<T> c) {
4028 if (readInt() != 0) {
4029 return c.createFromParcel(this);
4030 } else {
4031 return null;
4032 }
4033 }
4034
4035 /**
4036 * Read a new multi-dimensional array from a parcel. If you want to read Parcelable or
4037 * IInterface values, use {@link #readFixedArray(Object, Parcelable.Creator)} or
4038 * {@link #readFixedArray(Object, Function)}.
4039 * @param val the destination array to hold the read values.
4040 *
4041 * @see #writeTypedArray
4042 * @see #readBooleanArray
4043 * @see #readByteArray
4044 * @see #readCharArray
4045 * @see #readIntArray
4046 * @see #readLongArray
4047 * @see #readFloatArray
4048 * @see #readDoubleArray
4049 * @see #readBinderArray
4050 * @see #readInterfaceArray
4051 * @see #readTypedArray
4052 */
4053 public <T> void readFixedArray(@NonNull T val) {
4054 Class<?> componentType = val.getClass().getComponentType();
4055 if (componentType == boolean.class) {
4056 readBooleanArray((boolean[]) val);
4057 } else if (componentType == byte.class) {
4058 readByteArray((byte[]) val);
4059 } else if (componentType == char.class) {
4060 readCharArray((char[]) val);
4061 } else if (componentType == int.class) {
4062 readIntArray((int[]) val);
4063 } else if (componentType == long.class) {
4064 readLongArray((long[]) val);
4065 } else if (componentType == float.class) {
4066 readFloatArray((float[]) val);
4067 } else if (componentType == double.class) {
4068 readDoubleArray((double[]) val);
4069 } else if (componentType == IBinder.class) {
4070 readBinderArray((IBinder[]) val);
4071 } else if (componentType.isArray()) {
4072 int length = readInt();
4073 if (length != Array.getLength(val)) {
4074 throw new BadParcelableException("Bad length: expected " + Array.getLength(val)
4075 + ", but got " + length);
4076 }
4077 for (int i = 0; i < length; i++) {
4078 readFixedArray(Array.get(val, i));
4079 }
4080 } else {
4081 throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
4082 }
4083 }
4084
4085 /**
4086 * Read a new multi-dimensional array of typed interfaces from a parcel.
4087 * If you want to read Parcelable values, use
4088 * {@link #readFixedArray(Object, Parcelable.Creator)}. For values of other types, use
4089 * {@link #readFixedArray(Object)}.
4090 * @param val the destination array to hold the read values.
4091 */
4092 public <T, S extends IInterface> void readFixedArray(@NonNull T val,
4093 @NonNull Function<IBinder, S> asInterface) {
4094 Class<?> componentType = val.getClass().getComponentType();
4095 if (IInterface.class.isAssignableFrom(componentType)) {
4096 readInterfaceArray((S[]) val, asInterface);
4097 } else if (componentType.isArray()) {
4098 int length = readInt();
4099 if (length != Array.getLength(val)) {
4100 throw new BadParcelableException("Bad length: expected " + Array.getLength(val)
4101 + ", but got " + length);
4102 }
4103 for (int i = 0; i < length; i++) {
4104 readFixedArray(Array.get(val, i), asInterface);
4105 }
4106 } else {
4107 throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
4108 }
4109 }
4110
4111 /**
4112 * Read a new multi-dimensional array of typed parcelables from a parcel.
4113 * If you want to read IInterface values, use
4114 * {@link #readFixedArray(Object, Function)}. For values of other types, use
4115 * {@link #readFixedArray(Object)}.
4116 * @param val the destination array to hold the read values.
4117 */
4118 public <T, S extends Parcelable> void readFixedArray(@NonNull T val,
4119 @NonNull Parcelable.Creator<S> c) {
4120 Class<?> componentType = val.getClass().getComponentType();
4121 if (Parcelable.class.isAssignableFrom(componentType)) {
4122 readTypedArray((S[]) val, c);
4123 } else if (componentType.isArray()) {
4124 int length = readInt();
4125 if (length != Array.getLength(val)) {
4126 throw new BadParcelableException("Bad length: expected " + Array.getLength(val)
4127 + ", but got " + length);
4128 }
4129 for (int i = 0; i < length; i++) {
4130 readFixedArray(Array.get(val, i), c);
4131 }
4132 } else {
4133 throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
4134 }
4135 }
4136
4137 private void ensureClassHasExpectedDimensions(@NonNull Class<?> cls, int numDimension) {
4138 if (numDimension <= 0) {
4139 throw new BadParcelableException("Fixed-size array should have dimensions.");
4140 }
4141
4142 for (int i = 0; i < numDimension; i++) {
4143 if (!cls.isArray()) {
4144 throw new BadParcelableException("Array has fewer dimensions than expected: "
4145 + numDimension);
4146 }
4147 cls = cls.getComponentType();
4148 }
4149 if (cls.isArray()) {
4150 throw new BadParcelableException("Array has more dimensions than expected: "
4151 + numDimension);
4152 }
4153 }
4154
4155 /**
4156 * Read and return a new multi-dimensional array from a parcel. Returns null if the
4157 * previously written array object is null. If you want to read Parcelable or
4158 * IInterface values, use {@link #createFixedArray(Class, Parcelable.Creator, int[])} or
4159 * {@link #createFixedArray(Class, Function, int[])}.
4160 * @param cls the Class object for the target array type. (e.g. int[][].class)
4161 * @param dimensions an array of int representing length of each dimension.
4162 *
4163 * @see #writeTypedArray
4164 * @see #createBooleanArray
4165 * @see #createByteArray
4166 * @see #createCharArray
4167 * @see #createIntArray
4168 * @see #createLongArray
4169 * @see #createFloatArray
4170 * @see #createDoubleArray
4171 * @see #createBinderArray
4172 * @see #createInterfaceArray
4173 * @see #createTypedArray
4174 */
4175 @Nullable
4176 public <T> T createFixedArray(@NonNull Class<T> cls, @NonNull int... dimensions) {
4177 // Check if type matches with dimensions
4178 // If type is one-dimensional array, delegate to other creators
4179 // Otherwise, create an multi-dimensional array at once and then fill it with readFixedArray
4180
4181 ensureClassHasExpectedDimensions(cls, dimensions.length);
4182
4183 T val = null;
4184 final Class<?> componentType = cls.getComponentType();
4185 if (componentType == boolean.class) {
4186 val = (T) createBooleanArray();
4187 } else if (componentType == byte.class) {
4188 val = (T) createByteArray();
4189 } else if (componentType == char.class) {
4190 val = (T) createCharArray();
4191 } else if (componentType == int.class) {
4192 val = (T) createIntArray();
4193 } else if (componentType == long.class) {
4194 val = (T) createLongArray();
4195 } else if (componentType == float.class) {
4196 val = (T) createFloatArray();
4197 } else if (componentType == double.class) {
4198 val = (T) createDoubleArray();
4199 } else if (componentType == IBinder.class) {
4200 val = (T) createBinderArray();
4201 } else if (componentType.isArray()) {
4202 int length = readInt();
4203 if (length < 0) {
4204 return null;
4205 }
4206 if (length != dimensions[0]) {
4207 throw new BadParcelableException("Bad length: expected " + dimensions[0]
4208 + ", but got " + length);
4209 }
4210
4211 // Create a multi-dimensional array with an innermost component type and dimensions
4212 Class<?> innermost = componentType.getComponentType();
4213 while (innermost.isArray()) {
4214 innermost = innermost.getComponentType();
4215 }
4216 val = (T) Array.newInstance(innermost, dimensions);
4217 for (int i = 0; i < length; i++) {
4218 readFixedArray(Array.get(val, i));
4219 }
4220 return val;
4221 } else {
4222 throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
4223 }
4224
4225 // Check if val is null (which is OK) or has the expected size.
4226 // This check doesn't have to be multi-dimensional because multi-dimensional arrays
4227 // are created with expected dimensions.
4228 if (val != null && Array.getLength(val) != dimensions[0]) {
4229 throw new BadParcelableException("Bad length: expected " + dimensions[0] + ", but got "
4230 + Array.getLength(val));
4231 }
4232 return val;
4233 }
4234
4235 /**
4236 * Read and return a new multi-dimensional array of typed interfaces from a parcel.
4237 * Returns null if the previously written array object is null. If you want to read
4238 * Parcelable values, use {@link #createFixedArray(Class, Parcelable.Creator, int[])}.
4239 * For values of other types use {@link #createFixedArray(Class, int[])}.
4240 * @param cls the Class object for the target array type. (e.g. IFoo[][].class)
4241 * @param dimensions an array of int representing length of each dimension.
4242 */
4243 @Nullable
4244 public <T, S extends IInterface> T createFixedArray(@NonNull Class<T> cls,
4245 @NonNull Function<IBinder, S> asInterface, @NonNull int... dimensions) {
4246 // Check if type matches with dimensions
4247 // If type is one-dimensional array, delegate to other creators
4248 // Otherwise, create an multi-dimensional array at once and then fill it with readFixedArray
4249
4250 ensureClassHasExpectedDimensions(cls, dimensions.length);
4251
4252 T val = null;
4253 final Class<?> componentType = cls.getComponentType();
4254 if (IInterface.class.isAssignableFrom(componentType)) {
4255 val = (T) createInterfaceArray(n -> (S[]) Array.newInstance(componentType, n),
4256 asInterface);
4257 } else if (componentType.isArray()) {
4258 int length = readInt();
4259 if (length < 0) {
4260 return null;
4261 }
4262 if (length != dimensions[0]) {
4263 throw new BadParcelableException("Bad length: expected " + dimensions[0]
4264 + ", but got " + length);
4265 }
4266
4267 // Create a multi-dimensional array with an innermost component type and dimensions
4268 Class<?> innermost = componentType.getComponentType();
4269 while (innermost.isArray()) {
4270 innermost = innermost.getComponentType();
4271 }
4272 val = (T) Array.newInstance(innermost, dimensions);
4273 for (int i = 0; i < length; i++) {
4274 readFixedArray(Array.get(val, i), asInterface);
4275 }
4276 return val;
4277 } else {
4278 throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
4279 }
4280
4281 // Check if val is null (which is OK) or has the expected size.
4282 // This check doesn't have to be multi-dimensional because multi-dimensional arrays
4283 // are created with expected dimensions.
4284 if (val != null && Array.getLength(val) != dimensions[0]) {
4285 throw new BadParcelableException("Bad length: expected " + dimensions[0] + ", but got "
4286 + Array.getLength(val));
4287 }
4288 return val;
4289 }
4290
4291 /**
4292 * Read and return a new multi-dimensional array of typed parcelables from a parcel.
4293 * Returns null if the previously written array object is null. If you want to read
4294 * IInterface values, use {@link #createFixedArray(Class, Function, int[])}.
4295 * For values of other types use {@link #createFixedArray(Class, int[])}.
4296 * @param cls the Class object for the target array type. (e.g. Foo[][].class)
4297 * @param dimensions an array of int representing length of each dimension.
4298 */
4299 @Nullable
4300 public <T, S extends Parcelable> T createFixedArray(@NonNull Class<T> cls,
4301 @NonNull Parcelable.Creator<S> c, @NonNull int... dimensions) {
4302 // Check if type matches with dimensions
4303 // If type is one-dimensional array, delegate to other creators
4304 // Otherwise, create an multi-dimensional array at once and then fill it with readFixedArray
4305
4306 ensureClassHasExpectedDimensions(cls, dimensions.length);
4307
4308 T val = null;
4309 final Class<?> componentType = cls.getComponentType();
4310 if (Parcelable.class.isAssignableFrom(componentType)) {
4311 val = (T) createTypedArray(c);
4312 } else if (componentType.isArray()) {
4313 int length = readInt();
4314 if (length < 0) {
4315 return null;
4316 }
4317 if (length != dimensions[0]) {
4318 throw new BadParcelableException("Bad length: expected " + dimensions[0]
4319 + ", but got " + length);
4320 }
4321
4322 // Create a multi-dimensional array with an innermost component type and dimensions
4323 Class<?> innermost = componentType.getComponentType();
4324 while (innermost.isArray()) {
4325 innermost = innermost.getComponentType();
4326 }
4327 val = (T) Array.newInstance(innermost, dimensions);
4328 for (int i = 0; i < length; i++) {
4329 readFixedArray(Array.get(val, i), c);
4330 }
4331 return val;
4332 } else {
4333 throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
4334 }
4335
4336 // Check if val is null (which is OK) or has the expected size.
4337 // This check doesn't have to be multi-dimensional because multi-dimensional arrays
4338 // are created with expected dimensions.
4339 if (val != null && Array.getLength(val) != dimensions[0]) {
4340 throw new BadParcelableException("Bad length: expected " + dimensions[0] + ", but got "
4341 + Array.getLength(val));
4342 }
4343 return val;
4344 }
4345
4346 /**
4347 * Write a heterogeneous array of Parcelable objects into the Parcel.
4348 * Each object in the array is written along with its class name, so
4349 * that the correct class can later be instantiated. As a result, this
4350 * has significantly more overhead than {@link #writeTypedArray}, but will
4351 * correctly handle an array containing more than one type of object.
4352 *
4353 * @param value The array of objects to be written.
4354 * @param parcelableFlags Contextual flags as per
4355 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
4356 *
4357 * @see #writeTypedArray
4358 */
4359 public final <T extends Parcelable> void writeParcelableArray(@Nullable T[] value,
4360 int parcelableFlags) {
4361 if (value != null) {
4362 int N = value.length;
4363 writeInt(N);
4364 for (int i=0; i<N; i++) {
4365 writeParcelable(value[i], parcelableFlags);
4366 }
4367 } else {
4368 writeInt(-1);
4369 }
4370 }
4371
4372 /**
4373 * Read a typed object from a parcel. The given class loader will be
4374 * used to load any enclosed Parcelables. If it is null, the default class
4375 * loader will be used.
4376 */
4377 @Nullable
4378 public final Object readValue(@Nullable ClassLoader loader) {
4379 return readValue(loader, /* clazz */ null);
4380 }
4381
4382
4383 /**
4384 * @see #readValue(int, ClassLoader, Class, Class[])
4385 */
4386 @Nullable
4387 private <T> T readValue(@Nullable ClassLoader loader, @Nullable Class<T> clazz,
4388 @Nullable Class<?>... itemTypes) {
4389 int type = readInt();
4390 final T object;
4391 if (isLengthPrefixed(type)) {
4392 int length = readInt();
4393 int start = dataPosition();
4394 object = readValue(type, loader, clazz, itemTypes);
4395 int actual = dataPosition() - start;
4396 if (actual != length) {
4397 Slog.wtfStack(TAG,
4398 "Unparcelling of " + object + " of type " + Parcel.valueTypeToString(type)
4399 + " consumed " + actual + " bytes, but " + length + " expected.");
4400 }
4401 } else {
4402 object = readValue(type, loader, clazz, itemTypes);
4403 }
4404 return object;
4405 }
4406
4407 /**
4408 * This will return a {@link BiFunction} for length-prefixed types that deserializes the object
4409 * when {@link BiFunction#apply} is called (the arguments correspond to the ones of {@link
4410 * #readValue(int, ClassLoader, Class, Class[])} after the class loader), for other types it
4411 * will return the object itself.
4412 *
4413 * <p>After calling {@link BiFunction#apply} the parcel cursor will not change. Note that you
4414 * shouldn't recycle the parcel, not at least until all objects have been retrieved. No
4415 * synchronization attempts are made.
4416 *
4417 * </p>The function returned implements {@link #equals(Object)} and {@link #hashCode()}. Two
4418 * function objects are equal if either of the following is true:
4419 * <ul>
4420 * <li>{@link BiFunction#apply} has been called on both and both objects returned are equal.
4421 * <li>{@link BiFunction#apply} hasn't been called on either one and everything below is true:
4422 * <ul>
4423 * <li>The {@code loader} parameters used to retrieve each are equal.
4424 * <li>They both have the same type.
4425 * <li>They have the same payload length.
4426 * <li>Their binary content is the same.
4427 * </ul>
4428 * </ul>
4429 *
4430 * @hide
4431 */
4432 @Nullable
4433 public Object readLazyValue(@Nullable ClassLoader loader) {
4434 int start = dataPosition();
4435 int type = readInt();
4436 if (isLengthPrefixed(type)) {
4437 int objectLength = readInt();
4438 if (objectLength < 0) {
4439 return null;
4440 }
4441 int end = MathUtils.addOrThrow(dataPosition(), objectLength);
4442 int valueLength = end - start;
4443 setDataPosition(end);
4444 return new LazyValue(this, start, valueLength, type, loader);
4445 } else {
4446 return readValue(type, loader, /* clazz */ null);
4447 }
4448 }
4449
4450
4451 private static final class LazyValue implements BiFunction<Class<?>, Class<?>[], Object> {
4452 /**
4453 * | 4B | 4B |
4454 * mSource = Parcel{... | type | length | object | ...}
4455 * a b c d
4456 * length = d - c
4457 * mPosition = a
4458 * mLength = d - a
4459 */
4460 private final int mPosition;
4461 private final int mLength;
4462 private final int mType;
4463 @Nullable private final ClassLoader mLoader;
4464 @Nullable private Object mObject;
4465
4466 /**
4467 * This goes from non-null to null once. Always check the nullability of this object before
4468 * performing any operations, either involving itself or mObject since the happens-before
4469 * established by this volatile will guarantee visibility of either. We can assume this
4470 * parcel won't change anymore.
4471 */
4472 @Nullable private volatile Parcel mSource;
4473
4474 LazyValue(Parcel source, int position, int length, int type, @Nullable ClassLoader loader) {
4475 mSource = requireNonNull(source);
4476 mPosition = position;
4477 mLength = length;
4478 mType = type;
4479 mLoader = loader;
4480 }
4481
4482 @Override
4483 public Object apply(@Nullable Class<?> clazz, @Nullable Class<?>[] itemTypes) {
4484 Parcel source = mSource;
4485 if (source != null) {
4486 synchronized (source) {
4487 // Check mSource != null guarantees callers won't ever see different objects.
4488 if (mSource != null) {
4489 int restore = source.dataPosition();
4490 try {
4491 source.setDataPosition(mPosition);
4492 mObject = source.readValue(mLoader, clazz, itemTypes);
4493 } finally {
4494 source.setDataPosition(restore);
4495 }
4496 mSource = null;
4497 }
4498 }
4499 }
4500 return mObject;
4501 }
4502
4503 public void writeToParcel(Parcel out) {
4504 Parcel source = mSource;
4505 if (source != null) {
4506 out.appendFrom(source, mPosition, mLength);
4507 } else {
4508 out.writeValue(mObject);
4509 }
4510 }
4511
4512 public boolean hasFileDescriptors() {
4513 Parcel source = mSource;
4514 return (source != null)
4515 ? source.hasFileDescriptors(mPosition, mLength)
4516 : Parcel.hasFileDescriptors(mObject);
4517 }
4518
4519 @Override
4520 public String toString() {
4521 return (mSource != null)
4522 ? "Supplier{" + valueTypeToString(mType) + "@" + mPosition + "+" + mLength + '}'
4523 : "Supplier{" + mObject + "}";
4524 }
4525
4526 /**
4527 * We're checking if the *lazy value* is equal to another one, not if the *object*
4528 * represented by the lazy value is equal to the other one. So, if there are two lazy values
4529 * and one of them has been deserialized but the other hasn't this will always return false.
4530 */
4531 @Override
4532 public boolean equals(Object other) {
4533 if (this == other) {
4534 return true;
4535 }
4536 if (!(other instanceof LazyValue)) {
4537 return false;
4538 }
4539 LazyValue value = (LazyValue) other;
4540 // Check if they are either both serialized or both deserialized.
4541 Parcel source = mSource;
4542 Parcel otherSource = value.mSource;
4543 if ((source == null) != (otherSource == null)) {
4544 return false;
4545 }
4546 // If both are deserialized, compare the live objects.
4547 if (source == null) {
4548 // Note that here it's guaranteed that both mObject references contain valid values
4549 // (possibly null) since mSource will have provided the memory barrier for those and
4550 // once deserialized we never go back to serialized state.
4551 return Objects.equals(mObject, value.mObject);
4552 }
4553 // Better safely fail here since this could mean we get different objects.
4554 if (!Objects.equals(mLoader, value.mLoader)) {
4555 return false;
4556 }
4557 // Otherwise compare metadata prior to comparing payload.
4558 if (mType != value.mType || mLength != value.mLength) {
4559 return false;
4560 }
4561 // Finally we compare the payload.
4562 return Parcel.compareData(source, mPosition, otherSource, value.mPosition, mLength);
4563 }
4564
4565 @Override
4566 public int hashCode() {
4567 // Accessing mSource first to provide memory barrier for mObject
4568 return Objects.hash(mSource == null, mObject, mLoader, mType, mLength);
4569 }
4570 }
4571
4572 /** Same as {@link #readValue(ClassLoader, Class, Class[])} without any item types. */
4573 private <T> T readValue(int type, @Nullable ClassLoader loader, @Nullable Class<T> clazz) {
4574 // Avoids allocating Class[0] array
4575 return readValue(type, loader, clazz, (Class<?>[]) null);
4576 }
4577
4578 /**
4579 * Reads a value from the parcel of type {@code type}. Does NOT read the int representing the
4580 * type first.
4581 *
4582 * @param clazz The type of the object expected or {@code null} for performing no checks.
4583 * @param itemTypes If the value is a container, these represent the item types (eg. for a list
4584 * it's the item type, for a map, it's the key type, followed by the value
4585 * type).
4586 */
4587 @SuppressWarnings("unchecked")
4588 @Nullable
4589 private <T> T readValue(int type, @Nullable ClassLoader loader, @Nullable Class<T> clazz,
4590 @Nullable Class<?>... itemTypes) {
4591 final Object object;
4592 switch (type) {
4593 case VAL_NULL:
4594 object = null;
4595 break;
4596
4597 case VAL_STRING:
4598 object = readString();
4599 break;
4600
4601 case VAL_INTEGER:
4602 object = readInt();
4603 break;
4604
4605 case VAL_MAP:
4606 checkTypeToUnparcel(clazz, HashMap.class);
4607 Class<?> keyType = ArrayUtils.getOrNull(itemTypes, 0);
4608 Class<?> valueType = ArrayUtils.getOrNull(itemTypes, 1);
4609 checkArgument((keyType == null) == (valueType == null));
4610 object = readHashMapInternal(loader, keyType, valueType);
4611 break;
4612
4613 case VAL_PARCELABLE:
4614 object = readParcelableInternal(loader, clazz);
4615 break;
4616
4617 case VAL_SHORT:
4618 object = (short) readInt();
4619 break;
4620
4621 case VAL_LONG:
4622 object = readLong();
4623 break;
4624
4625 case VAL_FLOAT:
4626 object = readFloat();
4627 break;
4628
4629 case VAL_DOUBLE:
4630 object = readDouble();
4631 break;
4632
4633 case VAL_BOOLEAN:
4634 object = readInt() == 1;
4635 break;
4636
4637 case VAL_CHARSEQUENCE:
4638 object = readCharSequence();
4639 break;
4640
4641 case VAL_LIST: {
4642 checkTypeToUnparcel(clazz, ArrayList.class);
4643 Class<?> itemType = ArrayUtils.getOrNull(itemTypes, 0);
4644 object = readArrayListInternal(loader, itemType);
4645 break;
4646 }
4647 case VAL_BOOLEANARRAY:
4648 object = createBooleanArray();
4649 break;
4650
4651 case VAL_BYTEARRAY:
4652 object = createByteArray();
4653 break;
4654
4655 case VAL_STRINGARRAY:
4656 object = readStringArray();
4657 break;
4658
4659 case VAL_CHARSEQUENCEARRAY:
4660 object = readCharSequenceArray();
4661 break;
4662
4663 case VAL_IBINDER:
4664 object = readStrongBinder();
4665 break;
4666
4667 case VAL_OBJECTARRAY: {
4668 Class<?> itemType = ArrayUtils.getOrNull(itemTypes, 0);
4669 checkArrayTypeToUnparcel(clazz, (itemType != null) ? itemType : Object.class);
4670 object = readArrayInternal(loader, itemType);
4671 break;
4672 }
4673 case VAL_INTARRAY:
4674 object = createIntArray();
4675 break;
4676
4677 case VAL_LONGARRAY:
4678 object = createLongArray();
4679 break;
4680
4681 case VAL_BYTE:
4682 object = readByte();
4683 break;
4684
4685 case VAL_SERIALIZABLE:
4686 object = readSerializableInternal(loader, clazz);
4687 break;
4688
4689 case VAL_PARCELABLEARRAY: {
4690 Class<?> itemType = ArrayUtils.getOrNull(itemTypes, 0);
4691 checkArrayTypeToUnparcel(clazz, (itemType != null) ? itemType : Parcelable.class);
4692 object = readParcelableArrayInternal(loader, itemType);
4693 break;
4694 }
4695 case VAL_SPARSEARRAY: {
4696 checkTypeToUnparcel(clazz, SparseArray.class);
4697 Class<?> itemType = ArrayUtils.getOrNull(itemTypes, 0);
4698 object = readSparseArrayInternal(loader, itemType);
4699 break;
4700 }
4701 case VAL_SPARSEBOOLEANARRAY:
4702 object = readSparseBooleanArray();
4703 break;
4704
4705 case VAL_BUNDLE:
4706 object = readBundle(loader); // loading will be deferred
4707 break;
4708
4709 case VAL_PERSISTABLEBUNDLE:
4710 object = readPersistableBundle(loader);
4711 break;
4712
4713 case VAL_SIZE:
4714 object = readSize();
4715 break;
4716
4717 case VAL_SIZEF:
4718 object = readSizeF();
4719 break;
4720
4721 case VAL_DOUBLEARRAY:
4722 object = createDoubleArray();
4723 break;
4724
4725 case VAL_CHAR:
4726 object = (char) readInt();
4727 break;
4728
4729 case VAL_SHORTARRAY:
4730 object = createShortArray();
4731 break;
4732
4733 case VAL_CHARARRAY:
4734 object = createCharArray();
4735 break;
4736
4737 case VAL_FLOATARRAY:
4738 object = createFloatArray();
4739 break;
4740
4741 default:
4742 int off = dataPosition() - 4;
4743 throw new BadParcelableException(
4744 "Parcel " + this + ": Unmarshalling unknown type code " + type
4745 + " at offset " + off);
4746 }
4747 if (object != null && clazz != null && !clazz.isInstance(object)) {
4748 throw new BadTypeParcelableException("Unparcelled object " + object
4749 + " is not an instance of required class " + clazz.getName()
4750 + " provided in the parameter");
4751 }
4752 return (T) object;
4753 }
4754
4755 private boolean isLengthPrefixed(int type) {
4756 // In general, we want custom types and containers of custom types to be length-prefixed,
4757 // this allows clients (eg. Bundle) to skip their content during deserialization. The
4758 // exception to this is Bundle, since Bundle is already length-prefixed and already copies
4759 // the correspondent section of the parcel internally.
4760 switch (type) {
4761 case VAL_MAP:
4762 case VAL_PARCELABLE:
4763 case VAL_LIST:
4764 case VAL_SPARSEARRAY:
4765 case VAL_PARCELABLEARRAY:
4766 case VAL_OBJECTARRAY:
4767 case VAL_SERIALIZABLE:
4768 return true;
4769 default:
4770 return false;
4771 }
4772 }
4773
4774 /**
4775 * Checks that an array of type T[], where T is {@code componentTypeToUnparcel}, is a subtype of
4776 * {@code requiredArrayType}.
4777 */
4778 private void checkArrayTypeToUnparcel(@Nullable Class<?> requiredArrayType,
4779 Class<?> componentTypeToUnparcel) {
4780 if (requiredArrayType != null) {
4781 // In Java 12, we could use componentTypeToUnparcel.arrayType() for the check
4782 Class<?> requiredComponentType = requiredArrayType.getComponentType();
4783 if (requiredComponentType == null) {
4784 throw new BadTypeParcelableException(
4785 "About to unparcel an array but type "
4786 + requiredArrayType.getCanonicalName()
4787 + " required by caller is not an array.");
4788 }
4789 checkTypeToUnparcel(requiredComponentType, componentTypeToUnparcel);
4790 }
4791 }
4792
4793 /**
4794 * Checks that {@code typeToUnparcel} is a subtype of {@code requiredType}, if {@code
4795 * requiredType} is not {@code null}.
4796 */
4797 private void checkTypeToUnparcel(@Nullable Class<?> requiredType, Class<?> typeToUnparcel) {
4798 if (requiredType != null && !requiredType.isAssignableFrom(typeToUnparcel)) {
4799 throw new BadTypeParcelableException(
4800 "About to unparcel a " + typeToUnparcel.getCanonicalName()
4801 + ", which is not a subtype of type " + requiredType.getCanonicalName()
4802 + " required by caller.");
4803 }
4804 }
4805
4806 /**
4807 * Read and return a new Parcelable from the parcel. The given class loader
4808 * will be used to load any enclosed Parcelables. If it is null, the default
4809 * class loader will be used.
4810 * @param loader A ClassLoader from which to instantiate the Parcelable
4811 * object, or null for the default class loader.
4812 * @return Returns the newly created Parcelable, or null if a null
4813 * object has been written.
4814 * @throws BadParcelableException Throws BadParcelableException if there
4815 * was an error trying to instantiate the Parcelable.
4816 *
4817 * @deprecated Use the type-safer version {@link #readParcelable(ClassLoader, Class)} starting
4818 * from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the format to
4819 * use {@link Parcelable.Creator#createFromParcel(Parcel)} if possible since this is also
4820 * more performant. Note that changing to the latter also requires changing the writes.
4821 */
4822 @Deprecated
4823 @Nullable
4824 public final <T extends Parcelable> T readParcelable(@Nullable ClassLoader loader) {
4825 return readParcelableInternal(loader, /* clazz */ null);
4826 }
4827
4828 /**
4829 * Same as {@link #readParcelable(ClassLoader)} but accepts {@code clazz} parameter as the type
4830 * required for each item.
4831 *
4832 * <p><b>Warning: </b> the class that implements {@link Parcelable} has to be the immediately
4833 * enclosing class of the runtime type of its CREATOR field (that is,
4834 * {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
4835 * otherwise this method might throw an exception. If the Parcelable class does not enclose the
4836 * CREATOR, use the deprecated {@link #readParcelable(ClassLoader)} instead.
4837 *
4838 * @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
4839 * is not an instance of that class or any of its children classes or there was an error
4840 * trying to instantiate an element.
4841 */
4842 @Nullable
4843 public <T> T readParcelable(@Nullable ClassLoader loader, @NonNull Class<T> clazz) {
4844 Objects.requireNonNull(clazz);
4845 return readParcelableInternal(loader, clazz);
4846 }
4847
4848 /**
4849 * @param clazz The type of the parcelable expected or {@code null} for performing no checks.
4850 */
4851 @SuppressWarnings("unchecked")
4852 @Nullable
4853 private <T> T readParcelableInternal(@Nullable ClassLoader loader, @Nullable Class<T> clazz) {
4854 Parcelable.Creator<?> creator = readParcelableCreatorInternal(loader, clazz);
4855 if (creator == null) {
4856 return null;
4857 }
4858 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
4859 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
4860 (Parcelable.ClassLoaderCreator<?>) creator;
4861 return (T) classLoaderCreator.createFromParcel(this, loader);
4862 }
4863 return (T) creator.createFromParcel(this);
4864 }
4865
4866 /** @hide */
4867 @UnsupportedAppUsage
4868 @SuppressWarnings("unchecked")
4869 @Nullable
4870 public final <T extends Parcelable> T readCreator(@NonNull Parcelable.Creator<?> creator,
4871 @Nullable ClassLoader loader) {
4872 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
4873 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
4874 (Parcelable.ClassLoaderCreator<?>) creator;
4875 return (T) classLoaderCreator.createFromParcel(this, loader);
4876 }
4877 return (T) creator.createFromParcel(this);
4878 }
4879
4880 /**
4881 * Read and return a Parcelable.Creator from the parcel. The given class loader will be used to
4882 * load the {@link Parcelable.Creator}. If it is null, the default class loader will be used.
4883 *
4884 * @param loader A ClassLoader from which to instantiate the {@link Parcelable.Creator}
4885 * object, or null for the default class loader.
4886 * @return the previously written {@link Parcelable.Creator}, or null if a null Creator was
4887 * written.
4888 * @throws BadParcelableException Throws BadParcelableException if there was an error trying to
4889 * read the {@link Parcelable.Creator}.
4890 *
4891 * @see #writeParcelableCreator
4892 *
4893 * @deprecated Use the type-safer version {@link #readParcelableCreator(ClassLoader, Class)}
4894 * starting from Android {@link Build.VERSION_CODES#TIRAMISU}.
4895 */
4896 @Deprecated
4897 @Nullable
4898 public final Parcelable.Creator<?> readParcelableCreator(@Nullable ClassLoader loader) {
4899 return readParcelableCreatorInternal(loader, /* clazz */ null);
4900 }
4901
4902 /**
4903 * Same as {@link #readParcelableCreator(ClassLoader)} but accepts {@code clazz} parameter
4904 * as the required type.
4905 *
4906 * <p><b>Warning: </b> the class that implements {@link Parcelable} has to be the immediately
4907 * enclosing class of the runtime type of its CREATOR field (that is,
4908 * {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
4909 * otherwise this method might throw an exception. If the Parcelable class does not enclose the
4910 * CREATOR, use the deprecated {@link #readParcelableCreator(ClassLoader) instead.
4911 *
4912 * @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
4913 * is not an instance of that class or any of its children classes or there there was an error
4914 * trying to read the {@link Parcelable.Creator}.
4915 */
4916 @Nullable
4917 public <T> Parcelable.Creator<T> readParcelableCreator(
4918 @Nullable ClassLoader loader, @NonNull Class<T> clazz) {
4919 Objects.requireNonNull(clazz);
4920 return readParcelableCreatorInternal(loader, clazz);
4921 }
4922
4923 /**
4924 * @param clazz The type of the parcelable expected or {@code null} for performing no checks.
4925 */
4926 @SuppressWarnings("unchecked")
4927 @Nullable
4928 private <T> Parcelable.Creator<T> readParcelableCreatorInternal(
4929 @Nullable ClassLoader loader, @Nullable Class<T> clazz) {
4930 String name = readString();
4931 if (name == null) {
4932 return null;
4933 }
4934
4935 Pair<Parcelable.Creator<?>, Class<?>> creatorAndParcelableClass;
4936 synchronized (sPairedCreators) {
4937 HashMap<String, Pair<Parcelable.Creator<?>, Class<?>>> map =
4938 sPairedCreators.get(loader);
4939 if (map == null) {
4940 sPairedCreators.put(loader, new HashMap<>());
4941 mCreators.put(loader, new HashMap<>());
4942 creatorAndParcelableClass = null;
4943 } else {
4944 creatorAndParcelableClass = map.get(name);
4945 }
4946 }
4947
4948 if (creatorAndParcelableClass != null) {
4949 Parcelable.Creator<?> creator = creatorAndParcelableClass.first;
4950 Class<?> parcelableClass = creatorAndParcelableClass.second;
4951 if (clazz != null) {
4952 if (!clazz.isAssignableFrom(parcelableClass)) {
4953 throw new BadTypeParcelableException("Parcelable creator " + name + " is not "
4954 + "a subclass of required class " + clazz.getName()
4955 + " provided in the parameter");
4956 }
4957 }
4958
4959 return (Parcelable.Creator<T>) creator;
4960 }
4961
4962 Parcelable.Creator<?> creator;
4963 Class<?> parcelableClass;
4964 try {
4965 // If loader == null, explicitly emulate Class.forName(String) "caller
4966 // classloader" behavior.
4967 ClassLoader parcelableClassLoader =
4968 (loader == null ? getClass().getClassLoader() : loader);
4969 // Avoid initializing the Parcelable class until we know it implements
4970 // Parcelable and has the necessary CREATOR field. http://b/1171613.
4971 parcelableClass = Class.forName(name, false /* initialize */,
4972 parcelableClassLoader);
4973 if (!Parcelable.class.isAssignableFrom(parcelableClass)) {
4974 throw new BadParcelableException("Parcelable protocol requires subclassing "
4975 + "from Parcelable on class " + name);
4976 }
4977 if (clazz != null) {
4978 if (!clazz.isAssignableFrom(parcelableClass)) {
4979 throw new BadTypeParcelableException("Parcelable creator " + name + " is not "
4980 + "a subclass of required class " + clazz.getName()
4981 + " provided in the parameter");
4982 }
4983 }
4984
4985 Field f = parcelableClass.getField("CREATOR");
4986 if ((f.getModifiers() & Modifier.STATIC) == 0) {
4987 throw new BadParcelableException("Parcelable protocol requires "
4988 + "the CREATOR object to be static on class " + name);
4989 }
4990 Class<?> creatorType = f.getType();
4991 if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) {
4992 // Fail before calling Field.get(), not after, to avoid initializing
4993 // parcelableClass unnecessarily.
4994 throw new BadParcelableException("Parcelable protocol requires a "
4995 + "Parcelable.Creator object called "
4996 + "CREATOR on class " + name);
4997 }
4998 creator = (Parcelable.Creator<?>) f.get(null);
4999 } catch (IllegalAccessException e) {
5000 Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
5001 throw new BadParcelableException(
5002 "IllegalAccessException when unmarshalling: " + name, e);
5003 } catch (ClassNotFoundException e) {
5004 Log.e(TAG, "Class not found when unmarshalling: " + name, e);
5005 throw new BadParcelableException(
5006 "ClassNotFoundException when unmarshalling: " + name, e);
5007 } catch (NoSuchFieldException e) {
5008 throw new BadParcelableException("Parcelable protocol requires a "
5009 + "Parcelable.Creator object called "
5010 + "CREATOR on class " + name, e);
5011 }
5012 if (creator == null) {
5013 throw new BadParcelableException("Parcelable protocol requires a "
5014 + "non-null Parcelable.Creator object called "
5015 + "CREATOR on class " + name);
5016 }
5017
5018 synchronized (sPairedCreators) {
5019 sPairedCreators.get(loader).put(name, Pair.create(creator, parcelableClass));
5020 mCreators.get(loader).put(name, creator);
5021 }
5022
5023 return (Parcelable.Creator<T>) creator;
5024 }
5025
5026 /**
5027 * Read and return a new Parcelable array from the parcel.
5028 * The given class loader will be used to load any enclosed
5029 * Parcelables.
5030 * @return the Parcelable array, or null if the array is null
5031 *
5032 * @deprecated Use the type-safer version {@link #readParcelableArray(ClassLoader, Class)}
5033 * starting from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the
5034 * format to use {@link #createTypedArray(Parcelable.Creator)} if possible (eg. if the
5035 * items' class is final) since this is also more performant. Note that changing to the
5036 * latter also requires changing the writes.
5037 */
5038 @Deprecated
5039 @Nullable
5040 public Parcelable[] readParcelableArray(@Nullable ClassLoader loader) {
5041 return readParcelableArrayInternal(loader, /* clazz */ null);
5042 }
5043
5044 /**
5045 * Same as {@link #readParcelableArray(ClassLoader)} but accepts {@code clazz} parameter as
5046 * the type required for each item.
5047 *
5048 * <p><b>Warning: </b> the class that implements {@link Parcelable} has to be the immediately
5049 * enclosing class of the runtime type of its CREATOR field (that is,
5050 * {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
5051 * otherwise this method might throw an exception. If the Parcelable class does not enclose the
5052 * CREATOR, use the deprecated {@link #readParcelableArray(ClassLoader)} instead.
5053 *
5054 * @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
5055 * is not an instance of that class or any of its children classes or there was an error
5056 * trying to instantiate an element.
5057 */
5058 @SuppressLint({"ArrayReturn", "NullableCollection"})
5059 @Nullable
5060 public <T> T[] readParcelableArray(@Nullable ClassLoader loader, @NonNull Class<T> clazz) {
5061 return readParcelableArrayInternal(loader, requireNonNull(clazz));
5062 }
5063
5064 @SuppressWarnings("unchecked")
5065 @Nullable
5066 private <T> T[] readParcelableArrayInternal(@Nullable ClassLoader loader,
5067 @Nullable Class<T> clazz) {
5068 int n = readInt();
5069 if (n < 0) {
5070 return null;
5071 }
5072 T[] p = (T[]) ((clazz == null) ? new Parcelable[n] : Array.newInstance(clazz, n));
5073 for (int i = 0; i < n; i++) {
5074 p[i] = readParcelableInternal(loader, clazz);
5075 }
5076 return p;
5077 }
5078
5079 /**
5080 * Read and return a new Serializable object from the parcel.
5081 * @return the Serializable object, or null if the Serializable name
5082 * wasn't found in the parcel.
5083 *
5084 * Unlike {@link #readSerializable(ClassLoader, Class)}, it uses the nearest valid class loader
5085 * up the execution stack to instantiate the Serializable object.
5086 *
5087 * @deprecated Use the type-safer version {@link #readSerializable(ClassLoader, Class)} starting
5088 * from Android {@link Build.VERSION_CODES#TIRAMISU}.
5089 */
5090 @Deprecated
5091 @Nullable
5092 public Serializable readSerializable() {
5093 return readSerializableInternal(/* loader */ null, /* clazz */ null);
5094 }
5095
5096 /**
5097 * Same as {@link #readSerializable()} but accepts {@code loader} and {@code clazz} parameters.
5098 *
5099 * @param loader A ClassLoader from which to instantiate the Serializable object,
5100 * or null for the default class loader.
5101 * @param clazz The type of the object expected.
5102 *
5103 * @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
5104 * is not an instance of that class or any of its children class or there there was an error
5105 * deserializing the object.
5106 */
5107 @Nullable
5108 public <T> T readSerializable(@Nullable ClassLoader loader, @NonNull Class<T> clazz) {
5109 Objects.requireNonNull(clazz);
5110 return readSerializableInternal(
5111 loader == null ? getClass().getClassLoader() : loader, clazz);
5112 }
5113
5114 /**
5115 * @param clazz The type of the serializable expected or {@code null} for performing no checks
5116 */
5117 @Nullable
5118 private <T> T readSerializableInternal(@Nullable final ClassLoader loader,
5119 @Nullable Class<T> clazz) {
5120 String name = readString();
5121 if (name == null) {
5122 // For some reason we were unable to read the name of the Serializable (either there
5123 // is nothing left in the Parcel to read, or the next value wasn't a String), so
5124 // return null, which indicates that the name wasn't found in the parcel.
5125 return null;
5126 }
5127
5128 try {
5129 if (clazz != null && loader != null) {
5130 // If custom classloader is provided, resolve the type of serializable using the
5131 // name, then check the type before deserialization. As in this case we can resolve
5132 // the class the same way as ObjectInputStream, using the provided classloader.
5133 Class<?> cl = Class.forName(name, false, loader);
5134 if (!clazz.isAssignableFrom(cl)) {
5135 throw new BadTypeParcelableException("Serializable object "
5136 + cl.getName() + " is not a subclass of required class "
5137 + clazz.getName() + " provided in the parameter");
5138 }
5139 }
5140 byte[] serializedData = createByteArray();
5141 ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
5142 ObjectInputStream ois = new ObjectInputStream(bais) {
5143 @Override
5144 protected Class<?> resolveClass(ObjectStreamClass osClass)
5145 throws IOException, ClassNotFoundException {
5146 // try the custom classloader if provided
5147 if (loader != null) {
5148 Class<?> c = Class.forName(osClass.getName(), false, loader);
5149 return Objects.requireNonNull(c);
5150 }
5151 return super.resolveClass(osClass);
5152 }
5153 };
5154 T object = (T) ois.readObject();
5155 if (clazz != null && loader == null) {
5156 // If custom classloader is not provided, check the type of the serializable using
5157 // the deserialized object, as we cannot resolve the class the same way as
5158 // ObjectInputStream.
5159 if (!clazz.isAssignableFrom(object.getClass())) {
5160 throw new BadTypeParcelableException("Serializable object "
5161 + object.getClass().getName() + " is not a subclass of required class "
5162 + clazz.getName() + " provided in the parameter");
5163 }
5164 }
5165 return object;
5166 } catch (IOException ioe) {
5167 throw new BadParcelableException("Parcelable encountered "
5168 + "IOException reading a Serializable object (name = "
5169 + name + ")", ioe);
5170 } catch (ClassNotFoundException cnfe) {
5171 throw new BadParcelableException("Parcelable encountered "
5172 + "ClassNotFoundException reading a Serializable object (name = "
5173 + name + ")", cnfe);
5174 }
5175 }
5176
5177
5178 // Left due to the UnsupportedAppUsage. Do not use anymore - use sPairedCreators instead
5179 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
5180 private static final HashMap<ClassLoader, HashMap<String, Parcelable.Creator<?>>>
5181 mCreators = new HashMap<>();
5182
5183 // Cache of previously looked up CREATOR.createFromParcel() methods for particular classes.
5184 // Keys are the names of the classes, values are a pair consisting of a parcelable creator,
5185 // and the class of the parcelable type for the object.
5186 private static final HashMap<ClassLoader, HashMap<String,
5187 Pair<Parcelable.Creator<?>, Class<?>>>> sPairedCreators = new HashMap<>();
5188
5189 /** @hide for internal use only. */
5190 static protected final Parcel obtain(int obj) {
5191 throw new UnsupportedOperationException();
5192 }
5193
5194 /** @hide */
5195 static protected final Parcel obtain(long obj) {
5196 Parcel res = null;
5197 synchronized (sPoolSync) {
5198 if (sHolderPool != null) {
5199 res = sHolderPool;
5200 sHolderPool = res.mPoolNext;
5201 res.mPoolNext = null;
5202 sHolderPoolSize--;
5203 }
5204 }
5205
5206 // When no cache found above, create from scratch; otherwise prepare the
5207 // cached object to be used
5208 if (res == null) {
5209 res = new Parcel(obj);
5210 } else {
5211 res.mRecycled = false;
5212 if (DEBUG_RECYCLE) {
5213 res.mStack = new RuntimeException();
5214 }
5215 res.init(obj);
5216 }
5217 return res;
5218 }
5219
5220 private Parcel(long nativePtr) {
5221 if (DEBUG_RECYCLE) {
5222 mStack = new RuntimeException();
5223 }
5224 //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
5225 init(nativePtr);
5226 }
5227
5228 private void init(long nativePtr) {
5229 if (nativePtr != 0) {
5230 mNativePtr = nativePtr;
5231 mOwnsNativeParcelObject = false;
5232 } else {
5233 mNativePtr = nativeCreate();
5234 mOwnsNativeParcelObject = true;
5235 }
5236 }
5237
5238 private void freeBuffer() {
5239 mFlags = 0;
5240 resetSqaushingState();
5241 if (mOwnsNativeParcelObject) {
5242 nativeFreeBuffer(mNativePtr);
5243 }
5244 mReadWriteHelper = ReadWriteHelper.DEFAULT;
5245 }
5246
5247 private void destroy() {
5248 resetSqaushingState();
5249 if (mNativePtr != 0) {
5250 if (mOwnsNativeParcelObject) {
5251 nativeDestroy(mNativePtr);
5252 }
5253 mNativePtr = 0;
5254 }
5255 }
5256
5257 @Override
5258 protected void finalize() throws Throwable {
5259 if (DEBUG_RECYCLE) {
5260 // we could always have this log on, but it's spammy
5261 if (!mRecycled) {
5262 Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
5263 }
5264 }
5265 destroy();
5266 }
5267
5268 /**
5269 * To be replaced by {@link #readMapInternal(Map, int, ClassLoader, Class, Class)}, but keep
5270 * the old API for compatibility usages.
5271 */
5272 /* package */ void readMapInternal(@NonNull Map outVal, int n,
5273 @Nullable ClassLoader loader) {
5274 readMapInternal(outVal, n, loader, /* clazzKey */null, /* clazzValue */null);
5275 }
5276
5277 @Nullable
5278 private <K, V> HashMap<K, V> readHashMapInternal(@Nullable ClassLoader loader,
5279 @NonNull Class<? extends K> clazzKey, @NonNull Class<? extends V> clazzValue) {
5280 int n = readInt();
5281 if (n < 0) {
5282 return null;
5283 }
5284 HashMap<K, V> map = new HashMap<>(n);
5285 readMapInternal(map, n, loader, clazzKey, clazzValue);
5286 return map;
5287 }
5288
5289 private <K, V> void readMapInternal(@NonNull Map<? super K, ? super V> outVal,
5290 @Nullable ClassLoader loader, @Nullable Class<K> clazzKey,
5291 @Nullable Class<V> clazzValue) {
5292 int n = readInt();
5293 readMapInternal(outVal, n, loader, clazzKey, clazzValue);
5294 }
5295
5296 private <K, V> void readMapInternal(@NonNull Map<? super K, ? super V> outVal, int n,
5297 @Nullable ClassLoader loader, @Nullable Class<K> clazzKey,
5298 @Nullable Class<V> clazzValue) {
5299 while (n > 0) {
5300 K key = readValue(loader, clazzKey);
5301 V value = readValue(loader, clazzValue);
5302 outVal.put(key, value);
5303 n--;
5304 }
5305 }
5306
5307 private void readArrayMapInternal(@NonNull ArrayMap<? super String, Object> outVal,
5308 int size, @Nullable ClassLoader loader) {
5309 readArrayMap(outVal, size, /* sorted */ true, /* lazy */ false, loader);
5310 }
5311
5312 /**
5313 * Reads a map into {@code map}.
5314 *
5315 * @param sorted Whether the keys are sorted by their hashes, if so we use an optimized path.
5316 * @param lazy Whether to populate the map with lazy {@link Supplier} objects for
5317 * length-prefixed values. See {@link Parcel#readLazyValue(ClassLoader)} for more
5318 * details.
5319 * @return whether the parcel can be recycled or not.
5320 * @hide
5321 */
5322 boolean readArrayMap(ArrayMap<? super String, Object> map, int size, boolean sorted,
5323 boolean lazy, @Nullable ClassLoader loader) {
5324 boolean recycle = true;
5325 while (size > 0) {
5326 String key = readString();
5327 Object value = (lazy) ? readLazyValue(loader) : readValue(loader);
5328 if (value instanceof LazyValue) {
5329 recycle = false;
5330 }
5331 if (sorted) {
5332 map.append(key, value);
5333 } else {
5334 map.put(key, value);
5335 }
5336 size--;
5337 }
5338 if (sorted) {
5339 map.validate();
5340 }
5341 return recycle;
5342 }
5343
5344 /**
5345 * @hide For testing only.
5346 */
5347 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5348 public void readArrayMap(@NonNull ArrayMap<? super String, Object> outVal,
5349 @Nullable ClassLoader loader) {
5350 final int N = readInt();
5351 if (N < 0) {
5352 return;
5353 }
5354 readArrayMapInternal(outVal, N, loader);
5355 }
5356
5357 /**
5358 * Reads an array set.
5359 *
5360 * @param loader The class loader to use.
5361 *
5362 * @hide
5363 */
5364 @UnsupportedAppUsage
5365 public @Nullable ArraySet<? extends Object> readArraySet(@Nullable ClassLoader loader) {
5366 final int size = readInt();
5367 if (size < 0) {
5368 return null;
5369 }
5370 ArraySet<Object> result = new ArraySet<>(size);
5371 for (int i = 0; i < size; i++) {
5372 Object value = readValue(loader);
5373 result.append(value);
5374 }
5375 return result;
5376 }
5377
5378 /**
5379 * The method is replaced by {@link #readListInternal(List, int, ClassLoader, Class)}, however
5380 * we are keeping this unused method here to allow unsupported app usages.
5381 */
5382 private void readListInternal(@NonNull List outVal, int n, @Nullable ClassLoader loader) {
5383 readListInternal(outVal, n, loader, /* clazz */ null);
5384 }
5385
5386 /**
5387 * @param clazz The type of the object expected or {@code null} for performing no checks.
5388 */
5389 private <T> void readListInternal(@NonNull List<? super T> outVal, int n,
5390 @Nullable ClassLoader loader, @Nullable Class<T> clazz) {
5391 while (n > 0) {
5392 T value = readValue(loader, clazz);
5393 //Log.d(TAG, "Unmarshalling value=" + value);
5394 outVal.add(value);
5395 n--;
5396 }
5397 }
5398
5399 /**
5400 * @param clazz The type of the object expected or {@code null} for performing no checks.
5401 */
5402 @SuppressLint({"ConcreteCollection", "NullableCollection"})
5403 @Nullable
5404 private <T> ArrayList<T> readArrayListInternal(@Nullable ClassLoader loader,
5405 @Nullable Class<? extends T> clazz) {
5406 int n = readInt();
5407 if (n < 0) {
5408 return null;
5409 }
5410 ArrayList<T> l = new ArrayList<>(n);
5411 readListInternal(l, n, loader, clazz);
5412 return l;
5413 }
5414
5415 /**
5416 * The method is replaced by {@link #readArrayInternal(ClassLoader, Class)}, however
5417 * we are keeping this unused method here to allow unsupported app usages.
5418 */
5419 private void readArrayInternal(@NonNull Object[] outVal, int N,
5420 @Nullable ClassLoader loader) {
5421 for (int i = 0; i < N; i++) {
5422 Object value = readValue(loader, /* clazz */ null);
5423 outVal[i] = value;
5424 }
5425 }
5426
5427 /**
5428 * @param clazz The type of the object expected or {@code null} for performing no checks.
5429 */
5430 @SuppressWarnings("unchecked")
5431 @Nullable
5432 private <T> T[] readArrayInternal(@Nullable ClassLoader loader, @Nullable Class<T> clazz) {
5433 int n = readInt();
5434 if (n < 0) {
5435 return null;
5436 }
5437 T[] outVal = (T[]) ((clazz == null) ? new Object[n] : Array.newInstance(clazz, n));
5438
5439 for (int i = 0; i < n; i++) {
5440 T value = readValue(loader, clazz);
5441 outVal[i] = value;
5442 }
5443 return outVal;
5444 }
5445
5446 /**
5447 * The method is replaced by {@link #readSparseArray(ClassLoader, Class)}, however
5448 * we are keeping this unused method here to allow unsupported app usages.
5449 */
5450 private void readSparseArrayInternal(@NonNull SparseArray outVal, int N,
5451 @Nullable ClassLoader loader) {
5452 while (N > 0) {
5453 int key = readInt();
5454 Object value = readValue(loader);
5455 outVal.append(key, value);
5456 N--;
5457 }
5458 }
5459
5460 /**
5461 * @param clazz The type of the object expected or {@code null} for performing no checks.
5462 */
5463 @Nullable
5464 private <T> SparseArray<T> readSparseArrayInternal(@Nullable ClassLoader loader,
5465 @Nullable Class<? extends T> clazz) {
5466 int n = readInt();
5467 if (n < 0) {
5468 return null;
5469 }
5470 SparseArray<T> outVal = new SparseArray<>(n);
5471
5472 while (n > 0) {
5473 int key = readInt();
5474 T value = readValue(loader, clazz);
5475 outVal.append(key, value);
5476 n--;
5477 }
5478 return outVal;
5479 }
5480
5481
5482 private void readSparseBooleanArrayInternal(@NonNull SparseBooleanArray outVal, int N) {
5483 while (N > 0) {
5484 int key = readInt();
5485 boolean value = this.readByte() == 1;
5486 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
5487 outVal.append(key, value);
5488 N--;
5489 }
5490 }
5491
5492 private void readSparseIntArrayInternal(@NonNull SparseIntArray outVal, int N) {
5493 while (N > 0) {
5494 int key = readInt();
5495 int value = readInt();
5496 outVal.append(key, value);
5497 N--;
5498 }
5499 }
5500
5501 /**
5502 * @hide For testing
5503 */
5504 public long getOpenAshmemSize() {
5505 return nativeGetOpenAshmemSize(mNativePtr);
5506 }
5507
5508 private static String valueTypeToString(int type) {
5509 switch (type) {
5510 case VAL_NULL: return "VAL_NULL";
5511 case VAL_INTEGER: return "VAL_INTEGER";
5512 case VAL_MAP: return "VAL_MAP";
5513 case VAL_BUNDLE: return "VAL_BUNDLE";
5514 case VAL_PERSISTABLEBUNDLE: return "VAL_PERSISTABLEBUNDLE";
5515 case VAL_PARCELABLE: return "VAL_PARCELABLE";
5516 case VAL_SHORT: return "VAL_SHORT";
5517 case VAL_LONG: return "VAL_LONG";
5518 case VAL_FLOAT: return "VAL_FLOAT";
5519 case VAL_DOUBLE: return "VAL_DOUBLE";
5520 case VAL_BOOLEAN: return "VAL_BOOLEAN";
5521 case VAL_CHARSEQUENCE: return "VAL_CHARSEQUENCE";
5522 case VAL_LIST: return "VAL_LIST";
5523 case VAL_SPARSEARRAY: return "VAL_SPARSEARRAY";
5524 case VAL_BOOLEANARRAY: return "VAL_BOOLEANARRAY";
5525 case VAL_BYTEARRAY: return "VAL_BYTEARRAY";
5526 case VAL_STRINGARRAY: return "VAL_STRINGARRAY";
5527 case VAL_CHARSEQUENCEARRAY: return "VAL_CHARSEQUENCEARRAY";
5528 case VAL_IBINDER: return "VAL_IBINDER";
5529 case VAL_PARCELABLEARRAY: return "VAL_PARCELABLEARRAY";
5530 case VAL_INTARRAY: return "VAL_INTARRAY";
5531 case VAL_LONGARRAY: return "VAL_LONGARRAY";
5532 case VAL_BYTE: return "VAL_BYTE";
5533 case VAL_SIZE: return "VAL_SIZE";
5534 case VAL_SIZEF: return "VAL_SIZEF";
5535 case VAL_DOUBLEARRAY: return "VAL_DOUBLEARRAY";
5536 case VAL_CHAR: return "VAL_CHAR";
5537 case VAL_SHORTARRAY: return "VAL_SHORTARRAY";
5538 case VAL_CHARARRAY: return "VAL_CHARARRAY";
5539 case VAL_FLOATARRAY: return "VAL_FLOATARRAY";
5540 case VAL_OBJECTARRAY: return "VAL_OBJECTARRAY";
5541 case VAL_SERIALIZABLE: return "VAL_SERIALIZABLE";
5542 default: return "UNKNOWN(" + type + ")";
5543 }
5544 }
5545 }