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