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