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