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