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