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