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