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