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