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


2375 
2376             // retrieve record components
2377             RecordComponent[] recordComponents = desc.forClass().getRecordComponents();
2378 
2379             var types = Arrays.stream(recordComponents).map(RecordComponent::getType).toArray(Class<?>[]::new);
2380             var names = Arrays.stream(recordComponents).map(RecordComponent::getName).toArray(String[]::new);
2381             int count = recordComponents.length;
2382             // retrieve the canonical constructor
2383             // (T1, T2, ..., Tn):TR
2384             mh = desc.getRecordConstructor();
2385 
2386             mh = buildMethodHandle(desc, mh, types, names, count);
2387 
2388             // store it into cache and return the 1st value stored
2389             mh = desc.cachedRecordConstructors.putIfAbsentAndGet(desc.getFields(false), mh);
2390 
2391             return mh;
2392         }
2393 
2394         private static MethodHandle deserializer(ObjectStreamClass desc) {
2395             Executable deserializer = desc.deserializer;
2396             var types = deserializer.getParameterTypes();
2397             String[] names = deserializer.getDeclaredAnnotation(Deserializer.class).value();
2398             int count = types.length;
2399 
2400             MethodHandle mh;
2401             var lookup = MethodHandles.publicLookup();
2402             try {
2403                 mh = deserializer instanceof Method m ? lookup.unreflect(m)
2404                         : lookup.unreflectConstructor((Constructor<?>) deserializer);
2405             } catch (ReflectiveOperationException e) {
2406                 throw new InternalError(e);
2407             }
2408 
2409             return buildMethodHandle(desc, mh, types, names, count);
2410         }
2411 
2412         private static MethodHandle buildMethodHandle(ObjectStreamClass desc,
2413                                                       MethodHandle mh,
2414                                                       Class<?>[] types,
2415                                                       String[] names,
2416                                                       int count) {
2417             // change return type to Object
2418             // (T1, T2, ..., Tn):TR -> (T1, T2, ..., Tn):Object
2419             mh = mh.asType(mh.type().changeReturnType(Object.class));
2420 
2421             // drop last 2 arguments representing primValues and objValues arrays
2422             // (T1, T2, ..., Tn):Object -> (T1, T2, ..., Tn, byte[], Object[]):Object
2423             mh = MethodHandles.dropArguments(mh, mh.type().parameterCount(), byte[].class, Object[].class);
2424 
2425             for (int i = count-1; i >= 0; i--) {
2426                 String name = names[i];
2427                 Class<?> type = types[i];
2428                 // obtain stream field extractor that extracts argument at
2429                 // position i (Ti+1) from primValues and objValues arrays
2430                 // (byte[], Object[]):Ti+1
2431                 MethodHandle combiner = streamFieldExtractor(name, type, desc);
2432                 // fold byte[] privValues and Object[] objValues into argument at position i (Ti+1)
2433                 // (..., Ti, Ti+1, byte[], Object[]):Object -> (..., Ti, byte[], Object[]):Object
2434                 mh = MethodHandles.foldArguments(mh, i, combiner);
2435             }
2436             // what we are left with is a MethodHandle taking just the primValues
2437             // and objValues arrays and returning the constructed record instance
2438             // (byte[], Object[]):Object
2439             return mh;



2440         }
2441 
2442         /** Returns the number of primitive fields for the given descriptor. */
2443         private static int numberPrimValues(ObjectStreamClass desc) {
2444             ObjectStreamField[] fields = desc.getFields();
2445             int primValueCount = 0;
2446             for (int i = 0; i < fields.length; i++) {
2447                 if (fields[i].isPrimitive())
2448                     primValueCount++;
2449                 else
2450                     break;  // can be no more
2451             }
2452             return primValueCount;
2453         }
2454 
2455         /**
2456          * Returns extractor MethodHandle taking the primValues and objValues arrays
2457          * and extracting the argument of canonical constructor with given name and type
2458          * or producing  default value for the given type if the field is absent.
2459          */
2460         private static MethodHandle streamFieldExtractor(String pName,
2461                                                          Class<?> pType,
2462                                                          ObjectStreamClass desc) {
2463             ObjectStreamField[] fields = desc.getFields(false);
2464 
2465             for (int i = 0; i < fields.length; i++) {
2466                 ObjectStreamField f = fields[i];
2467                 String fName = f.getName();
2468                 if (!fName.equals(pName))
2469                     continue;
2470 
2471                 Class<?> fType = f.getField().getType();
2472                 if (!pType.isAssignableFrom(fType))
2473                     throw new InternalError(fName + " unassignable, pType:" + pType + ", fType:" + fType);
2474 
2475                 if (f.isPrimitive()) {
2476                     // (byte[], int):fType
2477                     MethodHandle mh = PRIM_VALUE_EXTRACTORS.get(fType);
2478                     if (mh == null) {
2479                         throw new InternalError("Unexpected type: " + fType);
2480                     }
2481                     // bind offset
2482                     // (byte[], int):fType -> (byte[]):fType
2483                     mh = MethodHandles.insertArguments(mh, 1, f.getOffset());
2484                     // drop objValues argument
2485                     // (byte[]):fType -> (byte[], Object[]):fType
2486                     mh = MethodHandles.dropArguments(mh, 1, Object[].class);
2487                     // adapt return type to pType
2488                     // (byte[], Object[]):fType -> (byte[], Object[]):pType
2489                     if (pType != fType) {
2490                         mh = mh.asType(mh.type().changeReturnType(pType));
2491                     }
2492                     return mh;
2493                 } else { // reference
2494                     // (Object[], int):Object
2495                     MethodHandle mh = MethodHandles.arrayElementGetter(Object[].class);
2496                     // bind index
2497                     // (Object[], int):Object -> (Object[]):Object
2498                     mh = MethodHandles.insertArguments(mh, 1, i - numberPrimValues(desc));
2499                     // drop primValues argument
2500                     // (Object[]):Object -> (byte[], Object[]):Object
2501                     mh = MethodHandles.dropArguments(mh, 0, byte[].class);
2502                     // adapt return type to pType
2503                     // (byte[], Object[]):Object -> (byte[], Object[]):pType
2504                     if (pType != Object.class) {
2505                         mh = mh.asType(mh.type().changeReturnType(pType));
2506                     }
2507                     return mh;
2508                 }
2509             }
2510 
2511             // return default value extractor if no field matches pName
2512             return MethodHandles.empty(MethodType.methodType(pType, byte[].class, Object[].class));
2513         }
2514 
2515         private static final Map<Class<?>, MethodHandle> PRIM_VALUE_EXTRACTORS;
2516         static {
2517             var lkp = MethodHandles.lookup();
2518             try {
2519                 PRIM_VALUE_EXTRACTORS = Map.of(
2520                     byte.class, MethodHandles.arrayElementGetter(byte[].class),
2521                     short.class, lkp.findStatic(ByteArray.class, "getShort", MethodType.methodType(short.class, byte[].class, int.class)),
2522                     int.class, lkp.findStatic(ByteArray.class, "getInt", MethodType.methodType(int.class, byte[].class, int.class)),
2523                     long.class, lkp.findStatic(ByteArray.class, "getLong", MethodType.methodType(long.class, byte[].class, int.class)),
2524                     float.class, lkp.findStatic(ByteArray.class, "getFloat", MethodType.methodType(float.class, byte[].class, int.class)),
2525                     double.class, lkp.findStatic(ByteArray.class, "getDouble", MethodType.methodType(double.class, byte[].class, int.class)),
2526                     char.class, lkp.findStatic(ByteArray.class, "getChar", MethodType.methodType(char.class, byte[].class, int.class)),
2527                     boolean.class, lkp.findStatic(ByteArray.class, "getBoolean", MethodType.methodType(boolean.class, byte[].class, int.class))
2528                 );
2529             } catch (NoSuchMethodException | IllegalAccessException e) {
2530                 throw new InternalError("Can't lookup " + ByteArray.class.getName() + ".getXXX", e);
2531             }
2532         }
2533     }
2534 }
--- EOF ---