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