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