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