View Javadoc
1   /*
2    * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4    *
5    * This code is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU General Public License version 2 only, as
7    * published by the Free Software Foundation.  Oracle designates this
8    * particular file as subject to the "Classpath" exception as provided
9    * by Oracle in the LICENSE file that accompanied this code.
10   *
11   * This code is distributed in the hope that it will be useful, but WITHOUT
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14   * version 2 for more details (a copy is included in the LICENSE file that
15   * accompanied this code).
16   *
17   * You should have received a copy of the GNU General Public License version
18   * 2 along with this work; if not, write to the Free Software Foundation,
19   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20   *
21   * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22   * or visit www.oracle.com if you need additional information or have any
23   * questions.
24   */
25  
26  package java.io;
27  
28  import java.lang.ref.Reference;
29  import java.lang.ref.ReferenceQueue;
30  import java.lang.ref.SoftReference;
31  import java.lang.ref.WeakReference;
32  import java.lang.reflect.Constructor;
33  import java.lang.reflect.Field;
34  import java.lang.reflect.InvocationTargetException;
35  import java.lang.reflect.Member;
36  import java.lang.reflect.Method;
37  import java.lang.reflect.Modifier;
38  import java.lang.reflect.Proxy;
39  import java.security.AccessController;
40  import java.security.MessageDigest;
41  import java.security.NoSuchAlgorithmException;
42  import java.security.PrivilegedAction;
43  import java.util.ArrayList;
44  import java.util.Arrays;
45  import java.util.Collections;
46  import java.util.Comparator;
47  import java.util.HashSet;
48  import java.util.Set;
49  import java.util.concurrent.ConcurrentHashMap;
50  import java.util.concurrent.ConcurrentMap;
51  import sun.misc.Unsafe;
52  import sun.reflect.CallerSensitive;
53  import sun.reflect.Reflection;
54  import sun.reflect.ReflectionFactory;
55  import sun.reflect.misc.ReflectUtil;
56  
57  /**
58   * Serialization's descriptor for classes.  It contains the name and
59   * serialVersionUID of the class.  The ObjectStreamClass for a specific class
60   * loaded in this Java VM can be found/created using the lookup method.
61   *
62   * <p>The algorithm to compute the SerialVersionUID is described in
63   * <a href="../../../platform/serialization/spec/class.html#4100">Object
64   * Serialization Specification, Section 4.6, Stream Unique Identifiers</a>.
65   *
66   * @author      Mike Warres
67   * @author      Roger Riggs
68   * @see ObjectStreamField
69   * @see <a href="../../../platform/serialization/spec/class.html">Object Serialization Specification, Section 4, Class Descriptors</a>
70   * @since   JDK1.1
71   */
72  public class ObjectStreamClass implements Serializable {
73  
74      /** serialPersistentFields value indicating no serializable fields */
75      public static final ObjectStreamField[] NO_FIELDS =
76          new ObjectStreamField[0];
77  
78      private static final long serialVersionUID = -6120832682080437368L;
79      private static final ObjectStreamField[] serialPersistentFields =
80          NO_FIELDS;
81  
82      /** reflection factory for obtaining serialization constructors */
83      private static final ReflectionFactory reflFactory =
84          AccessController.doPrivileged(
85              new ReflectionFactory.GetReflectionFactoryAction());
86  
87      private static class Caches {
88          /** cache mapping local classes -> descriptors */
89          static final ConcurrentMap<WeakClassKey,Reference<?>> localDescs =
90              new ConcurrentHashMap<>();
91  
92          /** cache mapping field group/local desc pairs -> field reflectors */
93          static final ConcurrentMap<FieldReflectorKey,Reference<?>> reflectors =
94              new ConcurrentHashMap<>();
95  
96          /** queue for WeakReferences to local classes */
97          private static final ReferenceQueue<Class<?>> localDescsQueue =
98              new ReferenceQueue<>();
99          /** queue for WeakReferences to field reflectors keys */
100         private static final ReferenceQueue<Class<?>> reflectorsQueue =
101             new ReferenceQueue<>();
102     }
103 
104     /** class associated with this descriptor (if any) */
105     private Class<?> cl;
106     /** name of class represented by this descriptor */
107     private String name;
108     /** serialVersionUID of represented class (null if not computed yet) */
109     private volatile Long suid;
110 
111     /** true if represents dynamic proxy class */
112     private boolean isProxy;
113     /** true if represents enum type */
114     private boolean isEnum;
115     /** true if represented class implements Serializable */
116     private boolean serializable;
117     /** true if represented class implements Externalizable */
118     private boolean externalizable;
119     /** true if desc has data written by class-defined writeObject method */
120     private boolean hasWriteObjectData;
121     /**
122      * true if desc has externalizable data written in block data format; this
123      * must be true by default to accommodate ObjectInputStream subclasses which
124      * override readClassDescriptor() to return class descriptors obtained from
125      * ObjectStreamClass.lookup() (see 4461737)
126      */
127     private boolean hasBlockExternalData = true;
128 
129     /**
130      * Contains information about InvalidClassException instances to be thrown
131      * when attempting operations on an invalid class. Note that instances of
132      * this class are immutable and are potentially shared among
133      * ObjectStreamClass instances.
134      */
135     private static class ExceptionInfo {
136         private final String className;
137         private final String message;
138 
139         ExceptionInfo(String cn, String msg) {
140             className = cn;
141             message = msg;
142         }
143 
144         /**
145          * Returns (does not throw) an InvalidClassException instance created
146          * from the information in this object, suitable for being thrown by
147          * the caller.
148          */
149         InvalidClassException newInvalidClassException() {
150             return new InvalidClassException(className, message);
151         }
152     }
153 
154     /** exception (if any) thrown while attempting to resolve class */
155     private ClassNotFoundException resolveEx;
156     /** exception (if any) to throw if non-enum deserialization attempted */
157     private ExceptionInfo deserializeEx;
158     /** exception (if any) to throw if non-enum serialization attempted */
159     private ExceptionInfo serializeEx;
160     /** exception (if any) to throw if default serialization attempted */
161     private ExceptionInfo defaultSerializeEx;
162 
163     /** serializable fields */
164     private ObjectStreamField[] fields;
165     /** aggregate marshalled size of primitive fields */
166     private int primDataSize;
167     /** number of non-primitive fields */
168     private int numObjFields;
169     /** reflector for setting/getting serializable field values */
170     private FieldReflector fieldRefl;
171     /** data layout of serialized objects described by this class desc */
172     private volatile ClassDataSlot[] dataLayout;
173 
174     /** serialization-appropriate constructor, or null if none */
175     private Constructor<?> cons;
176     /** class-defined writeObject method, or null if none */
177     private Method writeObjectMethod;
178     /** class-defined readObject method, or null if none */
179     private Method readObjectMethod;
180     /** class-defined readObjectNoData method, or null if none */
181     private Method readObjectNoDataMethod;
182     /** class-defined writeReplace method, or null if none */
183     private Method writeReplaceMethod;
184     /** class-defined readResolve method, or null if none */
185     private Method readResolveMethod;
186 
187     /** local class descriptor for represented class (may point to self) */
188     private ObjectStreamClass localDesc;
189     /** superclass descriptor appearing in stream */
190     private ObjectStreamClass superDesc;
191 
192     /**
193      * Initializes native code.
194      */
195     private static native void initNative();
196     static {
197         initNative();
198     }
199 
200     /**
201      * Find the descriptor for a class that can be serialized.  Creates an
202      * ObjectStreamClass instance if one does not exist yet for class. Null is
203      * returned if the specified class does not implement java.io.Serializable
204      * or java.io.Externalizable.
205      *
206      * @param   cl class for which to get the descriptor
207      * @return  the class descriptor for the specified class
208      */
209     public static ObjectStreamClass lookup(Class<?> cl) {
210         return lookup(cl, false);
211     }
212 
213     /**
214      * Returns the descriptor for any class, regardless of whether it
215      * implements {@link Serializable}.
216      *
217      * @param        cl class for which to get the descriptor
218      * @return       the class descriptor for the specified class
219      * @since 1.6
220      */
221     public static ObjectStreamClass lookupAny(Class<?> cl) {
222         return lookup(cl, true);
223     }
224 
225     /**
226      * Returns the name of the class described by this descriptor.
227      * This method returns the name of the class in the format that
228      * is used by the {@link Class#getName} method.
229      *
230      * @return a string representing the name of the class
231      */
232     public String getName() {
233         return name;
234     }
235 
236     /**
237      * Return the serialVersionUID for this class.  The serialVersionUID
238      * defines a set of classes all with the same name that have evolved from a
239      * common root class and agree to be serialized and deserialized using a
240      * common format.  NonSerializable classes have a serialVersionUID of 0L.
241      *
242      * @return  the SUID of the class described by this descriptor
243      */
244     public long getSerialVersionUID() {
245         // REMIND: synchronize instead of relying on volatile?
246         if (suid == null) {
247             suid = AccessController.doPrivileged(
248                 new PrivilegedAction<Long>() {
249                     public Long run() {
250                         return computeDefaultSUID(cl);
251                     }
252                 }
253             );
254         }
255         return suid.longValue();
256     }
257 
258     /**
259      * Return the class in the local VM that this version is mapped to.  Null
260      * is returned if there is no corresponding local class.
261      *
262      * @return  the <code>Class</code> instance that this descriptor represents
263      */
264     @CallerSensitive
265     public Class<?> forClass() {
266         if (cl == null) {
267             return null;
268         }
269         if (System.getSecurityManager() != null) {
270             Class<?> caller = Reflection.getCallerClass();
271             if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(), cl.getClassLoader())) {
272                 ReflectUtil.checkPackageAccess(cl);
273             }
274         }
275         return cl;
276     }
277 
278     /**
279      * Return an array of the fields of this serializable class.
280      *
281      * @return  an array containing an element for each persistent field of
282      *          this class. Returns an array of length zero if there are no
283      *          fields.
284      * @since 1.2
285      */
286     public ObjectStreamField[] getFields() {
287         return getFields(true);
288     }
289 
290     /**
291      * Get the field of this class by name.
292      *
293      * @param   name the name of the data field to look for
294      * @return  The ObjectStreamField object of the named field or null if
295      *          there is no such named field.
296      */
297     public ObjectStreamField getField(String name) {
298         return getField(name, null);
299     }
300 
301     /**
302      * Return a string describing this ObjectStreamClass.
303      */
304     public String toString() {
305         return name + ": static final long serialVersionUID = " +
306             getSerialVersionUID() + "L;";
307     }
308 
309     /**
310      * Looks up and returns class descriptor for given class, or null if class
311      * is non-serializable and "all" is set to false.
312      *
313      * @param   cl class to look up
314      * @param   all if true, return descriptors for all classes; if false, only
315      *          return descriptors for serializable classes
316      */
317     static ObjectStreamClass lookup(Class<?> cl, boolean all) {
318         if (!(all || Serializable.class.isAssignableFrom(cl))) {
319             return null;
320         }
321         processQueue(Caches.localDescsQueue, Caches.localDescs);
322         WeakClassKey key = new WeakClassKey(cl, Caches.localDescsQueue);
323         Reference<?> ref = Caches.localDescs.get(key);
324         Object entry = null;
325         if (ref != null) {
326             entry = ref.get();
327         }
328         EntryFuture future = null;
329         if (entry == null) {
330             EntryFuture newEntry = new EntryFuture();
331             Reference<?> newRef = new SoftReference<>(newEntry);
332             do {
333                 if (ref != null) {
334                     Caches.localDescs.remove(key, ref);
335                 }
336                 ref = Caches.localDescs.putIfAbsent(key, newRef);
337                 if (ref != null) {
338                     entry = ref.get();
339                 }
340             } while (ref != null && entry == null);
341             if (entry == null) {
342                 future = newEntry;
343             }
344         }
345 
346         if (entry instanceof ObjectStreamClass) {  // check common case first
347             return (ObjectStreamClass) entry;
348         }
349         if (entry instanceof EntryFuture) {
350             future = (EntryFuture) entry;
351             if (future.getOwner() == Thread.currentThread()) {
352                 /*
353                  * Handle nested call situation described by 4803747: waiting
354                  * for future value to be set by a lookup() call further up the
355                  * stack will result in deadlock, so calculate and set the
356                  * future value here instead.
357                  */
358                 entry = null;
359             } else {
360                 entry = future.get();
361             }
362         }
363         if (entry == null) {
364             try {
365                 entry = new ObjectStreamClass(cl);
366             } catch (Throwable th) {
367                 entry = th;
368             }
369             if (future.set(entry)) {
370                 Caches.localDescs.put(key, new SoftReference<Object>(entry));
371             } else {
372                 // nested lookup call already set future
373                 entry = future.get();
374             }
375         }
376 
377         if (entry instanceof ObjectStreamClass) {
378             return (ObjectStreamClass) entry;
379         } else if (entry instanceof RuntimeException) {
380             throw (RuntimeException) entry;
381         } else if (entry instanceof Error) {
382             throw (Error) entry;
383         } else {
384             throw new InternalError("unexpected entry: " + entry);
385         }
386     }
387 
388     /**
389      * Placeholder used in class descriptor and field reflector lookup tables
390      * for an entry in the process of being initialized.  (Internal) callers
391      * which receive an EntryFuture belonging to another thread as the result
392      * of a lookup should call the get() method of the EntryFuture; this will
393      * return the actual entry once it is ready for use and has been set().  To
394      * conserve objects, EntryFutures synchronize on themselves.
395      */
396     private static class EntryFuture {
397 
398         private static final Object unset = new Object();
399         private final Thread owner = Thread.currentThread();
400         private Object entry = unset;
401 
402         /**
403          * Attempts to set the value contained by this EntryFuture.  If the
404          * EntryFuture's value has not been set already, then the value is
405          * saved, any callers blocked in the get() method are notified, and
406          * true is returned.  If the value has already been set, then no saving
407          * or notification occurs, and false is returned.
408          */
409         synchronized boolean set(Object entry) {
410             if (this.entry != unset) {
411                 return false;
412             }
413             this.entry = entry;
414             notifyAll();
415             return true;
416         }
417 
418         /**
419          * Returns the value contained by this EntryFuture, blocking if
420          * necessary until a value is set.
421          */
422         synchronized Object get() {
423             boolean interrupted = false;
424             while (entry == unset) {
425                 try {
426                     wait();
427                 } catch (InterruptedException ex) {
428                     interrupted = true;
429                 }
430             }
431             if (interrupted) {
432                 AccessController.doPrivileged(
433                     new PrivilegedAction<Void>() {
434                         public Void run() {
435                             Thread.currentThread().interrupt();
436                             return null;
437                         }
438                     }
439                 );
440             }
441             return entry;
442         }
443 
444         /**
445          * Returns the thread that created this EntryFuture.
446          */
447         Thread getOwner() {
448             return owner;
449         }
450     }
451 
452     /**
453      * Creates local class descriptor representing given class.
454      */
455     private ObjectStreamClass(final Class<?> cl) {
456         this.cl = cl;
457         name = cl.getName();
458         isProxy = Proxy.isProxyClass(cl);
459         isEnum = Enum.class.isAssignableFrom(cl);
460         serializable = Serializable.class.isAssignableFrom(cl);
461         externalizable = Externalizable.class.isAssignableFrom(cl);
462 
463         Class<?> superCl = cl.getSuperclass();
464         superDesc = (superCl != null) ? lookup(superCl, false) : null;
465         localDesc = this;
466 
467         if (serializable) {
468             AccessController.doPrivileged(new PrivilegedAction<Void>() {
469                 public Void run() {
470                     if (isEnum) {
471                         suid = Long.valueOf(0);
472                         fields = NO_FIELDS;
473                         return null;
474                     }
475                     if (cl.isArray()) {
476                         fields = NO_FIELDS;
477                         return null;
478                     }
479 
480                     suid = getDeclaredSUID(cl);
481                     try {
482                         fields = getSerialFields(cl);
483                         computeFieldOffsets();
484                     } catch (InvalidClassException e) {
485                         serializeEx = deserializeEx =
486                             new ExceptionInfo(e.classname, e.getMessage());
487                         fields = NO_FIELDS;
488                     }
489 
490                     if (externalizable) {
491                         cons = getExternalizableConstructor(cl);
492                     } else {
493                         cons = getSerializableConstructor(cl);
494                         writeObjectMethod = getPrivateMethod(cl, "writeObject",
495                             new Class<?>[] { ObjectOutputStream.class },
496                             Void.TYPE);
497                         readObjectMethod = getPrivateMethod(cl, "readObject",
498                             new Class<?>[] { ObjectInputStream.class },
499                             Void.TYPE);
500                         readObjectNoDataMethod = getPrivateMethod(
501                             cl, "readObjectNoData", null, Void.TYPE);
502                         hasWriteObjectData = (writeObjectMethod != null);
503                     }
504                     writeReplaceMethod = getInheritableMethod(
505                         cl, "writeReplace", null, Object.class);
506                     readResolveMethod = getInheritableMethod(
507                         cl, "readResolve", null, Object.class);
508                     return null;
509                 }
510             });
511         } else {
512             suid = Long.valueOf(0);
513             fields = NO_FIELDS;
514         }
515 
516         try {
517             fieldRefl = getReflector(fields, this);
518         } catch (InvalidClassException ex) {
519             // field mismatches impossible when matching local fields vs. self
520             throw new InternalError(ex);
521         }
522 
523         if (deserializeEx == null) {
524             if (isEnum) {
525                 deserializeEx = new ExceptionInfo(name, "enum type");
526             } else if (cons == null) {
527                 deserializeEx = new ExceptionInfo(name, "no valid constructor");
528             }
529         }
530         for (int i = 0; i < fields.length; i++) {
531             if (fields[i].getField() == null) {
532                 defaultSerializeEx = new ExceptionInfo(
533                     name, "unmatched serializable field(s) declared");
534             }
535         }
536     }
537 
538     /**
539      * Creates blank class descriptor which should be initialized via a
540      * subsequent call to initProxy(), initNonProxy() or readNonProxy().
541      */
542     ObjectStreamClass() {
543     }
544 
545     /**
546      * Initializes class descriptor representing a proxy class.
547      */
548     void initProxy(Class<?> cl,
549                    ClassNotFoundException resolveEx,
550                    ObjectStreamClass superDesc)
551         throws InvalidClassException
552     {
553         this.cl = cl;
554         this.resolveEx = resolveEx;
555         this.superDesc = superDesc;
556         isProxy = true;
557         serializable = true;
558         suid = Long.valueOf(0);
559         fields = NO_FIELDS;
560 
561         if (cl != null) {
562             localDesc = lookup(cl, true);
563             if (!localDesc.isProxy) {
564                 throw new InvalidClassException(
565                     "cannot bind proxy descriptor to a non-proxy class");
566             }
567             name = localDesc.name;
568             externalizable = localDesc.externalizable;
569             cons = localDesc.cons;
570             writeReplaceMethod = localDesc.writeReplaceMethod;
571             readResolveMethod = localDesc.readResolveMethod;
572             deserializeEx = localDesc.deserializeEx;
573         }
574         fieldRefl = getReflector(fields, localDesc);
575     }
576 
577     /**
578      * Initializes class descriptor representing a non-proxy class.
579      */
580     void initNonProxy(ObjectStreamClass model,
581                       Class<?> cl,
582                       ClassNotFoundException resolveEx,
583                       ObjectStreamClass superDesc)
584         throws InvalidClassException
585     {
586         this.cl = cl;
587         this.resolveEx = resolveEx;
588         this.superDesc = superDesc;
589         name = model.name;
590         suid = Long.valueOf(model.getSerialVersionUID());
591         isProxy = false;
592         isEnum = model.isEnum;
593         serializable = model.serializable;
594         externalizable = model.externalizable;
595         hasBlockExternalData = model.hasBlockExternalData;
596         hasWriteObjectData = model.hasWriteObjectData;
597         fields = model.fields;
598         primDataSize = model.primDataSize;
599         numObjFields = model.numObjFields;
600 
601         if (cl != null) {
602             localDesc = lookup(cl, true);
603             if (localDesc.isProxy) {
604                 throw new InvalidClassException(
605                     "cannot bind non-proxy descriptor to a proxy class");
606             }
607             if (isEnum != localDesc.isEnum) {
608                 throw new InvalidClassException(isEnum ?
609                     "cannot bind enum descriptor to a non-enum class" :
610                     "cannot bind non-enum descriptor to an enum class");
611             }
612 
613             if (serializable == localDesc.serializable &&
614                 !cl.isArray() &&
615                 suid.longValue() != localDesc.getSerialVersionUID())
616             {
617                 throw new InvalidClassException(localDesc.name,
618                     "local class incompatible: " +
619                     "stream classdesc serialVersionUID = " + suid +
620                     ", local class serialVersionUID = " +
621                     localDesc.getSerialVersionUID());
622             }
623 
624             if (!classNamesEqual(name, localDesc.name)) {
625                 throw new InvalidClassException(localDesc.name,
626                     "local class name incompatible with stream class " +
627                     "name \"" + name + "\"");
628             }
629 
630             if (!isEnum) {
631                 if ((serializable == localDesc.serializable) &&
632                     (externalizable != localDesc.externalizable))
633                 {
634                     throw new InvalidClassException(localDesc.name,
635                         "Serializable incompatible with Externalizable");
636                 }
637 
638                 if ((serializable != localDesc.serializable) ||
639                     (externalizable != localDesc.externalizable) ||
640                     !(serializable || externalizable))
641                 {
642                     deserializeEx = new ExceptionInfo(
643                         localDesc.name, "class invalid for deserialization");
644                 }
645             }
646 
647             cons = localDesc.cons;
648             writeObjectMethod = localDesc.writeObjectMethod;
649             readObjectMethod = localDesc.readObjectMethod;
650             readObjectNoDataMethod = localDesc.readObjectNoDataMethod;
651             writeReplaceMethod = localDesc.writeReplaceMethod;
652             readResolveMethod = localDesc.readResolveMethod;
653             if (deserializeEx == null) {
654                 deserializeEx = localDesc.deserializeEx;
655             }
656         }
657         fieldRefl = getReflector(fields, localDesc);
658         // reassign to matched fields so as to reflect local unshared settings
659         fields = fieldRefl.getFields();
660     }
661 
662     /**
663      * Reads non-proxy class descriptor information from given input stream.
664      * The resulting class descriptor is not fully functional; it can only be
665      * used as input to the ObjectInputStream.resolveClass() and
666      * ObjectStreamClass.initNonProxy() methods.
667      */
668     void readNonProxy(ObjectInputStream in)
669         throws IOException, ClassNotFoundException
670     {
671         name = in.readUTF();
672         suid = Long.valueOf(in.readLong());
673         isProxy = false;
674 
675         byte flags = in.readByte();
676         hasWriteObjectData =
677             ((flags & ObjectStreamConstants.SC_WRITE_METHOD) != 0);
678         hasBlockExternalData =
679             ((flags & ObjectStreamConstants.SC_BLOCK_DATA) != 0);
680         externalizable =
681             ((flags & ObjectStreamConstants.SC_EXTERNALIZABLE) != 0);
682         boolean sflag =
683             ((flags & ObjectStreamConstants.SC_SERIALIZABLE) != 0);
684         if (externalizable && sflag) {
685             throw new InvalidClassException(
686                 name, "serializable and externalizable flags conflict");
687         }
688         serializable = externalizable || sflag;
689         isEnum = ((flags & ObjectStreamConstants.SC_ENUM) != 0);
690         if (isEnum && suid.longValue() != 0L) {
691             throw new InvalidClassException(name,
692                 "enum descriptor has non-zero serialVersionUID: " + suid);
693         }
694 
695         int numFields = in.readShort();
696         if (isEnum && numFields != 0) {
697             throw new InvalidClassException(name,
698                 "enum descriptor has non-zero field count: " + numFields);
699         }
700         fields = (numFields > 0) ?
701             new ObjectStreamField[numFields] : NO_FIELDS;
702         for (int i = 0; i < numFields; i++) {
703             char tcode = (char) in.readByte();
704             String fname = in.readUTF();
705             String signature = ((tcode == 'L') || (tcode == '[')) ?
706                 in.readTypeString() : new String(new char[] { tcode });
707             try {
708                 fields[i] = new ObjectStreamField(fname, signature, false);
709             } catch (RuntimeException e) {
710                 throw (IOException) new InvalidClassException(name,
711                     "invalid descriptor for field " + fname).initCause(e);
712             }
713         }
714         computeFieldOffsets();
715     }
716 
717     /**
718      * Writes non-proxy class descriptor information to given output stream.
719      */
720     void writeNonProxy(ObjectOutputStream out) throws IOException {
721         out.writeUTF(name);
722         out.writeLong(getSerialVersionUID());
723 
724         byte flags = 0;
725         if (externalizable) {
726             flags |= ObjectStreamConstants.SC_EXTERNALIZABLE;
727             int protocol = out.getProtocolVersion();
728             if (protocol != ObjectStreamConstants.PROTOCOL_VERSION_1) {
729                 flags |= ObjectStreamConstants.SC_BLOCK_DATA;
730             }
731         } else if (serializable) {
732             flags |= ObjectStreamConstants.SC_SERIALIZABLE;
733         }
734         if (hasWriteObjectData) {
735             flags |= ObjectStreamConstants.SC_WRITE_METHOD;
736         }
737         if (isEnum) {
738             flags |= ObjectStreamConstants.SC_ENUM;
739         }
740         out.writeByte(flags);
741 
742         out.writeShort(fields.length);
743         for (int i = 0; i < fields.length; i++) {
744             ObjectStreamField f = fields[i];
745             out.writeByte(f.getTypeCode());
746             out.writeUTF(f.getName());
747             if (!f.isPrimitive()) {
748                 out.writeTypeString(f.getTypeString());
749             }
750         }
751     }
752 
753     /**
754      * Returns ClassNotFoundException (if any) thrown while attempting to
755      * resolve local class corresponding to this class descriptor.
756      */
757     ClassNotFoundException getResolveException() {
758         return resolveEx;
759     }
760 
761     /**
762      * Throws an InvalidClassException if object instances referencing this
763      * class descriptor should not be allowed to deserialize.  This method does
764      * not apply to deserialization of enum constants.
765      */
766     void checkDeserialize() throws InvalidClassException {
767         if (deserializeEx != null) {
768             throw deserializeEx.newInvalidClassException();
769         }
770     }
771 
772     /**
773      * Throws an InvalidClassException if objects whose class is represented by
774      * this descriptor should not be allowed to serialize.  This method does
775      * not apply to serialization of enum constants.
776      */
777     void checkSerialize() throws InvalidClassException {
778         if (serializeEx != null) {
779             throw serializeEx.newInvalidClassException();
780         }
781     }
782 
783     /**
784      * Throws an InvalidClassException if objects whose class is represented by
785      * this descriptor should not be permitted to use default serialization
786      * (e.g., if the class declares serializable fields that do not correspond
787      * to actual fields, and hence must use the GetField API).  This method
788      * does not apply to deserialization of enum constants.
789      */
790     void checkDefaultSerialize() throws InvalidClassException {
791         if (defaultSerializeEx != null) {
792             throw defaultSerializeEx.newInvalidClassException();
793         }
794     }
795 
796     /**
797      * Returns superclass descriptor.  Note that on the receiving side, the
798      * superclass descriptor may be bound to a class that is not a superclass
799      * of the subclass descriptor's bound class.
800      */
801     ObjectStreamClass getSuperDesc() {
802         return superDesc;
803     }
804 
805     /**
806      * Returns the "local" class descriptor for the class associated with this
807      * class descriptor (i.e., the result of
808      * ObjectStreamClass.lookup(this.forClass())) or null if there is no class
809      * associated with this descriptor.
810      */
811     ObjectStreamClass getLocalDesc() {
812         return localDesc;
813     }
814 
815     /**
816      * Returns arrays of ObjectStreamFields representing the serializable
817      * fields of the represented class.  If copy is true, a clone of this class
818      * descriptor's field array is returned, otherwise the array itself is
819      * returned.
820      */
821     ObjectStreamField[] getFields(boolean copy) {
822         return copy ? fields.clone() : fields;
823     }
824 
825     /**
826      * Looks up a serializable field of the represented class by name and type.
827      * A specified type of null matches all types, Object.class matches all
828      * non-primitive types, and any other non-null type matches assignable
829      * types only.  Returns matching field, or null if no match found.
830      */
831     ObjectStreamField getField(String name, Class<?> type) {
832         for (int i = 0; i < fields.length; i++) {
833             ObjectStreamField f = fields[i];
834             if (f.getName().equals(name)) {
835                 if (type == null ||
836                     (type == Object.class && !f.isPrimitive()))
837                 {
838                     return f;
839                 }
840                 Class<?> ftype = f.getType();
841                 if (ftype != null && type.isAssignableFrom(ftype)) {
842                     return f;
843                 }
844             }
845         }
846         return null;
847     }
848 
849     /**
850      * Returns true if class descriptor represents a dynamic proxy class, false
851      * otherwise.
852      */
853     boolean isProxy() {
854         return isProxy;
855     }
856 
857     /**
858      * Returns true if class descriptor represents an enum type, false
859      * otherwise.
860      */
861     boolean isEnum() {
862         return isEnum;
863     }
864 
865     /**
866      * Returns true if represented class implements Externalizable, false
867      * otherwise.
868      */
869     boolean isExternalizable() {
870         return externalizable;
871     }
872 
873     /**
874      * Returns true if represented class implements Serializable, false
875      * otherwise.
876      */
877     boolean isSerializable() {
878         return serializable;
879     }
880 
881     /**
882      * Returns true if class descriptor represents externalizable class that
883      * has written its data in 1.2 (block data) format, false otherwise.
884      */
885     boolean hasBlockExternalData() {
886         return hasBlockExternalData;
887     }
888 
889     /**
890      * Returns true if class descriptor represents serializable (but not
891      * externalizable) class which has written its data via a custom
892      * writeObject() method, false otherwise.
893      */
894     boolean hasWriteObjectData() {
895         return hasWriteObjectData;
896     }
897 
898     /**
899      * Returns true if represented class is serializable/externalizable and can
900      * be instantiated by the serialization runtime--i.e., if it is
901      * externalizable and defines a public no-arg constructor, or if it is
902      * non-externalizable and its first non-serializable superclass defines an
903      * accessible no-arg constructor.  Otherwise, returns false.
904      */
905     boolean isInstantiable() {
906         return (cons != null);
907     }
908 
909     /**
910      * Returns true if represented class is serializable (but not
911      * externalizable) and defines a conformant writeObject method.  Otherwise,
912      * returns false.
913      */
914     boolean hasWriteObjectMethod() {
915         return (writeObjectMethod != null);
916     }
917 
918     /**
919      * Returns true if represented class is serializable (but not
920      * externalizable) and defines a conformant readObject method.  Otherwise,
921      * returns false.
922      */
923     boolean hasReadObjectMethod() {
924         return (readObjectMethod != null);
925     }
926 
927     /**
928      * Returns true if represented class is serializable (but not
929      * externalizable) and defines a conformant readObjectNoData method.
930      * Otherwise, returns false.
931      */
932     boolean hasReadObjectNoDataMethod() {
933         return (readObjectNoDataMethod != null);
934     }
935 
936     /**
937      * Returns true if represented class is serializable or externalizable and
938      * defines a conformant writeReplace method.  Otherwise, returns false.
939      */
940     boolean hasWriteReplaceMethod() {
941         return (writeReplaceMethod != null);
942     }
943 
944     /**
945      * Returns true if represented class is serializable or externalizable and
946      * defines a conformant readResolve method.  Otherwise, returns false.
947      */
948     boolean hasReadResolveMethod() {
949         return (readResolveMethod != null);
950     }
951 
952     /**
953      * Creates a new instance of the represented class.  If the class is
954      * externalizable, invokes its public no-arg constructor; otherwise, if the
955      * class is serializable, invokes the no-arg constructor of the first
956      * non-serializable superclass.  Throws UnsupportedOperationException if
957      * this class descriptor is not associated with a class, if the associated
958      * class is non-serializable or if the appropriate no-arg constructor is
959      * inaccessible/unavailable.
960      */
961     Object newInstance()
962         throws InstantiationException, InvocationTargetException,
963                UnsupportedOperationException
964     {
965         if (cons != null) {
966             try {
967                 return cons.newInstance();
968             } catch (IllegalAccessException ex) {
969                 // should not occur, as access checks have been suppressed
970                 throw new InternalError(ex);
971             }
972         } else {
973             throw new UnsupportedOperationException();
974         }
975     }
976 
977     /**
978      * Invokes the writeObject method of the represented serializable class.
979      * Throws UnsupportedOperationException if this class descriptor is not
980      * associated with a class, or if the class is externalizable,
981      * non-serializable or does not define writeObject.
982      */
983     void invokeWriteObject(Object obj, ObjectOutputStream out)
984         throws IOException, UnsupportedOperationException
985     {
986         if (writeObjectMethod != null) {
987             try {
988                 writeObjectMethod.invoke(obj, new Object[]{ out });
989             } catch (InvocationTargetException ex) {
990                 Throwable th = ex.getTargetException();
991                 if (th instanceof IOException) {
992                     throw (IOException) th;
993                 } else {
994                     throwMiscException(th);
995                 }
996             } catch (IllegalAccessException ex) {
997                 // should not occur, as access checks have been suppressed
998                 throw new InternalError(ex);
999             }
1000         } else {
1001             throw new UnsupportedOperationException();
1002         }
1003     }
1004 
1005     /**
1006      * Invokes the readObject method of the represented serializable class.
1007      * Throws UnsupportedOperationException if this class descriptor is not
1008      * associated with a class, or if the class is externalizable,
1009      * non-serializable or does not define readObject.
1010      */
1011     void invokeReadObject(Object obj, ObjectInputStream in)
1012         throws ClassNotFoundException, IOException,
1013                UnsupportedOperationException
1014     {
1015         if (readObjectMethod != null) {
1016             try {
1017                 readObjectMethod.invoke(obj, new Object[]{ in });
1018             } catch (InvocationTargetException ex) {
1019                 Throwable th = ex.getTargetException();
1020                 if (th instanceof ClassNotFoundException) {
1021                     throw (ClassNotFoundException) th;
1022                 } else if (th instanceof IOException) {
1023                     throw (IOException) th;
1024                 } else {
1025                     throwMiscException(th);
1026                 }
1027             } catch (IllegalAccessException ex) {
1028                 // should not occur, as access checks have been suppressed
1029                 throw new InternalError(ex);
1030             }
1031         } else {
1032             throw new UnsupportedOperationException();
1033         }
1034     }
1035 
1036     /**
1037      * Invokes the readObjectNoData method of the represented serializable
1038      * class.  Throws UnsupportedOperationException if this class descriptor is
1039      * not associated with a class, or if the class is externalizable,
1040      * non-serializable or does not define readObjectNoData.
1041      */
1042     void invokeReadObjectNoData(Object obj)
1043         throws IOException, UnsupportedOperationException
1044     {
1045         if (readObjectNoDataMethod != null) {
1046             try {
1047                 readObjectNoDataMethod.invoke(obj, (Object[]) null);
1048             } catch (InvocationTargetException ex) {
1049                 Throwable th = ex.getTargetException();
1050                 if (th instanceof ObjectStreamException) {
1051                     throw (ObjectStreamException) th;
1052                 } else {
1053                     throwMiscException(th);
1054                 }
1055             } catch (IllegalAccessException ex) {
1056                 // should not occur, as access checks have been suppressed
1057                 throw new InternalError(ex);
1058             }
1059         } else {
1060             throw new UnsupportedOperationException();
1061         }
1062     }
1063 
1064     /**
1065      * Invokes the writeReplace method of the represented serializable class and
1066      * returns the result.  Throws UnsupportedOperationException if this class
1067      * descriptor is not associated with a class, or if the class is
1068      * non-serializable or does not define writeReplace.
1069      */
1070     Object invokeWriteReplace(Object obj)
1071         throws IOException, UnsupportedOperationException
1072     {
1073         if (writeReplaceMethod != null) {
1074             try {
1075                 return writeReplaceMethod.invoke(obj, (Object[]) null);
1076             } catch (InvocationTargetException ex) {
1077                 Throwable th = ex.getTargetException();
1078                 if (th instanceof ObjectStreamException) {
1079                     throw (ObjectStreamException) th;
1080                 } else {
1081                     throwMiscException(th);
1082                     throw new InternalError(th);  // never reached
1083                 }
1084             } catch (IllegalAccessException ex) {
1085                 // should not occur, as access checks have been suppressed
1086                 throw new InternalError(ex);
1087             }
1088         } else {
1089             throw new UnsupportedOperationException();
1090         }
1091     }
1092 
1093     /**
1094      * Invokes the readResolve method of the represented serializable class and
1095      * returns the result.  Throws UnsupportedOperationException if this class
1096      * descriptor is not associated with a class, or if the class is
1097      * non-serializable or does not define readResolve.
1098      */
1099     Object invokeReadResolve(Object obj)
1100         throws IOException, UnsupportedOperationException
1101     {
1102         if (readResolveMethod != null) {
1103             try {
1104                 return readResolveMethod.invoke(obj, (Object[]) null);
1105             } catch (InvocationTargetException ex) {
1106                 Throwable th = ex.getTargetException();
1107                 if (th instanceof ObjectStreamException) {
1108                     throw (ObjectStreamException) th;
1109                 } else {
1110                     throwMiscException(th);
1111                     throw new InternalError(th);  // never reached
1112                 }
1113             } catch (IllegalAccessException ex) {
1114                 // should not occur, as access checks have been suppressed
1115                 throw new InternalError(ex);
1116             }
1117         } else {
1118             throw new UnsupportedOperationException();
1119         }
1120     }
1121 
1122     /**
1123      * Class representing the portion of an object's serialized form allotted
1124      * to data described by a given class descriptor.  If "hasData" is false,
1125      * the object's serialized form does not contain data associated with the
1126      * class descriptor.
1127      */
1128     static class ClassDataSlot {
1129 
1130         /** class descriptor "occupying" this slot */
1131         final ObjectStreamClass desc;
1132         /** true if serialized form includes data for this slot's descriptor */
1133         final boolean hasData;
1134 
1135         ClassDataSlot(ObjectStreamClass desc, boolean hasData) {
1136             this.desc = desc;
1137             this.hasData = hasData;
1138         }
1139     }
1140 
1141     /**
1142      * Returns array of ClassDataSlot instances representing the data layout
1143      * (including superclass data) for serialized objects described by this
1144      * class descriptor.  ClassDataSlots are ordered by inheritance with those
1145      * containing "higher" superclasses appearing first.  The final
1146      * ClassDataSlot contains a reference to this descriptor.
1147      */
1148     ClassDataSlot[] getClassDataLayout() throws InvalidClassException {
1149         // REMIND: synchronize instead of relying on volatile?
1150         if (dataLayout == null) {
1151             dataLayout = getClassDataLayout0();
1152         }
1153         return dataLayout;
1154     }
1155 
1156     private ClassDataSlot[] getClassDataLayout0()
1157         throws InvalidClassException
1158     {
1159         ArrayList<ClassDataSlot> slots = new ArrayList<>();
1160         Class<?> start = cl, end = cl;
1161 
1162         // locate closest non-serializable superclass
1163         while (end != null && Serializable.class.isAssignableFrom(end)) {
1164             end = end.getSuperclass();
1165         }
1166 
1167         HashSet<String> oscNames = new HashSet<>(3);
1168 
1169         for (ObjectStreamClass d = this; d != null; d = d.superDesc) {
1170             if (oscNames.contains(d.name)) {
1171                 throw new InvalidClassException("Circular reference.");
1172             } else {
1173                 oscNames.add(d.name);
1174             }
1175 
1176             // search up inheritance hierarchy for class with matching name
1177             String searchName = (d.cl != null) ? d.cl.getName() : d.name;
1178             Class<?> match = null;
1179             for (Class<?> c = start; c != end; c = c.getSuperclass()) {
1180                 if (searchName.equals(c.getName())) {
1181                     match = c;
1182                     break;
1183                 }
1184             }
1185 
1186             // add "no data" slot for each unmatched class below match
1187             if (match != null) {
1188                 for (Class<?> c = start; c != match; c = c.getSuperclass()) {
1189                     slots.add(new ClassDataSlot(
1190                         ObjectStreamClass.lookup(c, true), false));
1191                 }
1192                 start = match.getSuperclass();
1193             }
1194 
1195             // record descriptor/class pairing
1196             slots.add(new ClassDataSlot(d.getVariantFor(match), true));
1197         }
1198 
1199         // add "no data" slot for any leftover unmatched classes
1200         for (Class<?> c = start; c != end; c = c.getSuperclass()) {
1201             slots.add(new ClassDataSlot(
1202                 ObjectStreamClass.lookup(c, true), false));
1203         }
1204 
1205         // order slots from superclass -> subclass
1206         Collections.reverse(slots);
1207         return slots.toArray(new ClassDataSlot[slots.size()]);
1208     }
1209 
1210     /**
1211      * Returns aggregate size (in bytes) of marshalled primitive field values
1212      * for represented class.
1213      */
1214     int getPrimDataSize() {
1215         return primDataSize;
1216     }
1217 
1218     /**
1219      * Returns number of non-primitive serializable fields of represented
1220      * class.
1221      */
1222     int getNumObjFields() {
1223         return numObjFields;
1224     }
1225 
1226     /**
1227      * Fetches the serializable primitive field values of object obj and
1228      * marshals them into byte array buf starting at offset 0.  It is the
1229      * responsibility of the caller to ensure that obj is of the proper type if
1230      * non-null.
1231      */
1232     void getPrimFieldValues(Object obj, byte[] buf) {
1233         fieldRefl.getPrimFieldValues(obj, buf);
1234     }
1235 
1236     /**
1237      * Sets the serializable primitive fields of object obj using values
1238      * unmarshalled from byte array buf starting at offset 0.  It is the
1239      * responsibility of the caller to ensure that obj is of the proper type if
1240      * non-null.
1241      */
1242     void setPrimFieldValues(Object obj, byte[] buf) {
1243         fieldRefl.setPrimFieldValues(obj, buf);
1244     }
1245 
1246     /**
1247      * Fetches the serializable object field values of object obj and stores
1248      * them in array vals starting at offset 0.  It is the responsibility of
1249      * the caller to ensure that obj is of the proper type if non-null.
1250      */
1251     void getObjFieldValues(Object obj, Object[] vals) {
1252         fieldRefl.getObjFieldValues(obj, vals);
1253     }
1254 
1255     /**
1256      * Sets the serializable object fields of object obj using values from
1257      * array vals starting at offset 0.  It is the responsibility of the caller
1258      * to ensure that obj is of the proper type if non-null.
1259      */
1260     void setObjFieldValues(Object obj, Object[] vals) {
1261         fieldRefl.setObjFieldValues(obj, vals);
1262     }
1263 
1264     /**
1265      * Calculates and sets serializable field offsets, as well as primitive
1266      * data size and object field count totals.  Throws InvalidClassException
1267      * if fields are illegally ordered.
1268      */
1269     private void computeFieldOffsets() throws InvalidClassException {
1270         primDataSize = 0;
1271         numObjFields = 0;
1272         int firstObjIndex = -1;
1273 
1274         for (int i = 0; i < fields.length; i++) {
1275             ObjectStreamField f = fields[i];
1276             switch (f.getTypeCode()) {
1277                 case 'Z':
1278                 case 'B':
1279                     f.setOffset(primDataSize++);
1280                     break;
1281 
1282                 case 'C':
1283                 case 'S':
1284                     f.setOffset(primDataSize);
1285                     primDataSize += 2;
1286                     break;
1287 
1288                 case 'I':
1289                 case 'F':
1290                     f.setOffset(primDataSize);
1291                     primDataSize += 4;
1292                     break;
1293 
1294                 case 'J':
1295                 case 'D':
1296                     f.setOffset(primDataSize);
1297                     primDataSize += 8;
1298                     break;
1299 
1300                 case '[':
1301                 case 'L':
1302                     f.setOffset(numObjFields++);
1303                     if (firstObjIndex == -1) {
1304                         firstObjIndex = i;
1305                     }
1306                     break;
1307 
1308                 default:
1309                     throw new InternalError();
1310             }
1311         }
1312         if (firstObjIndex != -1 &&
1313             firstObjIndex + numObjFields != fields.length)
1314         {
1315             throw new InvalidClassException(name, "illegal field order");
1316         }
1317     }
1318 
1319     /**
1320      * If given class is the same as the class associated with this class
1321      * descriptor, returns reference to this class descriptor.  Otherwise,
1322      * returns variant of this class descriptor bound to given class.
1323      */
1324     private ObjectStreamClass getVariantFor(Class<?> cl)
1325         throws InvalidClassException
1326     {
1327         if (this.cl == cl) {
1328             return this;
1329         }
1330         ObjectStreamClass desc = new ObjectStreamClass();
1331         if (isProxy) {
1332             desc.initProxy(cl, null, superDesc);
1333         } else {
1334             desc.initNonProxy(this, cl, null, superDesc);
1335         }
1336         return desc;
1337     }
1338 
1339     /**
1340      * Returns public no-arg constructor of given class, or null if none found.
1341      * Access checks are disabled on the returned constructor (if any), since
1342      * the defining class may still be non-public.
1343      */
1344     private static Constructor<?> getExternalizableConstructor(Class<?> cl) {
1345         try {
1346             Constructor<?> cons = cl.getDeclaredConstructor((Class<?>[]) null);
1347             cons.setAccessible(true);
1348             return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ?
1349                 cons : null;
1350         } catch (NoSuchMethodException ex) {
1351             return null;
1352         }
1353     }
1354 
1355     /**
1356      * Returns subclass-accessible no-arg constructor of first non-serializable
1357      * superclass, or null if none found.  Access checks are disabled on the
1358      * returned constructor (if any).
1359      */
1360     private static Constructor<?> getSerializableConstructor(Class<?> cl) {
1361         Class<?> initCl = cl;
1362         while (Serializable.class.isAssignableFrom(initCl)) {
1363             if ((initCl = initCl.getSuperclass()) == null) {
1364                 return null;
1365             }
1366         }
1367         try {
1368             Constructor<?> cons = initCl.getDeclaredConstructor((Class<?>[]) null);
1369             int mods = cons.getModifiers();
1370             if ((mods & Modifier.PRIVATE) != 0 ||
1371                 ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
1372                  !packageEquals(cl, initCl)))
1373             {
1374                 return null;
1375             }
1376             cons = reflFactory.newConstructorForSerialization(cl, cons);
1377             cons.setAccessible(true);
1378             return cons;
1379         } catch (NoSuchMethodException ex) {
1380             return null;
1381         }
1382     }
1383 
1384     /**
1385      * Returns non-static, non-abstract method with given signature provided it
1386      * is defined by or accessible (via inheritance) by the given class, or
1387      * null if no match found.  Access checks are disabled on the returned
1388      * method (if any).
1389      */
1390     private static Method getInheritableMethod(Class<?> cl, String name,
1391                                                Class<?>[] argTypes,
1392                                                Class<?> returnType)
1393     {
1394         Method meth = null;
1395         Class<?> defCl = cl;
1396         while (defCl != null) {
1397             try {
1398                 meth = defCl.getDeclaredMethod(name, argTypes);
1399                 break;
1400             } catch (NoSuchMethodException ex) {
1401                 defCl = defCl.getSuperclass();
1402             }
1403         }
1404 
1405         if ((meth == null) || (meth.getReturnType() != returnType)) {
1406             return null;
1407         }
1408         meth.setAccessible(true);
1409         int mods = meth.getModifiers();
1410         if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
1411             return null;
1412         } else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
1413             return meth;
1414         } else if ((mods & Modifier.PRIVATE) != 0) {
1415             return (cl == defCl) ? meth : null;
1416         } else {
1417             return packageEquals(cl, defCl) ? meth : null;
1418         }
1419     }
1420 
1421     /**
1422      * Returns non-static private method with given signature defined by given
1423      * class, or null if none found.  Access checks are disabled on the
1424      * returned method (if any).
1425      */
1426     private static Method getPrivateMethod(Class<?> cl, String name,
1427                                            Class<?>[] argTypes,
1428                                            Class<?> returnType)
1429     {
1430         try {
1431             Method meth = cl.getDeclaredMethod(name, argTypes);
1432             meth.setAccessible(true);
1433             int mods = meth.getModifiers();
1434             return ((meth.getReturnType() == returnType) &&
1435                     ((mods & Modifier.STATIC) == 0) &&
1436                     ((mods & Modifier.PRIVATE) != 0)) ? meth : null;
1437         } catch (NoSuchMethodException ex) {
1438             return null;
1439         }
1440     }
1441 
1442     /**
1443      * Returns true if classes are defined in the same runtime package, false
1444      * otherwise.
1445      */
1446     private static boolean packageEquals(Class<?> cl1, Class<?> cl2) {
1447         return (cl1.getClassLoader() == cl2.getClassLoader() &&
1448                 getPackageName(cl1).equals(getPackageName(cl2)));
1449     }
1450 
1451     /**
1452      * Returns package name of given class.
1453      */
1454     private static String getPackageName(Class<?> cl) {
1455         String s = cl.getName();
1456         int i = s.lastIndexOf('[');
1457         if (i >= 0) {
1458             s = s.substring(i + 2);
1459         }
1460         i = s.lastIndexOf('.');
1461         return (i >= 0) ? s.substring(0, i) : "";
1462     }
1463 
1464     /**
1465      * Compares class names for equality, ignoring package names.  Returns true
1466      * if class names equal, false otherwise.
1467      */
1468     private static boolean classNamesEqual(String name1, String name2) {
1469         name1 = name1.substring(name1.lastIndexOf('.') + 1);
1470         name2 = name2.substring(name2.lastIndexOf('.') + 1);
1471         return name1.equals(name2);
1472     }
1473 
1474     /**
1475      * Returns JVM type signature for given class.
1476      */
1477     private static String getClassSignature(Class<?> cl) {
1478         StringBuilder sbuf = new StringBuilder();
1479         while (cl.isArray()) {
1480             sbuf.append('[');
1481             cl = cl.getComponentType();
1482         }
1483         if (cl.isPrimitive()) {
1484             if (cl == Integer.TYPE) {
1485                 sbuf.append('I');
1486             } else if (cl == Byte.TYPE) {
1487                 sbuf.append('B');
1488             } else if (cl == Long.TYPE) {
1489                 sbuf.append('J');
1490             } else if (cl == Float.TYPE) {
1491                 sbuf.append('F');
1492             } else if (cl == Double.TYPE) {
1493                 sbuf.append('D');
1494             } else if (cl == Short.TYPE) {
1495                 sbuf.append('S');
1496             } else if (cl == Character.TYPE) {
1497                 sbuf.append('C');
1498             } else if (cl == Boolean.TYPE) {
1499                 sbuf.append('Z');
1500             } else if (cl == Void.TYPE) {
1501                 sbuf.append('V');
1502             } else {
1503                 throw new InternalError();
1504             }
1505         } else {
1506             sbuf.append('L' + cl.getName().replace('.', '/') + ';');
1507         }
1508         return sbuf.toString();
1509     }
1510 
1511     /**
1512      * Returns JVM type signature for given list of parameters and return type.
1513      */
1514     private static String getMethodSignature(Class<?>[] paramTypes,
1515                                              Class<?> retType)
1516     {
1517         StringBuilder sbuf = new StringBuilder();
1518         sbuf.append('(');
1519         for (int i = 0; i < paramTypes.length; i++) {
1520             sbuf.append(getClassSignature(paramTypes[i]));
1521         }
1522         sbuf.append(')');
1523         sbuf.append(getClassSignature(retType));
1524         return sbuf.toString();
1525     }
1526 
1527     /**
1528      * Convenience method for throwing an exception that is either a
1529      * RuntimeException, Error, or of some unexpected type (in which case it is
1530      * wrapped inside an IOException).
1531      */
1532     private static void throwMiscException(Throwable th) throws IOException {
1533         if (th instanceof RuntimeException) {
1534             throw (RuntimeException) th;
1535         } else if (th instanceof Error) {
1536             throw (Error) th;
1537         } else {
1538             IOException ex = new IOException("unexpected exception type");
1539             ex.initCause(th);
1540             throw ex;
1541         }
1542     }
1543 
1544     /**
1545      * Returns ObjectStreamField array describing the serializable fields of
1546      * the given class.  Serializable fields backed by an actual field of the
1547      * class are represented by ObjectStreamFields with corresponding non-null
1548      * Field objects.  Throws InvalidClassException if the (explicitly
1549      * declared) serializable fields are invalid.
1550      */
1551     private static ObjectStreamField[] getSerialFields(Class<?> cl)
1552         throws InvalidClassException
1553     {
1554         ObjectStreamField[] fields;
1555         if (Serializable.class.isAssignableFrom(cl) &&
1556             !Externalizable.class.isAssignableFrom(cl) &&
1557             !Proxy.isProxyClass(cl) &&
1558             !cl.isInterface())
1559         {
1560             if ((fields = getDeclaredSerialFields(cl)) == null) {
1561                 fields = getDefaultSerialFields(cl);
1562             }
1563             Arrays.sort(fields);
1564         } else {
1565             fields = NO_FIELDS;
1566         }
1567         return fields;
1568     }
1569 
1570     /**
1571      * Returns serializable fields of given class as defined explicitly by a
1572      * "serialPersistentFields" field, or null if no appropriate
1573      * "serialPersistentFields" field is defined.  Serializable fields backed
1574      * by an actual field of the class are represented by ObjectStreamFields
1575      * with corresponding non-null Field objects.  For compatibility with past
1576      * releases, a "serialPersistentFields" field with a null value is
1577      * considered equivalent to not declaring "serialPersistentFields".  Throws
1578      * InvalidClassException if the declared serializable fields are
1579      * invalid--e.g., if multiple fields share the same name.
1580      */
1581     private static ObjectStreamField[] getDeclaredSerialFields(Class<?> cl)
1582         throws InvalidClassException
1583     {
1584         ObjectStreamField[] serialPersistentFields = null;
1585         try {
1586             Field f = cl.getDeclaredField("serialPersistentFields");
1587             int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
1588             if ((f.getModifiers() & mask) == mask) {
1589                 f.setAccessible(true);
1590                 serialPersistentFields = (ObjectStreamField[]) f.get(null);
1591             }
1592         } catch (Exception ex) {
1593         }
1594         if (serialPersistentFields == null) {
1595             return null;
1596         } else if (serialPersistentFields.length == 0) {
1597             return NO_FIELDS;
1598         }
1599 
1600         ObjectStreamField[] boundFields =
1601             new ObjectStreamField[serialPersistentFields.length];
1602         Set<String> fieldNames = new HashSet<>(serialPersistentFields.length);
1603 
1604         for (int i = 0; i < serialPersistentFields.length; i++) {
1605             ObjectStreamField spf = serialPersistentFields[i];
1606 
1607             String fname = spf.getName();
1608             if (fieldNames.contains(fname)) {
1609                 throw new InvalidClassException(
1610                     "multiple serializable fields named " + fname);
1611             }
1612             fieldNames.add(fname);
1613 
1614             try {
1615                 Field f = cl.getDeclaredField(fname);
1616                 if ((f.getType() == spf.getType()) &&
1617                     ((f.getModifiers() & Modifier.STATIC) == 0))
1618                 {
1619                     boundFields[i] =
1620                         new ObjectStreamField(f, spf.isUnshared(), true);
1621                 }
1622             } catch (NoSuchFieldException ex) {
1623             }
1624             if (boundFields[i] == null) {
1625                 boundFields[i] = new ObjectStreamField(
1626                     fname, spf.getType(), spf.isUnshared());
1627             }
1628         }
1629         return boundFields;
1630     }
1631 
1632     /**
1633      * Returns array of ObjectStreamFields corresponding to all non-static
1634      * non-transient fields declared by given class.  Each ObjectStreamField
1635      * contains a Field object for the field it represents.  If no default
1636      * serializable fields exist, NO_FIELDS is returned.
1637      */
1638     private static ObjectStreamField[] getDefaultSerialFields(Class<?> cl) {
1639         Field[] clFields = cl.getDeclaredFields();
1640         ArrayList<ObjectStreamField> list = new ArrayList<>();
1641         int mask = Modifier.STATIC | Modifier.TRANSIENT;
1642 
1643         for (int i = 0; i < clFields.length; i++) {
1644             if ((clFields[i].getModifiers() & mask) == 0) {
1645                 list.add(new ObjectStreamField(clFields[i], false, true));
1646             }
1647         }
1648         int size = list.size();
1649         return (size == 0) ? NO_FIELDS :
1650             list.toArray(new ObjectStreamField[size]);
1651     }
1652 
1653     /**
1654      * Returns explicit serial version UID value declared by given class, or
1655      * null if none.
1656      */
1657     private static Long getDeclaredSUID(Class<?> cl) {
1658         try {
1659             Field f = cl.getDeclaredField("serialVersionUID");
1660             int mask = Modifier.STATIC | Modifier.FINAL;
1661             if ((f.getModifiers() & mask) == mask) {
1662                 f.setAccessible(true);
1663                 return Long.valueOf(f.getLong(null));
1664             }
1665         } catch (Exception ex) {
1666         }
1667         return null;
1668     }
1669 
1670     /**
1671      * Computes the default serial version UID value for the given class.
1672      */
1673     private static long computeDefaultSUID(Class<?> cl) {
1674         if (!Serializable.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl))
1675         {
1676             return 0L;
1677         }
1678 
1679         try {
1680             ByteArrayOutputStream bout = new ByteArrayOutputStream();
1681             DataOutputStream dout = new DataOutputStream(bout);
1682 
1683             dout.writeUTF(cl.getName());
1684 
1685             int classMods = cl.getModifiers() &
1686                 (Modifier.PUBLIC | Modifier.FINAL |
1687                  Modifier.INTERFACE | Modifier.ABSTRACT);
1688 
1689             /*
1690              * compensate for javac bug in which ABSTRACT bit was set for an
1691              * interface only if the interface declared methods
1692              */
1693             Method[] methods = cl.getDeclaredMethods();
1694             if ((classMods & Modifier.INTERFACE) != 0) {
1695                 classMods = (methods.length > 0) ?
1696                     (classMods | Modifier.ABSTRACT) :
1697                     (classMods & ~Modifier.ABSTRACT);
1698             }
1699             dout.writeInt(classMods);
1700 
1701             if (!cl.isArray()) {
1702                 /*
1703                  * compensate for change in 1.2FCS in which
1704                  * Class.getInterfaces() was modified to return Cloneable and
1705                  * Serializable for array classes.
1706                  */
1707                 Class<?>[] interfaces = cl.getInterfaces();
1708                 String[] ifaceNames = new String[interfaces.length];
1709                 for (int i = 0; i < interfaces.length; i++) {
1710                     ifaceNames[i] = interfaces[i].getName();
1711                 }
1712                 Arrays.sort(ifaceNames);
1713                 for (int i = 0; i < ifaceNames.length; i++) {
1714                     dout.writeUTF(ifaceNames[i]);
1715                 }
1716             }
1717 
1718             Field[] fields = cl.getDeclaredFields();
1719             MemberSignature[] fieldSigs = new MemberSignature[fields.length];
1720             for (int i = 0; i < fields.length; i++) {
1721                 fieldSigs[i] = new MemberSignature(fields[i]);
1722             }
1723             Arrays.sort(fieldSigs, new Comparator<MemberSignature>() {
1724                 public int compare(MemberSignature ms1, MemberSignature ms2) {
1725                     return ms1.name.compareTo(ms2.name);
1726                 }
1727             });
1728             for (int i = 0; i < fieldSigs.length; i++) {
1729                 MemberSignature sig = fieldSigs[i];
1730                 int mods = sig.member.getModifiers() &
1731                     (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
1732                      Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE |
1733                      Modifier.TRANSIENT);
1734                 if (((mods & Modifier.PRIVATE) == 0) ||
1735                     ((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0))
1736                 {
1737                     dout.writeUTF(sig.name);
1738                     dout.writeInt(mods);
1739                     dout.writeUTF(sig.signature);
1740                 }
1741             }
1742 
1743             if (hasStaticInitializer(cl)) {
1744                 dout.writeUTF("<clinit>");
1745                 dout.writeInt(Modifier.STATIC);
1746                 dout.writeUTF("()V");
1747             }
1748 
1749             Constructor<?>[] cons = cl.getDeclaredConstructors();
1750             MemberSignature[] consSigs = new MemberSignature[cons.length];
1751             for (int i = 0; i < cons.length; i++) {
1752                 consSigs[i] = new MemberSignature(cons[i]);
1753             }
1754             Arrays.sort(consSigs, new Comparator<MemberSignature>() {
1755                 public int compare(MemberSignature ms1, MemberSignature ms2) {
1756                     return ms1.signature.compareTo(ms2.signature);
1757                 }
1758             });
1759             for (int i = 0; i < consSigs.length; i++) {
1760                 MemberSignature sig = consSigs[i];
1761                 int mods = sig.member.getModifiers() &
1762                     (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
1763                      Modifier.STATIC | Modifier.FINAL |
1764                      Modifier.SYNCHRONIZED | Modifier.NATIVE |
1765                      Modifier.ABSTRACT | Modifier.STRICT);
1766                 if ((mods & Modifier.PRIVATE) == 0) {
1767                     dout.writeUTF("<init>");
1768                     dout.writeInt(mods);
1769                     dout.writeUTF(sig.signature.replace('/', '.'));
1770                 }
1771             }
1772 
1773             MemberSignature[] methSigs = new MemberSignature[methods.length];
1774             for (int i = 0; i < methods.length; i++) {
1775                 methSigs[i] = new MemberSignature(methods[i]);
1776             }
1777             Arrays.sort(methSigs, new Comparator<MemberSignature>() {
1778                 public int compare(MemberSignature ms1, MemberSignature ms2) {
1779                     int comp = ms1.name.compareTo(ms2.name);
1780                     if (comp == 0) {
1781                         comp = ms1.signature.compareTo(ms2.signature);
1782                     }
1783                     return comp;
1784                 }
1785             });
1786             for (int i = 0; i < methSigs.length; i++) {
1787                 MemberSignature sig = methSigs[i];
1788                 int mods = sig.member.getModifiers() &
1789                     (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
1790                      Modifier.STATIC | Modifier.FINAL |
1791                      Modifier.SYNCHRONIZED | Modifier.NATIVE |
1792                      Modifier.ABSTRACT | Modifier.STRICT);
1793                 if ((mods & Modifier.PRIVATE) == 0) {
1794                     dout.writeUTF(sig.name);
1795                     dout.writeInt(mods);
1796                     dout.writeUTF(sig.signature.replace('/', '.'));
1797                 }
1798             }
1799 
1800             dout.flush();
1801 
1802             MessageDigest md = MessageDigest.getInstance("SHA");
1803             byte[] hashBytes = md.digest(bout.toByteArray());
1804             long hash = 0;
1805             for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
1806                 hash = (hash << 8) | (hashBytes[i] & 0xFF);
1807             }
1808             return hash;
1809         } catch (IOException ex) {
1810             throw new InternalError(ex);
1811         } catch (NoSuchAlgorithmException ex) {
1812             throw new SecurityException(ex.getMessage());
1813         }
1814     }
1815 
1816     /**
1817      * Returns true if the given class defines a static initializer method,
1818      * false otherwise.
1819      */
1820     private native static boolean hasStaticInitializer(Class<?> cl);
1821 
1822     /**
1823      * Class for computing and caching field/constructor/method signatures
1824      * during serialVersionUID calculation.
1825      */
1826     private static class MemberSignature {
1827 
1828         public final Member member;
1829         public final String name;
1830         public final String signature;
1831 
1832         public MemberSignature(Field field) {
1833             member = field;
1834             name = field.getName();
1835             signature = getClassSignature(field.getType());
1836         }
1837 
1838         public MemberSignature(Constructor<?> cons) {
1839             member = cons;
1840             name = cons.getName();
1841             signature = getMethodSignature(
1842                 cons.getParameterTypes(), Void.TYPE);
1843         }
1844 
1845         public MemberSignature(Method meth) {
1846             member = meth;
1847             name = meth.getName();
1848             signature = getMethodSignature(
1849                 meth.getParameterTypes(), meth.getReturnType());
1850         }
1851     }
1852 
1853     /**
1854      * Class for setting and retrieving serializable field values in batch.
1855      */
1856     // REMIND: dynamically generate these?
1857     private static class FieldReflector {
1858 
1859         /** handle for performing unsafe operations */
1860         private static final Unsafe unsafe = Unsafe.getUnsafe();
1861 
1862         /** fields to operate on */
1863         private final ObjectStreamField[] fields;
1864         /** number of primitive fields */
1865         private final int numPrimFields;
1866         /** unsafe field keys for reading fields - may contain dupes */
1867         private final long[] readKeys;
1868         /** unsafe fields keys for writing fields - no dupes */
1869         private final long[] writeKeys;
1870         /** field data offsets */
1871         private final int[] offsets;
1872         /** field type codes */
1873         private final char[] typeCodes;
1874         /** field types */
1875         private final Class<?>[] types;
1876 
1877         /**
1878          * Constructs FieldReflector capable of setting/getting values from the
1879          * subset of fields whose ObjectStreamFields contain non-null
1880          * reflective Field objects.  ObjectStreamFields with null Fields are
1881          * treated as filler, for which get operations return default values
1882          * and set operations discard given values.
1883          */
1884         FieldReflector(ObjectStreamField[] fields) {
1885             this.fields = fields;
1886             int nfields = fields.length;
1887             readKeys = new long[nfields];
1888             writeKeys = new long[nfields];
1889             offsets = new int[nfields];
1890             typeCodes = new char[nfields];
1891             ArrayList<Class<?>> typeList = new ArrayList<>();
1892             Set<Long> usedKeys = new HashSet<>();
1893 
1894 
1895             for (int i = 0; i < nfields; i++) {
1896                 ObjectStreamField f = fields[i];
1897                 Field rf = f.getField();
1898                 long key = (rf != null) ?
1899                     unsafe.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET;
1900                 readKeys[i] = key;
1901                 writeKeys[i] = usedKeys.add(key) ?
1902                     key : Unsafe.INVALID_FIELD_OFFSET;
1903                 offsets[i] = f.getOffset();
1904                 typeCodes[i] = f.getTypeCode();
1905                 if (!f.isPrimitive()) {
1906                     typeList.add((rf != null) ? rf.getType() : null);
1907                 }
1908             }
1909 
1910             types = typeList.toArray(new Class<?>[typeList.size()]);
1911             numPrimFields = nfields - types.length;
1912         }
1913 
1914         /**
1915          * Returns list of ObjectStreamFields representing fields operated on
1916          * by this reflector.  The shared/unshared values and Field objects
1917          * contained by ObjectStreamFields in the list reflect their bindings
1918          * to locally defined serializable fields.
1919          */
1920         ObjectStreamField[] getFields() {
1921             return fields;
1922         }
1923 
1924         /**
1925          * Fetches the serializable primitive field values of object obj and
1926          * marshals them into byte array buf starting at offset 0.  The caller
1927          * is responsible for ensuring that obj is of the proper type.
1928          */
1929         void getPrimFieldValues(Object obj, byte[] buf) {
1930             if (obj == null) {
1931                 throw new NullPointerException();
1932             }
1933             /* assuming checkDefaultSerialize() has been called on the class
1934              * descriptor this FieldReflector was obtained from, no field keys
1935              * in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
1936              */
1937             for (int i = 0; i < numPrimFields; i++) {
1938                 long key = readKeys[i];
1939                 int off = offsets[i];
1940                 switch (typeCodes[i]) {
1941                     case 'Z':
1942                         Bits.putBoolean(buf, off, unsafe.getBoolean(obj, key));
1943                         break;
1944 
1945                     case 'B':
1946                         buf[off] = unsafe.getByte(obj, key);
1947                         break;
1948 
1949                     case 'C':
1950                         Bits.putChar(buf, off, unsafe.getChar(obj, key));
1951                         break;
1952 
1953                     case 'S':
1954                         Bits.putShort(buf, off, unsafe.getShort(obj, key));
1955                         break;
1956 
1957                     case 'I':
1958                         Bits.putInt(buf, off, unsafe.getInt(obj, key));
1959                         break;
1960 
1961                     case 'F':
1962                         Bits.putFloat(buf, off, unsafe.getFloat(obj, key));
1963                         break;
1964 
1965                     case 'J':
1966                         Bits.putLong(buf, off, unsafe.getLong(obj, key));
1967                         break;
1968 
1969                     case 'D':
1970                         Bits.putDouble(buf, off, unsafe.getDouble(obj, key));
1971                         break;
1972 
1973                     default:
1974                         throw new InternalError();
1975                 }
1976             }
1977         }
1978 
1979         /**
1980          * Sets the serializable primitive fields of object obj using values
1981          * unmarshalled from byte array buf starting at offset 0.  The caller
1982          * is responsible for ensuring that obj is of the proper type.
1983          */
1984         void setPrimFieldValues(Object obj, byte[] buf) {
1985             if (obj == null) {
1986                 throw new NullPointerException();
1987             }
1988             for (int i = 0; i < numPrimFields; i++) {
1989                 long key = writeKeys[i];
1990                 if (key == Unsafe.INVALID_FIELD_OFFSET) {
1991                     continue;           // discard value
1992                 }
1993                 int off = offsets[i];
1994                 switch (typeCodes[i]) {
1995                     case 'Z':
1996                         unsafe.putBoolean(obj, key, Bits.getBoolean(buf, off));
1997                         break;
1998 
1999                     case 'B':
2000                         unsafe.putByte(obj, key, buf[off]);
2001                         break;
2002 
2003                     case 'C':
2004                         unsafe.putChar(obj, key, Bits.getChar(buf, off));
2005                         break;
2006 
2007                     case 'S':
2008                         unsafe.putShort(obj, key, Bits.getShort(buf, off));
2009                         break;
2010 
2011                     case 'I':
2012                         unsafe.putInt(obj, key, Bits.getInt(buf, off));
2013                         break;
2014 
2015                     case 'F':
2016                         unsafe.putFloat(obj, key, Bits.getFloat(buf, off));
2017                         break;
2018 
2019                     case 'J':
2020                         unsafe.putLong(obj, key, Bits.getLong(buf, off));
2021                         break;
2022 
2023                     case 'D':
2024                         unsafe.putDouble(obj, key, Bits.getDouble(buf, off));
2025                         break;
2026 
2027                     default:
2028                         throw new InternalError();
2029                 }
2030             }
2031         }
2032 
2033         /**
2034          * Fetches the serializable object field values of object obj and
2035          * stores them in array vals starting at offset 0.  The caller is
2036          * responsible for ensuring that obj is of the proper type.
2037          */
2038         void getObjFieldValues(Object obj, Object[] vals) {
2039             if (obj == null) {
2040                 throw new NullPointerException();
2041             }
2042             /* assuming checkDefaultSerialize() has been called on the class
2043              * descriptor this FieldReflector was obtained from, no field keys
2044              * in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
2045              */
2046             for (int i = numPrimFields; i < fields.length; i++) {
2047                 switch (typeCodes[i]) {
2048                     case 'L':
2049                     case '[':
2050                         vals[offsets[i]] = unsafe.getObject(obj, readKeys[i]);
2051                         break;
2052 
2053                     default:
2054                         throw new InternalError();
2055                 }
2056             }
2057         }
2058 
2059         /**
2060          * Sets the serializable object fields of object obj using values from
2061          * array vals starting at offset 0.  The caller is responsible for
2062          * ensuring that obj is of the proper type; however, attempts to set a
2063          * field with a value of the wrong type will trigger an appropriate
2064          * ClassCastException.
2065          */
2066         void setObjFieldValues(Object obj, Object[] vals) {
2067             if (obj == null) {
2068                 throw new NullPointerException();
2069             }
2070             for (int i = numPrimFields; i < fields.length; i++) {
2071                 long key = writeKeys[i];
2072                 if (key == Unsafe.INVALID_FIELD_OFFSET) {
2073                     continue;           // discard value
2074                 }
2075                 switch (typeCodes[i]) {
2076                     case 'L':
2077                     case '[':
2078                         Object val = vals[offsets[i]];
2079                         if (val != null &&
2080                             !types[i - numPrimFields].isInstance(val))
2081                         {
2082                             Field f = fields[i].getField();
2083                             throw new ClassCastException(
2084                                 "cannot assign instance of " +
2085                                 val.getClass().getName() + " to field " +
2086                                 f.getDeclaringClass().getName() + "." +
2087                                 f.getName() + " of type " +
2088                                 f.getType().getName() + " in instance of " +
2089                                 obj.getClass().getName());
2090                         }
2091                         unsafe.putObject(obj, key, val);
2092                         break;
2093 
2094                     default:
2095                         throw new InternalError();
2096                 }
2097             }
2098         }
2099     }
2100 
2101     /**
2102      * Matches given set of serializable fields with serializable fields
2103      * described by the given local class descriptor, and returns a
2104      * FieldReflector instance capable of setting/getting values from the
2105      * subset of fields that match (non-matching fields are treated as filler,
2106      * for which get operations return default values and set operations
2107      * discard given values).  Throws InvalidClassException if unresolvable
2108      * type conflicts exist between the two sets of fields.
2109      */
2110     private static FieldReflector getReflector(ObjectStreamField[] fields,
2111                                                ObjectStreamClass localDesc)
2112         throws InvalidClassException
2113     {
2114         // class irrelevant if no fields
2115         Class<?> cl = (localDesc != null && fields.length > 0) ?
2116             localDesc.cl : null;
2117         processQueue(Caches.reflectorsQueue, Caches.reflectors);
2118         FieldReflectorKey key = new FieldReflectorKey(cl, fields,
2119                                                       Caches.reflectorsQueue);
2120         Reference<?> ref = Caches.reflectors.get(key);
2121         Object entry = null;
2122         if (ref != null) {
2123             entry = ref.get();
2124         }
2125         EntryFuture future = null;
2126         if (entry == null) {
2127             EntryFuture newEntry = new EntryFuture();
2128             Reference<?> newRef = new SoftReference<>(newEntry);
2129             do {
2130                 if (ref != null) {
2131                     Caches.reflectors.remove(key, ref);
2132                 }
2133                 ref = Caches.reflectors.putIfAbsent(key, newRef);
2134                 if (ref != null) {
2135                     entry = ref.get();
2136                 }
2137             } while (ref != null && entry == null);
2138             if (entry == null) {
2139                 future = newEntry;
2140             }
2141         }
2142 
2143         if (entry instanceof FieldReflector) {  // check common case first
2144             return (FieldReflector) entry;
2145         } else if (entry instanceof EntryFuture) {
2146             entry = ((EntryFuture) entry).get();
2147         } else if (entry == null) {
2148             try {
2149                 entry = new FieldReflector(matchFields(fields, localDesc));
2150             } catch (Throwable th) {
2151                 entry = th;
2152             }
2153             future.set(entry);
2154             Caches.reflectors.put(key, new SoftReference<Object>(entry));
2155         }
2156 
2157         if (entry instanceof FieldReflector) {
2158             return (FieldReflector) entry;
2159         } else if (entry instanceof InvalidClassException) {
2160             throw (InvalidClassException) entry;
2161         } else if (entry instanceof RuntimeException) {
2162             throw (RuntimeException) entry;
2163         } else if (entry instanceof Error) {
2164             throw (Error) entry;
2165         } else {
2166             throw new InternalError("unexpected entry: " + entry);
2167         }
2168     }
2169 
2170     /**
2171      * FieldReflector cache lookup key.  Keys are considered equal if they
2172      * refer to the same class and equivalent field formats.
2173      */
2174     private static class FieldReflectorKey extends WeakReference<Class<?>> {
2175 
2176         private final String sigs;
2177         private final int hash;
2178         private final boolean nullClass;
2179 
2180         FieldReflectorKey(Class<?> cl, ObjectStreamField[] fields,
2181                           ReferenceQueue<Class<?>> queue)
2182         {
2183             super(cl, queue);
2184             nullClass = (cl == null);
2185             StringBuilder sbuf = new StringBuilder();
2186             for (int i = 0; i < fields.length; i++) {
2187                 ObjectStreamField f = fields[i];
2188                 sbuf.append(f.getName()).append(f.getSignature());
2189             }
2190             sigs = sbuf.toString();
2191             hash = System.identityHashCode(cl) + sigs.hashCode();
2192         }
2193 
2194         public int hashCode() {
2195             return hash;
2196         }
2197 
2198         public boolean equals(Object obj) {
2199             if (obj == this) {
2200                 return true;
2201             }
2202 
2203             if (obj instanceof FieldReflectorKey) {
2204                 FieldReflectorKey other = (FieldReflectorKey) obj;
2205                 Class<?> referent;
2206                 return (nullClass ? other.nullClass
2207                                   : ((referent = get()) != null) &&
2208                                     (referent == other.get())) &&
2209                     sigs.equals(other.sigs);
2210             } else {
2211                 return false;
2212             }
2213         }
2214     }
2215 
2216     /**
2217      * Matches given set of serializable fields with serializable fields
2218      * obtained from the given local class descriptor (which contain bindings
2219      * to reflective Field objects).  Returns list of ObjectStreamFields in
2220      * which each ObjectStreamField whose signature matches that of a local
2221      * field contains a Field object for that field; unmatched
2222      * ObjectStreamFields contain null Field objects.  Shared/unshared settings
2223      * of the returned ObjectStreamFields also reflect those of matched local
2224      * ObjectStreamFields.  Throws InvalidClassException if unresolvable type
2225      * conflicts exist between the two sets of fields.
2226      */
2227     private static ObjectStreamField[] matchFields(ObjectStreamField[] fields,
2228                                                    ObjectStreamClass localDesc)
2229         throws InvalidClassException
2230     {
2231         ObjectStreamField[] localFields = (localDesc != null) ?
2232             localDesc.fields : NO_FIELDS;
2233 
2234         /*
2235          * Even if fields == localFields, we cannot simply return localFields
2236          * here.  In previous implementations of serialization,
2237          * ObjectStreamField.getType() returned Object.class if the
2238          * ObjectStreamField represented a non-primitive field and belonged to
2239          * a non-local class descriptor.  To preserve this (questionable)
2240          * behavior, the ObjectStreamField instances returned by matchFields
2241          * cannot report non-primitive types other than Object.class; hence
2242          * localFields cannot be returned directly.
2243          */
2244 
2245         ObjectStreamField[] matches = new ObjectStreamField[fields.length];
2246         for (int i = 0; i < fields.length; i++) {
2247             ObjectStreamField f = fields[i], m = null;
2248             for (int j = 0; j < localFields.length; j++) {
2249                 ObjectStreamField lf = localFields[j];
2250                 if (f.getName().equals(lf.getName())) {
2251                     if ((f.isPrimitive() || lf.isPrimitive()) &&
2252                         f.getTypeCode() != lf.getTypeCode())
2253                     {
2254                         throw new InvalidClassException(localDesc.name,
2255                             "incompatible types for field " + f.getName());
2256                     }
2257                     if (lf.getField() != null) {
2258                         m = new ObjectStreamField(
2259                             lf.getField(), lf.isUnshared(), false);
2260                     } else {
2261                         m = new ObjectStreamField(
2262                             lf.getName(), lf.getSignature(), lf.isUnshared());
2263                     }
2264                 }
2265             }
2266             if (m == null) {
2267                 m = new ObjectStreamField(
2268                     f.getName(), f.getSignature(), false);
2269             }
2270             m.setOffset(f.getOffset());
2271             matches[i] = m;
2272         }
2273         return matches;
2274     }
2275 
2276     /**
2277      * Removes from the specified map any keys that have been enqueued
2278      * on the specified reference queue.
2279      */
2280     static void processQueue(ReferenceQueue<Class<?>> queue,
2281                              ConcurrentMap<? extends
2282                              WeakReference<Class<?>>, ?> map)
2283     {
2284         Reference<? extends Class<?>> ref;
2285         while((ref = queue.poll()) != null) {
2286             map.remove(ref);
2287         }
2288     }
2289 
2290     /**
2291      *  Weak key for Class objects.
2292      *
2293      **/
2294     static class WeakClassKey extends WeakReference<Class<?>> {
2295         /**
2296          * saved value of the referent's identity hash code, to maintain
2297          * a consistent hash code after the referent has been cleared
2298          */
2299         private final int hash;
2300 
2301         /**
2302          * Create a new WeakClassKey to the given object, registered
2303          * with a queue.
2304          */
2305         WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
2306             super(cl, refQueue);
2307             hash = System.identityHashCode(cl);
2308         }
2309 
2310         /**
2311          * Returns the identity hash code of the original referent.
2312          */
2313         public int hashCode() {
2314             return hash;
2315         }
2316 
2317         /**
2318          * Returns true if the given object is this identical
2319          * WeakClassKey instance, or, if this object's referent has not
2320          * been cleared, if the given object is another WeakClassKey
2321          * instance with the identical non-null referent as this one.
2322          */
2323         public boolean equals(Object obj) {
2324             if (obj == this) {
2325                 return true;
2326             }
2327 
2328             if (obj instanceof WeakClassKey) {
2329                 Object referent = get();
2330                 return (referent != null) &&
2331                        (referent == ((WeakClassKey) obj).get());
2332             } else {
2333                 return false;
2334             }
2335         }
2336     }
2337 }