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