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