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