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