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