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