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