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