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