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