OSDN Git Service

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