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