ObjectStreamClass.java 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. /* ObjectStreamClass.java -- Class used to write class information
  2. about serialized objects.
  3. Copyright (C) 1998, 1999, 2000, 2001, 2003, 2005 Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.io;
  33. import gnu.java.io.NullOutputStream;
  34. import gnu.java.lang.reflect.TypeSignature;
  35. import gnu.java.security.action.SetAccessibleAction;
  36. import gnu.java.security.provider.Gnu;
  37. import java.lang.reflect.Constructor;
  38. import java.lang.reflect.Field;
  39. import java.lang.reflect.Member;
  40. import java.lang.reflect.Method;
  41. import java.lang.reflect.Modifier;
  42. import java.lang.reflect.Proxy;
  43. import java.security.AccessController;
  44. import java.security.DigestOutputStream;
  45. import java.security.MessageDigest;
  46. import java.security.NoSuchAlgorithmException;
  47. import java.security.PrivilegedAction;
  48. import java.security.Security;
  49. import java.util.Arrays;
  50. import java.util.Comparator;
  51. import java.util.Hashtable;
  52. /**
  53. * @author Tom Tromey (tromey@redhat.com)
  54. * @author Jeroen Frijters (jeroen@frijters.net)
  55. * @author Guilhem Lavaux (guilhem@kaffe.org)
  56. * @author Michael Koch (konqueror@gmx.de)
  57. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  58. */
  59. public class ObjectStreamClass implements Serializable
  60. {
  61. static final ObjectStreamField[] INVALID_FIELDS = new ObjectStreamField[0];
  62. /**
  63. * Returns the <code>ObjectStreamClass</code> for <code>cl</code>.
  64. * If <code>cl</code> is null, or is not <code>Serializable</code>,
  65. * null is returned. <code>ObjectStreamClass</code>'s are memorized;
  66. * later calls to this method with the same class will return the
  67. * same <code>ObjectStreamClass</code> object and no recalculation
  68. * will be done.
  69. *
  70. * Warning: If this class contains an invalid serialPersistentField arrays
  71. * lookup will not throw anything. However {@link #getFields()} will return
  72. * an empty array and {@link java.io.ObjectOutputStream#writeObject} will throw an
  73. * {@link java.io.InvalidClassException}.
  74. *
  75. * @see java.io.Serializable
  76. */
  77. public static ObjectStreamClass lookup(Class<?> cl)
  78. {
  79. if (cl == null)
  80. return null;
  81. if (! (Serializable.class).isAssignableFrom(cl))
  82. return null;
  83. return lookupForClassObject(cl);
  84. }
  85. /**
  86. * This lookup for internal use by ObjectOutputStream. Suppose
  87. * we have a java.lang.Class object C for class A, though A is not
  88. * serializable, but it's okay to serialize C.
  89. */
  90. static ObjectStreamClass lookupForClassObject(Class cl)
  91. {
  92. if (cl == null)
  93. return null;
  94. ObjectStreamClass osc = classLookupTable.get(cl);
  95. if (osc != null)
  96. return osc;
  97. else
  98. {
  99. osc = new ObjectStreamClass(cl);
  100. classLookupTable.put(cl, osc);
  101. return osc;
  102. }
  103. }
  104. /**
  105. * Returns the name of the class that this
  106. * <code>ObjectStreamClass</code> represents.
  107. *
  108. * @return the name of the class.
  109. */
  110. public String getName()
  111. {
  112. return name;
  113. }
  114. /**
  115. * Returns the class that this <code>ObjectStreamClass</code>
  116. * represents. Null could be returned if this
  117. * <code>ObjectStreamClass</code> was read from an
  118. * <code>ObjectInputStream</code> and the class it represents cannot
  119. * be found or loaded.
  120. *
  121. * @see java.io.ObjectInputStream
  122. */
  123. public Class<?> forClass()
  124. {
  125. return clazz;
  126. }
  127. /**
  128. * Returns the serial version stream-unique identifier for the class
  129. * represented by this <code>ObjectStreamClass</code>. This SUID is
  130. * either defined by the class as <code>static final long
  131. * serialVersionUID</code> or is calculated as specified in
  132. * Javasoft's "Object Serialization Specification" XXX: add reference
  133. *
  134. * @return the serial version UID.
  135. */
  136. public long getSerialVersionUID()
  137. {
  138. return uid;
  139. }
  140. /**
  141. * Returns the serializable (non-static and non-transient) Fields
  142. * of the class represented by this ObjectStreamClass. The Fields
  143. * are sorted by name.
  144. * If fields were obtained using serialPersistentFields and this array
  145. * is faulty then the returned array of this method will be empty.
  146. *
  147. * @return the fields.
  148. */
  149. public ObjectStreamField[] getFields()
  150. {
  151. ObjectStreamField[] copy = new ObjectStreamField[ fields.length ];
  152. System.arraycopy(fields, 0, copy, 0, fields.length);
  153. return copy;
  154. }
  155. // XXX doc
  156. // Can't do binary search since fields is sorted by name and
  157. // primitiveness.
  158. public ObjectStreamField getField (String name)
  159. {
  160. for (int i = 0; i < fields.length; i++)
  161. if (fields[i].getName().equals(name))
  162. return fields[i];
  163. return null;
  164. }
  165. /**
  166. * Returns a textual representation of this
  167. * <code>ObjectStreamClass</code> object including the name of the
  168. * class it represents as well as that class's serial version
  169. * stream-unique identifier.
  170. *
  171. * @see #getSerialVersionUID()
  172. * @see #getName()
  173. */
  174. public String toString()
  175. {
  176. return "java.io.ObjectStreamClass< " + name + ", " + uid + " >";
  177. }
  178. // Returns true iff the class that this ObjectStreamClass represents
  179. // has the following method:
  180. //
  181. // private void writeObject (ObjectOutputStream)
  182. //
  183. // This method is used by the class to override default
  184. // serialization behavior.
  185. boolean hasWriteMethod()
  186. {
  187. return (flags & ObjectStreamConstants.SC_WRITE_METHOD) != 0;
  188. }
  189. // Returns true iff the class that this ObjectStreamClass represents
  190. // implements Serializable but does *not* implement Externalizable.
  191. boolean isSerializable()
  192. {
  193. return (flags & ObjectStreamConstants.SC_SERIALIZABLE) != 0;
  194. }
  195. // Returns true iff the class that this ObjectStreamClass represents
  196. // implements Externalizable.
  197. boolean isExternalizable()
  198. {
  199. return (flags & ObjectStreamConstants.SC_EXTERNALIZABLE) != 0;
  200. }
  201. // Returns true iff the class that this ObjectStreamClass represents
  202. // implements Externalizable.
  203. boolean isEnum()
  204. {
  205. return (flags & ObjectStreamConstants.SC_ENUM) != 0;
  206. }
  207. // Returns the <code>ObjectStreamClass</code> that represents the
  208. // class that is the superclass of the class this
  209. // <code>ObjectStreamClass</code> represents. If the superclass is
  210. // not Serializable, null is returned.
  211. ObjectStreamClass getSuper()
  212. {
  213. return superClass;
  214. }
  215. /**
  216. * returns an array of ObjectStreamClasses that represent the super
  217. * classes of the class represented by this and the class
  218. * represented by this itself in order from most super to this.
  219. * ObjectStreamClass[0] is the highest superclass of this that is
  220. * serializable.
  221. *
  222. * The result of consecutive calls this hierarchy() will be the same
  223. * array instance.
  224. *
  225. * @return an array of ObjectStreamClass representing the
  226. * super-class hierarchy of serializable classes.
  227. */
  228. ObjectStreamClass[] hierarchy()
  229. {
  230. ObjectStreamClass[] result = hierarchy;
  231. if (result == null)
  232. {
  233. int d = 0;
  234. for(ObjectStreamClass osc = this; osc != null; osc = osc.getSuper())
  235. d++;
  236. result = new ObjectStreamClass[d];
  237. for (ObjectStreamClass osc = this; osc != null; osc = osc.getSuper())
  238. {
  239. result[--d] = osc;
  240. }
  241. hierarchy = result;
  242. }
  243. return result;
  244. }
  245. /**
  246. * Cache for hierarchy() result.
  247. */
  248. private ObjectStreamClass[] hierarchy = null;
  249. // Returns an integer that consists of bit-flags that indicate
  250. // properties of the class represented by this ObjectStreamClass.
  251. // The bit-flags that could be present are those defined in
  252. // ObjectStreamConstants that begin with `SC_'
  253. int getFlags()
  254. {
  255. return flags;
  256. }
  257. ObjectStreamClass(String name, long uid, byte flags,
  258. ObjectStreamField[] fields)
  259. {
  260. this.name = name;
  261. this.uid = uid;
  262. this.flags = flags;
  263. this.fields = fields;
  264. }
  265. /**
  266. * This method builds the internal description corresponding to a Java Class.
  267. * As the constructor only assign a name to the current ObjectStreamClass instance,
  268. * that method sets the serial UID, chose the fields which will be serialized,
  269. * and compute the position of the fields in the serialized stream.
  270. *
  271. * @param cl The Java class which is used as a reference for building the descriptor.
  272. * @param superClass The descriptor of the super class for this class descriptor.
  273. * @throws InvalidClassException if an incompatibility between computed UID and
  274. * already set UID is found.
  275. */
  276. void setClass(Class cl, ObjectStreamClass superClass) throws InvalidClassException
  277. {hierarchy = null;
  278. this.clazz = cl;
  279. cacheMethods();
  280. long class_uid = getClassUID(cl);
  281. if (uid == 0)
  282. uid = class_uid;
  283. else
  284. {
  285. // Check that the actual UID of the resolved class matches the UID from
  286. // the stream. Mismatches for array classes are ignored.
  287. if (!cl.isArray() && uid != class_uid)
  288. {
  289. String msg = cl +
  290. ": Local class not compatible: stream serialVersionUID="
  291. + uid + ", local serialVersionUID=" + class_uid;
  292. throw new InvalidClassException (msg);
  293. }
  294. }
  295. isProxyClass = clazz != null && Proxy.isProxyClass(clazz);
  296. this.superClass = superClass;
  297. calculateOffsets();
  298. try
  299. {
  300. ObjectStreamField[] exportedFields = getSerialPersistentFields (clazz);
  301. if (exportedFields == null)
  302. return;
  303. ObjectStreamField[] newFieldList = new ObjectStreamField[exportedFields.length + fields.length];
  304. int i, j, k;
  305. /* We now check the import fields against the exported fields.
  306. * There should not be contradiction (e.g. int x and String x)
  307. * but extra virtual fields can be added to the class.
  308. */
  309. Arrays.sort(exportedFields);
  310. i = 0; j = 0; k = 0;
  311. while (i < fields.length && j < exportedFields.length)
  312. {
  313. int comp = fields[i].compareTo(exportedFields[j]);
  314. if (comp < 0)
  315. {
  316. newFieldList[k] = fields[i];
  317. fields[i].setPersistent(false);
  318. fields[i].setToSet(false);
  319. i++;
  320. }
  321. else if (comp > 0)
  322. {
  323. /* field not found in imported fields. We add it
  324. * in the list of supported fields.
  325. */
  326. newFieldList[k] = exportedFields[j];
  327. newFieldList[k].setPersistent(true);
  328. newFieldList[k].setToSet(false);
  329. try
  330. {
  331. newFieldList[k].lookupField(clazz);
  332. newFieldList[k].checkFieldType();
  333. }
  334. catch (NoSuchFieldException _)
  335. {
  336. }
  337. j++;
  338. }
  339. else
  340. {
  341. try
  342. {
  343. exportedFields[j].lookupField(clazz);
  344. exportedFields[j].checkFieldType();
  345. }
  346. catch (NoSuchFieldException _)
  347. {
  348. }
  349. if (!fields[i].getType().equals(exportedFields[j].getType()))
  350. throw new InvalidClassException
  351. ("serialPersistentFields must be compatible with" +
  352. " imported fields (about " + fields[i].getName() + ")");
  353. newFieldList[k] = fields[i];
  354. fields[i].setPersistent(true);
  355. i++;
  356. j++;
  357. }
  358. k++;
  359. }
  360. if (i < fields.length)
  361. for (;i<fields.length;i++,k++)
  362. {
  363. fields[i].setPersistent(false);
  364. fields[i].setToSet(false);
  365. newFieldList[k] = fields[i];
  366. }
  367. else
  368. if (j < exportedFields.length)
  369. for (;j<exportedFields.length;j++,k++)
  370. {
  371. exportedFields[j].setPersistent(true);
  372. exportedFields[j].setToSet(false);
  373. newFieldList[k] = exportedFields[j];
  374. }
  375. fields = new ObjectStreamField[k];
  376. System.arraycopy(newFieldList, 0, fields, 0, k);
  377. }
  378. catch (NoSuchFieldException ignore)
  379. {
  380. return;
  381. }
  382. catch (IllegalAccessException ignore)
  383. {
  384. return;
  385. }
  386. }
  387. void setSuperclass (ObjectStreamClass osc)
  388. {
  389. superClass = osc;
  390. hierarchy = null;
  391. }
  392. void calculateOffsets()
  393. {
  394. int i;
  395. ObjectStreamField field;
  396. primFieldSize = 0;
  397. int fcount = fields.length;
  398. for (i = 0; i < fcount; ++ i)
  399. {
  400. field = fields[i];
  401. if (! field.isPrimitive())
  402. break;
  403. field.setOffset(primFieldSize);
  404. switch (field.getTypeCode())
  405. {
  406. case 'B':
  407. case 'Z':
  408. ++ primFieldSize;
  409. break;
  410. case 'C':
  411. case 'S':
  412. primFieldSize += 2;
  413. break;
  414. case 'I':
  415. case 'F':
  416. primFieldSize += 4;
  417. break;
  418. case 'D':
  419. case 'J':
  420. primFieldSize += 8;
  421. break;
  422. }
  423. }
  424. for (objectFieldCount = 0; i < fcount; ++ i)
  425. fields[i].setOffset(objectFieldCount++);
  426. }
  427. private Method findMethod(Method[] methods, String name, Class[] params,
  428. Class returnType, boolean mustBePrivate)
  429. {
  430. outer:
  431. for (int i = 0; i < methods.length; i++)
  432. {
  433. final Method m = methods[i];
  434. int mods = m.getModifiers();
  435. if (Modifier.isStatic(mods)
  436. || (mustBePrivate && !Modifier.isPrivate(mods)))
  437. {
  438. continue;
  439. }
  440. if (m.getName().equals(name)
  441. && m.getReturnType() == returnType)
  442. {
  443. Class[] mp = m.getParameterTypes();
  444. if (mp.length == params.length)
  445. {
  446. for (int j = 0; j < mp.length; j++)
  447. {
  448. if (mp[j] != params[j])
  449. {
  450. continue outer;
  451. }
  452. }
  453. AccessController.doPrivileged(new SetAccessibleAction(m));
  454. return m;
  455. }
  456. }
  457. }
  458. return null;
  459. }
  460. private static boolean inSamePackage(Class c1, Class c2)
  461. {
  462. String name1 = c1.getName();
  463. String name2 = c2.getName();
  464. int id1 = name1.lastIndexOf('.');
  465. int id2 = name2.lastIndexOf('.');
  466. // Handle the default package
  467. if (id1 == -1 || id2 == -1)
  468. return id1 == id2;
  469. String package1 = name1.substring(0, id1);
  470. String package2 = name2.substring(0, id2);
  471. return package1.equals(package2);
  472. }
  473. final static Class[] noArgs = new Class[0];
  474. private static Method findAccessibleMethod(String name, Class from)
  475. {
  476. for (Class c = from; c != null; c = c.getSuperclass())
  477. {
  478. try
  479. {
  480. Method res = c.getDeclaredMethod(name, noArgs);
  481. int mods = res.getModifiers();
  482. if (c == from
  483. || Modifier.isProtected(mods)
  484. || Modifier.isPublic(mods)
  485. || (! Modifier.isPrivate(mods) && inSamePackage(c, from)))
  486. {
  487. AccessController.doPrivileged(new SetAccessibleAction(res));
  488. return res;
  489. }
  490. }
  491. catch (NoSuchMethodException e)
  492. {
  493. }
  494. }
  495. return null;
  496. }
  497. /**
  498. * Helper routine to check if a class was loaded by boot or
  499. * application class loader. Classes for which this is not the case
  500. * should not be cached since caching prevent class file garbage
  501. * collection.
  502. *
  503. * @param cl a class
  504. *
  505. * @return true if cl was loaded by boot or application class loader,
  506. * false if cl was loaded by a user class loader.
  507. */
  508. private static boolean loadedByBootOrApplicationClassLoader(Class cl)
  509. {
  510. ClassLoader l = cl.getClassLoader();
  511. return
  512. ( l == null /* boot loader */ )
  513. || (l == ClassLoader.getSystemClassLoader() /* application loader */);
  514. }
  515. static Hashtable methodCache = new Hashtable();
  516. static final Class[] readObjectSignature = { ObjectInputStream.class };
  517. static final Class[] writeObjectSignature = { ObjectOutputStream.class };
  518. private void cacheMethods()
  519. {
  520. Class cl = forClass();
  521. Method[] cached = (Method[]) methodCache.get(cl);
  522. if (cached == null)
  523. {
  524. cached = new Method[4];
  525. Method[] methods = cl.getDeclaredMethods();
  526. cached[0] = findMethod(methods, "readObject",
  527. readObjectSignature,
  528. Void.TYPE, true);
  529. cached[1] = findMethod(methods, "writeObject",
  530. writeObjectSignature,
  531. Void.TYPE, true);
  532. // readResolve and writeReplace can be in parent classes, as long as they
  533. // are accessible from this class.
  534. cached[2] = findAccessibleMethod("readResolve", cl);
  535. cached[3] = findAccessibleMethod("writeReplace", cl);
  536. /* put in cache if classes not loaded by user class loader.
  537. * For a user class loader, the cache may otherwise grow
  538. * without limit.
  539. */
  540. if (loadedByBootOrApplicationClassLoader(cl))
  541. methodCache.put(cl,cached);
  542. }
  543. readObjectMethod = cached[0];
  544. writeObjectMethod = cached[1];
  545. readResolveMethod = cached[2];
  546. writeReplaceMethod = cached[3];
  547. }
  548. private ObjectStreamClass(Class cl)
  549. {
  550. uid = 0;
  551. flags = 0;
  552. isProxyClass = Proxy.isProxyClass(cl);
  553. clazz = cl;
  554. cacheMethods();
  555. name = cl.getName();
  556. setFlags(cl);
  557. setFields(cl);
  558. // to those class nonserializable, its uid field is 0
  559. if ( (Serializable.class).isAssignableFrom(cl) && !isProxyClass)
  560. uid = getClassUID(cl);
  561. superClass = lookup(cl.getSuperclass());
  562. }
  563. // Sets bits in flags according to features of CL.
  564. private void setFlags(Class cl)
  565. {
  566. if ((java.io.Externalizable.class).isAssignableFrom(cl))
  567. flags |= ObjectStreamConstants.SC_EXTERNALIZABLE;
  568. else if ((java.io.Serializable.class).isAssignableFrom(cl))
  569. // only set this bit if CL is NOT Externalizable
  570. flags |= ObjectStreamConstants.SC_SERIALIZABLE;
  571. if (writeObjectMethod != null)
  572. flags |= ObjectStreamConstants.SC_WRITE_METHOD;
  573. if (cl.isEnum() || cl == Enum.class)
  574. flags |= ObjectStreamConstants.SC_ENUM;
  575. }
  576. /* GCJ LOCAL */
  577. // FIXME: This is a workaround for a fairly obscure bug that happens
  578. // when reading a Proxy and then writing it back out again. The
  579. // result is that the ObjectStreamClass doesn't have its fields set,
  580. // generating a NullPointerException. Rather than this kludge we
  581. // should probably fix the real bug, but it would require a fairly
  582. // radical reorganization to do so.
  583. final void ensureFieldsSet(Class cl)
  584. {
  585. if (! fieldsSet)
  586. setFields(cl);
  587. }
  588. /* END GCJ LOCAL */
  589. // Sets fields to be a sorted array of the serializable fields of
  590. // clazz.
  591. private void setFields(Class cl)
  592. {
  593. /* GCJ LOCAL */
  594. fieldsSet = true;
  595. /* END GCJ LOCAL */
  596. SetAccessibleAction setAccessible = new SetAccessibleAction();
  597. if (!isSerializable() || isExternalizable() || isEnum())
  598. {
  599. fields = NO_FIELDS;
  600. return;
  601. }
  602. try
  603. {
  604. final Field f =
  605. cl.getDeclaredField("serialPersistentFields");
  606. setAccessible.setMember(f);
  607. AccessController.doPrivileged(setAccessible);
  608. int modifiers = f.getModifiers();
  609. if (Modifier.isStatic(modifiers)
  610. && Modifier.isFinal(modifiers)
  611. && Modifier.isPrivate(modifiers))
  612. {
  613. fields = getSerialPersistentFields(cl);
  614. if (fields != null)
  615. {
  616. ObjectStreamField[] fieldsName = new ObjectStreamField[fields.length];
  617. System.arraycopy(fields, 0, fieldsName, 0, fields.length);
  618. Arrays.sort (fieldsName, new Comparator() {
  619. public int compare(Object o1, Object o2)
  620. {
  621. ObjectStreamField f1 = (ObjectStreamField)o1;
  622. ObjectStreamField f2 = (ObjectStreamField)o2;
  623. return f1.getName().compareTo(f2.getName());
  624. }
  625. });
  626. for (int i=1; i < fields.length; i++)
  627. {
  628. if (fieldsName[i-1].getName().equals(fieldsName[i].getName()))
  629. {
  630. fields = INVALID_FIELDS;
  631. return;
  632. }
  633. }
  634. Arrays.sort (fields);
  635. // Retrieve field reference.
  636. for (int i=0; i < fields.length; i++)
  637. {
  638. try
  639. {
  640. fields[i].lookupField(cl);
  641. }
  642. catch (NoSuchFieldException _)
  643. {
  644. fields[i].setToSet(false);
  645. }
  646. }
  647. calculateOffsets();
  648. return;
  649. }
  650. }
  651. }
  652. catch (NoSuchFieldException ignore)
  653. {
  654. }
  655. catch (IllegalAccessException ignore)
  656. {
  657. }
  658. int num_good_fields = 0;
  659. Field[] all_fields = cl.getDeclaredFields();
  660. int modifiers;
  661. // set non-serializable fields to null in all_fields
  662. for (int i = 0; i < all_fields.length; i++)
  663. {
  664. modifiers = all_fields[i].getModifiers();
  665. if (Modifier.isTransient(modifiers)
  666. || Modifier.isStatic(modifiers))
  667. all_fields[i] = null;
  668. else
  669. num_good_fields++;
  670. }
  671. // make a copy of serializable (non-null) fields
  672. fields = new ObjectStreamField[ num_good_fields ];
  673. for (int from = 0, to = 0; from < all_fields.length; from++)
  674. if (all_fields[from] != null)
  675. {
  676. final Field f = all_fields[from];
  677. setAccessible.setMember(f);
  678. AccessController.doPrivileged(setAccessible);
  679. fields[to] = new ObjectStreamField(all_fields[from]);
  680. to++;
  681. }
  682. Arrays.sort(fields);
  683. // Make sure we don't have any duplicate field names
  684. // (Sun JDK 1.4.1. throws an Internal Error as well)
  685. for (int i = 1; i < fields.length; i++)
  686. {
  687. if(fields[i - 1].getName().equals(fields[i].getName()))
  688. throw new InternalError("Duplicate field " +
  689. fields[i].getName() + " in class " + cl.getName());
  690. }
  691. calculateOffsets();
  692. }
  693. static Hashtable uidCache = new Hashtable();
  694. // Returns the serial version UID defined by class, or if that
  695. // isn't present, calculates value of serial version UID.
  696. private long getClassUID(Class cl)
  697. {
  698. long result = 0;
  699. Long cache = (Long) uidCache.get(cl);
  700. if (cache != null)
  701. result = cache.longValue();
  702. else
  703. {
  704. // Note that we can't use Class.isEnum() here, because that returns
  705. // false for java.lang.Enum and enum value sub classes.
  706. if (Enum.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl))
  707. {
  708. // Spec says that enums and dynamic proxies have
  709. // a serialVersionUID of 0L.
  710. return 0L;
  711. }
  712. try
  713. {
  714. result = getClassUIDFromField(cl);
  715. }
  716. catch (NoSuchFieldException ignore)
  717. {
  718. try
  719. {
  720. result = calculateClassUID(cl);
  721. }
  722. catch (NoSuchAlgorithmException e)
  723. {
  724. throw new RuntimeException
  725. ("The SHA algorithm was not found to use in computing the Serial Version UID for class "
  726. + cl.getName(), e);
  727. }
  728. catch (IOException ioe)
  729. {
  730. throw new RuntimeException(ioe);
  731. }
  732. }
  733. if (loadedByBootOrApplicationClassLoader(cl))
  734. uidCache.put(cl,Long.valueOf(result));
  735. }
  736. return result;
  737. }
  738. /**
  739. * Search for a serialVersionUID field in the given class and read
  740. * its value.
  741. *
  742. * @return the contents of the serialVersionUID field
  743. *
  744. * @throws NoSuchFieldException if such a field does not exist or is
  745. * not static, not final, not of type Long or not accessible.
  746. */
  747. long getClassUIDFromField(Class cl)
  748. throws NoSuchFieldException
  749. {
  750. long result;
  751. try
  752. {
  753. // Use getDeclaredField rather than getField, since serialVersionUID
  754. // may not be public AND we only want the serialVersionUID of this
  755. // class, not a superclass or interface.
  756. final Field suid = cl.getDeclaredField("serialVersionUID");
  757. SetAccessibleAction setAccessible = new SetAccessibleAction(suid);
  758. AccessController.doPrivileged(setAccessible);
  759. int modifiers = suid.getModifiers();
  760. if (Modifier.isStatic(modifiers)
  761. && Modifier.isFinal(modifiers)
  762. && suid.getType() == Long.TYPE)
  763. result = suid.getLong(null);
  764. else
  765. throw new NoSuchFieldException();
  766. }
  767. catch (IllegalAccessException ignore)
  768. {
  769. throw new NoSuchFieldException();
  770. }
  771. return result;
  772. }
  773. /**
  774. * Calculate class serial version UID for a class that does not
  775. * define serialVersionUID:
  776. *
  777. * @param cl a class
  778. *
  779. * @return the calculated serial varsion UID.
  780. *
  781. * @throws NoSuchAlgorithmException if SHA algorithm not found
  782. *
  783. * @throws IOException if writing to the DigestOutputStream causes
  784. * an IOException.
  785. */
  786. long calculateClassUID(Class cl)
  787. throws NoSuchAlgorithmException, IOException
  788. {
  789. long result;
  790. MessageDigest md;
  791. try
  792. {
  793. md = MessageDigest.getInstance("SHA");
  794. }
  795. catch (NoSuchAlgorithmException e)
  796. {
  797. // If a provider already provides SHA, use it; otherwise, use this.
  798. Gnu gnuProvider = new Gnu();
  799. Security.addProvider(gnuProvider);
  800. md = MessageDigest.getInstance("SHA");
  801. }
  802. DigestOutputStream digest_out =
  803. new DigestOutputStream(nullOutputStream, md);
  804. DataOutputStream data_out = new DataOutputStream(digest_out);
  805. data_out.writeUTF(cl.getName());
  806. int modifiers = cl.getModifiers();
  807. // just look at interesting bits
  808. modifiers = modifiers & (Modifier.ABSTRACT | Modifier.FINAL
  809. | Modifier.INTERFACE | Modifier.PUBLIC);
  810. data_out.writeInt(modifiers);
  811. // Pretend that an array has no interfaces, because when array
  812. // serialization was defined (JDK 1.1), arrays didn't have it.
  813. if (! cl.isArray())
  814. {
  815. Class[] interfaces = cl.getInterfaces();
  816. Arrays.sort(interfaces, interfaceComparator);
  817. for (int i = 0; i < interfaces.length; i++)
  818. data_out.writeUTF(interfaces[i].getName());
  819. }
  820. Field field;
  821. Field[] fields = cl.getDeclaredFields();
  822. Arrays.sort(fields, memberComparator);
  823. for (int i = 0; i < fields.length; i++)
  824. {
  825. field = fields[i];
  826. modifiers = field.getModifiers();
  827. if (Modifier.isPrivate(modifiers)
  828. && (Modifier.isStatic(modifiers)
  829. || Modifier.isTransient(modifiers)))
  830. continue;
  831. data_out.writeUTF(field.getName());
  832. data_out.writeInt(modifiers);
  833. data_out.writeUTF(TypeSignature.getEncodingOfClass (field.getType()));
  834. }
  835. // write class initializer method if present
  836. if (VMObjectStreamClass.hasClassInitializer(cl))
  837. {
  838. data_out.writeUTF("<clinit>");
  839. data_out.writeInt(Modifier.STATIC);
  840. data_out.writeUTF("()V");
  841. }
  842. Constructor constructor;
  843. Constructor[] constructors = cl.getDeclaredConstructors();
  844. Arrays.sort (constructors, memberComparator);
  845. for (int i = 0; i < constructors.length; i++)
  846. {
  847. constructor = constructors[i];
  848. modifiers = constructor.getModifiers();
  849. if (Modifier.isPrivate(modifiers))
  850. continue;
  851. data_out.writeUTF("<init>");
  852. data_out.writeInt(modifiers);
  853. // the replacement of '/' with '.' was needed to make computed
  854. // SUID's agree with those computed by JDK
  855. data_out.writeUTF
  856. (TypeSignature.getEncodingOfConstructor(constructor).replace('/','.'));
  857. }
  858. Method method;
  859. Method[] methods = cl.getDeclaredMethods();
  860. Arrays.sort(methods, memberComparator);
  861. for (int i = 0; i < methods.length; i++)
  862. {
  863. method = methods[i];
  864. modifiers = method.getModifiers();
  865. if (Modifier.isPrivate(modifiers))
  866. continue;
  867. data_out.writeUTF(method.getName());
  868. data_out.writeInt(modifiers);
  869. // the replacement of '/' with '.' was needed to make computed
  870. // SUID's agree with those computed by JDK
  871. data_out.writeUTF
  872. (TypeSignature.getEncodingOfMethod(method).replace('/', '.'));
  873. }
  874. data_out.close();
  875. byte[] sha = md.digest();
  876. result = 0;
  877. int len = sha.length < 8 ? sha.length : 8;
  878. for (int i = 0; i < len; i++)
  879. result += (long) (sha[i] & 0xFF) << (8 * i);
  880. return result;
  881. }
  882. /**
  883. * Returns the value of CLAZZ's private static final field named
  884. * `serialPersistentFields'. It performs some sanity checks before
  885. * returning the real array. Besides, the returned array is a clean
  886. * copy of the original. So it can be modified.
  887. *
  888. * @param clazz Class to retrieve 'serialPersistentFields' from.
  889. * @return The content of 'serialPersistentFields'.
  890. */
  891. private ObjectStreamField[] getSerialPersistentFields(Class clazz)
  892. throws NoSuchFieldException, IllegalAccessException
  893. {
  894. ObjectStreamField[] fieldsArray = null;
  895. ObjectStreamField[] o;
  896. // Use getDeclaredField rather than getField for the same reason
  897. // as above in getDefinedSUID.
  898. Field f = clazz.getDeclaredField("serialPersistentFields");
  899. f.setAccessible(true);
  900. int modifiers = f.getModifiers();
  901. if (!(Modifier.isStatic(modifiers) &&
  902. Modifier.isFinal(modifiers) &&
  903. Modifier.isPrivate(modifiers)))
  904. return null;
  905. o = (ObjectStreamField[]) f.get(null);
  906. if (o == null)
  907. return null;
  908. fieldsArray = new ObjectStreamField[ o.length ];
  909. System.arraycopy(o, 0, fieldsArray, 0, o.length);
  910. return fieldsArray;
  911. }
  912. /**
  913. * Returns a new instance of the Class this ObjectStreamClass corresponds
  914. * to.
  915. * Note that this should only be used for Externalizable classes.
  916. *
  917. * @return A new instance.
  918. */
  919. Externalizable newInstance() throws InvalidClassException
  920. {
  921. synchronized(this)
  922. {
  923. if (constructor == null)
  924. {
  925. try
  926. {
  927. final Constructor c = clazz.getConstructor(new Class[0]);
  928. AccessController.doPrivileged(new PrivilegedAction()
  929. {
  930. public Object run()
  931. {
  932. c.setAccessible(true);
  933. return null;
  934. }
  935. });
  936. constructor = c;
  937. }
  938. catch(NoSuchMethodException x)
  939. {
  940. throw new InvalidClassException(clazz.getName(),
  941. "No public zero-argument constructor");
  942. }
  943. }
  944. }
  945. try
  946. {
  947. return (Externalizable)constructor.newInstance();
  948. }
  949. catch(Exception x)
  950. {
  951. throw (InvalidClassException)
  952. new InvalidClassException(clazz.getName(),
  953. "Unable to instantiate").initCause(x);
  954. }
  955. }
  956. public static final ObjectStreamField[] NO_FIELDS = {};
  957. private static Hashtable<Class,ObjectStreamClass> classLookupTable
  958. = new Hashtable<Class,ObjectStreamClass>();
  959. private static final NullOutputStream nullOutputStream = new NullOutputStream();
  960. private static final Comparator interfaceComparator = new InterfaceComparator();
  961. private static final Comparator memberComparator = new MemberComparator();
  962. private static final
  963. Class[] writeMethodArgTypes = { java.io.ObjectOutputStream.class };
  964. private ObjectStreamClass superClass;
  965. private Class<?> clazz;
  966. private String name;
  967. private long uid;
  968. private byte flags;
  969. // this field is package protected so that ObjectInputStream and
  970. // ObjectOutputStream can access it directly
  971. ObjectStreamField[] fields;
  972. // these are accessed by ObjectIn/OutputStream
  973. int primFieldSize = -1; // -1 if not yet calculated
  974. int objectFieldCount;
  975. Method readObjectMethod;
  976. Method readResolveMethod;
  977. Method writeReplaceMethod;
  978. Method writeObjectMethod;
  979. boolean realClassIsSerializable;
  980. boolean realClassIsExternalizable;
  981. ObjectStreamField[] fieldMapping;
  982. Constructor firstNonSerializableParentConstructor;
  983. private Constructor constructor; // default constructor for Externalizable
  984. boolean isProxyClass = false;
  985. /* GCJ LOCAL */
  986. // True after setFields() has been called
  987. private boolean fieldsSet = false;
  988. /* END GCJ LOCAL */
  989. // This is probably not necessary because this class is special cased already
  990. // but it will avoid showing up as a discrepancy when comparing SUIDs.
  991. private static final long serialVersionUID = -6120832682080437368L;
  992. // interfaces are compared only by name
  993. private static final class InterfaceComparator implements Comparator
  994. {
  995. public int compare(Object o1, Object o2)
  996. {
  997. return ((Class) o1).getName().compareTo(((Class) o2).getName());
  998. }
  999. }
  1000. // Members (Methods and Constructors) are compared first by name,
  1001. // conflicts are resolved by comparing type signatures
  1002. private static final class MemberComparator implements Comparator
  1003. {
  1004. public int compare(Object o1, Object o2)
  1005. {
  1006. Member m1 = (Member) o1;
  1007. Member m2 = (Member) o2;
  1008. int comp = m1.getName().compareTo(m2.getName());
  1009. if (comp == 0)
  1010. return TypeSignature.getEncodingOfMember(m1).
  1011. compareTo(TypeSignature.getEncodingOfMember(m2));
  1012. else
  1013. return comp;
  1014. }
  1015. }
  1016. }