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