1 /* 2 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.io; 27 28 import java.io.ObjectStreamClass.WeakClassKey; 29 import java.lang.ref.ReferenceQueue; 30 import java.lang.reflect.Array; 31 import java.lang.reflect.Modifier; 32 import java.lang.reflect.Proxy; 33 import java.security.AccessControlContext; 34 import java.security.AccessController; 35 import java.security.PrivilegedAction; 36 import java.security.PrivilegedActionException; 37 import java.security.PrivilegedExceptionAction; 38 import java.util.Arrays; 39 import java.util.HashMap; 40 import java.util.concurrent.ConcurrentHashMap; 41 import java.util.concurrent.ConcurrentMap; 42 import static java.io.ObjectStreamClass.processQueue; 43 import sun.misc.Unsafe; 44 import sun.reflect.misc.ReflectUtil; 45 46 /** 47 * An ObjectInputStream deserializes primitive data and objects previously 48 * written using an ObjectOutputStream. 49 * 50 * <p>ObjectOutputStream and ObjectInputStream can provide an application with 51 * persistent storage for graphs of objects when used with a FileOutputStream 52 * and FileInputStream respectively. ObjectInputStream is used to recover 53 * those objects previously serialized. Other uses include passing objects 54 * between hosts using a socket stream or for marshaling and unmarshaling 55 * arguments and parameters in a remote communication system. 56 * 57 * <p>ObjectInputStream ensures that the types of all objects in the graph 58 * created from the stream match the classes present in the Java Virtual 59 * Machine. Classes are loaded as required using the standard mechanisms. 60 * 61 * <p>Only objects that support the java.io.Serializable or 62 * java.io.Externalizable interface can be read from streams. 63 * 64 * <p>The method <code>readObject</code> is used to read an object from the 65 * stream. Java's safe casting should be used to get the desired type. In 66 * Java, strings and arrays are objects and are treated as objects during 67 * serialization. When read they need to be cast to the expected type. 68 * 69 * <p>Primitive data types can be read from the stream using the appropriate 70 * method on DataInput. 71 * 72 * <p>The default deserialization mechanism for objects restores the contents 73 * of each field to the value and type it had when it was written. Fields 74 * declared as transient or static are ignored by the deserialization process. 75 * References to other objects cause those objects to be read from the stream 76 * as necessary. Graphs of objects are restored correctly using a reference 77 * sharing mechanism. New objects are always allocated when deserializing, 78 * which prevents existing objects from being overwritten. 79 * 80 * <p>Reading an object is analogous to running the constructors of a new 81 * object. Memory is allocated for the object and initialized to zero (NULL). 82 * No-arg constructors are invoked for the non-serializable classes and then 83 * the fields of the serializable classes are restored from the stream starting 84 * with the serializable class closest to java.lang.object and finishing with 85 * the object's most specific class. 86 * 87 * <p>For example to read from a stream as written by the example in 88 * ObjectOutputStream: 89 * <br> 90 * <pre> 91 * FileInputStream fis = new FileInputStream("t.tmp"); 92 * ObjectInputStream ois = new ObjectInputStream(fis); 93 * 94 * int i = ois.readInt(); 95 * String today = (String) ois.readObject(); 96 * Date date = (Date) ois.readObject(); 97 * 98 * ois.close(); 99 * </pre> 100 * 101 * <p>Classes control how they are serialized by implementing either the 102 * java.io.Serializable or java.io.Externalizable interfaces. 103 * 104 * <p>Implementing the Serializable interface allows object serialization to 105 * save and restore the entire state of the object and it allows classes to 106 * evolve between the time the stream is written and the time it is read. It 107 * automatically traverses references between objects, saving and restoring 108 * entire graphs. 109 * 110 * <p>Serializable classes that require special handling during the 111 * serialization and deserialization process should implement the following 112 * methods: 113 * 114 * <pre> 115 * private void writeObject(java.io.ObjectOutputStream stream) 116 * throws IOException; 117 * private void readObject(java.io.ObjectInputStream stream) 118 * throws IOException, ClassNotFoundException; 119 * private void readObjectNoData() 120 * throws ObjectStreamException; 121 * </pre> 122 * 123 * <p>The readObject method is responsible for reading and restoring the state 124 * of the object for its particular class using data written to the stream by 125 * the corresponding writeObject method. The method does not need to concern 126 * itself with the state belonging to its superclasses or subclasses. State is 127 * restored by reading data from the ObjectInputStream for the individual 128 * fields and making assignments to the appropriate fields of the object. 129 * Reading primitive data types is supported by DataInput. 130 * 131 * <p>Any attempt to read object data which exceeds the boundaries of the 132 * custom data written by the corresponding writeObject method will cause an 133 * OptionalDataException to be thrown with an eof field value of true. 134 * Non-object reads which exceed the end of the allotted data will reflect the 135 * end of data in the same way that they would indicate the end of the stream: 136 * bytewise reads will return -1 as the byte read or number of bytes read, and 137 * primitive reads will throw EOFExceptions. If there is no corresponding 138 * writeObject method, then the end of default serialized data marks the end of 139 * the allotted data. 140 * 141 * <p>Primitive and object read calls issued from within a readExternal method 142 * behave in the same manner--if the stream is already positioned at the end of 143 * data written by the corresponding writeExternal method, object reads will 144 * throw OptionalDataExceptions with eof set to true, bytewise reads will 145 * return -1, and primitive reads will throw EOFExceptions. Note that this 146 * behavior does not hold for streams written with the old 147 * <code>ObjectStreamConstants.PROTOCOL_VERSION_1</code> protocol, in which the 148 * end of data written by writeExternal methods is not demarcated, and hence 149 * cannot be detected. 150 * 151 * <p>The readObjectNoData method is responsible for initializing the state of 152 * the object for its particular class in the event that the serialization 153 * stream does not list the given class as a superclass of the object being 154 * deserialized. This may occur in cases where the receiving party uses a 155 * different version of the deserialized instance's class than the sending 156 * party, and the receiver's version extends classes that are not extended by 157 * the sender's version. This may also occur if the serialization stream has 158 * been tampered; hence, readObjectNoData is useful for initializing 159 * deserialized objects properly despite a "hostile" or incomplete source 160 * stream. 161 * 162 * <p>Serialization does not read or assign values to the fields of any object 163 * that does not implement the java.io.Serializable interface. Subclasses of 164 * Objects that are not serializable can be serializable. In this case the 165 * non-serializable class must have a no-arg constructor to allow its fields to 166 * be initialized. In this case it is the responsibility of the subclass to 167 * save and restore the state of the non-serializable class. It is frequently 168 * the case that the fields of that class are accessible (public, package, or 169 * protected) or that there are get and set methods that can be used to restore 170 * the state. 171 * 172 * <p>Any exception that occurs while deserializing an object will be caught by 173 * the ObjectInputStream and abort the reading process. 174 * 175 * <p>Implementing the Externalizable interface allows the object to assume 176 * complete control over the contents and format of the object's serialized 177 * form. The methods of the Externalizable interface, writeExternal and 178 * readExternal, are called to save and restore the objects state. When 179 * implemented by a class they can write and read their own state using all of 180 * the methods of ObjectOutput and ObjectInput. It is the responsibility of 181 * the objects to handle any versioning that occurs. 182 * 183 * <p>Enum constants are deserialized differently than ordinary serializable or 184 * externalizable objects. The serialized form of an enum constant consists 185 * solely of its name; field values of the constant are not transmitted. To 186 * deserialize an enum constant, ObjectInputStream reads the constant name from 187 * the stream; the deserialized constant is then obtained by calling the static 188 * method <code>Enum.valueOf(Class, String)</code> with the enum constant's 189 * base type and the received constant name as arguments. Like other 190 * serializable or externalizable objects, enum constants can function as the 191 * targets of back references appearing subsequently in the serialization 192 * stream. The process by which enum constants are deserialized cannot be 193 * customized: any class-specific readObject, readObjectNoData, and readResolve 194 * methods defined by enum types are ignored during deserialization. 195 * Similarly, any serialPersistentFields or serialVersionUID field declarations 196 * are also ignored--all enum types have a fixed serialVersionUID of 0L. 197 * 198 * @author Mike Warres 199 * @author Roger Riggs 200 * @see java.io.DataInput 201 * @see java.io.ObjectOutputStream 202 * @see java.io.Serializable 203 * @see <a href="../../../platform/serialization/spec/input.html"> Object Serialization Specification, Section 3, Object Input Classes</a> 204 * @since 1.1 205 */ 206 public class ObjectInputStream 207 extends InputStream implements ObjectInput, ObjectStreamConstants 208 { 209 /** handle value representing null */ 210 private static final int NULL_HANDLE = -1; 211 212 /** marker for unshared objects in internal handle table */ 213 private static final Object unsharedMarker = new Object(); 214 215 /** table mapping primitive type names to corresponding class objects */ 216 private static final HashMap<String, Class<?>> primClasses 217 = new HashMap<>(8, 1.0F); 218 static { 219 primClasses.put("boolean", boolean.class); 220 primClasses.put("byte", byte.class); 221 primClasses.put("char", char.class); 222 primClasses.put("short", short.class); 223 primClasses.put("int", int.class); 224 primClasses.put("long", long.class); 225 primClasses.put("float", float.class); 226 primClasses.put("double", double.class); 227 primClasses.put("void", void.class); 228 } 229 230 private static class Caches { 231 /** cache of subclass security audit results */ 232 static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits = 233 new ConcurrentHashMap<>(); 234 235 /** queue for WeakReferences to audited subclasses */ 236 static final ReferenceQueue<Class<?>> subclassAuditsQueue = 237 new ReferenceQueue<>(); 238 } 239 240 /** filter stream for handling block data conversion */ 241 private final BlockDataInputStream bin; 242 /** validation callback list */ 243 private final ValidationList vlist; 244 /** recursion depth */ 245 private int depth; 246 /** whether stream is closed */ 247 private boolean closed; 248 249 /** wire handle -> obj/exception map */ 250 private final HandleTable handles; 251 /** scratch field for passing handle values up/down call stack */ 252 private int passHandle = NULL_HANDLE; 253 /** flag set when at end of field value block with no TC_ENDBLOCKDATA */ 254 private boolean defaultDataEnd = false; 255 256 /** if true, invoke readObjectOverride() instead of readObject() */ 257 private final boolean enableOverride; 258 /** if true, invoke resolveObject() */ 259 private boolean enableResolve; 260 261 /** 262 * Context during upcalls to class-defined readObject methods; holds 263 * object currently being deserialized and descriptor for current class. 264 * Null when not during readObject upcall. 265 */ 266 private SerialCallbackContext curContext; 267 268 /** 269 * Creates an ObjectInputStream that reads from the specified InputStream. 270 * A serialization stream header is read from the stream and verified. 271 * This constructor will block until the corresponding ObjectOutputStream 272 * has written and flushed the header. 273 * 274 * <p>If a security manager is installed, this constructor will check for 275 * the "enableSubclassImplementation" SerializablePermission when invoked 276 * directly or indirectly by the constructor of a subclass which overrides 277 * the ObjectInputStream.readFields or ObjectInputStream.readUnshared 278 * methods. 279 * 280 * @param in input stream to read from 281 * @throws StreamCorruptedException if the stream header is incorrect 282 * @throws IOException if an I/O error occurs while reading stream header 283 * @throws SecurityException if untrusted subclass illegally overrides 284 * security-sensitive methods 285 * @throws NullPointerException if <code>in</code> is <code>null</code> 286 * @see ObjectInputStream#ObjectInputStream() 287 * @see ObjectInputStream#readFields() 288 * @see ObjectOutputStream#ObjectOutputStream(OutputStream) 289 */ 290 public ObjectInputStream(InputStream in) throws IOException { 291 verifySubclass(); 292 bin = new BlockDataInputStream(in); 293 handles = new HandleTable(10); 294 vlist = new ValidationList(); 295 enableOverride = false; 296 readStreamHeader(); 297 bin.setBlockDataMode(true); 298 } 299 300 /** 301 * Provide a way for subclasses that are completely reimplementing 302 * ObjectInputStream to not have to allocate private data just used by this 303 * implementation of ObjectInputStream. 304 * 305 * <p>If there is a security manager installed, this method first calls the 306 * security manager's <code>checkPermission</code> method with the 307 * <code>SerializablePermission("enableSubclassImplementation")</code> 308 * permission to ensure it's ok to enable subclassing. 309 * 310 * @throws SecurityException if a security manager exists and its 311 * <code>checkPermission</code> method denies enabling 312 * subclassing. 313 * @throws IOException if an I/O error occurs while creating this stream 314 * @see SecurityManager#checkPermission 315 * @see java.io.SerializablePermission 316 */ 317 protected ObjectInputStream() throws IOException, SecurityException { 318 SecurityManager sm = System.getSecurityManager(); 319 if (sm != null) { 320 sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION); 321 } 322 bin = null; 323 handles = null; 324 vlist = null; 325 enableOverride = true; 326 } 327 328 /** 329 * Read an object from the ObjectInputStream. The class of the object, the 330 * signature of the class, and the values of the non-transient and 331 * non-static fields of the class and all of its supertypes are read. 332 * Default deserializing for a class can be overriden using the writeObject 333 * and readObject methods. Objects referenced by this object are read 334 * transitively so that a complete equivalent graph of objects is 335 * reconstructed by readObject. 336 * 337 * <p>The root object is completely restored when all of its fields and the 338 * objects it references are completely restored. At this point the object 339 * validation callbacks are executed in order based on their registered 340 * priorities. The callbacks are registered by objects (in the readObject 341 * special methods) as they are individually restored. 342 * 343 * <p>Exceptions are thrown for problems with the InputStream and for 344 * classes that should not be deserialized. All exceptions are fatal to 345 * the InputStream and leave it in an indeterminate state; it is up to the 346 * caller to ignore or recover the stream state. 347 * 348 * @throws ClassNotFoundException Class of a serialized object cannot be 349 * found. 350 * @throws InvalidClassException Something is wrong with a class used by 351 * serialization. 352 * @throws StreamCorruptedException Control information in the 353 * stream is inconsistent. 354 * @throws OptionalDataException Primitive data was found in the 355 * stream instead of objects. 356 * @throws IOException Any of the usual Input/Output related exceptions. 357 */ 358 public final Object readObject() 359 throws IOException, ClassNotFoundException 360 { 361 if (enableOverride) { 362 return readObjectOverride(); 363 } 364 365 // if nested read, passHandle contains handle of enclosing object 366 int outerHandle = passHandle; 367 try { 368 Object obj = readObject0(false); 369 handles.markDependency(outerHandle, passHandle); 370 ClassNotFoundException ex = handles.lookupException(passHandle); 371 if (ex != null) { 372 throw ex; 373 } 374 if (depth == 0) { 375 vlist.doCallbacks(); 376 freeze(); 377 } 378 return obj; 379 } finally { 380 passHandle = outerHandle; 381 if (closed && depth == 0) { 382 clear(); 383 } 384 } 385 } 386 387 /** 388 * This method is called by trusted subclasses of ObjectOutputStream that 389 * constructed ObjectOutputStream using the protected no-arg constructor. 390 * The subclass is expected to provide an override method with the modifier 391 * "final". 392 * 393 * @return the Object read from the stream. 394 * @throws ClassNotFoundException Class definition of a serialized object 395 * cannot be found. 396 * @throws OptionalDataException Primitive data was found in the stream 397 * instead of objects. 398 * @throws IOException if I/O errors occurred while reading from the 399 * underlying stream 400 * @see #ObjectInputStream() 401 * @see #readObject() 402 * @since 1.2 403 */ 404 protected Object readObjectOverride() 405 throws IOException, ClassNotFoundException 406 { 407 return null; 408 } 409 410 /** 411 * Reads an "unshared" object from the ObjectInputStream. This method is 412 * identical to readObject, except that it prevents subsequent calls to 413 * readObject and readUnshared from returning additional references to the 414 * deserialized instance obtained via this call. Specifically: 415 * <ul> 416 * <li>If readUnshared is called to deserialize a back-reference (the 417 * stream representation of an object which has been written 418 * previously to the stream), an ObjectStreamException will be 419 * thrown. 420 * 421 * <li>If readUnshared returns successfully, then any subsequent attempts 422 * to deserialize back-references to the stream handle deserialized 423 * by readUnshared will cause an ObjectStreamException to be thrown. 424 * </ul> 425 * Deserializing an object via readUnshared invalidates the stream handle 426 * associated with the returned object. Note that this in itself does not 427 * always guarantee that the reference returned by readUnshared is unique; 428 * the deserialized object may define a readResolve method which returns an 429 * object visible to other parties, or readUnshared may return a Class 430 * object or enum constant obtainable elsewhere in the stream or through 431 * external means. If the deserialized object defines a readResolve method 432 * and the invocation of that method returns an array, then readUnshared 433 * returns a shallow clone of that array; this guarantees that the returned 434 * array object is unique and cannot be obtained a second time from an 435 * invocation of readObject or readUnshared on the ObjectInputStream, 436 * even if the underlying data stream has been manipulated. 437 * 438 * <p>ObjectInputStream subclasses which override this method can only be 439 * constructed in security contexts possessing the 440 * "enableSubclassImplementation" SerializablePermission; any attempt to 441 * instantiate such a subclass without this permission will cause a 442 * SecurityException to be thrown. 443 * 444 * @return reference to deserialized object 445 * @throws ClassNotFoundException if class of an object to deserialize 446 * cannot be found 447 * @throws StreamCorruptedException if control information in the stream 448 * is inconsistent 449 * @throws ObjectStreamException if object to deserialize has already 450 * appeared in stream 451 * @throws OptionalDataException if primitive data is next in stream 452 * @throws IOException if an I/O error occurs during deserialization 453 * @since 1.4 454 */ 455 public Object readUnshared() throws IOException, ClassNotFoundException { 456 // if nested read, passHandle contains handle of enclosing object 457 int outerHandle = passHandle; 458 try { 459 Object obj = readObject0(true); 460 handles.markDependency(outerHandle, passHandle); 461 ClassNotFoundException ex = handles.lookupException(passHandle); 462 if (ex != null) { 463 throw ex; 464 } 465 if (depth == 0) { 466 vlist.doCallbacks(); 467 freeze(); 468 } 469 return obj; 470 } finally { 471 passHandle = outerHandle; 472 if (closed && depth == 0) { 473 clear(); 474 } 475 } 476 } 477 478 /** 479 * Read the non-static and non-transient fields of the current class from 480 * this stream. This may only be called from the readObject method of the 481 * class being deserialized. It will throw the NotActiveException if it is 482 * called otherwise. 483 * 484 * @throws ClassNotFoundException if the class of a serialized object 485 * could not be found. 486 * @throws IOException if an I/O error occurs. 487 * @throws NotActiveException if the stream is not currently reading 488 * objects. 489 */ 490 public void defaultReadObject() 491 throws IOException, ClassNotFoundException 492 { 493 SerialCallbackContext ctx = curContext; 494 if (ctx == null) { 495 throw new NotActiveException("not in call to readObject"); 496 } 497 Object curObj = ctx.getObj(); 498 ObjectStreamClass curDesc = ctx.getDesc(); 499 bin.setBlockDataMode(false); 500 FieldValues vals = defaultReadFields(curObj, curDesc); 501 if (curObj != null) { 502 defaultCheckFieldValues(curObj, curDesc, vals); 503 defaultSetFieldValues(curObj, curDesc, vals); 504 } 505 bin.setBlockDataMode(true); 506 if (!curDesc.hasWriteObjectData()) { 507 /* 508 * Fix for 4360508: since stream does not contain terminating 509 * TC_ENDBLOCKDATA tag, set flag so that reading code elsewhere 510 * knows to simulate end-of-custom-data behavior. 511 */ 512 defaultDataEnd = true; 513 } 514 ClassNotFoundException ex = handles.lookupException(passHandle); 515 if (ex != null) { 516 throw ex; 517 } 518 } 519 520 /** 521 * Reads the persistent fields from the stream and makes them available by 522 * name. 523 * 524 * @return the <code>GetField</code> object representing the persistent 525 * fields of the object being deserialized 526 * @throws ClassNotFoundException if the class of a serialized object 527 * could not be found. 528 * @throws IOException if an I/O error occurs. 529 * @throws NotActiveException if the stream is not currently reading 530 * objects. 531 * @since 1.2 532 */ 533 public ObjectInputStream.GetField readFields() 534 throws IOException, ClassNotFoundException 535 { 536 SerialCallbackContext ctx = curContext; 537 if (ctx == null) { 538 throw new NotActiveException("not in call to readObject"); 539 } 540 ctx.checkAndSetUsed(); 541 ObjectStreamClass curDesc = ctx.getDesc(); 542 bin.setBlockDataMode(false); 543 GetFieldImpl getField = new GetFieldImpl(curDesc); 544 getField.readFields(); 545 bin.setBlockDataMode(true); 546 if (!curDesc.hasWriteObjectData()) { 547 /* 548 * Fix for 4360508: since stream does not contain terminating 549 * TC_ENDBLOCKDATA tag, set flag so that reading code elsewhere 550 * knows to simulate end-of-custom-data behavior. 551 */ 552 defaultDataEnd = true; 553 } 554 555 return getField; 556 } 557 558 /** 559 * Register an object to be validated before the graph is returned. While 560 * similar to resolveObject these validations are called after the entire 561 * graph has been reconstituted. Typically, a readObject method will 562 * register the object with the stream so that when all of the objects are 563 * restored a final set of validations can be performed. 564 * 565 * @param obj the object to receive the validation callback. 566 * @param prio controls the order of callbacks;zero is a good default. 567 * Use higher numbers to be called back earlier, lower numbers for 568 * later callbacks. Within a priority, callbacks are processed in 569 * no particular order. 570 * @throws NotActiveException The stream is not currently reading objects 571 * so it is invalid to register a callback. 572 * @throws InvalidObjectException The validation object is null. 573 */ 574 public void registerValidation(ObjectInputValidation obj, int prio) 575 throws NotActiveException, InvalidObjectException 576 { 577 if (depth == 0) { 578 throw new NotActiveException("stream inactive"); 579 } 580 vlist.register(obj, prio); 581 } 582 583 /** 584 * Load the local class equivalent of the specified stream class 585 * description. Subclasses may implement this method to allow classes to 586 * be fetched from an alternate source. 587 * 588 * <p>The corresponding method in <code>ObjectOutputStream</code> is 589 * <code>annotateClass</code>. This method will be invoked only once for 590 * each unique class in the stream. This method can be implemented by 591 * subclasses to use an alternate loading mechanism but must return a 592 * <code>Class</code> object. Once returned, if the class is not an array 593 * class, its serialVersionUID is compared to the serialVersionUID of the 594 * serialized class, and if there is a mismatch, the deserialization fails 595 * and an {@link InvalidClassException} is thrown. 596 * 597 * <p>The default implementation of this method in 598 * <code>ObjectInputStream</code> returns the result of calling 599 * <pre> 600 * Class.forName(desc.getName(), false, loader) 601 * </pre> 602 * where <code>loader</code> is determined as follows: if there is a 603 * method on the current thread's stack whose declaring class was 604 * defined by a user-defined class loader (and was not a generated to 605 * implement reflective invocations), then <code>loader</code> is class 606 * loader corresponding to the closest such method to the currently 607 * executing frame; otherwise, <code>loader</code> is 608 * <code>null</code>. If this call results in a 609 * <code>ClassNotFoundException</code> and the name of the passed 610 * <code>ObjectStreamClass</code> instance is the Java language keyword 611 * for a primitive type or void, then the <code>Class</code> object 612 * representing that primitive type or void will be returned 613 * (e.g., an <code>ObjectStreamClass</code> with the name 614 * <code>"int"</code> will be resolved to <code>Integer.TYPE</code>). 615 * Otherwise, the <code>ClassNotFoundException</code> will be thrown to 616 * the caller of this method. 617 * 618 * @param desc an instance of class <code>ObjectStreamClass</code> 619 * @return a <code>Class</code> object corresponding to <code>desc</code> 620 * @throws IOException any of the usual Input/Output exceptions. 621 * @throws ClassNotFoundException if class of a serialized object cannot 622 * be found. 623 */ 624 protected Class<?> resolveClass(ObjectStreamClass desc) 625 throws IOException, ClassNotFoundException 626 { 627 String name = desc.getName(); 628 try { 629 return Class.forName(name, false, latestUserDefinedLoader()); 630 } catch (ClassNotFoundException ex) { 631 Class<?> cl = primClasses.get(name); 632 if (cl != null) { 633 return cl; 634 } else { 635 throw ex; 636 } 637 } 638 } 639 640 /** 641 * Returns a proxy class that implements the interfaces named in a proxy 642 * class descriptor; subclasses may implement this method to read custom 643 * data from the stream along with the descriptors for dynamic proxy 644 * classes, allowing them to use an alternate loading mechanism for the 645 * interfaces and the proxy class. 646 * 647 * <p>This method is called exactly once for each unique proxy class 648 * descriptor in the stream. 649 * 650 * <p>The corresponding method in <code>ObjectOutputStream</code> is 651 * <code>annotateProxyClass</code>. For a given subclass of 652 * <code>ObjectInputStream</code> that overrides this method, the 653 * <code>annotateProxyClass</code> method in the corresponding subclass of 654 * <code>ObjectOutputStream</code> must write any data or objects read by 655 * this method. 656 * 657 * <p>The default implementation of this method in 658 * <code>ObjectInputStream</code> returns the result of calling 659 * <code>Proxy.getProxyClass</code> with the list of <code>Class</code> 660 * objects for the interfaces that are named in the <code>interfaces</code> 661 * parameter. The <code>Class</code> object for each interface name 662 * <code>i</code> is the value returned by calling 663 * <pre> 664 * Class.forName(i, false, loader) 665 * </pre> 666 * where <code>loader</code> is that of the first non-<code>null</code> 667 * class loader up the execution stack, or <code>null</code> if no 668 * non-<code>null</code> class loaders are on the stack (the same class 669 * loader choice used by the <code>resolveClass</code> method). Unless any 670 * of the resolved interfaces are non-public, this same value of 671 * <code>loader</code> is also the class loader passed to 672 * <code>Proxy.getProxyClass</code>; if non-public interfaces are present, 673 * their class loader is passed instead (if more than one non-public 674 * interface class loader is encountered, an 675 * <code>IllegalAccessError</code> is thrown). 676 * If <code>Proxy.getProxyClass</code> throws an 677 * <code>IllegalArgumentException</code>, <code>resolveProxyClass</code> 678 * will throw a <code>ClassNotFoundException</code> containing the 679 * <code>IllegalArgumentException</code>. 680 * 681 * @param interfaces the list of interface names that were 682 * deserialized in the proxy class descriptor 683 * @return a proxy class for the specified interfaces 684 * @throws IOException any exception thrown by the underlying 685 * <code>InputStream</code> 686 * @throws ClassNotFoundException if the proxy class or any of the 687 * named interfaces could not be found 688 * @see ObjectOutputStream#annotateProxyClass(Class) 689 * @since 1.3 690 */ 691 protected Class<?> resolveProxyClass(String[] interfaces) 692 throws IOException, ClassNotFoundException 693 { 694 ClassLoader latestLoader = latestUserDefinedLoader(); 695 ClassLoader nonPublicLoader = null; 696 boolean hasNonPublicInterface = false; 697 698 // define proxy in class loader of non-public interface(s), if any 699 Class<?>[] classObjs = new Class<?>[interfaces.length]; 700 for (int i = 0; i < interfaces.length; i++) { 701 Class<?> cl = Class.forName(interfaces[i], false, latestLoader); 702 if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { 703 if (hasNonPublicInterface) { 704 if (nonPublicLoader != cl.getClassLoader()) { 705 throw new IllegalAccessError( 706 "conflicting non-public interface class loaders"); 707 } 708 } else { 709 nonPublicLoader = cl.getClassLoader(); 710 hasNonPublicInterface = true; 711 } 712 } 713 classObjs[i] = cl; 714 } 715 try { 716 return Proxy.getProxyClass( 717 hasNonPublicInterface ? nonPublicLoader : latestLoader, 718 classObjs); 719 } catch (IllegalArgumentException e) { 720 throw new ClassNotFoundException(null, e); 721 } 722 } 723 724 /** 725 * This method will allow trusted subclasses of ObjectInputStream to 726 * substitute one object for another during deserialization. Replacing 727 * objects is disabled until enableResolveObject is called. The 728 * enableResolveObject method checks that the stream requesting to resolve 729 * object can be trusted. Every reference to serializable objects is passed 730 * to resolveObject. To insure that the private state of objects is not 731 * unintentionally exposed only trusted streams may use resolveObject. 732 * 733 * <p>This method is called after an object has been read but before it is 734 * returned from readObject. The default resolveObject method just returns 735 * the same object. 736 * 737 * <p>When a subclass is replacing objects it must insure that the 738 * substituted object is compatible with every field where the reference 739 * will be stored. Objects whose type is not a subclass of the type of the 740 * field or array element abort the serialization by raising an exception 741 * and the object is not be stored. 742 * 743 * <p>This method is called only once when each object is first 744 * encountered. All subsequent references to the object will be redirected 745 * to the new object. 746 * 747 * @param obj object to be substituted 748 * @return the substituted object 749 * @throws IOException Any of the usual Input/Output exceptions. 750 */ 751 protected Object resolveObject(Object obj) throws IOException { 752 return obj; 753 } 754 755 /** 756 * Enable the stream to allow objects read from the stream to be replaced. 757 * When enabled, the resolveObject method is called for every object being 758 * deserialized. 759 * 760 * <p>If <i>enable</i> is true, and there is a security manager installed, 761 * this method first calls the security manager's 762 * <code>checkPermission</code> method with the 763 * <code>SerializablePermission("enableSubstitution")</code> permission to 764 * ensure it's ok to enable the stream to allow objects read from the 765 * stream to be replaced. 766 * 767 * @param enable true for enabling use of <code>resolveObject</code> for 768 * every object being deserialized 769 * @return the previous setting before this method was invoked 770 * @throws SecurityException if a security manager exists and its 771 * <code>checkPermission</code> method denies enabling the stream 772 * to allow objects read from the stream to be replaced. 773 * @see SecurityManager#checkPermission 774 * @see java.io.SerializablePermission 775 */ 776 protected boolean enableResolveObject(boolean enable) 777 throws SecurityException 778 { 779 if (enable == enableResolve) { 780 return enable; 781 } 782 if (enable) { 783 SecurityManager sm = System.getSecurityManager(); 784 if (sm != null) { 785 sm.checkPermission(SUBSTITUTION_PERMISSION); 786 } 787 } 788 enableResolve = enable; 789 return !enableResolve; 790 } 791 792 /** 793 * The readStreamHeader method is provided to allow subclasses to read and 794 * verify their own stream headers. It reads and verifies the magic number 795 * and version number. 796 * 797 * @throws IOException if there are I/O errors while reading from the 798 * underlying <code>InputStream</code> 799 * @throws StreamCorruptedException if control information in the stream 800 * is inconsistent 801 */ 802 protected void readStreamHeader() 803 throws IOException, StreamCorruptedException 804 { 805 short s0 = bin.readShort(); 806 short s1 = bin.readShort(); 807 if (s0 != STREAM_MAGIC || s1 != STREAM_VERSION) { 808 throw new StreamCorruptedException( 809 String.format("invalid stream header: %04X%04X", s0, s1)); 810 } 811 } 812 813 /** 814 * Read a class descriptor from the serialization stream. This method is 815 * called when the ObjectInputStream expects a class descriptor as the next 816 * item in the serialization stream. Subclasses of ObjectInputStream may 817 * override this method to read in class descriptors that have been written 818 * in non-standard formats (by subclasses of ObjectOutputStream which have 819 * overridden the <code>writeClassDescriptor</code> method). By default, 820 * this method reads class descriptors according to the format defined in 821 * the Object Serialization specification. 822 * 823 * @return the class descriptor read 824 * @throws IOException If an I/O error has occurred. 825 * @throws ClassNotFoundException If the Class of a serialized object used 826 * in the class descriptor representation cannot be found 827 * @see java.io.ObjectOutputStream#writeClassDescriptor(java.io.ObjectStreamClass) 828 * @since 1.3 829 */ 830 protected ObjectStreamClass readClassDescriptor() 831 throws IOException, ClassNotFoundException 832 { 833 ObjectStreamClass desc = new ObjectStreamClass(); 834 desc.readNonProxy(this); 835 return desc; 836 } 837 838 /** 839 * Reads a byte of data. This method will block if no input is available. 840 * 841 * @return the byte read, or -1 if the end of the stream is reached. 842 * @throws IOException If an I/O error has occurred. 843 */ 844 public int read() throws IOException { 845 return bin.read(); 846 } 847 848 /** 849 * Reads into an array of bytes. This method will block until some input 850 * is available. Consider using java.io.DataInputStream.readFully to read 851 * exactly 'length' bytes. 852 * 853 * @param buf the buffer into which the data is read 854 * @param off the start offset of the data 855 * @param len the maximum number of bytes read 856 * @return the actual number of bytes read, -1 is returned when the end of 857 * the stream is reached. 858 * @throws IOException If an I/O error has occurred. 859 * @see java.io.DataInputStream#readFully(byte[],int,int) 860 */ 861 public int read(byte[] buf, int off, int len) throws IOException { 862 if (buf == null) { 863 throw new NullPointerException(); 864 } 865 int endoff = off + len; 866 if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) { 867 throw new IndexOutOfBoundsException(); 868 } 869 return bin.read(buf, off, len, false); 870 } 871 872 /** 873 * Returns the number of bytes that can be read without blocking. 874 * 875 * @return the number of available bytes. 876 * @throws IOException if there are I/O errors while reading from the 877 * underlying <code>InputStream</code> 878 */ 879 public int available() throws IOException { 880 return bin.available(); 881 } 882 883 /** 884 * Closes the input stream. Must be called to release any resources 885 * associated with the stream. 886 * 887 * @throws IOException If an I/O error has occurred. 888 */ 889 public void close() throws IOException { 890 /* 891 * Even if stream already closed, propagate redundant close to 892 * underlying stream to stay consistent with previous implementations. 893 */ 894 closed = true; 895 if (depth == 0) { 896 clear(); 897 } 898 bin.close(); 899 } 900 901 /** 902 * Reads in a boolean. 903 * 904 * @return the boolean read. 905 * @throws EOFException If end of file is reached. 906 * @throws IOException If other I/O error has occurred. 907 */ 908 public boolean readBoolean() throws IOException { 909 return bin.readBoolean(); 910 } 911 912 /** 913 * Reads an 8 bit byte. 914 * 915 * @return the 8 bit byte read. 916 * @throws EOFException If end of file is reached. 917 * @throws IOException If other I/O error has occurred. 918 */ 919 public byte readByte() throws IOException { 920 return bin.readByte(); 921 } 922 923 /** 924 * Reads an unsigned 8 bit byte. 925 * 926 * @return the 8 bit byte read. 927 * @throws EOFException If end of file is reached. 928 * @throws IOException If other I/O error has occurred. 929 */ 930 public int readUnsignedByte() throws IOException { 931 return bin.readUnsignedByte(); 932 } 933 934 /** 935 * Reads a 16 bit char. 936 * 937 * @return the 16 bit char read. 938 * @throws EOFException If end of file is reached. 939 * @throws IOException If other I/O error has occurred. 940 */ 941 public char readChar() throws IOException { 942 return bin.readChar(); 943 } 944 945 /** 946 * Reads a 16 bit short. 947 * 948 * @return the 16 bit short read. 949 * @throws EOFException If end of file is reached. 950 * @throws IOException If other I/O error has occurred. 951 */ 952 public short readShort() throws IOException { 953 return bin.readShort(); 954 } 955 956 /** 957 * Reads an unsigned 16 bit short. 958 * 959 * @return the 16 bit short read. 960 * @throws EOFException If end of file is reached. 961 * @throws IOException If other I/O error has occurred. 962 */ 963 public int readUnsignedShort() throws IOException { 964 return bin.readUnsignedShort(); 965 } 966 967 /** 968 * Reads a 32 bit int. 969 * 970 * @return the 32 bit integer read. 971 * @throws EOFException If end of file is reached. 972 * @throws IOException If other I/O error has occurred. 973 */ 974 public int readInt() throws IOException { 975 return bin.readInt(); 976 } 977 978 /** 979 * Reads a 64 bit long. 980 * 981 * @return the read 64 bit long. 982 * @throws EOFException If end of file is reached. 983 * @throws IOException If other I/O error has occurred. 984 */ 985 public long readLong() throws IOException { 986 return bin.readLong(); 987 } 988 989 /** 990 * Reads a 32 bit float. 991 * 992 * @return the 32 bit float read. 993 * @throws EOFException If end of file is reached. 994 * @throws IOException If other I/O error has occurred. 995 */ 996 public float readFloat() throws IOException { 997 return bin.readFloat(); 998 } 999 1000 /** 1001 * Reads a 64 bit double. 1002 * 1003 * @return the 64 bit double read. 1004 * @throws EOFException If end of file is reached. 1005 * @throws IOException If other I/O error has occurred. 1006 */ 1007 public double readDouble() throws IOException { 1008 return bin.readDouble(); 1009 } 1010 1011 /** 1012 * Reads bytes, blocking until all bytes are read. 1013 * 1014 * @param buf the buffer into which the data is read 1015 * @throws EOFException If end of file is reached. 1016 * @throws IOException If other I/O error has occurred. 1017 */ 1018 public void readFully(byte[] buf) throws IOException { 1019 bin.readFully(buf, 0, buf.length, false); 1020 } 1021 1022 /** 1023 * Reads bytes, blocking until all bytes are read. 1024 * 1025 * @param buf the buffer into which the data is read 1026 * @param off the start offset of the data 1027 * @param len the maximum number of bytes to read 1028 * @throws EOFException If end of file is reached. 1029 * @throws IOException If other I/O error has occurred. 1030 */ 1031 public void readFully(byte[] buf, int off, int len) throws IOException { 1032 int endoff = off + len; 1033 if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) { 1034 throw new IndexOutOfBoundsException(); 1035 } 1036 bin.readFully(buf, off, len, false); 1037 } 1038 1039 /** 1040 * Skips bytes. 1041 * 1042 * @param len the number of bytes to be skipped 1043 * @return the actual number of bytes skipped. 1044 * @throws IOException If an I/O error has occurred. 1045 */ 1046 public int skipBytes(int len) throws IOException { 1047 return bin.skipBytes(len); 1048 } 1049 1050 /** 1051 * Reads in a line that has been terminated by a \n, \r, \r\n or EOF. 1052 * 1053 * @return a String copy of the line. 1054 * @throws IOException if there are I/O errors while reading from the 1055 * underlying <code>InputStream</code> 1056 * @deprecated This method does not properly convert bytes to characters. 1057 * see DataInputStream for the details and alternatives. 1058 */ 1059 @Deprecated 1060 public String readLine() throws IOException { 1061 return bin.readLine(); 1062 } 1063 1064 /** 1065 * Reads a String in 1066 * <a href="DataInput.html#modified-utf-8">modified UTF-8</a> 1067 * format. 1068 * 1069 * @return the String. 1070 * @throws IOException if there are I/O errors while reading from the 1071 * underlying <code>InputStream</code> 1072 * @throws UTFDataFormatException if read bytes do not represent a valid 1073 * modified UTF-8 encoding of a string 1074 */ 1075 public String readUTF() throws IOException { 1076 return bin.readUTF(); 1077 } 1078 1079 /** 1080 * Provide access to the persistent fields read from the input stream. 1081 */ 1082 public static abstract class GetField { 1083 1084 /** 1085 * Get the ObjectStreamClass that describes the fields in the stream. 1086 * 1087 * @return the descriptor class that describes the serializable fields 1088 */ 1089 public abstract ObjectStreamClass getObjectStreamClass(); 1090 1091 /** 1092 * Return true if the named field is defaulted and has no value in this 1093 * stream. 1094 * 1095 * @param name the name of the field 1096 * @return true, if and only if the named field is defaulted 1097 * @throws IOException if there are I/O errors while reading from 1098 * the underlying <code>InputStream</code> 1099 * @throws IllegalArgumentException if <code>name</code> does not 1100 * correspond to a serializable field 1101 */ 1102 public abstract boolean defaulted(String name) throws IOException; 1103 1104 /** 1105 * Get the value of the named boolean field from the persistent field. 1106 * 1107 * @param name the name of the field 1108 * @param val the default value to use if <code>name</code> does not 1109 * have a value 1110 * @return the value of the named <code>boolean</code> field 1111 * @throws IOException if there are I/O errors while reading from the 1112 * underlying <code>InputStream</code> 1113 * @throws IllegalArgumentException if type of <code>name</code> is 1114 * not serializable or if the field type is incorrect 1115 */ 1116 public abstract boolean get(String name, boolean val) 1117 throws IOException; 1118 1119 /** 1120 * Get the value of the named byte field from the persistent field. 1121 * 1122 * @param name the name of the field 1123 * @param val the default value to use if <code>name</code> does not 1124 * have a value 1125 * @return the value of the named <code>byte</code> field 1126 * @throws IOException if there are I/O errors while reading from the 1127 * underlying <code>InputStream</code> 1128 * @throws IllegalArgumentException if type of <code>name</code> is 1129 * not serializable or if the field type is incorrect 1130 */ 1131 public abstract byte get(String name, byte val) throws IOException; 1132 1133 /** 1134 * Get the value of the named char field from the persistent field. 1135 * 1136 * @param name the name of the field 1137 * @param val the default value to use if <code>name</code> does not 1138 * have a value 1139 * @return the value of the named <code>char</code> field 1140 * @throws IOException if there are I/O errors while reading from the 1141 * underlying <code>InputStream</code> 1142 * @throws IllegalArgumentException if type of <code>name</code> is 1143 * not serializable or if the field type is incorrect 1144 */ 1145 public abstract char get(String name, char val) throws IOException; 1146 1147 /** 1148 * Get the value of the named short field from the persistent field. 1149 * 1150 * @param name the name of the field 1151 * @param val the default value to use if <code>name</code> does not 1152 * have a value 1153 * @return the value of the named <code>short</code> field 1154 * @throws IOException if there are I/O errors while reading from the 1155 * underlying <code>InputStream</code> 1156 * @throws IllegalArgumentException if type of <code>name</code> is 1157 * not serializable or if the field type is incorrect 1158 */ 1159 public abstract short get(String name, short val) throws IOException; 1160 1161 /** 1162 * Get the value of the named int field from the persistent field. 1163 * 1164 * @param name the name of the field 1165 * @param val the default value to use if <code>name</code> does not 1166 * have a value 1167 * @return the value of the named <code>int</code> field 1168 * @throws IOException if there are I/O errors while reading from the 1169 * underlying <code>InputStream</code> 1170 * @throws IllegalArgumentException if type of <code>name</code> is 1171 * not serializable or if the field type is incorrect 1172 */ 1173 public abstract int get(String name, int val) throws IOException; 1174 1175 /** 1176 * Get the value of the named long field from the persistent field. 1177 * 1178 * @param name the name of the field 1179 * @param val the default value to use if <code>name</code> does not 1180 * have a value 1181 * @return the value of the named <code>long</code> field 1182 * @throws IOException if there are I/O errors while reading from the 1183 * underlying <code>InputStream</code> 1184 * @throws IllegalArgumentException if type of <code>name</code> is 1185 * not serializable or if the field type is incorrect 1186 */ 1187 public abstract long get(String name, long val) throws IOException; 1188 1189 /** 1190 * Get the value of the named float field from the persistent field. 1191 * 1192 * @param name the name of the field 1193 * @param val the default value to use if <code>name</code> does not 1194 * have a value 1195 * @return the value of the named <code>float</code> field 1196 * @throws IOException if there are I/O errors while reading from the 1197 * underlying <code>InputStream</code> 1198 * @throws IllegalArgumentException if type of <code>name</code> is 1199 * not serializable or if the field type is incorrect 1200 */ 1201 public abstract float get(String name, float val) throws IOException; 1202 1203 /** 1204 * Get the value of the named double field from the persistent field. 1205 * 1206 * @param name the name of the field 1207 * @param val the default value to use if <code>name</code> does not 1208 * have a value 1209 * @return the value of the named <code>double</code> field 1210 * @throws IOException if there are I/O errors while reading from the 1211 * underlying <code>InputStream</code> 1212 * @throws IllegalArgumentException if type of <code>name</code> is 1213 * not serializable or if the field type is incorrect 1214 */ 1215 public abstract double get(String name, double val) throws IOException; 1216 1217 /** 1218 * Get the value of the named Object field from the persistent field. 1219 * 1220 * @param name the name of the field 1221 * @param val the default value to use if <code>name</code> does not 1222 * have a value 1223 * @return the value of the named <code>Object</code> field 1224 * @throws IOException if there are I/O errors while reading from the 1225 * underlying <code>InputStream</code> 1226 * @throws IllegalArgumentException if type of <code>name</code> is 1227 * not serializable or if the field type is incorrect 1228 */ 1229 public abstract Object get(String name, Object val) throws IOException; 1230 } 1231 1232 /** 1233 * Verifies that this (possibly subclass) instance can be constructed 1234 * without violating security constraints: the subclass must not override 1235 * security-sensitive non-final methods, or else the 1236 * "enableSubclassImplementation" SerializablePermission is checked. 1237 */ 1238 private void verifySubclass() { 1239 Class<?> cl = getClass(); 1240 if (cl == ObjectInputStream.class) { 1241 return; 1242 } 1243 SecurityManager sm = System.getSecurityManager(); 1244 if (sm == null) { 1245 return; 1246 } 1247 processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits); 1248 WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue); 1249 Boolean result = Caches.subclassAudits.get(key); 1250 if (result == null) { 1251 result = Boolean.valueOf(auditSubclass(cl)); 1252 Caches.subclassAudits.putIfAbsent(key, result); 1253 } 1254 if (result.booleanValue()) { 1255 return; 1256 } 1257 sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION); 1258 } 1259 1260 /** 1261 * Performs reflective checks on given subclass to verify that it doesn't 1262 * override security-sensitive non-final methods. Returns true if subclass 1263 * is "safe", false otherwise. 1264 */ 1265 private static boolean auditSubclass(final Class<?> subcl) { 1266 Boolean result = AccessController.doPrivileged( 1267 new PrivilegedAction<>() { 1268 public Boolean run() { 1269 for (Class<?> cl = subcl; 1270 cl != ObjectInputStream.class; 1271 cl = cl.getSuperclass()) 1272 { 1273 try { 1274 cl.getDeclaredMethod( 1275 "readUnshared", (Class[]) null); 1276 return Boolean.FALSE; 1277 } catch (NoSuchMethodException ex) { 1278 } 1279 try { 1280 cl.getDeclaredMethod("readFields", (Class[]) null); 1281 return Boolean.FALSE; 1282 } catch (NoSuchMethodException ex) { 1283 } 1284 } 1285 return Boolean.TRUE; 1286 } 1287 } 1288 ); 1289 return result.booleanValue(); 1290 } 1291 1292 /** 1293 * Clears internal data structures. 1294 */ 1295 private void clear() { 1296 handles.clear(); 1297 vlist.clear(); 1298 } 1299 1300 /** 1301 * Underlying readObject implementation. 1302 */ 1303 private Object readObject0(boolean unshared) throws IOException { 1304 boolean oldMode = bin.getBlockDataMode(); 1305 if (oldMode) { 1306 int remain = bin.currentBlockRemaining(); 1307 if (remain > 0) { 1308 throw new OptionalDataException(remain); 1309 } else if (defaultDataEnd) { 1310 /* 1311 * Fix for 4360508: stream is currently at the end of a field 1312 * value block written via default serialization; since there 1313 * is no terminating TC_ENDBLOCKDATA tag, simulate 1314 * end-of-custom-data behavior explicitly. 1315 */ 1316 throw new OptionalDataException(true); 1317 } 1318 bin.setBlockDataMode(false); 1319 } 1320 1321 byte tc; 1322 while ((tc = bin.peekByte()) == TC_RESET) { 1323 bin.readByte(); 1324 handleReset(); 1325 } 1326 1327 depth++; 1328 try { 1329 switch (tc) { 1330 case TC_NULL: 1331 return readNull(); 1332 1333 case TC_REFERENCE: 1334 return readHandle(unshared); 1335 1336 case TC_CLASS: 1337 return readClass(unshared); 1338 1339 case TC_CLASSDESC: 1340 case TC_PROXYCLASSDESC: 1341 return readClassDesc(unshared); 1342 1343 case TC_STRING: 1344 case TC_LONGSTRING: 1345 return checkResolve(readString(unshared)); 1346 1347 case TC_ARRAY: 1348 return checkResolve(readArray(unshared)); 1349 1350 case TC_ENUM: 1351 return checkResolve(readEnum(unshared)); 1352 1353 case TC_OBJECT: 1354 return checkResolve(readOrdinaryObject(unshared)); 1355 1356 case TC_EXCEPTION: 1357 IOException ex = readFatalException(); 1358 throw new WriteAbortedException("writing aborted", ex); 1359 1360 case TC_BLOCKDATA: 1361 case TC_BLOCKDATALONG: 1362 if (oldMode) { 1363 bin.setBlockDataMode(true); 1364 bin.peek(); // force header read 1365 throw new OptionalDataException( 1366 bin.currentBlockRemaining()); 1367 } else { 1368 throw new StreamCorruptedException( 1369 "unexpected block data"); 1370 } 1371 1372 case TC_ENDBLOCKDATA: 1373 if (oldMode) { 1374 throw new OptionalDataException(true); 1375 } else { 1376 throw new StreamCorruptedException( 1377 "unexpected end of block data"); 1378 } 1379 1380 default: 1381 throw new StreamCorruptedException( 1382 String.format("invalid type code: %02X", tc)); 1383 } 1384 } finally { 1385 depth--; 1386 bin.setBlockDataMode(oldMode); 1387 } 1388 } 1389 1390 /** 1391 * If resolveObject has been enabled and given object does not have an 1392 * exception associated with it, calls resolveObject to determine 1393 * replacement for object, and updates handle table accordingly. Returns 1394 * replacement object, or echoes provided object if no replacement 1395 * occurred. Expects that passHandle is set to given object's handle prior 1396 * to calling this method. 1397 */ 1398 private Object checkResolve(Object obj) throws IOException { 1399 if (!enableResolve || handles.lookupException(passHandle) != null) { 1400 return obj; 1401 } 1402 Object rep = resolveObject(obj); 1403 if (rep != obj) { 1404 handles.setObject(passHandle, rep); 1405 } 1406 return rep; 1407 } 1408 1409 /** 1410 * Reads string without allowing it to be replaced in stream. Called from 1411 * within ObjectStreamClass.read(). 1412 */ 1413 String readTypeString() throws IOException { 1414 int oldHandle = passHandle; 1415 try { 1416 byte tc = bin.peekByte(); 1417 switch (tc) { 1418 case TC_NULL: 1419 return (String) readNull(); 1420 1421 case TC_REFERENCE: 1422 return (String) readHandle(false); 1423 1424 case TC_STRING: 1425 case TC_LONGSTRING: 1426 return readString(false); 1427 1428 default: 1429 throw new StreamCorruptedException( 1430 String.format("invalid type code: %02X", tc)); 1431 } 1432 } finally { 1433 passHandle = oldHandle; 1434 } 1435 } 1436 1437 /** 1438 * Reads in null code, sets passHandle to NULL_HANDLE and returns null. 1439 */ 1440 private Object readNull() throws IOException { 1441 if (bin.readByte() != TC_NULL) { 1442 throw new InternalError(); 1443 } 1444 passHandle = NULL_HANDLE; 1445 return null; 1446 } 1447 1448 /** 1449 * Reads in object handle, sets passHandle to the read handle, and returns 1450 * object associated with the handle. 1451 */ 1452 private Object readHandle(boolean unshared) throws IOException { 1453 if (bin.readByte() != TC_REFERENCE) { 1454 throw new InternalError(); 1455 } 1456 passHandle = bin.readInt() - baseWireHandle; 1457 if (passHandle < 0 || passHandle >= handles.size()) { 1458 throw new StreamCorruptedException( 1459 String.format("invalid handle value: %08X", passHandle + 1460 baseWireHandle)); 1461 } 1462 if (unshared) { 1463 // REMIND: what type of exception to throw here? 1464 throw new InvalidObjectException( 1465 "cannot read back reference as unshared"); 1466 } 1467 1468 Object obj = handles.lookupObject(passHandle); 1469 if (obj == unsharedMarker) { 1470 // REMIND: what type of exception to throw here? 1471 throw new InvalidObjectException( 1472 "cannot read back reference to unshared object"); 1473 } 1474 return obj; 1475 } 1476 1477 /** 1478 * Reads in and returns class object. Sets passHandle to class object's 1479 * assigned handle. Returns null if class is unresolvable (in which case a 1480 * ClassNotFoundException will be associated with the class' handle in the 1481 * handle table). 1482 */ 1483 private Class<?> readClass(boolean unshared) throws IOException { 1484 if (bin.readByte() != TC_CLASS) { 1485 throw new InternalError(); 1486 } 1487 ObjectStreamClass desc = readClassDesc(false); 1488 Class<?> cl = desc.forClass(); 1489 passHandle = handles.assign(unshared ? unsharedMarker : cl); 1490 1491 ClassNotFoundException resolveEx = desc.getResolveException(); 1492 if (resolveEx != null) { 1493 handles.markException(passHandle, resolveEx); 1494 } 1495 1496 handles.finish(passHandle); 1497 return cl; 1498 } 1499 1500 /** 1501 * Reads in and returns (possibly null) class descriptor. Sets passHandle 1502 * to class descriptor's assigned handle. If class descriptor cannot be 1503 * resolved to a class in the local VM, a ClassNotFoundException is 1504 * associated with the class descriptor's handle. 1505 */ 1506 private ObjectStreamClass readClassDesc(boolean unshared) 1507 throws IOException 1508 { 1509 byte tc = bin.peekByte(); 1510 switch (tc) { 1511 case TC_NULL: 1512 return (ObjectStreamClass) readNull(); 1513 1514 case TC_REFERENCE: 1515 return (ObjectStreamClass) readHandle(unshared); 1516 1517 case TC_PROXYCLASSDESC: 1518 return readProxyDesc(unshared); 1519 1520 case TC_CLASSDESC: 1521 return readNonProxyDesc(unshared); 1522 1523 default: 1524 throw new StreamCorruptedException( 1525 String.format("invalid type code: %02X", tc)); 1526 } 1527 } 1528 1529 private boolean isCustomSubclass() { 1530 // Return true if this class is a custom subclass of ObjectInputStream 1531 return getClass().getClassLoader() 1532 != ObjectInputStream.class.getClassLoader(); 1533 } 1534 1535 /** 1536 * Reads in and returns class descriptor for a dynamic proxy class. Sets 1537 * passHandle to proxy class descriptor's assigned handle. If proxy class 1538 * descriptor cannot be resolved to a class in the local VM, a 1539 * ClassNotFoundException is associated with the descriptor's handle. 1540 */ 1541 private ObjectStreamClass readProxyDesc(boolean unshared) 1542 throws IOException 1543 { 1544 if (bin.readByte() != TC_PROXYCLASSDESC) { 1545 throw new InternalError(); 1546 } 1547 1548 ObjectStreamClass desc = new ObjectStreamClass(); 1549 int descHandle = handles.assign(unshared ? unsharedMarker : desc); 1550 passHandle = NULL_HANDLE; 1551 1552 int numIfaces = bin.readInt(); 1553 String[] ifaces = new String[numIfaces]; 1554 for (int i = 0; i < numIfaces; i++) { 1555 ifaces[i] = bin.readUTF(); 1556 } 1557 1558 Class<?> cl = null; 1559 ClassNotFoundException resolveEx = null; 1560 bin.setBlockDataMode(true); 1561 try { 1562 if ((cl = resolveProxyClass(ifaces)) == null) { 1563 resolveEx = new ClassNotFoundException("null class"); 1564 } else if (!Proxy.isProxyClass(cl)) { 1565 throw new InvalidClassException("Not a proxy"); 1566 } else { 1567 // ReflectUtil.checkProxyPackageAccess makes a test 1568 // equivalent to isCustomSubclass so there's no need 1569 // to condition this call to isCustomSubclass == true here. 1570 ReflectUtil.checkProxyPackageAccess( 1571 getClass().getClassLoader(), 1572 cl.getInterfaces()); 1573 } 1574 } catch (ClassNotFoundException ex) { 1575 resolveEx = ex; 1576 } 1577 skipCustomData(); 1578 1579 desc.initProxy(cl, resolveEx, readClassDesc(false)); 1580 1581 handles.finish(descHandle); 1582 passHandle = descHandle; 1583 return desc; 1584 } 1585 1586 /** 1587 * Reads in and returns class descriptor for a class that is not a dynamic 1588 * proxy class. Sets passHandle to class descriptor's assigned handle. If 1589 * class descriptor cannot be resolved to a class in the local VM, a 1590 * ClassNotFoundException is associated with the descriptor's handle. 1591 */ 1592 private ObjectStreamClass readNonProxyDesc(boolean unshared) 1593 throws IOException 1594 { 1595 if (bin.readByte() != TC_CLASSDESC) { 1596 throw new InternalError(); 1597 } 1598 1599 ObjectStreamClass desc = new ObjectStreamClass(); 1600 int descHandle = handles.assign(unshared ? unsharedMarker : desc); 1601 passHandle = NULL_HANDLE; 1602 1603 ObjectStreamClass readDesc; 1604 try { 1605 readDesc = readClassDescriptor(); 1606 } catch (ClassNotFoundException ex) { 1607 throw (IOException) new InvalidClassException( 1608 "failed to read class descriptor").initCause(ex); 1609 } 1610 1611 Class<?> cl = null; 1612 ClassNotFoundException resolveEx = null; 1613 bin.setBlockDataMode(true); 1614 final boolean checksRequired = isCustomSubclass(); 1615 try { 1616 if ((cl = resolveClass(readDesc)) == null) { 1617 resolveEx = new ClassNotFoundException("null class"); 1618 } else if (checksRequired) { 1619 ReflectUtil.checkPackageAccess(cl); 1620 } 1621 } catch (ClassNotFoundException ex) { 1622 resolveEx = ex; 1623 } 1624 skipCustomData(); 1625 1626 desc.initNonProxy(readDesc, cl, resolveEx, readClassDesc(false)); 1627 1628 handles.finish(descHandle); 1629 passHandle = descHandle; 1630 return desc; 1631 } 1632 1633 /** 1634 * Reads in and returns new string. Sets passHandle to new string's 1635 * assigned handle. 1636 */ 1637 private String readString(boolean unshared) throws IOException { 1638 String str; 1639 byte tc = bin.readByte(); 1640 switch (tc) { 1641 case TC_STRING: 1642 str = bin.readUTF(); 1643 break; 1644 1645 case TC_LONGSTRING: 1646 str = bin.readLongUTF(); 1647 break; 1648 1649 default: 1650 throw new StreamCorruptedException( 1651 String.format("invalid type code: %02X", tc)); 1652 } 1653 passHandle = handles.assign(unshared ? unsharedMarker : str); 1654 handles.finish(passHandle); 1655 return str; 1656 } 1657 1658 /** 1659 * Reads in and returns array object, or null if array class is 1660 * unresolvable. Sets passHandle to array's assigned handle. 1661 */ 1662 private Object readArray(boolean unshared) throws IOException { 1663 if (bin.readByte() != TC_ARRAY) { 1664 throw new InternalError(); 1665 } 1666 1667 ObjectStreamClass desc = readClassDesc(false); 1668 int len = bin.readInt(); 1669 1670 Object array = null; 1671 Class<?> cl, ccl = null; 1672 if ((cl = desc.forClass()) != null) { 1673 ccl = cl.getComponentType(); 1674 array = Array.newInstance(ccl, len); 1675 } 1676 1677 int arrayHandle = handles.assign(unshared ? unsharedMarker : array); 1678 ClassNotFoundException resolveEx = desc.getResolveException(); 1679 if (resolveEx != null) { 1680 handles.markException(arrayHandle, resolveEx); 1681 } 1682 1683 if (ccl == null) { 1684 for (int i = 0; i < len; i++) { 1685 readObject0(false); 1686 } 1687 } else if (ccl.isPrimitive()) { 1688 if (ccl == Integer.TYPE) { 1689 bin.readInts((int[]) array, 0, len); 1690 } else if (ccl == Byte.TYPE) { 1691 bin.readFully((byte[]) array, 0, len, true); 1692 } else if (ccl == Long.TYPE) { 1693 bin.readLongs((long[]) array, 0, len); 1694 } else if (ccl == Float.TYPE) { 1695 bin.readFloats((float[]) array, 0, len); 1696 } else if (ccl == Double.TYPE) { 1697 bin.readDoubles((double[]) array, 0, len); 1698 } else if (ccl == Short.TYPE) { 1699 bin.readShorts((short[]) array, 0, len); 1700 } else if (ccl == Character.TYPE) { 1701 bin.readChars((char[]) array, 0, len); 1702 } else if (ccl == Boolean.TYPE) { 1703 bin.readBooleans((boolean[]) array, 0, len); 1704 } else { 1705 throw new InternalError(); 1706 } 1707 } else { 1708 Object[] oa = (Object[]) array; 1709 for (int i = 0; i < len; i++) { 1710 oa[i] = readObject0(false); 1711 handles.markDependency(arrayHandle, passHandle); 1712 } 1713 } 1714 1715 handles.finish(arrayHandle); 1716 passHandle = arrayHandle; 1717 return array; 1718 } 1719 1720 /** 1721 * Reads in and returns enum constant, or null if enum type is 1722 * unresolvable. Sets passHandle to enum constant's assigned handle. 1723 */ 1724 private Enum<?> readEnum(boolean unshared) throws IOException { 1725 if (bin.readByte() != TC_ENUM) { 1726 throw new InternalError(); 1727 } 1728 1729 ObjectStreamClass desc = readClassDesc(false); 1730 if (!desc.isEnum()) { 1731 throw new InvalidClassException("non-enum class: " + desc); 1732 } 1733 1734 int enumHandle = handles.assign(unshared ? unsharedMarker : null); 1735 ClassNotFoundException resolveEx = desc.getResolveException(); 1736 if (resolveEx != null) { 1737 handles.markException(enumHandle, resolveEx); 1738 } 1739 1740 String name = readString(false); 1741 Enum<?> result = null; 1742 Class<?> cl = desc.forClass(); 1743 if (cl != null) { 1744 try { 1745 @SuppressWarnings("unchecked") 1746 Enum<?> en = Enum.valueOf((Class)cl, name); 1747 result = en; 1748 } catch (IllegalArgumentException ex) { 1749 throw (IOException) new InvalidObjectException( 1750 "enum constant " + name + " does not exist in " + 1751 cl).initCause(ex); 1752 } 1753 if (!unshared) { 1754 handles.setObject(enumHandle, result); 1755 } 1756 } 1757 1758 handles.finish(enumHandle); 1759 passHandle = enumHandle; 1760 return result; 1761 } 1762 1763 /** 1764 * Reads and returns "ordinary" (i.e., not a String, Class, 1765 * ObjectStreamClass, array, or enum constant) object, or null if object's 1766 * class is unresolvable (in which case a ClassNotFoundException will be 1767 * associated with object's handle). Sets passHandle to object's assigned 1768 * handle. 1769 */ 1770 private Object readOrdinaryObject(boolean unshared) 1771 throws IOException 1772 { 1773 if (bin.readByte() != TC_OBJECT) { 1774 throw new InternalError(); 1775 } 1776 1777 ObjectStreamClass desc = readClassDesc(false); 1778 desc.checkDeserialize(); 1779 1780 Class<?> cl = desc.forClass(); 1781 if (cl == String.class || cl == Class.class 1782 || cl == ObjectStreamClass.class) { 1783 throw new InvalidClassException("invalid class descriptor"); 1784 } 1785 1786 Object obj; 1787 try { 1788 obj = desc.isInstantiable() ? desc.newInstance() : null; 1789 } catch (Exception ex) { 1790 throw (IOException) new InvalidClassException( 1791 desc.forClass().getName(), 1792 "unable to create instance").initCause(ex); 1793 } 1794 1795 passHandle = handles.assign(unshared ? unsharedMarker : obj); 1796 ClassNotFoundException resolveEx = desc.getResolveException(); 1797 if (resolveEx != null) { 1798 handles.markException(passHandle, resolveEx); 1799 } 1800 1801 if (desc.isExternalizable()) { 1802 readExternalData((Externalizable) obj, desc); 1803 } else { 1804 readSerialData(obj, desc); 1805 } 1806 1807 handles.finish(passHandle); 1808 1809 if (obj != null && 1810 handles.lookupException(passHandle) == null && 1811 desc.hasReadResolveMethod()) 1812 { 1813 Object rep = desc.invokeReadResolve(obj); 1814 if (unshared && rep.getClass().isArray()) { 1815 rep = cloneArray(rep); 1816 } 1817 if (rep != obj) { 1818 handles.setObject(passHandle, obj = rep); 1819 } 1820 } 1821 1822 return obj; 1823 } 1824 1825 /** 1826 * If obj is non-null, reads externalizable data by invoking readExternal() 1827 * method of obj; otherwise, attempts to skip over externalizable data. 1828 * Expects that passHandle is set to obj's handle before this method is 1829 * called. 1830 */ 1831 private void readExternalData(Externalizable obj, ObjectStreamClass desc) 1832 throws IOException 1833 { 1834 SerialCallbackContext oldContext = curContext; 1835 curContext = null; 1836 try { 1837 boolean blocked = desc.hasBlockExternalData(); 1838 if (blocked) { 1839 bin.setBlockDataMode(true); 1840 } 1841 if (obj != null) { 1842 try { 1843 obj.readExternal(this); 1844 } catch (ClassNotFoundException ex) { 1845 /* 1846 * In most cases, the handle table has already propagated 1847 * a CNFException to passHandle at this point; this mark 1848 * call is included to address cases where the readExternal 1849 * method has cons'ed and thrown a new CNFException of its 1850 * own. 1851 */ 1852 handles.markException(passHandle, ex); 1853 } 1854 } 1855 if (blocked) { 1856 skipCustomData(); 1857 } 1858 } finally { 1859 curContext = oldContext; 1860 } 1861 /* 1862 * At this point, if the externalizable data was not written in 1863 * block-data form and either the externalizable class doesn't exist 1864 * locally (i.e., obj == null) or readExternal() just threw a 1865 * CNFException, then the stream is probably in an inconsistent state, 1866 * since some (or all) of the externalizable data may not have been 1867 * consumed. Since there's no "correct" action to take in this case, 1868 * we mimic the behavior of past serialization implementations and 1869 * blindly hope that the stream is in sync; if it isn't and additional 1870 * externalizable data remains in the stream, a subsequent read will 1871 * most likely throw a StreamCorruptedException. 1872 */ 1873 } 1874 1875 /** 1876 * Reads (or attempts to skip, if obj is null or is tagged with a 1877 * ClassNotFoundException) instance data for each serializable class of 1878 * object in stream, from superclass to subclass. Expects that passHandle 1879 * is set to obj's handle before this method is called. 1880 */ 1881 private void readSerialData(Object obj, ObjectStreamClass desc) 1882 throws IOException 1883 { 1884 ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout(); 1885 // Best effort Failure Atomicity; slotValues will be non-null if field 1886 // values can be set after reading all field data in the hierarchy. 1887 // Field values can only be set after reading all data if there are no 1888 // user observable methods in the hierarchy, readObject(NoData). The 1889 // top most Serializable class in the hierarchy can be skipped. 1890 FieldValues[] slotValues = null; 1891 1892 boolean hasSpecialReadMethod = false; 1893 for (int i = 1; i < slots.length; i++) { 1894 ObjectStreamClass slotDesc = slots[i].desc; 1895 if (slotDesc.hasReadObjectMethod() 1896 || slotDesc.hasReadObjectNoDataMethod()) { 1897 hasSpecialReadMethod = true; 1898 break; 1899 } 1900 } 1901 // No special read methods, can store values and defer setting. 1902 if (!hasSpecialReadMethod) 1903 slotValues = new FieldValues[slots.length]; 1904 1905 for (int i = 0; i < slots.length; i++) { 1906 ObjectStreamClass slotDesc = slots[i].desc; 1907 1908 if (slots[i].hasData) { 1909 if (obj != null && 1910 slotDesc.hasReadObjectMethod() && 1911 handles.lookupException(passHandle) == null) 1912 { 1913 SerialCallbackContext oldContext = curContext; 1914 1915 try { 1916 curContext = new SerialCallbackContext(obj, slotDesc); 1917 1918 bin.setBlockDataMode(true); 1919 slotDesc.invokeReadObject(obj, this); 1920 } catch (ClassNotFoundException ex) { 1921 /* 1922 * In most cases, the handle table has already 1923 * propagated a CNFException to passHandle at this 1924 * point; this mark call is included to address cases 1925 * where the custom readObject method has cons'ed and 1926 * thrown a new CNFException of its own. 1927 */ 1928 handles.markException(passHandle, ex); 1929 } finally { 1930 curContext.setUsed(); 1931 curContext = oldContext; 1932 } 1933 1934 /* 1935 * defaultDataEnd may have been set indirectly by custom 1936 * readObject() method when calling defaultReadObject() or 1937 * readFields(); clear it to restore normal read behavior. 1938 */ 1939 defaultDataEnd = false; 1940 } else { 1941 FieldValues vals = defaultReadFields(obj, slotDesc); 1942 if (slotValues != null) { 1943 slotValues[i] = vals; 1944 } else if (obj != null) { 1945 defaultCheckFieldValues(obj, slotDesc, vals); 1946 defaultSetFieldValues(obj, slotDesc, vals); 1947 } 1948 } 1949 if (slotDesc.hasWriteObjectData()) { 1950 skipCustomData(); 1951 } else { 1952 bin.setBlockDataMode(false); 1953 } 1954 } else { 1955 if (obj != null && 1956 slotDesc.hasReadObjectNoDataMethod() && 1957 handles.lookupException(passHandle) == null) 1958 { 1959 slotDesc.invokeReadObjectNoData(obj); 1960 } 1961 } 1962 } 1963 1964 if (obj != null && slotValues != null) { 1965 // Check that the non-primitive types are assignable for all slots 1966 // before assigning. 1967 for (int i = 0; i < slots.length; i++) { 1968 if (slotValues[i] != null) 1969 defaultCheckFieldValues(obj, slots[i].desc, slotValues[i]); 1970 } 1971 for (int i = 0; i < slots.length; i++) { 1972 if (slotValues[i] != null) 1973 defaultSetFieldValues(obj, slots[i].desc, slotValues[i]); 1974 } 1975 } 1976 } 1977 1978 /** 1979 * Skips over all block data and objects until TC_ENDBLOCKDATA is 1980 * encountered. 1981 */ 1982 private void skipCustomData() throws IOException { 1983 int oldHandle = passHandle; 1984 for (;;) { 1985 if (bin.getBlockDataMode()) { 1986 bin.skipBlockData(); 1987 bin.setBlockDataMode(false); 1988 } 1989 switch (bin.peekByte()) { 1990 case TC_BLOCKDATA: 1991 case TC_BLOCKDATALONG: 1992 bin.setBlockDataMode(true); 1993 break; 1994 1995 case TC_ENDBLOCKDATA: 1996 bin.readByte(); 1997 passHandle = oldHandle; 1998 return; 1999 2000 default: 2001 readObject0(false); 2002 break; 2003 } 2004 } 2005 } 2006 2007 private class FieldValues { 2008 final byte[] primValues; 2009 final Object[] objValues; 2010 2011 FieldValues(byte[] primValues, Object[] objValues) { 2012 this.primValues = primValues; 2013 this.objValues = objValues; 2014 } 2015 } 2016 2017 /** 2018 * Reads in values of serializable fields declared by given class 2019 * descriptor. Expects that passHandle is set to obj's handle before this 2020 * method is called. 2021 */ 2022 private FieldValues defaultReadFields(Object obj, ObjectStreamClass desc) 2023 throws IOException 2024 { 2025 Class<?> cl = desc.forClass(); 2026 if (cl != null && obj != null && !cl.isInstance(obj)) { 2027 throw new ClassCastException(); 2028 } 2029 2030 byte[] primVals = null; 2031 int primDataSize = desc.getPrimDataSize(); 2032 if (primDataSize > 0) { 2033 primVals = new byte[primDataSize]; 2034 bin.readFully(primVals, 0, primDataSize, false); 2035 } 2036 2037 Object[] objVals = null; 2038 int numObjFields = desc.getNumObjFields(); 2039 if (numObjFields > 0) { 2040 int objHandle = passHandle; 2041 ObjectStreamField[] fields = desc.getFields(false); 2042 objVals = new Object[numObjFields]; 2043 int numPrimFields = fields.length - objVals.length; 2044 for (int i = 0; i < objVals.length; i++) { 2045 ObjectStreamField f = fields[numPrimFields + i]; 2046 objVals[i] = readObject0(f.isUnshared()); 2047 if (f.getField() != null) { 2048 handles.markDependency(objHandle, passHandle); 2049 } 2050 } 2051 passHandle = objHandle; 2052 } 2053 2054 return new FieldValues(primVals, objVals); 2055 } 2056 2057 /** Throws ClassCastException if any value is not assignable. */ 2058 private void defaultCheckFieldValues(Object obj, ObjectStreamClass desc, 2059 FieldValues values) { 2060 Object[] objectValues = values.objValues; 2061 if (objectValues != null) 2062 desc.checkObjFieldValueTypes(obj, objectValues); 2063 } 2064 2065 /** Sets field values in obj. */ 2066 private void defaultSetFieldValues(Object obj, ObjectStreamClass desc, 2067 FieldValues values) { 2068 byte[] primValues = values.primValues; 2069 Object[] objectValues = values.objValues; 2070 2071 if (primValues != null) 2072 desc.setPrimFieldValues(obj, primValues); 2073 if (objectValues != null) 2074 desc.setObjFieldValues(obj, objectValues); 2075 } 2076 2077 /** 2078 * Reads in and returns IOException that caused serialization to abort. 2079 * All stream state is discarded prior to reading in fatal exception. Sets 2080 * passHandle to fatal exception's handle. 2081 */ 2082 private IOException readFatalException() throws IOException { 2083 if (bin.readByte() != TC_EXCEPTION) { 2084 throw new InternalError(); 2085 } 2086 clear(); 2087 return (IOException) readObject0(false); 2088 } 2089 2090 /** 2091 * If recursion depth is 0, clears internal data structures; otherwise, 2092 * throws a StreamCorruptedException. This method is called when a 2093 * TC_RESET typecode is encountered. 2094 */ 2095 private void handleReset() throws StreamCorruptedException { 2096 if (depth > 0) { 2097 throw new StreamCorruptedException( 2098 "unexpected reset; recursion depth: " + depth); 2099 } 2100 clear(); 2101 } 2102 2103 /** 2104 * Converts specified span of bytes into float values. 2105 */ 2106 // REMIND: remove once hotspot inlines Float.intBitsToFloat 2107 private static native void bytesToFloats(byte[] src, int srcpos, 2108 float[] dst, int dstpos, 2109 int nfloats); 2110 2111 /** 2112 * Converts specified span of bytes into double values. 2113 */ 2114 // REMIND: remove once hotspot inlines Double.longBitsToDouble 2115 private static native void bytesToDoubles(byte[] src, int srcpos, 2116 double[] dst, int dstpos, 2117 int ndoubles); 2118 2119 /** 2120 * Returns the first non-null class loader (not counting class loaders of 2121 * generated reflection implementation classes) up the execution stack, or 2122 * null if only code from the null class loader is on the stack. This 2123 * method is also called via reflection by the following RMI-IIOP class: 2124 * 2125 * com.sun.corba.se.internal.util.JDKClassLoader 2126 * 2127 * This method should not be removed or its signature changed without 2128 * corresponding modifications to the above class. 2129 */ 2130 private static ClassLoader latestUserDefinedLoader() { 2131 return sun.misc.VM.latestUserDefinedLoader(); 2132 } 2133 2134 /** 2135 * Default GetField implementation. 2136 */ 2137 private class GetFieldImpl extends GetField { 2138 2139 /** class descriptor describing serializable fields */ 2140 private final ObjectStreamClass desc; 2141 /** primitive field values */ 2142 private final byte[] primVals; 2143 /** object field values */ 2144 private final Object[] objVals; 2145 /** object field value handles */ 2146 private final int[] objHandles; 2147 2148 /** 2149 * Creates GetFieldImpl object for reading fields defined in given 2150 * class descriptor. 2151 */ 2152 GetFieldImpl(ObjectStreamClass desc) { 2153 this.desc = desc; 2154 primVals = new byte[desc.getPrimDataSize()]; 2155 objVals = new Object[desc.getNumObjFields()]; 2156 objHandles = new int[objVals.length]; 2157 } 2158 2159 public ObjectStreamClass getObjectStreamClass() { 2160 return desc; 2161 } 2162 2163 public boolean defaulted(String name) throws IOException { 2164 return (getFieldOffset(name, null) < 0); 2165 } 2166 2167 public boolean get(String name, boolean val) throws IOException { 2168 int off = getFieldOffset(name, Boolean.TYPE); 2169 return (off >= 0) ? Bits.getBoolean(primVals, off) : val; 2170 } 2171 2172 public byte get(String name, byte val) throws IOException { 2173 int off = getFieldOffset(name, Byte.TYPE); 2174 return (off >= 0) ? primVals[off] : val; 2175 } 2176 2177 public char get(String name, char val) throws IOException { 2178 int off = getFieldOffset(name, Character.TYPE); 2179 return (off >= 0) ? Bits.getChar(primVals, off) : val; 2180 } 2181 2182 public short get(String name, short val) throws IOException { 2183 int off = getFieldOffset(name, Short.TYPE); 2184 return (off >= 0) ? Bits.getShort(primVals, off) : val; 2185 } 2186 2187 public int get(String name, int val) throws IOException { 2188 int off = getFieldOffset(name, Integer.TYPE); 2189 return (off >= 0) ? Bits.getInt(primVals, off) : val; 2190 } 2191 2192 public float get(String name, float val) throws IOException { 2193 int off = getFieldOffset(name, Float.TYPE); 2194 return (off >= 0) ? Bits.getFloat(primVals, off) : val; 2195 } 2196 2197 public long get(String name, long val) throws IOException { 2198 int off = getFieldOffset(name, Long.TYPE); 2199 return (off >= 0) ? Bits.getLong(primVals, off) : val; 2200 } 2201 2202 public double get(String name, double val) throws IOException { 2203 int off = getFieldOffset(name, Double.TYPE); 2204 return (off >= 0) ? Bits.getDouble(primVals, off) : val; 2205 } 2206 2207 public Object get(String name, Object val) throws IOException { 2208 int off = getFieldOffset(name, Object.class); 2209 if (off >= 0) { 2210 int objHandle = objHandles[off]; 2211 handles.markDependency(passHandle, objHandle); 2212 return (handles.lookupException(objHandle) == null) ? 2213 objVals[off] : null; 2214 } else { 2215 return val; 2216 } 2217 } 2218 2219 /** 2220 * Reads primitive and object field values from stream. 2221 */ 2222 void readFields() throws IOException { 2223 bin.readFully(primVals, 0, primVals.length, false); 2224 2225 int oldHandle = passHandle; 2226 ObjectStreamField[] fields = desc.getFields(false); 2227 int numPrimFields = fields.length - objVals.length; 2228 for (int i = 0; i < objVals.length; i++) { 2229 objVals[i] = 2230 readObject0(fields[numPrimFields + i].isUnshared()); 2231 objHandles[i] = passHandle; 2232 } 2233 passHandle = oldHandle; 2234 } 2235 2236 /** 2237 * Returns offset of field with given name and type. A specified type 2238 * of null matches all types, Object.class matches all non-primitive 2239 * types, and any other non-null type matches assignable types only. 2240 * If no matching field is found in the (incoming) class 2241 * descriptor but a matching field is present in the associated local 2242 * class descriptor, returns -1. Throws IllegalArgumentException if 2243 * neither incoming nor local class descriptor contains a match. 2244 */ 2245 private int getFieldOffset(String name, Class<?> type) { 2246 ObjectStreamField field = desc.getField(name, type); 2247 if (field != null) { 2248 return field.getOffset(); 2249 } else if (desc.getLocalDesc().getField(name, type) != null) { 2250 return -1; 2251 } else { 2252 throw new IllegalArgumentException("no such field " + name + 2253 " with type " + type); 2254 } 2255 } 2256 } 2257 2258 /** 2259 * Prioritized list of callbacks to be performed once object graph has been 2260 * completely deserialized. 2261 */ 2262 private static class ValidationList { 2263 2264 private static class Callback { 2265 final ObjectInputValidation obj; 2266 final int priority; 2267 Callback next; 2268 final AccessControlContext acc; 2269 2270 Callback(ObjectInputValidation obj, int priority, Callback next, 2271 AccessControlContext acc) 2272 { 2273 this.obj = obj; 2274 this.priority = priority; 2275 this.next = next; 2276 this.acc = acc; 2277 } 2278 } 2279 2280 /** linked list of callbacks */ 2281 private Callback list; 2282 2283 /** 2284 * Creates new (empty) ValidationList. 2285 */ 2286 ValidationList() { 2287 } 2288 2289 /** 2290 * Registers callback. Throws InvalidObjectException if callback 2291 * object is null. 2292 */ 2293 void register(ObjectInputValidation obj, int priority) 2294 throws InvalidObjectException 2295 { 2296 if (obj == null) { 2297 throw new InvalidObjectException("null callback"); 2298 } 2299 2300 Callback prev = null, cur = list; 2301 while (cur != null && priority < cur.priority) { 2302 prev = cur; 2303 cur = cur.next; 2304 } 2305 AccessControlContext acc = AccessController.getContext(); 2306 if (prev != null) { 2307 prev.next = new Callback(obj, priority, cur, acc); 2308 } else { 2309 list = new Callback(obj, priority, list, acc); 2310 } 2311 } 2312 2313 /** 2314 * Invokes all registered callbacks and clears the callback list. 2315 * Callbacks with higher priorities are called first; those with equal 2316 * priorities may be called in any order. If any of the callbacks 2317 * throws an InvalidObjectException, the callback process is terminated 2318 * and the exception propagated upwards. 2319 */ 2320 void doCallbacks() throws InvalidObjectException { 2321 try { 2322 while (list != null) { 2323 AccessController.doPrivileged( 2324 new PrivilegedExceptionAction<>() 2325 { 2326 public Void run() throws InvalidObjectException { 2327 list.obj.validateObject(); 2328 return null; 2329 } 2330 }, list.acc); 2331 list = list.next; 2332 } 2333 } catch (PrivilegedActionException ex) { 2334 list = null; 2335 throw (InvalidObjectException) ex.getException(); 2336 } 2337 } 2338 2339 /** 2340 * Resets the callback list to its initial (empty) state. 2341 */ 2342 public void clear() { 2343 list = null; 2344 } 2345 } 2346 2347 /** 2348 * Input stream supporting single-byte peek operations. 2349 */ 2350 private static class PeekInputStream extends InputStream { 2351 2352 /** underlying stream */ 2353 private final InputStream in; 2354 /** peeked byte */ 2355 private int peekb = -1; 2356 2357 /** 2358 * Creates new PeekInputStream on top of given underlying stream. 2359 */ 2360 PeekInputStream(InputStream in) { 2361 this.in = in; 2362 } 2363 2364 /** 2365 * Peeks at next byte value in stream. Similar to read(), except 2366 * that it does not consume the read value. 2367 */ 2368 int peek() throws IOException { 2369 return (peekb >= 0) ? peekb : (peekb = in.read()); 2370 } 2371 2372 public int read() throws IOException { 2373 if (peekb >= 0) { 2374 int v = peekb; 2375 peekb = -1; 2376 return v; 2377 } else { 2378 return in.read(); 2379 } 2380 } 2381 2382 public int read(byte[] b, int off, int len) throws IOException { 2383 if (len == 0) { 2384 return 0; 2385 } else if (peekb < 0) { 2386 return in.read(b, off, len); 2387 } else { 2388 b[off++] = (byte) peekb; 2389 len--; 2390 peekb = -1; 2391 int n = in.read(b, off, len); 2392 return (n >= 0) ? (n + 1) : 1; 2393 } 2394 } 2395 2396 void readFully(byte[] b, int off, int len) throws IOException { 2397 int n = 0; 2398 while (n < len) { 2399 int count = read(b, off + n, len - n); 2400 if (count < 0) { 2401 throw new EOFException(); 2402 } 2403 n += count; 2404 } 2405 } 2406 2407 public long skip(long n) throws IOException { 2408 if (n <= 0) { 2409 return 0; 2410 } 2411 int skipped = 0; 2412 if (peekb >= 0) { 2413 peekb = -1; 2414 skipped++; 2415 n--; 2416 } 2417 return skipped + in.skip(n); 2418 } 2419 2420 public int available() throws IOException { 2421 return in.available() + ((peekb >= 0) ? 1 : 0); 2422 } 2423 2424 public void close() throws IOException { 2425 in.close(); 2426 } 2427 } 2428 2429 private static final Unsafe UNSAFE = Unsafe.getUnsafe(); 2430 2431 /** 2432 * Performs a "freeze" action, required to adhere to final field semantics. 2433 * 2434 * <p> This method can be called unconditionally before returning the graph, 2435 * from the topmost readObject call, since it is expected that the 2436 * additional cost of the freeze action is negligible compared to 2437 * reconstituting even the most simple graph. 2438 * 2439 * <p> Nested calls to readObject do not issue freeze actions because the 2440 * sub-graph returned from a nested call is not guaranteed to be fully 2441 * initialized yet (possible cycles). 2442 */ 2443 private void freeze() { 2444 // Issue a StoreStore|StoreLoad fence, which is at least sufficient 2445 // to provide final-freeze semantics. 2446 UNSAFE.storeFence(); 2447 } 2448 2449 /** 2450 * Input stream with two modes: in default mode, inputs data written in the 2451 * same format as DataOutputStream; in "block data" mode, inputs data 2452 * bracketed by block data markers (see object serialization specification 2453 * for details). Buffering depends on block data mode: when in default 2454 * mode, no data is buffered in advance; when in block data mode, all data 2455 * for the current data block is read in at once (and buffered). 2456 */ 2457 private class BlockDataInputStream 2458 extends InputStream implements DataInput 2459 { 2460 /** maximum data block length */ 2461 private static final int MAX_BLOCK_SIZE = 1024; 2462 /** maximum data block header length */ 2463 private static final int MAX_HEADER_SIZE = 5; 2464 /** (tunable) length of char buffer (for reading strings) */ 2465 private static final int CHAR_BUF_SIZE = 256; 2466 /** readBlockHeader() return value indicating header read may block */ 2467 private static final int HEADER_BLOCKED = -2; 2468 2469 /** buffer for reading general/block data */ 2470 private final byte[] buf = new byte[MAX_BLOCK_SIZE]; 2471 /** buffer for reading block data headers */ 2472 private final byte[] hbuf = new byte[MAX_HEADER_SIZE]; 2473 /** char buffer for fast string reads */ 2474 private final char[] cbuf = new char[CHAR_BUF_SIZE]; 2475 2476 /** block data mode */ 2477 private boolean blkmode = false; 2478 2479 // block data state fields; values meaningful only when blkmode true 2480 /** current offset into buf */ 2481 private int pos = 0; 2482 /** end offset of valid data in buf, or -1 if no more block data */ 2483 private int end = -1; 2484 /** number of bytes in current block yet to be read from stream */ 2485 private int unread = 0; 2486 2487 /** underlying stream (wrapped in peekable filter stream) */ 2488 private final PeekInputStream in; 2489 /** loopback stream (for data reads that span data blocks) */ 2490 private final DataInputStream din; 2491 2492 /** 2493 * Creates new BlockDataInputStream on top of given underlying stream. 2494 * Block data mode is turned off by default. 2495 */ 2496 BlockDataInputStream(InputStream in) { 2497 this.in = new PeekInputStream(in); 2498 din = new DataInputStream(this); 2499 } 2500 2501 /** 2502 * Sets block data mode to the given mode (true == on, false == off) 2503 * and returns the previous mode value. If the new mode is the same as 2504 * the old mode, no action is taken. Throws IllegalStateException if 2505 * block data mode is being switched from on to off while unconsumed 2506 * block data is still present in the stream. 2507 */ 2508 boolean setBlockDataMode(boolean newmode) throws IOException { 2509 if (blkmode == newmode) { 2510 return blkmode; 2511 } 2512 if (newmode) { 2513 pos = 0; 2514 end = 0; 2515 unread = 0; 2516 } else if (pos < end) { 2517 throw new IllegalStateException("unread block data"); 2518 } 2519 blkmode = newmode; 2520 return !blkmode; 2521 } 2522 2523 /** 2524 * Returns true if the stream is currently in block data mode, false 2525 * otherwise. 2526 */ 2527 boolean getBlockDataMode() { 2528 return blkmode; 2529 } 2530 2531 /** 2532 * If in block data mode, skips to the end of the current group of data 2533 * blocks (but does not unset block data mode). If not in block data 2534 * mode, throws an IllegalStateException. 2535 */ 2536 void skipBlockData() throws IOException { 2537 if (!blkmode) { 2538 throw new IllegalStateException("not in block data mode"); 2539 } 2540 while (end >= 0) { 2541 refill(); 2542 } 2543 } 2544 2545 /** 2546 * Attempts to read in the next block data header (if any). If 2547 * canBlock is false and a full header cannot be read without possibly 2548 * blocking, returns HEADER_BLOCKED, else if the next element in the 2549 * stream is a block data header, returns the block data length 2550 * specified by the header, else returns -1. 2551 */ 2552 private int readBlockHeader(boolean canBlock) throws IOException { 2553 if (defaultDataEnd) { 2554 /* 2555 * Fix for 4360508: stream is currently at the end of a field 2556 * value block written via default serialization; since there 2557 * is no terminating TC_ENDBLOCKDATA tag, simulate 2558 * end-of-custom-data behavior explicitly. 2559 */ 2560 return -1; 2561 } 2562 try { 2563 for (;;) { 2564 int avail = canBlock ? Integer.MAX_VALUE : in.available(); 2565 if (avail == 0) { 2566 return HEADER_BLOCKED; 2567 } 2568 2569 int tc = in.peek(); 2570 switch (tc) { 2571 case TC_BLOCKDATA: 2572 if (avail < 2) { 2573 return HEADER_BLOCKED; 2574 } 2575 in.readFully(hbuf, 0, 2); 2576 return hbuf[1] & 0xFF; 2577 2578 case TC_BLOCKDATALONG: 2579 if (avail < 5) { 2580 return HEADER_BLOCKED; 2581 } 2582 in.readFully(hbuf, 0, 5); 2583 int len = Bits.getInt(hbuf, 1); 2584 if (len < 0) { 2585 throw new StreamCorruptedException( 2586 "illegal block data header length: " + 2587 len); 2588 } 2589 return len; 2590 2591 /* 2592 * TC_RESETs may occur in between data blocks. 2593 * Unfortunately, this case must be parsed at a lower 2594 * level than other typecodes, since primitive data 2595 * reads may span data blocks separated by a TC_RESET. 2596 */ 2597 case TC_RESET: 2598 in.read(); 2599 handleReset(); 2600 break; 2601 2602 default: 2603 if (tc >= 0 && (tc < TC_BASE || tc > TC_MAX)) { 2604 throw new StreamCorruptedException( 2605 String.format("invalid type code: %02X", 2606 tc)); 2607 } 2608 return -1; 2609 } 2610 } 2611 } catch (EOFException ex) { 2612 throw new StreamCorruptedException( 2613 "unexpected EOF while reading block data header"); 2614 } 2615 } 2616 2617 /** 2618 * Refills internal buffer buf with block data. Any data in buf at the 2619 * time of the call is considered consumed. Sets the pos, end, and 2620 * unread fields to reflect the new amount of available block data; if 2621 * the next element in the stream is not a data block, sets pos and 2622 * unread to 0 and end to -1. 2623 */ 2624 private void refill() throws IOException { 2625 try { 2626 do { 2627 pos = 0; 2628 if (unread > 0) { 2629 int n = 2630 in.read(buf, 0, Math.min(unread, MAX_BLOCK_SIZE)); 2631 if (n >= 0) { 2632 end = n; 2633 unread -= n; 2634 } else { 2635 throw new StreamCorruptedException( 2636 "unexpected EOF in middle of data block"); 2637 } 2638 } else { 2639 int n = readBlockHeader(true); 2640 if (n >= 0) { 2641 end = 0; 2642 unread = n; 2643 } else { 2644 end = -1; 2645 unread = 0; 2646 } 2647 } 2648 } while (pos == end); 2649 } catch (IOException ex) { 2650 pos = 0; 2651 end = -1; 2652 unread = 0; 2653 throw ex; 2654 } 2655 } 2656 2657 /** 2658 * If in block data mode, returns the number of unconsumed bytes 2659 * remaining in the current data block. If not in block data mode, 2660 * throws an IllegalStateException. 2661 */ 2662 int currentBlockRemaining() { 2663 if (blkmode) { 2664 return (end >= 0) ? (end - pos) + unread : 0; 2665 } else { 2666 throw new IllegalStateException(); 2667 } 2668 } 2669 2670 /** 2671 * Peeks at (but does not consume) and returns the next byte value in 2672 * the stream, or -1 if the end of the stream/block data (if in block 2673 * data mode) has been reached. 2674 */ 2675 int peek() throws IOException { 2676 if (blkmode) { 2677 if (pos == end) { 2678 refill(); 2679 } 2680 return (end >= 0) ? (buf[pos] & 0xFF) : -1; 2681 } else { 2682 return in.peek(); 2683 } 2684 } 2685 2686 /** 2687 * Peeks at (but does not consume) and returns the next byte value in 2688 * the stream, or throws EOFException if end of stream/block data has 2689 * been reached. 2690 */ 2691 byte peekByte() throws IOException { 2692 int val = peek(); 2693 if (val < 0) { 2694 throw new EOFException(); 2695 } 2696 return (byte) val; 2697 } 2698 2699 2700 /* ----------------- generic input stream methods ------------------ */ 2701 /* 2702 * The following methods are equivalent to their counterparts in 2703 * InputStream, except that they interpret data block boundaries and 2704 * read the requested data from within data blocks when in block data 2705 * mode. 2706 */ 2707 2708 public int read() throws IOException { 2709 if (blkmode) { 2710 if (pos == end) { 2711 refill(); 2712 } 2713 return (end >= 0) ? (buf[pos++] & 0xFF) : -1; 2714 } else { 2715 return in.read(); 2716 } 2717 } 2718 2719 public int read(byte[] b, int off, int len) throws IOException { 2720 return read(b, off, len, false); 2721 } 2722 2723 public long skip(long len) throws IOException { 2724 long remain = len; 2725 while (remain > 0) { 2726 if (blkmode) { 2727 if (pos == end) { 2728 refill(); 2729 } 2730 if (end < 0) { 2731 break; 2732 } 2733 int nread = (int) Math.min(remain, end - pos); 2734 remain -= nread; 2735 pos += nread; 2736 } else { 2737 int nread = (int) Math.min(remain, MAX_BLOCK_SIZE); 2738 if ((nread = in.read(buf, 0, nread)) < 0) { 2739 break; 2740 } 2741 remain -= nread; 2742 } 2743 } 2744 return len - remain; 2745 } 2746 2747 public int available() throws IOException { 2748 if (blkmode) { 2749 if ((pos == end) && (unread == 0)) { 2750 int n; 2751 while ((n = readBlockHeader(false)) == 0) ; 2752 switch (n) { 2753 case HEADER_BLOCKED: 2754 break; 2755 2756 case -1: 2757 pos = 0; 2758 end = -1; 2759 break; 2760 2761 default: 2762 pos = 0; 2763 end = 0; 2764 unread = n; 2765 break; 2766 } 2767 } 2768 // avoid unnecessary call to in.available() if possible 2769 int unreadAvail = (unread > 0) ? 2770 Math.min(in.available(), unread) : 0; 2771 return (end >= 0) ? (end - pos) + unreadAvail : 0; 2772 } else { 2773 return in.available(); 2774 } 2775 } 2776 2777 public void close() throws IOException { 2778 if (blkmode) { 2779 pos = 0; 2780 end = -1; 2781 unread = 0; 2782 } 2783 in.close(); 2784 } 2785 2786 /** 2787 * Attempts to read len bytes into byte array b at offset off. Returns 2788 * the number of bytes read, or -1 if the end of stream/block data has 2789 * been reached. If copy is true, reads values into an intermediate 2790 * buffer before copying them to b (to avoid exposing a reference to 2791 * b). 2792 */ 2793 int read(byte[] b, int off, int len, boolean copy) throws IOException { 2794 if (len == 0) { 2795 return 0; 2796 } else if (blkmode) { 2797 if (pos == end) { 2798 refill(); 2799 } 2800 if (end < 0) { 2801 return -1; 2802 } 2803 int nread = Math.min(len, end - pos); 2804 System.arraycopy(buf, pos, b, off, nread); 2805 pos += nread; 2806 return nread; 2807 } else if (copy) { 2808 int nread = in.read(buf, 0, Math.min(len, MAX_BLOCK_SIZE)); 2809 if (nread > 0) { 2810 System.arraycopy(buf, 0, b, off, nread); 2811 } 2812 return nread; 2813 } else { 2814 return in.read(b, off, len); 2815 } 2816 } 2817 2818 /* ----------------- primitive data input methods ------------------ */ 2819 /* 2820 * The following methods are equivalent to their counterparts in 2821 * DataInputStream, except that they interpret data block boundaries 2822 * and read the requested data from within data blocks when in block 2823 * data mode. 2824 */ 2825 2826 public void readFully(byte[] b) throws IOException { 2827 readFully(b, 0, b.length, false); 2828 } 2829 2830 public void readFully(byte[] b, int off, int len) throws IOException { 2831 readFully(b, off, len, false); 2832 } 2833 2834 public void readFully(byte[] b, int off, int len, boolean copy) 2835 throws IOException 2836 { 2837 while (len > 0) { 2838 int n = read(b, off, len, copy); 2839 if (n < 0) { 2840 throw new EOFException(); 2841 } 2842 off += n; 2843 len -= n; 2844 } 2845 } 2846 2847 public int skipBytes(int n) throws IOException { 2848 return din.skipBytes(n); 2849 } 2850 2851 public boolean readBoolean() throws IOException { 2852 int v = read(); 2853 if (v < 0) { 2854 throw new EOFException(); 2855 } 2856 return (v != 0); 2857 } 2858 2859 public byte readByte() throws IOException { 2860 int v = read(); 2861 if (v < 0) { 2862 throw new EOFException(); 2863 } 2864 return (byte) v; 2865 } 2866 2867 public int readUnsignedByte() throws IOException { 2868 int v = read(); 2869 if (v < 0) { 2870 throw new EOFException(); 2871 } 2872 return v; 2873 } 2874 2875 public char readChar() throws IOException { 2876 if (!blkmode) { 2877 pos = 0; 2878 in.readFully(buf, 0, 2); 2879 } else if (end - pos < 2) { 2880 return din.readChar(); 2881 } 2882 char v = Bits.getChar(buf, pos); 2883 pos += 2; 2884 return v; 2885 } 2886 2887 public short readShort() throws IOException { 2888 if (!blkmode) { 2889 pos = 0; 2890 in.readFully(buf, 0, 2); 2891 } else if (end - pos < 2) { 2892 return din.readShort(); 2893 } 2894 short v = Bits.getShort(buf, pos); 2895 pos += 2; 2896 return v; 2897 } 2898 2899 public int readUnsignedShort() throws IOException { 2900 if (!blkmode) { 2901 pos = 0; 2902 in.readFully(buf, 0, 2); 2903 } else if (end - pos < 2) { 2904 return din.readUnsignedShort(); 2905 } 2906 int v = Bits.getShort(buf, pos) & 0xFFFF; 2907 pos += 2; 2908 return v; 2909 } 2910 2911 public int readInt() throws IOException { 2912 if (!blkmode) { 2913 pos = 0; 2914 in.readFully(buf, 0, 4); 2915 } else if (end - pos < 4) { 2916 return din.readInt(); 2917 } 2918 int v = Bits.getInt(buf, pos); 2919 pos += 4; 2920 return v; 2921 } 2922 2923 public float readFloat() throws IOException { 2924 if (!blkmode) { 2925 pos = 0; 2926 in.readFully(buf, 0, 4); 2927 } else if (end - pos < 4) { 2928 return din.readFloat(); 2929 } 2930 float v = Bits.getFloat(buf, pos); 2931 pos += 4; 2932 return v; 2933 } 2934 2935 public long readLong() throws IOException { 2936 if (!blkmode) { 2937 pos = 0; 2938 in.readFully(buf, 0, 8); 2939 } else if (end - pos < 8) { 2940 return din.readLong(); 2941 } 2942 long v = Bits.getLong(buf, pos); 2943 pos += 8; 2944 return v; 2945 } 2946 2947 public double readDouble() throws IOException { 2948 if (!blkmode) { 2949 pos = 0; 2950 in.readFully(buf, 0, 8); 2951 } else if (end - pos < 8) { 2952 return din.readDouble(); 2953 } 2954 double v = Bits.getDouble(buf, pos); 2955 pos += 8; 2956 return v; 2957 } 2958 2959 public String readUTF() throws IOException { 2960 return readUTFBody(readUnsignedShort()); 2961 } 2962 2963 @SuppressWarnings("deprecation") 2964 public String readLine() throws IOException { 2965 return din.readLine(); // deprecated, not worth optimizing 2966 } 2967 2968 /* -------------- primitive data array input methods --------------- */ 2969 /* 2970 * The following methods read in spans of primitive data values. 2971 * Though equivalent to calling the corresponding primitive read 2972 * methods repeatedly, these methods are optimized for reading groups 2973 * of primitive data values more efficiently. 2974 */ 2975 2976 void readBooleans(boolean[] v, int off, int len) throws IOException { 2977 int stop, endoff = off + len; 2978 while (off < endoff) { 2979 if (!blkmode) { 2980 int span = Math.min(endoff - off, MAX_BLOCK_SIZE); 2981 in.readFully(buf, 0, span); 2982 stop = off + span; 2983 pos = 0; 2984 } else if (end - pos < 1) { 2985 v[off++] = din.readBoolean(); 2986 continue; 2987 } else { 2988 stop = Math.min(endoff, off + end - pos); 2989 } 2990 2991 while (off < stop) { 2992 v[off++] = Bits.getBoolean(buf, pos++); 2993 } 2994 } 2995 } 2996 2997 void readChars(char[] v, int off, int len) throws IOException { 2998 int stop, endoff = off + len; 2999 while (off < endoff) { 3000 if (!blkmode) { 3001 int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 1); 3002 in.readFully(buf, 0, span << 1); 3003 stop = off + span; 3004 pos = 0; 3005 } else if (end - pos < 2) { 3006 v[off++] = din.readChar(); 3007 continue; 3008 } else { 3009 stop = Math.min(endoff, off + ((end - pos) >> 1)); 3010 } 3011 3012 while (off < stop) { 3013 v[off++] = Bits.getChar(buf, pos); 3014 pos += 2; 3015 } 3016 } 3017 } 3018 3019 void readShorts(short[] v, int off, int len) throws IOException { 3020 int stop, endoff = off + len; 3021 while (off < endoff) { 3022 if (!blkmode) { 3023 int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 1); 3024 in.readFully(buf, 0, span << 1); 3025 stop = off + span; 3026 pos = 0; 3027 } else if (end - pos < 2) { 3028 v[off++] = din.readShort(); 3029 continue; 3030 } else { 3031 stop = Math.min(endoff, off + ((end - pos) >> 1)); 3032 } 3033 3034 while (off < stop) { 3035 v[off++] = Bits.getShort(buf, pos); 3036 pos += 2; 3037 } 3038 } 3039 } 3040 3041 void readInts(int[] v, int off, int len) throws IOException { 3042 int stop, endoff = off + len; 3043 while (off < endoff) { 3044 if (!blkmode) { 3045 int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 2); 3046 in.readFully(buf, 0, span << 2); 3047 stop = off + span; 3048 pos = 0; 3049 } else if (end - pos < 4) { 3050 v[off++] = din.readInt(); 3051 continue; 3052 } else { 3053 stop = Math.min(endoff, off + ((end - pos) >> 2)); 3054 } 3055 3056 while (off < stop) { 3057 v[off++] = Bits.getInt(buf, pos); 3058 pos += 4; 3059 } 3060 } 3061 } 3062 3063 void readFloats(float[] v, int off, int len) throws IOException { 3064 int span, endoff = off + len; 3065 while (off < endoff) { 3066 if (!blkmode) { 3067 span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 2); 3068 in.readFully(buf, 0, span << 2); 3069 pos = 0; 3070 } else if (end - pos < 4) { 3071 v[off++] = din.readFloat(); 3072 continue; 3073 } else { 3074 span = Math.min(endoff - off, ((end - pos) >> 2)); 3075 } 3076 3077 bytesToFloats(buf, pos, v, off, span); 3078 off += span; 3079 pos += span << 2; 3080 } 3081 } 3082 3083 void readLongs(long[] v, int off, int len) throws IOException { 3084 int stop, endoff = off + len; 3085 while (off < endoff) { 3086 if (!blkmode) { 3087 int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3); 3088 in.readFully(buf, 0, span << 3); 3089 stop = off + span; 3090 pos = 0; 3091 } else if (end - pos < 8) { 3092 v[off++] = din.readLong(); 3093 continue; 3094 } else { 3095 stop = Math.min(endoff, off + ((end - pos) >> 3)); 3096 } 3097 3098 while (off < stop) { 3099 v[off++] = Bits.getLong(buf, pos); 3100 pos += 8; 3101 } 3102 } 3103 } 3104 3105 void readDoubles(double[] v, int off, int len) throws IOException { 3106 int span, endoff = off + len; 3107 while (off < endoff) { 3108 if (!blkmode) { 3109 span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3); 3110 in.readFully(buf, 0, span << 3); 3111 pos = 0; 3112 } else if (end - pos < 8) { 3113 v[off++] = din.readDouble(); 3114 continue; 3115 } else { 3116 span = Math.min(endoff - off, ((end - pos) >> 3)); 3117 } 3118 3119 bytesToDoubles(buf, pos, v, off, span); 3120 off += span; 3121 pos += span << 3; 3122 } 3123 } 3124 3125 /** 3126 * Reads in string written in "long" UTF format. "Long" UTF format is 3127 * identical to standard UTF, except that it uses an 8 byte header 3128 * (instead of the standard 2 bytes) to convey the UTF encoding length. 3129 */ 3130 String readLongUTF() throws IOException { 3131 return readUTFBody(readLong()); 3132 } 3133 3134 /** 3135 * Reads in the "body" (i.e., the UTF representation minus the 2-byte 3136 * or 8-byte length header) of a UTF encoding, which occupies the next 3137 * utflen bytes. 3138 */ 3139 private String readUTFBody(long utflen) throws IOException { 3140 StringBuilder sbuf = new StringBuilder(); 3141 if (!blkmode) { 3142 end = pos = 0; 3143 } 3144 3145 while (utflen > 0) { 3146 int avail = end - pos; 3147 if (avail >= 3 || (long) avail == utflen) { 3148 utflen -= readUTFSpan(sbuf, utflen); 3149 } else { 3150 if (blkmode) { 3151 // near block boundary, read one byte at a time 3152 utflen -= readUTFChar(sbuf, utflen); 3153 } else { 3154 // shift and refill buffer manually 3155 if (avail > 0) { 3156 System.arraycopy(buf, pos, buf, 0, avail); 3157 } 3158 pos = 0; 3159 end = (int) Math.min(MAX_BLOCK_SIZE, utflen); 3160 in.readFully(buf, avail, end - avail); 3161 } 3162 } 3163 } 3164 3165 return sbuf.toString(); 3166 } 3167 3168 /** 3169 * Reads span of UTF-encoded characters out of internal buffer 3170 * (starting at offset pos and ending at or before offset end), 3171 * consuming no more than utflen bytes. Appends read characters to 3172 * sbuf. Returns the number of bytes consumed. 3173 */ 3174 private long readUTFSpan(StringBuilder sbuf, long utflen) 3175 throws IOException 3176 { 3177 int cpos = 0; 3178 int start = pos; 3179 int avail = Math.min(end - pos, CHAR_BUF_SIZE); 3180 // stop short of last char unless all of utf bytes in buffer 3181 int stop = pos + ((utflen > avail) ? avail - 2 : (int) utflen); 3182 boolean outOfBounds = false; 3183 3184 try { 3185 while (pos < stop) { 3186 int b1, b2, b3; 3187 b1 = buf[pos++] & 0xFF; 3188 switch (b1 >> 4) { 3189 case 0: 3190 case 1: 3191 case 2: 3192 case 3: 3193 case 4: 3194 case 5: 3195 case 6: 3196 case 7: // 1 byte format: 0xxxxxxx 3197 cbuf[cpos++] = (char) b1; 3198 break; 3199 3200 case 12: 3201 case 13: // 2 byte format: 110xxxxx 10xxxxxx 3202 b2 = buf[pos++]; 3203 if ((b2 & 0xC0) != 0x80) { 3204 throw new UTFDataFormatException(); 3205 } 3206 cbuf[cpos++] = (char) (((b1 & 0x1F) << 6) | 3207 ((b2 & 0x3F) << 0)); 3208 break; 3209 3210 case 14: // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx 3211 b3 = buf[pos + 1]; 3212 b2 = buf[pos + 0]; 3213 pos += 2; 3214 if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) { 3215 throw new UTFDataFormatException(); 3216 } 3217 cbuf[cpos++] = (char) (((b1 & 0x0F) << 12) | 3218 ((b2 & 0x3F) << 6) | 3219 ((b3 & 0x3F) << 0)); 3220 break; 3221 3222 default: // 10xx xxxx, 1111 xxxx 3223 throw new UTFDataFormatException(); 3224 } 3225 } 3226 } catch (ArrayIndexOutOfBoundsException ex) { 3227 outOfBounds = true; 3228 } finally { 3229 if (outOfBounds || (pos - start) > utflen) { 3230 /* 3231 * Fix for 4450867: if a malformed utf char causes the 3232 * conversion loop to scan past the expected end of the utf 3233 * string, only consume the expected number of utf bytes. 3234 */ 3235 pos = start + (int) utflen; 3236 throw new UTFDataFormatException(); 3237 } 3238 } 3239 3240 sbuf.append(cbuf, 0, cpos); 3241 return pos - start; 3242 } 3243 3244 /** 3245 * Reads in single UTF-encoded character one byte at a time, appends 3246 * the character to sbuf, and returns the number of bytes consumed. 3247 * This method is used when reading in UTF strings written in block 3248 * data mode to handle UTF-encoded characters which (potentially) 3249 * straddle block-data boundaries. 3250 */ 3251 private int readUTFChar(StringBuilder sbuf, long utflen) 3252 throws IOException 3253 { 3254 int b1, b2, b3; 3255 b1 = readByte() & 0xFF; 3256 switch (b1 >> 4) { 3257 case 0: 3258 case 1: 3259 case 2: 3260 case 3: 3261 case 4: 3262 case 5: 3263 case 6: 3264 case 7: // 1 byte format: 0xxxxxxx 3265 sbuf.append((char) b1); 3266 return 1; 3267 3268 case 12: 3269 case 13: // 2 byte format: 110xxxxx 10xxxxxx 3270 if (utflen < 2) { 3271 throw new UTFDataFormatException(); 3272 } 3273 b2 = readByte(); 3274 if ((b2 & 0xC0) != 0x80) { 3275 throw new UTFDataFormatException(); 3276 } 3277 sbuf.append((char) (((b1 & 0x1F) << 6) | 3278 ((b2 & 0x3F) << 0))); 3279 return 2; 3280 3281 case 14: // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx 3282 if (utflen < 3) { 3283 if (utflen == 2) { 3284 readByte(); // consume remaining byte 3285 } 3286 throw new UTFDataFormatException(); 3287 } 3288 b2 = readByte(); 3289 b3 = readByte(); 3290 if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) { 3291 throw new UTFDataFormatException(); 3292 } 3293 sbuf.append((char) (((b1 & 0x0F) << 12) | 3294 ((b2 & 0x3F) << 6) | 3295 ((b3 & 0x3F) << 0))); 3296 return 3; 3297 3298 default: // 10xx xxxx, 1111 xxxx 3299 throw new UTFDataFormatException(); 3300 } 3301 } 3302 } 3303 3304 /** 3305 * Unsynchronized table which tracks wire handle to object mappings, as 3306 * well as ClassNotFoundExceptions associated with deserialized objects. 3307 * This class implements an exception-propagation algorithm for 3308 * determining which objects should have ClassNotFoundExceptions associated 3309 * with them, taking into account cycles and discontinuities (e.g., skipped 3310 * fields) in the object graph. 3311 * 3312 * <p>General use of the table is as follows: during deserialization, a 3313 * given object is first assigned a handle by calling the assign method. 3314 * This method leaves the assigned handle in an "open" state, wherein 3315 * dependencies on the exception status of other handles can be registered 3316 * by calling the markDependency method, or an exception can be directly 3317 * associated with the handle by calling markException. When a handle is 3318 * tagged with an exception, the HandleTable assumes responsibility for 3319 * propagating the exception to any other objects which depend 3320 * (transitively) on the exception-tagged object. 3321 * 3322 * <p>Once all exception information/dependencies for the handle have been 3323 * registered, the handle should be "closed" by calling the finish method 3324 * on it. The act of finishing a handle allows the exception propagation 3325 * algorithm to aggressively prune dependency links, lessening the 3326 * performance/memory impact of exception tracking. 3327 * 3328 * <p>Note that the exception propagation algorithm used depends on handles 3329 * being assigned/finished in LIFO order; however, for simplicity as well 3330 * as memory conservation, it does not enforce this constraint. 3331 */ 3332 // REMIND: add full description of exception propagation algorithm? 3333 private static class HandleTable { 3334 3335 /* status codes indicating whether object has associated exception */ 3336 private static final byte STATUS_OK = 1; 3337 private static final byte STATUS_UNKNOWN = 2; 3338 private static final byte STATUS_EXCEPTION = 3; 3339 3340 /** array mapping handle -> object status */ 3341 byte[] status; 3342 /** array mapping handle -> object/exception (depending on status) */ 3343 Object[] entries; 3344 /** array mapping handle -> list of dependent handles (if any) */ 3345 HandleList[] deps; 3346 /** lowest unresolved dependency */ 3347 int lowDep = -1; 3348 /** number of handles in table */ 3349 int size = 0; 3350 3351 /** 3352 * Creates handle table with the given initial capacity. 3353 */ 3354 HandleTable(int initialCapacity) { 3355 status = new byte[initialCapacity]; 3356 entries = new Object[initialCapacity]; 3357 deps = new HandleList[initialCapacity]; 3358 } 3359 3360 /** 3361 * Assigns next available handle to given object, and returns assigned 3362 * handle. Once object has been completely deserialized (and all 3363 * dependencies on other objects identified), the handle should be 3364 * "closed" by passing it to finish(). 3365 */ 3366 int assign(Object obj) { 3367 if (size >= entries.length) { 3368 grow(); 3369 } 3370 status[size] = STATUS_UNKNOWN; 3371 entries[size] = obj; 3372 return size++; 3373 } 3374 3375 /** 3376 * Registers a dependency (in exception status) of one handle on 3377 * another. The dependent handle must be "open" (i.e., assigned, but 3378 * not finished yet). No action is taken if either dependent or target 3379 * handle is NULL_HANDLE. 3380 */ 3381 void markDependency(int dependent, int target) { 3382 if (dependent == NULL_HANDLE || target == NULL_HANDLE) { 3383 return; 3384 } 3385 switch (status[dependent]) { 3386 3387 case STATUS_UNKNOWN: 3388 switch (status[target]) { 3389 case STATUS_OK: 3390 // ignore dependencies on objs with no exception 3391 break; 3392 3393 case STATUS_EXCEPTION: 3394 // eagerly propagate exception 3395 markException(dependent, 3396 (ClassNotFoundException) entries[target]); 3397 break; 3398 3399 case STATUS_UNKNOWN: 3400 // add to dependency list of target 3401 if (deps[target] == null) { 3402 deps[target] = new HandleList(); 3403 } 3404 deps[target].add(dependent); 3405 3406 // remember lowest unresolved target seen 3407 if (lowDep < 0 || lowDep > target) { 3408 lowDep = target; 3409 } 3410 break; 3411 3412 default: 3413 throw new InternalError(); 3414 } 3415 break; 3416 3417 case STATUS_EXCEPTION: 3418 break; 3419 3420 default: 3421 throw new InternalError(); 3422 } 3423 } 3424 3425 /** 3426 * Associates a ClassNotFoundException (if one not already associated) 3427 * with the currently active handle and propagates it to other 3428 * referencing objects as appropriate. The specified handle must be 3429 * "open" (i.e., assigned, but not finished yet). 3430 */ 3431 void markException(int handle, ClassNotFoundException ex) { 3432 switch (status[handle]) { 3433 case STATUS_UNKNOWN: 3434 status[handle] = STATUS_EXCEPTION; 3435 entries[handle] = ex; 3436 3437 // propagate exception to dependents 3438 HandleList dlist = deps[handle]; 3439 if (dlist != null) { 3440 int ndeps = dlist.size(); 3441 for (int i = 0; i < ndeps; i++) { 3442 markException(dlist.get(i), ex); 3443 } 3444 deps[handle] = null; 3445 } 3446 break; 3447 3448 case STATUS_EXCEPTION: 3449 break; 3450 3451 default: 3452 throw new InternalError(); 3453 } 3454 } 3455 3456 /** 3457 * Marks given handle as finished, meaning that no new dependencies 3458 * will be marked for handle. Calls to the assign and finish methods 3459 * must occur in LIFO order. 3460 */ 3461 void finish(int handle) { 3462 int end; 3463 if (lowDep < 0) { 3464 // no pending unknowns, only resolve current handle 3465 end = handle + 1; 3466 } else if (lowDep >= handle) { 3467 // pending unknowns now clearable, resolve all upward handles 3468 end = size; 3469 lowDep = -1; 3470 } else { 3471 // unresolved backrefs present, can't resolve anything yet 3472 return; 3473 } 3474 3475 // change STATUS_UNKNOWN -> STATUS_OK in selected span of handles 3476 for (int i = handle; i < end; i++) { 3477 switch (status[i]) { 3478 case STATUS_UNKNOWN: 3479 status[i] = STATUS_OK; 3480 deps[i] = null; 3481 break; 3482 3483 case STATUS_OK: 3484 case STATUS_EXCEPTION: 3485 break; 3486 3487 default: 3488 throw new InternalError(); 3489 } 3490 } 3491 } 3492 3493 /** 3494 * Assigns a new object to the given handle. The object previously 3495 * associated with the handle is forgotten. This method has no effect 3496 * if the given handle already has an exception associated with it. 3497 * This method may be called at any time after the handle is assigned. 3498 */ 3499 void setObject(int handle, Object obj) { 3500 switch (status[handle]) { 3501 case STATUS_UNKNOWN: 3502 case STATUS_OK: 3503 entries[handle] = obj; 3504 break; 3505 3506 case STATUS_EXCEPTION: 3507 break; 3508 3509 default: 3510 throw new InternalError(); 3511 } 3512 } 3513 3514 /** 3515 * Looks up and returns object associated with the given handle. 3516 * Returns null if the given handle is NULL_HANDLE, or if it has an 3517 * associated ClassNotFoundException. 3518 */ 3519 Object lookupObject(int handle) { 3520 return (handle != NULL_HANDLE && 3521 status[handle] != STATUS_EXCEPTION) ? 3522 entries[handle] : null; 3523 } 3524 3525 /** 3526 * Looks up and returns ClassNotFoundException associated with the 3527 * given handle. Returns null if the given handle is NULL_HANDLE, or 3528 * if there is no ClassNotFoundException associated with the handle. 3529 */ 3530 ClassNotFoundException lookupException(int handle) { 3531 return (handle != NULL_HANDLE && 3532 status[handle] == STATUS_EXCEPTION) ? 3533 (ClassNotFoundException) entries[handle] : null; 3534 } 3535 3536 /** 3537 * Resets table to its initial state. 3538 */ 3539 void clear() { 3540 Arrays.fill(status, 0, size, (byte) 0); 3541 Arrays.fill(entries, 0, size, null); 3542 Arrays.fill(deps, 0, size, null); 3543 lowDep = -1; 3544 size = 0; 3545 } 3546 3547 /** 3548 * Returns number of handles registered in table. 3549 */ 3550 int size() { 3551 return size; 3552 } 3553 3554 /** 3555 * Expands capacity of internal arrays. 3556 */ 3557 private void grow() { 3558 int newCapacity = (entries.length << 1) + 1; 3559 3560 byte[] newStatus = new byte[newCapacity]; 3561 Object[] newEntries = new Object[newCapacity]; 3562 HandleList[] newDeps = new HandleList[newCapacity]; 3563 3564 System.arraycopy(status, 0, newStatus, 0, size); 3565 System.arraycopy(entries, 0, newEntries, 0, size); 3566 System.arraycopy(deps, 0, newDeps, 0, size); 3567 3568 status = newStatus; 3569 entries = newEntries; 3570 deps = newDeps; 3571 } 3572 3573 /** 3574 * Simple growable list of (integer) handles. 3575 */ 3576 private static class HandleList { 3577 private int[] list = new int[4]; 3578 private int size = 0; 3579 3580 public HandleList() { 3581 } 3582 3583 public void add(int handle) { 3584 if (size >= list.length) { 3585 int[] newList = new int[list.length << 1]; 3586 System.arraycopy(list, 0, newList, 0, list.length); 3587 list = newList; 3588 } 3589 list[size++] = handle; 3590 } 3591 3592 public int get(int index) { 3593 if (index >= size) { 3594 throw new ArrayIndexOutOfBoundsException(); 3595 } 3596 return list[index]; 3597 } 3598 3599 public int size() { 3600 return size; 3601 } 3602 } 3603 } 3604 3605 /** 3606 * Method for cloning arrays in case of using unsharing reading 3607 */ 3608 private static Object cloneArray(Object array) { 3609 if (array instanceof Object[]) { 3610 return ((Object[]) array).clone(); 3611 } else if (array instanceof boolean[]) { 3612 return ((boolean[]) array).clone(); 3613 } else if (array instanceof byte[]) { 3614 return ((byte[]) array).clone(); 3615 } else if (array instanceof char[]) { 3616 return ((char[]) array).clone(); 3617 } else if (array instanceof double[]) { 3618 return ((double[]) array).clone(); 3619 } else if (array instanceof float[]) { 3620 return ((float[]) array).clone(); 3621 } else if (array instanceof int[]) { 3622 return ((int[]) array).clone(); 3623 } else if (array instanceof long[]) { 3624 return ((long[]) array).clone(); 3625 } else if (array instanceof short[]) { 3626 return ((short[]) array).clone(); 3627 } else { 3628 throw new AssertionError(); 3629 } 3630 } 3631 3632 }