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