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