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