rev 12972 : 8140606: Update library code to use internal Unsafe
Reviewed-by: duke

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