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