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