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