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