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