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     void checkObjFieldValueTypes(Object obj, Object[] vals) {
1256         fieldRefl.checkObjectFieldValueTypes(obj, vals);
1257     }
1258 
1259     /**
1260      * Sets the serializable object fields of object obj using values from
1261      * array vals starting at offset 0.  It is the responsibility of the caller
1262      * to ensure that obj is of the proper type if non-null.
1263      */
1264     void setObjFieldValues(Object obj, Object[] vals) {
1265         fieldRefl.setObjFieldValues(obj, vals);
1266     }
1267 
1268     /**
1269      * Calculates and sets serializable field offsets, as well as primitive
1270      * data size and object field count totals.  Throws InvalidClassException
1271      * if fields are illegally ordered.
1272      */
1273     private void computeFieldOffsets() throws InvalidClassException {
1274         primDataSize = 0;
1275         numObjFields = 0;
1276         int firstObjIndex = -1;
1277 
1278         for (int i = 0; i < fields.length; i++) {
1279             ObjectStreamField f = fields[i];
1280             switch (f.getTypeCode()) {
1281                 case 'Z':
1282                 case 'B':
1283                     f.setOffset(primDataSize++);
1284                     break;
1285 
1286                 case 'C':
1287                 case 'S':
1288                     f.setOffset(primDataSize);
1289                     primDataSize += 2;
1290                     break;
1291 
1292                 case 'I':
1293                 case 'F':
1294                     f.setOffset(primDataSize);
1295                     primDataSize += 4;
1296                     break;
1297 
1298                 case 'J':
1299                 case 'D':
1300                     f.setOffset(primDataSize);
1301                     primDataSize += 8;
1302                     break;
1303 
1304                 case '[':
1305                 case 'L':
1306                     f.setOffset(numObjFields++);
1307                     if (firstObjIndex == -1) {
1308                         firstObjIndex = i;
1309                     }
1310                     break;
1311 
1312                 default:
1313                     throw new InternalError();
1314             }
1315         }
1316         if (firstObjIndex != -1 &&
1317             firstObjIndex + numObjFields != fields.length)
1318         {
1319             throw new InvalidClassException(name, "illegal field order");
1320         }
1321     }
1322 
1323     /**
1324      * If given class is the same as the class associated with this class
1325      * descriptor, returns reference to this class descriptor.  Otherwise,
1326      * returns variant of this class descriptor bound to given class.
1327      */
1328     private ObjectStreamClass getVariantFor(Class<?> cl)
1329         throws InvalidClassException
1330     {
1331         if (this.cl == cl) {
1332             return this;
1333         }
1334         ObjectStreamClass desc = new ObjectStreamClass();
1335         if (isProxy) {
1336             desc.initProxy(cl, null, superDesc);
1337         } else {
1338             desc.initNonProxy(this, cl, null, superDesc);
1339         }
1340         return desc;
1341     }
1342 
1343     /**
1344      * Returns public no-arg constructor of given class, or null if none found.
1345      * Access checks are disabled on the returned constructor (if any), since
1346      * the defining class may still be non-public.
1347      */
1348     private static Constructor<?> getExternalizableConstructor(Class<?> cl) {
1349         try {
1350             Constructor<?> cons = cl.getDeclaredConstructor((Class<?>[]) null);
1351             cons.setAccessible(true);
1352             return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ?
1353                 cons : null;
1354         } catch (NoSuchMethodException ex) {
1355             return null;
1356         }
1357     }
1358 
1359     /**
1360      * Returns subclass-accessible no-arg constructor of first non-serializable
1361      * superclass, or null if none found.  Access checks are disabled on the
1362      * returned constructor (if any).
1363      */
1364     private static Constructor<?> getSerializableConstructor(Class<?> cl) {
1365         Class<?> initCl = cl;
1366         while (Serializable.class.isAssignableFrom(initCl)) {
1367             if ((initCl = initCl.getSuperclass()) == null) {
1368                 return null;
1369             }
1370         }
1371         try {
1372             Constructor<?> cons = initCl.getDeclaredConstructor((Class<?>[]) null);
1373             int mods = cons.getModifiers();
1374             if ((mods & Modifier.PRIVATE) != 0 ||
1375                 ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
1376                  !packageEquals(cl, initCl)))
1377             {
1378                 return null;
1379             }
1380             cons = reflFactory.newConstructorForSerialization(cl, cons);
1381             cons.setAccessible(true);
1382             return cons;
1383         } catch (NoSuchMethodException ex) {
1384             return null;
1385         }
1386     }
1387 
1388     /**
1389      * Returns non-static, non-abstract method with given signature provided it
1390      * is defined by or accessible (via inheritance) by the given class, or
1391      * null if no match found.  Access checks are disabled on the returned
1392      * method (if any).
1393      */
1394     private static Method getInheritableMethod(Class<?> cl, String name,
1395                                                Class<?>[] argTypes,
1396                                                Class<?> returnType)
1397     {
1398         Method meth = null;
1399         Class<?> defCl = cl;
1400         while (defCl != null) {
1401             try {
1402                 meth = defCl.getDeclaredMethod(name, argTypes);
1403                 break;
1404             } catch (NoSuchMethodException ex) {
1405                 defCl = defCl.getSuperclass();
1406             }
1407         }
1408 
1409         if ((meth == null) || (meth.getReturnType() != returnType)) {
1410             return null;
1411         }
1412         meth.setAccessible(true);
1413         int mods = meth.getModifiers();
1414         if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
1415             return null;
1416         } else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
1417             return meth;
1418         } else if ((mods & Modifier.PRIVATE) != 0) {
1419             return (cl == defCl) ? meth : null;
1420         } else {
1421             return packageEquals(cl, defCl) ? meth : null;
1422         }
1423     }
1424 
1425     /**
1426      * Returns non-static private method with given signature defined by given
1427      * class, or null if none found.  Access checks are disabled on the
1428      * returned method (if any).
1429      */
1430     private static Method getPrivateMethod(Class<?> cl, String name,
1431                                            Class<?>[] argTypes,
1432                                            Class<?> returnType)
1433     {
1434         try {
1435             Method meth = cl.getDeclaredMethod(name, argTypes);
1436             meth.setAccessible(true);
1437             int mods = meth.getModifiers();
1438             return ((meth.getReturnType() == returnType) &&
1439                     ((mods & Modifier.STATIC) == 0) &&
1440                     ((mods & Modifier.PRIVATE) != 0)) ? meth : null;
1441         } catch (NoSuchMethodException ex) {
1442             return null;
1443         }
1444     }
1445 
1446     /**
1447      * Returns true if classes are defined in the same runtime package, false
1448      * otherwise.
1449      */
1450     private static boolean packageEquals(Class<?> cl1, Class<?> cl2) {
1451         return (cl1.getClassLoader() == cl2.getClassLoader() &&
1452                 getPackageName(cl1).equals(getPackageName(cl2)));
1453     }
1454 
1455     /**
1456      * Returns package name of given class.
1457      */
1458     private static String getPackageName(Class<?> cl) {
1459         String s = cl.getName();
1460         int i = s.lastIndexOf('[');
1461         if (i >= 0) {
1462             s = s.substring(i + 2);
1463         }
1464         i = s.lastIndexOf('.');
1465         return (i >= 0) ? s.substring(0, i) : "";
1466     }
1467 
1468     /**
1469      * Compares class names for equality, ignoring package names.  Returns true
1470      * if class names equal, false otherwise.
1471      */
1472     private static boolean classNamesEqual(String name1, String name2) {
1473         name1 = name1.substring(name1.lastIndexOf('.') + 1);
1474         name2 = name2.substring(name2.lastIndexOf('.') + 1);
1475         return name1.equals(name2);
1476     }
1477 
1478     /**
1479      * Returns JVM type signature for given primitive.
1480      */
1481     private static String getPrimitiveSignature(Class<?> cl) {
1482         if (cl == Integer.TYPE)
1483             return "I";
1484         else if (cl == Byte.TYPE)
1485             return "B";
1486         else if (cl == Long.TYPE)
1487             return "J";
1488         else if (cl == Float.TYPE)
1489             return "F";
1490         else if (cl == Double.TYPE)
1491             return "D";
1492         else if (cl == Short.TYPE)
1493             return "S";
1494         else if (cl == Character.TYPE)
1495             return "C";
1496         else if (cl == Boolean.TYPE)
1497             return "Z";
1498         else if (cl == Void.TYPE)
1499             return "V";
1500         else
1501             throw new InternalError();
1502     }
1503 
1504     /**
1505      * Returns JVM type signature for given class.
1506      */
1507     static String getClassSignature(Class<?> cl) {
1508         if (cl.isPrimitive())
1509             return getPrimitiveSignature(cl);
1510         else
1511             return appendClassSignature(new StringBuilder(), cl).toString();
1512     }
1513 
1514     private static StringBuilder appendClassSignature(StringBuilder sbuf, Class<?> cl) {
1515        while (cl.isArray()) {
1516            sbuf.append('[');
1517            cl = cl.getComponentType();
1518        }
1519 
1520        if (cl.isPrimitive())
1521            sbuf.append(getPrimitiveSignature(cl));
1522        else
1523            sbuf.append('L').append(cl.getName().replace('.', '/')).append(';');
1524 
1525        return sbuf;
1526    }
1527 
1528     /**
1529      * Returns JVM type signature for given list of parameters and return type.
1530      */
1531     private static String getMethodSignature(Class<?>[] paramTypes,
1532                                              Class<?> retType)
1533     {
1534         StringBuilder sbuf = new StringBuilder();
1535         sbuf.append('(');
1536         for (int i = 0; i < paramTypes.length; i++) {
1537             appendClassSignature(sbuf, paramTypes[i]);
1538         }
1539         sbuf.append(')');
1540         appendClassSignature(sbuf, retType);
1541         return sbuf.toString();
1542     }
1543 
1544     /**
1545      * Convenience method for throwing an exception that is either a
1546      * RuntimeException, Error, or of some unexpected type (in which case it is
1547      * wrapped inside an IOException).
1548      */
1549     private static void throwMiscException(Throwable th) throws IOException {
1550         if (th instanceof RuntimeException) {
1551             throw (RuntimeException) th;
1552         } else if (th instanceof Error) {
1553             throw (Error) th;
1554         } else {
1555             IOException ex = new IOException("unexpected exception type");
1556             ex.initCause(th);
1557             throw ex;
1558         }
1559     }
1560 
1561     /**
1562      * Returns ObjectStreamField array describing the serializable fields of
1563      * the given class.  Serializable fields backed by an actual field of the
1564      * class are represented by ObjectStreamFields with corresponding non-null
1565      * Field objects.  Throws InvalidClassException if the (explicitly
1566      * declared) serializable fields are invalid.
1567      */
1568     private static ObjectStreamField[] getSerialFields(Class<?> cl)
1569         throws InvalidClassException
1570     {
1571         ObjectStreamField[] fields;
1572         if (Serializable.class.isAssignableFrom(cl) &&
1573             !Externalizable.class.isAssignableFrom(cl) &&
1574             !Proxy.isProxyClass(cl) &&
1575             !cl.isInterface())
1576         {
1577             if ((fields = getDeclaredSerialFields(cl)) == null) {
1578                 fields = getDefaultSerialFields(cl);
1579             }
1580             Arrays.sort(fields);
1581         } else {
1582             fields = NO_FIELDS;
1583         }
1584         return fields;
1585     }
1586 
1587     /**
1588      * Returns serializable fields of given class as defined explicitly by a
1589      * "serialPersistentFields" field, or null if no appropriate
1590      * "serialPersistentFields" field is defined.  Serializable fields backed
1591      * by an actual field of the class are represented by ObjectStreamFields
1592      * with corresponding non-null Field objects.  For compatibility with past
1593      * releases, a "serialPersistentFields" field with a null value is
1594      * considered equivalent to not declaring "serialPersistentFields".  Throws
1595      * InvalidClassException if the declared serializable fields are
1596      * invalid--e.g., if multiple fields share the same name.
1597      */
1598     private static ObjectStreamField[] getDeclaredSerialFields(Class<?> cl)
1599         throws InvalidClassException
1600     {
1601         ObjectStreamField[] serialPersistentFields = null;
1602         try {
1603             Field f = cl.getDeclaredField("serialPersistentFields");
1604             int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
1605             if ((f.getModifiers() & mask) == mask) {
1606                 f.setAccessible(true);
1607                 serialPersistentFields = (ObjectStreamField[]) f.get(null);
1608             }
1609         } catch (Exception ex) {
1610         }
1611         if (serialPersistentFields == null) {
1612             return null;
1613         } else if (serialPersistentFields.length == 0) {
1614             return NO_FIELDS;
1615         }
1616 
1617         ObjectStreamField[] boundFields =
1618             new ObjectStreamField[serialPersistentFields.length];
1619         Set<String> fieldNames = new HashSet<>(serialPersistentFields.length);
1620 
1621         for (int i = 0; i < serialPersistentFields.length; i++) {
1622             ObjectStreamField spf = serialPersistentFields[i];
1623 
1624             String fname = spf.getName();
1625             if (fieldNames.contains(fname)) {
1626                 throw new InvalidClassException(
1627                     "multiple serializable fields named " + fname);
1628             }
1629             fieldNames.add(fname);
1630 
1631             try {
1632                 Field f = cl.getDeclaredField(fname);
1633                 if ((f.getType() == spf.getType()) &&
1634                     ((f.getModifiers() & Modifier.STATIC) == 0))
1635                 {
1636                     boundFields[i] =
1637                         new ObjectStreamField(f, spf.isUnshared(), true);
1638                 }
1639             } catch (NoSuchFieldException ex) {
1640             }
1641             if (boundFields[i] == null) {
1642                 boundFields[i] = new ObjectStreamField(
1643                     fname, spf.getType(), spf.isUnshared());
1644             }
1645         }
1646         return boundFields;
1647     }
1648 
1649     /**
1650      * Returns array of ObjectStreamFields corresponding to all non-static
1651      * non-transient fields declared by given class.  Each ObjectStreamField
1652      * contains a Field object for the field it represents.  If no default
1653      * serializable fields exist, NO_FIELDS is returned.
1654      */
1655     private static ObjectStreamField[] getDefaultSerialFields(Class<?> cl) {
1656         Field[] clFields = cl.getDeclaredFields();
1657         ArrayList<ObjectStreamField> list = new ArrayList<>();
1658         int mask = Modifier.STATIC | Modifier.TRANSIENT;
1659 
1660         for (int i = 0; i < clFields.length; i++) {
1661             if ((clFields[i].getModifiers() & mask) == 0) {
1662                 list.add(new ObjectStreamField(clFields[i], false, true));
1663             }
1664         }
1665         int size = list.size();
1666         return (size == 0) ? NO_FIELDS :
1667             list.toArray(new ObjectStreamField[size]);
1668     }
1669 
1670     /**
1671      * Returns explicit serial version UID value declared by given class, or
1672      * null if none.
1673      */
1674     private static Long getDeclaredSUID(Class<?> cl) {
1675         try {
1676             Field f = cl.getDeclaredField("serialVersionUID");
1677             int mask = Modifier.STATIC | Modifier.FINAL;
1678             if ((f.getModifiers() & mask) == mask) {
1679                 f.setAccessible(true);
1680                 return Long.valueOf(f.getLong(null));
1681             }
1682         } catch (Exception ex) {
1683         }
1684         return null;
1685     }
1686 
1687     /**
1688      * Computes the default serial version UID value for the given class.
1689      */
1690     private static long computeDefaultSUID(Class<?> cl) {
1691         if (!Serializable.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl))
1692         {
1693             return 0L;
1694         }
1695 
1696         try {
1697             ByteArrayOutputStream bout = new ByteArrayOutputStream();
1698             DataOutputStream dout = new DataOutputStream(bout);
1699 
1700             dout.writeUTF(cl.getName());
1701 
1702             int classMods = cl.getModifiers() &
1703                 (Modifier.PUBLIC | Modifier.FINAL |
1704                  Modifier.INTERFACE | Modifier.ABSTRACT);
1705 
1706             /*
1707              * compensate for javac bug in which ABSTRACT bit was set for an
1708              * interface only if the interface declared methods
1709              */
1710             Method[] methods = cl.getDeclaredMethods();
1711             if ((classMods & Modifier.INTERFACE) != 0) {
1712                 classMods = (methods.length > 0) ?
1713                     (classMods | Modifier.ABSTRACT) :
1714                     (classMods & ~Modifier.ABSTRACT);
1715             }
1716             dout.writeInt(classMods);
1717 
1718             if (!cl.isArray()) {
1719                 /*
1720                  * compensate for change in 1.2FCS in which
1721                  * Class.getInterfaces() was modified to return Cloneable and
1722                  * Serializable for array classes.
1723                  */
1724                 Class<?>[] interfaces = cl.getInterfaces();
1725                 String[] ifaceNames = new String[interfaces.length];
1726                 for (int i = 0; i < interfaces.length; i++) {
1727                     ifaceNames[i] = interfaces[i].getName();
1728                 }
1729                 Arrays.sort(ifaceNames);
1730                 for (int i = 0; i < ifaceNames.length; i++) {
1731                     dout.writeUTF(ifaceNames[i]);
1732                 }
1733             }
1734 
1735             Field[] fields = cl.getDeclaredFields();
1736             MemberSignature[] fieldSigs = new MemberSignature[fields.length];
1737             for (int i = 0; i < fields.length; i++) {
1738                 fieldSigs[i] = new MemberSignature(fields[i]);
1739             }
1740             Arrays.sort(fieldSigs, new Comparator<MemberSignature>() {
1741                 public int compare(MemberSignature ms1, MemberSignature ms2) {
1742                     return ms1.name.compareTo(ms2.name);
1743                 }
1744             });
1745             for (int i = 0; i < fieldSigs.length; i++) {
1746                 MemberSignature sig = fieldSigs[i];
1747                 int mods = sig.member.getModifiers() &
1748                     (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
1749                      Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE |
1750                      Modifier.TRANSIENT);
1751                 if (((mods & Modifier.PRIVATE) == 0) ||
1752                     ((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0))
1753                 {
1754                     dout.writeUTF(sig.name);
1755                     dout.writeInt(mods);
1756                     dout.writeUTF(sig.signature);
1757                 }
1758             }
1759 
1760             if (hasStaticInitializer(cl)) {
1761                 dout.writeUTF("<clinit>");
1762                 dout.writeInt(Modifier.STATIC);
1763                 dout.writeUTF("()V");
1764             }
1765 
1766             Constructor<?>[] cons = cl.getDeclaredConstructors();
1767             MemberSignature[] consSigs = new MemberSignature[cons.length];
1768             for (int i = 0; i < cons.length; i++) {
1769                 consSigs[i] = new MemberSignature(cons[i]);
1770             }
1771             Arrays.sort(consSigs, new Comparator<MemberSignature>() {
1772                 public int compare(MemberSignature ms1, MemberSignature ms2) {
1773                     return ms1.signature.compareTo(ms2.signature);
1774                 }
1775             });
1776             for (int i = 0; i < consSigs.length; i++) {
1777                 MemberSignature sig = consSigs[i];
1778                 int mods = sig.member.getModifiers() &
1779                     (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
1780                      Modifier.STATIC | Modifier.FINAL |
1781                      Modifier.SYNCHRONIZED | Modifier.NATIVE |
1782                      Modifier.ABSTRACT | Modifier.STRICT);
1783                 if ((mods & Modifier.PRIVATE) == 0) {
1784                     dout.writeUTF("<init>");
1785                     dout.writeInt(mods);
1786                     dout.writeUTF(sig.signature.replace('/', '.'));
1787                 }
1788             }
1789 
1790             MemberSignature[] methSigs = new MemberSignature[methods.length];
1791             for (int i = 0; i < methods.length; i++) {
1792                 methSigs[i] = new MemberSignature(methods[i]);
1793             }
1794             Arrays.sort(methSigs, new Comparator<MemberSignature>() {
1795                 public int compare(MemberSignature ms1, MemberSignature ms2) {
1796                     int comp = ms1.name.compareTo(ms2.name);
1797                     if (comp == 0) {
1798                         comp = ms1.signature.compareTo(ms2.signature);
1799                     }
1800                     return comp;
1801                 }
1802             });
1803             for (int i = 0; i < methSigs.length; i++) {
1804                 MemberSignature sig = methSigs[i];
1805                 int mods = sig.member.getModifiers() &
1806                     (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
1807                      Modifier.STATIC | Modifier.FINAL |
1808                      Modifier.SYNCHRONIZED | Modifier.NATIVE |
1809                      Modifier.ABSTRACT | Modifier.STRICT);
1810                 if ((mods & Modifier.PRIVATE) == 0) {
1811                     dout.writeUTF(sig.name);
1812                     dout.writeInt(mods);
1813                     dout.writeUTF(sig.signature.replace('/', '.'));
1814                 }
1815             }
1816 
1817             dout.flush();
1818 
1819             MessageDigest md = MessageDigest.getInstance("SHA");
1820             byte[] hashBytes = md.digest(bout.toByteArray());
1821             long hash = 0;
1822             for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
1823                 hash = (hash << 8) | (hashBytes[i] & 0xFF);
1824             }
1825             return hash;
1826         } catch (IOException ex) {
1827             throw new InternalError(ex);
1828         } catch (NoSuchAlgorithmException ex) {
1829             throw new SecurityException(ex.getMessage());
1830         }
1831     }
1832 
1833     /**
1834      * Returns true if the given class defines a static initializer method,
1835      * false otherwise.
1836      */
1837     private native static boolean hasStaticInitializer(Class<?> cl);
1838 
1839     /**
1840      * Class for computing and caching field/constructor/method signatures
1841      * during serialVersionUID calculation.
1842      */
1843     private static class MemberSignature {
1844 
1845         public final Member member;
1846         public final String name;
1847         public final String signature;
1848 
1849         public MemberSignature(Field field) {
1850             member = field;
1851             name = field.getName();
1852             signature = getClassSignature(field.getType());
1853         }
1854 
1855         public MemberSignature(Constructor<?> cons) {
1856             member = cons;
1857             name = cons.getName();
1858             signature = getMethodSignature(
1859                 cons.getParameterTypes(), Void.TYPE);
1860         }
1861 
1862         public MemberSignature(Method meth) {
1863             member = meth;
1864             name = meth.getName();
1865             signature = getMethodSignature(
1866                 meth.getParameterTypes(), meth.getReturnType());
1867         }
1868     }
1869 
1870     /**
1871      * Class for setting and retrieving serializable field values in batch.
1872      */
1873     // REMIND: dynamically generate these?
1874     private static class FieldReflector {
1875 
1876         /** handle for performing unsafe operations */
1877         private static final Unsafe unsafe = Unsafe.getUnsafe();
1878 
1879         /** fields to operate on */
1880         private final ObjectStreamField[] fields;
1881         /** number of primitive fields */
1882         private final int numPrimFields;
1883         /** unsafe field keys for reading fields - may contain dupes */
1884         private final long[] readKeys;
1885         /** unsafe fields keys for writing fields - no dupes */
1886         private final long[] writeKeys;
1887         /** field data offsets */
1888         private final int[] offsets;
1889         /** field type codes */
1890         private final char[] typeCodes;
1891         /** field types */
1892         private final Class<?>[] types;
1893 
1894         /**
1895          * Constructs FieldReflector capable of setting/getting values from the
1896          * subset of fields whose ObjectStreamFields contain non-null
1897          * reflective Field objects.  ObjectStreamFields with null Fields are
1898          * treated as filler, for which get operations return default values
1899          * and set operations discard given values.
1900          */
1901         FieldReflector(ObjectStreamField[] fields) {
1902             this.fields = fields;
1903             int nfields = fields.length;
1904             readKeys = new long[nfields];
1905             writeKeys = new long[nfields];
1906             offsets = new int[nfields];
1907             typeCodes = new char[nfields];
1908             ArrayList<Class<?>> typeList = new ArrayList<>();
1909             Set<Long> usedKeys = new HashSet<>();
1910 
1911 
1912             for (int i = 0; i < nfields; i++) {
1913                 ObjectStreamField f = fields[i];
1914                 Field rf = f.getField();
1915                 long key = (rf != null) ?
1916                     unsafe.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET;
1917                 readKeys[i] = key;
1918                 writeKeys[i] = usedKeys.add(key) ?
1919                     key : Unsafe.INVALID_FIELD_OFFSET;
1920                 offsets[i] = f.getOffset();
1921                 typeCodes[i] = f.getTypeCode();
1922                 if (!f.isPrimitive()) {
1923                     typeList.add((rf != null) ? rf.getType() : null);
1924                 }
1925             }
1926 
1927             types = typeList.toArray(new Class<?>[typeList.size()]);
1928             numPrimFields = nfields - types.length;
1929         }
1930 
1931         /**
1932          * Returns list of ObjectStreamFields representing fields operated on
1933          * by this reflector.  The shared/unshared values and Field objects
1934          * contained by ObjectStreamFields in the list reflect their bindings
1935          * to locally defined serializable fields.
1936          */
1937         ObjectStreamField[] getFields() {
1938             return fields;
1939         }
1940 
1941         /**
1942          * Fetches the serializable primitive field values of object obj and
1943          * marshals them into byte array buf starting at offset 0.  The caller
1944          * is responsible for ensuring that obj is of the proper type.
1945          */
1946         void getPrimFieldValues(Object obj, byte[] buf) {
1947             if (obj == null) {
1948                 throw new NullPointerException();
1949             }
1950             /* assuming checkDefaultSerialize() has been called on the class
1951              * descriptor this FieldReflector was obtained from, no field keys
1952              * in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
1953              */
1954             for (int i = 0; i < numPrimFields; i++) {
1955                 long key = readKeys[i];
1956                 int off = offsets[i];
1957                 switch (typeCodes[i]) {
1958                     case 'Z':
1959                         Bits.putBoolean(buf, off, unsafe.getBoolean(obj, key));
1960                         break;
1961 
1962                     case 'B':
1963                         buf[off] = unsafe.getByte(obj, key);
1964                         break;
1965 
1966                     case 'C':
1967                         Bits.putChar(buf, off, unsafe.getChar(obj, key));
1968                         break;
1969 
1970                     case 'S':
1971                         Bits.putShort(buf, off, unsafe.getShort(obj, key));
1972                         break;
1973 
1974                     case 'I':
1975                         Bits.putInt(buf, off, unsafe.getInt(obj, key));
1976                         break;
1977 
1978                     case 'F':
1979                         Bits.putFloat(buf, off, unsafe.getFloat(obj, key));
1980                         break;
1981 
1982                     case 'J':
1983                         Bits.putLong(buf, off, unsafe.getLong(obj, key));
1984                         break;
1985 
1986                     case 'D':
1987                         Bits.putDouble(buf, off, unsafe.getDouble(obj, key));
1988                         break;
1989 
1990                     default:
1991                         throw new InternalError();
1992                 }
1993             }
1994         }
1995 
1996         /**
1997          * Sets the serializable primitive fields of object obj using values
1998          * unmarshalled from byte array buf starting at offset 0.  The caller
1999          * is responsible for ensuring that obj is of the proper type.
2000          */
2001         void setPrimFieldValues(Object obj, byte[] buf) {
2002             if (obj == null) {
2003                 throw new NullPointerException();
2004             }
2005             for (int i = 0; i < numPrimFields; i++) {
2006                 long key = writeKeys[i];
2007                 if (key == Unsafe.INVALID_FIELD_OFFSET) {
2008                     continue;           // discard value
2009                 }
2010                 int off = offsets[i];
2011                 switch (typeCodes[i]) {
2012                     case 'Z':
2013                         unsafe.putBoolean(obj, key, Bits.getBoolean(buf, off));
2014                         break;
2015 
2016                     case 'B':
2017                         unsafe.putByte(obj, key, buf[off]);
2018                         break;
2019 
2020                     case 'C':
2021                         unsafe.putChar(obj, key, Bits.getChar(buf, off));
2022                         break;
2023 
2024                     case 'S':
2025                         unsafe.putShort(obj, key, Bits.getShort(buf, off));
2026                         break;
2027 
2028                     case 'I':
2029                         unsafe.putInt(obj, key, Bits.getInt(buf, off));
2030                         break;
2031 
2032                     case 'F':
2033                         unsafe.putFloat(obj, key, Bits.getFloat(buf, off));
2034                         break;
2035 
2036                     case 'J':
2037                         unsafe.putLong(obj, key, Bits.getLong(buf, off));
2038                         break;
2039 
2040                     case 'D':
2041                         unsafe.putDouble(obj, key, Bits.getDouble(buf, off));
2042                         break;
2043 
2044                     default:
2045                         throw new InternalError();
2046                 }
2047             }
2048         }
2049 
2050         /**
2051          * Fetches the serializable object field values of object obj and
2052          * stores them in array vals starting at offset 0.  The caller is
2053          * responsible for ensuring that obj is of the proper type.
2054          */
2055         void getObjFieldValues(Object obj, Object[] vals) {
2056             if (obj == null) {
2057                 throw new NullPointerException();
2058             }
2059             /* assuming checkDefaultSerialize() has been called on the class
2060              * descriptor this FieldReflector was obtained from, no field keys
2061              * in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
2062              */
2063             for (int i = numPrimFields; i < fields.length; i++) {
2064                 switch (typeCodes[i]) {
2065                     case 'L':
2066                     case '[':
2067                         vals[offsets[i]] = unsafe.getObject(obj, readKeys[i]);
2068                         break;
2069 
2070                     default:
2071                         throw new InternalError();
2072                 }
2073             }
2074         }
2075 
2076         void checkObjectFieldValueTypes(Object obj, Object[] vals) {
2077             setObjFieldValues(obj, vals, true);
2078         }
2079 
2080         /**
2081          * Sets the serializable object fields of object obj using values from
2082          * array vals starting at offset 0.  The caller is responsible for
2083          * ensuring that obj is of the proper type; however, attempts to set a
2084          * field with a value of the wrong type will trigger an appropriate
2085          * ClassCastException.
2086          */
2087         void setObjFieldValues(Object obj, Object[] vals) {
2088             setObjFieldValues(obj, vals, false);
2089         }
2090 
2091         private void setObjFieldValues(Object obj, Object[] vals, boolean dryRun) {
2092             if (obj == null) {
2093                 throw new NullPointerException();
2094             }
2095             for (int i = numPrimFields; i < fields.length; i++) {
2096                 long key = writeKeys[i];
2097                 if (key == Unsafe.INVALID_FIELD_OFFSET) {
2098                     continue;           // discard value
2099                 }
2100                 switch (typeCodes[i]) {
2101                     case 'L':
2102                     case '[':
2103                         Object val = vals[offsets[i]];
2104                         if (val != null &&
2105                             !types[i - numPrimFields].isInstance(val))
2106                         {
2107                             Field f = fields[i].getField();
2108                             throw new ClassCastException(
2109                                 "cannot assign instance of " +
2110                                 val.getClass().getName() + " to field " +
2111                                 f.getDeclaringClass().getName() + "." +
2112                                 f.getName() + " of type " +
2113                                 f.getType().getName() + " in instance of " +
2114                                 obj.getClass().getName());
2115                         }
2116                         if (!dryRun)
2117                             unsafe.putObject(obj, key, val);
2118                         break;
2119 
2120                     default:
2121                         throw new InternalError();
2122                 }
2123             }
2124         }
2125     }
2126 
2127     /**
2128      * Matches given set of serializable fields with serializable fields
2129      * described by the given local class descriptor, and returns a
2130      * FieldReflector instance capable of setting/getting values from the
2131      * subset of fields that match (non-matching fields are treated as filler,
2132      * for which get operations return default values and set operations
2133      * discard given values).  Throws InvalidClassException if unresolvable
2134      * type conflicts exist between the two sets of fields.
2135      */
2136     private static FieldReflector getReflector(ObjectStreamField[] fields,
2137                                                ObjectStreamClass localDesc)
2138         throws InvalidClassException
2139     {
2140         // class irrelevant if no fields
2141         Class<?> cl = (localDesc != null && fields.length > 0) ?
2142             localDesc.cl : null;
2143         processQueue(Caches.reflectorsQueue, Caches.reflectors);
2144         FieldReflectorKey key = new FieldReflectorKey(cl, fields,
2145                                                       Caches.reflectorsQueue);
2146         Reference<?> ref = Caches.reflectors.get(key);
2147         Object entry = null;
2148         if (ref != null) {
2149             entry = ref.get();
2150         }
2151         EntryFuture future = null;
2152         if (entry == null) {
2153             EntryFuture newEntry = new EntryFuture();
2154             Reference<?> newRef = new SoftReference<>(newEntry);
2155             do {
2156                 if (ref != null) {
2157                     Caches.reflectors.remove(key, ref);
2158                 }
2159                 ref = Caches.reflectors.putIfAbsent(key, newRef);
2160                 if (ref != null) {
2161                     entry = ref.get();
2162                 }
2163             } while (ref != null && entry == null);
2164             if (entry == null) {
2165                 future = newEntry;
2166             }
2167         }
2168 
2169         if (entry instanceof FieldReflector) {  // check common case first
2170             return (FieldReflector) entry;
2171         } else if (entry instanceof EntryFuture) {
2172             entry = ((EntryFuture) entry).get();
2173         } else if (entry == null) {
2174             try {
2175                 entry = new FieldReflector(matchFields(fields, localDesc));
2176             } catch (Throwable th) {
2177                 entry = th;
2178             }
2179             future.set(entry);
2180             Caches.reflectors.put(key, new SoftReference<Object>(entry));
2181         }
2182 
2183         if (entry instanceof FieldReflector) {
2184             return (FieldReflector) entry;
2185         } else if (entry instanceof InvalidClassException) {
2186             throw (InvalidClassException) entry;
2187         } else if (entry instanceof RuntimeException) {
2188             throw (RuntimeException) entry;
2189         } else if (entry instanceof Error) {
2190             throw (Error) entry;
2191         } else {
2192             throw new InternalError("unexpected entry: " + entry);
2193         }
2194     }
2195 
2196     /**
2197      * FieldReflector cache lookup key.  Keys are considered equal if they
2198      * refer to the same class and equivalent field formats.
2199      */
2200     private static class FieldReflectorKey extends WeakReference<Class<?>> {
2201 
2202         private final String sigs;
2203         private final int hash;
2204         private final boolean nullClass;
2205 
2206         FieldReflectorKey(Class<?> cl, ObjectStreamField[] fields,
2207                           ReferenceQueue<Class<?>> queue)
2208         {
2209             super(cl, queue);
2210             nullClass = (cl == null);
2211             StringBuilder sbuf = new StringBuilder();
2212             for (int i = 0; i < fields.length; i++) {
2213                 ObjectStreamField f = fields[i];
2214                 sbuf.append(f.getName()).append(f.getSignature());
2215             }
2216             sigs = sbuf.toString();
2217             hash = System.identityHashCode(cl) + sigs.hashCode();
2218         }
2219 
2220         public int hashCode() {
2221             return hash;
2222         }
2223 
2224         public boolean equals(Object obj) {
2225             if (obj == this) {
2226                 return true;
2227             }
2228 
2229             if (obj instanceof FieldReflectorKey) {
2230                 FieldReflectorKey other = (FieldReflectorKey) obj;
2231                 Class<?> referent;
2232                 return (nullClass ? other.nullClass
2233                                   : ((referent = get()) != null) &&
2234                                     (referent == other.get())) &&
2235                     sigs.equals(other.sigs);
2236             } else {
2237                 return false;
2238             }
2239         }
2240     }
2241 
2242     /**
2243      * Matches given set of serializable fields with serializable fields
2244      * obtained from the given local class descriptor (which contain bindings
2245      * to reflective Field objects).  Returns list of ObjectStreamFields in
2246      * which each ObjectStreamField whose signature matches that of a local
2247      * field contains a Field object for that field; unmatched
2248      * ObjectStreamFields contain null Field objects.  Shared/unshared settings
2249      * of the returned ObjectStreamFields also reflect those of matched local
2250      * ObjectStreamFields.  Throws InvalidClassException if unresolvable type
2251      * conflicts exist between the two sets of fields.
2252      */
2253     private static ObjectStreamField[] matchFields(ObjectStreamField[] fields,
2254                                                    ObjectStreamClass localDesc)
2255         throws InvalidClassException
2256     {
2257         ObjectStreamField[] localFields = (localDesc != null) ?
2258             localDesc.fields : NO_FIELDS;
2259 
2260         /*
2261          * Even if fields == localFields, we cannot simply return localFields
2262          * here.  In previous implementations of serialization,
2263          * ObjectStreamField.getType() returned Object.class if the
2264          * ObjectStreamField represented a non-primitive field and belonged to
2265          * a non-local class descriptor.  To preserve this (questionable)
2266          * behavior, the ObjectStreamField instances returned by matchFields
2267          * cannot report non-primitive types other than Object.class; hence
2268          * localFields cannot be returned directly.
2269          */
2270 
2271         ObjectStreamField[] matches = new ObjectStreamField[fields.length];
2272         for (int i = 0; i < fields.length; i++) {
2273             ObjectStreamField f = fields[i], m = null;
2274             for (int j = 0; j < localFields.length; j++) {
2275                 ObjectStreamField lf = localFields[j];
2276                 if (f.getName().equals(lf.getName())) {
2277                     if ((f.isPrimitive() || lf.isPrimitive()) &&
2278                         f.getTypeCode() != lf.getTypeCode())
2279                     {
2280                         throw new InvalidClassException(localDesc.name,
2281                             "incompatible types for field " + f.getName());
2282                     }
2283                     if (lf.getField() != null) {
2284                         m = new ObjectStreamField(
2285                             lf.getField(), lf.isUnshared(), false);
2286                     } else {
2287                         m = new ObjectStreamField(
2288                             lf.getName(), lf.getSignature(), lf.isUnshared());
2289                     }
2290                 }
2291             }
2292             if (m == null) {
2293                 m = new ObjectStreamField(
2294                     f.getName(), f.getSignature(), false);
2295             }
2296             m.setOffset(f.getOffset());
2297             matches[i] = m;
2298         }
2299         return matches;
2300     }
2301 
2302     /**
2303      * Removes from the specified map any keys that have been enqueued
2304      * on the specified reference queue.
2305      */
2306     static void processQueue(ReferenceQueue<Class<?>> queue,
2307                              ConcurrentMap<? extends
2308                              WeakReference<Class<?>>, ?> map)
2309     {
2310         Reference<? extends Class<?>> ref;
2311         while((ref = queue.poll()) != null) {
2312             map.remove(ref);
2313         }
2314     }
2315 
2316     /**
2317      *  Weak key for Class objects.
2318      *
2319      **/
2320     static class WeakClassKey extends WeakReference<Class<?>> {
2321         /**
2322          * saved value of the referent's identity hash code, to maintain
2323          * a consistent hash code after the referent has been cleared
2324          */
2325         private final int hash;
2326 
2327         /**
2328          * Create a new WeakClassKey to the given object, registered
2329          * with a queue.
2330          */
2331         WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
2332             super(cl, refQueue);
2333             hash = System.identityHashCode(cl);
2334         }
2335 
2336         /**
2337          * Returns the identity hash code of the original referent.
2338          */
2339         public int hashCode() {
2340             return hash;
2341         }
2342 
2343         /**
2344          * Returns true if the given object is this identical
2345          * WeakClassKey instance, or, if this object's referent has not
2346          * been cleared, if the given object is another WeakClassKey
2347          * instance with the identical non-null referent as this one.
2348          */
2349         public boolean equals(Object obj) {
2350             if (obj == this) {
2351                 return true;
2352             }
2353 
2354             if (obj instanceof WeakClassKey) {
2355                 Object referent = get();
2356                 return (referent != null) &&
2357                        (referent == ((WeakClassKey) obj).get());
2358             } else {
2359                 return false;
2360             }
2361         }
2362     }
2363 }