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