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) 1055 throw (InstantiationException) cause; 1056 if (cause instanceof InvocationTargetException) 1057 throw (InvocationTargetException) cause; 1058 if (cause instanceof IllegalAccessException) 1059 throw (IllegalAccessException) cause; 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 (InstantiationError err) { 1068 var ex = new InstantiationException(); 1069 ex.initCause(err); 1070 throw ex; 1071 } 1072 } else if (isValue) { 1073 // Start with a buffered default value. 1074 return FieldReflector.newValueInstance(cl); 1075 } else { 1076 throw new UnsupportedOperationException(); 1077 } 1078 } 1079 1080 /** 1081 * Finish the initialization of a value object. 1082 * @param obj an object (larval if a value object) 1083 * @return the finished object 1084 */ 1085 Object finishValue(Object obj) { 1086 return (isValue) ? FieldReflector.finishValueInstance(obj) : obj; 1087 } 1088 1089 /** 1090 * Invokes the writeObject method of the represented serializable class. 1091 * Throws UnsupportedOperationException if this class descriptor is not 1092 * associated with a class, or if the class is externalizable, 1093 * non-serializable or does not define writeObject. 1094 */ 1095 void invokeWriteObject(Object obj, ObjectOutputStream out) 1096 throws IOException, UnsupportedOperationException 1097 { 1098 requireInitialized(); 1099 if (writeObjectMethod != null) { 1100 try { 1101 writeObjectMethod.invoke(obj, new Object[]{ out }); 1102 } catch (InvocationTargetException ex) { 1103 Throwable th = ex.getCause(); 1104 if (th instanceof IOException) { 1105 throw (IOException) th; 1106 } else { 1107 throwMiscException(th); 1108 } 1109 } catch (IllegalAccessException ex) { 1110 // should not occur, as access checks have been suppressed 1111 throw new InternalError(ex); 1112 } 1113 } else { 1114 throw new UnsupportedOperationException(); 1115 } 1116 } 1117 1118 /** 1119 * Invokes the readObject method of the represented serializable class. 1120 * Throws UnsupportedOperationException if this class descriptor is not 1121 * associated with a class, or if the class is externalizable, 1122 * non-serializable or does not define readObject. 1123 */ 1124 void invokeReadObject(Object obj, ObjectInputStream in) 1125 throws ClassNotFoundException, IOException, 1126 UnsupportedOperationException 1127 { 1128 requireInitialized(); 1129 if (readObjectMethod != null) { 1130 try { 1131 readObjectMethod.invoke(obj, new Object[]{ in }); 1132 } catch (InvocationTargetException ex) { 1133 Throwable th = ex.getCause(); 1134 if (th instanceof ClassNotFoundException) { 1135 throw (ClassNotFoundException) th; 1136 } else if (th instanceof IOException) { 1137 throw (IOException) th; 1138 } else { 1139 throwMiscException(th); 1140 } 1141 } catch (IllegalAccessException ex) { 1142 // should not occur, as access checks have been suppressed 1143 throw new InternalError(ex); 1144 } 1145 } else { 1146 throw new UnsupportedOperationException(); 1147 } 1148 } 1149 1150 /** 1151 * Invokes the readObjectNoData method of the represented serializable 1152 * class. Throws UnsupportedOperationException if this class descriptor is 1153 * not associated with a class, or if the class is externalizable, 1154 * non-serializable or does not define readObjectNoData. 1155 */ 1156 void invokeReadObjectNoData(Object obj) 1157 throws IOException, UnsupportedOperationException 1158 { 1159 requireInitialized(); 1160 if (readObjectNoDataMethod != null) { 1161 try { 1162 readObjectNoDataMethod.invoke(obj, (Object[]) null); 1163 } catch (InvocationTargetException ex) { 1164 Throwable th = ex.getCause(); 1165 if (th instanceof ObjectStreamException) { 1166 throw (ObjectStreamException) th; 1167 } else { 1168 throwMiscException(th); 1169 } 1170 } catch (IllegalAccessException ex) { 1171 // should not occur, as access checks have been suppressed 1172 throw new InternalError(ex); 1173 } 1174 } else { 1175 throw new UnsupportedOperationException(); 1176 } 1177 } 1178 1179 /** 1180 * Invokes the writeReplace method of the represented serializable class and 1181 * returns the result. Throws UnsupportedOperationException if this class 1182 * descriptor is not associated with a class, or if the class is 1183 * non-serializable or does not define writeReplace. 1184 */ 1185 Object invokeWriteReplace(Object obj) 1186 throws IOException, UnsupportedOperationException 1187 { 1188 requireInitialized(); 1189 if (writeReplaceMethod != null) { 1190 try { 1191 return writeReplaceMethod.invoke(obj, (Object[]) null); 1192 } catch (InvocationTargetException ex) { 1193 Throwable th = ex.getCause(); 1194 if (th instanceof ObjectStreamException) { 1195 throw (ObjectStreamException) th; 1196 } else { 1197 throwMiscException(th); 1198 throw new InternalError(th); // never reached 1199 } 1200 } catch (IllegalAccessException ex) { 1201 // should not occur, as access checks have been suppressed 1202 throw new InternalError(ex); 1203 } 1204 } else { 1205 throw new UnsupportedOperationException(); 1206 } 1207 } 1208 1209 /** 1210 * Invokes the readResolve method of the represented serializable class and 1211 * returns the result. Throws UnsupportedOperationException if this class 1212 * descriptor is not associated with a class, or if the class is 1213 * non-serializable or does not define readResolve. 1214 */ 1215 Object invokeReadResolve(Object obj) 1216 throws IOException, UnsupportedOperationException 1217 { 1218 requireInitialized(); 1219 if (readResolveMethod != null) { 1220 try { 1221 return readResolveMethod.invoke(obj, (Object[]) null); 1222 } catch (InvocationTargetException ex) { 1223 Throwable th = ex.getCause(); 1224 if (th instanceof ObjectStreamException) { 1225 throw (ObjectStreamException) th; 1226 } else { 1227 throwMiscException(th); 1228 throw new InternalError(th); // never reached 1229 } 1230 } catch (IllegalAccessException ex) { 1231 // should not occur, as access checks have been suppressed 1232 throw new InternalError(ex); 1233 } 1234 } else { 1235 throw new UnsupportedOperationException(); 1236 } 1237 } 1238 1239 /** 1240 * Class representing the portion of an object's serialized form allotted 1241 * to data described by a given class descriptor. If "hasData" is false, 1242 * the object's serialized form does not contain data associated with the 1243 * class descriptor. 1244 */ 1245 static class ClassDataSlot { 1246 1247 /** class descriptor "occupying" this slot */ 1248 final ObjectStreamClass desc; 1249 /** true if serialized form includes data for this slot's descriptor */ 1250 final boolean hasData; 1251 1252 ClassDataSlot(ObjectStreamClass desc, boolean hasData) { 1253 this.desc = desc; 1254 this.hasData = hasData; 1255 } 1256 } 1257 1258 /** 1259 * Returns array of ClassDataSlot instances representing the data layout 1260 * (including superclass data) for serialized objects described by this 1261 * class descriptor. ClassDataSlots are ordered by inheritance with those 1262 * containing "higher" superclasses appearing first. The final 1263 * ClassDataSlot contains a reference to this descriptor. 1264 */ 1265 ClassDataSlot[] getClassDataLayout() throws InvalidClassException { 1266 // REMIND: synchronize instead of relying on volatile? 1267 if (dataLayout == null) { 1268 dataLayout = getClassDataLayout0(); 1269 } 1270 return dataLayout; 1271 } 1272 1273 private ClassDataSlot[] getClassDataLayout0() 1274 throws InvalidClassException 1275 { 1276 ArrayList<ClassDataSlot> slots = new ArrayList<>(); 1277 Class<?> start = cl, end = cl; 1278 1279 // locate closest non-serializable superclass 1280 while (end != null && Serializable.class.isAssignableFrom(end)) { 1281 end = end.getSuperclass(); 1282 } 1283 1284 HashSet<String> oscNames = new HashSet<>(3); 1285 1286 for (ObjectStreamClass d = this; d != null; d = d.superDesc) { 1287 if (oscNames.contains(d.name)) { 1288 throw new InvalidClassException("Circular reference."); 1289 } else { 1290 oscNames.add(d.name); 1291 } 1292 1293 // search up inheritance hierarchy for class with matching name 1294 String searchName = (d.cl != null) ? d.cl.getName() : d.name; 1295 Class<?> match = null; 1296 for (Class<?> c = start; c != end; c = c.getSuperclass()) { 1297 if (searchName.equals(c.getName())) { 1298 match = c; 1299 break; 1300 } 1301 } 1302 1303 // add "no data" slot for each unmatched class below match 1304 if (match != null) { 1305 for (Class<?> c = start; c != match; c = c.getSuperclass()) { 1306 slots.add(new ClassDataSlot( 1307 ObjectStreamClass.lookup(c, true), false)); 1308 } 1309 start = match.getSuperclass(); 1310 } 1311 1312 // record descriptor/class pairing 1313 slots.add(new ClassDataSlot(d.getVariantFor(match), true)); 1314 } 1315 1316 // add "no data" slot for any leftover unmatched classes 1317 for (Class<?> c = start; c != end; c = c.getSuperclass()) { 1318 slots.add(new ClassDataSlot( 1319 ObjectStreamClass.lookup(c, true), false)); 1320 } 1321 1322 // order slots from superclass -> subclass 1323 Collections.reverse(slots); 1324 return slots.toArray(new ClassDataSlot[slots.size()]); 1325 } 1326 1327 /** 1328 * Returns aggregate size (in bytes) of marshalled primitive field values 1329 * for represented class. 1330 */ 1331 int getPrimDataSize() { 1332 return primDataSize; 1333 } 1334 1335 /** 1336 * Returns number of non-primitive serializable fields of represented 1337 * class. 1338 */ 1339 int getNumObjFields() { 1340 return numObjFields; 1341 } 1342 1343 /** 1344 * Fetches the serializable primitive field values of object obj and 1345 * marshals them into byte array buf starting at offset 0. It is the 1346 * responsibility of the caller to ensure that obj is of the proper type if 1347 * non-null. 1348 */ 1349 void getPrimFieldValues(Object obj, byte[] buf) { 1350 fieldRefl.getPrimFieldValues(obj, buf); 1351 } 1352 1353 /** 1354 * Sets the serializable primitive fields of object obj using values 1355 * unmarshalled from byte array buf starting at offset 0. It is the 1356 * responsibility of the caller to ensure that obj is of the proper type if 1357 * non-null. 1358 */ 1359 void setPrimFieldValues(Object obj, byte[] buf) { 1360 fieldRefl.setPrimFieldValues(obj, buf); 1361 } 1362 1363 /** 1364 * Fetches the serializable object field values of object obj and stores 1365 * them in array vals starting at offset 0. It is the responsibility of 1366 * the caller to ensure that obj is of the proper type if non-null. 1367 */ 1368 void getObjFieldValues(Object obj, Object[] vals) { 1369 fieldRefl.getObjFieldValues(obj, vals); 1370 } 1371 1372 /** 1373 * Checks that the given values, from array vals starting at offset 0, 1374 * are assignable to the given serializable object fields. 1375 * @throws ClassCastException if any value is not assignable 1376 */ 1377 void checkObjFieldValueTypes(Object obj, Object[] vals) { 1378 fieldRefl.checkObjectFieldValueTypes(obj, vals); 1379 } 1380 1381 /** 1382 * Sets the serializable object fields of object obj using values from 1383 * array vals starting at offset 0. It is the responsibility of the caller 1384 * to ensure that obj is of the proper type if non-null. 1385 */ 1386 void setObjFieldValues(Object obj, Object[] vals) { 1387 fieldRefl.setObjFieldValues(obj, vals); 1388 } 1389 1390 /** 1391 * Calculates and sets serializable field offsets, as well as primitive 1392 * data size and object field count totals. Throws InvalidClassException 1393 * if fields are illegally ordered. 1394 */ 1395 private void computeFieldOffsets() throws InvalidClassException { 1396 primDataSize = 0; 1397 numObjFields = 0; 1398 int firstObjIndex = -1; 1399 1400 for (int i = 0; i < fields.length; i++) { 1401 ObjectStreamField f = fields[i]; 1402 switch (f.getTypeCode()) { 1403 case 'Z', 'B' -> f.setOffset(primDataSize++); 1404 case 'C', 'S' -> { 1405 f.setOffset(primDataSize); 1406 primDataSize += 2; 1407 } 1408 case 'I', 'F' -> { 1409 f.setOffset(primDataSize); 1410 primDataSize += 4; 1411 } 1412 case 'J', 'D' -> { 1413 f.setOffset(primDataSize); 1414 primDataSize += 8; 1415 } 1416 case '[', 'L' -> { 1417 f.setOffset(numObjFields++); 1418 if (firstObjIndex == -1) { 1419 firstObjIndex = i; 1420 } 1421 } 1422 default -> throw new InternalError(); 1423 } 1424 } 1425 if (firstObjIndex != -1 && 1426 firstObjIndex + numObjFields != fields.length) 1427 { 1428 throw new InvalidClassException(name, "illegal field order"); 1429 } 1430 } 1431 1432 /** 1433 * If given class is the same as the class associated with this class 1434 * descriptor, returns reference to this class descriptor. Otherwise, 1435 * returns variant of this class descriptor bound to given class. 1436 */ 1437 private ObjectStreamClass getVariantFor(Class<?> cl) 1438 throws InvalidClassException 1439 { 1440 if (this.cl == cl) { 1441 return this; 1442 } 1443 ObjectStreamClass desc = new ObjectStreamClass(); 1444 if (isProxy) { 1445 desc.initProxy(cl, null, superDesc); 1446 } else { 1447 desc.initNonProxy(this, cl, null, superDesc); 1448 } 1449 return desc; 1450 } 1451 1452 /** 1453 * Returns public no-arg constructor of given class, or null if none found. 1454 * Access checks are disabled on the returned constructor (if any), since 1455 * the defining class may still be non-public. 1456 */ 1457 private static Constructor<?> getExternalizableConstructor(Class<?> cl) { 1458 try { 1459 Constructor<?> cons = cl.getDeclaredConstructor((Class<?>[]) null); 1460 cons.setAccessible(true); 1461 return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ? 1462 cons : null; 1463 } catch (NoSuchMethodException | InaccessibleObjectException ex) { 1464 return null; 1465 } 1466 } 1467 1468 /** 1469 * Returns subclass-accessible no-arg constructor of first non-serializable 1470 * superclass, or null if none found. Access checks are disabled on the 1471 * returned constructor (if any). 1472 */ 1473 private static Constructor<?> getSerializableConstructor(Class<?> cl) { 1474 return reflFactory.newConstructorForSerialization(cl); 1475 } 1476 1477 /** 1478 * Returns the canonical constructor for the given record class, or null if 1479 * the not found ( which should never happen for correctly generated record 1480 * classes ). 1481 */ 1482 @SuppressWarnings("removal") 1483 private static MethodHandle canonicalRecordCtr(Class<?> cls) { 1484 assert cls.isRecord() : "Expected record, got: " + cls; 1485 PrivilegedAction<MethodHandle> pa = () -> { 1486 Class<?>[] paramTypes = Arrays.stream(cls.getRecordComponents()) 1487 .map(RecordComponent::getType) 1488 .toArray(Class<?>[]::new); 1489 try { 1490 Constructor<?> ctr = cls.getDeclaredConstructor(paramTypes); 1491 ctr.setAccessible(true); 1492 return MethodHandles.lookup().unreflectConstructor(ctr); 1493 } catch (IllegalAccessException | NoSuchMethodException e) { 1494 return null; 1495 } 1496 }; 1497 return AccessController.doPrivileged(pa); 1498 } 1499 1500 /** 1501 * Returns the canonical constructor, if the local class equivalent of this 1502 * stream class descriptor is a record class, otherwise null. 1503 */ 1504 MethodHandle getRecordConstructor() { 1505 return canonicalCtr; 1506 } 1507 1508 /** 1509 * Returns non-static, non-abstract method with given signature provided it 1510 * is defined by or accessible (via inheritance) by the given class, or 1511 * null if no match found. Access checks are disabled on the returned 1512 * method (if any). 1513 */ 1514 private static Method getInheritableMethod(Class<?> cl, String name, 1515 Class<?>[] argTypes, 1516 Class<?> returnType) 1517 { 1518 Method meth = null; 1519 Class<?> defCl = cl; 1520 while (defCl != null) { 1521 try { 1522 meth = defCl.getDeclaredMethod(name, argTypes); 1523 break; 1524 } catch (NoSuchMethodException ex) { 1525 defCl = defCl.getSuperclass(); 1526 } 1527 } 1528 1529 if ((meth == null) || (meth.getReturnType() != returnType)) { 1530 return null; 1531 } 1532 meth.setAccessible(true); 1533 int mods = meth.getModifiers(); 1534 if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) { 1535 return null; 1536 } else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) { 1537 return meth; 1538 } else if ((mods & Modifier.PRIVATE) != 0) { 1539 return (cl == defCl) ? meth : null; 1540 } else { 1541 return packageEquals(cl, defCl) ? meth : null; 1542 } 1543 } 1544 1545 /** 1546 * Returns non-static private method with given signature defined by given 1547 * class, or null if none found. Access checks are disabled on the 1548 * returned method (if any). 1549 */ 1550 private static Method getPrivateMethod(Class<?> cl, String name, 1551 Class<?>[] argTypes, 1552 Class<?> returnType) 1553 { 1554 try { 1555 Method meth = cl.getDeclaredMethod(name, argTypes); 1556 meth.setAccessible(true); 1557 int mods = meth.getModifiers(); 1558 return ((meth.getReturnType() == returnType) && 1559 ((mods & Modifier.STATIC) == 0) && 1560 ((mods & Modifier.PRIVATE) != 0)) ? meth : null; 1561 } catch (NoSuchMethodException ex) { 1562 return null; 1563 } 1564 } 1565 1566 /** 1567 * Returns true if classes are defined in the same runtime package, false 1568 * otherwise. 1569 */ 1570 private static boolean packageEquals(Class<?> cl1, Class<?> cl2) { 1571 return cl1.getClassLoader() == cl2.getClassLoader() && 1572 cl1.getPackageName() == cl2.getPackageName(); 1573 } 1574 1575 /** 1576 * Compares class names for equality, ignoring package names. Returns true 1577 * if class names equal, false otherwise. 1578 */ 1579 private static boolean classNamesEqual(String name1, String name2) { 1580 int idx1 = name1.lastIndexOf('.') + 1; 1581 int idx2 = name2.lastIndexOf('.') + 1; 1582 int len1 = name1.length() - idx1; 1583 int len2 = name2.length() - idx2; 1584 return len1 == len2 && 1585 name1.regionMatches(idx1, name2, idx2, len1); 1586 } 1587 1588 /** 1589 * Returns JVM type signature for given list of parameters and return type. 1590 */ 1591 private static String getMethodSignature(Class<?>[] paramTypes, 1592 Class<?> retType) 1593 { 1594 StringBuilder sb = new StringBuilder(); 1595 sb.append('('); 1596 for (int i = 0; i < paramTypes.length; i++) { 1597 sb.append(paramTypes[i].descriptorString()); 1598 } 1599 sb.append(')'); 1600 sb.append(retType.descriptorString()); 1601 return sb.toString(); 1602 } 1603 1604 /** 1605 * Convenience method for throwing an exception that is either a 1606 * RuntimeException, Error, or of some unexpected type (in which case it is 1607 * wrapped inside an IOException). 1608 */ 1609 private static void throwMiscException(Throwable th) throws IOException { 1610 if (th instanceof RuntimeException) { 1611 throw (RuntimeException) th; 1612 } else if (th instanceof Error) { 1613 throw (Error) th; 1614 } else { 1615 throw new IOException("unexpected exception type", th); 1616 } 1617 } 1618 1619 /** 1620 * Returns ObjectStreamField array describing the serializable fields of 1621 * the given class. Serializable fields backed by an actual field of the 1622 * class are represented by ObjectStreamFields with corresponding non-null 1623 * Field objects. Throws InvalidClassException if the (explicitly 1624 * declared) serializable fields are invalid. 1625 */ 1626 private static ObjectStreamField[] getSerialFields(Class<?> cl) 1627 throws InvalidClassException 1628 { 1629 if (!Serializable.class.isAssignableFrom(cl)) 1630 return NO_FIELDS; 1631 1632 ObjectStreamField[] fields; 1633 if (cl.isRecord()) { 1634 fields = getDefaultSerialFields(cl); 1635 Arrays.sort(fields); 1636 } else if (!Externalizable.class.isAssignableFrom(cl) && 1637 !Proxy.isProxyClass(cl) && 1638 !cl.isInterface()) { 1639 if ((fields = getDeclaredSerialFields(cl)) == null) { 1640 fields = getDefaultSerialFields(cl); 1641 } 1642 Arrays.sort(fields); 1643 } else { 1644 fields = NO_FIELDS; 1645 } 1646 return fields; 1647 } 1648 1649 /** 1650 * Returns serializable fields of given class as defined explicitly by a 1651 * "serialPersistentFields" field, or null if no appropriate 1652 * "serialPersistentFields" field is defined. Serializable fields backed 1653 * by an actual field of the class are represented by ObjectStreamFields 1654 * with corresponding non-null Field objects. For compatibility with past 1655 * releases, a "serialPersistentFields" field with a null value is 1656 * considered equivalent to not declaring "serialPersistentFields". Throws 1657 * InvalidClassException if the declared serializable fields are 1658 * invalid--e.g., if multiple fields share the same name. 1659 */ 1660 private static ObjectStreamField[] getDeclaredSerialFields(Class<?> cl) 1661 throws InvalidClassException 1662 { 1663 ObjectStreamField[] serialPersistentFields = null; 1664 try { 1665 Field f = cl.getDeclaredField("serialPersistentFields"); 1666 int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL; 1667 if ((f.getModifiers() & mask) == mask) { 1668 f.setAccessible(true); 1669 serialPersistentFields = (ObjectStreamField[]) f.get(null); 1670 } 1671 } catch (Exception ex) { 1672 } 1673 if (serialPersistentFields == null) { 1674 return null; 1675 } else if (serialPersistentFields.length == 0) { 1676 return NO_FIELDS; 1677 } 1678 1679 ObjectStreamField[] boundFields = 1680 new ObjectStreamField[serialPersistentFields.length]; 1681 Set<String> fieldNames = HashSet.newHashSet(serialPersistentFields.length); 1682 1683 for (int i = 0; i < serialPersistentFields.length; i++) { 1684 ObjectStreamField spf = serialPersistentFields[i]; 1685 1686 String fname = spf.getName(); 1687 if (fieldNames.contains(fname)) { 1688 throw new InvalidClassException( 1689 "multiple serializable fields named " + fname); 1690 } 1691 fieldNames.add(fname); 1692 1693 try { 1694 Field f = cl.getDeclaredField(fname); 1695 if ((f.getType() == spf.getType()) && 1696 ((f.getModifiers() & Modifier.STATIC) == 0)) 1697 { 1698 boundFields[i] = 1699 new ObjectStreamField(f, spf.isUnshared(), true); 1700 } 1701 } catch (NoSuchFieldException ex) { 1702 } 1703 if (boundFields[i] == null) { 1704 boundFields[i] = new ObjectStreamField( 1705 fname, spf.getType(), spf.isUnshared()); 1706 } 1707 } 1708 return boundFields; 1709 } 1710 1711 /** 1712 * Returns array of ObjectStreamFields corresponding to all non-static 1713 * non-transient fields declared by given class. Each ObjectStreamField 1714 * contains a Field object for the field it represents. If no default 1715 * serializable fields exist, NO_FIELDS is returned. 1716 */ 1717 private static ObjectStreamField[] getDefaultSerialFields(Class<?> cl) { 1718 Field[] clFields = cl.getDeclaredFields(); 1719 ArrayList<ObjectStreamField> list = new ArrayList<>(); 1720 int mask = Modifier.STATIC | Modifier.TRANSIENT; 1721 1722 for (int i = 0; i < clFields.length; i++) { 1723 if ((clFields[i].getModifiers() & mask) == 0) { 1724 list.add(new ObjectStreamField(clFields[i], false, true)); 1725 } 1726 } 1727 int size = list.size(); 1728 return (size == 0) ? NO_FIELDS : 1729 list.toArray(new ObjectStreamField[size]); 1730 } 1731 1732 /** 1733 * Returns explicit serial version UID value declared by given class, or 1734 * null if none. 1735 */ 1736 private static Long getDeclaredSUID(Class<?> cl) { 1737 try { 1738 Field f = cl.getDeclaredField("serialVersionUID"); 1739 int mask = Modifier.STATIC | Modifier.FINAL; 1740 if ((f.getModifiers() & mask) == mask) { 1741 f.setAccessible(true); 1742 return f.getLong(null); 1743 } 1744 } catch (Exception ex) { 1745 } 1746 return null; 1747 } 1748 1749 /** 1750 * Computes the default serial version UID value for the given class. 1751 */ 1752 private static long computeDefaultSUID(Class<?> cl) { 1753 if (!Serializable.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl)) 1754 { 1755 return 0L; 1756 } 1757 1758 try { 1759 ByteArrayOutputStream bout = new ByteArrayOutputStream(); 1760 DataOutputStream dout = new DataOutputStream(bout); 1761 1762 dout.writeUTF(cl.getName()); 1763 1764 int classMods = cl.getModifiers() & 1765 (Modifier.PUBLIC | Modifier.FINAL | 1766 Modifier.INTERFACE | Modifier.ABSTRACT); 1767 1768 /* 1769 * compensate for javac bug in which ABSTRACT bit was set for an 1770 * interface only if the interface declared methods 1771 */ 1772 Method[] methods = cl.getDeclaredMethods(); 1773 if ((classMods & Modifier.INTERFACE) != 0) { 1774 classMods = (methods.length > 0) ? 1775 (classMods | Modifier.ABSTRACT) : 1776 (classMods & ~Modifier.ABSTRACT); 1777 } 1778 dout.writeInt(classMods); 1779 1780 if (!cl.isArray()) { 1781 /* 1782 * compensate for change in 1.2FCS in which 1783 * Class.getInterfaces() was modified to return Cloneable and 1784 * Serializable for array classes. 1785 */ 1786 Class<?>[] interfaces = cl.getInterfaces(); 1787 String[] ifaceNames = new String[interfaces.length]; 1788 for (int i = 0; i < interfaces.length; i++) { 1789 ifaceNames[i] = interfaces[i].getName(); 1790 } 1791 Arrays.sort(ifaceNames); 1792 for (int i = 0; i < ifaceNames.length; i++) { 1793 dout.writeUTF(ifaceNames[i]); 1794 } 1795 } 1796 1797 Field[] fields = cl.getDeclaredFields(); 1798 MemberSignature[] fieldSigs = new MemberSignature[fields.length]; 1799 for (int i = 0; i < fields.length; i++) { 1800 fieldSigs[i] = new MemberSignature(fields[i]); 1801 } 1802 Arrays.sort(fieldSigs, new Comparator<>() { 1803 public int compare(MemberSignature ms1, MemberSignature ms2) { 1804 return ms1.name.compareTo(ms2.name); 1805 } 1806 }); 1807 for (int i = 0; i < fieldSigs.length; i++) { 1808 MemberSignature sig = fieldSigs[i]; 1809 int mods = sig.member.getModifiers() & 1810 (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | 1811 Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE | 1812 Modifier.TRANSIENT); 1813 if (((mods & Modifier.PRIVATE) == 0) || 1814 ((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0)) 1815 { 1816 dout.writeUTF(sig.name); 1817 dout.writeInt(mods); 1818 dout.writeUTF(sig.signature); 1819 } 1820 } 1821 1822 if (hasStaticInitializer(cl)) { 1823 dout.writeUTF("<clinit>"); 1824 dout.writeInt(Modifier.STATIC); 1825 dout.writeUTF("()V"); 1826 } 1827 1828 Constructor<?>[] cons = cl.getDeclaredConstructors(); 1829 MemberSignature[] consSigs = new MemberSignature[cons.length]; 1830 for (int i = 0; i < cons.length; i++) { 1831 consSigs[i] = new MemberSignature(cons[i]); 1832 } 1833 Arrays.sort(consSigs, new Comparator<>() { 1834 public int compare(MemberSignature ms1, MemberSignature ms2) { 1835 return ms1.signature.compareTo(ms2.signature); 1836 } 1837 }); 1838 for (int i = 0; i < consSigs.length; i++) { 1839 MemberSignature sig = consSigs[i]; 1840 int mods = sig.member.getModifiers() & 1841 (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | 1842 Modifier.STATIC | Modifier.FINAL | 1843 Modifier.SYNCHRONIZED | Modifier.NATIVE | 1844 Modifier.ABSTRACT | Modifier.STRICT); 1845 if ((mods & Modifier.PRIVATE) == 0) { 1846 dout.writeUTF("<init>"); 1847 dout.writeInt(mods); 1848 dout.writeUTF(sig.signature.replace('/', '.')); 1849 } 1850 } 1851 1852 MemberSignature[] methSigs = new MemberSignature[methods.length]; 1853 for (int i = 0; i < methods.length; i++) { 1854 methSigs[i] = new MemberSignature(methods[i]); 1855 } 1856 Arrays.sort(methSigs, new Comparator<>() { 1857 public int compare(MemberSignature ms1, MemberSignature ms2) { 1858 int comp = ms1.name.compareTo(ms2.name); 1859 if (comp == 0) { 1860 comp = ms1.signature.compareTo(ms2.signature); 1861 } 1862 return comp; 1863 } 1864 }); 1865 for (int i = 0; i < methSigs.length; i++) { 1866 MemberSignature sig = methSigs[i]; 1867 int mods = sig.member.getModifiers() & 1868 (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | 1869 Modifier.STATIC | Modifier.FINAL | 1870 Modifier.SYNCHRONIZED | Modifier.NATIVE | 1871 Modifier.ABSTRACT | Modifier.STRICT); 1872 if ((mods & Modifier.PRIVATE) == 0) { 1873 dout.writeUTF(sig.name); 1874 dout.writeInt(mods); 1875 dout.writeUTF(sig.signature.replace('/', '.')); 1876 } 1877 } 1878 1879 dout.flush(); 1880 1881 MessageDigest md = MessageDigest.getInstance("SHA"); 1882 byte[] hashBytes = md.digest(bout.toByteArray()); 1883 long hash = 0; 1884 for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) { 1885 hash = (hash << 8) | (hashBytes[i] & 0xFF); 1886 } 1887 return hash; 1888 } catch (IOException ex) { 1889 throw new InternalError(ex); 1890 } catch (NoSuchAlgorithmException ex) { 1891 throw new SecurityException(ex.getMessage()); 1892 } 1893 } 1894 1895 /** 1896 * Returns true if the given class defines a static initializer method, 1897 * false otherwise. 1898 */ 1899 private static native boolean hasStaticInitializer(Class<?> cl); 1900 1901 /** 1902 * Class for computing and caching field/constructor/method signatures 1903 * during serialVersionUID calculation. 1904 */ 1905 private static final class MemberSignature { 1906 1907 public final Member member; 1908 public final String name; 1909 public final String signature; 1910 1911 public MemberSignature(Field field) { 1912 member = field; 1913 name = field.getName(); 1914 signature = field.getType().descriptorString(); 1915 } 1916 1917 public MemberSignature(Constructor<?> cons) { 1918 member = cons; 1919 name = cons.getName(); 1920 signature = getMethodSignature( 1921 cons.getParameterTypes(), Void.TYPE); 1922 } 1923 1924 public MemberSignature(Method meth) { 1925 member = meth; 1926 name = meth.getName(); 1927 signature = getMethodSignature( 1928 meth.getParameterTypes(), meth.getReturnType()); 1929 } 1930 } 1931 1932 /** 1933 * Class for setting and retrieving serializable field values in batch. 1934 */ 1935 // REMIND: dynamically generate these? 1936 private static final class FieldReflector { 1937 1938 /** handle for performing unsafe operations */ 1939 private static final Unsafe UNSAFE = Unsafe.getUnsafe(); 1940 1941 /** fields to operate on */ 1942 private final ObjectStreamField[] fields; 1943 /** number of primitive fields */ 1944 private final int numPrimFields; 1945 /** unsafe field keys for reading fields - may contain dupes */ 1946 private final long[] readKeys; 1947 /** unsafe fields keys for writing fields - no dupes */ 1948 private final long[] writeKeys; 1949 /** field data offsets */ 1950 private final int[] offsets; 1951 /** field type codes */ 1952 private final char[] typeCodes; 1953 /** field types */ 1954 private final Class<?>[] types; 1955 1956 /** 1957 * Return a new instance of the class using Unsafe.uninitializedDefaultValue 1958 * and buffer it. 1959 * @param clazz The value class 1960 * @return a buffered default value 1961 */ 1962 static Object newValueInstance(Class<?> clazz) throws InstantiationException{ 1963 assert clazz.isValue() : "Should be a value class"; 1964 Object obj = UNSAFE.uninitializedDefaultValue(clazz); 1965 return UNSAFE.makePrivateBuffer(obj); 1966 } 1967 1968 /** 1969 * Finish a value object, clear the larval state and returning the value object. 1970 * @param obj a buffered value object in a larval state 1971 * @return the finished value object 1972 */ 1973 static Object finishValueInstance(Object obj) { 1974 assert (obj.getClass().isValue()) : "Should be a value class"; 1975 return UNSAFE.finishPrivateBuffer(obj); 1976 } 1977 1978 /** 1979 * Constructs FieldReflector capable of setting/getting values from the 1980 * subset of fields whose ObjectStreamFields contain non-null 1981 * reflective Field objects. ObjectStreamFields with null Fields are 1982 * treated as filler, for which get operations return default values 1983 * and set operations discard given values. 1984 */ 1985 FieldReflector(ObjectStreamField[] fields) { 1986 this.fields = fields; 1987 int nfields = fields.length; 1988 readKeys = new long[nfields]; 1989 writeKeys = new long[nfields]; 1990 offsets = new int[nfields]; 1991 typeCodes = new char[nfields]; 1992 ArrayList<Class<?>> typeList = new ArrayList<>(); 1993 Set<Long> usedKeys = new HashSet<>(); 1994 1995 1996 for (int i = 0; i < nfields; i++) { 1997 ObjectStreamField f = fields[i]; 1998 Field rf = f.getField(); 1999 long key = (rf != null) ? 2000 UNSAFE.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET; 2001 readKeys[i] = key; 2002 writeKeys[i] = usedKeys.add(key) ? 2003 key : Unsafe.INVALID_FIELD_OFFSET; 2004 offsets[i] = f.getOffset(); 2005 typeCodes[i] = f.getTypeCode(); 2006 if (!f.isPrimitive()) { 2007 typeList.add((rf != null) ? rf.getType() : null); 2008 } 2009 } 2010 2011 types = typeList.toArray(new Class<?>[typeList.size()]); 2012 numPrimFields = nfields - types.length; 2013 } 2014 2015 /** 2016 * Returns list of ObjectStreamFields representing fields operated on 2017 * by this reflector. The shared/unshared values and Field objects 2018 * contained by ObjectStreamFields in the list reflect their bindings 2019 * to locally defined serializable fields. 2020 */ 2021 ObjectStreamField[] getFields() { 2022 return fields; 2023 } 2024 2025 /** 2026 * Fetches the serializable primitive field values of object obj and 2027 * marshals them into byte array buf starting at offset 0. The caller 2028 * is responsible for ensuring that obj is of the proper type. 2029 */ 2030 void getPrimFieldValues(Object obj, byte[] buf) { 2031 if (obj == null) { 2032 throw new NullPointerException(); 2033 } 2034 /* assuming checkDefaultSerialize() has been called on the class 2035 * descriptor this FieldReflector was obtained from, no field keys 2036 * in array should be equal to Unsafe.INVALID_FIELD_OFFSET. 2037 */ 2038 for (int i = 0; i < numPrimFields; i++) { 2039 long key = readKeys[i]; 2040 int off = offsets[i]; 2041 switch (typeCodes[i]) { 2042 case 'Z' -> ByteArray.setBoolean(buf, off, UNSAFE.getBoolean(obj, key)); 2043 case 'B' -> buf[off] = UNSAFE.getByte(obj, key); 2044 case 'C' -> ByteArray.setChar(buf, off, UNSAFE.getChar(obj, key)); 2045 case 'S' -> ByteArray.setShort(buf, off, UNSAFE.getShort(obj, key)); 2046 case 'I' -> ByteArray.setInt(buf, off, UNSAFE.getInt(obj, key)); 2047 case 'F' -> ByteArray.setFloat(buf, off, UNSAFE.getFloat(obj, key)); 2048 case 'J' -> ByteArray.setLong(buf, off, UNSAFE.getLong(obj, key)); 2049 case 'D' -> ByteArray.setDouble(buf, off, UNSAFE.getDouble(obj, key)); 2050 default -> throw new InternalError(); 2051 } 2052 } 2053 } 2054 2055 /** 2056 * Sets the serializable primitive fields of object obj using values 2057 * unmarshalled from byte array buf starting at offset 0. The caller 2058 * is responsible for ensuring that obj is of the proper type. 2059 */ 2060 void setPrimFieldValues(Object obj, byte[] buf) { 2061 if (obj == null) { 2062 throw new NullPointerException(); 2063 } 2064 for (int i = 0; i < numPrimFields; i++) { 2065 long key = writeKeys[i]; 2066 if (key == Unsafe.INVALID_FIELD_OFFSET) { 2067 continue; // discard value 2068 } 2069 int off = offsets[i]; 2070 switch (typeCodes[i]) { 2071 case 'Z' -> UNSAFE.putBoolean(obj, key, ByteArray.getBoolean(buf, off)); 2072 case 'B' -> UNSAFE.putByte(obj, key, buf[off]); 2073 case 'C' -> UNSAFE.putChar(obj, key, ByteArray.getChar(buf, off)); 2074 case 'S' -> UNSAFE.putShort(obj, key, ByteArray.getShort(buf, off)); 2075 case 'I' -> UNSAFE.putInt(obj, key, ByteArray.getInt(buf, off)); 2076 case 'F' -> UNSAFE.putFloat(obj, key, ByteArray.getFloat(buf, off)); 2077 case 'J' -> UNSAFE.putLong(obj, key, ByteArray.getLong(buf, off)); 2078 case 'D' -> UNSAFE.putDouble(obj, key, ByteArray.getDouble(buf, off)); 2079 default -> throw new InternalError(); 2080 } 2081 } 2082 } 2083 2084 /** 2085 * Fetches the serializable object field values of object obj and 2086 * stores them in array vals starting at offset 0. The caller is 2087 * responsible for ensuring that obj is of the proper type. 2088 */ 2089 void getObjFieldValues(Object obj, Object[] vals) { 2090 if (obj == null) { 2091 throw new NullPointerException(); 2092 } 2093 /* assuming checkDefaultSerialize() has been called on the class 2094 * descriptor this FieldReflector was obtained from, no field keys 2095 * in array should be equal to Unsafe.INVALID_FIELD_OFFSET. 2096 */ 2097 for (int i = numPrimFields; i < fields.length; i++) { 2098 Field f = fields[i].getField(); 2099 vals[offsets[i]] = switch (typeCodes[i]) { 2100 case 'L', '[' -> 2101 UNSAFE.isFlattened(f) 2102 ? UNSAFE.getValue(obj, readKeys[i], f.getType()) 2103 : UNSAFE.getReference(obj, readKeys[i]); 2104 default -> throw new InternalError(); 2105 }; 2106 } 2107 } 2108 2109 /** 2110 * Checks that the given values, from array vals starting at offset 0, 2111 * are assignable to the given serializable object fields. 2112 * @throws ClassCastException if any value is not assignable 2113 */ 2114 void checkObjectFieldValueTypes(Object obj, Object[] vals) { 2115 setObjFieldValues(obj, vals, true); 2116 } 2117 2118 /** 2119 * Sets the serializable object fields of object obj using values from 2120 * array vals starting at offset 0. The caller is responsible for 2121 * ensuring that obj is of the proper type; however, attempts to set a 2122 * field with a value of the wrong type will trigger an appropriate 2123 * ClassCastException. 2124 */ 2125 void setObjFieldValues(Object obj, Object[] vals) { 2126 setObjFieldValues(obj, vals, false); 2127 } 2128 2129 private void setObjFieldValues(Object obj, Object[] vals, boolean dryRun) { 2130 if (obj == null) { 2131 throw new NullPointerException(); 2132 } 2133 for (int i = numPrimFields; i < fields.length; i++) { 2134 long key = writeKeys[i]; 2135 if (key == Unsafe.INVALID_FIELD_OFFSET) { 2136 continue; // discard value 2137 } 2138 switch (typeCodes[i]) { 2139 case 'L', '[' -> { 2140 Field f = fields[i].getField(); 2141 Object val = vals[offsets[i]]; 2142 if (val != null && 2143 !types[i - numPrimFields].isInstance(val)) 2144 { 2145 throw new ClassCastException( 2146 "cannot assign instance of " + 2147 val.getClass().getName() + " to field " + 2148 f.getDeclaringClass().getName() + "." + 2149 f.getName() + " of type " + 2150 f.getType().getName() + " in instance of " + 2151 obj.getClass().getName()); 2152 } 2153 if (!dryRun) { 2154 if (UNSAFE.isFlattened(f)) { 2155 UNSAFE.putValue(obj, key, f.getType(), val); 2156 } else { 2157 UNSAFE.putReference(obj, key, val); 2158 } 2159 } 2160 } 2161 default -> throw new InternalError(); 2162 } 2163 } 2164 } 2165 } 2166 2167 /** 2168 * Matches given set of serializable fields with serializable fields 2169 * described by the given local class descriptor, and returns a 2170 * FieldReflector instance capable of setting/getting values from the 2171 * subset of fields that match (non-matching fields are treated as filler, 2172 * for which get operations return default values and set operations 2173 * discard given values). Throws InvalidClassException if unresolvable 2174 * type conflicts exist between the two sets of fields. 2175 */ 2176 private static FieldReflector getReflector(ObjectStreamField[] fields, 2177 ObjectStreamClass localDesc) 2178 throws InvalidClassException 2179 { 2180 // class irrelevant if no fields 2181 Class<?> cl = (localDesc != null && fields.length > 0) ? 2182 localDesc.cl : Void.class; 2183 2184 var clReflectors = Caches.reflectors.get(cl); 2185 var key = new FieldReflectorKey(fields); 2186 var reflector = clReflectors.get(key); 2187 if (reflector == null) { 2188 reflector = new FieldReflector(matchFields(fields, localDesc)); 2189 var oldReflector = clReflectors.putIfAbsent(key, reflector); 2190 if (oldReflector != null) { 2191 reflector = oldReflector; 2192 } 2193 } 2194 return reflector; 2195 } 2196 2197 /** 2198 * FieldReflector cache lookup key. Keys are considered equal if they 2199 * refer to equivalent field formats. 2200 */ 2201 private static class FieldReflectorKey { 2202 2203 private final String[] sigs; 2204 private final int hash; 2205 2206 FieldReflectorKey(ObjectStreamField[] fields) 2207 { 2208 sigs = new String[2 * fields.length]; 2209 for (int i = 0, j = 0; i < fields.length; i++) { 2210 ObjectStreamField f = fields[i]; 2211 sigs[j++] = f.getName(); 2212 sigs[j++] = f.getSignature(); 2213 } 2214 hash = Arrays.hashCode(sigs); 2215 } 2216 2217 public int hashCode() { 2218 return hash; 2219 } 2220 2221 public boolean equals(Object obj) { 2222 return obj == this || 2223 obj instanceof FieldReflectorKey other && 2224 Arrays.equals(sigs, other.sigs); 2225 } 2226 } 2227 2228 /** 2229 * Matches given set of serializable fields with serializable fields 2230 * obtained from the given local class descriptor (which contain bindings 2231 * to reflective Field objects). Returns list of ObjectStreamFields in 2232 * which each ObjectStreamField whose signature matches that of a local 2233 * field contains a Field object for that field; unmatched 2234 * ObjectStreamFields contain null Field objects. Shared/unshared settings 2235 * of the returned ObjectStreamFields also reflect those of matched local 2236 * ObjectStreamFields. Throws InvalidClassException if unresolvable type 2237 * conflicts exist between the two sets of fields. 2238 */ 2239 private static ObjectStreamField[] matchFields(ObjectStreamField[] fields, 2240 ObjectStreamClass localDesc) 2241 throws InvalidClassException 2242 { 2243 ObjectStreamField[] localFields = (localDesc != null) ? 2244 localDesc.fields : NO_FIELDS; 2245 2246 /* 2247 * Even if fields == localFields, we cannot simply return localFields 2248 * here. In previous implementations of serialization, 2249 * ObjectStreamField.getType() returned Object.class if the 2250 * ObjectStreamField represented a non-primitive field and belonged to 2251 * a non-local class descriptor. To preserve this (questionable) 2252 * behavior, the ObjectStreamField instances returned by matchFields 2253 * cannot report non-primitive types other than Object.class; hence 2254 * localFields cannot be returned directly. 2255 */ 2256 2257 ObjectStreamField[] matches = new ObjectStreamField[fields.length]; 2258 for (int i = 0; i < fields.length; i++) { 2259 ObjectStreamField f = fields[i], m = null; 2260 for (int j = 0; j < localFields.length; j++) { 2261 ObjectStreamField lf = localFields[j]; 2262 if (f.getName().equals(lf.getName())) { 2263 if ((f.isPrimitive() || lf.isPrimitive()) && 2264 f.getTypeCode() != lf.getTypeCode()) 2265 { 2266 throw new InvalidClassException(localDesc.name, 2267 "incompatible types for field " + f.getName()); 2268 } 2269 if (lf.getField() != null) { 2270 m = new ObjectStreamField( 2271 lf.getField(), lf.isUnshared(), false); 2272 } else { 2273 m = new ObjectStreamField( 2274 lf.getName(), lf.getSignature(), lf.isUnshared()); 2275 } 2276 } 2277 } 2278 if (m == null) { 2279 m = new ObjectStreamField( 2280 f.getName(), f.getSignature(), false); 2281 } 2282 m.setOffset(f.getOffset()); 2283 matches[i] = m; 2284 } 2285 return matches; 2286 } 2287 2288 /** 2289 * A LRA cache of record deserialization constructors. 2290 */ 2291 @SuppressWarnings("serial") 2292 private static final class DeserializationConstructorsCache 2293 extends ConcurrentHashMap<DeserializationConstructorsCache.Key, MethodHandle> { 2294 2295 // keep max. 10 cached entries - when the 11th element is inserted the oldest 2296 // is removed and 10 remains - 11 is the biggest map size where internal 2297 // table of 16 elements is sufficient (inserting 12th element would resize it to 32) 2298 private static final int MAX_SIZE = 10; 2299 private Key.Impl first, last; // first and last in FIFO queue 2300 2301 DeserializationConstructorsCache() { 2302 // start small - if there is more than one shape of ObjectStreamClass 2303 // deserialized, there will typically be two (current version and previous version) 2304 super(2); 2305 } 2306 2307 MethodHandle get(ObjectStreamField[] fields) { 2308 return get(new Key.Lookup(fields)); 2309 } 2310 2311 synchronized MethodHandle putIfAbsentAndGet(ObjectStreamField[] fields, MethodHandle mh) { 2312 Key.Impl key = new Key.Impl(fields); 2313 var oldMh = putIfAbsent(key, mh); 2314 if (oldMh != null) return oldMh; 2315 // else we did insert new entry -> link the new key as last 2316 if (last == null) { 2317 last = first = key; 2318 } else { 2319 last = (last.next = key); 2320 } 2321 // may need to remove first 2322 if (size() > MAX_SIZE) { 2323 assert first != null; 2324 remove(first); 2325 first = first.next; 2326 if (first == null) { 2327 last = null; 2328 } 2329 } 2330 return mh; 2331 } 2332 2333 // a key composed of ObjectStreamField[] names and types 2334 abstract static class Key { 2335 abstract int length(); 2336 abstract String fieldName(int i); 2337 abstract Class<?> fieldType(int i); 2338 2339 @Override 2340 public final int hashCode() { 2341 int n = length(); 2342 int h = 0; 2343 for (int i = 0; i < n; i++) h = h * 31 + fieldType(i).hashCode(); 2344 for (int i = 0; i < n; i++) h = h * 31 + fieldName(i).hashCode(); 2345 return h; 2346 } 2347 2348 @Override 2349 public final boolean equals(Object obj) { 2350 if (!(obj instanceof Key other)) return false; 2351 int n = length(); 2352 if (n != other.length()) return false; 2353 for (int i = 0; i < n; i++) if (fieldType(i) != other.fieldType(i)) return false; 2354 for (int i = 0; i < n; i++) if (!fieldName(i).equals(other.fieldName(i))) return false; 2355 return true; 2356 } 2357 2358 // lookup key - just wraps ObjectStreamField[] 2359 static final class Lookup extends Key { 2360 final ObjectStreamField[] fields; 2361 2362 Lookup(ObjectStreamField[] fields) { this.fields = fields; } 2363 2364 @Override 2365 int length() { return fields.length; } 2366 2367 @Override 2368 String fieldName(int i) { return fields[i].getName(); } 2369 2370 @Override 2371 Class<?> fieldType(int i) { return fields[i].getType(); } 2372 } 2373 2374 // real key - copies field names and types and forms FIFO queue in cache 2375 static final class Impl extends Key { 2376 Impl next; 2377 final String[] fieldNames; 2378 final Class<?>[] fieldTypes; 2379 2380 Impl(ObjectStreamField[] fields) { 2381 this.fieldNames = new String[fields.length]; 2382 this.fieldTypes = new Class<?>[fields.length]; 2383 for (int i = 0; i < fields.length; i++) { 2384 fieldNames[i] = fields[i].getName(); 2385 fieldTypes[i] = fields[i].getType(); 2386 } 2387 } 2388 2389 @Override 2390 int length() { return fieldNames.length; } 2391 2392 @Override 2393 String fieldName(int i) { return fieldNames[i]; } 2394 2395 @Override 2396 Class<?> fieldType(int i) { return fieldTypes[i]; } 2397 } 2398 } 2399 } 2400 2401 /** Record specific support for retrieving and binding stream field values. */ 2402 static final class RecordSupport { 2403 /** 2404 * Returns canonical record constructor adapted to take two arguments: 2405 * {@code (byte[] primValues, Object[] objValues)} 2406 * and return 2407 * {@code Object} 2408 */ 2409 @SuppressWarnings("removal") 2410 static MethodHandle deserializationCtr(ObjectStreamClass desc) { 2411 // check the cached value 1st 2412 MethodHandle mh = desc.deserializationCtr; 2413 if (mh != null) return mh; 2414 mh = desc.deserializationCtrs.get(desc.getFields(false)); 2415 if (mh != null) return desc.deserializationCtr = mh; 2416 2417 // retrieve record components 2418 RecordComponent[] recordComponents; 2419 try { 2420 Class<?> cls = desc.forClass(); 2421 PrivilegedExceptionAction<RecordComponent[]> pa = cls::getRecordComponents; 2422 recordComponents = AccessController.doPrivileged(pa); 2423 } catch (PrivilegedActionException e) { 2424 throw new InternalError(e.getCause()); 2425 } 2426 2427 // retrieve the canonical constructor 2428 // (T1, T2, ..., Tn):TR 2429 mh = desc.getRecordConstructor(); 2430 2431 // change return type to Object 2432 // (T1, T2, ..., Tn):TR -> (T1, T2, ..., Tn):Object 2433 mh = mh.asType(mh.type().changeReturnType(Object.class)); 2434 2435 // drop last 2 arguments representing primValues and objValues arrays 2436 // (T1, T2, ..., Tn):Object -> (T1, T2, ..., Tn, byte[], Object[]):Object 2437 mh = MethodHandles.dropArguments(mh, mh.type().parameterCount(), byte[].class, Object[].class); 2438 2439 for (int i = recordComponents.length-1; i >= 0; i--) { 2440 String name = recordComponents[i].getName(); 2441 Class<?> type = recordComponents[i].getType(); 2442 // obtain stream field extractor that extracts argument at 2443 // position i (Ti+1) from primValues and objValues arrays 2444 // (byte[], Object[]):Ti+1 2445 MethodHandle combiner = streamFieldExtractor(name, type, desc); 2446 // fold byte[] privValues and Object[] objValues into argument at position i (Ti+1) 2447 // (..., Ti, Ti+1, byte[], Object[]):Object -> (..., Ti, byte[], Object[]):Object 2448 mh = MethodHandles.foldArguments(mh, i, combiner); 2449 } 2450 // what we are left with is a MethodHandle taking just the primValues 2451 // and objValues arrays and returning the constructed record instance 2452 // (byte[], Object[]):Object 2453 2454 // store it into cache and return the 1st value stored 2455 return desc.deserializationCtr = 2456 desc.deserializationCtrs.putIfAbsentAndGet(desc.getFields(false), mh); 2457 } 2458 2459 /** Returns the number of primitive fields for the given descriptor. */ 2460 private static int numberPrimValues(ObjectStreamClass desc) { 2461 ObjectStreamField[] fields = desc.getFields(); 2462 int primValueCount = 0; 2463 for (int i = 0; i < fields.length; i++) { 2464 if (fields[i].isPrimitive()) 2465 primValueCount++; 2466 else 2467 break; // can be no more 2468 } 2469 return primValueCount; 2470 } 2471 2472 /** 2473 * Returns extractor MethodHandle taking the primValues and objValues arrays 2474 * and extracting the argument of canonical constructor with given name and type 2475 * or producing default value for the given type if the field is absent. 2476 */ 2477 private static MethodHandle streamFieldExtractor(String pName, 2478 Class<?> pType, 2479 ObjectStreamClass desc) { 2480 ObjectStreamField[] fields = desc.getFields(false); 2481 2482 for (int i = 0; i < fields.length; i++) { 2483 ObjectStreamField f = fields[i]; 2484 String fName = f.getName(); 2485 if (!fName.equals(pName)) 2486 continue; 2487 2488 Class<?> fType = f.getField().getType(); 2489 if (!pType.isAssignableFrom(fType)) 2490 throw new InternalError(fName + " unassignable, pType:" + pType + ", fType:" + fType); 2491 2492 if (f.isPrimitive()) { 2493 // (byte[], int):fType 2494 MethodHandle mh = PRIM_VALUE_EXTRACTORS.get(fType); 2495 if (mh == null) { 2496 throw new InternalError("Unexpected type: " + fType); 2497 } 2498 // bind offset 2499 // (byte[], int):fType -> (byte[]):fType 2500 mh = MethodHandles.insertArguments(mh, 1, f.getOffset()); 2501 // drop objValues argument 2502 // (byte[]):fType -> (byte[], Object[]):fType 2503 mh = MethodHandles.dropArguments(mh, 1, Object[].class); 2504 // adapt return type to pType 2505 // (byte[], Object[]):fType -> (byte[], Object[]):pType 2506 if (pType != fType) { 2507 mh = mh.asType(mh.type().changeReturnType(pType)); 2508 } 2509 return mh; 2510 } else { // reference 2511 // (Object[], int):Object 2512 MethodHandle mh = MethodHandles.arrayElementGetter(Object[].class); 2513 // bind index 2514 // (Object[], int):Object -> (Object[]):Object 2515 mh = MethodHandles.insertArguments(mh, 1, i - numberPrimValues(desc)); 2516 // drop primValues argument 2517 // (Object[]):Object -> (byte[], Object[]):Object 2518 mh = MethodHandles.dropArguments(mh, 0, byte[].class); 2519 // adapt return type to pType 2520 // (byte[], Object[]):Object -> (byte[], Object[]):pType 2521 if (pType != Object.class) { 2522 mh = mh.asType(mh.type().changeReturnType(pType)); 2523 } 2524 return mh; 2525 } 2526 } 2527 2528 // return default value extractor if no field matches pName 2529 return MethodHandles.empty(MethodType.methodType(pType, byte[].class, Object[].class)); 2530 } 2531 2532 private static final Map<Class<?>, MethodHandle> PRIM_VALUE_EXTRACTORS; 2533 static { 2534 var lkp = MethodHandles.lookup(); 2535 try { 2536 PRIM_VALUE_EXTRACTORS = Map.of( 2537 byte.class, MethodHandles.arrayElementGetter(byte[].class), 2538 short.class, lkp.findStatic(ByteArray.class, "getShort", MethodType.methodType(short.class, byte[].class, int.class)), 2539 int.class, lkp.findStatic(ByteArray.class, "getInt", MethodType.methodType(int.class, byte[].class, int.class)), 2540 long.class, lkp.findStatic(ByteArray.class, "getLong", MethodType.methodType(long.class, byte[].class, int.class)), 2541 float.class, lkp.findStatic(ByteArray.class, "getFloat", MethodType.methodType(float.class, byte[].class, int.class)), 2542 double.class, lkp.findStatic(ByteArray.class, "getDouble", MethodType.methodType(double.class, byte[].class, int.class)), 2543 char.class, lkp.findStatic(ByteArray.class, "getChar", MethodType.methodType(char.class, byte[].class, int.class)), 2544 boolean.class, lkp.findStatic(ByteArray.class, "getBoolean", MethodType.methodType(boolean.class, byte[].class, int.class)) 2545 ); 2546 } catch (NoSuchMethodException | IllegalAccessException e) { 2547 throw new InternalError("Can't lookup " + ByteArray.class.getName() + ".getXXX", e); 2548 } 2549 } 2550 } 2551 }