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