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