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