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