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