1. /*
  2. * @(#)ObjectStreamClass.java 1.130 03/01/23
  3. *
  4. * Copyright 2003 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.Constructor;
  9. import java.lang.reflect.Field;
  10. import java.lang.reflect.InvocationTargetException;
  11. import java.lang.reflect.Member;
  12. import java.lang.reflect.Method;
  13. import java.lang.reflect.Modifier;
  14. import java.lang.reflect.Proxy;
  15. import java.security.AccessController;
  16. import java.security.MessageDigest;
  17. import java.security.NoSuchAlgorithmException;
  18. import java.security.PrivilegedAction;
  19. import java.util.ArrayList;
  20. import java.util.Arrays;
  21. import java.util.Collections;
  22. import java.util.Comparator;
  23. import java.util.HashSet;
  24. import java.util.Set;
  25. import sun.misc.SoftCache;
  26. import sun.misc.Unsafe;
  27. import sun.reflect.ReflectionFactory;
  28. /**
  29. * Serialization's descriptor for classes. It contains the name and
  30. * serialVersionUID of the class. The ObjectStreamClass for a specific class
  31. * loaded in this Java VM can be found/created using the lookup method.
  32. *
  33. * <p>The algorithm to compute the SerialVersionUID is described in
  34. * <a href="../../../guide/serialization/spec/class.doc4.html">Object
  35. * Serialization Specification, Section 4.4, Stream Unique Identifiers</a>.
  36. *
  37. * @author Mike Warres
  38. * @author Roger Riggs
  39. * @version 1.98 02/02/00
  40. * @see ObjectStreamField
  41. * @see <a href="../../../guide/serialization/spec/class.doc.html">Object Serialization Specification, Section 4, Class Descriptors</a>
  42. * @since JDK1.1
  43. */
  44. public class ObjectStreamClass implements Serializable {
  45. /** serialPersistentFields value indicating no serializable fields */
  46. public static final ObjectStreamField[] NO_FIELDS =
  47. new ObjectStreamField[0];
  48. private static final long serialVersionUID = -6120832682080437368L;
  49. private static final ObjectStreamField[] serialPersistentFields =
  50. NO_FIELDS;
  51. /** reflection factory for obtaining serialization constructors */
  52. private static final ReflectionFactory reflFactory = (ReflectionFactory)
  53. AccessController.doPrivileged(
  54. new ReflectionFactory.GetReflectionFactoryAction());
  55. /** cache mapping local classes -> descriptors */
  56. private static final SoftCache localDescs = new SoftCache(10);
  57. /** cache mapping field group/local desc pairs -> field reflectors */
  58. private static final SoftCache reflectors = new SoftCache(10);
  59. /** class associated with this descriptor (if any) */
  60. private Class cl;
  61. /** name of class represented by this descriptor */
  62. private String name;
  63. /** serialVersionUID of represented class (null if not computed yet) */
  64. private volatile Long suid;
  65. /** true if represents dynamic proxy class */
  66. private boolean isProxy;
  67. /** true if represented class implements Serializable */
  68. private boolean serializable;
  69. /** true if represented class implements Externalizable */
  70. private boolean externalizable;
  71. /** true if desc has data written by class-defined writeObject method */
  72. private boolean hasWriteObjectData;
  73. /**
  74. * true if desc has externalizable data written in block data format; this
  75. * must be true by default to accomodate ObjectInputStream subclasses which
  76. * override readClassDescriptor() to return class descriptors obtained from
  77. * ObjectStreamClass.lookup() (see 4461737)
  78. */
  79. private boolean hasBlockExternalData = true;
  80. /** exception (if any) thrown while attempting to resolve class */
  81. private ClassNotFoundException resolveEx;
  82. /** exception (if any) to be thrown if deserialization attempted */
  83. private InvalidClassException deserializeEx;
  84. /** exception (if any) to be thrown if serialization attempted */
  85. private InvalidClassException serializeEx;
  86. /** exception (if any) to be thrown if default serialization attempted */
  87. private InvalidClassException defaultSerializeEx;
  88. /** serializable fields */
  89. private ObjectStreamField[] fields;
  90. /** aggregate marshalled size of primitive fields */
  91. private int primDataSize;
  92. /** number of non-primitive fields */
  93. private int numObjFields;
  94. /** reflector for setting/getting serializable field values */
  95. private FieldReflector fieldRefl;
  96. /** data layout of serialized objects described by this class desc */
  97. private volatile ClassDataSlot[] dataLayout;
  98. /** serialization-appropriate constructor, or null if none */
  99. private Constructor cons;
  100. /** class-defined writeObject method, or null if none */
  101. private Method writeObjectMethod;
  102. /** class-defined readObject method, or null if none */
  103. private Method readObjectMethod;
  104. /** class-defined readObjectNoData method, or null if none */
  105. private Method readObjectNoDataMethod;
  106. /** class-defined writeReplace method, or null if none */
  107. private Method writeReplaceMethod;
  108. /** class-defined readResolve method, or null if none */
  109. private Method readResolveMethod;
  110. /** local class descriptor for represented class (may point to self) */
  111. private ObjectStreamClass localDesc;
  112. /** superclass descriptor appearing in stream */
  113. private ObjectStreamClass superDesc;
  114. /**
  115. * Initializes native code.
  116. */
  117. private static native void initNative();
  118. static {
  119. initNative();
  120. }
  121. /**
  122. * Find the descriptor for a class that can be serialized. Creates an
  123. * ObjectStreamClass instance if one does not exist yet for class. Null is
  124. * returned if the specified class does not implement java.io.Serializable
  125. * or java.io.Externalizable.
  126. *
  127. * @param cl class for which to get the descriptor
  128. * @return the class descriptor for the specified class
  129. */
  130. public static ObjectStreamClass lookup(Class cl) {
  131. return lookup(cl, false);
  132. }
  133. /**
  134. * The name of the class described by this descriptor.
  135. *
  136. * @return a <code>String</code> representing the fully qualified name of
  137. * the class
  138. */
  139. public String getName() {
  140. return name;
  141. }
  142. /**
  143. * Return the serialVersionUID for this class. The serialVersionUID
  144. * defines a set of classes all with the same name that have evolved from a
  145. * common root class and agree to be serialized and deserialized using a
  146. * common format. NonSerializable classes have a serialVersionUID of 0L.
  147. *
  148. * @return the SUID of the class described by this descriptor
  149. */
  150. public long getSerialVersionUID() {
  151. // REMIND: synchronize instead of relying on volatile?
  152. if (suid == null) {
  153. suid = (Long) AccessController.doPrivileged(
  154. new PrivilegedAction() {
  155. public Object run() {
  156. return new Long(computeDefaultSUID(cl));
  157. }
  158. }
  159. );
  160. }
  161. return suid.longValue();
  162. }
  163. /**
  164. * Return the class in the local VM that this version is mapped to. Null
  165. * is returned if there is no corresponding local class.
  166. *
  167. * @return the <code>Class</code> instance that this descriptor represents
  168. */
  169. public Class forClass() {
  170. return cl;
  171. }
  172. /**
  173. * Return an array of the fields of this serializable class.
  174. *
  175. * @return an array containing an element for each persistent field of
  176. * this class. Returns an array of length zero if there are no
  177. * fields.
  178. * @since 1.2
  179. */
  180. public ObjectStreamField[] getFields() {
  181. return getFields(true);
  182. }
  183. /**
  184. * Get the field of this class by name.
  185. *
  186. * @param name the name of the data field to look for
  187. * @return The ObjectStreamField object of the named field or null if
  188. * there is no such named field.
  189. */
  190. public ObjectStreamField getField(String name) {
  191. return getField(name, null);
  192. }
  193. /**
  194. * Return a string describing this ObjectStreamClass.
  195. */
  196. public String toString() {
  197. return name + ": static final long serialVersionUID = " +
  198. getSerialVersionUID() + "L;";
  199. }
  200. /**
  201. * Looks up and returns class descriptor for given class, or null if class
  202. * is non-serializable and "all" is set to false.
  203. *
  204. * @param cl class to look up
  205. * @param all if true, return descriptors for all classes; if false, only
  206. * return descriptors for serializable classes
  207. */
  208. static ObjectStreamClass lookup(Class cl, boolean all) {
  209. if (!(all || Serializable.class.isAssignableFrom(cl))) {
  210. return null;
  211. }
  212. /*
  213. * Note: using the class directly as the key for storing entries does
  214. * not pin the class indefinitely, since SoftCache removes strong refs
  215. * to keys when the corresponding values are gc'ed.
  216. */
  217. Object entry;
  218. EntryFuture future = null;
  219. synchronized (localDescs) {
  220. if ((entry = localDescs.get(cl)) == null) {
  221. localDescs.put(cl, future = new EntryFuture());
  222. }
  223. }
  224. if (entry instanceof ObjectStreamClass) { // check common case first
  225. return (ObjectStreamClass) entry;
  226. } else if (entry instanceof EntryFuture) {
  227. entry = ((EntryFuture) entry).get();
  228. } else if (entry == null) {
  229. try {
  230. entry = new ObjectStreamClass(cl);
  231. } catch (Throwable th) {
  232. entry = th;
  233. }
  234. future.set(entry);
  235. synchronized (localDescs) {
  236. localDescs.put(cl, entry);
  237. }
  238. }
  239. if (entry instanceof ObjectStreamClass) {
  240. return (ObjectStreamClass) entry;
  241. } else if (entry instanceof RuntimeException) {
  242. throw (RuntimeException) entry;
  243. } else if (entry instanceof Error) {
  244. throw (Error) entry;
  245. } else {
  246. throw new InternalError("unexpected entry: " + entry);
  247. }
  248. }
  249. /**
  250. * Placeholder used in class descriptor and field reflector lookup tables
  251. * for an entry in the process of being initialized. (Internal) callers
  252. * which receive an EntryFuture as the result of a lookup should call the
  253. * get() method of the EntryFuture; this will return the actual entry once
  254. * it is ready for use and has been set(). To conserve objects,
  255. * EntryFutures synchronize on themselves.
  256. */
  257. private static class EntryFuture {
  258. private static final Object unset = new Object();
  259. private Object entry = unset;
  260. synchronized void set(Object entry) {
  261. if (this.entry != unset) {
  262. throw new IllegalStateException();
  263. }
  264. this.entry = entry;
  265. notifyAll();
  266. }
  267. synchronized Object get() {
  268. boolean interrupted = false;
  269. while (entry == unset) {
  270. try {
  271. wait();
  272. } catch (InterruptedException ex) {
  273. interrupted = true;
  274. }
  275. }
  276. if (interrupted) {
  277. AccessController.doPrivileged(
  278. new PrivilegedAction() {
  279. public Object run() {
  280. Thread.currentThread().interrupt();
  281. return null;
  282. }
  283. }
  284. );
  285. }
  286. return entry;
  287. }
  288. }
  289. /**
  290. * Creates local class descriptor representing given class.
  291. */
  292. private ObjectStreamClass(final Class cl) {
  293. this.cl = cl;
  294. name = cl.getName();
  295. isProxy = Proxy.isProxyClass(cl);
  296. serializable = Serializable.class.isAssignableFrom(cl);
  297. externalizable = Externalizable.class.isAssignableFrom(cl);
  298. Class superCl = cl.getSuperclass();
  299. superDesc = (superCl != null) ? lookup(superCl, false) : null;
  300. localDesc = this;
  301. if (serializable) {
  302. AccessController.doPrivileged(new PrivilegedAction() {
  303. public Object run() {
  304. suid = getDeclaredSUID(cl);
  305. try {
  306. fields = getSerialFields(cl);
  307. computeFieldOffsets();
  308. } catch (InvalidClassException e) {
  309. serializeEx = deserializeEx = e;
  310. fields = NO_FIELDS;
  311. }
  312. if (externalizable) {
  313. cons = getExternalizableConstructor(cl);
  314. } else {
  315. cons = getSerializableConstructor(cl);
  316. writeObjectMethod = getPrivateMethod(cl, "writeObject",
  317. new Class[] { ObjectOutputStream.class },
  318. Void.TYPE);
  319. readObjectMethod = getPrivateMethod(cl, "readObject",
  320. new Class[] { ObjectInputStream.class },
  321. Void.TYPE);
  322. readObjectNoDataMethod = getPrivateMethod(
  323. cl, "readObjectNoData",
  324. new Class[0], Void.TYPE);
  325. hasWriteObjectData = (writeObjectMethod != null);
  326. }
  327. writeReplaceMethod = getInheritableMethod(
  328. cl, "writeReplace", new Class[0], Object.class);
  329. readResolveMethod = getInheritableMethod(
  330. cl, "readResolve", new Class[0], Object.class);
  331. return null;
  332. }
  333. });
  334. } else {
  335. suid = new Long(0);
  336. fields = NO_FIELDS;
  337. }
  338. try {
  339. fieldRefl = getReflector(fields, this);
  340. } catch (InvalidClassException ex) {
  341. // field mismatches impossible when matching local fields vs. self
  342. throw new InternalError();
  343. }
  344. if (cons == null) {
  345. deserializeEx = new InvalidClassException(
  346. name, "no valid constructor");
  347. }
  348. for (int i = 0; i < fields.length; i++) {
  349. if (fields[i].getField() == null) {
  350. defaultSerializeEx = new InvalidClassException(
  351. name, "unmatched serializable field(s) declared");
  352. }
  353. }
  354. }
  355. /**
  356. * Creates blank class descriptor which should be initialized via a
  357. * subsequent call to initProxy(), initNonProxy() or readNonProxy().
  358. */
  359. ObjectStreamClass() {
  360. }
  361. /**
  362. * Initializes class descriptor representing a proxy class.
  363. */
  364. void initProxy(Class cl,
  365. ClassNotFoundException resolveEx,
  366. ObjectStreamClass superDesc)
  367. throws InvalidClassException
  368. {
  369. this.cl = cl;
  370. this.resolveEx = resolveEx;
  371. this.superDesc = superDesc;
  372. isProxy = true;
  373. serializable = true;
  374. suid = new Long(0);
  375. fields = NO_FIELDS;
  376. if (cl != null) {
  377. localDesc = lookup(cl, true);
  378. if (!localDesc.isProxy) {
  379. throw new InvalidClassException(
  380. "cannot bind proxy descriptor to a non-proxy class");
  381. }
  382. name = localDesc.name;
  383. externalizable = localDesc.externalizable;
  384. cons = localDesc.cons;
  385. writeReplaceMethod = localDesc.writeReplaceMethod;
  386. readResolveMethod = localDesc.readResolveMethod;
  387. deserializeEx = localDesc.deserializeEx;
  388. }
  389. fieldRefl = getReflector(fields, localDesc);
  390. }
  391. /**
  392. * Initializes class descriptor representing a non-proxy class.
  393. */
  394. void initNonProxy(ObjectStreamClass model,
  395. Class cl,
  396. ClassNotFoundException resolveEx,
  397. ObjectStreamClass superDesc)
  398. throws InvalidClassException
  399. {
  400. this.cl = cl;
  401. this.resolveEx = resolveEx;
  402. this.superDesc = superDesc;
  403. name = model.name;
  404. suid = new Long(model.getSerialVersionUID());
  405. isProxy = false;
  406. serializable = model.serializable;
  407. externalizable = model.externalizable;
  408. hasBlockExternalData = model.hasBlockExternalData;
  409. hasWriteObjectData = model.hasWriteObjectData;
  410. fields = model.fields;
  411. primDataSize = model.primDataSize;
  412. numObjFields = model.numObjFields;
  413. if (cl != null) {
  414. localDesc = lookup(cl, true);
  415. if (localDesc.isProxy) {
  416. throw new InvalidClassException(
  417. "cannot bind non-proxy descriptor to a proxy class");
  418. }
  419. if (serializable == localDesc.serializable &&
  420. !cl.isArray() &&
  421. suid.longValue() != localDesc.getSerialVersionUID())
  422. {
  423. throw new InvalidClassException(localDesc.name,
  424. "local class incompatible: " +
  425. "stream classdesc serialVersionUID = " + suid +
  426. ", local class serialVersionUID = " +
  427. localDesc.getSerialVersionUID());
  428. }
  429. if (!classNamesEqual(name, localDesc.name)) {
  430. throw new InvalidClassException(localDesc.name,
  431. "local class name incompatible with stream class " +
  432. "name \"" + name + "\"");
  433. }
  434. if ((serializable == localDesc.serializable) &&
  435. (externalizable != localDesc.externalizable))
  436. {
  437. throw new InvalidClassException(localDesc.name,
  438. "Serializable incompatible with Externalizable");
  439. }
  440. if ((serializable != localDesc.serializable) ||
  441. (externalizable != localDesc.externalizable) ||
  442. !(serializable || externalizable))
  443. {
  444. deserializeEx = new InvalidClassException(localDesc.name,
  445. "class invalid for deserialization");
  446. }
  447. cons = localDesc.cons;
  448. writeObjectMethod = localDesc.writeObjectMethod;
  449. readObjectMethod = localDesc.readObjectMethod;
  450. readObjectNoDataMethod = localDesc.readObjectNoDataMethod;
  451. writeReplaceMethod = localDesc.writeReplaceMethod;
  452. readResolveMethod = localDesc.readResolveMethod;
  453. if (deserializeEx == null) {
  454. deserializeEx = localDesc.deserializeEx;
  455. }
  456. }
  457. fieldRefl = getReflector(fields, localDesc);
  458. // reassign to matched fields so as to reflect local unshared settings
  459. fields = fieldRefl.getFields();
  460. }
  461. /**
  462. * Reads non-proxy class descriptor information from given input stream.
  463. * The resulting class descriptor is not fully functional; it can only be
  464. * used as input to the ObjectInputStream.resolveClass() and
  465. * ObjectStreamClass.initNonProxy() methods.
  466. */
  467. void readNonProxy(ObjectInputStream in)
  468. throws IOException, ClassNotFoundException
  469. {
  470. name = in.readUTF();
  471. suid = new Long(in.readLong());
  472. isProxy = false;
  473. byte flags = in.readByte();
  474. hasWriteObjectData =
  475. ((flags & ObjectStreamConstants.SC_WRITE_METHOD) != 0);
  476. hasBlockExternalData =
  477. ((flags & ObjectStreamConstants.SC_BLOCK_DATA) != 0);
  478. externalizable =
  479. ((flags & ObjectStreamConstants.SC_EXTERNALIZABLE) != 0);
  480. boolean sflag =
  481. ((flags & ObjectStreamConstants.SC_SERIALIZABLE) != 0);
  482. if (externalizable && sflag) {
  483. throw new InvalidClassException(
  484. name, "serializable and externalizable flags conflict");
  485. }
  486. serializable = externalizable || sflag;
  487. int numFields = in.readShort();
  488. fields = (numFields > 0) ?
  489. new ObjectStreamField[numFields] : NO_FIELDS;
  490. for (int i = 0; i < numFields; i++) {
  491. char tcode = (char) in.readByte();
  492. String fname = in.readUTF();
  493. String signature = ((tcode == 'L') || (tcode == '[')) ?
  494. in.readTypeString() : new String(new char[] { tcode });
  495. try {
  496. fields[i] = new ObjectStreamField(fname, signature, false);
  497. } catch (RuntimeException e) {
  498. throw (IOException) new InvalidClassException(name,
  499. "invalid descriptor for field " + fname).initCause(e);
  500. }
  501. }
  502. computeFieldOffsets();
  503. }
  504. /**
  505. * Writes non-proxy class descriptor information to given output stream.
  506. */
  507. void writeNonProxy(ObjectOutputStream out) throws IOException {
  508. out.writeUTF(name);
  509. out.writeLong(getSerialVersionUID());
  510. byte flags = 0;
  511. if (externalizable) {
  512. flags |= ObjectStreamConstants.SC_EXTERNALIZABLE;
  513. int protocol = out.getProtocolVersion();
  514. if (protocol != ObjectStreamConstants.PROTOCOL_VERSION_1) {
  515. flags |= ObjectStreamConstants.SC_BLOCK_DATA;
  516. }
  517. } else if (serializable) {
  518. flags |= ObjectStreamConstants.SC_SERIALIZABLE;
  519. }
  520. if (hasWriteObjectData) {
  521. flags |= ObjectStreamConstants.SC_WRITE_METHOD;
  522. }
  523. out.writeByte(flags);
  524. out.writeShort(fields.length);
  525. for (int i = 0; i < fields.length; i++) {
  526. ObjectStreamField f = fields[i];
  527. out.writeByte(f.getTypeCode());
  528. out.writeUTF(f.getName());
  529. if (!f.isPrimitive()) {
  530. out.writeTypeString(f.getTypeString());
  531. }
  532. }
  533. }
  534. /**
  535. * Returns ClassNotFoundException (if any) thrown while attempting to
  536. * resolve local class corresponding to this class descriptor.
  537. */
  538. ClassNotFoundException getResolveException() {
  539. return resolveEx;
  540. }
  541. /**
  542. * Throws an InvalidClassException if object instances referencing this
  543. * class descriptor should not be allowed to deserialize.
  544. */
  545. void checkDeserialize() throws InvalidClassException {
  546. if (deserializeEx != null) {
  547. throw deserializeEx;
  548. }
  549. }
  550. /**
  551. * Throws an InvalidClassException if objects whose class is represented by
  552. * this descriptor should not be allowed to serialize.
  553. */
  554. void checkSerialize() throws InvalidClassException {
  555. if (serializeEx != null) {
  556. throw serializeEx;
  557. }
  558. }
  559. /**
  560. * Throws an InvalidClassException if objects whose class is represented by
  561. * this descriptor should not be permitted to use default serialization
  562. * (e.g., if the class declares serializable fields that do not correspond
  563. * to actual fields, and hence must use the GetField API).
  564. */
  565. void checkDefaultSerialize() throws InvalidClassException {
  566. if (defaultSerializeEx != null) {
  567. throw defaultSerializeEx;
  568. }
  569. }
  570. /**
  571. * Returns superclass descriptor. Note that on the receiving side, the
  572. * superclass descriptor may be bound to a class that is not a superclass
  573. * of the subclass descriptor's bound class.
  574. */
  575. ObjectStreamClass getSuperDesc() {
  576. return superDesc;
  577. }
  578. /**
  579. * Returns the "local" class descriptor for the class associated with this
  580. * class descriptor (i.e., the result of
  581. * ObjectStreamClass.lookup(this.forClass())) or null if there is no class
  582. * associated with this descriptor.
  583. */
  584. ObjectStreamClass getLocalDesc() {
  585. return localDesc;
  586. }
  587. /**
  588. * Returns arrays of ObjectStreamFields representing the serializable
  589. * fields of the represented class. If copy is true, a clone of this class
  590. * descriptor's field array is returned, otherwise the array itself is
  591. * returned.
  592. */
  593. ObjectStreamField[] getFields(boolean copy) {
  594. return copy ? (ObjectStreamField[]) fields.clone() : fields;
  595. }
  596. /**
  597. * Looks up a serializable field of the represented class by name and type.
  598. * A specified type of null matches all types, Object.class matches all
  599. * non-primitive types, and any other non-null type matches assignable
  600. * types only. Returns matching field, or null if no match found.
  601. */
  602. ObjectStreamField getField(String name, Class type) {
  603. for (int i = 0; i < fields.length; i++) {
  604. ObjectStreamField f = fields[i];
  605. if (f.getName().equals(name)) {
  606. if (type == null ||
  607. (type == Object.class && !f.isPrimitive()))
  608. {
  609. return f;
  610. }
  611. Class ftype = f.getType();
  612. if (ftype != null && type.isAssignableFrom(ftype)) {
  613. return f;
  614. }
  615. }
  616. }
  617. return null;
  618. }
  619. /**
  620. * Returns true if class descriptor represents a dynamic proxy class, false
  621. * otherwise.
  622. */
  623. boolean isProxy() {
  624. return isProxy;
  625. }
  626. /**
  627. * Returns true if represented class implements Externalizable, false
  628. * otherwise.
  629. */
  630. boolean isExternalizable() {
  631. return externalizable;
  632. }
  633. /**
  634. * Returns true if represented class implements Serializable, false
  635. * otherwise.
  636. */
  637. boolean isSerializable() {
  638. return serializable;
  639. }
  640. /**
  641. * Returns true if class descriptor represents externalizable class that
  642. * has written its data in 1.2 (block data) format, false otherwise.
  643. */
  644. boolean hasBlockExternalData() {
  645. return hasBlockExternalData;
  646. }
  647. /**
  648. * Returns true if class descriptor represents serializable (but not
  649. * externalizable) class which has written its data via a custom
  650. * writeObject() method, false otherwise.
  651. */
  652. boolean hasWriteObjectData() {
  653. return hasWriteObjectData;
  654. }
  655. /**
  656. * Returns true if represented class is serializable/externalizable and can
  657. * be instantiated by the serialization runtime--i.e., if it is
  658. * externalizable and defines a public no-arg constructor, or if it is
  659. * non-externalizable and its first non-serializable superclass defines an
  660. * accessible no-arg constructor. Otherwise, returns false.
  661. */
  662. boolean isInstantiable() {
  663. return (cons != null);
  664. }
  665. /**
  666. * Returns true if represented class is serializable (but not
  667. * externalizable) and defines a conformant writeObject method. Otherwise,
  668. * returns false.
  669. */
  670. boolean hasWriteObjectMethod() {
  671. return (writeObjectMethod != null);
  672. }
  673. /**
  674. * Returns true if represented class is serializable (but not
  675. * externalizable) and defines a conformant readObject method. Otherwise,
  676. * returns false.
  677. */
  678. boolean hasReadObjectMethod() {
  679. return (readObjectMethod != null);
  680. }
  681. /**
  682. * Returns true if represented class is serializable (but not
  683. * externalizable) and defines a conformant readObjectNoData method.
  684. * Otherwise, returns false.
  685. */
  686. boolean hasReadObjectNoDataMethod() {
  687. return (readObjectNoDataMethod != null);
  688. }
  689. /**
  690. * Returns true if represented class is serializable or externalizable and
  691. * defines a conformant writeReplace method. Otherwise, returns false.
  692. */
  693. boolean hasWriteReplaceMethod() {
  694. return (writeReplaceMethod != null);
  695. }
  696. /**
  697. * Returns true if represented class is serializable or externalizable and
  698. * defines a conformant readResolve method. Otherwise, returns false.
  699. */
  700. boolean hasReadResolveMethod() {
  701. return (readResolveMethod != null);
  702. }
  703. /**
  704. * Creates a new instance of the represented class. If the class is
  705. * externalizable, invokes its public no-arg constructor; otherwise, if the
  706. * class is serializable, invokes the no-arg constructor of the first
  707. * non-serializable superclass. Throws UnsupportedOperationException if
  708. * this class descriptor is not associated with a class, if the associated
  709. * class is non-serializable or if the appropriate no-arg constructor is
  710. * inaccessible/unavailable.
  711. */
  712. Object newInstance()
  713. throws InstantiationException, InvocationTargetException,
  714. UnsupportedOperationException
  715. {
  716. if (cons != null) {
  717. try {
  718. return cons.newInstance(new Object[0]);
  719. } catch (IllegalAccessException ex) {
  720. // should not occur, as access checks have been suppressed
  721. throw new InternalError();
  722. }
  723. } else {
  724. throw new UnsupportedOperationException();
  725. }
  726. }
  727. /**
  728. * Invokes the writeObject method of the represented serializable class.
  729. * Throws UnsupportedOperationException if this class descriptor is not
  730. * associated with a class, or if the class is externalizable,
  731. * non-serializable or does not define writeObject.
  732. */
  733. void invokeWriteObject(Object obj, ObjectOutputStream out)
  734. throws IOException, UnsupportedOperationException
  735. {
  736. if (writeObjectMethod != null) {
  737. try {
  738. writeObjectMethod.invoke(obj, new Object[]{ out });
  739. } catch (InvocationTargetException ex) {
  740. Throwable th = ex.getTargetException();
  741. if (th instanceof IOException) {
  742. throw (IOException) th;
  743. } else {
  744. throwMiscException(th);
  745. }
  746. } catch (IllegalAccessException ex) {
  747. // should not occur, as access checks have been suppressed
  748. throw new InternalError();
  749. }
  750. } else {
  751. throw new UnsupportedOperationException();
  752. }
  753. }
  754. /**
  755. * Invokes the readObject method of the represented serializable class.
  756. * Throws UnsupportedOperationException if this class descriptor is not
  757. * associated with a class, or if the class is externalizable,
  758. * non-serializable or does not define readObject.
  759. */
  760. void invokeReadObject(Object obj, ObjectInputStream in)
  761. throws ClassNotFoundException, IOException,
  762. UnsupportedOperationException
  763. {
  764. if (readObjectMethod != null) {
  765. try {
  766. readObjectMethod.invoke(obj, new Object[]{ in });
  767. } catch (InvocationTargetException ex) {
  768. Throwable th = ex.getTargetException();
  769. if (th instanceof ClassNotFoundException) {
  770. throw (ClassNotFoundException) th;
  771. } else if (th instanceof IOException) {
  772. throw (IOException) th;
  773. } else {
  774. throwMiscException(th);
  775. }
  776. } catch (IllegalAccessException ex) {
  777. // should not occur, as access checks have been suppressed
  778. throw new InternalError();
  779. }
  780. } else {
  781. throw new UnsupportedOperationException();
  782. }
  783. }
  784. /**
  785. * Invokes the readObjectNoData method of the represented serializable
  786. * class. Throws UnsupportedOperationException if this class descriptor is
  787. * not associated with a class, or if the class is externalizable,
  788. * non-serializable or does not define readObjectNoData.
  789. */
  790. void invokeReadObjectNoData(Object obj)
  791. throws IOException, UnsupportedOperationException
  792. {
  793. if (readObjectNoDataMethod != null) {
  794. try {
  795. readObjectNoDataMethod.invoke(obj, new Object[0]);
  796. } catch (InvocationTargetException ex) {
  797. Throwable th = ex.getTargetException();
  798. if (th instanceof ObjectStreamException) {
  799. throw (ObjectStreamException) th;
  800. } else {
  801. throwMiscException(th);
  802. }
  803. } catch (IllegalAccessException ex) {
  804. // should not occur, as access checks have been suppressed
  805. throw new InternalError();
  806. }
  807. } else {
  808. throw new UnsupportedOperationException();
  809. }
  810. }
  811. /**
  812. * Invokes the writeReplace method of the represented serializable class and
  813. * returns the result. Throws UnsupportedOperationException if this class
  814. * descriptor is not associated with a class, or if the class is
  815. * non-serializable or does not define writeReplace.
  816. */
  817. Object invokeWriteReplace(Object obj)
  818. throws IOException, UnsupportedOperationException
  819. {
  820. if (writeReplaceMethod != null) {
  821. try {
  822. return writeReplaceMethod.invoke(obj, new Object[0]);
  823. } catch (InvocationTargetException ex) {
  824. Throwable th = ex.getTargetException();
  825. if (th instanceof ObjectStreamException) {
  826. throw (ObjectStreamException) th;
  827. } else {
  828. throwMiscException(th);
  829. throw new InternalError(); // never reached
  830. }
  831. } catch (IllegalAccessException ex) {
  832. // should not occur, as access checks have been suppressed
  833. throw new InternalError();
  834. }
  835. } else {
  836. throw new UnsupportedOperationException();
  837. }
  838. }
  839. /**
  840. * Invokes the readResolve method of the represented serializable class and
  841. * returns the result. Throws UnsupportedOperationException if this class
  842. * descriptor is not associated with a class, or if the class is
  843. * non-serializable or does not define readResolve.
  844. */
  845. Object invokeReadResolve(Object obj)
  846. throws IOException, UnsupportedOperationException
  847. {
  848. if (readResolveMethod != null) {
  849. try {
  850. return readResolveMethod.invoke(obj, new Object[0]);
  851. } catch (InvocationTargetException ex) {
  852. Throwable th = ex.getTargetException();
  853. if (th instanceof ObjectStreamException) {
  854. throw (ObjectStreamException) th;
  855. } else {
  856. throwMiscException(th);
  857. throw new InternalError(); // never reached
  858. }
  859. } catch (IllegalAccessException ex) {
  860. // should not occur, as access checks have been suppressed
  861. throw new InternalError();
  862. }
  863. } else {
  864. throw new UnsupportedOperationException();
  865. }
  866. }
  867. /**
  868. * Class representing the portion of an object's serialized form allotted
  869. * to data described by a given class descriptor. If "hasData" is false,
  870. * the object's serialized form does not contain data associated with the
  871. * class descriptor.
  872. */
  873. static class ClassDataSlot {
  874. /** class descriptor "occupying" this slot */
  875. final ObjectStreamClass desc;
  876. /** true if serialized form includes data for this slot's descriptor */
  877. final boolean hasData;
  878. ClassDataSlot(ObjectStreamClass desc, boolean hasData) {
  879. this.desc = desc;
  880. this.hasData = hasData;
  881. }
  882. }
  883. /**
  884. * Returns array of ClassDataSlot instances representing the data layout
  885. * (including superclass data) for serialized objects described by this
  886. * class descriptor. ClassDataSlots are ordered by inheritance with those
  887. * containing "higher" superclasses appearing first. The final
  888. * ClassDataSlot contains a reference to this descriptor.
  889. */
  890. ClassDataSlot[] getClassDataLayout() throws InvalidClassException {
  891. // REMIND: synchronize instead of relying on volatile?
  892. if (dataLayout == null) {
  893. dataLayout = getClassDataLayout0();
  894. }
  895. return dataLayout;
  896. }
  897. private ClassDataSlot[] getClassDataLayout0()
  898. throws InvalidClassException
  899. {
  900. ArrayList slots = new ArrayList();
  901. Class start = cl, end = cl;
  902. // locate closest non-serializable superclass
  903. while (end != null && Serializable.class.isAssignableFrom(end)) {
  904. end = end.getSuperclass();
  905. }
  906. for (ObjectStreamClass d = this; d != null; d = d.superDesc) {
  907. // search up inheritance heirarchy for class with matching name
  908. String searchName = (d.cl != null) ? d.cl.getName() : d.name;
  909. Class match = null;
  910. for (Class c = start; c != end; c = c.getSuperclass()) {
  911. if (searchName.equals(c.getName())) {
  912. match = c;
  913. break;
  914. }
  915. }
  916. // add "no data" slot for each unmatched class below match
  917. if (match != null) {
  918. for (Class c = start; c != match; c = c.getSuperclass()) {
  919. slots.add(new ClassDataSlot(
  920. ObjectStreamClass.lookup(c, true), false));
  921. }
  922. start = match.getSuperclass();
  923. }
  924. // record descriptor/class pairing
  925. slots.add(new ClassDataSlot(d.getVariantFor(match), true));
  926. }
  927. // add "no data" slot for any leftover unmatched classes
  928. for (Class c = start; c != end; c = c.getSuperclass()) {
  929. slots.add(new ClassDataSlot(
  930. ObjectStreamClass.lookup(c, true), false));
  931. }
  932. // order slots from superclass -> subclass
  933. Collections.reverse(slots);
  934. return (ClassDataSlot[])
  935. slots.toArray(new ClassDataSlot[slots.size()]);
  936. }
  937. /**
  938. * Returns aggregate size (in bytes) of marshalled primitive field values
  939. * for represented class.
  940. */
  941. int getPrimDataSize() {
  942. return primDataSize;
  943. }
  944. /**
  945. * Returns number of non-primitive serializable fields of represented
  946. * class.
  947. */
  948. int getNumObjFields() {
  949. return numObjFields;
  950. }
  951. /**
  952. * Fetches the serializable primitive field values of object obj and
  953. * marshals them into byte array buf starting at offset 0. It is the
  954. * responsibility of the caller to ensure that obj is of the proper type if
  955. * non-null.
  956. */
  957. void getPrimFieldValues(Object obj, byte[] buf) {
  958. fieldRefl.getPrimFieldValues(obj, buf);
  959. }
  960. /**
  961. * Sets the serializable primitive fields of object obj using values
  962. * unmarshalled from byte array buf starting at offset 0. It is the
  963. * responsibility of the caller to ensure that obj is of the proper type if
  964. * non-null.
  965. */
  966. void setPrimFieldValues(Object obj, byte[] buf) {
  967. fieldRefl.setPrimFieldValues(obj, buf);
  968. }
  969. /**
  970. * Fetches the serializable object field values of object obj and stores
  971. * them in array vals starting at offset 0. It is the responsibility of
  972. * the caller to ensure that obj is of the proper type if non-null.
  973. */
  974. void getObjFieldValues(Object obj, Object[] vals) {
  975. fieldRefl.getObjFieldValues(obj, vals);
  976. }
  977. /**
  978. * Sets the serializable object fields of object obj using values from
  979. * array vals starting at offset 0. It is the responsibility of the caller
  980. * to ensure that obj is of the proper type if non-null.
  981. */
  982. void setObjFieldValues(Object obj, Object[] vals) {
  983. fieldRefl.setObjFieldValues(obj, vals);
  984. }
  985. /**
  986. * Calculates and sets serializable field offsets, as well as primitive
  987. * data size and object field count totals. Throws InvalidClassException
  988. * if fields are illegally ordered.
  989. */
  990. private void computeFieldOffsets() throws InvalidClassException {
  991. primDataSize = 0;
  992. numObjFields = 0;
  993. int firstObjIndex = -1;
  994. for (int i = 0; i < fields.length; i++) {
  995. ObjectStreamField f = fields[i];
  996. switch (f.getTypeCode()) {
  997. case 'Z':
  998. case 'B':
  999. f.setOffset(primDataSize++);
  1000. break;
  1001. case 'C':
  1002. case 'S':
  1003. f.setOffset(primDataSize);
  1004. primDataSize += 2;
  1005. break;
  1006. case 'I':
  1007. case 'F':
  1008. f.setOffset(primDataSize);
  1009. primDataSize += 4;
  1010. break;
  1011. case 'J':
  1012. case 'D':
  1013. f.setOffset(primDataSize);
  1014. primDataSize += 8;
  1015. break;
  1016. case '[':
  1017. case 'L':
  1018. f.setOffset(numObjFields++);
  1019. if (firstObjIndex == -1) {
  1020. firstObjIndex = i;
  1021. }
  1022. break;
  1023. default:
  1024. throw new InternalError();
  1025. }
  1026. }
  1027. if (firstObjIndex != -1 &&
  1028. firstObjIndex + numObjFields != fields.length)
  1029. {
  1030. throw new InvalidClassException(name, "illegal field order");
  1031. }
  1032. }
  1033. /**
  1034. * If given class is the same as the class associated with this class
  1035. * descriptor, returns reference to this class descriptor. Otherwise,
  1036. * returns variant of this class descriptor bound to given class.
  1037. */
  1038. private ObjectStreamClass getVariantFor(Class cl)
  1039. throws InvalidClassException
  1040. {
  1041. if (this.cl == cl) {
  1042. return this;
  1043. }
  1044. ObjectStreamClass desc = new ObjectStreamClass();
  1045. if (isProxy) {
  1046. desc.initProxy(cl, null, superDesc);
  1047. } else {
  1048. desc.initNonProxy(this, cl, null, superDesc);
  1049. }
  1050. return desc;
  1051. }
  1052. /**
  1053. * Returns public no-arg constructor of given class, or null if none found.
  1054. * Access checks are disabled on the returned constructor (if any), since
  1055. * the defining class may still be non-public.
  1056. */
  1057. private static Constructor getExternalizableConstructor(Class cl) {
  1058. try {
  1059. Constructor cons = cl.getDeclaredConstructor(new Class[0]);
  1060. cons.setAccessible(true);
  1061. return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ?
  1062. cons : null;
  1063. } catch (NoSuchMethodException ex) {
  1064. return null;
  1065. }
  1066. }
  1067. /**
  1068. * Returns subclass-accessible no-arg constructor of first non-serializable
  1069. * superclass, or null if none found. Access checks are disabled on the
  1070. * returned constructor (if any).
  1071. */
  1072. private static Constructor getSerializableConstructor(Class cl) {
  1073. Class initCl = cl;
  1074. while (Serializable.class.isAssignableFrom(initCl)) {
  1075. if ((initCl = initCl.getSuperclass()) == null) {
  1076. return null;
  1077. }
  1078. }
  1079. try {
  1080. Constructor cons = initCl.getDeclaredConstructor(new Class[0]);
  1081. int mods = cons.getModifiers();
  1082. if ((mods & Modifier.PRIVATE) != 0 ||
  1083. ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
  1084. !packageEquals(cl, initCl)))
  1085. {
  1086. return null;
  1087. }
  1088. cons = reflFactory.newConstructorForSerialization(cl, cons);
  1089. cons.setAccessible(true);
  1090. return cons;
  1091. } catch (NoSuchMethodException ex) {
  1092. return null;
  1093. }
  1094. }
  1095. /**
  1096. * Returns non-static, non-abstract method with given signature provided it
  1097. * is defined by or accessible (via inheritance) by the given class, or
  1098. * null if no match found. Access checks are disabled on the returned
  1099. * method (if any).
  1100. */
  1101. private static Method getInheritableMethod(Class cl, String name,
  1102. Class[] argTypes,
  1103. Class returnType)
  1104. {
  1105. Method meth = null;
  1106. Class defCl = cl;
  1107. while (defCl != null) {
  1108. try {
  1109. meth = defCl.getDeclaredMethod(name, argTypes);
  1110. break;
  1111. } catch (NoSuchMethodException ex) {
  1112. defCl = defCl.getSuperclass();
  1113. }
  1114. }
  1115. if ((meth == null) || (meth.getReturnType() != returnType)) {
  1116. return null;
  1117. }
  1118. meth.setAccessible(true);
  1119. int mods = meth.getModifiers();
  1120. if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
  1121. return null;
  1122. } else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
  1123. return meth;
  1124. } else if ((mods & Modifier.PRIVATE) != 0) {
  1125. return (cl == defCl) ? meth : null;
  1126. } else {
  1127. return packageEquals(cl, defCl) ? meth : null;
  1128. }
  1129. }
  1130. /**
  1131. * Returns non-static private method with given signature defined by given
  1132. * class, or null if none found. Access checks are disabled on the
  1133. * returned method (if any).
  1134. */
  1135. private static Method getPrivateMethod(Class cl, String name,
  1136. Class[] argTypes,
  1137. Class returnType)
  1138. {
  1139. try {
  1140. Method meth = cl.getDeclaredMethod(name, argTypes);
  1141. meth.setAccessible(true);
  1142. int mods = meth.getModifiers();
  1143. return ((meth.getReturnType() == returnType) &&
  1144. ((mods & Modifier.STATIC) == 0) &&
  1145. ((mods & Modifier.PRIVATE) != 0)) ? meth : null;
  1146. } catch (NoSuchMethodException ex) {
  1147. return null;
  1148. }
  1149. }
  1150. /**
  1151. * Returns true if classes are defined in the same runtime package, false
  1152. * otherwise.
  1153. */
  1154. private static boolean packageEquals(Class cl1, Class cl2) {
  1155. return (cl1.getClassLoader() == cl2.getClassLoader() &&
  1156. getPackageName(cl1).equals(getPackageName(cl2)));
  1157. }
  1158. /**
  1159. * Returns package name of given class.
  1160. */
  1161. private static String getPackageName(Class cl) {
  1162. String s = cl.getName();
  1163. int i = s.lastIndexOf('[');
  1164. if (i >= 0) {
  1165. s = s.substring(i + 2);
  1166. }
  1167. i = s.lastIndexOf('.');
  1168. return (i >= 0) ? s.substring(0, i) : "";
  1169. }
  1170. /**
  1171. * Compares class names for equality, ignoring package names. Returns true
  1172. * if class names equal, false otherwise.
  1173. */
  1174. private static boolean classNamesEqual(String name1, String name2) {
  1175. name1 = name1.substring(name1.lastIndexOf('.') + 1);
  1176. name2 = name2.substring(name2.lastIndexOf('.') + 1);
  1177. return name1.equals(name2);
  1178. }
  1179. /**
  1180. * Returns JVM type signature for given class.
  1181. */
  1182. static String getClassSignature(Class cl) {
  1183. StringBuffer sbuf = new StringBuffer();
  1184. while (cl.isArray()) {
  1185. sbuf.append('[');
  1186. cl = cl.getComponentType();
  1187. }
  1188. if (cl.isPrimitive()) {
  1189. if (cl == Integer.TYPE) {
  1190. sbuf.append('I');
  1191. } else if (cl == Byte.TYPE) {
  1192. sbuf.append('B');
  1193. } else if (cl == Long.TYPE) {
  1194. sbuf.append('J');
  1195. } else if (cl == Float.TYPE) {
  1196. sbuf.append('F');
  1197. } else if (cl == Double.TYPE) {
  1198. sbuf.append('D');
  1199. } else if (cl == Short.TYPE) {
  1200. sbuf.append('S');
  1201. } else if (cl == Character.TYPE) {
  1202. sbuf.append('C');
  1203. } else if (cl == Boolean.TYPE) {
  1204. sbuf.append('Z');
  1205. } else if (cl == Void.TYPE) {
  1206. sbuf.append('V');
  1207. } else {
  1208. throw new InternalError();
  1209. }
  1210. } else {
  1211. sbuf.append('L' + cl.getName().replace('.', '/') + ';');
  1212. }
  1213. return sbuf.toString();
  1214. }
  1215. /**
  1216. * Returns JVM type signature for given list of parameters and return type.
  1217. */
  1218. private static String getMethodSignature(Class[] paramTypes,
  1219. Class retType)
  1220. {
  1221. StringBuffer sbuf = new StringBuffer();
  1222. sbuf.append('(');
  1223. for (int i = 0; i < paramTypes.length; i++) {
  1224. sbuf.append(getClassSignature(paramTypes[i]));
  1225. }
  1226. sbuf.append(')');
  1227. sbuf.append(getClassSignature(retType));
  1228. return sbuf.toString();
  1229. }
  1230. /**
  1231. * Convenience method for throwing an exception that is either a
  1232. * RuntimeException, Error, or of some unexpected type (in which case it is
  1233. * wrapped inside an IOException).
  1234. */
  1235. private static void throwMiscException(Throwable th) throws IOException {
  1236. if (th instanceof RuntimeException) {
  1237. throw (RuntimeException) th;
  1238. } else if (th instanceof Error) {
  1239. throw (Error) th;
  1240. } else {
  1241. IOException ex = new IOException("unexpected exception type");
  1242. ex.initCause(th);
  1243. throw ex;
  1244. }
  1245. }
  1246. /**
  1247. * Returns ObjectStreamField array describing the serializable fields of
  1248. * the given class. Serializable fields backed by an actual field of the
  1249. * class are represented by ObjectStreamFields with corresponding non-null
  1250. * Field objects. Throws InvalidClassException if the (explicitly
  1251. * declared) serializable fields are invalid.
  1252. */
  1253. private static ObjectStreamField[] getSerialFields(Class cl)
  1254. throws InvalidClassException
  1255. {
  1256. ObjectStreamField[] fields;
  1257. if (Serializable.class.isAssignableFrom(cl) &&
  1258. !Externalizable.class.isAssignableFrom(cl) &&
  1259. !Proxy.isProxyClass(cl) &&
  1260. !cl.isInterface())
  1261. {
  1262. if ((fields = getDeclaredSerialFields(cl)) == null) {
  1263. fields = getDefaultSerialFields(cl);
  1264. }
  1265. Arrays.sort(fields);
  1266. } else {
  1267. fields = NO_FIELDS;
  1268. }
  1269. return fields;
  1270. }
  1271. /**
  1272. * Returns serializable fields of given class as defined explicitly by a
  1273. * "serialPersistentFields" field, or null if no appropriate
  1274. * "serialPersistendFields" field is defined. Serializable fields backed
  1275. * by an actual field of the class are represented by ObjectStreamFields
  1276. * with corresponding non-null Field objects. For compatibility with past
  1277. * releases, a "serialPersistentFields" field with a null value is
  1278. * considered equivalent to not declaring "serialPersistentFields". Throws
  1279. * InvalidClassException if the declared serializable fields are
  1280. * invalid--e.g., if multiple fields share the same name.
  1281. */
  1282. private static ObjectStreamField[] getDeclaredSerialFields(Class cl)
  1283. throws InvalidClassException
  1284. {
  1285. ObjectStreamField[] serialPersistentFields = null;
  1286. try {
  1287. Field f = cl.getDeclaredField("serialPersistentFields");
  1288. int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
  1289. if ((f.getModifiers() & mask) == mask) {
  1290. f.setAccessible(true);
  1291. serialPersistentFields = (ObjectStreamField[]) f.get(null);
  1292. }
  1293. } catch (Exception ex) {
  1294. }
  1295. if (serialPersistentFields == null) {
  1296. return null;
  1297. } else if (serialPersistentFields.length == 0) {
  1298. return NO_FIELDS;
  1299. }
  1300. ObjectStreamField[] boundFields =
  1301. new ObjectStreamField[serialPersistentFields.length];
  1302. Set fieldNames = new HashSet(serialPersistentFields.length);
  1303. for (int i = 0; i < serialPersistentFields.length; i++) {
  1304. ObjectStreamField spf = serialPersistentFields[i];
  1305. String fname = spf.getName();
  1306. if (fieldNames.contains(fname)) {
  1307. throw new InvalidClassException(
  1308. "multiple serializable fields named " + fname);
  1309. }
  1310. fieldNames.add(fname);
  1311. try {
  1312. Field f = cl.getDeclaredField(fname);
  1313. if ((f.getType() == spf.getType()) &&
  1314. ((f.getModifiers() & Modifier.STATIC) == 0))
  1315. {
  1316. boundFields[i] =
  1317. new ObjectStreamField(f, spf.isUnshared(), true);
  1318. }
  1319. } catch (NoSuchFieldException ex) {
  1320. }
  1321. if (boundFields[i] == null) {
  1322. boundFields[i] = new ObjectStreamField(
  1323. fname, spf.getType(), spf.isUnshared());
  1324. }
  1325. }
  1326. return boundFields;
  1327. }
  1328. /**
  1329. * Returns array of ObjectStreamFields corresponding to all non-static
  1330. * non-transient fields declared by given class. Each ObjectStreamField
  1331. * contains a Field object for the field it represents. If no default
  1332. * serializable fields exist, NO_FIELDS is returned.
  1333. */
  1334. private static ObjectStreamField[] getDefaultSerialFields(Class cl) {
  1335. Field[] clFields = cl.getDeclaredFields();
  1336. ArrayList list = new ArrayList();
  1337. int mask = Modifier.STATIC | Modifier.TRANSIENT;
  1338. for (int i = 0; i < clFields.length; i++) {
  1339. if ((clFields[i].getModifiers() & mask) == 0) {
  1340. list.add(new ObjectStreamField(clFields[i], false, true));
  1341. }
  1342. }
  1343. int size = list.size();
  1344. return (size == 0) ? NO_FIELDS :
  1345. (ObjectStreamField[]) list.toArray(new ObjectStreamField[size]);
  1346. }
  1347. /**
  1348. * Returns explicit serial version UID value declared by given class, or
  1349. * null if none.
  1350. */
  1351. private static Long getDeclaredSUID(Class cl) {
  1352. try {
  1353. Field f = cl.getDeclaredField("serialVersionUID");
  1354. int mask = Modifier.STATIC | Modifier.FINAL;
  1355. if ((f.getModifiers() & mask) == mask) {
  1356. f.setAccessible(true);
  1357. return new Long(f.getLong(null));
  1358. }
  1359. } catch (Exception ex) {
  1360. }
  1361. return null;
  1362. }
  1363. /**
  1364. * Computes the default serial version UID value for the given class.
  1365. */
  1366. private static long computeDefaultSUID(Class cl) {
  1367. if (!Serializable.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl))
  1368. {
  1369. return 0L;
  1370. }
  1371. try {
  1372. ByteArrayOutputStream bout = new ByteArrayOutputStream();
  1373. DataOutputStream dout = new DataOutputStream(bout);
  1374. dout.writeUTF(cl.getName());
  1375. int classMods = cl.getModifiers() &
  1376. (Modifier.PUBLIC | Modifier.FINAL |
  1377. Modifier.INTERFACE | Modifier.ABSTRACT);
  1378. /*
  1379. * compensate for javac bug in which ABSTRACT bit was set for an
  1380. * interface only if the interface declared methods
  1381. */
  1382. Method[] methods = cl.getDeclaredMethods();
  1383. if ((classMods & Modifier.INTERFACE) != 0) {
  1384. classMods = (methods.length > 0) ?
  1385. (classMods | Modifier.ABSTRACT) :
  1386. (classMods & ~Modifier.ABSTRACT);
  1387. }
  1388. dout.writeInt(classMods);
  1389. if (!cl.isArray()) {
  1390. /*
  1391. * compensate for change in 1.2FCS in which
  1392. * Class.getInterfaces() was modified to return Cloneable and
  1393. * Serializable for array classes.
  1394. */
  1395. Class[] interfaces = cl.getInterfaces();
  1396. String[] ifaceNames = new String[interfaces.length];
  1397. for (int i = 0; i < interfaces.length; i++) {
  1398. ifaceNames[i] = interfaces[i].getName();
  1399. }
  1400. Arrays.sort(ifaceNames);
  1401. for (int i = 0; i < ifaceNames.length; i++) {
  1402. dout.writeUTF(ifaceNames[i]);
  1403. }
  1404. }
  1405. Field[] fields = cl.getDeclaredFields();
  1406. MemberSignature[] fieldSigs = new MemberSignature[fields.length];
  1407. for (int i = 0; i < fields.length; i++) {
  1408. fieldSigs[i] = new MemberSignature(fields[i]);
  1409. }
  1410. Arrays.sort(fieldSigs, new Comparator() {
  1411. public int compare(Object o1, Object o2) {
  1412. String name1 = ((MemberSignature) o1).name;
  1413. String name2 = ((MemberSignature) o2).name;
  1414. return name1.compareTo(name2);
  1415. }
  1416. });
  1417. for (int i = 0; i < fieldSigs.length; i++) {
  1418. MemberSignature sig = fieldSigs[i];
  1419. int mods = sig.member.getModifiers();
  1420. if (((mods & Modifier.PRIVATE) == 0) ||
  1421. ((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0))
  1422. {
  1423. dout.writeUTF(sig.name);
  1424. dout.writeInt(mods);
  1425. dout.writeUTF(sig.signature);
  1426. }
  1427. }
  1428. if (hasStaticInitializer(cl)) {
  1429. dout.writeUTF("<clinit>");
  1430. dout.writeInt(Modifier.STATIC);
  1431. dout.writeUTF("()V");
  1432. }
  1433. Constructor[] cons = cl.getDeclaredConstructors();
  1434. MemberSignature[] consSigs = new MemberSignature[cons.length];
  1435. for (int i = 0; i < cons.length; i++) {
  1436. consSigs[i] = new MemberSignature(cons[i]);
  1437. }
  1438. Arrays.sort(consSigs, new Comparator() {
  1439. public int compare(Object o1, Object o2) {
  1440. String sig1 = ((MemberSignature) o1).signature;
  1441. String sig2 = ((MemberSignature) o2).signature;
  1442. return sig1.compareTo(sig2);
  1443. }
  1444. });
  1445. for (int i = 0; i < consSigs.length; i++) {
  1446. MemberSignature sig = consSigs[i];
  1447. int mods = sig.member.getModifiers();
  1448. if ((mods & Modifier.PRIVATE) == 0) {
  1449. dout.writeUTF("<init>");
  1450. dout.writeInt(mods);
  1451. dout.writeUTF(sig.signature.replace('/', '.'));
  1452. }
  1453. }
  1454. MemberSignature[] methSigs = new MemberSignature[methods.length];
  1455. for (int i = 0; i < methods.length; i++) {
  1456. methSigs[i] = new MemberSignature(methods[i]);
  1457. }
  1458. Arrays.sort(methSigs, new Comparator() {
  1459. public int compare(Object o1, Object o2) {
  1460. MemberSignature ms1 = (MemberSignature) o1;
  1461. MemberSignature ms2 = (MemberSignature) o2;
  1462. int comp = ms1.name.compareTo(ms2.name);
  1463. if (comp == 0) {
  1464. comp = ms1.signature.compareTo(ms2.signature);
  1465. }
  1466. return comp;
  1467. }
  1468. });
  1469. for (int i = 0; i < methSigs.length; i++) {
  1470. MemberSignature sig = methSigs[i];
  1471. int mods = sig.member.getModifiers();
  1472. if ((mods & Modifier.PRIVATE) == 0) {
  1473. dout.writeUTF(sig.name);
  1474. dout.writeInt(mods);
  1475. dout.writeUTF(sig.signature.replace('/', '.'));
  1476. }
  1477. }
  1478. dout.flush();
  1479. MessageDigest md = MessageDigest.getInstance("SHA");
  1480. byte[] hashBytes = md.digest(bout.toByteArray());
  1481. long hash = 0;
  1482. for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
  1483. hash = (hash << 8) | (hashBytes[i] & 0xFF);
  1484. }
  1485. return hash;
  1486. } catch (IOException ex) {
  1487. throw new InternalError();
  1488. } catch (NoSuchAlgorithmException ex) {
  1489. throw new SecurityException(ex.getMessage());
  1490. }
  1491. }
  1492. /**
  1493. * Returns true if the given class defines a static initializer method,
  1494. * false otherwise.
  1495. */
  1496. private native static boolean hasStaticInitializer(Class cl);
  1497. /**
  1498. * Class for computing and caching field/constructor/method signatures
  1499. * during serialVersionUID calculation.
  1500. */
  1501. private static class MemberSignature {
  1502. public final Member member;
  1503. public final String name;
  1504. public final String signature;
  1505. public MemberSignature(Field field) {
  1506. member = field;
  1507. name = field.getName();
  1508. signature = getClassSignature(field.getType());
  1509. }
  1510. public MemberSignature(Constructor cons) {
  1511. member = cons;
  1512. name = cons.getName();
  1513. signature = getMethodSignature(
  1514. cons.getParameterTypes(), Void.TYPE);
  1515. }
  1516. public MemberSignature(Method meth) {
  1517. member = meth;
  1518. name = meth.getName();
  1519. signature = getMethodSignature(
  1520. meth.getParameterTypes(), meth.getReturnType());
  1521. }
  1522. }
  1523. /**
  1524. * Class for setting and retrieving serializable field values in batch.
  1525. */
  1526. // REMIND: dynamically generate these?
  1527. private static class FieldReflector {
  1528. /** handle for performing unsafe operations */
  1529. private static final Unsafe unsafe = Unsafe.getUnsafe();
  1530. /** fields to operate on */
  1531. private final ObjectStreamField[] fields;
  1532. /** number of primitive fields */
  1533. private final int numPrimFields;
  1534. /** unsafe field keys */
  1535. private final long[] keys;
  1536. /** field data offsets */
  1537. private final int[] offsets;
  1538. /** field type codes */
  1539. private final char[] typeCodes;
  1540. /** field types */
  1541. private final Class[] types;
  1542. /**
  1543. * Constructs FieldReflector capable of setting/getting values from the
  1544. * subset of fields whose ObjectStreamFields contain non-null
  1545. * reflective Field objects. ObjectStreamFields with null Fields are
  1546. * treated as filler, for which get operations return default values
  1547. * and set operations discard given values.
  1548. */
  1549. FieldReflector(ObjectStreamField[] fields) {
  1550. this.fields = fields;
  1551. int nfields = fields.length;
  1552. keys = new long[nfields];
  1553. offsets = new int[nfields];
  1554. typeCodes = new char[nfields];
  1555. ArrayList typeList = new ArrayList();
  1556. for (int i = 0; i < nfields; i++) {
  1557. ObjectStreamField f = fields[i];
  1558. Field rf = f.getField();
  1559. keys[i] = (rf != null) ?
  1560. unsafe.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET;
  1561. offsets[i] = f.getOffset();
  1562. typeCodes[i] = f.getTypeCode();
  1563. if (!f.isPrimitive()) {
  1564. typeList.add((rf != null) ? rf.getType() : null);
  1565. }
  1566. }
  1567. types = (Class[]) typeList.toArray(new Class[typeList.size()]);
  1568. numPrimFields = nfields - types.length;
  1569. }
  1570. /**
  1571. * Returns list of ObjectStreamFields representing fields operated on
  1572. * by this reflector. The shared/unshared values and Field objects
  1573. * contained by ObjectStreamFields in the list reflect their bindings
  1574. * to locally defined serializable fields.
  1575. */
  1576. ObjectStreamField[] getFields() {
  1577. return fields;
  1578. }
  1579. /**
  1580. * Fetches the serializable primitive field values of object obj and
  1581. * marshals them into byte array buf starting at offset 0. The caller
  1582. * is responsible for ensuring that obj is of the proper type.
  1583. */
  1584. void getPrimFieldValues(Object obj, byte[] buf) {
  1585. if (obj == null) {
  1586. throw new NullPointerException();
  1587. }
  1588. /* assuming checkDefaultSerialize() has been called on the class
  1589. * descriptor this FieldReflector was obtained from, no field keys
  1590. * in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
  1591. */
  1592. for (int i = 0; i < numPrimFields; i++) {
  1593. long key = keys[i];
  1594. int off = offsets[i];
  1595. switch (typeCodes[i]) {
  1596. case 'Z':
  1597. Bits.putBoolean(buf, off, unsafe.getBoolean(obj, key));
  1598. break;
  1599. case 'B':
  1600. buf[off] = unsafe.getByte(obj, key);
  1601. break;
  1602. case 'C':
  1603. Bits.putChar(buf, off, unsafe.getChar(obj, key));
  1604. break;
  1605. case 'S':
  1606. Bits.putShort(buf, off, unsafe.getShort(obj, key));
  1607. break;
  1608. case 'I':
  1609. Bits.putInt(buf, off, unsafe.getInt(obj, key));
  1610. break;
  1611. case 'F':
  1612. Bits.putFloat(buf, off, unsafe.getFloat(obj, key));
  1613. break;
  1614. case 'J':
  1615. Bits.putLong(buf, off, unsafe.getLong(obj, key));
  1616. break;
  1617. case 'D':
  1618. Bits.putDouble(buf, off, unsafe.getDouble(obj, key));
  1619. break;
  1620. default:
  1621. throw new InternalError();
  1622. }
  1623. }
  1624. }
  1625. /**
  1626. * Sets the serializable primitive fields of object obj using values
  1627. * unmarshalled from byte array buf starting at offset 0. The caller
  1628. * is responsible for ensuring that obj is of the proper type.
  1629. */
  1630. void setPrimFieldValues(Object obj, byte[] buf) {
  1631. if (obj == null) {
  1632. throw new NullPointerException();
  1633. }
  1634. for (int i = 0; i < numPrimFields; i++) {
  1635. long key = keys[i];
  1636. if (key == Unsafe.INVALID_FIELD_OFFSET) {
  1637. continue; // discard value
  1638. }
  1639. int off = offsets[i];
  1640. switch (typeCodes[i]) {
  1641. case 'Z':
  1642. unsafe.putBoolean(obj, key, Bits.getBoolean(buf, off));
  1643. break;
  1644. case 'B':
  1645. unsafe.putByte(obj, key, buf[off]);
  1646. break;
  1647. case 'C':
  1648. unsafe.putChar(obj, key, Bits.getChar(buf, off));
  1649. break;
  1650. case 'S':
  1651. unsafe.putShort(obj, key, Bits.getShort(buf, off));
  1652. break;
  1653. case 'I':
  1654. unsafe.putInt(obj, key, Bits.getInt(buf, off));
  1655. break;
  1656. case 'F':
  1657. unsafe.putFloat(obj, key, Bits.getFloat(buf, off));
  1658. break;
  1659. case 'J':
  1660. unsafe.putLong(obj, key, Bits.getLong(buf, off));
  1661. break;
  1662. case 'D':
  1663. unsafe.putDouble(obj, key, Bits.getDouble(buf, off));
  1664. break;
  1665. default:
  1666. throw new InternalError();
  1667. }
  1668. }
  1669. }
  1670. /**
  1671. * Fetches the serializable object field values of object obj and
  1672. * stores them in array vals starting at offset 0. The caller is
  1673. * responsible for ensuring that obj is of the proper type.
  1674. */
  1675. void getObjFieldValues(Object obj, Object[] vals) {
  1676. if (obj == null) {
  1677. throw new NullPointerException();
  1678. }
  1679. /* assuming checkDefaultSerialize() has been called on the class
  1680. * descriptor this FieldReflector was obtained from, no field keys
  1681. * in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
  1682. */
  1683. for (int i = numPrimFields; i < fields.length; i++) {
  1684. switch (typeCodes[i]) {
  1685. case 'L':
  1686. case '[':
  1687. vals[offsets[i]] = unsafe.getObject(obj, keys[i]);
  1688. break;
  1689. default:
  1690. throw new InternalError();
  1691. }
  1692. }
  1693. }
  1694. /**
  1695. * Sets the serializable object fields of object obj using values from
  1696. * array vals starting at offset 0. The caller is responsible for
  1697. * ensuring that obj is of the proper type; however, attempts to set a
  1698. * field with a value of the wrong type will trigger an appropriate
  1699. * ClassCastException.
  1700. */
  1701. void setObjFieldValues(Object obj, Object[] vals) {
  1702. if (obj == null) {
  1703. throw new NullPointerException();
  1704. }
  1705. for (int i = numPrimFields; i < fields.length; i++) {
  1706. long key = keys[i];
  1707. if (key == Unsafe.INVALID_FIELD_OFFSET) {
  1708. continue; // discard value
  1709. }
  1710. switch (typeCodes[i]) {
  1711. case 'L':
  1712. case '[':
  1713. Object val = vals[offsets[i]];
  1714. if (val != null &&
  1715. !types[i - numPrimFields].isInstance(val))
  1716. {
  1717. Field f = fields[i].getField();
  1718. throw new ClassCastException(
  1719. "cannot assign instance of " +
  1720. val.getClass().getName() + " to field " +
  1721. f.getDeclaringClass().getName() + "." +
  1722. f.getName() + " of type " +
  1723. f.getType().getName() + " in instance of " +
  1724. obj.getClass().getName());
  1725. }
  1726. unsafe.putObject(obj, key, val);
  1727. break;
  1728. default:
  1729. throw new InternalError();
  1730. }
  1731. }
  1732. }
  1733. }
  1734. /**
  1735. * Matches given set of serializable fields with serializable fields
  1736. * described by the given local class descriptor, and returns a
  1737. * FieldReflector instance capable of setting/getting values from the
  1738. * subset of fields that match (non-matching fields are treated as filler,
  1739. * for which get operations return default values and set operations
  1740. * discard given values). Throws InvalidClassException if unresolvable
  1741. * type conflicts exist between the two sets of fields.
  1742. */
  1743. private static FieldReflector getReflector(ObjectStreamField[] fields,
  1744. ObjectStreamClass localDesc)
  1745. throws InvalidClassException
  1746. {
  1747. // class irrelevant if no fields
  1748. Class cl = (localDesc != null && fields.length > 0) ?
  1749. localDesc.cl : null;
  1750. Object key = new FieldReflectorKey(cl, fields);
  1751. Object entry;
  1752. EntryFuture future = null;
  1753. synchronized (reflectors) {
  1754. if ((entry = reflectors.get(key)) == null) {
  1755. reflectors.put(key, future = new EntryFuture());
  1756. }
  1757. }
  1758. if (entry instanceof FieldReflector) { // check common case first
  1759. return (FieldReflector) entry;
  1760. } else if (entry instanceof EntryFuture) {
  1761. entry = ((EntryFuture) entry).get();
  1762. } else if (entry == null) {
  1763. try {
  1764. entry = new FieldReflector(matchFields(fields, localDesc));
  1765. } catch (Throwable th) {
  1766. entry = th;
  1767. }
  1768. future.set(entry);
  1769. synchronized (reflectors) {
  1770. reflectors.put(key, entry);
  1771. }
  1772. }
  1773. if (entry instanceof FieldReflector) {
  1774. return (FieldReflector) entry;
  1775. } else if (entry instanceof InvalidClassException) {
  1776. throw (InvalidClassException) entry;
  1777. } else if (entry instanceof RuntimeException) {
  1778. throw (RuntimeException) entry;
  1779. } else if (entry instanceof Error) {
  1780. throw (Error) entry;
  1781. } else {
  1782. throw new InternalError("unexpected entry: " + entry);
  1783. }
  1784. }
  1785. /**
  1786. * FieldReflector cache lookup key. Keys are considered equal if they
  1787. * refer to the same class and equivalent field formats.
  1788. */
  1789. private static class FieldReflectorKey {
  1790. private final Class cl;
  1791. private final String sigs;
  1792. private final int hash;
  1793. FieldReflectorKey(Class cl, ObjectStreamField[] fields) {
  1794. /*
  1795. * Note: maintaining a direct reference to the class does not pin
  1796. * it indefinitely, since SoftCache removes strong refs to keys
  1797. * when the corresponding values are gc'ed.
  1798. */
  1799. this.cl = cl;
  1800. StringBuffer sbuf = new StringBuffer();
  1801. for (int i = 0; i < fields.length; i++) {
  1802. ObjectStreamField f = fields[i];
  1803. sbuf.append(f.getName()).append(f.getSignature());
  1804. }
  1805. sigs = sbuf.toString();
  1806. hash = System.identityHashCode(cl) + sigs.hashCode();
  1807. }
  1808. public int hashCode() {
  1809. return hash;
  1810. }
  1811. public boolean equals(Object obj) {
  1812. if (!(obj instanceof FieldReflectorKey)) {
  1813. return false;
  1814. }
  1815. FieldReflectorKey key = (FieldReflectorKey) obj;
  1816. return (cl == key.cl && sigs.equals(key.sigs));
  1817. }
  1818. }
  1819. /**
  1820. * Matches given set of serializable fields with serializable fields
  1821. * obtained from the given local class descriptor (which contain bindings
  1822. * to reflective Field objects). Returns list of ObjectStreamFields in
  1823. * which each ObjectStreamField whose signature matches that of a local
  1824. * field contains a Field object for that field; unmatched
  1825. * ObjectStreamFields contain null Field objects. Shared/unshared settings
  1826. * of the returned ObjectStreamFields also reflect those of matched local
  1827. * ObjectStreamFields. Throws InvalidClassException if unresolvable type
  1828. * conflicts exist between the two sets of fields.
  1829. */
  1830. private static ObjectStreamField[] matchFields(ObjectStreamField[] fields,
  1831. ObjectStreamClass localDesc)
  1832. throws InvalidClassException
  1833. {
  1834. ObjectStreamField[] localFields = (localDesc != null) ?
  1835. localDesc.fields : NO_FIELDS;
  1836. /*
  1837. * Even if fields == localFields, we cannot simply return localFields
  1838. * here. In previous implementations of serialization,
  1839. * ObjectStreamField.getType() returned Object.class if the
  1840. * ObjectStreamField represented a non-primitive field and belonged to
  1841. * a non-local class descriptor. To preserve this (questionable)
  1842. * behavior, the ObjectStreamField instances returned by matchFields
  1843. * cannot report non-primitive types other than Object.class; hence
  1844. * localFields cannot be returned directly.
  1845. */
  1846. ObjectStreamField[] matches = new ObjectStreamField[fields.length];
  1847. for (int i = 0; i < fields.length; i++) {
  1848. ObjectStreamField f = fields[i], m = null;
  1849. for (int j = 0; j < localFields.length; j++) {
  1850. ObjectStreamField lf = localFields[j];
  1851. if (f.getName().equals(lf.getName())) {
  1852. if ((f.isPrimitive() || lf.isPrimitive()) &&
  1853. f.getTypeCode() != lf.getTypeCode())
  1854. {
  1855. throw new InvalidClassException(localDesc.name,
  1856. "incompatible types for field " + f.getName());
  1857. }
  1858. if (lf.getField() != null) {
  1859. m = new ObjectStreamField(
  1860. lf.getField(), lf.isUnshared(), false);
  1861. } else {
  1862. m = new ObjectStreamField(
  1863. lf.getName(), lf.getSignature(), lf.isUnshared());
  1864. }
  1865. }
  1866. }
  1867. if (m == null) {
  1868. m = new ObjectStreamField(
  1869. f.getName(), f.getSignature(), false);
  1870. }
  1871. m.setOffset(f.getOffset());
  1872. matches[i] = m;
  1873. }
  1874. return matches;
  1875. }
  1876. }