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