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