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