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