Parcel.java revision a28b83ee04ca25100781f37a50665d6e1b05e3a2
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
1389    /**
1390     * Read a byte value from the parcel at the current dataPosition().
1391     */
1392    public final byte readByte() {
1393        return (byte)(readInt() & 0xff);
1394    }
1395
1396    /**
1397     * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
1398     * been written with {@link #writeBundle}.  Read into an existing Map object
1399     * from the parcel at the current dataPosition().
1400     */
1401    public final void readMap(Map outVal, ClassLoader loader) {
1402        int N = readInt();
1403        readMapInternal(outVal, N, loader);
1404    }
1405
1406    /**
1407     * Read into an existing List object from the parcel at the current
1408     * dataPosition(), using the given class loader to load any enclosed
1409     * Parcelables.  If it is null, the default class loader is used.
1410     */
1411    public final void readList(List outVal, ClassLoader loader) {
1412        int N = readInt();
1413        readListInternal(outVal, N, loader);
1414    }
1415
1416    /**
1417     * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
1418     * been written with {@link #writeBundle}.  Read and return a new HashMap
1419     * object from the parcel at the current dataPosition(), using the given
1420     * class loader to load any enclosed Parcelables.  Returns null if
1421     * the previously written map object was null.
1422     */
1423    public final HashMap readHashMap(ClassLoader loader)
1424    {
1425        int N = readInt();
1426        if (N < 0) {
1427            return null;
1428        }
1429        HashMap m = new HashMap(N);
1430        readMapInternal(m, N, loader);
1431        return m;
1432    }
1433
1434    /**
1435     * Read and return a new Bundle object from the parcel at the current
1436     * dataPosition().  Returns null if the previously written Bundle object was
1437     * null.
1438     */
1439    public final Bundle readBundle() {
1440        return readBundle(null);
1441    }
1442
1443    /**
1444     * Read and return a new Bundle object from the parcel at the current
1445     * dataPosition(), using the given class loader to initialize the class
1446     * loader of the Bundle for later retrieval of Parcelable objects.
1447     * Returns null if the previously written Bundle object was null.
1448     */
1449    public final Bundle readBundle(ClassLoader loader) {
1450        int length = readInt();
1451        if (length < 0) {
1452            return null;
1453        }
1454
1455        final Bundle bundle = new Bundle(this, length);
1456        if (loader != null) {
1457            bundle.setClassLoader(loader);
1458        }
1459        return bundle;
1460    }
1461
1462    /**
1463     * Read and return a byte[] object from the parcel.
1464     */
1465    public final native byte[] createByteArray();
1466
1467    /**
1468     * Read a byte[] object from the parcel and copy it into the
1469     * given byte array.
1470     */
1471    public final void readByteArray(byte[] val) {
1472        // TODO: make this a native method to avoid the extra copy.
1473        byte[] ba = createByteArray();
1474        if (ba.length == val.length) {
1475           System.arraycopy(ba, 0, val, 0, ba.length);
1476        } else {
1477            throw new RuntimeException("bad array lengths");
1478        }
1479    }
1480
1481    /**
1482     * Read and return a String[] object from the parcel.
1483     * {@hide}
1484     */
1485    public final String[] readStringArray() {
1486        String[] array = null;
1487
1488        int length = readInt();
1489        if (length >= 0)
1490        {
1491            array = new String[length];
1492
1493            for (int i = 0 ; i < length ; i++)
1494            {
1495                array[i] = readString();
1496            }
1497        }
1498
1499        return array;
1500    }
1501
1502    /**
1503     * Read and return a CharSequence[] object from the parcel.
1504     * {@hide}
1505     */
1506    public final CharSequence[] readCharSequenceArray() {
1507        CharSequence[] array = null;
1508
1509        int length = readInt();
1510        if (length >= 0)
1511        {
1512            array = new CharSequence[length];
1513
1514            for (int i = 0 ; i < length ; i++)
1515            {
1516                array[i] = readCharSequence();
1517            }
1518        }
1519
1520        return array;
1521    }
1522
1523    /**
1524     * Read and return a new ArrayList object from the parcel at the current
1525     * dataPosition().  Returns null if the previously written list object was
1526     * null.  The given class loader will be used to load any enclosed
1527     * Parcelables.
1528     */
1529    public final ArrayList readArrayList(ClassLoader loader) {
1530        int N = readInt();
1531        if (N < 0) {
1532            return null;
1533        }
1534        ArrayList l = new ArrayList(N);
1535        readListInternal(l, N, loader);
1536        return l;
1537    }
1538
1539    /**
1540     * Read and return a new Object array from the parcel at the current
1541     * dataPosition().  Returns null if the previously written array was
1542     * null.  The given class loader will be used to load any enclosed
1543     * Parcelables.
1544     */
1545    public final Object[] readArray(ClassLoader loader) {
1546        int N = readInt();
1547        if (N < 0) {
1548            return null;
1549        }
1550        Object[] l = new Object[N];
1551        readArrayInternal(l, N, loader);
1552        return l;
1553    }
1554
1555    /**
1556     * Read and return a new SparseArray object from the parcel at the current
1557     * dataPosition().  Returns null if the previously written list object was
1558     * null.  The given class loader will be used to load any enclosed
1559     * Parcelables.
1560     */
1561    public final SparseArray readSparseArray(ClassLoader loader) {
1562        int N = readInt();
1563        if (N < 0) {
1564            return null;
1565        }
1566        SparseArray sa = new SparseArray(N);
1567        readSparseArrayInternal(sa, N, loader);
1568        return sa;
1569    }
1570
1571    /**
1572     * Read and return a new SparseBooleanArray object from the parcel at the current
1573     * dataPosition().  Returns null if the previously written list object was
1574     * null.
1575     */
1576    public final SparseBooleanArray readSparseBooleanArray() {
1577        int N = readInt();
1578        if (N < 0) {
1579            return null;
1580        }
1581        SparseBooleanArray sa = new SparseBooleanArray(N);
1582        readSparseBooleanArrayInternal(sa, N);
1583        return sa;
1584    }
1585
1586    /**
1587     * Read and return a new ArrayList containing a particular object type from
1588     * the parcel that was written with {@link #writeTypedList} at the
1589     * current dataPosition().  Returns null if the
1590     * previously written list object was null.  The list <em>must</em> have
1591     * previously been written via {@link #writeTypedList} with the same object
1592     * type.
1593     *
1594     * @return A newly created ArrayList containing objects with the same data
1595     *         as those that were previously written.
1596     *
1597     * @see #writeTypedList
1598     */
1599    public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
1600        int N = readInt();
1601        if (N < 0) {
1602            return null;
1603        }
1604        ArrayList<T> l = new ArrayList<T>(N);
1605        while (N > 0) {
1606            if (readInt() != 0) {
1607                l.add(c.createFromParcel(this));
1608            } else {
1609                l.add(null);
1610            }
1611            N--;
1612        }
1613        return l;
1614    }
1615
1616    /**
1617     * Read into the given List items containing a particular object type
1618     * that were written with {@link #writeTypedList} at the
1619     * current dataPosition().  The list <em>must</em> have
1620     * previously been written via {@link #writeTypedList} with the same object
1621     * type.
1622     *
1623     * @return A newly created ArrayList containing objects with the same data
1624     *         as those that were previously written.
1625     *
1626     * @see #writeTypedList
1627     */
1628    public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
1629        int M = list.size();
1630        int N = readInt();
1631        int i = 0;
1632        for (; i < M && i < N; i++) {
1633            if (readInt() != 0) {
1634                list.set(i, c.createFromParcel(this));
1635            } else {
1636                list.set(i, null);
1637            }
1638        }
1639        for (; i<N; i++) {
1640            if (readInt() != 0) {
1641                list.add(c.createFromParcel(this));
1642            } else {
1643                list.add(null);
1644            }
1645        }
1646        for (; i<M; i++) {
1647            list.remove(N);
1648        }
1649    }
1650
1651    /**
1652     * Read and return a new ArrayList containing String objects from
1653     * the parcel that was written with {@link #writeStringList} at the
1654     * current dataPosition().  Returns null if the
1655     * previously written list object was null.
1656     *
1657     * @return A newly created ArrayList containing strings with the same data
1658     *         as those that were previously written.
1659     *
1660     * @see #writeStringList
1661     */
1662    public final ArrayList<String> createStringArrayList() {
1663        int N = readInt();
1664        if (N < 0) {
1665            return null;
1666        }
1667        ArrayList<String> l = new ArrayList<String>(N);
1668        while (N > 0) {
1669            l.add(readString());
1670            N--;
1671        }
1672        return l;
1673    }
1674
1675    /**
1676     * Read and return a new ArrayList containing IBinder objects from
1677     * the parcel that was written with {@link #writeBinderList} at the
1678     * current dataPosition().  Returns null if the
1679     * previously written list object was null.
1680     *
1681     * @return A newly created ArrayList containing strings with the same data
1682     *         as those that were previously written.
1683     *
1684     * @see #writeBinderList
1685     */
1686    public final ArrayList<IBinder> createBinderArrayList() {
1687        int N = readInt();
1688        if (N < 0) {
1689            return null;
1690        }
1691        ArrayList<IBinder> l = new ArrayList<IBinder>(N);
1692        while (N > 0) {
1693            l.add(readStrongBinder());
1694            N--;
1695        }
1696        return l;
1697    }
1698
1699    /**
1700     * Read into the given List items String objects that were written with
1701     * {@link #writeStringList} at the current dataPosition().
1702     *
1703     * @return A newly created ArrayList containing strings with the same data
1704     *         as those that were previously written.
1705     *
1706     * @see #writeStringList
1707     */
1708    public final void readStringList(List<String> list) {
1709        int M = list.size();
1710        int N = readInt();
1711        int i = 0;
1712        for (; i < M && i < N; i++) {
1713            list.set(i, readString());
1714        }
1715        for (; i<N; i++) {
1716            list.add(readString());
1717        }
1718        for (; i<M; i++) {
1719            list.remove(N);
1720        }
1721    }
1722
1723    /**
1724     * Read into the given List items IBinder objects that were written with
1725     * {@link #writeBinderList} at the current dataPosition().
1726     *
1727     * @return A newly created ArrayList containing strings with the same data
1728     *         as those that were previously written.
1729     *
1730     * @see #writeBinderList
1731     */
1732    public final void readBinderList(List<IBinder> list) {
1733        int M = list.size();
1734        int N = readInt();
1735        int i = 0;
1736        for (; i < M && i < N; i++) {
1737            list.set(i, readStrongBinder());
1738        }
1739        for (; i<N; i++) {
1740            list.add(readStrongBinder());
1741        }
1742        for (; i<M; i++) {
1743            list.remove(N);
1744        }
1745    }
1746
1747    /**
1748     * Read and return a new array containing a particular object type from
1749     * the parcel at the current dataPosition().  Returns null if the
1750     * previously written array was null.  The array <em>must</em> have
1751     * previously been written via {@link #writeTypedArray} with the same
1752     * object type.
1753     *
1754     * @return A newly created array containing objects with the same data
1755     *         as those that were previously written.
1756     *
1757     * @see #writeTypedArray
1758     */
1759    public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
1760        int N = readInt();
1761        if (N < 0) {
1762            return null;
1763        }
1764        T[] l = c.newArray(N);
1765        for (int i=0; i<N; i++) {
1766            if (readInt() != 0) {
1767                l[i] = c.createFromParcel(this);
1768            }
1769        }
1770        return l;
1771    }
1772
1773    public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
1774        int N = readInt();
1775        if (N == val.length) {
1776            for (int i=0; i<N; i++) {
1777                if (readInt() != 0) {
1778                    val[i] = c.createFromParcel(this);
1779                } else {
1780                    val[i] = null;
1781                }
1782            }
1783        } else {
1784            throw new RuntimeException("bad array lengths");
1785        }
1786    }
1787
1788    /**
1789     * @deprecated
1790     * @hide
1791     */
1792    @Deprecated
1793    public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
1794        return createTypedArray(c);
1795    }
1796
1797    /**
1798     * Write a heterogeneous array of Parcelable objects into the Parcel.
1799     * Each object in the array is written along with its class name, so
1800     * that the correct class can later be instantiated.  As a result, this
1801     * has significantly more overhead than {@link #writeTypedArray}, but will
1802     * correctly handle an array containing more than one type of object.
1803     *
1804     * @param value The array of objects to be written.
1805     * @param parcelableFlags Contextual flags as per
1806     * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1807     *
1808     * @see #writeTypedArray
1809     */
1810    public final <T extends Parcelable> void writeParcelableArray(T[] value,
1811            int parcelableFlags) {
1812        if (value != null) {
1813            int N = value.length;
1814            writeInt(N);
1815            for (int i=0; i<N; i++) {
1816                writeParcelable(value[i], parcelableFlags);
1817            }
1818        } else {
1819            writeInt(-1);
1820        }
1821    }
1822
1823    /**
1824     * Read a typed object from a parcel.  The given class loader will be
1825     * used to load any enclosed Parcelables.  If it is null, the default class
1826     * loader will be used.
1827     */
1828    public final Object readValue(ClassLoader loader) {
1829        int type = readInt();
1830
1831        switch (type) {
1832        case VAL_NULL:
1833            return null;
1834
1835        case VAL_STRING:
1836            return readString();
1837
1838        case VAL_INTEGER:
1839            return readInt();
1840
1841        case VAL_MAP:
1842            return readHashMap(loader);
1843
1844        case VAL_PARCELABLE:
1845            return readParcelable(loader);
1846
1847        case VAL_SHORT:
1848            return (short) readInt();
1849
1850        case VAL_LONG:
1851            return readLong();
1852
1853        case VAL_FLOAT:
1854            return readFloat();
1855
1856        case VAL_DOUBLE:
1857            return readDouble();
1858
1859        case VAL_BOOLEAN:
1860            return readInt() == 1;
1861
1862        case VAL_CHARSEQUENCE:
1863            return readCharSequence();
1864
1865        case VAL_LIST:
1866            return readArrayList(loader);
1867
1868        case VAL_BOOLEANARRAY:
1869            return createBooleanArray();
1870
1871        case VAL_BYTEARRAY:
1872            return createByteArray();
1873
1874        case VAL_STRINGARRAY:
1875            return readStringArray();
1876
1877        case VAL_CHARSEQUENCEARRAY:
1878            return readCharSequenceArray();
1879
1880        case VAL_IBINDER:
1881            return readStrongBinder();
1882
1883        case VAL_OBJECTARRAY:
1884            return readArray(loader);
1885
1886        case VAL_INTARRAY:
1887            return createIntArray();
1888
1889        case VAL_LONGARRAY:
1890            return createLongArray();
1891
1892        case VAL_BYTE:
1893            return readByte();
1894
1895        case VAL_SERIALIZABLE:
1896            return readSerializable();
1897
1898        case VAL_PARCELABLEARRAY:
1899            return readParcelableArray(loader);
1900
1901        case VAL_SPARSEARRAY:
1902            return readSparseArray(loader);
1903
1904        case VAL_SPARSEBOOLEANARRAY:
1905            return readSparseBooleanArray();
1906
1907        case VAL_BUNDLE:
1908            return readBundle(loader); // loading will be deferred
1909
1910        default:
1911            int off = dataPosition() - 4;
1912            throw new RuntimeException(
1913                "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
1914        }
1915    }
1916
1917    /**
1918     * Read and return a new Parcelable from the parcel.  The given class loader
1919     * will be used to load any enclosed Parcelables.  If it is null, the default
1920     * class loader will be used.
1921     * @param loader A ClassLoader from which to instantiate the Parcelable
1922     * object, or null for the default class loader.
1923     * @return Returns the newly created Parcelable, or null if a null
1924     * object has been written.
1925     * @throws BadParcelableException Throws BadParcelableException if there
1926     * was an error trying to instantiate the Parcelable.
1927     */
1928    public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
1929        String name = readString();
1930        if (name == null) {
1931            return null;
1932        }
1933        Parcelable.Creator<T> creator;
1934        synchronized (mCreators) {
1935            HashMap<String,Parcelable.Creator> map = mCreators.get(loader);
1936            if (map == null) {
1937                map = new HashMap<String,Parcelable.Creator>();
1938                mCreators.put(loader, map);
1939            }
1940            creator = map.get(name);
1941            if (creator == null) {
1942                try {
1943                    Class c = loader == null ?
1944                        Class.forName(name) : Class.forName(name, true, loader);
1945                    Field f = c.getField("CREATOR");
1946                    creator = (Parcelable.Creator)f.get(null);
1947                }
1948                catch (IllegalAccessException e) {
1949                    Log.e(TAG, "Class not found when unmarshalling: "
1950                                        + name + ", e: " + e);
1951                    throw new BadParcelableException(
1952                            "IllegalAccessException when unmarshalling: " + name);
1953                }
1954                catch (ClassNotFoundException e) {
1955                    Log.e(TAG, "Class not found when unmarshalling: "
1956                                        + name + ", e: " + e);
1957                    throw new BadParcelableException(
1958                            "ClassNotFoundException when unmarshalling: " + name);
1959                }
1960                catch (ClassCastException e) {
1961                    throw new BadParcelableException("Parcelable protocol requires a "
1962                                        + "Parcelable.Creator object called "
1963                                        + " CREATOR on class " + name);
1964                }
1965                catch (NoSuchFieldException e) {
1966                    throw new BadParcelableException("Parcelable protocol requires a "
1967                                        + "Parcelable.Creator object called "
1968                                        + " CREATOR on class " + name);
1969                }
1970                if (creator == null) {
1971                    throw new BadParcelableException("Parcelable protocol requires a "
1972                                        + "Parcelable.Creator object called "
1973                                        + " CREATOR on class " + name);
1974                }
1975
1976                map.put(name, creator);
1977            }
1978        }
1979
1980        return creator.createFromParcel(this);
1981    }
1982
1983    /**
1984     * Read and return a new Parcelable array from the parcel.
1985     * The given class loader will be used to load any enclosed
1986     * Parcelables.
1987     * @return the Parcelable array, or null if the array is null
1988     */
1989    public final Parcelable[] readParcelableArray(ClassLoader loader) {
1990        int N = readInt();
1991        if (N < 0) {
1992            return null;
1993        }
1994        Parcelable[] p = new Parcelable[N];
1995        for (int i = 0; i < N; i++) {
1996            p[i] = (Parcelable) readParcelable(loader);
1997        }
1998        return p;
1999    }
2000
2001    /**
2002     * Read and return a new Serializable object from the parcel.
2003     * @return the Serializable object, or null if the Serializable name
2004     * wasn't found in the parcel.
2005     */
2006    public final Serializable readSerializable() {
2007        String name = readString();
2008        if (name == null) {
2009            // For some reason we were unable to read the name of the Serializable (either there
2010            // is nothing left in the Parcel to read, or the next value wasn't a String), so
2011            // return null, which indicates that the name wasn't found in the parcel.
2012            return null;
2013        }
2014
2015        byte[] serializedData = createByteArray();
2016        ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
2017        try {
2018            ObjectInputStream ois = new ObjectInputStream(bais);
2019            return (Serializable) ois.readObject();
2020        } catch (IOException ioe) {
2021            throw new RuntimeException("Parcelable encountered " +
2022                "IOException reading a Serializable object (name = " + name +
2023                ")", ioe);
2024        } catch (ClassNotFoundException cnfe) {
2025            throw new RuntimeException("Parcelable encountered" +
2026                "ClassNotFoundException reading a Serializable object (name = "
2027                + name + ")", cnfe);
2028        }
2029    }
2030
2031    // Cache of previously looked up CREATOR.createFromParcel() methods for
2032    // particular classes.  Keys are the names of the classes, values are
2033    // Method objects.
2034    private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator>>
2035        mCreators = new HashMap<ClassLoader,HashMap<String,Parcelable.Creator>>();
2036
2037    static protected final Parcel obtain(int obj) {
2038        final Parcel[] pool = sHolderPool;
2039        synchronized (pool) {
2040            Parcel p;
2041            for (int i=0; i<POOL_SIZE; i++) {
2042                p = pool[i];
2043                if (p != null) {
2044                    pool[i] = null;
2045                    if (DEBUG_RECYCLE) {
2046                        p.mStack = new RuntimeException();
2047                    }
2048                    p.init(obj);
2049                    return p;
2050                }
2051            }
2052        }
2053        return new Parcel(obj);
2054    }
2055
2056    private Parcel(int obj) {
2057        if (DEBUG_RECYCLE) {
2058            mStack = new RuntimeException();
2059        }
2060        //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
2061        init(obj);
2062    }
2063
2064    @Override
2065    protected void finalize() throws Throwable {
2066        if (DEBUG_RECYCLE) {
2067            if (mStack != null) {
2068                Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
2069            }
2070        }
2071        destroy();
2072    }
2073
2074    private native void freeBuffer();
2075    private native void init(int obj);
2076    private native void destroy();
2077
2078    /* package */ void readMapInternal(Map outVal, int N,
2079        ClassLoader loader) {
2080        while (N > 0) {
2081            Object key = readValue(loader);
2082            Object value = readValue(loader);
2083            outVal.put(key, value);
2084            N--;
2085        }
2086    }
2087
2088    private void readListInternal(List outVal, int N,
2089        ClassLoader loader) {
2090        while (N > 0) {
2091            Object value = readValue(loader);
2092            //Log.d(TAG, "Unmarshalling value=" + value);
2093            outVal.add(value);
2094            N--;
2095        }
2096    }
2097
2098    private void readArrayInternal(Object[] outVal, int N,
2099        ClassLoader loader) {
2100        for (int i = 0; i < N; i++) {
2101            Object value = readValue(loader);
2102            //Log.d(TAG, "Unmarshalling value=" + value);
2103            outVal[i] = value;
2104        }
2105    }
2106
2107    private void readSparseArrayInternal(SparseArray outVal, int N,
2108        ClassLoader loader) {
2109        while (N > 0) {
2110            int key = readInt();
2111            Object value = readValue(loader);
2112            //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
2113            outVal.append(key, value);
2114            N--;
2115        }
2116    }
2117
2118
2119    private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
2120        while (N > 0) {
2121            int key = readInt();
2122            boolean value = this.readByte() == 1;
2123            //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
2124            outVal.append(key, value);
2125            N--;
2126        }
2127    }
2128}
2129