• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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         int size = entries.size();
839         writeInt(size);
840 
841         for (Map.Entry<String,Object> e : entries) {
842             writeValue(e.getKey());
843             writeValue(e.getValue());
844             size--;
845         }
846 
847         if (size != 0) {
848             throw new BadParcelableException("Map size does not match number of entries!");
849         }
850 
851     }
852 
853     /**
854      * Flatten an ArrayMap into the parcel at the current dataPosition(),
855      * growing dataCapacity() if needed.  The Map keys must be String objects.
856      */
writeArrayMapInternal(ArrayMap<String, Object> val)857     /* package */ void writeArrayMapInternal(ArrayMap<String, Object> val) {
858         if (val == null) {
859             writeInt(-1);
860             return;
861         }
862         // Keep the format of this Parcel in sync with writeToParcelInner() in
863         // frameworks/native/libs/binder/PersistableBundle.cpp.
864         final int N = val.size();
865         writeInt(N);
866         if (DEBUG_ARRAY_MAP) {
867             RuntimeException here =  new RuntimeException("here");
868             here.fillInStackTrace();
869             Log.d(TAG, "Writing " + N + " ArrayMap entries", here);
870         }
871         int startPos;
872         for (int i=0; i<N; i++) {
873             if (DEBUG_ARRAY_MAP) startPos = dataPosition();
874             writeString(val.keyAt(i));
875             writeValue(val.valueAt(i));
876             if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Write #" + i + " "
877                     + (dataPosition()-startPos) + " bytes: key=0x"
878                     + Integer.toHexString(val.keyAt(i) != null ? val.keyAt(i).hashCode() : 0)
879                     + " " + val.keyAt(i));
880         }
881     }
882 
883     /**
884      * @hide For testing only.
885      */
writeArrayMap(ArrayMap<String, Object> val)886     public void writeArrayMap(ArrayMap<String, Object> val) {
887         writeArrayMapInternal(val);
888     }
889 
890     /**
891      * Write an array set to the parcel.
892      *
893      * @param val The array set to write.
894      *
895      * @hide
896      */
writeArraySet(@ullable ArraySet<? extends Object> val)897     public void writeArraySet(@Nullable ArraySet<? extends Object> val) {
898         final int size = (val != null) ? val.size() : -1;
899         writeInt(size);
900         for (int i = 0; i < size; i++) {
901             writeValue(val.valueAt(i));
902         }
903     }
904 
905     /**
906      * Flatten a Bundle into the parcel at the current dataPosition(),
907      * growing dataCapacity() if needed.
908      */
writeBundle(Bundle val)909     public final void writeBundle(Bundle val) {
910         if (val == null) {
911             writeInt(-1);
912             return;
913         }
914 
915         val.writeToParcel(this, 0);
916     }
917 
918     /**
919      * Flatten a PersistableBundle into the parcel at the current dataPosition(),
920      * growing dataCapacity() if needed.
921      */
writePersistableBundle(PersistableBundle val)922     public final void writePersistableBundle(PersistableBundle val) {
923         if (val == null) {
924             writeInt(-1);
925             return;
926         }
927 
928         val.writeToParcel(this, 0);
929     }
930 
931     /**
932      * Flatten a Size into the parcel at the current dataPosition(),
933      * growing dataCapacity() if needed.
934      */
writeSize(Size val)935     public final void writeSize(Size val) {
936         writeInt(val.getWidth());
937         writeInt(val.getHeight());
938     }
939 
940     /**
941      * Flatten a SizeF into the parcel at the current dataPosition(),
942      * growing dataCapacity() if needed.
943      */
writeSizeF(SizeF val)944     public final void writeSizeF(SizeF val) {
945         writeFloat(val.getWidth());
946         writeFloat(val.getHeight());
947     }
948 
949     /**
950      * Flatten a List into the parcel at the current dataPosition(), growing
951      * dataCapacity() if needed.  The List values are written using
952      * {@link #writeValue} and must follow the specification there.
953      */
writeList(List val)954     public final void writeList(List val) {
955         if (val == null) {
956             writeInt(-1);
957             return;
958         }
959         int N = val.size();
960         int i=0;
961         writeInt(N);
962         while (i < N) {
963             writeValue(val.get(i));
964             i++;
965         }
966     }
967 
968     /**
969      * Flatten an Object array into the parcel at the current dataPosition(),
970      * growing dataCapacity() if needed.  The array values are written using
971      * {@link #writeValue} and must follow the specification there.
972      */
writeArray(Object[] val)973     public final void writeArray(Object[] val) {
974         if (val == null) {
975             writeInt(-1);
976             return;
977         }
978         int N = val.length;
979         int i=0;
980         writeInt(N);
981         while (i < N) {
982             writeValue(val[i]);
983             i++;
984         }
985     }
986 
987     /**
988      * Flatten a generic SparseArray into the parcel at the current
989      * dataPosition(), growing dataCapacity() if needed.  The SparseArray
990      * values are written using {@link #writeValue} and must follow the
991      * specification there.
992      */
writeSparseArray(SparseArray<Object> val)993     public final void writeSparseArray(SparseArray<Object> val) {
994         if (val == null) {
995             writeInt(-1);
996             return;
997         }
998         int N = val.size();
999         writeInt(N);
1000         int i=0;
1001         while (i < N) {
1002             writeInt(val.keyAt(i));
1003             writeValue(val.valueAt(i));
1004             i++;
1005         }
1006     }
1007 
writeSparseBooleanArray(SparseBooleanArray val)1008     public final void writeSparseBooleanArray(SparseBooleanArray val) {
1009         if (val == null) {
1010             writeInt(-1);
1011             return;
1012         }
1013         int N = val.size();
1014         writeInt(N);
1015         int i=0;
1016         while (i < N) {
1017             writeInt(val.keyAt(i));
1018             writeByte((byte)(val.valueAt(i) ? 1 : 0));
1019             i++;
1020         }
1021     }
1022 
1023     /**
1024      * @hide
1025      */
writeSparseIntArray(SparseIntArray val)1026     public final void writeSparseIntArray(SparseIntArray val) {
1027         if (val == null) {
1028             writeInt(-1);
1029             return;
1030         }
1031         int N = val.size();
1032         writeInt(N);
1033         int i=0;
1034         while (i < N) {
1035             writeInt(val.keyAt(i));
1036             writeInt(val.valueAt(i));
1037             i++;
1038         }
1039     }
1040 
writeBooleanArray(boolean[] val)1041     public final void writeBooleanArray(boolean[] val) {
1042         if (val != null) {
1043             int N = val.length;
1044             writeInt(N);
1045             for (int i=0; i<N; i++) {
1046                 writeInt(val[i] ? 1 : 0);
1047             }
1048         } else {
1049             writeInt(-1);
1050         }
1051     }
1052 
createBooleanArray()1053     public final boolean[] createBooleanArray() {
1054         int N = readInt();
1055         // >>2 as a fast divide-by-4 works in the create*Array() functions
1056         // because dataAvail() will never return a negative number.  4 is
1057         // the size of a stored boolean in the stream.
1058         if (N >= 0 && N <= (dataAvail() >> 2)) {
1059             boolean[] val = new boolean[N];
1060             for (int i=0; i<N; i++) {
1061                 val[i] = readInt() != 0;
1062             }
1063             return val;
1064         } else {
1065             return null;
1066         }
1067     }
1068 
readBooleanArray(boolean[] val)1069     public final void readBooleanArray(boolean[] val) {
1070         int N = readInt();
1071         if (N == val.length) {
1072             for (int i=0; i<N; i++) {
1073                 val[i] = readInt() != 0;
1074             }
1075         } else {
1076             throw new RuntimeException("bad array lengths");
1077         }
1078     }
1079 
writeCharArray(char[] val)1080     public final void writeCharArray(char[] val) {
1081         if (val != null) {
1082             int N = val.length;
1083             writeInt(N);
1084             for (int i=0; i<N; i++) {
1085                 writeInt((int)val[i]);
1086             }
1087         } else {
1088             writeInt(-1);
1089         }
1090     }
1091 
createCharArray()1092     public final char[] createCharArray() {
1093         int N = readInt();
1094         if (N >= 0 && N <= (dataAvail() >> 2)) {
1095             char[] val = new char[N];
1096             for (int i=0; i<N; i++) {
1097                 val[i] = (char)readInt();
1098             }
1099             return val;
1100         } else {
1101             return null;
1102         }
1103     }
1104 
readCharArray(char[] val)1105     public final void readCharArray(char[] val) {
1106         int N = readInt();
1107         if (N == val.length) {
1108             for (int i=0; i<N; i++) {
1109                 val[i] = (char)readInt();
1110             }
1111         } else {
1112             throw new RuntimeException("bad array lengths");
1113         }
1114     }
1115 
writeIntArray(int[] val)1116     public final void writeIntArray(int[] val) {
1117         if (val != null) {
1118             int N = val.length;
1119             writeInt(N);
1120             for (int i=0; i<N; i++) {
1121                 writeInt(val[i]);
1122             }
1123         } else {
1124             writeInt(-1);
1125         }
1126     }
1127 
createIntArray()1128     public final int[] createIntArray() {
1129         int N = readInt();
1130         if (N >= 0 && N <= (dataAvail() >> 2)) {
1131             int[] val = new int[N];
1132             for (int i=0; i<N; i++) {
1133                 val[i] = readInt();
1134             }
1135             return val;
1136         } else {
1137             return null;
1138         }
1139     }
1140 
readIntArray(int[] val)1141     public final void readIntArray(int[] val) {
1142         int N = readInt();
1143         if (N == val.length) {
1144             for (int i=0; i<N; i++) {
1145                 val[i] = readInt();
1146             }
1147         } else {
1148             throw new RuntimeException("bad array lengths");
1149         }
1150     }
1151 
writeLongArray(long[] val)1152     public final void writeLongArray(long[] val) {
1153         if (val != null) {
1154             int N = val.length;
1155             writeInt(N);
1156             for (int i=0; i<N; i++) {
1157                 writeLong(val[i]);
1158             }
1159         } else {
1160             writeInt(-1);
1161         }
1162     }
1163 
createLongArray()1164     public final long[] createLongArray() {
1165         int N = readInt();
1166         // >>3 because stored longs are 64 bits
1167         if (N >= 0 && N <= (dataAvail() >> 3)) {
1168             long[] val = new long[N];
1169             for (int i=0; i<N; i++) {
1170                 val[i] = readLong();
1171             }
1172             return val;
1173         } else {
1174             return null;
1175         }
1176     }
1177 
readLongArray(long[] val)1178     public final void readLongArray(long[] val) {
1179         int N = readInt();
1180         if (N == val.length) {
1181             for (int i=0; i<N; i++) {
1182                 val[i] = readLong();
1183             }
1184         } else {
1185             throw new RuntimeException("bad array lengths");
1186         }
1187     }
1188 
writeFloatArray(float[] val)1189     public final void writeFloatArray(float[] val) {
1190         if (val != null) {
1191             int N = val.length;
1192             writeInt(N);
1193             for (int i=0; i<N; i++) {
1194                 writeFloat(val[i]);
1195             }
1196         } else {
1197             writeInt(-1);
1198         }
1199     }
1200 
createFloatArray()1201     public final float[] createFloatArray() {
1202         int N = readInt();
1203         // >>2 because stored floats are 4 bytes
1204         if (N >= 0 && N <= (dataAvail() >> 2)) {
1205             float[] val = new float[N];
1206             for (int i=0; i<N; i++) {
1207                 val[i] = readFloat();
1208             }
1209             return val;
1210         } else {
1211             return null;
1212         }
1213     }
1214 
readFloatArray(float[] val)1215     public final void readFloatArray(float[] val) {
1216         int N = readInt();
1217         if (N == val.length) {
1218             for (int i=0; i<N; i++) {
1219                 val[i] = readFloat();
1220             }
1221         } else {
1222             throw new RuntimeException("bad array lengths");
1223         }
1224     }
1225 
writeDoubleArray(double[] val)1226     public final void writeDoubleArray(double[] val) {
1227         if (val != null) {
1228             int N = val.length;
1229             writeInt(N);
1230             for (int i=0; i<N; i++) {
1231                 writeDouble(val[i]);
1232             }
1233         } else {
1234             writeInt(-1);
1235         }
1236     }
1237 
createDoubleArray()1238     public final double[] createDoubleArray() {
1239         int N = readInt();
1240         // >>3 because stored doubles are 8 bytes
1241         if (N >= 0 && N <= (dataAvail() >> 3)) {
1242             double[] val = new double[N];
1243             for (int i=0; i<N; i++) {
1244                 val[i] = readDouble();
1245             }
1246             return val;
1247         } else {
1248             return null;
1249         }
1250     }
1251 
readDoubleArray(double[] val)1252     public final void readDoubleArray(double[] val) {
1253         int N = readInt();
1254         if (N == val.length) {
1255             for (int i=0; i<N; i++) {
1256                 val[i] = readDouble();
1257             }
1258         } else {
1259             throw new RuntimeException("bad array lengths");
1260         }
1261     }
1262 
writeStringArray(String[] val)1263     public final void writeStringArray(String[] val) {
1264         if (val != null) {
1265             int N = val.length;
1266             writeInt(N);
1267             for (int i=0; i<N; i++) {
1268                 writeString(val[i]);
1269             }
1270         } else {
1271             writeInt(-1);
1272         }
1273     }
1274 
createStringArray()1275     public final String[] createStringArray() {
1276         int N = readInt();
1277         if (N >= 0) {
1278             String[] val = new String[N];
1279             for (int i=0; i<N; i++) {
1280                 val[i] = readString();
1281             }
1282             return val;
1283         } else {
1284             return null;
1285         }
1286     }
1287 
readStringArray(String[] val)1288     public final void readStringArray(String[] val) {
1289         int N = readInt();
1290         if (N == val.length) {
1291             for (int i=0; i<N; i++) {
1292                 val[i] = readString();
1293             }
1294         } else {
1295             throw new RuntimeException("bad array lengths");
1296         }
1297     }
1298 
writeBinderArray(IBinder[] val)1299     public final void writeBinderArray(IBinder[] val) {
1300         if (val != null) {
1301             int N = val.length;
1302             writeInt(N);
1303             for (int i=0; i<N; i++) {
1304                 writeStrongBinder(val[i]);
1305             }
1306         } else {
1307             writeInt(-1);
1308         }
1309     }
1310 
1311     /**
1312      * @hide
1313      */
writeCharSequenceArray(CharSequence[] val)1314     public final void writeCharSequenceArray(CharSequence[] val) {
1315         if (val != null) {
1316             int N = val.length;
1317             writeInt(N);
1318             for (int i=0; i<N; i++) {
1319                 writeCharSequence(val[i]);
1320             }
1321         } else {
1322             writeInt(-1);
1323         }
1324     }
1325 
1326     /**
1327      * @hide
1328      */
writeCharSequenceList(ArrayList<CharSequence> val)1329     public final void writeCharSequenceList(ArrayList<CharSequence> val) {
1330         if (val != null) {
1331             int N = val.size();
1332             writeInt(N);
1333             for (int i=0; i<N; i++) {
1334                 writeCharSequence(val.get(i));
1335             }
1336         } else {
1337             writeInt(-1);
1338         }
1339     }
1340 
createBinderArray()1341     public final IBinder[] createBinderArray() {
1342         int N = readInt();
1343         if (N >= 0) {
1344             IBinder[] val = new IBinder[N];
1345             for (int i=0; i<N; i++) {
1346                 val[i] = readStrongBinder();
1347             }
1348             return val;
1349         } else {
1350             return null;
1351         }
1352     }
1353 
readBinderArray(IBinder[] val)1354     public final void readBinderArray(IBinder[] val) {
1355         int N = readInt();
1356         if (N == val.length) {
1357             for (int i=0; i<N; i++) {
1358                 val[i] = readStrongBinder();
1359             }
1360         } else {
1361             throw new RuntimeException("bad array lengths");
1362         }
1363     }
1364 
1365     /**
1366      * Flatten a List containing a particular object type into the parcel, at
1367      * the current dataPosition() and growing dataCapacity() if needed.  The
1368      * type of the objects in the list must be one that implements Parcelable.
1369      * Unlike the generic writeList() method, however, only the raw data of the
1370      * objects is written and not their type, so you must use the corresponding
1371      * readTypedList() to unmarshall them.
1372      *
1373      * @param val The list of objects to be written.
1374      *
1375      * @see #createTypedArrayList
1376      * @see #readTypedList
1377      * @see Parcelable
1378      */
writeTypedList(List<T> val)1379     public final <T extends Parcelable> void writeTypedList(List<T> val) {
1380         writeTypedList(val, 0);
1381     }
1382 
1383     /**
1384      * @hide
1385      */
writeTypedList(List<T> val, int parcelableFlags)1386     public <T extends Parcelable> void writeTypedList(List<T> val, int parcelableFlags) {
1387         if (val == null) {
1388             writeInt(-1);
1389             return;
1390         }
1391         int N = val.size();
1392         int i=0;
1393         writeInt(N);
1394         while (i < N) {
1395             writeTypedObject(val.get(i), parcelableFlags);
1396             i++;
1397         }
1398     }
1399 
1400     /**
1401      * Flatten a List containing String objects into the parcel, at
1402      * the current dataPosition() and growing dataCapacity() if needed.  They
1403      * can later be retrieved with {@link #createStringArrayList} or
1404      * {@link #readStringList}.
1405      *
1406      * @param val The list of strings to be written.
1407      *
1408      * @see #createStringArrayList
1409      * @see #readStringList
1410      */
writeStringList(List<String> val)1411     public final void writeStringList(List<String> val) {
1412         if (val == null) {
1413             writeInt(-1);
1414             return;
1415         }
1416         int N = val.size();
1417         int i=0;
1418         writeInt(N);
1419         while (i < N) {
1420             writeString(val.get(i));
1421             i++;
1422         }
1423     }
1424 
1425     /**
1426      * Flatten a List containing IBinder objects into the parcel, at
1427      * the current dataPosition() and growing dataCapacity() if needed.  They
1428      * can later be retrieved with {@link #createBinderArrayList} or
1429      * {@link #readBinderList}.
1430      *
1431      * @param val The list of strings to be written.
1432      *
1433      * @see #createBinderArrayList
1434      * @see #readBinderList
1435      */
writeBinderList(List<IBinder> val)1436     public final void writeBinderList(List<IBinder> val) {
1437         if (val == null) {
1438             writeInt(-1);
1439             return;
1440         }
1441         int N = val.size();
1442         int i=0;
1443         writeInt(N);
1444         while (i < N) {
1445             writeStrongBinder(val.get(i));
1446             i++;
1447         }
1448     }
1449 
1450     /**
1451      * Flatten a {@code List} containing arbitrary {@code Parcelable} objects into this parcel
1452      * at the current position. They can later be retrieved using
1453      * {@link #readParcelableList(List, ClassLoader)} if required.
1454      *
1455      * @see #readParcelableList(List, ClassLoader)
1456      * @hide
1457      */
writeParcelableList(List<T> val, int flags)1458     public final <T extends Parcelable> void writeParcelableList(List<T> val, int flags) {
1459         if (val == null) {
1460             writeInt(-1);
1461             return;
1462         }
1463 
1464         int N = val.size();
1465         int i=0;
1466         writeInt(N);
1467         while (i < N) {
1468             writeParcelable(val.get(i), flags);
1469             i++;
1470         }
1471     }
1472 
1473     /**
1474      * Flatten a homogeneous array containing a particular object type into
1475      * the parcel, at
1476      * the current dataPosition() and growing dataCapacity() if needed.  The
1477      * type of the objects in the array must be one that implements Parcelable.
1478      * Unlike the {@link #writeParcelableArray} method, however, only the
1479      * raw data of the objects is written and not their type, so you must use
1480      * {@link #readTypedArray} with the correct corresponding
1481      * {@link Parcelable.Creator} implementation to unmarshall them.
1482      *
1483      * @param val The array of objects to be written.
1484      * @param parcelableFlags Contextual flags as per
1485      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1486      *
1487      * @see #readTypedArray
1488      * @see #writeParcelableArray
1489      * @see Parcelable.Creator
1490      */
writeTypedArray(T[] val, int parcelableFlags)1491     public final <T extends Parcelable> void writeTypedArray(T[] val,
1492             int parcelableFlags) {
1493         if (val != null) {
1494             int N = val.length;
1495             writeInt(N);
1496             for (int i = 0; i < N; i++) {
1497                 writeTypedObject(val[i], parcelableFlags);
1498             }
1499         } else {
1500             writeInt(-1);
1501         }
1502     }
1503 
1504     /**
1505      * Flatten the Parcelable object into the parcel.
1506      *
1507      * @param val The Parcelable object to be written.
1508      * @param parcelableFlags Contextual flags as per
1509      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1510      *
1511      * @see #readTypedObject
1512      */
writeTypedObject(T val, int parcelableFlags)1513     public final <T extends Parcelable> void writeTypedObject(T val, int parcelableFlags) {
1514         if (val != null) {
1515             writeInt(1);
1516             val.writeToParcel(this, parcelableFlags);
1517         } else {
1518             writeInt(0);
1519         }
1520     }
1521 
1522     /**
1523      * Flatten a generic object in to a parcel.  The given Object value may
1524      * currently be one of the following types:
1525      *
1526      * <ul>
1527      * <li> null
1528      * <li> String
1529      * <li> Byte
1530      * <li> Short
1531      * <li> Integer
1532      * <li> Long
1533      * <li> Float
1534      * <li> Double
1535      * <li> Boolean
1536      * <li> String[]
1537      * <li> boolean[]
1538      * <li> byte[]
1539      * <li> int[]
1540      * <li> long[]
1541      * <li> Object[] (supporting objects of the same type defined here).
1542      * <li> {@link Bundle}
1543      * <li> Map (as supported by {@link #writeMap}).
1544      * <li> Any object that implements the {@link Parcelable} protocol.
1545      * <li> Parcelable[]
1546      * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
1547      * <li> List (as supported by {@link #writeList}).
1548      * <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}).
1549      * <li> {@link IBinder}
1550      * <li> Any object that implements Serializable (but see
1551      *      {@link #writeSerializable} for caveats).  Note that all of the
1552      *      previous types have relatively efficient implementations for
1553      *      writing to a Parcel; having to rely on the generic serialization
1554      *      approach is much less efficient and should be avoided whenever
1555      *      possible.
1556      * </ul>
1557      *
1558      * <p class="caution">{@link Parcelable} objects are written with
1559      * {@link Parcelable#writeToParcel} using contextual flags of 0.  When
1560      * serializing objects containing {@link ParcelFileDescriptor}s,
1561      * this may result in file descriptor leaks when they are returned from
1562      * Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE}
1563      * should be used).</p>
1564      */
writeValue(Object v)1565     public final void writeValue(Object v) {
1566         if (v == null) {
1567             writeInt(VAL_NULL);
1568         } else if (v instanceof String) {
1569             writeInt(VAL_STRING);
1570             writeString((String) v);
1571         } else if (v instanceof Integer) {
1572             writeInt(VAL_INTEGER);
1573             writeInt((Integer) v);
1574         } else if (v instanceof Map) {
1575             writeInt(VAL_MAP);
1576             writeMap((Map) v);
1577         } else if (v instanceof Bundle) {
1578             // Must be before Parcelable
1579             writeInt(VAL_BUNDLE);
1580             writeBundle((Bundle) v);
1581         } else if (v instanceof PersistableBundle) {
1582             writeInt(VAL_PERSISTABLEBUNDLE);
1583             writePersistableBundle((PersistableBundle) v);
1584         } else if (v instanceof Parcelable) {
1585             // IMPOTANT: cases for classes that implement Parcelable must
1586             // come before the Parcelable case, so that their specific VAL_*
1587             // types will be written.
1588             writeInt(VAL_PARCELABLE);
1589             writeParcelable((Parcelable) v, 0);
1590         } else if (v instanceof Short) {
1591             writeInt(VAL_SHORT);
1592             writeInt(((Short) v).intValue());
1593         } else if (v instanceof Long) {
1594             writeInt(VAL_LONG);
1595             writeLong((Long) v);
1596         } else if (v instanceof Float) {
1597             writeInt(VAL_FLOAT);
1598             writeFloat((Float) v);
1599         } else if (v instanceof Double) {
1600             writeInt(VAL_DOUBLE);
1601             writeDouble((Double) v);
1602         } else if (v instanceof Boolean) {
1603             writeInt(VAL_BOOLEAN);
1604             writeInt((Boolean) v ? 1 : 0);
1605         } else if (v instanceof CharSequence) {
1606             // Must be after String
1607             writeInt(VAL_CHARSEQUENCE);
1608             writeCharSequence((CharSequence) v);
1609         } else if (v instanceof List) {
1610             writeInt(VAL_LIST);
1611             writeList((List) v);
1612         } else if (v instanceof SparseArray) {
1613             writeInt(VAL_SPARSEARRAY);
1614             writeSparseArray((SparseArray) v);
1615         } else if (v instanceof boolean[]) {
1616             writeInt(VAL_BOOLEANARRAY);
1617             writeBooleanArray((boolean[]) v);
1618         } else if (v instanceof byte[]) {
1619             writeInt(VAL_BYTEARRAY);
1620             writeByteArray((byte[]) v);
1621         } else if (v instanceof String[]) {
1622             writeInt(VAL_STRINGARRAY);
1623             writeStringArray((String[]) v);
1624         } else if (v instanceof CharSequence[]) {
1625             // Must be after String[] and before Object[]
1626             writeInt(VAL_CHARSEQUENCEARRAY);
1627             writeCharSequenceArray((CharSequence[]) v);
1628         } else if (v instanceof IBinder) {
1629             writeInt(VAL_IBINDER);
1630             writeStrongBinder((IBinder) v);
1631         } else if (v instanceof Parcelable[]) {
1632             writeInt(VAL_PARCELABLEARRAY);
1633             writeParcelableArray((Parcelable[]) v, 0);
1634         } else if (v instanceof int[]) {
1635             writeInt(VAL_INTARRAY);
1636             writeIntArray((int[]) v);
1637         } else if (v instanceof long[]) {
1638             writeInt(VAL_LONGARRAY);
1639             writeLongArray((long[]) v);
1640         } else if (v instanceof Byte) {
1641             writeInt(VAL_BYTE);
1642             writeInt((Byte) v);
1643         } else if (v instanceof Size) {
1644             writeInt(VAL_SIZE);
1645             writeSize((Size) v);
1646         } else if (v instanceof SizeF) {
1647             writeInt(VAL_SIZEF);
1648             writeSizeF((SizeF) v);
1649         } else if (v instanceof double[]) {
1650             writeInt(VAL_DOUBLEARRAY);
1651             writeDoubleArray((double[]) v);
1652         } else {
1653             Class<?> clazz = v.getClass();
1654             if (clazz.isArray() && clazz.getComponentType() == Object.class) {
1655                 // Only pure Object[] are written here, Other arrays of non-primitive types are
1656                 // handled by serialization as this does not record the component type.
1657                 writeInt(VAL_OBJECTARRAY);
1658                 writeArray((Object[]) v);
1659             } else if (v instanceof Serializable) {
1660                 // Must be last
1661                 writeInt(VAL_SERIALIZABLE);
1662                 writeSerializable((Serializable) v);
1663             } else {
1664                 throw new RuntimeException("Parcel: unable to marshal value " + v);
1665             }
1666         }
1667     }
1668 
1669     /**
1670      * Flatten the name of the class of the Parcelable and its contents
1671      * into the parcel.
1672      *
1673      * @param p The Parcelable object to be written.
1674      * @param parcelableFlags Contextual flags as per
1675      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1676      */
writeParcelable(Parcelable p, int parcelableFlags)1677     public final void writeParcelable(Parcelable p, int parcelableFlags) {
1678         if (p == null) {
1679             writeString(null);
1680             return;
1681         }
1682         writeParcelableCreator(p);
1683         p.writeToParcel(this, parcelableFlags);
1684     }
1685 
1686     /** @hide */
writeParcelableCreator(Parcelable p)1687     public final void writeParcelableCreator(Parcelable p) {
1688         String name = p.getClass().getName();
1689         writeString(name);
1690     }
1691 
1692     /**
1693      * Write a generic serializable object in to a Parcel.  It is strongly
1694      * recommended that this method be avoided, since the serialization
1695      * overhead is extremely large, and this approach will be much slower than
1696      * using the other approaches to writing data in to a Parcel.
1697      */
writeSerializable(Serializable s)1698     public final void writeSerializable(Serializable s) {
1699         if (s == null) {
1700             writeString(null);
1701             return;
1702         }
1703         String name = s.getClass().getName();
1704         writeString(name);
1705 
1706         ByteArrayOutputStream baos = new ByteArrayOutputStream();
1707         try {
1708             ObjectOutputStream oos = new ObjectOutputStream(baos);
1709             oos.writeObject(s);
1710             oos.close();
1711 
1712             writeByteArray(baos.toByteArray());
1713         } catch (IOException ioe) {
1714             throw new RuntimeException("Parcelable encountered " +
1715                 "IOException writing serializable object (name = " + name +
1716                 ")", ioe);
1717         }
1718     }
1719 
1720     /** @hide For debugging purposes */
setStackTraceParceling(boolean enabled)1721     public static void setStackTraceParceling(boolean enabled) {
1722         sParcelExceptionStackTrace = enabled;
1723     }
1724 
1725     /**
1726      * Special function for writing an exception result at the header of
1727      * a parcel, to be used when returning an exception from a transaction.
1728      * Note that this currently only supports a few exception types; any other
1729      * exception will be re-thrown by this function as a RuntimeException
1730      * (to be caught by the system's last-resort exception handling when
1731      * dispatching a transaction).
1732      *
1733      * <p>The supported exception types are:
1734      * <ul>
1735      * <li>{@link BadParcelableException}
1736      * <li>{@link IllegalArgumentException}
1737      * <li>{@link IllegalStateException}
1738      * <li>{@link NullPointerException}
1739      * <li>{@link SecurityException}
1740      * <li>{@link UnsupportedOperationException}
1741      * <li>{@link NetworkOnMainThreadException}
1742      * </ul>
1743      *
1744      * @param e The Exception to be written.
1745      *
1746      * @see #writeNoException
1747      * @see #readException
1748      */
writeException(Exception e)1749     public final void writeException(Exception e) {
1750         int code = 0;
1751         if (e instanceof Parcelable
1752                 && (e.getClass().getClassLoader() == Parcelable.class.getClassLoader())) {
1753             // We only send Parcelable exceptions that are in the
1754             // BootClassLoader to ensure that the receiver can unpack them
1755             code = EX_PARCELABLE;
1756         } else if (e instanceof SecurityException) {
1757             code = EX_SECURITY;
1758         } else if (e instanceof BadParcelableException) {
1759             code = EX_BAD_PARCELABLE;
1760         } else if (e instanceof IllegalArgumentException) {
1761             code = EX_ILLEGAL_ARGUMENT;
1762         } else if (e instanceof NullPointerException) {
1763             code = EX_NULL_POINTER;
1764         } else if (e instanceof IllegalStateException) {
1765             code = EX_ILLEGAL_STATE;
1766         } else if (e instanceof NetworkOnMainThreadException) {
1767             code = EX_NETWORK_MAIN_THREAD;
1768         } else if (e instanceof UnsupportedOperationException) {
1769             code = EX_UNSUPPORTED_OPERATION;
1770         } else if (e instanceof ServiceSpecificException) {
1771             code = EX_SERVICE_SPECIFIC;
1772         }
1773         writeInt(code);
1774         StrictMode.clearGatheredViolations();
1775         if (code == 0) {
1776             if (e instanceof RuntimeException) {
1777                 throw (RuntimeException) e;
1778             }
1779             throw new RuntimeException(e);
1780         }
1781         writeString(e.getMessage());
1782         final long timeNow = sParcelExceptionStackTrace ? SystemClock.elapsedRealtime() : 0;
1783         if (sParcelExceptionStackTrace && (timeNow - sLastWriteExceptionStackTrace
1784                 > WRITE_EXCEPTION_STACK_TRACE_THRESHOLD_MS)) {
1785             sLastWriteExceptionStackTrace = timeNow;
1786             final int sizePosition = dataPosition();
1787             writeInt(0); // Header size will be filled in later
1788             StackTraceElement[] stackTrace = e.getStackTrace();
1789             final int truncatedSize = Math.min(stackTrace.length, 5);
1790             StringBuilder sb = new StringBuilder();
1791             for (int i = 0; i < truncatedSize; i++) {
1792                 sb.append("\tat ").append(stackTrace[i]).append('\n');
1793             }
1794             writeString(sb.toString());
1795             final int payloadPosition = dataPosition();
1796             setDataPosition(sizePosition);
1797             // Write stack trace header size. Used in native side to skip the header
1798             writeInt(payloadPosition - sizePosition);
1799             setDataPosition(payloadPosition);
1800         } else {
1801             writeInt(0);
1802         }
1803         switch (code) {
1804             case EX_SERVICE_SPECIFIC:
1805                 writeInt(((ServiceSpecificException) e).errorCode);
1806                 break;
1807             case EX_PARCELABLE:
1808                 // Write parceled exception prefixed by length
1809                 final int sizePosition = dataPosition();
1810                 writeInt(0);
1811                 writeParcelable((Parcelable) e, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1812                 final int payloadPosition = dataPosition();
1813                 setDataPosition(sizePosition);
1814                 writeInt(payloadPosition - sizePosition);
1815                 setDataPosition(payloadPosition);
1816                 break;
1817         }
1818     }
1819 
1820     /**
1821      * Special function for writing information at the front of the Parcel
1822      * indicating that no exception occurred.
1823      *
1824      * @see #writeException
1825      * @see #readException
1826      */
writeNoException()1827     public final void writeNoException() {
1828         // Despite the name of this function ("write no exception"),
1829         // it should instead be thought of as "write the RPC response
1830         // header", but because this function name is written out by
1831         // the AIDL compiler, we're not going to rename it.
1832         //
1833         // The response header, in the non-exception case (see also
1834         // writeException above, also called by the AIDL compiler), is
1835         // either a 0 (the default case), or EX_HAS_REPLY_HEADER if
1836         // StrictMode has gathered up violations that have occurred
1837         // during a Binder call, in which case we write out the number
1838         // of violations and their details, serialized, before the
1839         // actual RPC respons data.  The receiving end of this is
1840         // readException(), below.
1841         if (StrictMode.hasGatheredViolations()) {
1842             writeInt(EX_HAS_REPLY_HEADER);
1843             final int sizePosition = dataPosition();
1844             writeInt(0);  // total size of fat header, to be filled in later
1845             StrictMode.writeGatheredViolationsToParcel(this);
1846             final int payloadPosition = dataPosition();
1847             setDataPosition(sizePosition);
1848             writeInt(payloadPosition - sizePosition);  // header size
1849             setDataPosition(payloadPosition);
1850         } else {
1851             writeInt(0);
1852         }
1853     }
1854 
1855     /**
1856      * Special function for reading an exception result from the header of
1857      * a parcel, to be used after receiving the result of a transaction.  This
1858      * will throw the exception for you if it had been written to the Parcel,
1859      * otherwise return and let you read the normal result data from the Parcel.
1860      *
1861      * @see #writeException
1862      * @see #writeNoException
1863      */
readException()1864     public final void readException() {
1865         int code = readExceptionCode();
1866         if (code != 0) {
1867             String msg = readString();
1868             readException(code, msg);
1869         }
1870     }
1871 
1872     /**
1873      * Parses the header of a Binder call's response Parcel and
1874      * returns the exception code.  Deals with lite or fat headers.
1875      * In the common successful case, this header is generally zero.
1876      * In less common cases, it's a small negative number and will be
1877      * followed by an error string.
1878      *
1879      * This exists purely for android.database.DatabaseUtils and
1880      * insulating it from having to handle fat headers as returned by
1881      * e.g. StrictMode-induced RPC responses.
1882      *
1883      * @hide
1884      */
readExceptionCode()1885     public final int readExceptionCode() {
1886         int code = readInt();
1887         if (code == EX_HAS_REPLY_HEADER) {
1888             int headerSize = readInt();
1889             if (headerSize == 0) {
1890                 Log.e(TAG, "Unexpected zero-sized Parcel reply header.");
1891             } else {
1892                 // Currently the only thing in the header is StrictMode stacks,
1893                 // but discussions around event/RPC tracing suggest we might
1894                 // put that here too.  If so, switch on sub-header tags here.
1895                 // But for now, just parse out the StrictMode stuff.
1896                 StrictMode.readAndHandleBinderCallViolations(this);
1897             }
1898             // And fat response headers are currently only used when
1899             // there are no exceptions, so return no error:
1900             return 0;
1901         }
1902         return code;
1903     }
1904 
1905     /**
1906      * Throw an exception with the given message. Not intended for use
1907      * outside the Parcel class.
1908      *
1909      * @param code Used to determine which exception class to throw.
1910      * @param msg The exception message.
1911      */
readException(int code, String msg)1912     public final void readException(int code, String msg) {
1913         String remoteStackTrace = null;
1914         final int remoteStackPayloadSize = readInt();
1915         if (remoteStackPayloadSize > 0) {
1916             remoteStackTrace = readString();
1917         }
1918         Exception e = createException(code, msg);
1919         // Attach remote stack trace if availalble
1920         if (remoteStackTrace != null) {
1921             RemoteException cause = new RemoteException(
1922                     "Remote stack trace:\n" + remoteStackTrace, null, false, false);
1923             try {
1924                 Throwable rootCause = ExceptionUtils.getRootCause(e);
1925                 if (rootCause != null) {
1926                     rootCause.initCause(cause);
1927                 }
1928             } catch (RuntimeException ex) {
1929                 Log.e(TAG, "Cannot set cause " + cause + " for " + e, ex);
1930             }
1931         }
1932         SneakyThrow.sneakyThrow(e);
1933     }
1934 
1935     /**
1936      * Creates an exception with the given message.
1937      *
1938      * @param code Used to determine which exception class to throw.
1939      * @param msg The exception message.
1940      */
createException(int code, String msg)1941     private Exception createException(int code, String msg) {
1942         switch (code) {
1943             case EX_PARCELABLE:
1944                 if (readInt() > 0) {
1945                     return (Exception) readParcelable(Parcelable.class.getClassLoader());
1946                 } else {
1947                     return new RuntimeException(msg + " [missing Parcelable]");
1948                 }
1949             case EX_SECURITY:
1950                 return new SecurityException(msg);
1951             case EX_BAD_PARCELABLE:
1952                 return new BadParcelableException(msg);
1953             case EX_ILLEGAL_ARGUMENT:
1954                 return new IllegalArgumentException(msg);
1955             case EX_NULL_POINTER:
1956                 return new NullPointerException(msg);
1957             case EX_ILLEGAL_STATE:
1958                 return new IllegalStateException(msg);
1959             case EX_NETWORK_MAIN_THREAD:
1960                 return new NetworkOnMainThreadException();
1961             case EX_UNSUPPORTED_OPERATION:
1962                 return new UnsupportedOperationException(msg);
1963             case EX_SERVICE_SPECIFIC:
1964                 return new ServiceSpecificException(readInt(), msg);
1965         }
1966         return new RuntimeException("Unknown exception code: " + code
1967                 + " msg " + msg);
1968     }
1969 
1970     /**
1971      * Read an integer value from the parcel at the current dataPosition().
1972      */
readInt()1973     public final int readInt() {
1974         return nativeReadInt(mNativePtr);
1975     }
1976 
1977     /**
1978      * Read a long integer value from the parcel at the current dataPosition().
1979      */
readLong()1980     public final long readLong() {
1981         return nativeReadLong(mNativePtr);
1982     }
1983 
1984     /**
1985      * Read a floating point value from the parcel at the current
1986      * dataPosition().
1987      */
readFloat()1988     public final float readFloat() {
1989         return nativeReadFloat(mNativePtr);
1990     }
1991 
1992     /**
1993      * Read a double precision floating point value from the parcel at the
1994      * current dataPosition().
1995      */
readDouble()1996     public final double readDouble() {
1997         return nativeReadDouble(mNativePtr);
1998     }
1999 
2000     /**
2001      * Read a string value from the parcel at the current dataPosition().
2002      */
readString()2003     public final String readString() {
2004         return mReadWriteHelper.readString(this);
2005     }
2006 
2007     /**
2008      * Read a string without going though a {@link ReadWriteHelper}.  Subclasses of
2009      * {@link ReadWriteHelper} must use this method instead of {@link #readString} to avoid
2010      * infinity recursive calls.
2011      *
2012      * @hide
2013      */
readStringNoHelper()2014     public String readStringNoHelper() {
2015         return nativeReadString(mNativePtr);
2016     }
2017 
2018     /** @hide */
readBoolean()2019     public final boolean readBoolean() {
2020         return readInt() != 0;
2021     }
2022 
2023     /**
2024      * Read a CharSequence value from the parcel at the current dataPosition().
2025      * @hide
2026      */
readCharSequence()2027     public final CharSequence readCharSequence() {
2028         return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
2029     }
2030 
2031     /**
2032      * Read an object from the parcel at the current dataPosition().
2033      */
readStrongBinder()2034     public final IBinder readStrongBinder() {
2035         return nativeReadStrongBinder(mNativePtr);
2036     }
2037 
2038     /**
2039      * Read a FileDescriptor from the parcel at the current dataPosition().
2040      */
readFileDescriptor()2041     public final ParcelFileDescriptor readFileDescriptor() {
2042         FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
2043         return fd != null ? new ParcelFileDescriptor(fd) : null;
2044     }
2045 
2046     /** {@hide} */
readRawFileDescriptor()2047     public final FileDescriptor readRawFileDescriptor() {
2048         return nativeReadFileDescriptor(mNativePtr);
2049     }
2050 
2051     /**
2052      * {@hide}
2053      * Read and return a new array of FileDescriptors from the parcel.
2054      * @return the FileDescriptor array, or null if the array is null.
2055      **/
createRawFileDescriptorArray()2056     public final FileDescriptor[] createRawFileDescriptorArray() {
2057         int N = readInt();
2058         if (N < 0) {
2059             return null;
2060         }
2061         FileDescriptor[] f = new FileDescriptor[N];
2062         for (int i = 0; i < N; i++) {
2063             f[i] = readRawFileDescriptor();
2064         }
2065         return f;
2066     }
2067 
2068     /**
2069      * {@hide}
2070      * Read an array of FileDescriptors from a parcel.
2071      * The passed array must be exactly the length of the array in the parcel.
2072      * @return the FileDescriptor array, or null if the array is null.
2073      **/
readRawFileDescriptorArray(FileDescriptor[] val)2074     public final void readRawFileDescriptorArray(FileDescriptor[] val) {
2075         int N = readInt();
2076         if (N == val.length) {
2077             for (int i=0; i<N; i++) {
2078                 val[i] = readRawFileDescriptor();
2079             }
2080         } else {
2081             throw new RuntimeException("bad array lengths");
2082         }
2083     }
2084 
2085     /** @deprecated use {@link android.system.Os#open(String, int, int)} */
2086     @Deprecated
openFileDescriptor(String file, int mode)2087     static native FileDescriptor openFileDescriptor(String file, int mode)
2088             throws FileNotFoundException;
2089 
2090     /** @deprecated use {@link android.system.Os#dup(FileDescriptor)} */
2091     @Deprecated
dupFileDescriptor(FileDescriptor orig)2092     static native FileDescriptor dupFileDescriptor(FileDescriptor orig) throws IOException;
2093 
2094     /** @deprecated use {@link android.system.Os#close(FileDescriptor)} */
2095     @Deprecated
closeFileDescriptor(FileDescriptor desc)2096     static native void closeFileDescriptor(FileDescriptor desc) throws IOException;
2097 
2098     /**
2099      * Read a byte value from the parcel at the current dataPosition().
2100      */
readByte()2101     public final byte readByte() {
2102         return (byte)(readInt() & 0xff);
2103     }
2104 
2105     /**
2106      * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2107      * been written with {@link #writeBundle}.  Read into an existing Map object
2108      * from the parcel at the current dataPosition().
2109      */
readMap(Map outVal, ClassLoader loader)2110     public final void readMap(Map outVal, ClassLoader loader) {
2111         int N = readInt();
2112         readMapInternal(outVal, N, loader);
2113     }
2114 
2115     /**
2116      * Read into an existing List object from the parcel at the current
2117      * dataPosition(), using the given class loader to load any enclosed
2118      * Parcelables.  If it is null, the default class loader is used.
2119      */
readList(List outVal, ClassLoader loader)2120     public final void readList(List outVal, ClassLoader loader) {
2121         int N = readInt();
2122         readListInternal(outVal, N, loader);
2123     }
2124 
2125     /**
2126      * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2127      * been written with {@link #writeBundle}.  Read and return a new HashMap
2128      * object from the parcel at the current dataPosition(), using the given
2129      * class loader to load any enclosed Parcelables.  Returns null if
2130      * the previously written map object was null.
2131      */
readHashMap(ClassLoader loader)2132     public final HashMap readHashMap(ClassLoader loader)
2133     {
2134         int N = readInt();
2135         if (N < 0) {
2136             return null;
2137         }
2138         HashMap m = new HashMap(N);
2139         readMapInternal(m, N, loader);
2140         return m;
2141     }
2142 
2143     /**
2144      * Read and return a new Bundle object from the parcel at the current
2145      * dataPosition().  Returns null if the previously written Bundle object was
2146      * null.
2147      */
readBundle()2148     public final Bundle readBundle() {
2149         return readBundle(null);
2150     }
2151 
2152     /**
2153      * Read and return a new Bundle object from the parcel at the current
2154      * dataPosition(), using the given class loader to initialize the class
2155      * loader of the Bundle for later retrieval of Parcelable objects.
2156      * Returns null if the previously written Bundle object was null.
2157      */
readBundle(ClassLoader loader)2158     public final Bundle readBundle(ClassLoader loader) {
2159         int length = readInt();
2160         if (length < 0) {
2161             if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2162             return null;
2163         }
2164 
2165         final Bundle bundle = new Bundle(this, length);
2166         if (loader != null) {
2167             bundle.setClassLoader(loader);
2168         }
2169         return bundle;
2170     }
2171 
2172     /**
2173      * Read and return a new Bundle object from the parcel at the current
2174      * dataPosition().  Returns null if the previously written Bundle object was
2175      * null.
2176      */
readPersistableBundle()2177     public final PersistableBundle readPersistableBundle() {
2178         return readPersistableBundle(null);
2179     }
2180 
2181     /**
2182      * Read and return a new Bundle object from the parcel at the current
2183      * dataPosition(), using the given class loader to initialize the class
2184      * loader of the Bundle for later retrieval of Parcelable objects.
2185      * Returns null if the previously written Bundle object was null.
2186      */
readPersistableBundle(ClassLoader loader)2187     public final PersistableBundle readPersistableBundle(ClassLoader loader) {
2188         int length = readInt();
2189         if (length < 0) {
2190             if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2191             return null;
2192         }
2193 
2194         final PersistableBundle bundle = new PersistableBundle(this, length);
2195         if (loader != null) {
2196             bundle.setClassLoader(loader);
2197         }
2198         return bundle;
2199     }
2200 
2201     /**
2202      * Read a Size from the parcel at the current dataPosition().
2203      */
readSize()2204     public final Size readSize() {
2205         final int width = readInt();
2206         final int height = readInt();
2207         return new Size(width, height);
2208     }
2209 
2210     /**
2211      * Read a SizeF from the parcel at the current dataPosition().
2212      */
readSizeF()2213     public final SizeF readSizeF() {
2214         final float width = readFloat();
2215         final float height = readFloat();
2216         return new SizeF(width, height);
2217     }
2218 
2219     /**
2220      * Read and return a byte[] object from the parcel.
2221      */
createByteArray()2222     public final byte[] createByteArray() {
2223         return nativeCreateByteArray(mNativePtr);
2224     }
2225 
2226     /**
2227      * Read a byte[] object from the parcel and copy it into the
2228      * given byte array.
2229      */
readByteArray(byte[] val)2230     public final void readByteArray(byte[] val) {
2231         boolean valid = nativeReadByteArray(mNativePtr, val, (val != null) ? val.length : 0);
2232         if (!valid) {
2233             throw new RuntimeException("bad array lengths");
2234         }
2235     }
2236 
2237     /**
2238      * Read a blob of data from the parcel and return it as a byte array.
2239      * {@hide}
2240      * {@SystemApi}
2241      */
readBlob()2242     public final byte[] readBlob() {
2243         return nativeReadBlob(mNativePtr);
2244     }
2245 
2246     /**
2247      * Read and return a String[] object from the parcel.
2248      * {@hide}
2249      */
readStringArray()2250     public final String[] readStringArray() {
2251         String[] array = null;
2252 
2253         int length = readInt();
2254         if (length >= 0)
2255         {
2256             array = new String[length];
2257 
2258             for (int i = 0 ; i < length ; i++)
2259             {
2260                 array[i] = readString();
2261             }
2262         }
2263 
2264         return array;
2265     }
2266 
2267     /**
2268      * Read and return a CharSequence[] object from the parcel.
2269      * {@hide}
2270      */
readCharSequenceArray()2271     public final CharSequence[] readCharSequenceArray() {
2272         CharSequence[] array = null;
2273 
2274         int length = readInt();
2275         if (length >= 0)
2276         {
2277             array = new CharSequence[length];
2278 
2279             for (int i = 0 ; i < length ; i++)
2280             {
2281                 array[i] = readCharSequence();
2282             }
2283         }
2284 
2285         return array;
2286     }
2287 
2288     /**
2289      * Read and return an ArrayList&lt;CharSequence&gt; object from the parcel.
2290      * {@hide}
2291      */
readCharSequenceList()2292     public final ArrayList<CharSequence> readCharSequenceList() {
2293         ArrayList<CharSequence> array = null;
2294 
2295         int length = readInt();
2296         if (length >= 0) {
2297             array = new ArrayList<CharSequence>(length);
2298 
2299             for (int i = 0 ; i < length ; i++) {
2300                 array.add(readCharSequence());
2301             }
2302         }
2303 
2304         return array;
2305     }
2306 
2307     /**
2308      * Read and return a new ArrayList object from the parcel at the current
2309      * dataPosition().  Returns null if the previously written list object was
2310      * null.  The given class loader will be used to load any enclosed
2311      * Parcelables.
2312      */
readArrayList(ClassLoader loader)2313     public final ArrayList readArrayList(ClassLoader loader) {
2314         int N = readInt();
2315         if (N < 0) {
2316             return null;
2317         }
2318         ArrayList l = new ArrayList(N);
2319         readListInternal(l, N, loader);
2320         return l;
2321     }
2322 
2323     /**
2324      * Read and return a new Object array from the parcel at the current
2325      * dataPosition().  Returns null if the previously written array was
2326      * null.  The given class loader will be used to load any enclosed
2327      * Parcelables.
2328      */
readArray(ClassLoader loader)2329     public final Object[] readArray(ClassLoader loader) {
2330         int N = readInt();
2331         if (N < 0) {
2332             return null;
2333         }
2334         Object[] l = new Object[N];
2335         readArrayInternal(l, N, loader);
2336         return l;
2337     }
2338 
2339     /**
2340      * Read and return a new SparseArray object from the parcel at the current
2341      * dataPosition().  Returns null if the previously written list object was
2342      * null.  The given class loader will be used to load any enclosed
2343      * Parcelables.
2344      */
readSparseArray(ClassLoader loader)2345     public final SparseArray readSparseArray(ClassLoader loader) {
2346         int N = readInt();
2347         if (N < 0) {
2348             return null;
2349         }
2350         SparseArray sa = new SparseArray(N);
2351         readSparseArrayInternal(sa, N, loader);
2352         return sa;
2353     }
2354 
2355     /**
2356      * Read and return a new SparseBooleanArray object from the parcel at the current
2357      * dataPosition().  Returns null if the previously written list object was
2358      * null.
2359      */
readSparseBooleanArray()2360     public final SparseBooleanArray readSparseBooleanArray() {
2361         int N = readInt();
2362         if (N < 0) {
2363             return null;
2364         }
2365         SparseBooleanArray sa = new SparseBooleanArray(N);
2366         readSparseBooleanArrayInternal(sa, N);
2367         return sa;
2368     }
2369 
2370     /**
2371      * Read and return a new SparseIntArray object from the parcel at the current
2372      * dataPosition(). Returns null if the previously written array object was null.
2373      * @hide
2374      */
readSparseIntArray()2375     public final SparseIntArray readSparseIntArray() {
2376         int N = readInt();
2377         if (N < 0) {
2378             return null;
2379         }
2380         SparseIntArray sa = new SparseIntArray(N);
2381         readSparseIntArrayInternal(sa, N);
2382         return sa;
2383     }
2384 
2385     /**
2386      * Read and return a new ArrayList containing a particular object type from
2387      * the parcel that was written with {@link #writeTypedList} at the
2388      * current dataPosition().  Returns null if the
2389      * previously written list object was null.  The list <em>must</em> have
2390      * previously been written via {@link #writeTypedList} with the same object
2391      * type.
2392      *
2393      * @return A newly created ArrayList containing objects with the same data
2394      *         as those that were previously written.
2395      *
2396      * @see #writeTypedList
2397      */
createTypedArrayList(Parcelable.Creator<T> c)2398     public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
2399         int N = readInt();
2400         if (N < 0) {
2401             return null;
2402         }
2403         ArrayList<T> l = new ArrayList<T>(N);
2404         while (N > 0) {
2405             l.add(readTypedObject(c));
2406             N--;
2407         }
2408         return l;
2409     }
2410 
2411     /**
2412      * Read into the given List items containing a particular object type
2413      * that were written with {@link #writeTypedList} at the
2414      * current dataPosition().  The list <em>must</em> have
2415      * previously been written via {@link #writeTypedList} with the same object
2416      * type.
2417      *
2418      * @return A newly created ArrayList containing objects with the same data
2419      *         as those that were previously written.
2420      *
2421      * @see #writeTypedList
2422      */
readTypedList(List<T> list, Parcelable.Creator<T> c)2423     public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
2424         int M = list.size();
2425         int N = readInt();
2426         int i = 0;
2427         for (; i < M && i < N; i++) {
2428             list.set(i, readTypedObject(c));
2429         }
2430         for (; i<N; i++) {
2431             list.add(readTypedObject(c));
2432         }
2433         for (; i<M; i++) {
2434             list.remove(N);
2435         }
2436     }
2437 
2438     /**
2439      * Read and return a new ArrayList containing String objects from
2440      * the parcel that was written with {@link #writeStringList} at the
2441      * current dataPosition().  Returns null if the
2442      * previously written list object was null.
2443      *
2444      * @return A newly created ArrayList containing strings with the same data
2445      *         as those that were previously written.
2446      *
2447      * @see #writeStringList
2448      */
createStringArrayList()2449     public final ArrayList<String> createStringArrayList() {
2450         int N = readInt();
2451         if (N < 0) {
2452             return null;
2453         }
2454         ArrayList<String> l = new ArrayList<String>(N);
2455         while (N > 0) {
2456             l.add(readString());
2457             N--;
2458         }
2459         return l;
2460     }
2461 
2462     /**
2463      * Read and return a new ArrayList containing IBinder objects from
2464      * the parcel that was written with {@link #writeBinderList} at the
2465      * current dataPosition().  Returns null if the
2466      * previously written list object was null.
2467      *
2468      * @return A newly created ArrayList containing strings with the same data
2469      *         as those that were previously written.
2470      *
2471      * @see #writeBinderList
2472      */
createBinderArrayList()2473     public final ArrayList<IBinder> createBinderArrayList() {
2474         int N = readInt();
2475         if (N < 0) {
2476             return null;
2477         }
2478         ArrayList<IBinder> l = new ArrayList<IBinder>(N);
2479         while (N > 0) {
2480             l.add(readStrongBinder());
2481             N--;
2482         }
2483         return l;
2484     }
2485 
2486     /**
2487      * Read into the given List items String objects that were written with
2488      * {@link #writeStringList} at the current dataPosition().
2489      *
2490      * @see #writeStringList
2491      */
readStringList(List<String> list)2492     public final void readStringList(List<String> list) {
2493         int M = list.size();
2494         int N = readInt();
2495         int i = 0;
2496         for (; i < M && i < N; i++) {
2497             list.set(i, readString());
2498         }
2499         for (; i<N; i++) {
2500             list.add(readString());
2501         }
2502         for (; i<M; i++) {
2503             list.remove(N);
2504         }
2505     }
2506 
2507     /**
2508      * Read into the given List items IBinder objects that were written with
2509      * {@link #writeBinderList} at the current dataPosition().
2510      *
2511      * @see #writeBinderList
2512      */
readBinderList(List<IBinder> list)2513     public final void readBinderList(List<IBinder> list) {
2514         int M = list.size();
2515         int N = readInt();
2516         int i = 0;
2517         for (; i < M && i < N; i++) {
2518             list.set(i, readStrongBinder());
2519         }
2520         for (; i<N; i++) {
2521             list.add(readStrongBinder());
2522         }
2523         for (; i<M; i++) {
2524             list.remove(N);
2525         }
2526     }
2527 
2528     /**
2529      * Read the list of {@code Parcelable} objects at the current data position into the
2530      * given {@code list}. The contents of the {@code list} are replaced. If the serialized
2531      * list was {@code null}, {@code list} is cleared.
2532      *
2533      * @see #writeParcelableList(List, int)
2534      * @hide
2535      */
readParcelableList(List<T> list, ClassLoader cl)2536     public final <T extends Parcelable> List<T> readParcelableList(List<T> list, ClassLoader cl) {
2537         final int N = readInt();
2538         if (N == -1) {
2539             list.clear();
2540             return list;
2541         }
2542 
2543         final int M = list.size();
2544         int i = 0;
2545         for (; i < M && i < N; i++) {
2546             list.set(i, (T) readParcelable(cl));
2547         }
2548         for (; i<N; i++) {
2549             list.add((T) readParcelable(cl));
2550         }
2551         for (; i<M; i++) {
2552             list.remove(N);
2553         }
2554         return list;
2555     }
2556 
2557     /**
2558      * Read and return a new array containing a particular object type from
2559      * the parcel at the current dataPosition().  Returns null if the
2560      * previously written array was null.  The array <em>must</em> have
2561      * previously been written via {@link #writeTypedArray} with the same
2562      * object type.
2563      *
2564      * @return A newly created array containing objects with the same data
2565      *         as those that were previously written.
2566      *
2567      * @see #writeTypedArray
2568      */
createTypedArray(Parcelable.Creator<T> c)2569     public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
2570         int N = readInt();
2571         if (N < 0) {
2572             return null;
2573         }
2574         T[] l = c.newArray(N);
2575         for (int i=0; i<N; i++) {
2576             l[i] = readTypedObject(c);
2577         }
2578         return l;
2579     }
2580 
readTypedArray(T[] val, Parcelable.Creator<T> c)2581     public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
2582         int N = readInt();
2583         if (N == val.length) {
2584             for (int i=0; i<N; i++) {
2585                 val[i] = readTypedObject(c);
2586             }
2587         } else {
2588             throw new RuntimeException("bad array lengths");
2589         }
2590     }
2591 
2592     /**
2593      * @deprecated
2594      * @hide
2595      */
2596     @Deprecated
readTypedArray(Parcelable.Creator<T> c)2597     public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
2598         return createTypedArray(c);
2599     }
2600 
2601     /**
2602      * Read and return a typed Parcelable object from a parcel.
2603      * Returns null if the previous written object was null.
2604      * The object <em>must</em> have previous been written via
2605      * {@link #writeTypedObject} with the same object type.
2606      *
2607      * @return A newly created object of the type that was previously
2608      *         written.
2609      *
2610      * @see #writeTypedObject
2611      */
readTypedObject(Parcelable.Creator<T> c)2612     public final <T> T readTypedObject(Parcelable.Creator<T> c) {
2613         if (readInt() != 0) {
2614             return c.createFromParcel(this);
2615         } else {
2616             return null;
2617         }
2618     }
2619 
2620     /**
2621      * Write a heterogeneous array of Parcelable objects into the Parcel.
2622      * Each object in the array is written along with its class name, so
2623      * that the correct class can later be instantiated.  As a result, this
2624      * has significantly more overhead than {@link #writeTypedArray}, but will
2625      * correctly handle an array containing more than one type of object.
2626      *
2627      * @param value The array of objects to be written.
2628      * @param parcelableFlags Contextual flags as per
2629      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2630      *
2631      * @see #writeTypedArray
2632      */
writeParcelableArray(T[] value, int parcelableFlags)2633     public final <T extends Parcelable> void writeParcelableArray(T[] value,
2634             int parcelableFlags) {
2635         if (value != null) {
2636             int N = value.length;
2637             writeInt(N);
2638             for (int i=0; i<N; i++) {
2639                 writeParcelable(value[i], parcelableFlags);
2640             }
2641         } else {
2642             writeInt(-1);
2643         }
2644     }
2645 
2646     /**
2647      * Read a typed object from a parcel.  The given class loader will be
2648      * used to load any enclosed Parcelables.  If it is null, the default class
2649      * loader will be used.
2650      */
readValue(ClassLoader loader)2651     public final Object readValue(ClassLoader loader) {
2652         int type = readInt();
2653 
2654         switch (type) {
2655         case VAL_NULL:
2656             return null;
2657 
2658         case VAL_STRING:
2659             return readString();
2660 
2661         case VAL_INTEGER:
2662             return readInt();
2663 
2664         case VAL_MAP:
2665             return readHashMap(loader);
2666 
2667         case VAL_PARCELABLE:
2668             return readParcelable(loader);
2669 
2670         case VAL_SHORT:
2671             return (short) readInt();
2672 
2673         case VAL_LONG:
2674             return readLong();
2675 
2676         case VAL_FLOAT:
2677             return readFloat();
2678 
2679         case VAL_DOUBLE:
2680             return readDouble();
2681 
2682         case VAL_BOOLEAN:
2683             return readInt() == 1;
2684 
2685         case VAL_CHARSEQUENCE:
2686             return readCharSequence();
2687 
2688         case VAL_LIST:
2689             return readArrayList(loader);
2690 
2691         case VAL_BOOLEANARRAY:
2692             return createBooleanArray();
2693 
2694         case VAL_BYTEARRAY:
2695             return createByteArray();
2696 
2697         case VAL_STRINGARRAY:
2698             return readStringArray();
2699 
2700         case VAL_CHARSEQUENCEARRAY:
2701             return readCharSequenceArray();
2702 
2703         case VAL_IBINDER:
2704             return readStrongBinder();
2705 
2706         case VAL_OBJECTARRAY:
2707             return readArray(loader);
2708 
2709         case VAL_INTARRAY:
2710             return createIntArray();
2711 
2712         case VAL_LONGARRAY:
2713             return createLongArray();
2714 
2715         case VAL_BYTE:
2716             return readByte();
2717 
2718         case VAL_SERIALIZABLE:
2719             return readSerializable(loader);
2720 
2721         case VAL_PARCELABLEARRAY:
2722             return readParcelableArray(loader);
2723 
2724         case VAL_SPARSEARRAY:
2725             return readSparseArray(loader);
2726 
2727         case VAL_SPARSEBOOLEANARRAY:
2728             return readSparseBooleanArray();
2729 
2730         case VAL_BUNDLE:
2731             return readBundle(loader); // loading will be deferred
2732 
2733         case VAL_PERSISTABLEBUNDLE:
2734             return readPersistableBundle(loader);
2735 
2736         case VAL_SIZE:
2737             return readSize();
2738 
2739         case VAL_SIZEF:
2740             return readSizeF();
2741 
2742         case VAL_DOUBLEARRAY:
2743             return createDoubleArray();
2744 
2745         default:
2746             int off = dataPosition() - 4;
2747             throw new RuntimeException(
2748                 "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
2749         }
2750     }
2751 
2752     /**
2753      * Read and return a new Parcelable from the parcel.  The given class loader
2754      * will be used to load any enclosed Parcelables.  If it is null, the default
2755      * class loader will be used.
2756      * @param loader A ClassLoader from which to instantiate the Parcelable
2757      * object, or null for the default class loader.
2758      * @return Returns the newly created Parcelable, or null if a null
2759      * object has been written.
2760      * @throws BadParcelableException Throws BadParcelableException if there
2761      * was an error trying to instantiate the Parcelable.
2762      */
2763     @SuppressWarnings("unchecked")
readParcelable(ClassLoader loader)2764     public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
2765         Parcelable.Creator<?> creator = readParcelableCreator(loader);
2766         if (creator == null) {
2767             return null;
2768         }
2769         if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2770           Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2771               (Parcelable.ClassLoaderCreator<?>) creator;
2772           return (T) classLoaderCreator.createFromParcel(this, loader);
2773         }
2774         return (T) creator.createFromParcel(this);
2775     }
2776 
2777     /** @hide */
2778     @SuppressWarnings("unchecked")
readCreator(Parcelable.Creator<?> creator, ClassLoader loader)2779     public final <T extends Parcelable> T readCreator(Parcelable.Creator<?> creator,
2780             ClassLoader loader) {
2781         if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2782           Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2783               (Parcelable.ClassLoaderCreator<?>) creator;
2784           return (T) classLoaderCreator.createFromParcel(this, loader);
2785         }
2786         return (T) creator.createFromParcel(this);
2787     }
2788 
2789     /** @hide */
readParcelableCreator(ClassLoader loader)2790     public final Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) {
2791         String name = readString();
2792         if (name == null) {
2793             return null;
2794         }
2795         Parcelable.Creator<?> creator;
2796         synchronized (mCreators) {
2797             HashMap<String,Parcelable.Creator<?>> map = mCreators.get(loader);
2798             if (map == null) {
2799                 map = new HashMap<>();
2800                 mCreators.put(loader, map);
2801             }
2802             creator = map.get(name);
2803             if (creator == null) {
2804                 try {
2805                     // If loader == null, explicitly emulate Class.forName(String) "caller
2806                     // classloader" behavior.
2807                     ClassLoader parcelableClassLoader =
2808                             (loader == null ? getClass().getClassLoader() : loader);
2809                     // Avoid initializing the Parcelable class until we know it implements
2810                     // Parcelable and has the necessary CREATOR field. http://b/1171613.
2811                     Class<?> parcelableClass = Class.forName(name, false /* initialize */,
2812                             parcelableClassLoader);
2813                     if (!Parcelable.class.isAssignableFrom(parcelableClass)) {
2814                         throw new BadParcelableException("Parcelable protocol requires subclassing "
2815                                 + "from Parcelable on class " + name);
2816                     }
2817                     Field f = parcelableClass.getField("CREATOR");
2818                     if ((f.getModifiers() & Modifier.STATIC) == 0) {
2819                         throw new BadParcelableException("Parcelable protocol requires "
2820                                 + "the CREATOR object to be static on class " + name);
2821                     }
2822                     Class<?> creatorType = f.getType();
2823                     if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) {
2824                         // Fail before calling Field.get(), not after, to avoid initializing
2825                         // parcelableClass unnecessarily.
2826                         throw new BadParcelableException("Parcelable protocol requires a "
2827                                 + "Parcelable.Creator object called "
2828                                 + "CREATOR on class " + name);
2829                     }
2830                     creator = (Parcelable.Creator<?>) f.get(null);
2831                 }
2832                 catch (IllegalAccessException e) {
2833                     Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
2834                     throw new BadParcelableException(
2835                             "IllegalAccessException when unmarshalling: " + name);
2836                 }
2837                 catch (ClassNotFoundException e) {
2838                     Log.e(TAG, "Class not found when unmarshalling: " + name, e);
2839                     throw new BadParcelableException(
2840                             "ClassNotFoundException when unmarshalling: " + name);
2841                 }
2842                 catch (NoSuchFieldException e) {
2843                     throw new BadParcelableException("Parcelable protocol requires a "
2844                             + "Parcelable.Creator object called "
2845                             + "CREATOR on class " + name);
2846                 }
2847                 if (creator == null) {
2848                     throw new BadParcelableException("Parcelable protocol requires a "
2849                             + "non-null Parcelable.Creator object called "
2850                             + "CREATOR on class " + name);
2851                 }
2852 
2853                 map.put(name, creator);
2854             }
2855         }
2856 
2857         return creator;
2858     }
2859 
2860     /**
2861      * Read and return a new Parcelable array from the parcel.
2862      * The given class loader will be used to load any enclosed
2863      * Parcelables.
2864      * @return the Parcelable array, or null if the array is null
2865      */
readParcelableArray(ClassLoader loader)2866     public final Parcelable[] readParcelableArray(ClassLoader loader) {
2867         int N = readInt();
2868         if (N < 0) {
2869             return null;
2870         }
2871         Parcelable[] p = new Parcelable[N];
2872         for (int i = 0; i < N; i++) {
2873             p[i] = readParcelable(loader);
2874         }
2875         return p;
2876     }
2877 
2878     /** @hide */
readParcelableArray(ClassLoader loader, Class<T> clazz)2879     public final <T extends Parcelable> T[] readParcelableArray(ClassLoader loader,
2880             Class<T> clazz) {
2881         int N = readInt();
2882         if (N < 0) {
2883             return null;
2884         }
2885         T[] p = (T[]) Array.newInstance(clazz, N);
2886         for (int i = 0; i < N; i++) {
2887             p[i] = readParcelable(loader);
2888         }
2889         return p;
2890     }
2891 
2892     /**
2893      * Read and return a new Serializable object from the parcel.
2894      * @return the Serializable object, or null if the Serializable name
2895      * wasn't found in the parcel.
2896      */
readSerializable()2897     public final Serializable readSerializable() {
2898         return readSerializable(null);
2899     }
2900 
readSerializable(final ClassLoader loader)2901     private final Serializable readSerializable(final ClassLoader loader) {
2902         String name = readString();
2903         if (name == null) {
2904             // For some reason we were unable to read the name of the Serializable (either there
2905             // is nothing left in the Parcel to read, or the next value wasn't a String), so
2906             // return null, which indicates that the name wasn't found in the parcel.
2907             return null;
2908         }
2909 
2910         byte[] serializedData = createByteArray();
2911         ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
2912         try {
2913             ObjectInputStream ois = new ObjectInputStream(bais) {
2914                 @Override
2915                 protected Class<?> resolveClass(ObjectStreamClass osClass)
2916                         throws IOException, ClassNotFoundException {
2917                     // try the custom classloader if provided
2918                     if (loader != null) {
2919                         Class<?> c = Class.forName(osClass.getName(), false, loader);
2920                         if (c != null) {
2921                             return c;
2922                         }
2923                     }
2924                     return super.resolveClass(osClass);
2925                 }
2926             };
2927             return (Serializable) ois.readObject();
2928         } catch (IOException ioe) {
2929             throw new RuntimeException("Parcelable encountered " +
2930                 "IOException reading a Serializable object (name = " + name +
2931                 ")", ioe);
2932         } catch (ClassNotFoundException cnfe) {
2933             throw new RuntimeException("Parcelable encountered " +
2934                 "ClassNotFoundException reading a Serializable object (name = "
2935                 + name + ")", cnfe);
2936         }
2937     }
2938 
2939     // Cache of previously looked up CREATOR.createFromParcel() methods for
2940     // particular classes.  Keys are the names of the classes, values are
2941     // Method objects.
2942     private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator<?>>>
2943         mCreators = new HashMap<>();
2944 
2945     /** @hide for internal use only. */
obtain(int obj)2946     static protected final Parcel obtain(int obj) {
2947         throw new UnsupportedOperationException();
2948     }
2949 
2950     /** @hide */
obtain(long obj)2951     static protected final Parcel obtain(long obj) {
2952         final Parcel[] pool = sHolderPool;
2953         synchronized (pool) {
2954             Parcel p;
2955             for (int i=0; i<POOL_SIZE; i++) {
2956                 p = pool[i];
2957                 if (p != null) {
2958                     pool[i] = null;
2959                     if (DEBUG_RECYCLE) {
2960                         p.mStack = new RuntimeException();
2961                     }
2962                     p.init(obj);
2963                     return p;
2964                 }
2965             }
2966         }
2967         return new Parcel(obj);
2968     }
2969 
Parcel(long nativePtr)2970     private Parcel(long nativePtr) {
2971         if (DEBUG_RECYCLE) {
2972             mStack = new RuntimeException();
2973         }
2974         //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
2975         init(nativePtr);
2976     }
2977 
init(long nativePtr)2978     private void init(long nativePtr) {
2979         if (nativePtr != 0) {
2980             mNativePtr = nativePtr;
2981             mOwnsNativeParcelObject = false;
2982         } else {
2983             mNativePtr = nativeCreate();
2984             mOwnsNativeParcelObject = true;
2985         }
2986     }
2987 
freeBuffer()2988     private void freeBuffer() {
2989         if (mOwnsNativeParcelObject) {
2990             updateNativeSize(nativeFreeBuffer(mNativePtr));
2991         }
2992         mReadWriteHelper = ReadWriteHelper.DEFAULT;
2993     }
2994 
destroy()2995     private void destroy() {
2996         if (mNativePtr != 0) {
2997             if (mOwnsNativeParcelObject) {
2998                 nativeDestroy(mNativePtr);
2999                 updateNativeSize(0);
3000             }
3001             mNativePtr = 0;
3002         }
3003         mReadWriteHelper = null;
3004     }
3005 
3006     @Override
finalize()3007     protected void finalize() throws Throwable {
3008         if (DEBUG_RECYCLE) {
3009             if (mStack != null) {
3010                 Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
3011             }
3012         }
3013         destroy();
3014     }
3015 
readMapInternal(Map outVal, int N, ClassLoader loader)3016     /* package */ void readMapInternal(Map outVal, int N,
3017         ClassLoader loader) {
3018         while (N > 0) {
3019             Object key = readValue(loader);
3020             Object value = readValue(loader);
3021             outVal.put(key, value);
3022             N--;
3023         }
3024     }
3025 
readArrayMapInternal(ArrayMap outVal, int N, ClassLoader loader)3026     /* package */ void readArrayMapInternal(ArrayMap outVal, int N,
3027         ClassLoader loader) {
3028         if (DEBUG_ARRAY_MAP) {
3029             RuntimeException here =  new RuntimeException("here");
3030             here.fillInStackTrace();
3031             Log.d(TAG, "Reading " + N + " ArrayMap entries", here);
3032         }
3033         int startPos;
3034         while (N > 0) {
3035             if (DEBUG_ARRAY_MAP) startPos = dataPosition();
3036             String key = readString();
3037             Object value = readValue(loader);
3038             if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Read #" + (N-1) + " "
3039                     + (dataPosition()-startPos) + " bytes: key=0x"
3040                     + Integer.toHexString((key != null ? key.hashCode() : 0)) + " " + key);
3041             outVal.append(key, value);
3042             N--;
3043         }
3044         outVal.validate();
3045     }
3046 
readArrayMapSafelyInternal(ArrayMap outVal, int N, ClassLoader loader)3047     /* package */ void readArrayMapSafelyInternal(ArrayMap outVal, int N,
3048         ClassLoader loader) {
3049         if (DEBUG_ARRAY_MAP) {
3050             RuntimeException here =  new RuntimeException("here");
3051             here.fillInStackTrace();
3052             Log.d(TAG, "Reading safely " + N + " ArrayMap entries", here);
3053         }
3054         while (N > 0) {
3055             String key = readString();
3056             if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Read safe #" + (N-1) + ": key=0x"
3057                     + (key != null ? key.hashCode() : 0) + " " + key);
3058             Object value = readValue(loader);
3059             outVal.put(key, value);
3060             N--;
3061         }
3062     }
3063 
3064     /**
3065      * @hide For testing only.
3066      */
readArrayMap(ArrayMap outVal, ClassLoader loader)3067     public void readArrayMap(ArrayMap outVal, ClassLoader loader) {
3068         final int N = readInt();
3069         if (N < 0) {
3070             return;
3071         }
3072         readArrayMapInternal(outVal, N, loader);
3073     }
3074 
3075     /**
3076      * Reads an array set.
3077      *
3078      * @param loader The class loader to use.
3079      *
3080      * @hide
3081      */
readArraySet(ClassLoader loader)3082     public @Nullable ArraySet<? extends Object> readArraySet(ClassLoader loader) {
3083         final int size = readInt();
3084         if (size < 0) {
3085             return null;
3086         }
3087         ArraySet<Object> result = new ArraySet<>(size);
3088         for (int i = 0; i < size; i++) {
3089             Object value = readValue(loader);
3090             result.append(value);
3091         }
3092         return result;
3093     }
3094 
readListInternal(List outVal, int N, ClassLoader loader)3095     private void readListInternal(List outVal, int N,
3096         ClassLoader loader) {
3097         while (N > 0) {
3098             Object value = readValue(loader);
3099             //Log.d(TAG, "Unmarshalling value=" + value);
3100             outVal.add(value);
3101             N--;
3102         }
3103     }
3104 
readArrayInternal(Object[] outVal, int N, ClassLoader loader)3105     private void readArrayInternal(Object[] outVal, int N,
3106         ClassLoader loader) {
3107         for (int i = 0; i < N; i++) {
3108             Object value = readValue(loader);
3109             //Log.d(TAG, "Unmarshalling value=" + value);
3110             outVal[i] = value;
3111         }
3112     }
3113 
readSparseArrayInternal(SparseArray outVal, int N, ClassLoader loader)3114     private void readSparseArrayInternal(SparseArray outVal, int N,
3115         ClassLoader loader) {
3116         while (N > 0) {
3117             int key = readInt();
3118             Object value = readValue(loader);
3119             //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3120             outVal.append(key, value);
3121             N--;
3122         }
3123     }
3124 
3125 
readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N)3126     private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
3127         while (N > 0) {
3128             int key = readInt();
3129             boolean value = this.readByte() == 1;
3130             //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3131             outVal.append(key, value);
3132             N--;
3133         }
3134     }
3135 
readSparseIntArrayInternal(SparseIntArray outVal, int N)3136     private void readSparseIntArrayInternal(SparseIntArray outVal, int N) {
3137         while (N > 0) {
3138             int key = readInt();
3139             int value = readInt();
3140             outVal.append(key, value);
3141             N--;
3142         }
3143     }
3144 
3145     /**
3146      * @hide For testing
3147      */
getBlobAshmemSize()3148     public long getBlobAshmemSize() {
3149         return nativeGetBlobAshmemSize(mNativePtr);
3150     }
3151 }
3152