1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.os;
18 
19 import android.annotation.Nullable;
20 import android.text.TextUtils;
21 import android.util.ArrayMap;
22 import android.util.ArraySet;
23 import android.util.ExceptionUtils;
24 import android.util.Log;
25 import android.util.Size;
26 import android.util.SizeF;
27 import android.util.SparseArray;
28 import android.util.SparseBooleanArray;
29 import android.util.SparseIntArray;
30 
31 import dalvik.annotation.optimization.CriticalNative;
32 import dalvik.annotation.optimization.FastNative;
33 import dalvik.system.VMRuntime;
34 
35 import libcore.util.SneakyThrow;
36 
37 import java.io.ByteArrayInputStream;
38 import java.io.ByteArrayOutputStream;
39 import java.io.FileDescriptor;
40 import java.io.FileNotFoundException;
41 import java.io.IOException;
42 import java.io.ObjectInputStream;
43 import java.io.ObjectOutputStream;
44 import java.io.ObjectStreamClass;
45 import java.io.Serializable;
46 import java.lang.reflect.Array;
47 import java.lang.reflect.Field;
48 import java.lang.reflect.Modifier;
49 import java.util.ArrayList;
50 import java.util.Arrays;
51 import java.util.HashMap;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.Set;
55 
56 /**
57  * Container for a message (data and object references) that can
58  * be sent through an IBinder.  A Parcel can contain both flattened data
59  * that will be unflattened on the other side of the IPC (using the various
60  * methods here for writing specific types, or the general
61  * {@link Parcelable} interface), and references to live {@link IBinder}
62  * objects that will result in the other side receiving a proxy IBinder
63  * connected with the original IBinder in the Parcel.
64  *
65  * <p class="note">Parcel is <strong>not</strong> a general-purpose
66  * serialization mechanism.  This class (and the corresponding
67  * {@link Parcelable} API for placing arbitrary objects into a Parcel) is
68  * designed as a high-performance IPC transport.  As such, it is not
69  * appropriate to place any Parcel data in to persistent storage: changes
70  * in the underlying implementation of any of the data in the Parcel can
71  * render older data unreadable.</p>
72  *
73  * <p>The bulk of the Parcel API revolves around reading and writing data
74  * of various types.  There are six major classes of such functions available.</p>
75  *
76  * <h3>Primitives</h3>
77  *
78  * <p>The most basic data functions are for writing and reading primitive
79  * data types: {@link #writeByte}, {@link #readByte}, {@link #writeDouble},
80  * {@link #readDouble}, {@link #writeFloat}, {@link #readFloat}, {@link #writeInt},
81  * {@link #readInt}, {@link #writeLong}, {@link #readLong},
82  * {@link #writeString}, {@link #readString}.  Most other
83  * data operations are built on top of these.  The given data is written and
84  * read using the endianess of the host CPU.</p>
85  *
86  * <h3>Primitive Arrays</h3>
87  *
88  * <p>There are a variety of methods for reading and writing raw arrays
89  * of primitive objects, which generally result in writing a 4-byte length
90  * followed by the primitive data items.  The methods for reading can either
91  * read the data into an existing array, or create and return a new array.
92  * These available types are:</p>
93  *
94  * <ul>
95  * <li> {@link #writeBooleanArray(boolean[])},
96  * {@link #readBooleanArray(boolean[])}, {@link #createBooleanArray()}
97  * <li> {@link #writeByteArray(byte[])},
98  * {@link #writeByteArray(byte[], int, int)}, {@link #readByteArray(byte[])},
99  * {@link #createByteArray()}
100  * <li> {@link #writeCharArray(char[])}, {@link #readCharArray(char[])},
101  * {@link #createCharArray()}
102  * <li> {@link #writeDoubleArray(double[])}, {@link #readDoubleArray(double[])},
103  * {@link #createDoubleArray()}
104  * <li> {@link #writeFloatArray(float[])}, {@link #readFloatArray(float[])},
105  * {@link #createFloatArray()}
106  * <li> {@link #writeIntArray(int[])}, {@link #readIntArray(int[])},
107  * {@link #createIntArray()}
108  * <li> {@link #writeLongArray(long[])}, {@link #readLongArray(long[])},
109  * {@link #createLongArray()}
110  * <li> {@link #writeStringArray(String[])}, {@link #readStringArray(String[])},
111  * {@link #createStringArray()}.
112  * <li> {@link #writeSparseBooleanArray(SparseBooleanArray)},
113  * {@link #readSparseBooleanArray()}.
114  * </ul>
115  *
116  * <h3>Parcelables</h3>
117  *
118  * <p>The {@link Parcelable} protocol provides an extremely efficient (but
119  * low-level) protocol for objects to write and read themselves from Parcels.
120  * You can use the direct methods {@link #writeParcelable(Parcelable, int)}
121  * and {@link #readParcelable(ClassLoader)} or
122  * {@link #writeParcelableArray} and
123  * {@link #readParcelableArray(ClassLoader)} to write or read.  These
124  * methods write both the class type and its data to the Parcel, allowing
125  * that class to be reconstructed from the appropriate class loader when
126  * later reading.</p>
127  *
128  * <p>There are also some methods that provide a more efficient way to work
129  * with Parcelables: {@link #writeTypedObject}, {@link #writeTypedArray},
130  * {@link #writeTypedList}, {@link #readTypedObject},
131  * {@link #createTypedArray} and {@link #createTypedArrayList}.  These methods
132  * do not write the class information of the original object: instead, the
133  * caller of the read function must know what type to expect and pass in the
134  * appropriate {@link Parcelable.Creator Parcelable.Creator} instead to
135  * properly construct the new object and read its data.  (To more efficient
136  * write and read a single Parcelable object that is not null, you can directly
137  * call {@link Parcelable#writeToParcel Parcelable.writeToParcel} and
138  * {@link Parcelable.Creator#createFromParcel Parcelable.Creator.createFromParcel}
139  * yourself.)</p>
140  *
141  * <h3>Bundles</h3>
142  *
143  * <p>A special type-safe container, called {@link Bundle}, is available
144  * for key/value maps of heterogeneous values.  This has many optimizations
145  * for improved performance when reading and writing data, and its type-safe
146  * API avoids difficult to debug type errors when finally marshalling the
147  * data contents into a Parcel.  The methods to use are
148  * {@link #writeBundle(Bundle)}, {@link #readBundle()}, and
149  * {@link #readBundle(ClassLoader)}.
150  *
151  * <h3>Active Objects</h3>
152  *
153  * <p>An unusual feature of Parcel is the ability to read and write active
154  * objects.  For these objects the actual contents of the object is not
155  * written, rather a special token referencing the object is written.  When
156  * reading the object back from the Parcel, you do not get a new instance of
157  * the object, but rather a handle that operates on the exact same object that
158  * was originally written.  There are two forms of active objects available.</p>
159  *
160  * <p>{@link Binder} objects are a core facility of Android's general cross-process
161  * communication system.  The {@link IBinder} interface describes an abstract
162  * protocol with a Binder object.  Any such interface can be written in to
163  * a Parcel, and upon reading you will receive either the original object
164  * implementing that interface or a special proxy implementation
165  * that communicates calls back to the original object.  The methods to use are
166  * {@link #writeStrongBinder(IBinder)},
167  * {@link #writeStrongInterface(IInterface)}, {@link #readStrongBinder()},
168  * {@link #writeBinderArray(IBinder[])}, {@link #readBinderArray(IBinder[])},
169  * {@link #createBinderArray()},
170  * {@link #writeBinderList(List)}, {@link #readBinderList(List)},
171  * {@link #createBinderArrayList()}.</p>
172  *
173  * <p>FileDescriptor objects, representing raw Linux file descriptor identifiers,
174  * can be written and {@link ParcelFileDescriptor} objects returned to operate
175  * on the original file descriptor.  The returned file descriptor is a dup
176  * of the original file descriptor: the object and fd is different, but
177  * operating on the same underlying file stream, with the same position, etc.
178  * The methods to use are {@link #writeFileDescriptor(FileDescriptor)},
179  * {@link #readFileDescriptor()}.
180  *
181  * <h3>Untyped Containers</h3>
182  *
183  * <p>A final class of methods are for writing and reading standard Java
184  * containers of arbitrary types.  These all revolve around the
185  * {@link #writeValue(Object)} and {@link #readValue(ClassLoader)} methods
186  * which define the types of objects allowed.  The container methods are
187  * {@link #writeArray(Object[])}, {@link #readArray(ClassLoader)},
188  * {@link #writeList(List)}, {@link #readList(List, ClassLoader)},
189  * {@link #readArrayList(ClassLoader)},
190  * {@link #writeMap(Map)}, {@link #readMap(Map, ClassLoader)},
191  * {@link #writeSparseArray(SparseArray)},
192  * {@link #readSparseArray(ClassLoader)}.
193  */
194 public final class Parcel {
195 
196     private static final boolean DEBUG_RECYCLE = false;
197     private static final boolean DEBUG_ARRAY_MAP = false;
198     private static final String TAG = "Parcel";
199 
200     @SuppressWarnings({"UnusedDeclaration"})
201     private long mNativePtr; // used by native code
202 
203     /**
204      * Flag indicating if {@link #mNativePtr} was allocated by this object,
205      * indicating that we're responsible for its lifecycle.
206      */
207     private boolean mOwnsNativeParcelObject;
208     private long mNativeSize;
209 
210     private ArrayMap<Class, Object> mClassCookies;
211 
212     private RuntimeException mStack;
213 
214     /**
215      * Whether or not to parcel the stack trace of an exception. This has a performance
216      * impact, so should only be included in specific processes and only on debug builds.
217      */
218     private static boolean sParcelExceptionStackTrace;
219 
220     private static final int POOL_SIZE = 6;
221     private static final Parcel[] sOwnedPool = new Parcel[POOL_SIZE];
222     private static final Parcel[] sHolderPool = new Parcel[POOL_SIZE];
223 
224     // Keep in sync with frameworks/native/include/private/binder/ParcelValTypes.h.
225     private static final int VAL_NULL = -1;
226     private static final int VAL_STRING = 0;
227     private static final int VAL_INTEGER = 1;
228     private static final int VAL_MAP = 2;
229     private static final int VAL_BUNDLE = 3;
230     private static final int VAL_PARCELABLE = 4;
231     private static final int VAL_SHORT = 5;
232     private static final int VAL_LONG = 6;
233     private static final int VAL_FLOAT = 7;
234     private static final int VAL_DOUBLE = 8;
235     private static final int VAL_BOOLEAN = 9;
236     private static final int VAL_CHARSEQUENCE = 10;
237     private static final int VAL_LIST  = 11;
238     private static final int VAL_SPARSEARRAY = 12;
239     private static final int VAL_BYTEARRAY = 13;
240     private static final int VAL_STRINGARRAY = 14;
241     private static final int VAL_IBINDER = 15;
242     private static final int VAL_PARCELABLEARRAY = 16;
243     private static final int VAL_OBJECTARRAY = 17;
244     private static final int VAL_INTARRAY = 18;
245     private static final int VAL_LONGARRAY = 19;
246     private static final int VAL_BYTE = 20;
247     private static final int VAL_SERIALIZABLE = 21;
248     private static final int VAL_SPARSEBOOLEANARRAY = 22;
249     private static final int VAL_BOOLEANARRAY = 23;
250     private static final int VAL_CHARSEQUENCEARRAY = 24;
251     private static final int VAL_PERSISTABLEBUNDLE = 25;
252     private static final int VAL_SIZE = 26;
253     private static final int VAL_SIZEF = 27;
254     private static final int VAL_DOUBLEARRAY = 28;
255 
256     // The initial int32 in a Binder call's reply Parcel header:
257     // Keep these in sync with libbinder's binder/Status.h.
258     private static final int EX_SECURITY = -1;
259     private static final int EX_BAD_PARCELABLE = -2;
260     private static final int EX_ILLEGAL_ARGUMENT = -3;
261     private static final int EX_NULL_POINTER = -4;
262     private static final int EX_ILLEGAL_STATE = -5;
263     private static final int EX_NETWORK_MAIN_THREAD = -6;
264     private static final int EX_UNSUPPORTED_OPERATION = -7;
265     private static final int EX_SERVICE_SPECIFIC = -8;
266     private static final int EX_PARCELABLE = -9;
267     private static final int EX_HAS_REPLY_HEADER = -128;  // special; see below
268     // EX_TRANSACTION_FAILED is used exclusively in native code.
269     // see libbinder's binder/Status.h
270     private static final int EX_TRANSACTION_FAILED = -129;
271 
272     @CriticalNative
nativeDataSize(long nativePtr)273     private static native int nativeDataSize(long nativePtr);
274     @CriticalNative
nativeDataAvail(long nativePtr)275     private static native int nativeDataAvail(long nativePtr);
276     @CriticalNative
nativeDataPosition(long nativePtr)277     private static native int nativeDataPosition(long nativePtr);
278     @CriticalNative
nativeDataCapacity(long nativePtr)279     private static native int nativeDataCapacity(long nativePtr);
280     @FastNative
nativeSetDataSize(long nativePtr, int size)281     private static native long nativeSetDataSize(long nativePtr, int size);
282     @CriticalNative
nativeSetDataPosition(long nativePtr, int pos)283     private static native void nativeSetDataPosition(long nativePtr, int pos);
284     @FastNative
nativeSetDataCapacity(long nativePtr, int size)285     private static native void nativeSetDataCapacity(long nativePtr, int size);
286 
287     @CriticalNative
nativePushAllowFds(long nativePtr, boolean allowFds)288     private static native boolean nativePushAllowFds(long nativePtr, boolean allowFds);
289     @CriticalNative
nativeRestoreAllowFds(long nativePtr, boolean lastValue)290     private static native void nativeRestoreAllowFds(long nativePtr, boolean lastValue);
291 
nativeWriteByteArray(long nativePtr, byte[] b, int offset, int len)292     private static native void nativeWriteByteArray(long nativePtr, byte[] b, int offset, int len);
nativeWriteBlob(long nativePtr, byte[] b, int offset, int len)293     private static native void nativeWriteBlob(long nativePtr, byte[] b, int offset, int len);
294     @FastNative
nativeWriteInt(long nativePtr, int val)295     private static native void nativeWriteInt(long nativePtr, int val);
296     @FastNative
nativeWriteLong(long nativePtr, long val)297     private static native void nativeWriteLong(long nativePtr, long val);
298     @FastNative
nativeWriteFloat(long nativePtr, float val)299     private static native void nativeWriteFloat(long nativePtr, float val);
300     @FastNative
nativeWriteDouble(long nativePtr, double val)301     private static native void nativeWriteDouble(long nativePtr, double val);
nativeWriteString(long nativePtr, String val)302     static native void nativeWriteString(long nativePtr, String val);
nativeWriteStrongBinder(long nativePtr, IBinder val)303     private static native void nativeWriteStrongBinder(long nativePtr, IBinder val);
nativeWriteFileDescriptor(long nativePtr, FileDescriptor val)304     private static native long nativeWriteFileDescriptor(long nativePtr, FileDescriptor val);
305 
nativeCreateByteArray(long nativePtr)306     private static native byte[] nativeCreateByteArray(long nativePtr);
nativeReadByteArray(long nativePtr, byte[] dest, int destLen)307     private static native boolean nativeReadByteArray(long nativePtr, byte[] dest, int destLen);
nativeReadBlob(long nativePtr)308     private static native byte[] nativeReadBlob(long nativePtr);
309     @CriticalNative
nativeReadInt(long nativePtr)310     private static native int nativeReadInt(long nativePtr);
311     @CriticalNative
nativeReadLong(long nativePtr)312     private static native long nativeReadLong(long nativePtr);
313     @CriticalNative
nativeReadFloat(long nativePtr)314     private static native float nativeReadFloat(long nativePtr);
315     @CriticalNative
nativeReadDouble(long nativePtr)316     private static native double nativeReadDouble(long nativePtr);
nativeReadString(long nativePtr)317     static native String nativeReadString(long nativePtr);
nativeReadStrongBinder(long nativePtr)318     private static native IBinder nativeReadStrongBinder(long nativePtr);
nativeReadFileDescriptor(long nativePtr)319     private static native FileDescriptor nativeReadFileDescriptor(long nativePtr);
320 
nativeCreate()321     private static native long nativeCreate();
nativeFreeBuffer(long nativePtr)322     private static native long nativeFreeBuffer(long nativePtr);
nativeDestroy(long nativePtr)323     private static native void nativeDestroy(long nativePtr);
324 
nativeMarshall(long nativePtr)325     private static native byte[] nativeMarshall(long nativePtr);
nativeUnmarshall( long nativePtr, byte[] data, int offset, int length)326     private static native long nativeUnmarshall(
327             long nativePtr, byte[] data, int offset, int length);
nativeCompareData(long thisNativePtr, long otherNativePtr)328     private static native int nativeCompareData(long thisNativePtr, long otherNativePtr);
nativeAppendFrom( long thisNativePtr, long otherNativePtr, int offset, int length)329     private static native long nativeAppendFrom(
330             long thisNativePtr, long otherNativePtr, int offset, int length);
331     @CriticalNative
nativeHasFileDescriptors(long nativePtr)332     private static native boolean nativeHasFileDescriptors(long nativePtr);
nativeWriteInterfaceToken(long nativePtr, String interfaceName)333     private static native void nativeWriteInterfaceToken(long nativePtr, String interfaceName);
nativeEnforceInterface(long nativePtr, String interfaceName)334     private static native void nativeEnforceInterface(long nativePtr, String interfaceName);
335 
336     /** Last time exception with a stack trace was written */
337     private static volatile long sLastWriteExceptionStackTrace;
338     /** Used for throttling of writing stack trace, which is costly */
339     private static final int WRITE_EXCEPTION_STACK_TRACE_THRESHOLD_MS = 1000;
340 
341     @CriticalNative
nativeGetBlobAshmemSize(long nativePtr)342     private static native long nativeGetBlobAshmemSize(long nativePtr);
343 
344     public final static Parcelable.Creator<String> STRING_CREATOR
345              = new Parcelable.Creator<String>() {
346         public String createFromParcel(Parcel source) {
347             return source.readString();
348         }
349         public String[] newArray(int size) {
350             return new String[size];
351         }
352     };
353 
354     /**
355      * @hide
356      */
357     public static class ReadWriteHelper {
358         public static final ReadWriteHelper DEFAULT = new ReadWriteHelper();
359 
360         /**
361          * Called when writing a string to a parcel. Subclasses wanting to write a string
362          * must use {@link #writeStringNoHelper(String)} to avoid
363          * infinity recursive calls.
364          */
writeString(Parcel p, String s)365         public void writeString(Parcel p, String s) {
366             nativeWriteString(p.mNativePtr, s);
367         }
368 
369         /**
370          * Called when reading a string to a parcel. Subclasses wanting to read a string
371          * must use {@link #readStringNoHelper()} to avoid
372          * infinity recursive calls.
373          */
readString(Parcel p)374         public String readString(Parcel p) {
375             return nativeReadString(p.mNativePtr);
376         }
377     }
378 
379     private ReadWriteHelper mReadWriteHelper = ReadWriteHelper.DEFAULT;
380 
381     /**
382      * Retrieve a new Parcel object from the pool.
383      */
obtain()384     public static Parcel obtain() {
385         final Parcel[] pool = sOwnedPool;
386         synchronized (pool) {
387             Parcel p;
388             for (int i=0; i<POOL_SIZE; i++) {
389                 p = pool[i];
390                 if (p != null) {
391                     pool[i] = null;
392                     if (DEBUG_RECYCLE) {
393                         p.mStack = new RuntimeException();
394                     }
395                     p.mReadWriteHelper = ReadWriteHelper.DEFAULT;
396                     return p;
397                 }
398             }
399         }
400         return new Parcel(0);
401     }
402 
403     /**
404      * Put a Parcel object back into the pool.  You must not touch
405      * the object after this call.
406      */
recycle()407     public final void recycle() {
408         if (DEBUG_RECYCLE) mStack = null;
409         freeBuffer();
410 
411         final Parcel[] pool;
412         if (mOwnsNativeParcelObject) {
413             pool = sOwnedPool;
414         } else {
415             mNativePtr = 0;
416             pool = sHolderPool;
417         }
418 
419         synchronized (pool) {
420             for (int i=0; i<POOL_SIZE; i++) {
421                 if (pool[i] == null) {
422                     pool[i] = this;
423                     return;
424                 }
425             }
426         }
427     }
428 
429     /**
430      * Set a {@link ReadWriteHelper}, which can be used to avoid having duplicate strings, for
431      * example.
432      *
433      * @hide
434      */
setReadWriteHelper(ReadWriteHelper helper)435     public void setReadWriteHelper(ReadWriteHelper helper) {
436         mReadWriteHelper = helper != null ? helper : ReadWriteHelper.DEFAULT;
437     }
438 
439     /**
440      * @return whether this parcel has a {@link ReadWriteHelper}.
441      *
442      * @hide
443      */
hasReadWriteHelper()444     public boolean hasReadWriteHelper() {
445         return (mReadWriteHelper != null) && (mReadWriteHelper != ReadWriteHelper.DEFAULT);
446     }
447 
448     /** @hide */
getGlobalAllocSize()449     public static native long getGlobalAllocSize();
450 
451     /** @hide */
getGlobalAllocCount()452     public static native long getGlobalAllocCount();
453 
454     /**
455      * Returns the total amount of data contained in the parcel.
456      */
dataSize()457     public final int dataSize() {
458         return nativeDataSize(mNativePtr);
459     }
460 
461     /**
462      * Returns the amount of data remaining to be read from the
463      * parcel.  That is, {@link #dataSize}-{@link #dataPosition}.
464      */
dataAvail()465     public final int dataAvail() {
466         return nativeDataAvail(mNativePtr);
467     }
468 
469     /**
470      * Returns the current position in the parcel data.  Never
471      * more than {@link #dataSize}.
472      */
dataPosition()473     public final int dataPosition() {
474         return nativeDataPosition(mNativePtr);
475     }
476 
477     /**
478      * Returns the total amount of space in the parcel.  This is always
479      * >= {@link #dataSize}.  The difference between it and dataSize() is the
480      * amount of room left until the parcel needs to re-allocate its
481      * data buffer.
482      */
dataCapacity()483     public final int dataCapacity() {
484         return nativeDataCapacity(mNativePtr);
485     }
486 
487     /**
488      * Change the amount of data in the parcel.  Can be either smaller or
489      * larger than the current size.  If larger than the current capacity,
490      * more memory will be allocated.
491      *
492      * @param size The new number of bytes in the Parcel.
493      */
setDataSize(int size)494     public final void setDataSize(int size) {
495         updateNativeSize(nativeSetDataSize(mNativePtr, size));
496     }
497 
498     /**
499      * Move the current read/write position in the parcel.
500      * @param pos New offset in the parcel; must be between 0 and
501      * {@link #dataSize}.
502      */
setDataPosition(int pos)503     public final void setDataPosition(int pos) {
504         nativeSetDataPosition(mNativePtr, pos);
505     }
506 
507     /**
508      * Change the capacity (current available space) of the parcel.
509      *
510      * @param size The new capacity of the parcel, in bytes.  Can not be
511      * less than {@link #dataSize} -- that is, you can not drop existing data
512      * with this method.
513      */
setDataCapacity(int size)514     public final void setDataCapacity(int size) {
515         nativeSetDataCapacity(mNativePtr, size);
516     }
517 
518     /** @hide */
pushAllowFds(boolean allowFds)519     public final boolean pushAllowFds(boolean allowFds) {
520         return nativePushAllowFds(mNativePtr, allowFds);
521     }
522 
523     /** @hide */
restoreAllowFds(boolean lastValue)524     public final void restoreAllowFds(boolean lastValue) {
525         nativeRestoreAllowFds(mNativePtr, lastValue);
526     }
527 
528     /**
529      * Returns the raw bytes of the parcel.
530      *
531      * <p class="note">The data you retrieve here <strong>must not</strong>
532      * be placed in any kind of persistent storage (on local disk, across
533      * a network, etc).  For that, you should use standard serialization
534      * or another kind of general serialization mechanism.  The Parcel
535      * marshalled representation is highly optimized for local IPC, and as
536      * such does not attempt to maintain compatibility with data created
537      * in different versions of the platform.
538      */
marshall()539     public final byte[] marshall() {
540         return nativeMarshall(mNativePtr);
541     }
542 
543     /**
544      * Set the bytes in data to be the raw bytes of this Parcel.
545      */
unmarshall(byte[] data, int offset, int length)546     public final void unmarshall(byte[] data, int offset, int length) {
547         updateNativeSize(nativeUnmarshall(mNativePtr, data, offset, length));
548     }
549 
appendFrom(Parcel parcel, int offset, int length)550     public final void appendFrom(Parcel parcel, int offset, int length) {
551         updateNativeSize(nativeAppendFrom(mNativePtr, parcel.mNativePtr, offset, length));
552     }
553 
554     /** @hide */
compareData(Parcel other)555     public final int compareData(Parcel other) {
556         return nativeCompareData(mNativePtr, other.mNativePtr);
557     }
558 
559     /** @hide */
setClassCookie(Class clz, Object cookie)560     public final void setClassCookie(Class clz, Object cookie) {
561         if (mClassCookies == null) {
562             mClassCookies = new ArrayMap<>();
563         }
564         mClassCookies.put(clz, cookie);
565     }
566 
567     /** @hide */
getClassCookie(Class clz)568     public final Object getClassCookie(Class clz) {
569         return mClassCookies != null ? mClassCookies.get(clz) : null;
570     }
571 
572     /** @hide */
adoptClassCookies(Parcel from)573     public final void adoptClassCookies(Parcel from) {
574         mClassCookies = from.mClassCookies;
575     }
576 
577     /** @hide */
copyClassCookies()578     public Map<Class, Object> copyClassCookies() {
579         return new ArrayMap<>(mClassCookies);
580     }
581 
582     /** @hide */
putClassCookies(Map<Class, Object> cookies)583     public void putClassCookies(Map<Class, Object> cookies) {
584         if (cookies == null) {
585             return;
586         }
587         if (mClassCookies == null) {
588             mClassCookies = new ArrayMap<>();
589         }
590         mClassCookies.putAll(cookies);
591     }
592 
593     /**
594      * Report whether the parcel contains any marshalled file descriptors.
595      */
hasFileDescriptors()596     public final boolean hasFileDescriptors() {
597         return nativeHasFileDescriptors(mNativePtr);
598     }
599 
600     /**
601      * Store or read an IBinder interface token in the parcel at the current
602      * {@link #dataPosition}.  This is used to validate that the marshalled
603      * transaction is intended for the target interface.
604      */
writeInterfaceToken(String interfaceName)605     public final void writeInterfaceToken(String interfaceName) {
606         nativeWriteInterfaceToken(mNativePtr, interfaceName);
607     }
608 
enforceInterface(String interfaceName)609     public final void enforceInterface(String interfaceName) {
610         nativeEnforceInterface(mNativePtr, interfaceName);
611     }
612 
613     /**
614      * Write a byte array into the parcel at the current {@link #dataPosition},
615      * growing {@link #dataCapacity} if needed.
616      * @param b Bytes to place into the parcel.
617      */
writeByteArray(byte[] b)618     public final void writeByteArray(byte[] b) {
619         writeByteArray(b, 0, (b != null) ? b.length : 0);
620     }
621 
622     /**
623      * Write a byte array into the parcel at the current {@link #dataPosition},
624      * growing {@link #dataCapacity} if needed.
625      * @param b Bytes to place into the parcel.
626      * @param offset Index of first byte to be written.
627      * @param len Number of bytes to write.
628      */
writeByteArray(byte[] b, int offset, int len)629     public final void writeByteArray(byte[] b, int offset, int len) {
630         if (b == null) {
631             writeInt(-1);
632             return;
633         }
634         Arrays.checkOffsetAndCount(b.length, offset, len);
635         nativeWriteByteArray(mNativePtr, b, offset, len);
636     }
637 
638     /**
639      * Write a blob of data into the parcel at the current {@link #dataPosition},
640      * growing {@link #dataCapacity} if needed.
641      * @param b Bytes to place into the parcel.
642      * {@hide}
643      * {@SystemApi}
644      */
writeBlob(byte[] b)645     public final void writeBlob(byte[] b) {
646         writeBlob(b, 0, (b != null) ? b.length : 0);
647     }
648 
649     /**
650      * Write a blob of data into the parcel at the current {@link #dataPosition},
651      * growing {@link #dataCapacity} if needed.
652      * @param b Bytes to place into the parcel.
653      * @param offset Index of first byte to be written.
654      * @param len Number of bytes to write.
655      * {@hide}
656      * {@SystemApi}
657      */
writeBlob(byte[] b, int offset, int len)658     public final void writeBlob(byte[] b, int offset, int len) {
659         if (b == null) {
660             writeInt(-1);
661             return;
662         }
663         Arrays.checkOffsetAndCount(b.length, offset, len);
664         nativeWriteBlob(mNativePtr, b, offset, len);
665     }
666 
667     /**
668      * Write an integer value into the parcel at the current dataPosition(),
669      * growing dataCapacity() if needed.
670      */
writeInt(int val)671     public final void writeInt(int val) {
672         nativeWriteInt(mNativePtr, val);
673     }
674 
675     /**
676      * Write a long integer value into the parcel at the current dataPosition(),
677      * growing dataCapacity() if needed.
678      */
writeLong(long val)679     public final void writeLong(long val) {
680         nativeWriteLong(mNativePtr, val);
681     }
682 
683     /**
684      * Write a floating point value into the parcel at the current
685      * dataPosition(), growing dataCapacity() if needed.
686      */
writeFloat(float val)687     public final void writeFloat(float val) {
688         nativeWriteFloat(mNativePtr, val);
689     }
690 
691     /**
692      * Write a double precision floating point value into the parcel at the
693      * current dataPosition(), growing dataCapacity() if needed.
694      */
writeDouble(double val)695     public final void writeDouble(double val) {
696         nativeWriteDouble(mNativePtr, val);
697     }
698 
699     /**
700      * Write a string value into the parcel at the current dataPosition(),
701      * growing dataCapacity() if needed.
702      */
writeString(String val)703     public final void writeString(String val) {
704         mReadWriteHelper.writeString(this, val);
705     }
706 
707     /**
708      * Write a string without going though a {@link ReadWriteHelper}.  Subclasses of
709      * {@link ReadWriteHelper} must use this method instead of {@link #writeString} to avoid
710      * infinity recursive calls.
711      *
712      * @hide
713      */
writeStringNoHelper(String val)714     public void writeStringNoHelper(String val) {
715         nativeWriteString(mNativePtr, val);
716     }
717 
718     /** @hide */
writeBoolean(boolean val)719     public final void writeBoolean(boolean val) {
720         writeInt(val ? 1 : 0);
721     }
722 
723     /**
724      * Write a CharSequence value into the parcel at the current dataPosition(),
725      * growing dataCapacity() if needed.
726      * @hide
727      */
writeCharSequence(CharSequence val)728     public final void writeCharSequence(CharSequence val) {
729         TextUtils.writeToParcel(val, this, 0);
730     }
731 
732     /**
733      * Write an object into the parcel at the current dataPosition(),
734      * growing dataCapacity() if needed.
735      */
writeStrongBinder(IBinder val)736     public final void writeStrongBinder(IBinder val) {
737         nativeWriteStrongBinder(mNativePtr, val);
738     }
739 
740     /**
741      * Write an object into the parcel at the current dataPosition(),
742      * growing dataCapacity() if needed.
743      */
writeStrongInterface(IInterface val)744     public final void writeStrongInterface(IInterface val) {
745         writeStrongBinder(val == null ? null : val.asBinder());
746     }
747 
748     /**
749      * Write a FileDescriptor into the parcel at the current dataPosition(),
750      * growing dataCapacity() if needed.
751      *
752      * <p class="caution">The file descriptor will not be closed, which may
753      * result in file descriptor leaks when objects are returned from Binder
754      * calls.  Use {@link ParcelFileDescriptor#writeToParcel} instead, which
755      * accepts contextual flags and will close the original file descriptor
756      * if {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set.</p>
757      */
writeFileDescriptor(FileDescriptor val)758     public final void writeFileDescriptor(FileDescriptor val) {
759         updateNativeSize(nativeWriteFileDescriptor(mNativePtr, val));
760     }
761 
updateNativeSize(long newNativeSize)762     private void updateNativeSize(long newNativeSize) {
763         if (mOwnsNativeParcelObject) {
764             if (newNativeSize > Integer.MAX_VALUE) {
765                 newNativeSize = Integer.MAX_VALUE;
766             }
767             if (newNativeSize != mNativeSize) {
768                 int delta = (int) (newNativeSize - mNativeSize);
769                 if (delta > 0) {
770                     VMRuntime.getRuntime().registerNativeAllocation(delta);
771                 } else {
772                     VMRuntime.getRuntime().registerNativeFree(-delta);
773                 }
774                 mNativeSize = newNativeSize;
775             }
776         }
777     }
778 
779     /**
780      * {@hide}
781      * This will be the new name for writeFileDescriptor, for consistency.
782      **/
writeRawFileDescriptor(FileDescriptor val)783     public final void writeRawFileDescriptor(FileDescriptor val) {
784         nativeWriteFileDescriptor(mNativePtr, val);
785     }
786 
787     /**
788      * {@hide}
789      * Write an array of FileDescriptor objects into the Parcel.
790      *
791      * @param value The array of objects to be written.
792      */
writeRawFileDescriptorArray(FileDescriptor[] value)793     public final void writeRawFileDescriptorArray(FileDescriptor[] value) {
794         if (value != null) {
795             int N = value.length;
796             writeInt(N);
797             for (int i=0; i<N; i++) {
798                 writeRawFileDescriptor(value[i]);
799             }
800         } else {
801             writeInt(-1);
802         }
803     }
804 
805     /**
806      * Write a byte value into the parcel at the current dataPosition(),
807      * growing dataCapacity() if needed.
808      */
writeByte(byte val)809     public final void writeByte(byte val) {
810         writeInt(val);
811     }
812 
813     /**
814      * Please use {@link #writeBundle} instead.  Flattens a Map into the parcel
815      * at the current dataPosition(),
816      * growing dataCapacity() if needed.  The Map keys must be String objects.
817      * The Map values are written using {@link #writeValue} and must follow
818      * the specification there.
819      *
820      * <p>It is strongly recommended to use {@link #writeBundle} instead of
821      * this method, since the Bundle class provides a type-safe API that
822      * allows you to avoid mysterious type errors at the point of marshalling.
823      */
writeMap(Map val)824     public final void writeMap(Map val) {
825         writeMapInternal((Map<String, Object>) val);
826     }
827 
828     /**
829      * Flatten a Map into the parcel at the current dataPosition(),
830      * growing dataCapacity() if needed.  The Map keys must be String objects.
831      */
writeMapInternal(Map<String,Object> val)832     /* package */ void writeMapInternal(Map<String,Object> val) {
833         if (val == null) {
834             writeInt(-1);
835             return;
836         }
837         Set<Map.Entry<String,Object>> entries = val.entrySet();
838         writeInt(entries.size());
839         for (Map.Entry<String,Object> e : entries) {
840             writeValue(e.getKey());
841             writeValue(e.getValue());
842         }
843     }
844 
845     /**
846      * Flatten an ArrayMap into the parcel at the current dataPosition(),
847      * growing dataCapacity() if needed.  The Map keys must be String objects.
848      */
writeArrayMapInternal(ArrayMap<String, Object> val)849     /* package */ void writeArrayMapInternal(ArrayMap<String, Object> val) {
850         if (val == null) {
851             writeInt(-1);
852             return;
853         }
854         // Keep the format of this Parcel in sync with writeToParcelInner() in
855         // frameworks/native/libs/binder/PersistableBundle.cpp.
856         final int N = val.size();
857         writeInt(N);
858         if (DEBUG_ARRAY_MAP) {
859             RuntimeException here =  new RuntimeException("here");
860             here.fillInStackTrace();
861             Log.d(TAG, "Writing " + N + " ArrayMap entries", here);
862         }
863         int startPos;
864         for (int i=0; i<N; i++) {
865             if (DEBUG_ARRAY_MAP) startPos = dataPosition();
866             writeString(val.keyAt(i));
867             writeValue(val.valueAt(i));
868             if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Write #" + i + " "
869                     + (dataPosition()-startPos) + " bytes: key=0x"
870                     + Integer.toHexString(val.keyAt(i) != null ? val.keyAt(i).hashCode() : 0)
871                     + " " + val.keyAt(i));
872         }
873     }
874 
875     /**
876      * @hide For testing only.
877      */
writeArrayMap(ArrayMap<String, Object> val)878     public void writeArrayMap(ArrayMap<String, Object> val) {
879         writeArrayMapInternal(val);
880     }
881 
882     /**
883      * Write an array set to the parcel.
884      *
885      * @param val The array set to write.
886      *
887      * @hide
888      */
writeArraySet(@ullable ArraySet<? extends Object> val)889     public void writeArraySet(@Nullable ArraySet<? extends Object> val) {
890         final int size = (val != null) ? val.size() : -1;
891         writeInt(size);
892         for (int i = 0; i < size; i++) {
893             writeValue(val.valueAt(i));
894         }
895     }
896 
897     /**
898      * Flatten a Bundle into the parcel at the current dataPosition(),
899      * growing dataCapacity() if needed.
900      */
writeBundle(Bundle val)901     public final void writeBundle(Bundle val) {
902         if (val == null) {
903             writeInt(-1);
904             return;
905         }
906 
907         val.writeToParcel(this, 0);
908     }
909 
910     /**
911      * Flatten a PersistableBundle into the parcel at the current dataPosition(),
912      * growing dataCapacity() if needed.
913      */
writePersistableBundle(PersistableBundle val)914     public final void writePersistableBundle(PersistableBundle val) {
915         if (val == null) {
916             writeInt(-1);
917             return;
918         }
919 
920         val.writeToParcel(this, 0);
921     }
922 
923     /**
924      * Flatten a Size into the parcel at the current dataPosition(),
925      * growing dataCapacity() if needed.
926      */
writeSize(Size val)927     public final void writeSize(Size val) {
928         writeInt(val.getWidth());
929         writeInt(val.getHeight());
930     }
931 
932     /**
933      * Flatten a SizeF into the parcel at the current dataPosition(),
934      * growing dataCapacity() if needed.
935      */
writeSizeF(SizeF val)936     public final void writeSizeF(SizeF val) {
937         writeFloat(val.getWidth());
938         writeFloat(val.getHeight());
939     }
940 
941     /**
942      * Flatten a List into the parcel at the current dataPosition(), growing
943      * dataCapacity() if needed.  The List values are written using
944      * {@link #writeValue} and must follow the specification there.
945      */
writeList(List val)946     public final void writeList(List val) {
947         if (val == null) {
948             writeInt(-1);
949             return;
950         }
951         int N = val.size();
952         int i=0;
953         writeInt(N);
954         while (i < N) {
955             writeValue(val.get(i));
956             i++;
957         }
958     }
959 
960     /**
961      * Flatten an Object array into the parcel at the current dataPosition(),
962      * growing dataCapacity() if needed.  The array values are written using
963      * {@link #writeValue} and must follow the specification there.
964      */
writeArray(Object[] val)965     public final void writeArray(Object[] val) {
966         if (val == null) {
967             writeInt(-1);
968             return;
969         }
970         int N = val.length;
971         int i=0;
972         writeInt(N);
973         while (i < N) {
974             writeValue(val[i]);
975             i++;
976         }
977     }
978 
979     /**
980      * Flatten a generic SparseArray into the parcel at the current
981      * dataPosition(), growing dataCapacity() if needed.  The SparseArray
982      * values are written using {@link #writeValue} and must follow the
983      * specification there.
984      */
writeSparseArray(SparseArray<Object> val)985     public final void writeSparseArray(SparseArray<Object> val) {
986         if (val == null) {
987             writeInt(-1);
988             return;
989         }
990         int N = val.size();
991         writeInt(N);
992         int i=0;
993         while (i < N) {
994             writeInt(val.keyAt(i));
995             writeValue(val.valueAt(i));
996             i++;
997         }
998     }
999 
writeSparseBooleanArray(SparseBooleanArray val)1000     public final void writeSparseBooleanArray(SparseBooleanArray val) {
1001         if (val == null) {
1002             writeInt(-1);
1003             return;
1004         }
1005         int N = val.size();
1006         writeInt(N);
1007         int i=0;
1008         while (i < N) {
1009             writeInt(val.keyAt(i));
1010             writeByte((byte)(val.valueAt(i) ? 1 : 0));
1011             i++;
1012         }
1013     }
1014 
1015     /**
1016      * @hide
1017      */
writeSparseIntArray(SparseIntArray val)1018     public final void writeSparseIntArray(SparseIntArray val) {
1019         if (val == null) {
1020             writeInt(-1);
1021             return;
1022         }
1023         int N = val.size();
1024         writeInt(N);
1025         int i=0;
1026         while (i < N) {
1027             writeInt(val.keyAt(i));
1028             writeInt(val.valueAt(i));
1029             i++;
1030         }
1031     }
1032 
writeBooleanArray(boolean[] val)1033     public final void writeBooleanArray(boolean[] val) {
1034         if (val != null) {
1035             int N = val.length;
1036             writeInt(N);
1037             for (int i=0; i<N; i++) {
1038                 writeInt(val[i] ? 1 : 0);
1039             }
1040         } else {
1041             writeInt(-1);
1042         }
1043     }
1044 
createBooleanArray()1045     public final boolean[] createBooleanArray() {
1046         int N = readInt();
1047         // >>2 as a fast divide-by-4 works in the create*Array() functions
1048         // because dataAvail() will never return a negative number.  4 is
1049         // the size of a stored boolean in the stream.
1050         if (N >= 0 && N <= (dataAvail() >> 2)) {
1051             boolean[] val = new boolean[N];
1052             for (int i=0; i<N; i++) {
1053                 val[i] = readInt() != 0;
1054             }
1055             return val;
1056         } else {
1057             return null;
1058         }
1059     }
1060 
readBooleanArray(boolean[] val)1061     public final void readBooleanArray(boolean[] val) {
1062         int N = readInt();
1063         if (N == val.length) {
1064             for (int i=0; i<N; i++) {
1065                 val[i] = readInt() != 0;
1066             }
1067         } else {
1068             throw new RuntimeException("bad array lengths");
1069         }
1070     }
1071 
writeCharArray(char[] val)1072     public final void writeCharArray(char[] val) {
1073         if (val != null) {
1074             int N = val.length;
1075             writeInt(N);
1076             for (int i=0; i<N; i++) {
1077                 writeInt((int)val[i]);
1078             }
1079         } else {
1080             writeInt(-1);
1081         }
1082     }
1083 
createCharArray()1084     public final char[] createCharArray() {
1085         int N = readInt();
1086         if (N >= 0 && N <= (dataAvail() >> 2)) {
1087             char[] val = new char[N];
1088             for (int i=0; i<N; i++) {
1089                 val[i] = (char)readInt();
1090             }
1091             return val;
1092         } else {
1093             return null;
1094         }
1095     }
1096 
readCharArray(char[] val)1097     public final void readCharArray(char[] val) {
1098         int N = readInt();
1099         if (N == val.length) {
1100             for (int i=0; i<N; i++) {
1101                 val[i] = (char)readInt();
1102             }
1103         } else {
1104             throw new RuntimeException("bad array lengths");
1105         }
1106     }
1107 
writeIntArray(int[] val)1108     public final void writeIntArray(int[] val) {
1109         if (val != null) {
1110             int N = val.length;
1111             writeInt(N);
1112             for (int i=0; i<N; i++) {
1113                 writeInt(val[i]);
1114             }
1115         } else {
1116             writeInt(-1);
1117         }
1118     }
1119 
createIntArray()1120     public final int[] createIntArray() {
1121         int N = readInt();
1122         if (N >= 0 && N <= (dataAvail() >> 2)) {
1123             int[] val = new int[N];
1124             for (int i=0; i<N; i++) {
1125                 val[i] = readInt();
1126             }
1127             return val;
1128         } else {
1129             return null;
1130         }
1131     }
1132 
readIntArray(int[] val)1133     public final void readIntArray(int[] val) {
1134         int N = readInt();
1135         if (N == val.length) {
1136             for (int i=0; i<N; i++) {
1137                 val[i] = readInt();
1138             }
1139         } else {
1140             throw new RuntimeException("bad array lengths");
1141         }
1142     }
1143 
writeLongArray(long[] val)1144     public final void writeLongArray(long[] val) {
1145         if (val != null) {
1146             int N = val.length;
1147             writeInt(N);
1148             for (int i=0; i<N; i++) {
1149                 writeLong(val[i]);
1150             }
1151         } else {
1152             writeInt(-1);
1153         }
1154     }
1155 
createLongArray()1156     public final long[] createLongArray() {
1157         int N = readInt();
1158         // >>3 because stored longs are 64 bits
1159         if (N >= 0 && N <= (dataAvail() >> 3)) {
1160             long[] val = new long[N];
1161             for (int i=0; i<N; i++) {
1162                 val[i] = readLong();
1163             }
1164             return val;
1165         } else {
1166             return null;
1167         }
1168     }
1169 
readLongArray(long[] val)1170     public final void readLongArray(long[] val) {
1171         int N = readInt();
1172         if (N == val.length) {
1173             for (int i=0; i<N; i++) {
1174                 val[i] = readLong();
1175             }
1176         } else {
1177             throw new RuntimeException("bad array lengths");
1178         }
1179     }
1180 
writeFloatArray(float[] val)1181     public final void writeFloatArray(float[] val) {
1182         if (val != null) {
1183             int N = val.length;
1184             writeInt(N);
1185             for (int i=0; i<N; i++) {
1186                 writeFloat(val[i]);
1187             }
1188         } else {
1189             writeInt(-1);
1190         }
1191     }
1192 
createFloatArray()1193     public final float[] createFloatArray() {
1194         int N = readInt();
1195         // >>2 because stored floats are 4 bytes
1196         if (N >= 0 && N <= (dataAvail() >> 2)) {
1197             float[] val = new float[N];
1198             for (int i=0; i<N; i++) {
1199                 val[i] = readFloat();
1200             }
1201             return val;
1202         } else {
1203             return null;
1204         }
1205     }
1206 
readFloatArray(float[] val)1207     public final void readFloatArray(float[] val) {
1208         int N = readInt();
1209         if (N == val.length) {
1210             for (int i=0; i<N; i++) {
1211                 val[i] = readFloat();
1212             }
1213         } else {
1214             throw new RuntimeException("bad array lengths");
1215         }
1216     }
1217 
writeDoubleArray(double[] val)1218     public final void writeDoubleArray(double[] val) {
1219         if (val != null) {
1220             int N = val.length;
1221             writeInt(N);
1222             for (int i=0; i<N; i++) {
1223                 writeDouble(val[i]);
1224             }
1225         } else {
1226             writeInt(-1);
1227         }
1228     }
1229 
createDoubleArray()1230     public final double[] createDoubleArray() {
1231         int N = readInt();
1232         // >>3 because stored doubles are 8 bytes
1233         if (N >= 0 && N <= (dataAvail() >> 3)) {
1234             double[] val = new double[N];
1235             for (int i=0; i<N; i++) {
1236                 val[i] = readDouble();
1237             }
1238             return val;
1239         } else {
1240             return null;
1241         }
1242     }
1243 
readDoubleArray(double[] val)1244     public final void readDoubleArray(double[] val) {
1245         int N = readInt();
1246         if (N == val.length) {
1247             for (int i=0; i<N; i++) {
1248                 val[i] = readDouble();
1249             }
1250         } else {
1251             throw new RuntimeException("bad array lengths");
1252         }
1253     }
1254 
writeStringArray(String[] val)1255     public final void writeStringArray(String[] val) {
1256         if (val != null) {
1257             int N = val.length;
1258             writeInt(N);
1259             for (int i=0; i<N; i++) {
1260                 writeString(val[i]);
1261             }
1262         } else {
1263             writeInt(-1);
1264         }
1265     }
1266 
createStringArray()1267     public final String[] createStringArray() {
1268         int N = readInt();
1269         if (N >= 0) {
1270             String[] val = new String[N];
1271             for (int i=0; i<N; i++) {
1272                 val[i] = readString();
1273             }
1274             return val;
1275         } else {
1276             return null;
1277         }
1278     }
1279 
readStringArray(String[] val)1280     public final void readStringArray(String[] val) {
1281         int N = readInt();
1282         if (N == val.length) {
1283             for (int i=0; i<N; i++) {
1284                 val[i] = readString();
1285             }
1286         } else {
1287             throw new RuntimeException("bad array lengths");
1288         }
1289     }
1290 
writeBinderArray(IBinder[] val)1291     public final void writeBinderArray(IBinder[] val) {
1292         if (val != null) {
1293             int N = val.length;
1294             writeInt(N);
1295             for (int i=0; i<N; i++) {
1296                 writeStrongBinder(val[i]);
1297             }
1298         } else {
1299             writeInt(-1);
1300         }
1301     }
1302 
1303     /**
1304      * @hide
1305      */
writeCharSequenceArray(CharSequence[] val)1306     public final void writeCharSequenceArray(CharSequence[] val) {
1307         if (val != null) {
1308             int N = val.length;
1309             writeInt(N);
1310             for (int i=0; i<N; i++) {
1311                 writeCharSequence(val[i]);
1312             }
1313         } else {
1314             writeInt(-1);
1315         }
1316     }
1317 
1318     /**
1319      * @hide
1320      */
writeCharSequenceList(ArrayList<CharSequence> val)1321     public final void writeCharSequenceList(ArrayList<CharSequence> val) {
1322         if (val != null) {
1323             int N = val.size();
1324             writeInt(N);
1325             for (int i=0; i<N; i++) {
1326                 writeCharSequence(val.get(i));
1327             }
1328         } else {
1329             writeInt(-1);
1330         }
1331     }
1332 
createBinderArray()1333     public final IBinder[] createBinderArray() {
1334         int N = readInt();
1335         if (N >= 0) {
1336             IBinder[] val = new IBinder[N];
1337             for (int i=0; i<N; i++) {
1338                 val[i] = readStrongBinder();
1339             }
1340             return val;
1341         } else {
1342             return null;
1343         }
1344     }
1345 
readBinderArray(IBinder[] val)1346     public final void readBinderArray(IBinder[] val) {
1347         int N = readInt();
1348         if (N == val.length) {
1349             for (int i=0; i<N; i++) {
1350                 val[i] = readStrongBinder();
1351             }
1352         } else {
1353             throw new RuntimeException("bad array lengths");
1354         }
1355     }
1356 
1357     /**
1358      * Flatten a List containing a particular object type into the parcel, at
1359      * the current dataPosition() and growing dataCapacity() if needed.  The
1360      * type of the objects in the list must be one that implements Parcelable.
1361      * Unlike the generic writeList() method, however, only the raw data of the
1362      * objects is written and not their type, so you must use the corresponding
1363      * readTypedList() to unmarshall them.
1364      *
1365      * @param val The list of objects to be written.
1366      *
1367      * @see #createTypedArrayList
1368      * @see #readTypedList
1369      * @see Parcelable
1370      */
writeTypedList(List<T> val)1371     public final <T extends Parcelable> void writeTypedList(List<T> val) {
1372         writeTypedList(val, 0);
1373     }
1374 
1375     /**
1376      * @hide
1377      */
writeTypedList(List<T> val, int parcelableFlags)1378     public <T extends Parcelable> void writeTypedList(List<T> val, int parcelableFlags) {
1379         if (val == null) {
1380             writeInt(-1);
1381             return;
1382         }
1383         int N = val.size();
1384         int i=0;
1385         writeInt(N);
1386         while (i < N) {
1387             writeTypedObject(val.get(i), parcelableFlags);
1388             i++;
1389         }
1390     }
1391 
1392     /**
1393      * Flatten a List containing String objects into the parcel, at
1394      * the current dataPosition() and growing dataCapacity() if needed.  They
1395      * can later be retrieved with {@link #createStringArrayList} or
1396      * {@link #readStringList}.
1397      *
1398      * @param val The list of strings to be written.
1399      *
1400      * @see #createStringArrayList
1401      * @see #readStringList
1402      */
writeStringList(List<String> val)1403     public final void writeStringList(List<String> val) {
1404         if (val == null) {
1405             writeInt(-1);
1406             return;
1407         }
1408         int N = val.size();
1409         int i=0;
1410         writeInt(N);
1411         while (i < N) {
1412             writeString(val.get(i));
1413             i++;
1414         }
1415     }
1416 
1417     /**
1418      * Flatten a List containing IBinder objects into the parcel, at
1419      * the current dataPosition() and growing dataCapacity() if needed.  They
1420      * can later be retrieved with {@link #createBinderArrayList} or
1421      * {@link #readBinderList}.
1422      *
1423      * @param val The list of strings to be written.
1424      *
1425      * @see #createBinderArrayList
1426      * @see #readBinderList
1427      */
writeBinderList(List<IBinder> val)1428     public final void writeBinderList(List<IBinder> val) {
1429         if (val == null) {
1430             writeInt(-1);
1431             return;
1432         }
1433         int N = val.size();
1434         int i=0;
1435         writeInt(N);
1436         while (i < N) {
1437             writeStrongBinder(val.get(i));
1438             i++;
1439         }
1440     }
1441 
1442     /**
1443      * Flatten a {@code List} containing arbitrary {@code Parcelable} objects into this parcel
1444      * at the current position. They can later be retrieved using
1445      * {@link #readParcelableList(List, ClassLoader)} if required.
1446      *
1447      * @see #readParcelableList(List, ClassLoader)
1448      * @hide
1449      */
writeParcelableList(List<T> val, int flags)1450     public final <T extends Parcelable> void writeParcelableList(List<T> val, int flags) {
1451         if (val == null) {
1452             writeInt(-1);
1453             return;
1454         }
1455 
1456         int N = val.size();
1457         int i=0;
1458         writeInt(N);
1459         while (i < N) {
1460             writeParcelable(val.get(i), flags);
1461             i++;
1462         }
1463     }
1464 
1465     /**
1466      * Flatten a homogeneous array containing a particular object type into
1467      * the parcel, at
1468      * the current dataPosition() and growing dataCapacity() if needed.  The
1469      * type of the objects in the array must be one that implements Parcelable.
1470      * Unlike the {@link #writeParcelableArray} method, however, only the
1471      * raw data of the objects is written and not their type, so you must use
1472      * {@link #readTypedArray} with the correct corresponding
1473      * {@link Parcelable.Creator} implementation to unmarshall them.
1474      *
1475      * @param val The array of objects to be written.
1476      * @param parcelableFlags Contextual flags as per
1477      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1478      *
1479      * @see #readTypedArray
1480      * @see #writeParcelableArray
1481      * @see Parcelable.Creator
1482      */
writeTypedArray(T[] val, int parcelableFlags)1483     public final <T extends Parcelable> void writeTypedArray(T[] val,
1484             int parcelableFlags) {
1485         if (val != null) {
1486             int N = val.length;
1487             writeInt(N);
1488             for (int i = 0; i < N; i++) {
1489                 writeTypedObject(val[i], parcelableFlags);
1490             }
1491         } else {
1492             writeInt(-1);
1493         }
1494     }
1495 
1496     /**
1497      * Flatten the Parcelable object into the parcel.
1498      *
1499      * @param val The Parcelable object to be written.
1500      * @param parcelableFlags Contextual flags as per
1501      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1502      *
1503      * @see #readTypedObject
1504      */
writeTypedObject(T val, int parcelableFlags)1505     public final <T extends Parcelable> void writeTypedObject(T val, int parcelableFlags) {
1506         if (val != null) {
1507             writeInt(1);
1508             val.writeToParcel(this, parcelableFlags);
1509         } else {
1510             writeInt(0);
1511         }
1512     }
1513 
1514     /**
1515      * Flatten a generic object in to a parcel.  The given Object value may
1516      * currently be one of the following types:
1517      *
1518      * <ul>
1519      * <li> null
1520      * <li> String
1521      * <li> Byte
1522      * <li> Short
1523      * <li> Integer
1524      * <li> Long
1525      * <li> Float
1526      * <li> Double
1527      * <li> Boolean
1528      * <li> String[]
1529      * <li> boolean[]
1530      * <li> byte[]
1531      * <li> int[]
1532      * <li> long[]
1533      * <li> Object[] (supporting objects of the same type defined here).
1534      * <li> {@link Bundle}
1535      * <li> Map (as supported by {@link #writeMap}).
1536      * <li> Any object that implements the {@link Parcelable} protocol.
1537      * <li> Parcelable[]
1538      * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
1539      * <li> List (as supported by {@link #writeList}).
1540      * <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}).
1541      * <li> {@link IBinder}
1542      * <li> Any object that implements Serializable (but see
1543      *      {@link #writeSerializable} for caveats).  Note that all of the
1544      *      previous types have relatively efficient implementations for
1545      *      writing to a Parcel; having to rely on the generic serialization
1546      *      approach is much less efficient and should be avoided whenever
1547      *      possible.
1548      * </ul>
1549      *
1550      * <p class="caution">{@link Parcelable} objects are written with
1551      * {@link Parcelable#writeToParcel} using contextual flags of 0.  When
1552      * serializing objects containing {@link ParcelFileDescriptor}s,
1553      * this may result in file descriptor leaks when they are returned from
1554      * Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE}
1555      * should be used).</p>
1556      */
writeValue(Object v)1557     public final void writeValue(Object v) {
1558         if (v == null) {
1559             writeInt(VAL_NULL);
1560         } else if (v instanceof String) {
1561             writeInt(VAL_STRING);
1562             writeString((String) v);
1563         } else if (v instanceof Integer) {
1564             writeInt(VAL_INTEGER);
1565             writeInt((Integer) v);
1566         } else if (v instanceof Map) {
1567             writeInt(VAL_MAP);
1568             writeMap((Map) v);
1569         } else if (v instanceof Bundle) {
1570             // Must be before Parcelable
1571             writeInt(VAL_BUNDLE);
1572             writeBundle((Bundle) v);
1573         } else if (v instanceof PersistableBundle) {
1574             writeInt(VAL_PERSISTABLEBUNDLE);
1575             writePersistableBundle((PersistableBundle) v);
1576         } else if (v instanceof Parcelable) {
1577             // IMPOTANT: cases for classes that implement Parcelable must
1578             // come before the Parcelable case, so that their specific VAL_*
1579             // types will be written.
1580             writeInt(VAL_PARCELABLE);
1581             writeParcelable((Parcelable) v, 0);
1582         } else if (v instanceof Short) {
1583             writeInt(VAL_SHORT);
1584             writeInt(((Short) v).intValue());
1585         } else if (v instanceof Long) {
1586             writeInt(VAL_LONG);
1587             writeLong((Long) v);
1588         } else if (v instanceof Float) {
1589             writeInt(VAL_FLOAT);
1590             writeFloat((Float) v);
1591         } else if (v instanceof Double) {
1592             writeInt(VAL_DOUBLE);
1593             writeDouble((Double) v);
1594         } else if (v instanceof Boolean) {
1595             writeInt(VAL_BOOLEAN);
1596             writeInt((Boolean) v ? 1 : 0);
1597         } else if (v instanceof CharSequence) {
1598             // Must be after String
1599             writeInt(VAL_CHARSEQUENCE);
1600             writeCharSequence((CharSequence) v);
1601         } else if (v instanceof List) {
1602             writeInt(VAL_LIST);
1603             writeList((List) v);
1604         } else if (v instanceof SparseArray) {
1605             writeInt(VAL_SPARSEARRAY);
1606             writeSparseArray((SparseArray) v);
1607         } else if (v instanceof boolean[]) {
1608             writeInt(VAL_BOOLEANARRAY);
1609             writeBooleanArray((boolean[]) v);
1610         } else if (v instanceof byte[]) {
1611             writeInt(VAL_BYTEARRAY);
1612             writeByteArray((byte[]) v);
1613         } else if (v instanceof String[]) {
1614             writeInt(VAL_STRINGARRAY);
1615             writeStringArray((String[]) v);
1616         } else if (v instanceof CharSequence[]) {
1617             // Must be after String[] and before Object[]
1618             writeInt(VAL_CHARSEQUENCEARRAY);
1619             writeCharSequenceArray((CharSequence[]) v);
1620         } else if (v instanceof IBinder) {
1621             writeInt(VAL_IBINDER);
1622             writeStrongBinder((IBinder) v);
1623         } else if (v instanceof Parcelable[]) {
1624             writeInt(VAL_PARCELABLEARRAY);
1625             writeParcelableArray((Parcelable[]) v, 0);
1626         } else if (v instanceof int[]) {
1627             writeInt(VAL_INTARRAY);
1628             writeIntArray((int[]) v);
1629         } else if (v instanceof long[]) {
1630             writeInt(VAL_LONGARRAY);
1631             writeLongArray((long[]) v);
1632         } else if (v instanceof Byte) {
1633             writeInt(VAL_BYTE);
1634             writeInt((Byte) v);
1635         } else if (v instanceof Size) {
1636             writeInt(VAL_SIZE);
1637             writeSize((Size) v);
1638         } else if (v instanceof SizeF) {
1639             writeInt(VAL_SIZEF);
1640             writeSizeF((SizeF) v);
1641         } else if (v instanceof double[]) {
1642             writeInt(VAL_DOUBLEARRAY);
1643             writeDoubleArray((double[]) v);
1644         } else {
1645             Class<?> clazz = v.getClass();
1646             if (clazz.isArray() && clazz.getComponentType() == Object.class) {
1647                 // Only pure Object[] are written here, Other arrays of non-primitive types are
1648                 // handled by serialization as this does not record the component type.
1649                 writeInt(VAL_OBJECTARRAY);
1650                 writeArray((Object[]) v);
1651             } else if (v instanceof Serializable) {
1652                 // Must be last
1653                 writeInt(VAL_SERIALIZABLE);
1654                 writeSerializable((Serializable) v);
1655             } else {
1656                 throw new RuntimeException("Parcel: unable to marshal value " + v);
1657             }
1658         }
1659     }
1660 
1661     /**
1662      * Flatten the name of the class of the Parcelable and its contents
1663      * into the parcel.
1664      *
1665      * @param p The Parcelable object to be written.
1666      * @param parcelableFlags Contextual flags as per
1667      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1668      */
writeParcelable(Parcelable p, int parcelableFlags)1669     public final void writeParcelable(Parcelable p, int parcelableFlags) {
1670         if (p == null) {
1671             writeString(null);
1672             return;
1673         }
1674         writeParcelableCreator(p);
1675         p.writeToParcel(this, parcelableFlags);
1676     }
1677 
1678     /** @hide */
writeParcelableCreator(Parcelable p)1679     public final void writeParcelableCreator(Parcelable p) {
1680         String name = p.getClass().getName();
1681         writeString(name);
1682     }
1683 
1684     /**
1685      * Write a generic serializable object in to a Parcel.  It is strongly
1686      * recommended that this method be avoided, since the serialization
1687      * overhead is extremely large, and this approach will be much slower than
1688      * using the other approaches to writing data in to a Parcel.
1689      */
writeSerializable(Serializable s)1690     public final void writeSerializable(Serializable s) {
1691         if (s == null) {
1692             writeString(null);
1693             return;
1694         }
1695         String name = s.getClass().getName();
1696         writeString(name);
1697 
1698         ByteArrayOutputStream baos = new ByteArrayOutputStream();
1699         try {
1700             ObjectOutputStream oos = new ObjectOutputStream(baos);
1701             oos.writeObject(s);
1702             oos.close();
1703 
1704             writeByteArray(baos.toByteArray());
1705         } catch (IOException ioe) {
1706             throw new RuntimeException("Parcelable encountered " +
1707                 "IOException writing serializable object (name = " + name +
1708                 ")", ioe);
1709         }
1710     }
1711 
1712     /** @hide For debugging purposes */
setStackTraceParceling(boolean enabled)1713     public static void setStackTraceParceling(boolean enabled) {
1714         sParcelExceptionStackTrace = enabled;
1715     }
1716 
1717     /**
1718      * Special function for writing an exception result at the header of
1719      * a parcel, to be used when returning an exception from a transaction.
1720      * Note that this currently only supports a few exception types; any other
1721      * exception will be re-thrown by this function as a RuntimeException
1722      * (to be caught by the system's last-resort exception handling when
1723      * dispatching a transaction).
1724      *
1725      * <p>The supported exception types are:
1726      * <ul>
1727      * <li>{@link BadParcelableException}
1728      * <li>{@link IllegalArgumentException}
1729      * <li>{@link IllegalStateException}
1730      * <li>{@link NullPointerException}
1731      * <li>{@link SecurityException}
1732      * <li>{@link UnsupportedOperationException}
1733      * <li>{@link NetworkOnMainThreadException}
1734      * </ul>
1735      *
1736      * @param e The Exception to be written.
1737      *
1738      * @see #writeNoException
1739      * @see #readException
1740      */
writeException(Exception e)1741     public final void writeException(Exception e) {
1742         int code = 0;
1743         if (e instanceof Parcelable
1744                 && (e.getClass().getClassLoader() == Parcelable.class.getClassLoader())) {
1745             // We only send Parcelable exceptions that are in the
1746             // BootClassLoader to ensure that the receiver can unpack them
1747             code = EX_PARCELABLE;
1748         } else if (e instanceof SecurityException) {
1749             code = EX_SECURITY;
1750         } else if (e instanceof BadParcelableException) {
1751             code = EX_BAD_PARCELABLE;
1752         } else if (e instanceof IllegalArgumentException) {
1753             code = EX_ILLEGAL_ARGUMENT;
1754         } else if (e instanceof NullPointerException) {
1755             code = EX_NULL_POINTER;
1756         } else if (e instanceof IllegalStateException) {
1757             code = EX_ILLEGAL_STATE;
1758         } else if (e instanceof NetworkOnMainThreadException) {
1759             code = EX_NETWORK_MAIN_THREAD;
1760         } else if (e instanceof UnsupportedOperationException) {
1761             code = EX_UNSUPPORTED_OPERATION;
1762         } else if (e instanceof ServiceSpecificException) {
1763             code = EX_SERVICE_SPECIFIC;
1764         }
1765         writeInt(code);
1766         StrictMode.clearGatheredViolations();
1767         if (code == 0) {
1768             if (e instanceof RuntimeException) {
1769                 throw (RuntimeException) e;
1770             }
1771             throw new RuntimeException(e);
1772         }
1773         writeString(e.getMessage());
1774         final long timeNow = sParcelExceptionStackTrace ? SystemClock.elapsedRealtime() : 0;
1775         if (sParcelExceptionStackTrace && (timeNow - sLastWriteExceptionStackTrace
1776                 > WRITE_EXCEPTION_STACK_TRACE_THRESHOLD_MS)) {
1777             sLastWriteExceptionStackTrace = timeNow;
1778             final int sizePosition = dataPosition();
1779             writeInt(0); // Header size will be filled in later
1780             StackTraceElement[] stackTrace = e.getStackTrace();
1781             final int truncatedSize = Math.min(stackTrace.length, 5);
1782             StringBuilder sb = new StringBuilder();
1783             for (int i = 0; i < truncatedSize; i++) {
1784                 sb.append("\tat ").append(stackTrace[i]).append('\n');
1785             }
1786             writeString(sb.toString());
1787             final int payloadPosition = dataPosition();
1788             setDataPosition(sizePosition);
1789             // Write stack trace header size. Used in native side to skip the header
1790             writeInt(payloadPosition - sizePosition);
1791             setDataPosition(payloadPosition);
1792         } else {
1793             writeInt(0);
1794         }
1795         switch (code) {
1796             case EX_SERVICE_SPECIFIC:
1797                 writeInt(((ServiceSpecificException) e).errorCode);
1798                 break;
1799             case EX_PARCELABLE:
1800                 // Write parceled exception prefixed by length
1801                 final int sizePosition = dataPosition();
1802                 writeInt(0);
1803                 writeParcelable((Parcelable) e, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1804                 final int payloadPosition = dataPosition();
1805                 setDataPosition(sizePosition);
1806                 writeInt(payloadPosition - sizePosition);
1807                 setDataPosition(payloadPosition);
1808                 break;
1809         }
1810     }
1811 
1812     /**
1813      * Special function for writing information at the front of the Parcel
1814      * indicating that no exception occurred.
1815      *
1816      * @see #writeException
1817      * @see #readException
1818      */
writeNoException()1819     public final void writeNoException() {
1820         // Despite the name of this function ("write no exception"),
1821         // it should instead be thought of as "write the RPC response
1822         // header", but because this function name is written out by
1823         // the AIDL compiler, we're not going to rename it.
1824         //
1825         // The response header, in the non-exception case (see also
1826         // writeException above, also called by the AIDL compiler), is
1827         // either a 0 (the default case), or EX_HAS_REPLY_HEADER if
1828         // StrictMode has gathered up violations that have occurred
1829         // during a Binder call, in which case we write out the number
1830         // of violations and their details, serialized, before the
1831         // actual RPC respons data.  The receiving end of this is
1832         // readException(), below.
1833         if (StrictMode.hasGatheredViolations()) {
1834             writeInt(EX_HAS_REPLY_HEADER);
1835             final int sizePosition = dataPosition();
1836             writeInt(0);  // total size of fat header, to be filled in later
1837             StrictMode.writeGatheredViolationsToParcel(this);
1838             final int payloadPosition = dataPosition();
1839             setDataPosition(sizePosition);
1840             writeInt(payloadPosition - sizePosition);  // header size
1841             setDataPosition(payloadPosition);
1842         } else {
1843             writeInt(0);
1844         }
1845     }
1846 
1847     /**
1848      * Special function for reading an exception result from the header of
1849      * a parcel, to be used after receiving the result of a transaction.  This
1850      * will throw the exception for you if it had been written to the Parcel,
1851      * otherwise return and let you read the normal result data from the Parcel.
1852      *
1853      * @see #writeException
1854      * @see #writeNoException
1855      */
readException()1856     public final void readException() {
1857         int code = readExceptionCode();
1858         if (code != 0) {
1859             String msg = readString();
1860             readException(code, msg);
1861         }
1862     }
1863 
1864     /**
1865      * Parses the header of a Binder call's response Parcel and
1866      * returns the exception code.  Deals with lite or fat headers.
1867      * In the common successful case, this header is generally zero.
1868      * In less common cases, it's a small negative number and will be
1869      * followed by an error string.
1870      *
1871      * This exists purely for android.database.DatabaseUtils and
1872      * insulating it from having to handle fat headers as returned by
1873      * e.g. StrictMode-induced RPC responses.
1874      *
1875      * @hide
1876      */
readExceptionCode()1877     public final int readExceptionCode() {
1878         int code = readInt();
1879         if (code == EX_HAS_REPLY_HEADER) {
1880             int headerSize = readInt();
1881             if (headerSize == 0) {
1882                 Log.e(TAG, "Unexpected zero-sized Parcel reply header.");
1883             } else {
1884                 // Currently the only thing in the header is StrictMode stacks,
1885                 // but discussions around event/RPC tracing suggest we might
1886                 // put that here too.  If so, switch on sub-header tags here.
1887                 // But for now, just parse out the StrictMode stuff.
1888                 StrictMode.readAndHandleBinderCallViolations(this);
1889             }
1890             // And fat response headers are currently only used when
1891             // there are no exceptions, so return no error:
1892             return 0;
1893         }
1894         return code;
1895     }
1896 
1897     /**
1898      * Throw an exception with the given message. Not intended for use
1899      * outside the Parcel class.
1900      *
1901      * @param code Used to determine which exception class to throw.
1902      * @param msg The exception message.
1903      */
readException(int code, String msg)1904     public final void readException(int code, String msg) {
1905         String remoteStackTrace = null;
1906         final int remoteStackPayloadSize = readInt();
1907         if (remoteStackPayloadSize > 0) {
1908             remoteStackTrace = readString();
1909         }
1910         Exception e = createException(code, msg);
1911         // Attach remote stack trace if availalble
1912         if (remoteStackTrace != null) {
1913             RemoteException cause = new RemoteException(
1914                     "Remote stack trace:\n" + remoteStackTrace, null, false, false);
1915             try {
1916                 Throwable rootCause = ExceptionUtils.getRootCause(e);
1917                 if (rootCause != null) {
1918                     rootCause.initCause(cause);
1919                 }
1920             } catch (RuntimeException ex) {
1921                 Log.e(TAG, "Cannot set cause " + cause + " for " + e, ex);
1922             }
1923         }
1924         SneakyThrow.sneakyThrow(e);
1925     }
1926 
1927     /**
1928      * Creates an exception with the given message.
1929      *
1930      * @param code Used to determine which exception class to throw.
1931      * @param msg The exception message.
1932      */
createException(int code, String msg)1933     private Exception createException(int code, String msg) {
1934         switch (code) {
1935             case EX_PARCELABLE:
1936                 if (readInt() > 0) {
1937                     return (Exception) readParcelable(Parcelable.class.getClassLoader());
1938                 } else {
1939                     return new RuntimeException(msg + " [missing Parcelable]");
1940                 }
1941             case EX_SECURITY:
1942                 return new SecurityException(msg);
1943             case EX_BAD_PARCELABLE:
1944                 return new BadParcelableException(msg);
1945             case EX_ILLEGAL_ARGUMENT:
1946                 return new IllegalArgumentException(msg);
1947             case EX_NULL_POINTER:
1948                 return new NullPointerException(msg);
1949             case EX_ILLEGAL_STATE:
1950                 return new IllegalStateException(msg);
1951             case EX_NETWORK_MAIN_THREAD:
1952                 return new NetworkOnMainThreadException();
1953             case EX_UNSUPPORTED_OPERATION:
1954                 return new UnsupportedOperationException(msg);
1955             case EX_SERVICE_SPECIFIC:
1956                 return new ServiceSpecificException(readInt(), msg);
1957         }
1958         return new RuntimeException("Unknown exception code: " + code
1959                 + " msg " + msg);
1960     }
1961 
1962     /**
1963      * Read an integer value from the parcel at the current dataPosition().
1964      */
readInt()1965     public final int readInt() {
1966         return nativeReadInt(mNativePtr);
1967     }
1968 
1969     /**
1970      * Read a long integer value from the parcel at the current dataPosition().
1971      */
readLong()1972     public final long readLong() {
1973         return nativeReadLong(mNativePtr);
1974     }
1975 
1976     /**
1977      * Read a floating point value from the parcel at the current
1978      * dataPosition().
1979      */
readFloat()1980     public final float readFloat() {
1981         return nativeReadFloat(mNativePtr);
1982     }
1983 
1984     /**
1985      * Read a double precision floating point value from the parcel at the
1986      * current dataPosition().
1987      */
readDouble()1988     public final double readDouble() {
1989         return nativeReadDouble(mNativePtr);
1990     }
1991 
1992     /**
1993      * Read a string value from the parcel at the current dataPosition().
1994      */
readString()1995     public final String readString() {
1996         return mReadWriteHelper.readString(this);
1997     }
1998 
1999     /**
2000      * Read a string without going though a {@link ReadWriteHelper}.  Subclasses of
2001      * {@link ReadWriteHelper} must use this method instead of {@link #readString} to avoid
2002      * infinity recursive calls.
2003      *
2004      * @hide
2005      */
readStringNoHelper()2006     public String readStringNoHelper() {
2007         return nativeReadString(mNativePtr);
2008     }
2009 
2010     /** @hide */
readBoolean()2011     public final boolean readBoolean() {
2012         return readInt() != 0;
2013     }
2014 
2015     /**
2016      * Read a CharSequence value from the parcel at the current dataPosition().
2017      * @hide
2018      */
readCharSequence()2019     public final CharSequence readCharSequence() {
2020         return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
2021     }
2022 
2023     /**
2024      * Read an object from the parcel at the current dataPosition().
2025      */
readStrongBinder()2026     public final IBinder readStrongBinder() {
2027         return nativeReadStrongBinder(mNativePtr);
2028     }
2029 
2030     /**
2031      * Read a FileDescriptor from the parcel at the current dataPosition().
2032      */
readFileDescriptor()2033     public final ParcelFileDescriptor readFileDescriptor() {
2034         FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
2035         return fd != null ? new ParcelFileDescriptor(fd) : null;
2036     }
2037 
2038     /** {@hide} */
readRawFileDescriptor()2039     public final FileDescriptor readRawFileDescriptor() {
2040         return nativeReadFileDescriptor(mNativePtr);
2041     }
2042 
2043     /**
2044      * {@hide}
2045      * Read and return a new array of FileDescriptors from the parcel.
2046      * @return the FileDescriptor array, or null if the array is null.
2047      **/
createRawFileDescriptorArray()2048     public final FileDescriptor[] createRawFileDescriptorArray() {
2049         int N = readInt();
2050         if (N < 0) {
2051             return null;
2052         }
2053         FileDescriptor[] f = new FileDescriptor[N];
2054         for (int i = 0; i < N; i++) {
2055             f[i] = readRawFileDescriptor();
2056         }
2057         return f;
2058     }
2059 
2060     /**
2061      * {@hide}
2062      * Read an array of FileDescriptors from a parcel.
2063      * The passed array must be exactly the length of the array in the parcel.
2064      * @return the FileDescriptor array, or null if the array is null.
2065      **/
readRawFileDescriptorArray(FileDescriptor[] val)2066     public final void readRawFileDescriptorArray(FileDescriptor[] val) {
2067         int N = readInt();
2068         if (N == val.length) {
2069             for (int i=0; i<N; i++) {
2070                 val[i] = readRawFileDescriptor();
2071             }
2072         } else {
2073             throw new RuntimeException("bad array lengths");
2074         }
2075     }
2076 
2077     /** @deprecated use {@link android.system.Os#open(String, int, int)} */
2078     @Deprecated
openFileDescriptor(String file, int mode)2079     static native FileDescriptor openFileDescriptor(String file, int mode)
2080             throws FileNotFoundException;
2081 
2082     /** @deprecated use {@link android.system.Os#dup(FileDescriptor)} */
2083     @Deprecated
dupFileDescriptor(FileDescriptor orig)2084     static native FileDescriptor dupFileDescriptor(FileDescriptor orig) throws IOException;
2085 
2086     /** @deprecated use {@link android.system.Os#close(FileDescriptor)} */
2087     @Deprecated
closeFileDescriptor(FileDescriptor desc)2088     static native void closeFileDescriptor(FileDescriptor desc) throws IOException;
2089 
2090     /**
2091      * Read a byte value from the parcel at the current dataPosition().
2092      */
readByte()2093     public final byte readByte() {
2094         return (byte)(readInt() & 0xff);
2095     }
2096 
2097     /**
2098      * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2099      * been written with {@link #writeBundle}.  Read into an existing Map object
2100      * from the parcel at the current dataPosition().
2101      */
readMap(Map outVal, ClassLoader loader)2102     public final void readMap(Map outVal, ClassLoader loader) {
2103         int N = readInt();
2104         readMapInternal(outVal, N, loader);
2105     }
2106 
2107     /**
2108      * Read into an existing List object from the parcel at the current
2109      * dataPosition(), using the given class loader to load any enclosed
2110      * Parcelables.  If it is null, the default class loader is used.
2111      */
readList(List outVal, ClassLoader loader)2112     public final void readList(List outVal, ClassLoader loader) {
2113         int N = readInt();
2114         readListInternal(outVal, N, loader);
2115     }
2116 
2117     /**
2118      * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2119      * been written with {@link #writeBundle}.  Read and return a new HashMap
2120      * object from the parcel at the current dataPosition(), using the given
2121      * class loader to load any enclosed Parcelables.  Returns null if
2122      * the previously written map object was null.
2123      */
readHashMap(ClassLoader loader)2124     public final HashMap readHashMap(ClassLoader loader)
2125     {
2126         int N = readInt();
2127         if (N < 0) {
2128             return null;
2129         }
2130         HashMap m = new HashMap(N);
2131         readMapInternal(m, N, loader);
2132         return m;
2133     }
2134 
2135     /**
2136      * Read and return a new Bundle object from the parcel at the current
2137      * dataPosition().  Returns null if the previously written Bundle object was
2138      * null.
2139      */
readBundle()2140     public final Bundle readBundle() {
2141         return readBundle(null);
2142     }
2143 
2144     /**
2145      * Read and return a new Bundle object from the parcel at the current
2146      * dataPosition(), using the given class loader to initialize the class
2147      * loader of the Bundle for later retrieval of Parcelable objects.
2148      * Returns null if the previously written Bundle object was null.
2149      */
readBundle(ClassLoader loader)2150     public final Bundle readBundle(ClassLoader loader) {
2151         int length = readInt();
2152         if (length < 0) {
2153             if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2154             return null;
2155         }
2156 
2157         final Bundle bundle = new Bundle(this, length);
2158         if (loader != null) {
2159             bundle.setClassLoader(loader);
2160         }
2161         return bundle;
2162     }
2163 
2164     /**
2165      * Read and return a new Bundle object from the parcel at the current
2166      * dataPosition().  Returns null if the previously written Bundle object was
2167      * null.
2168      */
readPersistableBundle()2169     public final PersistableBundle readPersistableBundle() {
2170         return readPersistableBundle(null);
2171     }
2172 
2173     /**
2174      * Read and return a new Bundle object from the parcel at the current
2175      * dataPosition(), using the given class loader to initialize the class
2176      * loader of the Bundle for later retrieval of Parcelable objects.
2177      * Returns null if the previously written Bundle object was null.
2178      */
readPersistableBundle(ClassLoader loader)2179     public final PersistableBundle readPersistableBundle(ClassLoader loader) {
2180         int length = readInt();
2181         if (length < 0) {
2182             if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2183             return null;
2184         }
2185 
2186         final PersistableBundle bundle = new PersistableBundle(this, length);
2187         if (loader != null) {
2188             bundle.setClassLoader(loader);
2189         }
2190         return bundle;
2191     }
2192 
2193     /**
2194      * Read a Size from the parcel at the current dataPosition().
2195      */
readSize()2196     public final Size readSize() {
2197         final int width = readInt();
2198         final int height = readInt();
2199         return new Size(width, height);
2200     }
2201 
2202     /**
2203      * Read a SizeF from the parcel at the current dataPosition().
2204      */
readSizeF()2205     public final SizeF readSizeF() {
2206         final float width = readFloat();
2207         final float height = readFloat();
2208         return new SizeF(width, height);
2209     }
2210 
2211     /**
2212      * Read and return a byte[] object from the parcel.
2213      */
createByteArray()2214     public final byte[] createByteArray() {
2215         return nativeCreateByteArray(mNativePtr);
2216     }
2217 
2218     /**
2219      * Read a byte[] object from the parcel and copy it into the
2220      * given byte array.
2221      */
readByteArray(byte[] val)2222     public final void readByteArray(byte[] val) {
2223         boolean valid = nativeReadByteArray(mNativePtr, val, (val != null) ? val.length : 0);
2224         if (!valid) {
2225             throw new RuntimeException("bad array lengths");
2226         }
2227     }
2228 
2229     /**
2230      * Read a blob of data from the parcel and return it as a byte array.
2231      * {@hide}
2232      * {@SystemApi}
2233      */
readBlob()2234     public final byte[] readBlob() {
2235         return nativeReadBlob(mNativePtr);
2236     }
2237 
2238     /**
2239      * Read and return a String[] object from the parcel.
2240      * {@hide}
2241      */
readStringArray()2242     public final String[] readStringArray() {
2243         String[] array = null;
2244 
2245         int length = readInt();
2246         if (length >= 0)
2247         {
2248             array = new String[length];
2249 
2250             for (int i = 0 ; i < length ; i++)
2251             {
2252                 array[i] = readString();
2253             }
2254         }
2255 
2256         return array;
2257     }
2258 
2259     /**
2260      * Read and return a CharSequence[] object from the parcel.
2261      * {@hide}
2262      */
readCharSequenceArray()2263     public final CharSequence[] readCharSequenceArray() {
2264         CharSequence[] array = null;
2265 
2266         int length = readInt();
2267         if (length >= 0)
2268         {
2269             array = new CharSequence[length];
2270 
2271             for (int i = 0 ; i < length ; i++)
2272             {
2273                 array[i] = readCharSequence();
2274             }
2275         }
2276 
2277         return array;
2278     }
2279 
2280     /**
2281      * Read and return an ArrayList&lt;CharSequence&gt; object from the parcel.
2282      * {@hide}
2283      */
readCharSequenceList()2284     public final ArrayList<CharSequence> readCharSequenceList() {
2285         ArrayList<CharSequence> array = null;
2286 
2287         int length = readInt();
2288         if (length >= 0) {
2289             array = new ArrayList<CharSequence>(length);
2290 
2291             for (int i = 0 ; i < length ; i++) {
2292                 array.add(readCharSequence());
2293             }
2294         }
2295 
2296         return array;
2297     }
2298 
2299     /**
2300      * Read and return a new ArrayList object from the parcel at the current
2301      * dataPosition().  Returns null if the previously written list object was
2302      * null.  The given class loader will be used to load any enclosed
2303      * Parcelables.
2304      */
readArrayList(ClassLoader loader)2305     public final ArrayList readArrayList(ClassLoader loader) {
2306         int N = readInt();
2307         if (N < 0) {
2308             return null;
2309         }
2310         ArrayList l = new ArrayList(N);
2311         readListInternal(l, N, loader);
2312         return l;
2313     }
2314 
2315     /**
2316      * Read and return a new Object array from the parcel at the current
2317      * dataPosition().  Returns null if the previously written array was
2318      * null.  The given class loader will be used to load any enclosed
2319      * Parcelables.
2320      */
readArray(ClassLoader loader)2321     public final Object[] readArray(ClassLoader loader) {
2322         int N = readInt();
2323         if (N < 0) {
2324             return null;
2325         }
2326         Object[] l = new Object[N];
2327         readArrayInternal(l, N, loader);
2328         return l;
2329     }
2330 
2331     /**
2332      * Read and return a new SparseArray object from the parcel at the current
2333      * dataPosition().  Returns null if the previously written list object was
2334      * null.  The given class loader will be used to load any enclosed
2335      * Parcelables.
2336      */
readSparseArray(ClassLoader loader)2337     public final SparseArray readSparseArray(ClassLoader loader) {
2338         int N = readInt();
2339         if (N < 0) {
2340             return null;
2341         }
2342         SparseArray sa = new SparseArray(N);
2343         readSparseArrayInternal(sa, N, loader);
2344         return sa;
2345     }
2346 
2347     /**
2348      * Read and return a new SparseBooleanArray object from the parcel at the current
2349      * dataPosition().  Returns null if the previously written list object was
2350      * null.
2351      */
readSparseBooleanArray()2352     public final SparseBooleanArray readSparseBooleanArray() {
2353         int N = readInt();
2354         if (N < 0) {
2355             return null;
2356         }
2357         SparseBooleanArray sa = new SparseBooleanArray(N);
2358         readSparseBooleanArrayInternal(sa, N);
2359         return sa;
2360     }
2361 
2362     /**
2363      * Read and return a new SparseIntArray object from the parcel at the current
2364      * dataPosition(). Returns null if the previously written array object was null.
2365      * @hide
2366      */
readSparseIntArray()2367     public final SparseIntArray readSparseIntArray() {
2368         int N = readInt();
2369         if (N < 0) {
2370             return null;
2371         }
2372         SparseIntArray sa = new SparseIntArray(N);
2373         readSparseIntArrayInternal(sa, N);
2374         return sa;
2375     }
2376 
2377     /**
2378      * Read and return a new ArrayList containing a particular object type from
2379      * the parcel that was written with {@link #writeTypedList} at the
2380      * current dataPosition().  Returns null if the
2381      * previously written list object was null.  The list <em>must</em> have
2382      * previously been written via {@link #writeTypedList} with the same object
2383      * type.
2384      *
2385      * @return A newly created ArrayList containing objects with the same data
2386      *         as those that were previously written.
2387      *
2388      * @see #writeTypedList
2389      */
createTypedArrayList(Parcelable.Creator<T> c)2390     public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
2391         int N = readInt();
2392         if (N < 0) {
2393             return null;
2394         }
2395         ArrayList<T> l = new ArrayList<T>(N);
2396         while (N > 0) {
2397             l.add(readTypedObject(c));
2398             N--;
2399         }
2400         return l;
2401     }
2402 
2403     /**
2404      * Read into the given List items containing a particular object type
2405      * that were written with {@link #writeTypedList} at the
2406      * current dataPosition().  The list <em>must</em> have
2407      * previously been written via {@link #writeTypedList} with the same object
2408      * type.
2409      *
2410      * @return A newly created ArrayList containing objects with the same data
2411      *         as those that were previously written.
2412      *
2413      * @see #writeTypedList
2414      */
readTypedList(List<T> list, Parcelable.Creator<T> c)2415     public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
2416         int M = list.size();
2417         int N = readInt();
2418         int i = 0;
2419         for (; i < M && i < N; i++) {
2420             list.set(i, readTypedObject(c));
2421         }
2422         for (; i<N; i++) {
2423             list.add(readTypedObject(c));
2424         }
2425         for (; i<M; i++) {
2426             list.remove(N);
2427         }
2428     }
2429 
2430     /**
2431      * Read and return a new ArrayList containing String objects from
2432      * the parcel that was written with {@link #writeStringList} at the
2433      * current dataPosition().  Returns null if the
2434      * previously written list object was null.
2435      *
2436      * @return A newly created ArrayList containing strings with the same data
2437      *         as those that were previously written.
2438      *
2439      * @see #writeStringList
2440      */
createStringArrayList()2441     public final ArrayList<String> createStringArrayList() {
2442         int N = readInt();
2443         if (N < 0) {
2444             return null;
2445         }
2446         ArrayList<String> l = new ArrayList<String>(N);
2447         while (N > 0) {
2448             l.add(readString());
2449             N--;
2450         }
2451         return l;
2452     }
2453 
2454     /**
2455      * Read and return a new ArrayList containing IBinder objects from
2456      * the parcel that was written with {@link #writeBinderList} at the
2457      * current dataPosition().  Returns null if the
2458      * previously written list object was null.
2459      *
2460      * @return A newly created ArrayList containing strings with the same data
2461      *         as those that were previously written.
2462      *
2463      * @see #writeBinderList
2464      */
createBinderArrayList()2465     public final ArrayList<IBinder> createBinderArrayList() {
2466         int N = readInt();
2467         if (N < 0) {
2468             return null;
2469         }
2470         ArrayList<IBinder> l = new ArrayList<IBinder>(N);
2471         while (N > 0) {
2472             l.add(readStrongBinder());
2473             N--;
2474         }
2475         return l;
2476     }
2477 
2478     /**
2479      * Read into the given List items String objects that were written with
2480      * {@link #writeStringList} at the current dataPosition().
2481      *
2482      * @see #writeStringList
2483      */
readStringList(List<String> list)2484     public final void readStringList(List<String> list) {
2485         int M = list.size();
2486         int N = readInt();
2487         int i = 0;
2488         for (; i < M && i < N; i++) {
2489             list.set(i, readString());
2490         }
2491         for (; i<N; i++) {
2492             list.add(readString());
2493         }
2494         for (; i<M; i++) {
2495             list.remove(N);
2496         }
2497     }
2498 
2499     /**
2500      * Read into the given List items IBinder objects that were written with
2501      * {@link #writeBinderList} at the current dataPosition().
2502      *
2503      * @see #writeBinderList
2504      */
readBinderList(List<IBinder> list)2505     public final void readBinderList(List<IBinder> list) {
2506         int M = list.size();
2507         int N = readInt();
2508         int i = 0;
2509         for (; i < M && i < N; i++) {
2510             list.set(i, readStrongBinder());
2511         }
2512         for (; i<N; i++) {
2513             list.add(readStrongBinder());
2514         }
2515         for (; i<M; i++) {
2516             list.remove(N);
2517         }
2518     }
2519 
2520     /**
2521      * Read the list of {@code Parcelable} objects at the current data position into the
2522      * given {@code list}. The contents of the {@code list} are replaced. If the serialized
2523      * list was {@code null}, {@code list} is cleared.
2524      *
2525      * @see #writeParcelableList(List, int)
2526      * @hide
2527      */
readParcelableList(List<T> list, ClassLoader cl)2528     public final <T extends Parcelable> List<T> readParcelableList(List<T> list, ClassLoader cl) {
2529         final int N = readInt();
2530         if (N == -1) {
2531             list.clear();
2532             return list;
2533         }
2534 
2535         final int M = list.size();
2536         int i = 0;
2537         for (; i < M && i < N; i++) {
2538             list.set(i, (T) readParcelable(cl));
2539         }
2540         for (; i<N; i++) {
2541             list.add((T) readParcelable(cl));
2542         }
2543         for (; i<M; i++) {
2544             list.remove(N);
2545         }
2546         return list;
2547     }
2548 
2549     /**
2550      * Read and return a new array containing a particular object type from
2551      * the parcel at the current dataPosition().  Returns null if the
2552      * previously written array was null.  The array <em>must</em> have
2553      * previously been written via {@link #writeTypedArray} with the same
2554      * object type.
2555      *
2556      * @return A newly created array containing objects with the same data
2557      *         as those that were previously written.
2558      *
2559      * @see #writeTypedArray
2560      */
createTypedArray(Parcelable.Creator<T> c)2561     public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
2562         int N = readInt();
2563         if (N < 0) {
2564             return null;
2565         }
2566         T[] l = c.newArray(N);
2567         for (int i=0; i<N; i++) {
2568             l[i] = readTypedObject(c);
2569         }
2570         return l;
2571     }
2572 
readTypedArray(T[] val, Parcelable.Creator<T> c)2573     public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
2574         int N = readInt();
2575         if (N == val.length) {
2576             for (int i=0; i<N; i++) {
2577                 val[i] = readTypedObject(c);
2578             }
2579         } else {
2580             throw new RuntimeException("bad array lengths");
2581         }
2582     }
2583 
2584     /**
2585      * @deprecated
2586      * @hide
2587      */
2588     @Deprecated
readTypedArray(Parcelable.Creator<T> c)2589     public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
2590         return createTypedArray(c);
2591     }
2592 
2593     /**
2594      * Read and return a typed Parcelable object from a parcel.
2595      * Returns null if the previous written object was null.
2596      * The object <em>must</em> have previous been written via
2597      * {@link #writeTypedObject} with the same object type.
2598      *
2599      * @return A newly created object of the type that was previously
2600      *         written.
2601      *
2602      * @see #writeTypedObject
2603      */
readTypedObject(Parcelable.Creator<T> c)2604     public final <T> T readTypedObject(Parcelable.Creator<T> c) {
2605         if (readInt() != 0) {
2606             return c.createFromParcel(this);
2607         } else {
2608             return null;
2609         }
2610     }
2611 
2612     /**
2613      * Write a heterogeneous array of Parcelable objects into the Parcel.
2614      * Each object in the array is written along with its class name, so
2615      * that the correct class can later be instantiated.  As a result, this
2616      * has significantly more overhead than {@link #writeTypedArray}, but will
2617      * correctly handle an array containing more than one type of object.
2618      *
2619      * @param value The array of objects to be written.
2620      * @param parcelableFlags Contextual flags as per
2621      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2622      *
2623      * @see #writeTypedArray
2624      */
writeParcelableArray(T[] value, int parcelableFlags)2625     public final <T extends Parcelable> void writeParcelableArray(T[] value,
2626             int parcelableFlags) {
2627         if (value != null) {
2628             int N = value.length;
2629             writeInt(N);
2630             for (int i=0; i<N; i++) {
2631                 writeParcelable(value[i], parcelableFlags);
2632             }
2633         } else {
2634             writeInt(-1);
2635         }
2636     }
2637 
2638     /**
2639      * Read a typed object from a parcel.  The given class loader will be
2640      * used to load any enclosed Parcelables.  If it is null, the default class
2641      * loader will be used.
2642      */
readValue(ClassLoader loader)2643     public final Object readValue(ClassLoader loader) {
2644         int type = readInt();
2645 
2646         switch (type) {
2647         case VAL_NULL:
2648             return null;
2649 
2650         case VAL_STRING:
2651             return readString();
2652 
2653         case VAL_INTEGER:
2654             return readInt();
2655 
2656         case VAL_MAP:
2657             return readHashMap(loader);
2658 
2659         case VAL_PARCELABLE:
2660             return readParcelable(loader);
2661 
2662         case VAL_SHORT:
2663             return (short) readInt();
2664 
2665         case VAL_LONG:
2666             return readLong();
2667 
2668         case VAL_FLOAT:
2669             return readFloat();
2670 
2671         case VAL_DOUBLE:
2672             return readDouble();
2673 
2674         case VAL_BOOLEAN:
2675             return readInt() == 1;
2676 
2677         case VAL_CHARSEQUENCE:
2678             return readCharSequence();
2679 
2680         case VAL_LIST:
2681             return readArrayList(loader);
2682 
2683         case VAL_BOOLEANARRAY:
2684             return createBooleanArray();
2685 
2686         case VAL_BYTEARRAY:
2687             return createByteArray();
2688 
2689         case VAL_STRINGARRAY:
2690             return readStringArray();
2691 
2692         case VAL_CHARSEQUENCEARRAY:
2693             return readCharSequenceArray();
2694 
2695         case VAL_IBINDER:
2696             return readStrongBinder();
2697 
2698         case VAL_OBJECTARRAY:
2699             return readArray(loader);
2700 
2701         case VAL_INTARRAY:
2702             return createIntArray();
2703 
2704         case VAL_LONGARRAY:
2705             return createLongArray();
2706 
2707         case VAL_BYTE:
2708             return readByte();
2709 
2710         case VAL_SERIALIZABLE:
2711             return readSerializable(loader);
2712 
2713         case VAL_PARCELABLEARRAY:
2714             return readParcelableArray(loader);
2715 
2716         case VAL_SPARSEARRAY:
2717             return readSparseArray(loader);
2718 
2719         case VAL_SPARSEBOOLEANARRAY:
2720             return readSparseBooleanArray();
2721 
2722         case VAL_BUNDLE:
2723             return readBundle(loader); // loading will be deferred
2724 
2725         case VAL_PERSISTABLEBUNDLE:
2726             return readPersistableBundle(loader);
2727 
2728         case VAL_SIZE:
2729             return readSize();
2730 
2731         case VAL_SIZEF:
2732             return readSizeF();
2733 
2734         case VAL_DOUBLEARRAY:
2735             return createDoubleArray();
2736 
2737         default:
2738             int off = dataPosition() - 4;
2739             throw new RuntimeException(
2740                 "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
2741         }
2742     }
2743 
2744     /**
2745      * Read and return a new Parcelable from the parcel.  The given class loader
2746      * will be used to load any enclosed Parcelables.  If it is null, the default
2747      * class loader will be used.
2748      * @param loader A ClassLoader from which to instantiate the Parcelable
2749      * object, or null for the default class loader.
2750      * @return Returns the newly created Parcelable, or null if a null
2751      * object has been written.
2752      * @throws BadParcelableException Throws BadParcelableException if there
2753      * was an error trying to instantiate the Parcelable.
2754      */
2755     @SuppressWarnings("unchecked")
readParcelable(ClassLoader loader)2756     public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
2757         Parcelable.Creator<?> creator = readParcelableCreator(loader);
2758         if (creator == null) {
2759             return null;
2760         }
2761         if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2762           Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2763               (Parcelable.ClassLoaderCreator<?>) creator;
2764           return (T) classLoaderCreator.createFromParcel(this, loader);
2765         }
2766         return (T) creator.createFromParcel(this);
2767     }
2768 
2769     /** @hide */
2770     @SuppressWarnings("unchecked")
readCreator(Parcelable.Creator<?> creator, ClassLoader loader)2771     public final <T extends Parcelable> T readCreator(Parcelable.Creator<?> creator,
2772             ClassLoader loader) {
2773         if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2774           Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2775               (Parcelable.ClassLoaderCreator<?>) creator;
2776           return (T) classLoaderCreator.createFromParcel(this, loader);
2777         }
2778         return (T) creator.createFromParcel(this);
2779     }
2780 
2781     /** @hide */
readParcelableCreator(ClassLoader loader)2782     public final Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) {
2783         String name = readString();
2784         if (name == null) {
2785             return null;
2786         }
2787         Parcelable.Creator<?> creator;
2788         synchronized (mCreators) {
2789             HashMap<String,Parcelable.Creator<?>> map = mCreators.get(loader);
2790             if (map == null) {
2791                 map = new HashMap<>();
2792                 mCreators.put(loader, map);
2793             }
2794             creator = map.get(name);
2795             if (creator == null) {
2796                 try {
2797                     // If loader == null, explicitly emulate Class.forName(String) "caller
2798                     // classloader" behavior.
2799                     ClassLoader parcelableClassLoader =
2800                             (loader == null ? getClass().getClassLoader() : loader);
2801                     // Avoid initializing the Parcelable class until we know it implements
2802                     // Parcelable and has the necessary CREATOR field. http://b/1171613.
2803                     Class<?> parcelableClass = Class.forName(name, false /* initialize */,
2804                             parcelableClassLoader);
2805                     if (!Parcelable.class.isAssignableFrom(parcelableClass)) {
2806                         throw new BadParcelableException("Parcelable protocol requires subclassing "
2807                                 + "from Parcelable on class " + name);
2808                     }
2809                     Field f = parcelableClass.getField("CREATOR");
2810                     if ((f.getModifiers() & Modifier.STATIC) == 0) {
2811                         throw new BadParcelableException("Parcelable protocol requires "
2812                                 + "the CREATOR object to be static on class " + name);
2813                     }
2814                     Class<?> creatorType = f.getType();
2815                     if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) {
2816                         // Fail before calling Field.get(), not after, to avoid initializing
2817                         // parcelableClass unnecessarily.
2818                         throw new BadParcelableException("Parcelable protocol requires a "
2819                                 + "Parcelable.Creator object called "
2820                                 + "CREATOR on class " + name);
2821                     }
2822                     creator = (Parcelable.Creator<?>) f.get(null);
2823                 }
2824                 catch (IllegalAccessException e) {
2825                     Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
2826                     throw new BadParcelableException(
2827                             "IllegalAccessException when unmarshalling: " + name);
2828                 }
2829                 catch (ClassNotFoundException e) {
2830                     Log.e(TAG, "Class not found when unmarshalling: " + name, e);
2831                     throw new BadParcelableException(
2832                             "ClassNotFoundException when unmarshalling: " + name);
2833                 }
2834                 catch (NoSuchFieldException e) {
2835                     throw new BadParcelableException("Parcelable protocol requires a "
2836                             + "Parcelable.Creator object called "
2837                             + "CREATOR on class " + name);
2838                 }
2839                 if (creator == null) {
2840                     throw new BadParcelableException("Parcelable protocol requires a "
2841                             + "non-null Parcelable.Creator object called "
2842                             + "CREATOR on class " + name);
2843                 }
2844 
2845                 map.put(name, creator);
2846             }
2847         }
2848 
2849         return creator;
2850     }
2851 
2852     /**
2853      * Read and return a new Parcelable array from the parcel.
2854      * The given class loader will be used to load any enclosed
2855      * Parcelables.
2856      * @return the Parcelable array, or null if the array is null
2857      */
readParcelableArray(ClassLoader loader)2858     public final Parcelable[] readParcelableArray(ClassLoader loader) {
2859         int N = readInt();
2860         if (N < 0) {
2861             return null;
2862         }
2863         Parcelable[] p = new Parcelable[N];
2864         for (int i = 0; i < N; i++) {
2865             p[i] = readParcelable(loader);
2866         }
2867         return p;
2868     }
2869 
2870     /** @hide */
readParcelableArray(ClassLoader loader, Class<T> clazz)2871     public final <T extends Parcelable> T[] readParcelableArray(ClassLoader loader,
2872             Class<T> clazz) {
2873         int N = readInt();
2874         if (N < 0) {
2875             return null;
2876         }
2877         T[] p = (T[]) Array.newInstance(clazz, N);
2878         for (int i = 0; i < N; i++) {
2879             p[i] = readParcelable(loader);
2880         }
2881         return p;
2882     }
2883 
2884     /**
2885      * Read and return a new Serializable object from the parcel.
2886      * @return the Serializable object, or null if the Serializable name
2887      * wasn't found in the parcel.
2888      */
readSerializable()2889     public final Serializable readSerializable() {
2890         return readSerializable(null);
2891     }
2892 
readSerializable(final ClassLoader loader)2893     private final Serializable readSerializable(final ClassLoader loader) {
2894         String name = readString();
2895         if (name == null) {
2896             // For some reason we were unable to read the name of the Serializable (either there
2897             // is nothing left in the Parcel to read, or the next value wasn't a String), so
2898             // return null, which indicates that the name wasn't found in the parcel.
2899             return null;
2900         }
2901 
2902         byte[] serializedData = createByteArray();
2903         ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
2904         try {
2905             ObjectInputStream ois = new ObjectInputStream(bais) {
2906                 @Override
2907                 protected Class<?> resolveClass(ObjectStreamClass osClass)
2908                         throws IOException, ClassNotFoundException {
2909                     // try the custom classloader if provided
2910                     if (loader != null) {
2911                         Class<?> c = Class.forName(osClass.getName(), false, loader);
2912                         if (c != null) {
2913                             return c;
2914                         }
2915                     }
2916                     return super.resolveClass(osClass);
2917                 }
2918             };
2919             return (Serializable) ois.readObject();
2920         } catch (IOException ioe) {
2921             throw new RuntimeException("Parcelable encountered " +
2922                 "IOException reading a Serializable object (name = " + name +
2923                 ")", ioe);
2924         } catch (ClassNotFoundException cnfe) {
2925             throw new RuntimeException("Parcelable encountered " +
2926                 "ClassNotFoundException reading a Serializable object (name = "
2927                 + name + ")", cnfe);
2928         }
2929     }
2930 
2931     // Cache of previously looked up CREATOR.createFromParcel() methods for
2932     // particular classes.  Keys are the names of the classes, values are
2933     // Method objects.
2934     private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator<?>>>
2935         mCreators = new HashMap<>();
2936 
2937     /** @hide for internal use only. */
obtain(int obj)2938     static protected final Parcel obtain(int obj) {
2939         throw new UnsupportedOperationException();
2940     }
2941 
2942     /** @hide */
obtain(long obj)2943     static protected final Parcel obtain(long obj) {
2944         final Parcel[] pool = sHolderPool;
2945         synchronized (pool) {
2946             Parcel p;
2947             for (int i=0; i<POOL_SIZE; i++) {
2948                 p = pool[i];
2949                 if (p != null) {
2950                     pool[i] = null;
2951                     if (DEBUG_RECYCLE) {
2952                         p.mStack = new RuntimeException();
2953                     }
2954                     p.init(obj);
2955                     return p;
2956                 }
2957             }
2958         }
2959         return new Parcel(obj);
2960     }
2961 
Parcel(long nativePtr)2962     private Parcel(long nativePtr) {
2963         if (DEBUG_RECYCLE) {
2964             mStack = new RuntimeException();
2965         }
2966         //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
2967         init(nativePtr);
2968     }
2969 
init(long nativePtr)2970     private void init(long nativePtr) {
2971         if (nativePtr != 0) {
2972             mNativePtr = nativePtr;
2973             mOwnsNativeParcelObject = false;
2974         } else {
2975             mNativePtr = nativeCreate();
2976             mOwnsNativeParcelObject = true;
2977         }
2978     }
2979 
freeBuffer()2980     private void freeBuffer() {
2981         if (mOwnsNativeParcelObject) {
2982             updateNativeSize(nativeFreeBuffer(mNativePtr));
2983         }
2984         mReadWriteHelper = ReadWriteHelper.DEFAULT;
2985     }
2986 
destroy()2987     private void destroy() {
2988         if (mNativePtr != 0) {
2989             if (mOwnsNativeParcelObject) {
2990                 nativeDestroy(mNativePtr);
2991                 updateNativeSize(0);
2992             }
2993             mNativePtr = 0;
2994         }
2995         mReadWriteHelper = null;
2996     }
2997 
2998     @Override
finalize()2999     protected void finalize() throws Throwable {
3000         if (DEBUG_RECYCLE) {
3001             if (mStack != null) {
3002                 Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
3003             }
3004         }
3005         destroy();
3006     }
3007 
readMapInternal(Map outVal, int N, ClassLoader loader)3008     /* package */ void readMapInternal(Map outVal, int N,
3009         ClassLoader loader) {
3010         while (N > 0) {
3011             Object key = readValue(loader);
3012             Object value = readValue(loader);
3013             outVal.put(key, value);
3014             N--;
3015         }
3016     }
3017 
readArrayMapInternal(ArrayMap outVal, int N, ClassLoader loader)3018     /* package */ void readArrayMapInternal(ArrayMap outVal, int N,
3019         ClassLoader loader) {
3020         if (DEBUG_ARRAY_MAP) {
3021             RuntimeException here =  new RuntimeException("here");
3022             here.fillInStackTrace();
3023             Log.d(TAG, "Reading " + N + " ArrayMap entries", here);
3024         }
3025         int startPos;
3026         while (N > 0) {
3027             if (DEBUG_ARRAY_MAP) startPos = dataPosition();
3028             String key = readString();
3029             Object value = readValue(loader);
3030             if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Read #" + (N-1) + " "
3031                     + (dataPosition()-startPos) + " bytes: key=0x"
3032                     + Integer.toHexString((key != null ? key.hashCode() : 0)) + " " + key);
3033             outVal.append(key, value);
3034             N--;
3035         }
3036         outVal.validate();
3037     }
3038 
readArrayMapSafelyInternal(ArrayMap outVal, int N, ClassLoader loader)3039     /* package */ void readArrayMapSafelyInternal(ArrayMap outVal, int N,
3040         ClassLoader loader) {
3041         if (DEBUG_ARRAY_MAP) {
3042             RuntimeException here =  new RuntimeException("here");
3043             here.fillInStackTrace();
3044             Log.d(TAG, "Reading safely " + N + " ArrayMap entries", here);
3045         }
3046         while (N > 0) {
3047             String key = readString();
3048             if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Read safe #" + (N-1) + ": key=0x"
3049                     + (key != null ? key.hashCode() : 0) + " " + key);
3050             Object value = readValue(loader);
3051             outVal.put(key, value);
3052             N--;
3053         }
3054     }
3055 
3056     /**
3057      * @hide For testing only.
3058      */
readArrayMap(ArrayMap outVal, ClassLoader loader)3059     public void readArrayMap(ArrayMap outVal, ClassLoader loader) {
3060         final int N = readInt();
3061         if (N < 0) {
3062             return;
3063         }
3064         readArrayMapInternal(outVal, N, loader);
3065     }
3066 
3067     /**
3068      * Reads an array set.
3069      *
3070      * @param loader The class loader to use.
3071      *
3072      * @hide
3073      */
readArraySet(ClassLoader loader)3074     public @Nullable ArraySet<? extends Object> readArraySet(ClassLoader loader) {
3075         final int size = readInt();
3076         if (size < 0) {
3077             return null;
3078         }
3079         ArraySet<Object> result = new ArraySet<>(size);
3080         for (int i = 0; i < size; i++) {
3081             Object value = readValue(loader);
3082             result.append(value);
3083         }
3084         return result;
3085     }
3086 
readListInternal(List outVal, int N, ClassLoader loader)3087     private void readListInternal(List outVal, int N,
3088         ClassLoader loader) {
3089         while (N > 0) {
3090             Object value = readValue(loader);
3091             //Log.d(TAG, "Unmarshalling value=" + value);
3092             outVal.add(value);
3093             N--;
3094         }
3095     }
3096 
readArrayInternal(Object[] outVal, int N, ClassLoader loader)3097     private void readArrayInternal(Object[] outVal, int N,
3098         ClassLoader loader) {
3099         for (int i = 0; i < N; i++) {
3100             Object value = readValue(loader);
3101             //Log.d(TAG, "Unmarshalling value=" + value);
3102             outVal[i] = value;
3103         }
3104     }
3105 
readSparseArrayInternal(SparseArray outVal, int N, ClassLoader loader)3106     private void readSparseArrayInternal(SparseArray outVal, int N,
3107         ClassLoader loader) {
3108         while (N > 0) {
3109             int key = readInt();
3110             Object value = readValue(loader);
3111             //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3112             outVal.append(key, value);
3113             N--;
3114         }
3115     }
3116 
3117 
readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N)3118     private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
3119         while (N > 0) {
3120             int key = readInt();
3121             boolean value = this.readByte() == 1;
3122             //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3123             outVal.append(key, value);
3124             N--;
3125         }
3126     }
3127 
readSparseIntArrayInternal(SparseIntArray outVal, int N)3128     private void readSparseIntArrayInternal(SparseIntArray outVal, int N) {
3129         while (N > 0) {
3130             int key = readInt();
3131             int value = readInt();
3132             outVal.append(key, value);
3133             N--;
3134         }
3135     }
3136 
3137     /**
3138      * @hide For testing
3139      */
getBlobAshmemSize()3140     public long getBlobAshmemSize() {
3141         return nativeGetBlobAshmemSize(mNativePtr);
3142     }
3143 }
3144