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