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