Parcel.java revision 9c3e74f1f77d3b29ad47d2c74b0a0061e67c76f1
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            writeString(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     * @hide For testing only.
643     */
644    public void writeArrayMap(ArrayMap<String, Object> val) {
645        writeArrayMapInternal(val);
646    }
647
648    /**
649     * Flatten a Bundle into the parcel at the current dataPosition(),
650     * growing dataCapacity() if needed.
651     */
652    public final void writeBundle(Bundle val) {
653        if (val == null) {
654            writeInt(-1);
655            return;
656        }
657
658        val.writeToParcel(this, 0);
659    }
660
661    /**
662     * Flatten a PersistableBundle into the parcel at the current dataPosition(),
663     * growing dataCapacity() if needed.
664     */
665    public final void writePersistableBundle(PersistableBundle val) {
666        if (val == null) {
667            writeInt(-1);
668            return;
669        }
670
671        val.writeToParcel(this, 0);
672    }
673
674    /**
675     * Flatten a List into the parcel at the current dataPosition(), growing
676     * dataCapacity() if needed.  The List values are written using
677     * {@link #writeValue} and must follow the specification there.
678     */
679    public final void writeList(List val) {
680        if (val == null) {
681            writeInt(-1);
682            return;
683        }
684        int N = val.size();
685        int i=0;
686        writeInt(N);
687        while (i < N) {
688            writeValue(val.get(i));
689            i++;
690        }
691    }
692
693    /**
694     * Flatten an Object array into the parcel at the current dataPosition(),
695     * growing dataCapacity() if needed.  The array values are written using
696     * {@link #writeValue} and must follow the specification there.
697     */
698    public final void writeArray(Object[] val) {
699        if (val == null) {
700            writeInt(-1);
701            return;
702        }
703        int N = val.length;
704        int i=0;
705        writeInt(N);
706        while (i < N) {
707            writeValue(val[i]);
708            i++;
709        }
710    }
711
712    /**
713     * Flatten a generic SparseArray into the parcel at the current
714     * dataPosition(), growing dataCapacity() if needed.  The SparseArray
715     * values are written using {@link #writeValue} and must follow the
716     * specification there.
717     */
718    public final void writeSparseArray(SparseArray<Object> val) {
719        if (val == null) {
720            writeInt(-1);
721            return;
722        }
723        int N = val.size();
724        writeInt(N);
725        int i=0;
726        while (i < N) {
727            writeInt(val.keyAt(i));
728            writeValue(val.valueAt(i));
729            i++;
730        }
731    }
732
733    public final void writeSparseBooleanArray(SparseBooleanArray val) {
734        if (val == null) {
735            writeInt(-1);
736            return;
737        }
738        int N = val.size();
739        writeInt(N);
740        int i=0;
741        while (i < N) {
742            writeInt(val.keyAt(i));
743            writeByte((byte)(val.valueAt(i) ? 1 : 0));
744            i++;
745        }
746    }
747
748    public final void writeBooleanArray(boolean[] val) {
749        if (val != null) {
750            int N = val.length;
751            writeInt(N);
752            for (int i=0; i<N; i++) {
753                writeInt(val[i] ? 1 : 0);
754            }
755        } else {
756            writeInt(-1);
757        }
758    }
759
760    public final boolean[] createBooleanArray() {
761        int N = readInt();
762        // >>2 as a fast divide-by-4 works in the create*Array() functions
763        // because dataAvail() will never return a negative number.  4 is
764        // the size of a stored boolean in the stream.
765        if (N >= 0 && N <= (dataAvail() >> 2)) {
766            boolean[] val = new boolean[N];
767            for (int i=0; i<N; i++) {
768                val[i] = readInt() != 0;
769            }
770            return val;
771        } else {
772            return null;
773        }
774    }
775
776    public final void readBooleanArray(boolean[] val) {
777        int N = readInt();
778        if (N == val.length) {
779            for (int i=0; i<N; i++) {
780                val[i] = readInt() != 0;
781            }
782        } else {
783            throw new RuntimeException("bad array lengths");
784        }
785    }
786
787    public final void writeCharArray(char[] val) {
788        if (val != null) {
789            int N = val.length;
790            writeInt(N);
791            for (int i=0; i<N; i++) {
792                writeInt((int)val[i]);
793            }
794        } else {
795            writeInt(-1);
796        }
797    }
798
799    public final char[] createCharArray() {
800        int N = readInt();
801        if (N >= 0 && N <= (dataAvail() >> 2)) {
802            char[] val = new char[N];
803            for (int i=0; i<N; i++) {
804                val[i] = (char)readInt();
805            }
806            return val;
807        } else {
808            return null;
809        }
810    }
811
812    public final void readCharArray(char[] val) {
813        int N = readInt();
814        if (N == val.length) {
815            for (int i=0; i<N; i++) {
816                val[i] = (char)readInt();
817            }
818        } else {
819            throw new RuntimeException("bad array lengths");
820        }
821    }
822
823    public final void writeIntArray(int[] val) {
824        if (val != null) {
825            int N = val.length;
826            writeInt(N);
827            for (int i=0; i<N; i++) {
828                writeInt(val[i]);
829            }
830        } else {
831            writeInt(-1);
832        }
833    }
834
835    public final int[] createIntArray() {
836        int N = readInt();
837        if (N >= 0 && N <= (dataAvail() >> 2)) {
838            int[] val = new int[N];
839            for (int i=0; i<N; i++) {
840                val[i] = readInt();
841            }
842            return val;
843        } else {
844            return null;
845        }
846    }
847
848    public final void readIntArray(int[] val) {
849        int N = readInt();
850        if (N == val.length) {
851            for (int i=0; i<N; i++) {
852                val[i] = readInt();
853            }
854        } else {
855            throw new RuntimeException("bad array lengths");
856        }
857    }
858
859    public final void writeLongArray(long[] val) {
860        if (val != null) {
861            int N = val.length;
862            writeInt(N);
863            for (int i=0; i<N; i++) {
864                writeLong(val[i]);
865            }
866        } else {
867            writeInt(-1);
868        }
869    }
870
871    public final long[] createLongArray() {
872        int N = readInt();
873        // >>3 because stored longs are 64 bits
874        if (N >= 0 && N <= (dataAvail() >> 3)) {
875            long[] val = new long[N];
876            for (int i=0; i<N; i++) {
877                val[i] = readLong();
878            }
879            return val;
880        } else {
881            return null;
882        }
883    }
884
885    public final void readLongArray(long[] val) {
886        int N = readInt();
887        if (N == val.length) {
888            for (int i=0; i<N; i++) {
889                val[i] = readLong();
890            }
891        } else {
892            throw new RuntimeException("bad array lengths");
893        }
894    }
895
896    public final void writeFloatArray(float[] val) {
897        if (val != null) {
898            int N = val.length;
899            writeInt(N);
900            for (int i=0; i<N; i++) {
901                writeFloat(val[i]);
902            }
903        } else {
904            writeInt(-1);
905        }
906    }
907
908    public final float[] createFloatArray() {
909        int N = readInt();
910        // >>2 because stored floats are 4 bytes
911        if (N >= 0 && N <= (dataAvail() >> 2)) {
912            float[] val = new float[N];
913            for (int i=0; i<N; i++) {
914                val[i] = readFloat();
915            }
916            return val;
917        } else {
918            return null;
919        }
920    }
921
922    public final void readFloatArray(float[] val) {
923        int N = readInt();
924        if (N == val.length) {
925            for (int i=0; i<N; i++) {
926                val[i] = readFloat();
927            }
928        } else {
929            throw new RuntimeException("bad array lengths");
930        }
931    }
932
933    public final void writeDoubleArray(double[] val) {
934        if (val != null) {
935            int N = val.length;
936            writeInt(N);
937            for (int i=0; i<N; i++) {
938                writeDouble(val[i]);
939            }
940        } else {
941            writeInt(-1);
942        }
943    }
944
945    public final double[] createDoubleArray() {
946        int N = readInt();
947        // >>3 because stored doubles are 8 bytes
948        if (N >= 0 && N <= (dataAvail() >> 3)) {
949            double[] val = new double[N];
950            for (int i=0; i<N; i++) {
951                val[i] = readDouble();
952            }
953            return val;
954        } else {
955            return null;
956        }
957    }
958
959    public final void readDoubleArray(double[] val) {
960        int N = readInt();
961        if (N == val.length) {
962            for (int i=0; i<N; i++) {
963                val[i] = readDouble();
964            }
965        } else {
966            throw new RuntimeException("bad array lengths");
967        }
968    }
969
970    public final void writeStringArray(String[] val) {
971        if (val != null) {
972            int N = val.length;
973            writeInt(N);
974            for (int i=0; i<N; i++) {
975                writeString(val[i]);
976            }
977        } else {
978            writeInt(-1);
979        }
980    }
981
982    public final String[] createStringArray() {
983        int N = readInt();
984        if (N >= 0) {
985            String[] val = new String[N];
986            for (int i=0; i<N; i++) {
987                val[i] = readString();
988            }
989            return val;
990        } else {
991            return null;
992        }
993    }
994
995    public final void readStringArray(String[] val) {
996        int N = readInt();
997        if (N == val.length) {
998            for (int i=0; i<N; i++) {
999                val[i] = readString();
1000            }
1001        } else {
1002            throw new RuntimeException("bad array lengths");
1003        }
1004    }
1005
1006    public final void writeBinderArray(IBinder[] val) {
1007        if (val != null) {
1008            int N = val.length;
1009            writeInt(N);
1010            for (int i=0; i<N; i++) {
1011                writeStrongBinder(val[i]);
1012            }
1013        } else {
1014            writeInt(-1);
1015        }
1016    }
1017
1018    /**
1019     * @hide
1020     */
1021    public final void writeCharSequenceArray(CharSequence[] val) {
1022        if (val != null) {
1023            int N = val.length;
1024            writeInt(N);
1025            for (int i=0; i<N; i++) {
1026                writeCharSequence(val[i]);
1027            }
1028        } else {
1029            writeInt(-1);
1030        }
1031    }
1032
1033    public final IBinder[] createBinderArray() {
1034        int N = readInt();
1035        if (N >= 0) {
1036            IBinder[] val = new IBinder[N];
1037            for (int i=0; i<N; i++) {
1038                val[i] = readStrongBinder();
1039            }
1040            return val;
1041        } else {
1042            return null;
1043        }
1044    }
1045
1046    public final void readBinderArray(IBinder[] val) {
1047        int N = readInt();
1048        if (N == val.length) {
1049            for (int i=0; i<N; i++) {
1050                val[i] = readStrongBinder();
1051            }
1052        } else {
1053            throw new RuntimeException("bad array lengths");
1054        }
1055    }
1056
1057    /**
1058     * Flatten a List containing a particular object type into the parcel, at
1059     * the current dataPosition() and growing dataCapacity() if needed.  The
1060     * type of the objects in the list must be one that implements Parcelable.
1061     * Unlike the generic writeList() method, however, only the raw data of the
1062     * objects is written and not their type, so you must use the corresponding
1063     * readTypedList() to unmarshall them.
1064     *
1065     * @param val The list of objects to be written.
1066     *
1067     * @see #createTypedArrayList
1068     * @see #readTypedList
1069     * @see Parcelable
1070     */
1071    public final <T extends Parcelable> void writeTypedList(List<T> val) {
1072        if (val == null) {
1073            writeInt(-1);
1074            return;
1075        }
1076        int N = val.size();
1077        int i=0;
1078        writeInt(N);
1079        while (i < N) {
1080            T item = val.get(i);
1081            if (item != null) {
1082                writeInt(1);
1083                item.writeToParcel(this, 0);
1084            } else {
1085                writeInt(0);
1086            }
1087            i++;
1088        }
1089    }
1090
1091    /**
1092     * Flatten a List containing String objects into the parcel, at
1093     * the current dataPosition() and growing dataCapacity() if needed.  They
1094     * can later be retrieved with {@link #createStringArrayList} or
1095     * {@link #readStringList}.
1096     *
1097     * @param val The list of strings to be written.
1098     *
1099     * @see #createStringArrayList
1100     * @see #readStringList
1101     */
1102    public final void writeStringList(List<String> val) {
1103        if (val == null) {
1104            writeInt(-1);
1105            return;
1106        }
1107        int N = val.size();
1108        int i=0;
1109        writeInt(N);
1110        while (i < N) {
1111            writeString(val.get(i));
1112            i++;
1113        }
1114    }
1115
1116    /**
1117     * Flatten a List containing IBinder objects into the parcel, at
1118     * the current dataPosition() and growing dataCapacity() if needed.  They
1119     * can later be retrieved with {@link #createBinderArrayList} or
1120     * {@link #readBinderList}.
1121     *
1122     * @param val The list of strings to be written.
1123     *
1124     * @see #createBinderArrayList
1125     * @see #readBinderList
1126     */
1127    public final void writeBinderList(List<IBinder> val) {
1128        if (val == null) {
1129            writeInt(-1);
1130            return;
1131        }
1132        int N = val.size();
1133        int i=0;
1134        writeInt(N);
1135        while (i < N) {
1136            writeStrongBinder(val.get(i));
1137            i++;
1138        }
1139    }
1140
1141    /**
1142     * Flatten a heterogeneous array containing a particular object type into
1143     * the parcel, at
1144     * the current dataPosition() and growing dataCapacity() if needed.  The
1145     * type of the objects in the array must be one that implements Parcelable.
1146     * Unlike the {@link #writeParcelableArray} method, however, only the
1147     * raw data of the objects is written and not their type, so you must use
1148     * {@link #readTypedArray} with the correct corresponding
1149     * {@link Parcelable.Creator} implementation to unmarshall them.
1150     *
1151     * @param val The array of objects to be written.
1152     * @param parcelableFlags Contextual flags as per
1153     * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1154     *
1155     * @see #readTypedArray
1156     * @see #writeParcelableArray
1157     * @see Parcelable.Creator
1158     */
1159    public final <T extends Parcelable> void writeTypedArray(T[] val,
1160            int parcelableFlags) {
1161        if (val != null) {
1162            int N = val.length;
1163            writeInt(N);
1164            for (int i=0; i<N; i++) {
1165                T item = val[i];
1166                if (item != null) {
1167                    writeInt(1);
1168                    item.writeToParcel(this, parcelableFlags);
1169                } else {
1170                    writeInt(0);
1171                }
1172            }
1173        } else {
1174            writeInt(-1);
1175        }
1176    }
1177
1178    /**
1179     * Flatten a generic object in to a parcel.  The given Object value may
1180     * currently be one of the following types:
1181     *
1182     * <ul>
1183     * <li> null
1184     * <li> String
1185     * <li> Byte
1186     * <li> Short
1187     * <li> Integer
1188     * <li> Long
1189     * <li> Float
1190     * <li> Double
1191     * <li> Boolean
1192     * <li> String[]
1193     * <li> boolean[]
1194     * <li> byte[]
1195     * <li> int[]
1196     * <li> long[]
1197     * <li> Object[] (supporting objects of the same type defined here).
1198     * <li> {@link Bundle}
1199     * <li> Map (as supported by {@link #writeMap}).
1200     * <li> Any object that implements the {@link Parcelable} protocol.
1201     * <li> Parcelable[]
1202     * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
1203     * <li> List (as supported by {@link #writeList}).
1204     * <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}).
1205     * <li> {@link IBinder}
1206     * <li> Any object that implements Serializable (but see
1207     *      {@link #writeSerializable} for caveats).  Note that all of the
1208     *      previous types have relatively efficient implementations for
1209     *      writing to a Parcel; having to rely on the generic serialization
1210     *      approach is much less efficient and should be avoided whenever
1211     *      possible.
1212     * </ul>
1213     *
1214     * <p class="caution">{@link Parcelable} objects are written with
1215     * {@link Parcelable#writeToParcel} using contextual flags of 0.  When
1216     * serializing objects containing {@link ParcelFileDescriptor}s,
1217     * this may result in file descriptor leaks when they are returned from
1218     * Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE}
1219     * should be used).</p>
1220     */
1221    public final void writeValue(Object v) {
1222        if (v == null) {
1223            writeInt(VAL_NULL);
1224        } else if (v instanceof String) {
1225            writeInt(VAL_STRING);
1226            writeString((String) v);
1227        } else if (v instanceof Integer) {
1228            writeInt(VAL_INTEGER);
1229            writeInt((Integer) v);
1230        } else if (v instanceof Map) {
1231            writeInt(VAL_MAP);
1232            writeMap((Map) v);
1233        } else if (v instanceof Bundle) {
1234            // Must be before Parcelable
1235            writeInt(VAL_BUNDLE);
1236            writeBundle((Bundle) v);
1237        } else if (v instanceof Parcelable) {
1238            writeInt(VAL_PARCELABLE);
1239            writeParcelable((Parcelable) v, 0);
1240        } else if (v instanceof Short) {
1241            writeInt(VAL_SHORT);
1242            writeInt(((Short) v).intValue());
1243        } else if (v instanceof Long) {
1244            writeInt(VAL_LONG);
1245            writeLong((Long) v);
1246        } else if (v instanceof Float) {
1247            writeInt(VAL_FLOAT);
1248            writeFloat((Float) v);
1249        } else if (v instanceof Double) {
1250            writeInt(VAL_DOUBLE);
1251            writeDouble((Double) v);
1252        } else if (v instanceof Boolean) {
1253            writeInt(VAL_BOOLEAN);
1254            writeInt((Boolean) v ? 1 : 0);
1255        } else if (v instanceof CharSequence) {
1256            // Must be after String
1257            writeInt(VAL_CHARSEQUENCE);
1258            writeCharSequence((CharSequence) v);
1259        } else if (v instanceof List) {
1260            writeInt(VAL_LIST);
1261            writeList((List) v);
1262        } else if (v instanceof SparseArray) {
1263            writeInt(VAL_SPARSEARRAY);
1264            writeSparseArray((SparseArray) v);
1265        } else if (v instanceof boolean[]) {
1266            writeInt(VAL_BOOLEANARRAY);
1267            writeBooleanArray((boolean[]) v);
1268        } else if (v instanceof byte[]) {
1269            writeInt(VAL_BYTEARRAY);
1270            writeByteArray((byte[]) v);
1271        } else if (v instanceof String[]) {
1272            writeInt(VAL_STRINGARRAY);
1273            writeStringArray((String[]) v);
1274        } else if (v instanceof CharSequence[]) {
1275            // Must be after String[] and before Object[]
1276            writeInt(VAL_CHARSEQUENCEARRAY);
1277            writeCharSequenceArray((CharSequence[]) v);
1278        } else if (v instanceof IBinder) {
1279            writeInt(VAL_IBINDER);
1280            writeStrongBinder((IBinder) v);
1281        } else if (v instanceof Parcelable[]) {
1282            writeInt(VAL_PARCELABLEARRAY);
1283            writeParcelableArray((Parcelable[]) v, 0);
1284        } else if (v instanceof int[]) {
1285            writeInt(VAL_INTARRAY);
1286            writeIntArray((int[]) v);
1287        } else if (v instanceof long[]) {
1288            writeInt(VAL_LONGARRAY);
1289            writeLongArray((long[]) v);
1290        } else if (v instanceof Byte) {
1291            writeInt(VAL_BYTE);
1292            writeInt((Byte) v);
1293        } else if (v instanceof PersistableBundle) {
1294            writeInt(VAL_PERSISTABLEBUNDLE);
1295            writePersistableBundle((PersistableBundle) v);
1296        } else {
1297            Class<?> clazz = v.getClass();
1298            if (clazz.isArray() && clazz.getComponentType() == Object.class) {
1299                // Only pure Object[] are written here, Other arrays of non-primitive types are
1300                // handled by serialization as this does not record the component type.
1301                writeInt(VAL_OBJECTARRAY);
1302                writeArray((Object[]) v);
1303            } else if (v instanceof Serializable) {
1304                // Must be last
1305                writeInt(VAL_SERIALIZABLE);
1306                writeSerializable((Serializable) v);
1307            } else {
1308                throw new RuntimeException("Parcel: unable to marshal value " + v);
1309            }
1310        }
1311    }
1312
1313    /**
1314     * Flatten the name of the class of the Parcelable and its contents
1315     * into the parcel.
1316     *
1317     * @param p The Parcelable object to be written.
1318     * @param parcelableFlags Contextual flags as per
1319     * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1320     */
1321    public final void writeParcelable(Parcelable p, int parcelableFlags) {
1322        if (p == null) {
1323            writeString(null);
1324            return;
1325        }
1326        String name = p.getClass().getName();
1327        writeString(name);
1328        p.writeToParcel(this, parcelableFlags);
1329    }
1330
1331    /** @hide */
1332    public final void writeParcelableCreator(Parcelable p) {
1333        String name = p.getClass().getName();
1334        writeString(name);
1335    }
1336
1337    /**
1338     * Write a generic serializable object in to a Parcel.  It is strongly
1339     * recommended that this method be avoided, since the serialization
1340     * overhead is extremely large, and this approach will be much slower than
1341     * using the other approaches to writing data in to a Parcel.
1342     */
1343    public final void writeSerializable(Serializable s) {
1344        if (s == null) {
1345            writeString(null);
1346            return;
1347        }
1348        String name = s.getClass().getName();
1349        writeString(name);
1350
1351        ByteArrayOutputStream baos = new ByteArrayOutputStream();
1352        try {
1353            ObjectOutputStream oos = new ObjectOutputStream(baos);
1354            oos.writeObject(s);
1355            oos.close();
1356
1357            writeByteArray(baos.toByteArray());
1358        } catch (IOException ioe) {
1359            throw new RuntimeException("Parcelable encountered " +
1360                "IOException writing serializable object (name = " + name +
1361                ")", ioe);
1362        }
1363    }
1364
1365    /**
1366     * Special function for writing an exception result at the header of
1367     * a parcel, to be used when returning an exception from a transaction.
1368     * Note that this currently only supports a few exception types; any other
1369     * exception will be re-thrown by this function as a RuntimeException
1370     * (to be caught by the system's last-resort exception handling when
1371     * dispatching a transaction).
1372     *
1373     * <p>The supported exception types are:
1374     * <ul>
1375     * <li>{@link BadParcelableException}
1376     * <li>{@link IllegalArgumentException}
1377     * <li>{@link IllegalStateException}
1378     * <li>{@link NullPointerException}
1379     * <li>{@link SecurityException}
1380     * <li>{@link NetworkOnMainThreadException}
1381     * </ul>
1382     *
1383     * @param e The Exception to be written.
1384     *
1385     * @see #writeNoException
1386     * @see #readException
1387     */
1388    public final void writeException(Exception e) {
1389        int code = 0;
1390        if (e instanceof SecurityException) {
1391            code = EX_SECURITY;
1392        } else if (e instanceof BadParcelableException) {
1393            code = EX_BAD_PARCELABLE;
1394        } else if (e instanceof IllegalArgumentException) {
1395            code = EX_ILLEGAL_ARGUMENT;
1396        } else if (e instanceof NullPointerException) {
1397            code = EX_NULL_POINTER;
1398        } else if (e instanceof IllegalStateException) {
1399            code = EX_ILLEGAL_STATE;
1400        } else if (e instanceof NetworkOnMainThreadException) {
1401            code = EX_NETWORK_MAIN_THREAD;
1402        }
1403        writeInt(code);
1404        StrictMode.clearGatheredViolations();
1405        if (code == 0) {
1406            if (e instanceof RuntimeException) {
1407                throw (RuntimeException) e;
1408            }
1409            throw new RuntimeException(e);
1410        }
1411        writeString(e.getMessage());
1412    }
1413
1414    /**
1415     * Special function for writing information at the front of the Parcel
1416     * indicating that no exception occurred.
1417     *
1418     * @see #writeException
1419     * @see #readException
1420     */
1421    public final void writeNoException() {
1422        // Despite the name of this function ("write no exception"),
1423        // it should instead be thought of as "write the RPC response
1424        // header", but because this function name is written out by
1425        // the AIDL compiler, we're not going to rename it.
1426        //
1427        // The response header, in the non-exception case (see also
1428        // writeException above, also called by the AIDL compiler), is
1429        // either a 0 (the default case), or EX_HAS_REPLY_HEADER if
1430        // StrictMode has gathered up violations that have occurred
1431        // during a Binder call, in which case we write out the number
1432        // of violations and their details, serialized, before the
1433        // actual RPC respons data.  The receiving end of this is
1434        // readException(), below.
1435        if (StrictMode.hasGatheredViolations()) {
1436            writeInt(EX_HAS_REPLY_HEADER);
1437            final int sizePosition = dataPosition();
1438            writeInt(0);  // total size of fat header, to be filled in later
1439            StrictMode.writeGatheredViolationsToParcel(this);
1440            final int payloadPosition = dataPosition();
1441            setDataPosition(sizePosition);
1442            writeInt(payloadPosition - sizePosition);  // header size
1443            setDataPosition(payloadPosition);
1444        } else {
1445            writeInt(0);
1446        }
1447    }
1448
1449    /**
1450     * Special function for reading an exception result from the header of
1451     * a parcel, to be used after receiving the result of a transaction.  This
1452     * will throw the exception for you if it had been written to the Parcel,
1453     * otherwise return and let you read the normal result data from the Parcel.
1454     *
1455     * @see #writeException
1456     * @see #writeNoException
1457     */
1458    public final void readException() {
1459        int code = readExceptionCode();
1460        if (code != 0) {
1461            String msg = readString();
1462            readException(code, msg);
1463        }
1464    }
1465
1466    /**
1467     * Parses the header of a Binder call's response Parcel and
1468     * returns the exception code.  Deals with lite or fat headers.
1469     * In the common successful case, this header is generally zero.
1470     * In less common cases, it's a small negative number and will be
1471     * followed by an error string.
1472     *
1473     * This exists purely for android.database.DatabaseUtils and
1474     * insulating it from having to handle fat headers as returned by
1475     * e.g. StrictMode-induced RPC responses.
1476     *
1477     * @hide
1478     */
1479    public final int readExceptionCode() {
1480        int code = readInt();
1481        if (code == EX_HAS_REPLY_HEADER) {
1482            int headerSize = readInt();
1483            if (headerSize == 0) {
1484                Log.e(TAG, "Unexpected zero-sized Parcel reply header.");
1485            } else {
1486                // Currently the only thing in the header is StrictMode stacks,
1487                // but discussions around event/RPC tracing suggest we might
1488                // put that here too.  If so, switch on sub-header tags here.
1489                // But for now, just parse out the StrictMode stuff.
1490                StrictMode.readAndHandleBinderCallViolations(this);
1491            }
1492            // And fat response headers are currently only used when
1493            // there are no exceptions, so return no error:
1494            return 0;
1495        }
1496        return code;
1497    }
1498
1499    /**
1500     * Throw an exception with the given message. Not intended for use
1501     * outside the Parcel class.
1502     *
1503     * @param code Used to determine which exception class to throw.
1504     * @param msg The exception message.
1505     */
1506    public final void readException(int code, String msg) {
1507        switch (code) {
1508            case EX_SECURITY:
1509                throw new SecurityException(msg);
1510            case EX_BAD_PARCELABLE:
1511                throw new BadParcelableException(msg);
1512            case EX_ILLEGAL_ARGUMENT:
1513                throw new IllegalArgumentException(msg);
1514            case EX_NULL_POINTER:
1515                throw new NullPointerException(msg);
1516            case EX_ILLEGAL_STATE:
1517                throw new IllegalStateException(msg);
1518            case EX_NETWORK_MAIN_THREAD:
1519                throw new NetworkOnMainThreadException();
1520        }
1521        throw new RuntimeException("Unknown exception code: " + code
1522                + " msg " + msg);
1523    }
1524
1525    /**
1526     * Read an integer value from the parcel at the current dataPosition().
1527     */
1528    public final int readInt() {
1529        return nativeReadInt(mNativePtr);
1530    }
1531
1532    /**
1533     * Read a long integer value from the parcel at the current dataPosition().
1534     */
1535    public final long readLong() {
1536        return nativeReadLong(mNativePtr);
1537    }
1538
1539    /**
1540     * Read a floating point value from the parcel at the current
1541     * dataPosition().
1542     */
1543    public final float readFloat() {
1544        return nativeReadFloat(mNativePtr);
1545    }
1546
1547    /**
1548     * Read a double precision floating point value from the parcel at the
1549     * current dataPosition().
1550     */
1551    public final double readDouble() {
1552        return nativeReadDouble(mNativePtr);
1553    }
1554
1555    /**
1556     * Read a string value from the parcel at the current dataPosition().
1557     */
1558    public final String readString() {
1559        return nativeReadString(mNativePtr);
1560    }
1561
1562    /**
1563     * Read a CharSequence value from the parcel at the current dataPosition().
1564     * @hide
1565     */
1566    public final CharSequence readCharSequence() {
1567        return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
1568    }
1569
1570    /**
1571     * Read an object from the parcel at the current dataPosition().
1572     */
1573    public final IBinder readStrongBinder() {
1574        return nativeReadStrongBinder(mNativePtr);
1575    }
1576
1577    /**
1578     * Read a FileDescriptor from the parcel at the current dataPosition().
1579     */
1580    public final ParcelFileDescriptor readFileDescriptor() {
1581        FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
1582        return fd != null ? new ParcelFileDescriptor(fd) : null;
1583    }
1584
1585    /** {@hide} */
1586    public final FileDescriptor readRawFileDescriptor() {
1587        return nativeReadFileDescriptor(mNativePtr);
1588    }
1589
1590    /*package*/ static native FileDescriptor openFileDescriptor(String file,
1591            int mode) throws FileNotFoundException;
1592    /*package*/ static native FileDescriptor dupFileDescriptor(FileDescriptor orig)
1593            throws IOException;
1594    /*package*/ static native void closeFileDescriptor(FileDescriptor desc)
1595            throws IOException;
1596    /*package*/ static native void clearFileDescriptor(FileDescriptor desc);
1597
1598    /**
1599     * Read a byte value from the parcel at the current dataPosition().
1600     */
1601    public final byte readByte() {
1602        return (byte)(readInt() & 0xff);
1603    }
1604
1605    /**
1606     * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
1607     * been written with {@link #writeBundle}.  Read into an existing Map object
1608     * from the parcel at the current dataPosition().
1609     */
1610    public final void readMap(Map outVal, ClassLoader loader) {
1611        int N = readInt();
1612        readMapInternal(outVal, N, loader);
1613    }
1614
1615    /**
1616     * Read into an existing List object from the parcel at the current
1617     * dataPosition(), using the given class loader to load any enclosed
1618     * Parcelables.  If it is null, the default class loader is used.
1619     */
1620    public final void readList(List outVal, ClassLoader loader) {
1621        int N = readInt();
1622        readListInternal(outVal, N, loader);
1623    }
1624
1625    /**
1626     * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
1627     * been written with {@link #writeBundle}.  Read and return a new HashMap
1628     * object from the parcel at the current dataPosition(), using the given
1629     * class loader to load any enclosed Parcelables.  Returns null if
1630     * the previously written map object was null.
1631     */
1632    public final HashMap readHashMap(ClassLoader loader)
1633    {
1634        int N = readInt();
1635        if (N < 0) {
1636            return null;
1637        }
1638        HashMap m = new HashMap(N);
1639        readMapInternal(m, N, loader);
1640        return m;
1641    }
1642
1643    /**
1644     * Read and return a new Bundle object from the parcel at the current
1645     * dataPosition().  Returns null if the previously written Bundle object was
1646     * null.
1647     */
1648    public final Bundle readBundle() {
1649        return readBundle(null);
1650    }
1651
1652    /**
1653     * Read and return a new Bundle object from the parcel at the current
1654     * dataPosition(), using the given class loader to initialize the class
1655     * loader of the Bundle for later retrieval of Parcelable objects.
1656     * Returns null if the previously written Bundle object was null.
1657     */
1658    public final Bundle readBundle(ClassLoader loader) {
1659        int length = readInt();
1660        if (length < 0) {
1661            if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
1662            return null;
1663        }
1664
1665        final Bundle bundle = new Bundle(this, length);
1666        if (loader != null) {
1667            bundle.setClassLoader(loader);
1668        }
1669        return bundle;
1670    }
1671
1672    /**
1673     * Read and return a new Bundle object from the parcel at the current
1674     * dataPosition().  Returns null if the previously written Bundle object was
1675     * null.
1676     */
1677    public final PersistableBundle readPersistableBundle() {
1678        return readPersistableBundle(null);
1679    }
1680
1681    /**
1682     * Read and return a new Bundle object from the parcel at the current
1683     * dataPosition(), using the given class loader to initialize the class
1684     * loader of the Bundle for later retrieval of Parcelable objects.
1685     * Returns null if the previously written Bundle object was null.
1686     */
1687    public final PersistableBundle readPersistableBundle(ClassLoader loader) {
1688        int length = readInt();
1689        if (length < 0) {
1690            if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
1691            return null;
1692        }
1693
1694        final PersistableBundle bundle = new PersistableBundle(this, length);
1695        if (loader != null) {
1696            bundle.setClassLoader(loader);
1697        }
1698        return bundle;
1699    }
1700
1701    /**
1702     * Read and return a byte[] object from the parcel.
1703     */
1704    public final byte[] createByteArray() {
1705        return nativeCreateByteArray(mNativePtr);
1706    }
1707
1708    /**
1709     * Read a byte[] object from the parcel and copy it into the
1710     * given byte array.
1711     */
1712    public final void readByteArray(byte[] val) {
1713        // TODO: make this a native method to avoid the extra copy.
1714        byte[] ba = createByteArray();
1715        if (ba.length == val.length) {
1716           System.arraycopy(ba, 0, val, 0, ba.length);
1717        } else {
1718            throw new RuntimeException("bad array lengths");
1719        }
1720    }
1721
1722    /**
1723     * Read a blob of data from the parcel and return it as a byte array.
1724     * {@hide}
1725     * {@SystemApi}
1726     */
1727    public final byte[] readBlob() {
1728        return nativeReadBlob(mNativePtr);
1729    }
1730
1731    /**
1732     * Read and return a String[] object from the parcel.
1733     * {@hide}
1734     */
1735    public final String[] readStringArray() {
1736        String[] array = null;
1737
1738        int length = readInt();
1739        if (length >= 0)
1740        {
1741            array = new String[length];
1742
1743            for (int i = 0 ; i < length ; i++)
1744            {
1745                array[i] = readString();
1746            }
1747        }
1748
1749        return array;
1750    }
1751
1752    /**
1753     * Read and return a CharSequence[] object from the parcel.
1754     * {@hide}
1755     */
1756    public final CharSequence[] readCharSequenceArray() {
1757        CharSequence[] array = null;
1758
1759        int length = readInt();
1760        if (length >= 0)
1761        {
1762            array = new CharSequence[length];
1763
1764            for (int i = 0 ; i < length ; i++)
1765            {
1766                array[i] = readCharSequence();
1767            }
1768        }
1769
1770        return array;
1771    }
1772
1773    /**
1774     * Read and return a new ArrayList object from the parcel at the current
1775     * dataPosition().  Returns null if the previously written list object was
1776     * null.  The given class loader will be used to load any enclosed
1777     * Parcelables.
1778     */
1779    public final ArrayList readArrayList(ClassLoader loader) {
1780        int N = readInt();
1781        if (N < 0) {
1782            return null;
1783        }
1784        ArrayList l = new ArrayList(N);
1785        readListInternal(l, N, loader);
1786        return l;
1787    }
1788
1789    /**
1790     * Read and return a new Object array from the parcel at the current
1791     * dataPosition().  Returns null if the previously written array was
1792     * null.  The given class loader will be used to load any enclosed
1793     * Parcelables.
1794     */
1795    public final Object[] readArray(ClassLoader loader) {
1796        int N = readInt();
1797        if (N < 0) {
1798            return null;
1799        }
1800        Object[] l = new Object[N];
1801        readArrayInternal(l, N, loader);
1802        return l;
1803    }
1804
1805    /**
1806     * Read and return a new SparseArray object from the parcel at the current
1807     * dataPosition().  Returns null if the previously written list object was
1808     * null.  The given class loader will be used to load any enclosed
1809     * Parcelables.
1810     */
1811    public final SparseArray readSparseArray(ClassLoader loader) {
1812        int N = readInt();
1813        if (N < 0) {
1814            return null;
1815        }
1816        SparseArray sa = new SparseArray(N);
1817        readSparseArrayInternal(sa, N, loader);
1818        return sa;
1819    }
1820
1821    /**
1822     * Read and return a new SparseBooleanArray object from the parcel at the current
1823     * dataPosition().  Returns null if the previously written list object was
1824     * null.
1825     */
1826    public final SparseBooleanArray readSparseBooleanArray() {
1827        int N = readInt();
1828        if (N < 0) {
1829            return null;
1830        }
1831        SparseBooleanArray sa = new SparseBooleanArray(N);
1832        readSparseBooleanArrayInternal(sa, N);
1833        return sa;
1834    }
1835
1836    /**
1837     * Read and return a new ArrayList containing a particular object type from
1838     * the parcel that was written with {@link #writeTypedList} at the
1839     * current dataPosition().  Returns null if the
1840     * previously written list object was null.  The list <em>must</em> have
1841     * previously been written via {@link #writeTypedList} with the same object
1842     * type.
1843     *
1844     * @return A newly created ArrayList containing objects with the same data
1845     *         as those that were previously written.
1846     *
1847     * @see #writeTypedList
1848     */
1849    public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
1850        int N = readInt();
1851        if (N < 0) {
1852            return null;
1853        }
1854        ArrayList<T> l = new ArrayList<T>(N);
1855        while (N > 0) {
1856            if (readInt() != 0) {
1857                l.add(c.createFromParcel(this));
1858            } else {
1859                l.add(null);
1860            }
1861            N--;
1862        }
1863        return l;
1864    }
1865
1866    /**
1867     * Read into the given List items containing a particular object type
1868     * that were written with {@link #writeTypedList} at the
1869     * current dataPosition().  The list <em>must</em> have
1870     * previously been written via {@link #writeTypedList} with the same object
1871     * type.
1872     *
1873     * @return A newly created ArrayList containing objects with the same data
1874     *         as those that were previously written.
1875     *
1876     * @see #writeTypedList
1877     */
1878    public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
1879        int M = list.size();
1880        int N = readInt();
1881        int i = 0;
1882        for (; i < M && i < N; i++) {
1883            if (readInt() != 0) {
1884                list.set(i, c.createFromParcel(this));
1885            } else {
1886                list.set(i, null);
1887            }
1888        }
1889        for (; i<N; i++) {
1890            if (readInt() != 0) {
1891                list.add(c.createFromParcel(this));
1892            } else {
1893                list.add(null);
1894            }
1895        }
1896        for (; i<M; i++) {
1897            list.remove(N);
1898        }
1899    }
1900
1901    /**
1902     * Read and return a new ArrayList containing String objects from
1903     * the parcel that was written with {@link #writeStringList} at the
1904     * current dataPosition().  Returns null if the
1905     * previously written list object was null.
1906     *
1907     * @return A newly created ArrayList containing strings with the same data
1908     *         as those that were previously written.
1909     *
1910     * @see #writeStringList
1911     */
1912    public final ArrayList<String> createStringArrayList() {
1913        int N = readInt();
1914        if (N < 0) {
1915            return null;
1916        }
1917        ArrayList<String> l = new ArrayList<String>(N);
1918        while (N > 0) {
1919            l.add(readString());
1920            N--;
1921        }
1922        return l;
1923    }
1924
1925    /**
1926     * Read and return a new ArrayList containing IBinder objects from
1927     * the parcel that was written with {@link #writeBinderList} at the
1928     * current dataPosition().  Returns null if the
1929     * previously written list object was null.
1930     *
1931     * @return A newly created ArrayList containing strings with the same data
1932     *         as those that were previously written.
1933     *
1934     * @see #writeBinderList
1935     */
1936    public final ArrayList<IBinder> createBinderArrayList() {
1937        int N = readInt();
1938        if (N < 0) {
1939            return null;
1940        }
1941        ArrayList<IBinder> l = new ArrayList<IBinder>(N);
1942        while (N > 0) {
1943            l.add(readStrongBinder());
1944            N--;
1945        }
1946        return l;
1947    }
1948
1949    /**
1950     * Read into the given List items String objects that were written with
1951     * {@link #writeStringList} at the current dataPosition().
1952     *
1953     * @return A newly created ArrayList containing strings with the same data
1954     *         as those that were previously written.
1955     *
1956     * @see #writeStringList
1957     */
1958    public final void readStringList(List<String> list) {
1959        int M = list.size();
1960        int N = readInt();
1961        int i = 0;
1962        for (; i < M && i < N; i++) {
1963            list.set(i, readString());
1964        }
1965        for (; i<N; i++) {
1966            list.add(readString());
1967        }
1968        for (; i<M; i++) {
1969            list.remove(N);
1970        }
1971    }
1972
1973    /**
1974     * Read into the given List items IBinder objects that were written with
1975     * {@link #writeBinderList} at the current dataPosition().
1976     *
1977     * @return A newly created ArrayList containing strings with the same data
1978     *         as those that were previously written.
1979     *
1980     * @see #writeBinderList
1981     */
1982    public final void readBinderList(List<IBinder> list) {
1983        int M = list.size();
1984        int N = readInt();
1985        int i = 0;
1986        for (; i < M && i < N; i++) {
1987            list.set(i, readStrongBinder());
1988        }
1989        for (; i<N; i++) {
1990            list.add(readStrongBinder());
1991        }
1992        for (; i<M; i++) {
1993            list.remove(N);
1994        }
1995    }
1996
1997    /**
1998     * Read and return a new array containing a particular object type from
1999     * the parcel at the current dataPosition().  Returns null if the
2000     * previously written array was null.  The array <em>must</em> have
2001     * previously been written via {@link #writeTypedArray} with the same
2002     * object type.
2003     *
2004     * @return A newly created array containing objects with the same data
2005     *         as those that were previously written.
2006     *
2007     * @see #writeTypedArray
2008     */
2009    public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
2010        int N = readInt();
2011        if (N < 0) {
2012            return null;
2013        }
2014        T[] l = c.newArray(N);
2015        for (int i=0; i<N; i++) {
2016            if (readInt() != 0) {
2017                l[i] = c.createFromParcel(this);
2018            }
2019        }
2020        return l;
2021    }
2022
2023    public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
2024        int N = readInt();
2025        if (N == val.length) {
2026            for (int i=0; i<N; i++) {
2027                if (readInt() != 0) {
2028                    val[i] = c.createFromParcel(this);
2029                } else {
2030                    val[i] = null;
2031                }
2032            }
2033        } else {
2034            throw new RuntimeException("bad array lengths");
2035        }
2036    }
2037
2038    /**
2039     * @deprecated
2040     * @hide
2041     */
2042    @Deprecated
2043    public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
2044        return createTypedArray(c);
2045    }
2046
2047    /**
2048     * Write a heterogeneous array of Parcelable objects into the Parcel.
2049     * Each object in the array is written along with its class name, so
2050     * that the correct class can later be instantiated.  As a result, this
2051     * has significantly more overhead than {@link #writeTypedArray}, but will
2052     * correctly handle an array containing more than one type of object.
2053     *
2054     * @param value The array of objects to be written.
2055     * @param parcelableFlags Contextual flags as per
2056     * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2057     *
2058     * @see #writeTypedArray
2059     */
2060    public final <T extends Parcelable> void writeParcelableArray(T[] value,
2061            int parcelableFlags) {
2062        if (value != null) {
2063            int N = value.length;
2064            writeInt(N);
2065            for (int i=0; i<N; i++) {
2066                writeParcelable(value[i], parcelableFlags);
2067            }
2068        } else {
2069            writeInt(-1);
2070        }
2071    }
2072
2073    /**
2074     * Read a typed object from a parcel.  The given class loader will be
2075     * used to load any enclosed Parcelables.  If it is null, the default class
2076     * loader will be used.
2077     */
2078    public final Object readValue(ClassLoader loader) {
2079        int type = readInt();
2080
2081        switch (type) {
2082        case VAL_NULL:
2083            return null;
2084
2085        case VAL_STRING:
2086            return readString();
2087
2088        case VAL_INTEGER:
2089            return readInt();
2090
2091        case VAL_MAP:
2092            return readHashMap(loader);
2093
2094        case VAL_PARCELABLE:
2095            return readParcelable(loader);
2096
2097        case VAL_SHORT:
2098            return (short) readInt();
2099
2100        case VAL_LONG:
2101            return readLong();
2102
2103        case VAL_FLOAT:
2104            return readFloat();
2105
2106        case VAL_DOUBLE:
2107            return readDouble();
2108
2109        case VAL_BOOLEAN:
2110            return readInt() == 1;
2111
2112        case VAL_CHARSEQUENCE:
2113            return readCharSequence();
2114
2115        case VAL_LIST:
2116            return readArrayList(loader);
2117
2118        case VAL_BOOLEANARRAY:
2119            return createBooleanArray();
2120
2121        case VAL_BYTEARRAY:
2122            return createByteArray();
2123
2124        case VAL_STRINGARRAY:
2125            return readStringArray();
2126
2127        case VAL_CHARSEQUENCEARRAY:
2128            return readCharSequenceArray();
2129
2130        case VAL_IBINDER:
2131            return readStrongBinder();
2132
2133        case VAL_OBJECTARRAY:
2134            return readArray(loader);
2135
2136        case VAL_INTARRAY:
2137            return createIntArray();
2138
2139        case VAL_LONGARRAY:
2140            return createLongArray();
2141
2142        case VAL_BYTE:
2143            return readByte();
2144
2145        case VAL_SERIALIZABLE:
2146            return readSerializable(loader);
2147
2148        case VAL_PARCELABLEARRAY:
2149            return readParcelableArray(loader);
2150
2151        case VAL_SPARSEARRAY:
2152            return readSparseArray(loader);
2153
2154        case VAL_SPARSEBOOLEANARRAY:
2155            return readSparseBooleanArray();
2156
2157        case VAL_BUNDLE:
2158            return readBundle(loader); // loading will be deferred
2159
2160        case VAL_PERSISTABLEBUNDLE:
2161            return readPersistableBundle(loader);
2162
2163        default:
2164            int off = dataPosition() - 4;
2165            throw new RuntimeException(
2166                "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
2167        }
2168    }
2169
2170    /**
2171     * Read and return a new Parcelable from the parcel.  The given class loader
2172     * will be used to load any enclosed Parcelables.  If it is null, the default
2173     * class loader will be used.
2174     * @param loader A ClassLoader from which to instantiate the Parcelable
2175     * object, or null for the default class loader.
2176     * @return Returns the newly created Parcelable, or null if a null
2177     * object has been written.
2178     * @throws BadParcelableException Throws BadParcelableException if there
2179     * was an error trying to instantiate the Parcelable.
2180     */
2181    public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
2182        Parcelable.Creator<T> creator = readParcelableCreator(loader);
2183        if (creator == null) {
2184            return null;
2185        }
2186        if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2187            return ((Parcelable.ClassLoaderCreator<T>)creator).createFromParcel(this, loader);
2188        }
2189        return creator.createFromParcel(this);
2190    }
2191
2192    /** @hide */
2193    public final <T extends Parcelable> T readCreator(Parcelable.Creator<T> creator,
2194            ClassLoader loader) {
2195        if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2196            return ((Parcelable.ClassLoaderCreator<T>)creator).createFromParcel(this, loader);
2197        }
2198        return creator.createFromParcel(this);
2199    }
2200
2201    /** @hide */
2202    public final <T extends Parcelable> Parcelable.Creator<T> readParcelableCreator(
2203            ClassLoader loader) {
2204        String name = readString();
2205        if (name == null) {
2206            return null;
2207        }
2208        Parcelable.Creator<T> creator;
2209        synchronized (mCreators) {
2210            HashMap<String,Parcelable.Creator> map = mCreators.get(loader);
2211            if (map == null) {
2212                map = new HashMap<String,Parcelable.Creator>();
2213                mCreators.put(loader, map);
2214            }
2215            creator = map.get(name);
2216            if (creator == null) {
2217                try {
2218                    Class c = loader == null ?
2219                        Class.forName(name) : Class.forName(name, true, loader);
2220                    Field f = c.getField("CREATOR");
2221                    creator = (Parcelable.Creator)f.get(null);
2222                }
2223                catch (IllegalAccessException e) {
2224                    Log.e(TAG, "Illegal access when unmarshalling: "
2225                                        + name, e);
2226                    throw new BadParcelableException(
2227                            "IllegalAccessException when unmarshalling: " + name);
2228                }
2229                catch (ClassNotFoundException e) {
2230                    Log.e(TAG, "Class not found when unmarshalling: "
2231                                        + name, e);
2232                    throw new BadParcelableException(
2233                            "ClassNotFoundException when unmarshalling: " + name);
2234                }
2235                catch (ClassCastException e) {
2236                    throw new BadParcelableException("Parcelable protocol requires a "
2237                                        + "Parcelable.Creator object called "
2238                                        + " CREATOR on class " + name);
2239                }
2240                catch (NoSuchFieldException e) {
2241                    throw new BadParcelableException("Parcelable protocol requires a "
2242                                        + "Parcelable.Creator object called "
2243                                        + " CREATOR on class " + name);
2244                }
2245                catch (NullPointerException e) {
2246                    throw new BadParcelableException("Parcelable protocol requires "
2247                            + "the CREATOR object to be static on class " + name);
2248                }
2249                if (creator == null) {
2250                    throw new BadParcelableException("Parcelable protocol requires a "
2251                                        + "Parcelable.Creator object called "
2252                                        + " CREATOR on class " + name);
2253                }
2254
2255                map.put(name, creator);
2256            }
2257        }
2258
2259        return creator;
2260    }
2261
2262    /**
2263     * Read and return a new Parcelable array from the parcel.
2264     * The given class loader will be used to load any enclosed
2265     * Parcelables.
2266     * @return the Parcelable array, or null if the array is null
2267     */
2268    public final Parcelable[] readParcelableArray(ClassLoader loader) {
2269        int N = readInt();
2270        if (N < 0) {
2271            return null;
2272        }
2273        Parcelable[] p = new Parcelable[N];
2274        for (int i = 0; i < N; i++) {
2275            p[i] = (Parcelable) readParcelable(loader);
2276        }
2277        return p;
2278    }
2279
2280    /**
2281     * Read and return a new Serializable object from the parcel.
2282     * @return the Serializable object, or null if the Serializable name
2283     * wasn't found in the parcel.
2284     */
2285    public final Serializable readSerializable() {
2286        return readSerializable(null);
2287    }
2288
2289    private final Serializable readSerializable(final ClassLoader loader) {
2290        String name = readString();
2291        if (name == null) {
2292            // For some reason we were unable to read the name of the Serializable (either there
2293            // is nothing left in the Parcel to read, or the next value wasn't a String), so
2294            // return null, which indicates that the name wasn't found in the parcel.
2295            return null;
2296        }
2297
2298        byte[] serializedData = createByteArray();
2299        ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
2300        try {
2301            ObjectInputStream ois = new ObjectInputStream(bais) {
2302                @Override
2303                protected Class<?> resolveClass(ObjectStreamClass osClass)
2304                        throws IOException, ClassNotFoundException {
2305                    // try the custom classloader if provided
2306                    if (loader != null) {
2307                        Class<?> c = Class.forName(osClass.getName(), false, loader);
2308                        if (c != null) {
2309                            return c;
2310                        }
2311                    }
2312                    return super.resolveClass(osClass);
2313                }
2314            };
2315            return (Serializable) ois.readObject();
2316        } catch (IOException ioe) {
2317            throw new RuntimeException("Parcelable encountered " +
2318                "IOException reading a Serializable object (name = " + name +
2319                ")", ioe);
2320        } catch (ClassNotFoundException cnfe) {
2321            throw new RuntimeException("Parcelable encountered " +
2322                "ClassNotFoundException reading a Serializable object (name = "
2323                + name + ")", cnfe);
2324        }
2325    }
2326
2327    // Cache of previously looked up CREATOR.createFromParcel() methods for
2328    // particular classes.  Keys are the names of the classes, values are
2329    // Method objects.
2330    private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator>>
2331        mCreators = new HashMap<ClassLoader,HashMap<String,Parcelable.Creator>>();
2332
2333    /** @hide for internal use only. */
2334    static protected final Parcel obtain(int obj) {
2335        throw new UnsupportedOperationException();
2336    }
2337
2338    /** @hide */
2339    static protected final Parcel obtain(long obj) {
2340        final Parcel[] pool = sHolderPool;
2341        synchronized (pool) {
2342            Parcel p;
2343            for (int i=0; i<POOL_SIZE; i++) {
2344                p = pool[i];
2345                if (p != null) {
2346                    pool[i] = null;
2347                    if (DEBUG_RECYCLE) {
2348                        p.mStack = new RuntimeException();
2349                    }
2350                    p.init(obj);
2351                    return p;
2352                }
2353            }
2354        }
2355        return new Parcel(obj);
2356    }
2357
2358    private Parcel(long nativePtr) {
2359        if (DEBUG_RECYCLE) {
2360            mStack = new RuntimeException();
2361        }
2362        //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
2363        init(nativePtr);
2364    }
2365
2366    private void init(long nativePtr) {
2367        if (nativePtr != 0) {
2368            mNativePtr = nativePtr;
2369            mOwnsNativeParcelObject = false;
2370        } else {
2371            mNativePtr = nativeCreate();
2372            mOwnsNativeParcelObject = true;
2373        }
2374    }
2375
2376    private void freeBuffer() {
2377        if (mOwnsNativeParcelObject) {
2378            nativeFreeBuffer(mNativePtr);
2379        }
2380    }
2381
2382    private void destroy() {
2383        if (mNativePtr != 0) {
2384            if (mOwnsNativeParcelObject) {
2385                nativeDestroy(mNativePtr);
2386            }
2387            mNativePtr = 0;
2388        }
2389    }
2390
2391    @Override
2392    protected void finalize() throws Throwable {
2393        if (DEBUG_RECYCLE) {
2394            if (mStack != null) {
2395                Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
2396            }
2397        }
2398        destroy();
2399    }
2400
2401    /* package */ void readMapInternal(Map outVal, int N,
2402        ClassLoader loader) {
2403        while (N > 0) {
2404            Object key = readValue(loader);
2405            Object value = readValue(loader);
2406            outVal.put(key, value);
2407            N--;
2408        }
2409    }
2410
2411    /* package */ void readArrayMapInternal(ArrayMap outVal, int N,
2412        ClassLoader loader) {
2413        if (DEBUG_ARRAY_MAP) {
2414            RuntimeException here =  new RuntimeException("here");
2415            here.fillInStackTrace();
2416            Log.d(TAG, "Reading " + N + " ArrayMap entries", here);
2417        }
2418        int startPos;
2419        while (N > 0) {
2420            if (DEBUG_ARRAY_MAP) startPos = dataPosition();
2421            String key = readString();
2422            Object value = readValue(loader);
2423            if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Read #" + (N-1) + " "
2424                    + (dataPosition()-startPos) + " bytes: key=0x"
2425                    + Integer.toHexString((key != null ? key.hashCode() : 0)) + " " + key);
2426            outVal.append(key, value);
2427            N--;
2428        }
2429        outVal.validate();
2430    }
2431
2432    /* package */ void readArrayMapSafelyInternal(ArrayMap outVal, int N,
2433        ClassLoader loader) {
2434        if (DEBUG_ARRAY_MAP) {
2435            RuntimeException here =  new RuntimeException("here");
2436            here.fillInStackTrace();
2437            Log.d(TAG, "Reading safely " + N + " ArrayMap entries", here);
2438        }
2439        while (N > 0) {
2440            String key = readString();
2441            if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Read safe #" + (N-1) + ": key=0x"
2442                    + (key != null ? key.hashCode() : 0) + " " + key);
2443            Object value = readValue(loader);
2444            outVal.put(key, value);
2445            N--;
2446        }
2447    }
2448
2449    /**
2450     * @hide For testing only.
2451     */
2452    public void readArrayMap(ArrayMap outVal, ClassLoader loader) {
2453        final int N = readInt();
2454        if (N < 0) {
2455            return;
2456        }
2457        readArrayMapInternal(outVal, N, loader);
2458    }
2459
2460    private void readListInternal(List outVal, int N,
2461        ClassLoader loader) {
2462        while (N > 0) {
2463            Object value = readValue(loader);
2464            //Log.d(TAG, "Unmarshalling value=" + value);
2465            outVal.add(value);
2466            N--;
2467        }
2468    }
2469
2470    private void readArrayInternal(Object[] outVal, int N,
2471        ClassLoader loader) {
2472        for (int i = 0; i < N; i++) {
2473            Object value = readValue(loader);
2474            //Log.d(TAG, "Unmarshalling value=" + value);
2475            outVal[i] = value;
2476        }
2477    }
2478
2479    private void readSparseArrayInternal(SparseArray outVal, int N,
2480        ClassLoader loader) {
2481        while (N > 0) {
2482            int key = readInt();
2483            Object value = readValue(loader);
2484            //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
2485            outVal.append(key, value);
2486            N--;
2487        }
2488    }
2489
2490
2491    private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
2492        while (N > 0) {
2493            int key = readInt();
2494            boolean value = this.readByte() == 1;
2495            //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
2496            outVal.append(key, value);
2497            N--;
2498        }
2499    }
2500}
2501