emul/compact/src/main/java/java/io/ObjectOutputStream.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, 2010, 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.io.ObjectStreamClass.WeakClassKey;
jaroslav@601
    29
import java.lang.ref.ReferenceQueue;
jaroslav@601
    30
import java.security.AccessController;
jaroslav@601
    31
import java.security.PrivilegedAction;
jaroslav@601
    32
import java.util.ArrayList;
jaroslav@601
    33
import java.util.Arrays;
jaroslav@601
    34
import java.util.List;
jaroslav@601
    35
import java.util.concurrent.ConcurrentHashMap;
jaroslav@601
    36
import java.util.concurrent.ConcurrentMap;
jaroslav@601
    37
import static java.io.ObjectStreamClass.processQueue;
jaroslav@601
    38
import java.io.SerialCallbackContext;
jaroslav@601
    39
jaroslav@601
    40
/**
jaroslav@601
    41
 * An ObjectOutputStream writes primitive data types and graphs of Java objects
jaroslav@601
    42
 * to an OutputStream.  The objects can be read (reconstituted) using an
jaroslav@601
    43
 * ObjectInputStream.  Persistent storage of objects can be accomplished by
jaroslav@601
    44
 * using a file for the stream.  If the stream is a network socket stream, the
jaroslav@601
    45
 * objects can be reconstituted on another host or in another process.
jaroslav@601
    46
 *
jaroslav@601
    47
 * <p>Only objects that support the java.io.Serializable interface can be
jaroslav@601
    48
 * written to streams.  The class of each serializable object is encoded
jaroslav@601
    49
 * including the class name and signature of the class, the values of the
jaroslav@601
    50
 * object's fields and arrays, and the closure of any other objects referenced
jaroslav@601
    51
 * from the initial objects.
jaroslav@601
    52
 *
jaroslav@601
    53
 * <p>The method writeObject is used to write an object to the stream.  Any
jaroslav@601
    54
 * object, including Strings and arrays, is written with writeObject. Multiple
jaroslav@601
    55
 * objects or primitives can be written to the stream.  The objects must be
jaroslav@601
    56
 * read back from the corresponding ObjectInputstream with the same types and
jaroslav@601
    57
 * in the same order as they were written.
jaroslav@601
    58
 *
jaroslav@601
    59
 * <p>Primitive data types can also be written to the stream using the
jaroslav@601
    60
 * appropriate methods from DataOutput. Strings can also be written using the
jaroslav@601
    61
 * writeUTF method.
jaroslav@601
    62
 *
jaroslav@601
    63
 * <p>The default serialization mechanism for an object writes the class of the
jaroslav@601
    64
 * object, the class signature, and the values of all non-transient and
jaroslav@601
    65
 * non-static fields.  References to other objects (except in transient or
jaroslav@601
    66
 * static fields) cause those objects to be written also. Multiple references
jaroslav@601
    67
 * to a single object are encoded using a reference sharing mechanism so that
jaroslav@601
    68
 * graphs of objects can be restored to the same shape as when the original was
jaroslav@601
    69
 * written.
jaroslav@601
    70
 *
jaroslav@601
    71
 * <p>For example to write an object that can be read by the example in
jaroslav@601
    72
 * ObjectInputStream:
jaroslav@601
    73
 * <br>
jaroslav@601
    74
 * <pre>
jaroslav@601
    75
 *      FileOutputStream fos = new FileOutputStream("t.tmp");
jaroslav@601
    76
 *      ObjectOutputStream oos = new ObjectOutputStream(fos);
jaroslav@601
    77
 *
jaroslav@601
    78
 *      oos.writeInt(12345);
jaroslav@601
    79
 *      oos.writeObject("Today");
jaroslav@601
    80
 *      oos.writeObject(new Date());
jaroslav@601
    81
 *
jaroslav@601
    82
 *      oos.close();
jaroslav@601
    83
 * </pre>
jaroslav@601
    84
 *
jaroslav@601
    85
 * <p>Classes that require special handling during the serialization and
jaroslav@601
    86
 * deserialization process must implement special methods with these exact
jaroslav@601
    87
 * signatures:
jaroslav@601
    88
 * <br>
jaroslav@601
    89
 * <pre>
jaroslav@601
    90
 * private void readObject(java.io.ObjectInputStream stream)
jaroslav@601
    91
 *     throws IOException, ClassNotFoundException;
jaroslav@601
    92
 * private void writeObject(java.io.ObjectOutputStream stream)
jaroslav@601
    93
 *     throws IOException
jaroslav@601
    94
 * private void readObjectNoData()
jaroslav@601
    95
 *     throws ObjectStreamException;
jaroslav@601
    96
 * </pre>
jaroslav@601
    97
 *
jaroslav@601
    98
 * <p>The writeObject method is responsible for writing the state of the object
jaroslav@601
    99
 * for its particular class so that the corresponding readObject method can
jaroslav@601
   100
 * restore it.  The method does not need to concern itself with the state
jaroslav@601
   101
 * belonging to the object's superclasses or subclasses.  State is saved by
jaroslav@601
   102
 * writing the individual fields to the ObjectOutputStream using the
jaroslav@601
   103
 * writeObject method or by using the methods for primitive data types
jaroslav@601
   104
 * supported by DataOutput.
jaroslav@601
   105
 *
jaroslav@601
   106
 * <p>Serialization does not write out the fields of any object that does not
jaroslav@601
   107
 * implement the java.io.Serializable interface.  Subclasses of Objects that
jaroslav@601
   108
 * are not serializable can be serializable. In this case the non-serializable
jaroslav@601
   109
 * class must have a no-arg constructor to allow its fields to be initialized.
jaroslav@601
   110
 * In this case it is the responsibility of the subclass to save and restore
jaroslav@601
   111
 * the state of the non-serializable class. It is frequently the case that the
jaroslav@601
   112
 * fields of that class are accessible (public, package, or protected) or that
jaroslav@601
   113
 * there are get and set methods that can be used to restore the state.
jaroslav@601
   114
 *
jaroslav@601
   115
 * <p>Serialization of an object can be prevented by implementing writeObject
jaroslav@601
   116
 * and readObject methods that throw the NotSerializableException.  The
jaroslav@601
   117
 * exception will be caught by the ObjectOutputStream and abort the
jaroslav@601
   118
 * serialization process.
jaroslav@601
   119
 *
jaroslav@601
   120
 * <p>Implementing the Externalizable interface allows the object to assume
jaroslav@601
   121
 * complete control over the contents and format of the object's serialized
jaroslav@601
   122
 * form.  The methods of the Externalizable interface, writeExternal and
jaroslav@601
   123
 * readExternal, are called to save and restore the objects state.  When
jaroslav@601
   124
 * implemented by a class they can write and read their own state using all of
jaroslav@601
   125
 * the methods of ObjectOutput and ObjectInput.  It is the responsibility of
jaroslav@601
   126
 * the objects to handle any versioning that occurs.
jaroslav@601
   127
 *
jaroslav@601
   128
 * <p>Enum constants are serialized differently than ordinary serializable or
jaroslav@601
   129
 * externalizable objects.  The serialized form of an enum constant consists
jaroslav@601
   130
 * solely of its name; field values of the constant are not transmitted.  To
jaroslav@601
   131
 * serialize an enum constant, ObjectOutputStream writes the string returned by
jaroslav@601
   132
 * the constant's name method.  Like other serializable or externalizable
jaroslav@601
   133
 * objects, enum constants can function as the targets of back references
jaroslav@601
   134
 * appearing subsequently in the serialization stream.  The process by which
jaroslav@601
   135
 * enum constants are serialized cannot be customized; any class-specific
jaroslav@601
   136
 * writeObject and writeReplace methods defined by enum types are ignored
jaroslav@601
   137
 * during serialization.  Similarly, any serialPersistentFields or
jaroslav@601
   138
 * serialVersionUID field declarations are also ignored--all enum types have a
jaroslav@601
   139
 * fixed serialVersionUID of 0L.
jaroslav@601
   140
 *
jaroslav@601
   141
 * <p>Primitive data, excluding serializable fields and externalizable data, is
jaroslav@601
   142
 * written to the ObjectOutputStream in block-data records. A block data record
jaroslav@601
   143
 * is composed of a header and data. The block data header consists of a marker
jaroslav@601
   144
 * and the number of bytes to follow the header.  Consecutive primitive data
jaroslav@601
   145
 * writes are merged into one block-data record.  The blocking factor used for
jaroslav@601
   146
 * a block-data record will be 1024 bytes.  Each block-data record will be
jaroslav@601
   147
 * filled up to 1024 bytes, or be written whenever there is a termination of
jaroslav@601
   148
 * block-data mode.  Calls to the ObjectOutputStream methods writeObject,
jaroslav@601
   149
 * defaultWriteObject and writeFields initially terminate any existing
jaroslav@601
   150
 * block-data record.
jaroslav@601
   151
 *
jaroslav@601
   152
 * @author      Mike Warres
jaroslav@601
   153
 * @author      Roger Riggs
jaroslav@601
   154
 * @see java.io.DataOutput
jaroslav@601
   155
 * @see java.io.ObjectInputStream
jaroslav@601
   156
 * @see java.io.Serializable
jaroslav@601
   157
 * @see java.io.Externalizable
jaroslav@601
   158
 * @see <a href="../../../platform/serialization/spec/output.html">Object Serialization Specification, Section 2, Object Output Classes</a>
jaroslav@601
   159
 * @since       JDK1.1
jaroslav@601
   160
 */
jaroslav@601
   161
public class ObjectOutputStream
jaroslav@601
   162
    extends OutputStream implements ObjectOutput, ObjectStreamConstants
jaroslav@601
   163
{
jaroslav@601
   164
jaroslav@601
   165
    private static class Caches {
jaroslav@601
   166
        /** cache of subclass security audit results */
jaroslav@601
   167
        static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
jaroslav@601
   168
            new ConcurrentHashMap<>();
jaroslav@601
   169
jaroslav@601
   170
        /** queue for WeakReferences to audited subclasses */
jaroslav@601
   171
        static final ReferenceQueue<Class<?>> subclassAuditsQueue =
jaroslav@601
   172
            new ReferenceQueue<>();
jaroslav@601
   173
    }
jaroslav@601
   174
jaroslav@601
   175
    /** filter stream for handling block data conversion */
jaroslav@601
   176
    private final BlockDataOutputStream bout;
jaroslav@601
   177
    /** obj -> wire handle map */
jaroslav@601
   178
    private final HandleTable handles;
jaroslav@601
   179
    /** obj -> replacement obj map */
jaroslav@601
   180
    private final ReplaceTable subs;
jaroslav@601
   181
    /** stream protocol version */
jaroslav@601
   182
    private int protocol = PROTOCOL_VERSION_2;
jaroslav@601
   183
    /** recursion depth */
jaroslav@601
   184
    private int depth;
jaroslav@601
   185
jaroslav@601
   186
    /** buffer for writing primitive field values */
jaroslav@601
   187
    private byte[] primVals;
jaroslav@601
   188
jaroslav@601
   189
    /** if true, invoke writeObjectOverride() instead of writeObject() */
jaroslav@601
   190
    private final boolean enableOverride;
jaroslav@601
   191
    /** if true, invoke replaceObject() */
jaroslav@601
   192
    private boolean enableReplace;
jaroslav@601
   193
jaroslav@601
   194
    // values below valid only during upcalls to writeObject()/writeExternal()
jaroslav@601
   195
    /**
jaroslav@601
   196
     * Context during upcalls to class-defined writeObject methods; holds
jaroslav@601
   197
     * object currently being serialized and descriptor for current class.
jaroslav@601
   198
     * Null when not during writeObject upcall.
jaroslav@601
   199
     */
jaroslav@601
   200
    private SerialCallbackContext curContext;
jaroslav@601
   201
    /** current PutField object */
jaroslav@601
   202
    private PutFieldImpl curPut;
jaroslav@601
   203
jaroslav@601
   204
    /** custom storage for debug trace info */
jaroslav@601
   205
    private final DebugTraceInfoStack debugInfoStack;
jaroslav@601
   206
jaroslav@601
   207
    /**
jaroslav@601
   208
     * value of "sun.io.serialization.extendedDebugInfo" property,
jaroslav@601
   209
     * as true or false for extended information about exception's place
jaroslav@601
   210
     */
jaroslav@601
   211
    private static final boolean extendedDebugInfo =
jaroslav@601
   212
        java.security.AccessController.doPrivileged(
jaroslav@601
   213
            new sun.security.action.GetBooleanAction(
jaroslav@601
   214
                "sun.io.serialization.extendedDebugInfo")).booleanValue();
jaroslav@601
   215
jaroslav@601
   216
    /**
jaroslav@601
   217
     * Creates an ObjectOutputStream that writes to the specified OutputStream.
jaroslav@601
   218
     * This constructor writes the serialization stream header to the
jaroslav@601
   219
     * underlying stream; callers may wish to flush the stream immediately to
jaroslav@601
   220
     * ensure that constructors for receiving ObjectInputStreams will not block
jaroslav@601
   221
     * when reading the header.
jaroslav@601
   222
     *
jaroslav@601
   223
     * <p>If a security manager is installed, this constructor will check for
jaroslav@601
   224
     * the "enableSubclassImplementation" SerializablePermission when invoked
jaroslav@601
   225
     * directly or indirectly by the constructor of a subclass which overrides
jaroslav@601
   226
     * the ObjectOutputStream.putFields or ObjectOutputStream.writeUnshared
jaroslav@601
   227
     * methods.
jaroslav@601
   228
     *
jaroslav@601
   229
     * @param   out output stream to write to
jaroslav@601
   230
     * @throws  IOException if an I/O error occurs while writing stream header
jaroslav@601
   231
     * @throws  SecurityException if untrusted subclass illegally overrides
jaroslav@601
   232
     *          security-sensitive methods
jaroslav@601
   233
     * @throws  NullPointerException if <code>out</code> is <code>null</code>
jaroslav@601
   234
     * @since   1.4
jaroslav@601
   235
     * @see     ObjectOutputStream#ObjectOutputStream()
jaroslav@601
   236
     * @see     ObjectOutputStream#putFields()
jaroslav@601
   237
     * @see     ObjectInputStream#ObjectInputStream(InputStream)
jaroslav@601
   238
     */
jaroslav@601
   239
    public ObjectOutputStream(OutputStream out) throws IOException {
jaroslav@601
   240
        verifySubclass();
jaroslav@601
   241
        bout = new BlockDataOutputStream(out);
jaroslav@601
   242
        handles = new HandleTable(10, (float) 3.00);
jaroslav@601
   243
        subs = new ReplaceTable(10, (float) 3.00);
jaroslav@601
   244
        enableOverride = false;
jaroslav@601
   245
        writeStreamHeader();
jaroslav@601
   246
        bout.setBlockDataMode(true);
jaroslav@601
   247
        if (extendedDebugInfo) {
jaroslav@601
   248
            debugInfoStack = new DebugTraceInfoStack();
jaroslav@601
   249
        } else {
jaroslav@601
   250
            debugInfoStack = null;
jaroslav@601
   251
        }
jaroslav@601
   252
    }
jaroslav@601
   253
jaroslav@601
   254
    /**
jaroslav@601
   255
     * Provide a way for subclasses that are completely reimplementing
jaroslav@601
   256
     * ObjectOutputStream to not have to allocate private data just used by
jaroslav@601
   257
     * this implementation of ObjectOutputStream.
jaroslav@601
   258
     *
jaroslav@601
   259
     * <p>If there is a security manager installed, this method first calls the
jaroslav@601
   260
     * security manager's <code>checkPermission</code> method with a
jaroslav@601
   261
     * <code>SerializablePermission("enableSubclassImplementation")</code>
jaroslav@601
   262
     * permission to ensure it's ok to enable subclassing.
jaroslav@601
   263
     *
jaroslav@601
   264
     * @throws  SecurityException if a security manager exists and its
jaroslav@601
   265
     *          <code>checkPermission</code> method denies enabling
jaroslav@601
   266
     *          subclassing.
jaroslav@601
   267
     * @see SecurityManager#checkPermission
jaroslav@601
   268
     * @see java.io.SerializablePermission
jaroslav@601
   269
     */
jaroslav@601
   270
    protected ObjectOutputStream() throws IOException, SecurityException {
jaroslav@601
   271
        SecurityManager sm = System.getSecurityManager();
jaroslav@601
   272
        if (sm != null) {
jaroslav@601
   273
            sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
jaroslav@601
   274
        }
jaroslav@601
   275
        bout = null;
jaroslav@601
   276
        handles = null;
jaroslav@601
   277
        subs = null;
jaroslav@601
   278
        enableOverride = true;
jaroslav@601
   279
        debugInfoStack = null;
jaroslav@601
   280
    }
jaroslav@601
   281
jaroslav@601
   282
    /**
jaroslav@601
   283
     * Specify stream protocol version to use when writing the stream.
jaroslav@601
   284
     *
jaroslav@601
   285
     * <p>This routine provides a hook to enable the current version of
jaroslav@601
   286
     * Serialization to write in a format that is backwards compatible to a
jaroslav@601
   287
     * previous version of the stream format.
jaroslav@601
   288
     *
jaroslav@601
   289
     * <p>Every effort will be made to avoid introducing additional
jaroslav@601
   290
     * backwards incompatibilities; however, sometimes there is no
jaroslav@601
   291
     * other alternative.
jaroslav@601
   292
     *
jaroslav@601
   293
     * @param   version use ProtocolVersion from java.io.ObjectStreamConstants.
jaroslav@601
   294
     * @throws  IllegalStateException if called after any objects
jaroslav@601
   295
     *          have been serialized.
jaroslav@601
   296
     * @throws  IllegalArgumentException if invalid version is passed in.
jaroslav@601
   297
     * @throws  IOException if I/O errors occur
jaroslav@601
   298
     * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1
jaroslav@601
   299
     * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_2
jaroslav@601
   300
     * @since   1.2
jaroslav@601
   301
     */
jaroslav@601
   302
    public void useProtocolVersion(int version) throws IOException {
jaroslav@601
   303
        if (handles.size() != 0) {
jaroslav@601
   304
            // REMIND: implement better check for pristine stream?
jaroslav@601
   305
            throw new IllegalStateException("stream non-empty");
jaroslav@601
   306
        }
jaroslav@601
   307
        switch (version) {
jaroslav@601
   308
            case PROTOCOL_VERSION_1:
jaroslav@601
   309
            case PROTOCOL_VERSION_2:
jaroslav@601
   310
                protocol = version;
jaroslav@601
   311
                break;
jaroslav@601
   312
jaroslav@601
   313
            default:
jaroslav@601
   314
                throw new IllegalArgumentException(
jaroslav@601
   315
                    "unknown version: " + version);
jaroslav@601
   316
        }
jaroslav@601
   317
    }
jaroslav@601
   318
jaroslav@601
   319
    /**
jaroslav@601
   320
     * Write the specified object to the ObjectOutputStream.  The class of the
jaroslav@601
   321
     * object, the signature of the class, and the values of the non-transient
jaroslav@601
   322
     * and non-static fields of the class and all of its supertypes are
jaroslav@601
   323
     * written.  Default serialization for a class can be overridden using the
jaroslav@601
   324
     * writeObject and the readObject methods.  Objects referenced by this
jaroslav@601
   325
     * object are written transitively so that a complete equivalent graph of
jaroslav@601
   326
     * objects can be reconstructed by an ObjectInputStream.
jaroslav@601
   327
     *
jaroslav@601
   328
     * <p>Exceptions are thrown for problems with the OutputStream and for
jaroslav@601
   329
     * classes that should not be serialized.  All exceptions are fatal to the
jaroslav@601
   330
     * OutputStream, which is left in an indeterminate state, and it is up to
jaroslav@601
   331
     * the caller to ignore or recover the stream state.
jaroslav@601
   332
     *
jaroslav@601
   333
     * @throws  InvalidClassException Something is wrong with a class used by
jaroslav@601
   334
     *          serialization.
jaroslav@601
   335
     * @throws  NotSerializableException Some object to be serialized does not
jaroslav@601
   336
     *          implement the java.io.Serializable interface.
jaroslav@601
   337
     * @throws  IOException Any exception thrown by the underlying
jaroslav@601
   338
     *          OutputStream.
jaroslav@601
   339
     */
jaroslav@601
   340
    public final void writeObject(Object obj) throws IOException {
jaroslav@601
   341
        if (enableOverride) {
jaroslav@601
   342
            writeObjectOverride(obj);
jaroslav@601
   343
            return;
jaroslav@601
   344
        }
jaroslav@601
   345
        try {
jaroslav@601
   346
            writeObject0(obj, false);
jaroslav@601
   347
        } catch (IOException ex) {
jaroslav@601
   348
            if (depth == 0) {
jaroslav@601
   349
                writeFatalException(ex);
jaroslav@601
   350
            }
jaroslav@601
   351
            throw ex;
jaroslav@601
   352
        }
jaroslav@601
   353
    }
jaroslav@601
   354
jaroslav@601
   355
    /**
jaroslav@601
   356
     * Method used by subclasses to override the default writeObject method.
jaroslav@601
   357
     * This method is called by trusted subclasses of ObjectInputStream that
jaroslav@601
   358
     * constructed ObjectInputStream using the protected no-arg constructor.
jaroslav@601
   359
     * The subclass is expected to provide an override method with the modifier
jaroslav@601
   360
     * "final".
jaroslav@601
   361
     *
jaroslav@601
   362
     * @param   obj object to be written to the underlying stream
jaroslav@601
   363
     * @throws  IOException if there are I/O errors while writing to the
jaroslav@601
   364
     *          underlying stream
jaroslav@601
   365
     * @see #ObjectOutputStream()
jaroslav@601
   366
     * @see #writeObject(Object)
jaroslav@601
   367
     * @since 1.2
jaroslav@601
   368
     */
jaroslav@601
   369
    protected void writeObjectOverride(Object obj) throws IOException {
jaroslav@601
   370
    }
jaroslav@601
   371
jaroslav@601
   372
    /**
jaroslav@601
   373
     * Writes an "unshared" object to the ObjectOutputStream.  This method is
jaroslav@601
   374
     * identical to writeObject, except that it always writes the given object
jaroslav@601
   375
     * as a new, unique object in the stream (as opposed to a back-reference
jaroslav@601
   376
     * pointing to a previously serialized instance).  Specifically:
jaroslav@601
   377
     * <ul>
jaroslav@601
   378
     *   <li>An object written via writeUnshared is always serialized in the
jaroslav@601
   379
     *       same manner as a newly appearing object (an object that has not
jaroslav@601
   380
     *       been written to the stream yet), regardless of whether or not the
jaroslav@601
   381
     *       object has been written previously.
jaroslav@601
   382
     *
jaroslav@601
   383
     *   <li>If writeObject is used to write an object that has been previously
jaroslav@601
   384
     *       written with writeUnshared, the previous writeUnshared operation
jaroslav@601
   385
     *       is treated as if it were a write of a separate object.  In other
jaroslav@601
   386
     *       words, ObjectOutputStream will never generate back-references to
jaroslav@601
   387
     *       object data written by calls to writeUnshared.
jaroslav@601
   388
     * </ul>
jaroslav@601
   389
     * While writing an object via writeUnshared does not in itself guarantee a
jaroslav@601
   390
     * unique reference to the object when it is deserialized, it allows a
jaroslav@601
   391
     * single object to be defined multiple times in a stream, so that multiple
jaroslav@601
   392
     * calls to readUnshared by the receiver will not conflict.  Note that the
jaroslav@601
   393
     * rules described above only apply to the base-level object written with
jaroslav@601
   394
     * writeUnshared, and not to any transitively referenced sub-objects in the
jaroslav@601
   395
     * object graph to be serialized.
jaroslav@601
   396
     *
jaroslav@601
   397
     * <p>ObjectOutputStream subclasses which override this method can only be
jaroslav@601
   398
     * constructed in security contexts possessing the
jaroslav@601
   399
     * "enableSubclassImplementation" SerializablePermission; any attempt to
jaroslav@601
   400
     * instantiate such a subclass without this permission will cause a
jaroslav@601
   401
     * SecurityException to be thrown.
jaroslav@601
   402
     *
jaroslav@601
   403
     * @param   obj object to write to stream
jaroslav@601
   404
     * @throws  NotSerializableException if an object in the graph to be
jaroslav@601
   405
     *          serialized does not implement the Serializable interface
jaroslav@601
   406
     * @throws  InvalidClassException if a problem exists with the class of an
jaroslav@601
   407
     *          object to be serialized
jaroslav@601
   408
     * @throws  IOException if an I/O error occurs during serialization
jaroslav@601
   409
     * @since 1.4
jaroslav@601
   410
     */
jaroslav@601
   411
    public void writeUnshared(Object obj) throws IOException {
jaroslav@601
   412
        try {
jaroslav@601
   413
            writeObject0(obj, true);
jaroslav@601
   414
        } catch (IOException ex) {
jaroslav@601
   415
            if (depth == 0) {
jaroslav@601
   416
                writeFatalException(ex);
jaroslav@601
   417
            }
jaroslav@601
   418
            throw ex;
jaroslav@601
   419
        }
jaroslav@601
   420
    }
jaroslav@601
   421
jaroslav@601
   422
    /**
jaroslav@601
   423
     * Write the non-static and non-transient fields of the current class to
jaroslav@601
   424
     * this stream.  This may only be called from the writeObject method of the
jaroslav@601
   425
     * class being serialized. It will throw the NotActiveException if it is
jaroslav@601
   426
     * called otherwise.
jaroslav@601
   427
     *
jaroslav@601
   428
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   429
     *          <code>OutputStream</code>
jaroslav@601
   430
     */
jaroslav@601
   431
    public void defaultWriteObject() throws IOException {
jaroslav@601
   432
        if ( curContext == null ) {
jaroslav@601
   433
            throw new NotActiveException("not in call to writeObject");
jaroslav@601
   434
        }
jaroslav@601
   435
        Object curObj = curContext.getObj();
jaroslav@601
   436
        ObjectStreamClass curDesc = curContext.getDesc();
jaroslav@601
   437
        bout.setBlockDataMode(false);
jaroslav@601
   438
        defaultWriteFields(curObj, curDesc);
jaroslav@601
   439
        bout.setBlockDataMode(true);
jaroslav@601
   440
    }
jaroslav@601
   441
jaroslav@601
   442
    /**
jaroslav@601
   443
     * Retrieve the object used to buffer persistent fields to be written to
jaroslav@601
   444
     * the stream.  The fields will be written to the stream when writeFields
jaroslav@601
   445
     * method is called.
jaroslav@601
   446
     *
jaroslav@601
   447
     * @return  an instance of the class Putfield that holds the serializable
jaroslav@601
   448
     *          fields
jaroslav@601
   449
     * @throws  IOException if I/O errors occur
jaroslav@601
   450
     * @since 1.2
jaroslav@601
   451
     */
jaroslav@601
   452
    public ObjectOutputStream.PutField putFields() throws IOException {
jaroslav@601
   453
        if (curPut == null) {
jaroslav@601
   454
            if (curContext == null) {
jaroslav@601
   455
                throw new NotActiveException("not in call to writeObject");
jaroslav@601
   456
            }
jaroslav@601
   457
            Object curObj = curContext.getObj();
jaroslav@601
   458
            ObjectStreamClass curDesc = curContext.getDesc();
jaroslav@601
   459
            curPut = new PutFieldImpl(curDesc);
jaroslav@601
   460
        }
jaroslav@601
   461
        return curPut;
jaroslav@601
   462
    }
jaroslav@601
   463
jaroslav@601
   464
    /**
jaroslav@601
   465
     * Write the buffered fields to the stream.
jaroslav@601
   466
     *
jaroslav@601
   467
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   468
     *          stream
jaroslav@601
   469
     * @throws  NotActiveException Called when a classes writeObject method was
jaroslav@601
   470
     *          not called to write the state of the object.
jaroslav@601
   471
     * @since 1.2
jaroslav@601
   472
     */
jaroslav@601
   473
    public void writeFields() throws IOException {
jaroslav@601
   474
        if (curPut == null) {
jaroslav@601
   475
            throw new NotActiveException("no current PutField object");
jaroslav@601
   476
        }
jaroslav@601
   477
        bout.setBlockDataMode(false);
jaroslav@601
   478
        curPut.writeFields();
jaroslav@601
   479
        bout.setBlockDataMode(true);
jaroslav@601
   480
    }
jaroslav@601
   481
jaroslav@601
   482
    /**
jaroslav@601
   483
     * Reset will disregard the state of any objects already written to the
jaroslav@601
   484
     * stream.  The state is reset to be the same as a new ObjectOutputStream.
jaroslav@601
   485
     * The current point in the stream is marked as reset so the corresponding
jaroslav@601
   486
     * ObjectInputStream will be reset at the same point.  Objects previously
jaroslav@601
   487
     * written to the stream will not be refered to as already being in the
jaroslav@601
   488
     * stream.  They will be written to the stream again.
jaroslav@601
   489
     *
jaroslav@601
   490
     * @throws  IOException if reset() is invoked while serializing an object.
jaroslav@601
   491
     */
jaroslav@601
   492
    public void reset() throws IOException {
jaroslav@601
   493
        if (depth != 0) {
jaroslav@601
   494
            throw new IOException("stream active");
jaroslav@601
   495
        }
jaroslav@601
   496
        bout.setBlockDataMode(false);
jaroslav@601
   497
        bout.writeByte(TC_RESET);
jaroslav@601
   498
        clear();
jaroslav@601
   499
        bout.setBlockDataMode(true);
jaroslav@601
   500
    }
jaroslav@601
   501
jaroslav@601
   502
    /**
jaroslav@601
   503
     * Subclasses may implement this method to allow class data to be stored in
jaroslav@601
   504
     * the stream. By default this method does nothing.  The corresponding
jaroslav@601
   505
     * method in ObjectInputStream is resolveClass.  This method is called
jaroslav@601
   506
     * exactly once for each unique class in the stream.  The class name and
jaroslav@601
   507
     * signature will have already been written to the stream.  This method may
jaroslav@601
   508
     * make free use of the ObjectOutputStream to save any representation of
jaroslav@601
   509
     * the class it deems suitable (for example, the bytes of the class file).
jaroslav@601
   510
     * The resolveClass method in the corresponding subclass of
jaroslav@601
   511
     * ObjectInputStream must read and use any data or objects written by
jaroslav@601
   512
     * annotateClass.
jaroslav@601
   513
     *
jaroslav@601
   514
     * @param   cl the class to annotate custom data for
jaroslav@601
   515
     * @throws  IOException Any exception thrown by the underlying
jaroslav@601
   516
     *          OutputStream.
jaroslav@601
   517
     */
jaroslav@601
   518
    protected void annotateClass(Class<?> cl) throws IOException {
jaroslav@601
   519
    }
jaroslav@601
   520
jaroslav@601
   521
    /**
jaroslav@601
   522
     * Subclasses may implement this method to store custom data in the stream
jaroslav@601
   523
     * along with descriptors for dynamic proxy classes.
jaroslav@601
   524
     *
jaroslav@601
   525
     * <p>This method is called exactly once for each unique proxy class
jaroslav@601
   526
     * descriptor in the stream.  The default implementation of this method in
jaroslav@601
   527
     * <code>ObjectOutputStream</code> does nothing.
jaroslav@601
   528
     *
jaroslav@601
   529
     * <p>The corresponding method in <code>ObjectInputStream</code> is
jaroslav@601
   530
     * <code>resolveProxyClass</code>.  For a given subclass of
jaroslav@601
   531
     * <code>ObjectOutputStream</code> that overrides this method, the
jaroslav@601
   532
     * <code>resolveProxyClass</code> method in the corresponding subclass of
jaroslav@601
   533
     * <code>ObjectInputStream</code> must read any data or objects written by
jaroslav@601
   534
     * <code>annotateProxyClass</code>.
jaroslav@601
   535
     *
jaroslav@601
   536
     * @param   cl the proxy class to annotate custom data for
jaroslav@601
   537
     * @throws  IOException any exception thrown by the underlying
jaroslav@601
   538
     *          <code>OutputStream</code>
jaroslav@601
   539
     * @see ObjectInputStream#resolveProxyClass(String[])
jaroslav@601
   540
     * @since   1.3
jaroslav@601
   541
     */
jaroslav@601
   542
    protected void annotateProxyClass(Class<?> cl) throws IOException {
jaroslav@601
   543
    }
jaroslav@601
   544
jaroslav@601
   545
    /**
jaroslav@601
   546
     * This method will allow trusted subclasses of ObjectOutputStream to
jaroslav@601
   547
     * substitute one object for another during serialization. Replacing
jaroslav@601
   548
     * objects is disabled until enableReplaceObject is called. The
jaroslav@601
   549
     * enableReplaceObject method checks that the stream requesting to do
jaroslav@601
   550
     * replacement can be trusted.  The first occurrence of each object written
jaroslav@601
   551
     * into the serialization stream is passed to replaceObject.  Subsequent
jaroslav@601
   552
     * references to the object are replaced by the object returned by the
jaroslav@601
   553
     * original call to replaceObject.  To ensure that the private state of
jaroslav@601
   554
     * objects is not unintentionally exposed, only trusted streams may use
jaroslav@601
   555
     * replaceObject.
jaroslav@601
   556
     *
jaroslav@601
   557
     * <p>The ObjectOutputStream.writeObject method takes a parameter of type
jaroslav@601
   558
     * Object (as opposed to type Serializable) to allow for cases where
jaroslav@601
   559
     * non-serializable objects are replaced by serializable ones.
jaroslav@601
   560
     *
jaroslav@601
   561
     * <p>When a subclass is replacing objects it must insure that either a
jaroslav@601
   562
     * complementary substitution must be made during deserialization or that
jaroslav@601
   563
     * the substituted object is compatible with every field where the
jaroslav@601
   564
     * reference will be stored.  Objects whose type is not a subclass of the
jaroslav@601
   565
     * type of the field or array element abort the serialization by raising an
jaroslav@601
   566
     * exception and the object is not be stored.
jaroslav@601
   567
     *
jaroslav@601
   568
     * <p>This method is called only once when each object is first
jaroslav@601
   569
     * encountered.  All subsequent references to the object will be redirected
jaroslav@601
   570
     * to the new object. This method should return the object to be
jaroslav@601
   571
     * substituted or the original object.
jaroslav@601
   572
     *
jaroslav@601
   573
     * <p>Null can be returned as the object to be substituted, but may cause
jaroslav@601
   574
     * NullReferenceException in classes that contain references to the
jaroslav@601
   575
     * original object since they may be expecting an object instead of
jaroslav@601
   576
     * null.
jaroslav@601
   577
     *
jaroslav@601
   578
     * @param   obj the object to be replaced
jaroslav@601
   579
     * @return  the alternate object that replaced the specified one
jaroslav@601
   580
     * @throws  IOException Any exception thrown by the underlying
jaroslav@601
   581
     *          OutputStream.
jaroslav@601
   582
     */
jaroslav@601
   583
    protected Object replaceObject(Object obj) throws IOException {
jaroslav@601
   584
        return obj;
jaroslav@601
   585
    }
jaroslav@601
   586
jaroslav@601
   587
    /**
jaroslav@601
   588
     * Enable the stream to do replacement of objects in the stream.  When
jaroslav@601
   589
     * enabled, the replaceObject method is called for every object being
jaroslav@601
   590
     * serialized.
jaroslav@601
   591
     *
jaroslav@601
   592
     * <p>If <code>enable</code> is true, and there is a security manager
jaroslav@601
   593
     * installed, this method first calls the security manager's
jaroslav@601
   594
     * <code>checkPermission</code> method with a
jaroslav@601
   595
     * <code>SerializablePermission("enableSubstitution")</code> permission to
jaroslav@601
   596
     * ensure it's ok to enable the stream to do replacement of objects in the
jaroslav@601
   597
     * stream.
jaroslav@601
   598
     *
jaroslav@601
   599
     * @param   enable boolean parameter to enable replacement of objects
jaroslav@601
   600
     * @return  the previous setting before this method was invoked
jaroslav@601
   601
     * @throws  SecurityException if a security manager exists and its
jaroslav@601
   602
     *          <code>checkPermission</code> method denies enabling the stream
jaroslav@601
   603
     *          to do replacement of objects in the stream.
jaroslav@601
   604
     * @see SecurityManager#checkPermission
jaroslav@601
   605
     * @see java.io.SerializablePermission
jaroslav@601
   606
     */
jaroslav@601
   607
    protected boolean enableReplaceObject(boolean enable)
jaroslav@601
   608
        throws SecurityException
jaroslav@601
   609
    {
jaroslav@601
   610
        if (enable == enableReplace) {
jaroslav@601
   611
            return enable;
jaroslav@601
   612
        }
jaroslav@601
   613
        if (enable) {
jaroslav@601
   614
            SecurityManager sm = System.getSecurityManager();
jaroslav@601
   615
            if (sm != null) {
jaroslav@601
   616
                sm.checkPermission(SUBSTITUTION_PERMISSION);
jaroslav@601
   617
            }
jaroslav@601
   618
        }
jaroslav@601
   619
        enableReplace = enable;
jaroslav@601
   620
        return !enableReplace;
jaroslav@601
   621
    }
jaroslav@601
   622
jaroslav@601
   623
    /**
jaroslav@601
   624
     * The writeStreamHeader method is provided so subclasses can append or
jaroslav@601
   625
     * prepend their own header to the stream.  It writes the magic number and
jaroslav@601
   626
     * version to the stream.
jaroslav@601
   627
     *
jaroslav@601
   628
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   629
     *          stream
jaroslav@601
   630
     */
jaroslav@601
   631
    protected void writeStreamHeader() throws IOException {
jaroslav@601
   632
        bout.writeShort(STREAM_MAGIC);
jaroslav@601
   633
        bout.writeShort(STREAM_VERSION);
jaroslav@601
   634
    }
jaroslav@601
   635
jaroslav@601
   636
    /**
jaroslav@601
   637
     * Write the specified class descriptor to the ObjectOutputStream.  Class
jaroslav@601
   638
     * descriptors are used to identify the classes of objects written to the
jaroslav@601
   639
     * stream.  Subclasses of ObjectOutputStream may override this method to
jaroslav@601
   640
     * customize the way in which class descriptors are written to the
jaroslav@601
   641
     * serialization stream.  The corresponding method in ObjectInputStream,
jaroslav@601
   642
     * <code>readClassDescriptor</code>, should then be overridden to
jaroslav@601
   643
     * reconstitute the class descriptor from its custom stream representation.
jaroslav@601
   644
     * By default, this method writes class descriptors according to the format
jaroslav@601
   645
     * defined in the Object Serialization specification.
jaroslav@601
   646
     *
jaroslav@601
   647
     * <p>Note that this method will only be called if the ObjectOutputStream
jaroslav@601
   648
     * is not using the old serialization stream format (set by calling
jaroslav@601
   649
     * ObjectOutputStream's <code>useProtocolVersion</code> method).  If this
jaroslav@601
   650
     * serialization stream is using the old format
jaroslav@601
   651
     * (<code>PROTOCOL_VERSION_1</code>), the class descriptor will be written
jaroslav@601
   652
     * internally in a manner that cannot be overridden or customized.
jaroslav@601
   653
     *
jaroslav@601
   654
     * @param   desc class descriptor to write to the stream
jaroslav@601
   655
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   656
     * @see java.io.ObjectInputStream#readClassDescriptor()
jaroslav@601
   657
     * @see #useProtocolVersion(int)
jaroslav@601
   658
     * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1
jaroslav@601
   659
     * @since 1.3
jaroslav@601
   660
     */
jaroslav@601
   661
    protected void writeClassDescriptor(ObjectStreamClass desc)
jaroslav@601
   662
        throws IOException
jaroslav@601
   663
    {
jaroslav@601
   664
        desc.writeNonProxy(this);
jaroslav@601
   665
    }
jaroslav@601
   666
jaroslav@601
   667
    /**
jaroslav@601
   668
     * Writes a byte. This method will block until the byte is actually
jaroslav@601
   669
     * written.
jaroslav@601
   670
     *
jaroslav@601
   671
     * @param   val the byte to be written to the stream
jaroslav@601
   672
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   673
     */
jaroslav@601
   674
    public void write(int val) throws IOException {
jaroslav@601
   675
        bout.write(val);
jaroslav@601
   676
    }
jaroslav@601
   677
jaroslav@601
   678
    /**
jaroslav@601
   679
     * Writes an array of bytes. This method will block until the bytes are
jaroslav@601
   680
     * actually written.
jaroslav@601
   681
     *
jaroslav@601
   682
     * @param   buf the data to be written
jaroslav@601
   683
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   684
     */
jaroslav@601
   685
    public void write(byte[] buf) throws IOException {
jaroslav@601
   686
        bout.write(buf, 0, buf.length, false);
jaroslav@601
   687
    }
jaroslav@601
   688
jaroslav@601
   689
    /**
jaroslav@601
   690
     * Writes a sub array of bytes.
jaroslav@601
   691
     *
jaroslav@601
   692
     * @param   buf the data to be written
jaroslav@601
   693
     * @param   off the start offset in the data
jaroslav@601
   694
     * @param   len the number of bytes that are written
jaroslav@601
   695
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   696
     */
jaroslav@601
   697
    public void write(byte[] buf, int off, int len) throws IOException {
jaroslav@601
   698
        if (buf == null) {
jaroslav@601
   699
            throw new NullPointerException();
jaroslav@601
   700
        }
jaroslav@601
   701
        int endoff = off + len;
jaroslav@601
   702
        if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
jaroslav@601
   703
            throw new IndexOutOfBoundsException();
jaroslav@601
   704
        }
jaroslav@601
   705
        bout.write(buf, off, len, false);
jaroslav@601
   706
    }
jaroslav@601
   707
jaroslav@601
   708
    /**
jaroslav@601
   709
     * Flushes the stream. This will write any buffered output bytes and flush
jaroslav@601
   710
     * through to the underlying stream.
jaroslav@601
   711
     *
jaroslav@601
   712
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   713
     */
jaroslav@601
   714
    public void flush() throws IOException {
jaroslav@601
   715
        bout.flush();
jaroslav@601
   716
    }
jaroslav@601
   717
jaroslav@601
   718
    /**
jaroslav@601
   719
     * Drain any buffered data in ObjectOutputStream.  Similar to flush but
jaroslav@601
   720
     * does not propagate the flush to the underlying stream.
jaroslav@601
   721
     *
jaroslav@601
   722
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   723
     *          stream
jaroslav@601
   724
     */
jaroslav@601
   725
    protected void drain() throws IOException {
jaroslav@601
   726
        bout.drain();
jaroslav@601
   727
    }
jaroslav@601
   728
jaroslav@601
   729
    /**
jaroslav@601
   730
     * Closes the stream. This method must be called to release any resources
jaroslav@601
   731
     * associated with the stream.
jaroslav@601
   732
     *
jaroslav@601
   733
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   734
     */
jaroslav@601
   735
    public void close() throws IOException {
jaroslav@601
   736
        flush();
jaroslav@601
   737
        clear();
jaroslav@601
   738
        bout.close();
jaroslav@601
   739
    }
jaroslav@601
   740
jaroslav@601
   741
    /**
jaroslav@601
   742
     * Writes a boolean.
jaroslav@601
   743
     *
jaroslav@601
   744
     * @param   val the boolean to be written
jaroslav@601
   745
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   746
     *          stream
jaroslav@601
   747
     */
jaroslav@601
   748
    public void writeBoolean(boolean val) throws IOException {
jaroslav@601
   749
        bout.writeBoolean(val);
jaroslav@601
   750
    }
jaroslav@601
   751
jaroslav@601
   752
    /**
jaroslav@601
   753
     * Writes an 8 bit byte.
jaroslav@601
   754
     *
jaroslav@601
   755
     * @param   val the byte value to be written
jaroslav@601
   756
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   757
     *          stream
jaroslav@601
   758
     */
jaroslav@601
   759
    public void writeByte(int val) throws IOException  {
jaroslav@601
   760
        bout.writeByte(val);
jaroslav@601
   761
    }
jaroslav@601
   762
jaroslav@601
   763
    /**
jaroslav@601
   764
     * Writes a 16 bit short.
jaroslav@601
   765
     *
jaroslav@601
   766
     * @param   val the short value to be written
jaroslav@601
   767
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   768
     *          stream
jaroslav@601
   769
     */
jaroslav@601
   770
    public void writeShort(int val)  throws IOException {
jaroslav@601
   771
        bout.writeShort(val);
jaroslav@601
   772
    }
jaroslav@601
   773
jaroslav@601
   774
    /**
jaroslav@601
   775
     * Writes a 16 bit char.
jaroslav@601
   776
     *
jaroslav@601
   777
     * @param   val the char value to be written
jaroslav@601
   778
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   779
     *          stream
jaroslav@601
   780
     */
jaroslav@601
   781
    public void writeChar(int val)  throws IOException {
jaroslav@601
   782
        bout.writeChar(val);
jaroslav@601
   783
    }
jaroslav@601
   784
jaroslav@601
   785
    /**
jaroslav@601
   786
     * Writes a 32 bit int.
jaroslav@601
   787
     *
jaroslav@601
   788
     * @param   val the integer value to be written
jaroslav@601
   789
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   790
     *          stream
jaroslav@601
   791
     */
jaroslav@601
   792
    public void writeInt(int val)  throws IOException {
jaroslav@601
   793
        bout.writeInt(val);
jaroslav@601
   794
    }
jaroslav@601
   795
jaroslav@601
   796
    /**
jaroslav@601
   797
     * Writes a 64 bit long.
jaroslav@601
   798
     *
jaroslav@601
   799
     * @param   val the long value to be written
jaroslav@601
   800
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   801
     *          stream
jaroslav@601
   802
     */
jaroslav@601
   803
    public void writeLong(long val)  throws IOException {
jaroslav@601
   804
        bout.writeLong(val);
jaroslav@601
   805
    }
jaroslav@601
   806
jaroslav@601
   807
    /**
jaroslav@601
   808
     * Writes a 32 bit float.
jaroslav@601
   809
     *
jaroslav@601
   810
     * @param   val the float value to be written
jaroslav@601
   811
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   812
     *          stream
jaroslav@601
   813
     */
jaroslav@601
   814
    public void writeFloat(float val) throws IOException {
jaroslav@601
   815
        bout.writeFloat(val);
jaroslav@601
   816
    }
jaroslav@601
   817
jaroslav@601
   818
    /**
jaroslav@601
   819
     * Writes a 64 bit double.
jaroslav@601
   820
     *
jaroslav@601
   821
     * @param   val the double value to be written
jaroslav@601
   822
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   823
     *          stream
jaroslav@601
   824
     */
jaroslav@601
   825
    public void writeDouble(double val) throws IOException {
jaroslav@601
   826
        bout.writeDouble(val);
jaroslav@601
   827
    }
jaroslav@601
   828
jaroslav@601
   829
    /**
jaroslav@601
   830
     * Writes a String as a sequence of bytes.
jaroslav@601
   831
     *
jaroslav@601
   832
     * @param   str the String of bytes to be written
jaroslav@601
   833
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   834
     *          stream
jaroslav@601
   835
     */
jaroslav@601
   836
    public void writeBytes(String str) throws IOException {
jaroslav@601
   837
        bout.writeBytes(str);
jaroslav@601
   838
    }
jaroslav@601
   839
jaroslav@601
   840
    /**
jaroslav@601
   841
     * Writes a String as a sequence of chars.
jaroslav@601
   842
     *
jaroslav@601
   843
     * @param   str the String of chars to be written
jaroslav@601
   844
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   845
     *          stream
jaroslav@601
   846
     */
jaroslav@601
   847
    public void writeChars(String str) throws IOException {
jaroslav@601
   848
        bout.writeChars(str);
jaroslav@601
   849
    }
jaroslav@601
   850
jaroslav@601
   851
    /**
jaroslav@601
   852
     * Primitive data write of this String in
jaroslav@601
   853
     * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
jaroslav@601
   854
     * format.  Note that there is a
jaroslav@601
   855
     * significant difference between writing a String into the stream as
jaroslav@601
   856
     * primitive data or as an Object. A String instance written by writeObject
jaroslav@601
   857
     * is written into the stream as a String initially. Future writeObject()
jaroslav@601
   858
     * calls write references to the string into the stream.
jaroslav@601
   859
     *
jaroslav@601
   860
     * @param   str the String to be written
jaroslav@601
   861
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   862
     *          stream
jaroslav@601
   863
     */
jaroslav@601
   864
    public void writeUTF(String str) throws IOException {
jaroslav@601
   865
        bout.writeUTF(str);
jaroslav@601
   866
    }
jaroslav@601
   867
jaroslav@601
   868
    /**
jaroslav@601
   869
     * Provide programmatic access to the persistent fields to be written
jaroslav@601
   870
     * to ObjectOutput.
jaroslav@601
   871
     *
jaroslav@601
   872
     * @since 1.2
jaroslav@601
   873
     */
jaroslav@601
   874
    public static abstract class PutField {
jaroslav@601
   875
jaroslav@601
   876
        /**
jaroslav@601
   877
         * Put the value of the named boolean field into the persistent field.
jaroslav@601
   878
         *
jaroslav@601
   879
         * @param  name the name of the serializable field
jaroslav@601
   880
         * @param  val the value to assign to the field
jaroslav@601
   881
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   882
         * match the name of a serializable field for the class whose fields
jaroslav@601
   883
         * are being written, or if the type of the named field is not
jaroslav@601
   884
         * <code>boolean</code>
jaroslav@601
   885
         */
jaroslav@601
   886
        public abstract void put(String name, boolean val);
jaroslav@601
   887
jaroslav@601
   888
        /**
jaroslav@601
   889
         * Put the value of the named byte field into the persistent field.
jaroslav@601
   890
         *
jaroslav@601
   891
         * @param  name the name of the serializable field
jaroslav@601
   892
         * @param  val the value to assign to the field
jaroslav@601
   893
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   894
         * match the name of a serializable field for the class whose fields
jaroslav@601
   895
         * are being written, or if the type of the named field is not
jaroslav@601
   896
         * <code>byte</code>
jaroslav@601
   897
         */
jaroslav@601
   898
        public abstract void put(String name, byte val);
jaroslav@601
   899
jaroslav@601
   900
        /**
jaroslav@601
   901
         * Put the value of the named char field into the persistent field.
jaroslav@601
   902
         *
jaroslav@601
   903
         * @param  name the name of the serializable field
jaroslav@601
   904
         * @param  val the value to assign to the field
jaroslav@601
   905
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   906
         * match the name of a serializable field for the class whose fields
jaroslav@601
   907
         * are being written, or if the type of the named field is not
jaroslav@601
   908
         * <code>char</code>
jaroslav@601
   909
         */
jaroslav@601
   910
        public abstract void put(String name, char val);
jaroslav@601
   911
jaroslav@601
   912
        /**
jaroslav@601
   913
         * Put the value of the named short field into the persistent field.
jaroslav@601
   914
         *
jaroslav@601
   915
         * @param  name the name of the serializable field
jaroslav@601
   916
         * @param  val the value to assign to the field
jaroslav@601
   917
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   918
         * match the name of a serializable field for the class whose fields
jaroslav@601
   919
         * are being written, or if the type of the named field is not
jaroslav@601
   920
         * <code>short</code>
jaroslav@601
   921
         */
jaroslav@601
   922
        public abstract void put(String name, short val);
jaroslav@601
   923
jaroslav@601
   924
        /**
jaroslav@601
   925
         * Put the value of the named int field into the persistent field.
jaroslav@601
   926
         *
jaroslav@601
   927
         * @param  name the name of the serializable field
jaroslav@601
   928
         * @param  val the value to assign to the field
jaroslav@601
   929
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   930
         * match the name of a serializable field for the class whose fields
jaroslav@601
   931
         * are being written, or if the type of the named field is not
jaroslav@601
   932
         * <code>int</code>
jaroslav@601
   933
         */
jaroslav@601
   934
        public abstract void put(String name, int val);
jaroslav@601
   935
jaroslav@601
   936
        /**
jaroslav@601
   937
         * Put the value of the named long field into the persistent field.
jaroslav@601
   938
         *
jaroslav@601
   939
         * @param  name the name of the serializable field
jaroslav@601
   940
         * @param  val the value to assign to the field
jaroslav@601
   941
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   942
         * match the name of a serializable field for the class whose fields
jaroslav@601
   943
         * are being written, or if the type of the named field is not
jaroslav@601
   944
         * <code>long</code>
jaroslav@601
   945
         */
jaroslav@601
   946
        public abstract void put(String name, long val);
jaroslav@601
   947
jaroslav@601
   948
        /**
jaroslav@601
   949
         * Put the value of the named float field into the persistent field.
jaroslav@601
   950
         *
jaroslav@601
   951
         * @param  name the name of the serializable field
jaroslav@601
   952
         * @param  val the value to assign to the field
jaroslav@601
   953
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   954
         * match the name of a serializable field for the class whose fields
jaroslav@601
   955
         * are being written, or if the type of the named field is not
jaroslav@601
   956
         * <code>float</code>
jaroslav@601
   957
         */
jaroslav@601
   958
        public abstract void put(String name, float val);
jaroslav@601
   959
jaroslav@601
   960
        /**
jaroslav@601
   961
         * Put the value of the named double field into the persistent field.
jaroslav@601
   962
         *
jaroslav@601
   963
         * @param  name the name of the serializable field
jaroslav@601
   964
         * @param  val the value to assign to the field
jaroslav@601
   965
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   966
         * match the name of a serializable field for the class whose fields
jaroslav@601
   967
         * are being written, or if the type of the named field is not
jaroslav@601
   968
         * <code>double</code>
jaroslav@601
   969
         */
jaroslav@601
   970
        public abstract void put(String name, double val);
jaroslav@601
   971
jaroslav@601
   972
        /**
jaroslav@601
   973
         * Put the value of the named Object field into the persistent field.
jaroslav@601
   974
         *
jaroslav@601
   975
         * @param  name the name of the serializable field
jaroslav@601
   976
         * @param  val the value to assign to the field
jaroslav@601
   977
         *         (which may be <code>null</code>)
jaroslav@601
   978
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   979
         * match the name of a serializable field for the class whose fields
jaroslav@601
   980
         * are being written, or if the type of the named field is not a
jaroslav@601
   981
         * reference type
jaroslav@601
   982
         */
jaroslav@601
   983
        public abstract void put(String name, Object val);
jaroslav@601
   984
jaroslav@601
   985
        /**
jaroslav@601
   986
         * Write the data and fields to the specified ObjectOutput stream,
jaroslav@601
   987
         * which must be the same stream that produced this
jaroslav@601
   988
         * <code>PutField</code> object.
jaroslav@601
   989
         *
jaroslav@601
   990
         * @param  out the stream to write the data and fields to
jaroslav@601
   991
         * @throws IOException if I/O errors occur while writing to the
jaroslav@601
   992
         *         underlying stream
jaroslav@601
   993
         * @throws IllegalArgumentException if the specified stream is not
jaroslav@601
   994
         *         the same stream that produced this <code>PutField</code>
jaroslav@601
   995
         *         object
jaroslav@601
   996
         * @deprecated This method does not write the values contained by this
jaroslav@601
   997
         *         <code>PutField</code> object in a proper format, and may
jaroslav@601
   998
         *         result in corruption of the serialization stream.  The
jaroslav@601
   999
         *         correct way to write <code>PutField</code> data is by
jaroslav@601
  1000
         *         calling the {@link java.io.ObjectOutputStream#writeFields()}
jaroslav@601
  1001
         *         method.
jaroslav@601
  1002
         */
jaroslav@601
  1003
        @Deprecated
jaroslav@601
  1004
        public abstract void write(ObjectOutput out) throws IOException;
jaroslav@601
  1005
    }
jaroslav@601
  1006
jaroslav@601
  1007
jaroslav@601
  1008
    /**
jaroslav@601
  1009
     * Returns protocol version in use.
jaroslav@601
  1010
     */
jaroslav@601
  1011
    int getProtocolVersion() {
jaroslav@601
  1012
        return protocol;
jaroslav@601
  1013
    }
jaroslav@601
  1014
jaroslav@601
  1015
    /**
jaroslav@601
  1016
     * Writes string without allowing it to be replaced in stream.  Used by
jaroslav@601
  1017
     * ObjectStreamClass to write class descriptor type strings.
jaroslav@601
  1018
     */
jaroslav@601
  1019
    void writeTypeString(String str) throws IOException {
jaroslav@601
  1020
        int handle;
jaroslav@601
  1021
        if (str == null) {
jaroslav@601
  1022
            writeNull();
jaroslav@601
  1023
        } else if ((handle = handles.lookup(str)) != -1) {
jaroslav@601
  1024
            writeHandle(handle);
jaroslav@601
  1025
        } else {
jaroslav@601
  1026
            writeString(str, false);
jaroslav@601
  1027
        }
jaroslav@601
  1028
    }
jaroslav@601
  1029
jaroslav@601
  1030
    /**
jaroslav@601
  1031
     * Verifies that this (possibly subclass) instance can be constructed
jaroslav@601
  1032
     * without violating security constraints: the subclass must not override
jaroslav@601
  1033
     * security-sensitive non-final methods, or else the
jaroslav@601
  1034
     * "enableSubclassImplementation" SerializablePermission is checked.
jaroslav@601
  1035
     */
jaroslav@601
  1036
    private void verifySubclass() {
jaroslav@601
  1037
        Class cl = getClass();
jaroslav@601
  1038
        if (cl == ObjectOutputStream.class) {
jaroslav@601
  1039
            return;
jaroslav@601
  1040
        }
jaroslav@601
  1041
        SecurityManager sm = System.getSecurityManager();
jaroslav@601
  1042
        if (sm == null) {
jaroslav@601
  1043
            return;
jaroslav@601
  1044
        }
jaroslav@601
  1045
        processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
jaroslav@601
  1046
        WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
jaroslav@601
  1047
        Boolean result = Caches.subclassAudits.get(key);
jaroslav@601
  1048
        if (result == null) {
jaroslav@601
  1049
            result = Boolean.valueOf(auditSubclass(cl));
jaroslav@601
  1050
            Caches.subclassAudits.putIfAbsent(key, result);
jaroslav@601
  1051
        }
jaroslav@601
  1052
        if (result.booleanValue()) {
jaroslav@601
  1053
            return;
jaroslav@601
  1054
        }
jaroslav@601
  1055
        sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
jaroslav@601
  1056
    }
jaroslav@601
  1057
jaroslav@601
  1058
    /**
jaroslav@601
  1059
     * Performs reflective checks on given subclass to verify that it doesn't
jaroslav@601
  1060
     * override security-sensitive non-final methods.  Returns true if subclass
jaroslav@601
  1061
     * is "safe", false otherwise.
jaroslav@601
  1062
     */
jaroslav@601
  1063
    private static boolean auditSubclass(final Class subcl) {
jaroslav@601
  1064
        Boolean result = AccessController.doPrivileged(
jaroslav@601
  1065
            new PrivilegedAction<Boolean>() {
jaroslav@601
  1066
                public Boolean run() {
jaroslav@601
  1067
                    for (Class cl = subcl;
jaroslav@601
  1068
                         cl != ObjectOutputStream.class;
jaroslav@601
  1069
                         cl = cl.getSuperclass())
jaroslav@601
  1070
                    {
jaroslav@601
  1071
                        try {
jaroslav@601
  1072
                            cl.getDeclaredMethod(
jaroslav@601
  1073
                                "writeUnshared", new Class[] { Object.class });
jaroslav@601
  1074
                            return Boolean.FALSE;
jaroslav@601
  1075
                        } catch (NoSuchMethodException ex) {
jaroslav@601
  1076
                        }
jaroslav@601
  1077
                        try {
jaroslav@601
  1078
                            cl.getDeclaredMethod("putFields", (Class[]) null);
jaroslav@601
  1079
                            return Boolean.FALSE;
jaroslav@601
  1080
                        } catch (NoSuchMethodException ex) {
jaroslav@601
  1081
                        }
jaroslav@601
  1082
                    }
jaroslav@601
  1083
                    return Boolean.TRUE;
jaroslav@601
  1084
                }
jaroslav@601
  1085
            }
jaroslav@601
  1086
        );
jaroslav@601
  1087
        return result.booleanValue();
jaroslav@601
  1088
    }
jaroslav@601
  1089
jaroslav@601
  1090
    /**
jaroslav@601
  1091
     * Clears internal data structures.
jaroslav@601
  1092
     */
jaroslav@601
  1093
    private void clear() {
jaroslav@601
  1094
        subs.clear();
jaroslav@601
  1095
        handles.clear();
jaroslav@601
  1096
    }
jaroslav@601
  1097
jaroslav@601
  1098
    /**
jaroslav@601
  1099
     * Underlying writeObject/writeUnshared implementation.
jaroslav@601
  1100
     */
jaroslav@601
  1101
    private void writeObject0(Object obj, boolean unshared)
jaroslav@601
  1102
        throws IOException
jaroslav@601
  1103
    {
jaroslav@601
  1104
        boolean oldMode = bout.setBlockDataMode(false);
jaroslav@601
  1105
        depth++;
jaroslav@601
  1106
        try {
jaroslav@601
  1107
            // handle previously written and non-replaceable objects
jaroslav@601
  1108
            int h;
jaroslav@601
  1109
            if ((obj = subs.lookup(obj)) == null) {
jaroslav@601
  1110
                writeNull();
jaroslav@601
  1111
                return;
jaroslav@601
  1112
            } else if (!unshared && (h = handles.lookup(obj)) != -1) {
jaroslav@601
  1113
                writeHandle(h);
jaroslav@601
  1114
                return;
jaroslav@601
  1115
            } else if (obj instanceof Class) {
jaroslav@601
  1116
                writeClass((Class) obj, unshared);
jaroslav@601
  1117
                return;
jaroslav@601
  1118
            } else if (obj instanceof ObjectStreamClass) {
jaroslav@601
  1119
                writeClassDesc((ObjectStreamClass) obj, unshared);
jaroslav@601
  1120
                return;
jaroslav@601
  1121
            }
jaroslav@601
  1122
jaroslav@601
  1123
            // check for replacement object
jaroslav@601
  1124
            Object orig = obj;
jaroslav@601
  1125
            Class cl = obj.getClass();
jaroslav@601
  1126
            ObjectStreamClass desc;
jaroslav@601
  1127
            for (;;) {
jaroslav@601
  1128
                // REMIND: skip this check for strings/arrays?
jaroslav@601
  1129
                Class repCl;
jaroslav@601
  1130
                desc = ObjectStreamClass.lookup(cl, true);
jaroslav@601
  1131
                if (!desc.hasWriteReplaceMethod() ||
jaroslav@601
  1132
                    (obj = desc.invokeWriteReplace(obj)) == null ||
jaroslav@601
  1133
                    (repCl = obj.getClass()) == cl)
jaroslav@601
  1134
                {
jaroslav@601
  1135
                    break;
jaroslav@601
  1136
                }
jaroslav@601
  1137
                cl = repCl;
jaroslav@601
  1138
            }
jaroslav@601
  1139
            if (enableReplace) {
jaroslav@601
  1140
                Object rep = replaceObject(obj);
jaroslav@601
  1141
                if (rep != obj && rep != null) {
jaroslav@601
  1142
                    cl = rep.getClass();
jaroslav@601
  1143
                    desc = ObjectStreamClass.lookup(cl, true);
jaroslav@601
  1144
                }
jaroslav@601
  1145
                obj = rep;
jaroslav@601
  1146
            }
jaroslav@601
  1147
jaroslav@601
  1148
            // if object replaced, run through original checks a second time
jaroslav@601
  1149
            if (obj != orig) {
jaroslav@601
  1150
                subs.assign(orig, obj);
jaroslav@601
  1151
                if (obj == null) {
jaroslav@601
  1152
                    writeNull();
jaroslav@601
  1153
                    return;
jaroslav@601
  1154
                } else if (!unshared && (h = handles.lookup(obj)) != -1) {
jaroslav@601
  1155
                    writeHandle(h);
jaroslav@601
  1156
                    return;
jaroslav@601
  1157
                } else if (obj instanceof Class) {
jaroslav@601
  1158
                    writeClass((Class) obj, unshared);
jaroslav@601
  1159
                    return;
jaroslav@601
  1160
                } else if (obj instanceof ObjectStreamClass) {
jaroslav@601
  1161
                    writeClassDesc((ObjectStreamClass) obj, unshared);
jaroslav@601
  1162
                    return;
jaroslav@601
  1163
                }
jaroslav@601
  1164
            }
jaroslav@601
  1165
jaroslav@601
  1166
            // remaining cases
jaroslav@601
  1167
            if (obj instanceof String) {
jaroslav@601
  1168
                writeString((String) obj, unshared);
jaroslav@601
  1169
            } else if (cl.isArray()) {
jaroslav@601
  1170
                writeArray(obj, desc, unshared);
jaroslav@601
  1171
            } else if (obj instanceof Enum) {
jaroslav@601
  1172
                writeEnum((Enum) obj, desc, unshared);
jaroslav@601
  1173
            } else if (obj instanceof Serializable) {
jaroslav@601
  1174
                writeOrdinaryObject(obj, desc, unshared);
jaroslav@601
  1175
            } else {
jaroslav@601
  1176
                if (extendedDebugInfo) {
jaroslav@601
  1177
                    throw new NotSerializableException(
jaroslav@601
  1178
                        cl.getName() + "\n" + debugInfoStack.toString());
jaroslav@601
  1179
                } else {
jaroslav@601
  1180
                    throw new NotSerializableException(cl.getName());
jaroslav@601
  1181
                }
jaroslav@601
  1182
            }
jaroslav@601
  1183
        } finally {
jaroslav@601
  1184
            depth--;
jaroslav@601
  1185
            bout.setBlockDataMode(oldMode);
jaroslav@601
  1186
        }
jaroslav@601
  1187
    }
jaroslav@601
  1188
jaroslav@601
  1189
    /**
jaroslav@601
  1190
     * Writes null code to stream.
jaroslav@601
  1191
     */
jaroslav@601
  1192
    private void writeNull() throws IOException {
jaroslav@601
  1193
        bout.writeByte(TC_NULL);
jaroslav@601
  1194
    }
jaroslav@601
  1195
jaroslav@601
  1196
    /**
jaroslav@601
  1197
     * Writes given object handle to stream.
jaroslav@601
  1198
     */
jaroslav@601
  1199
    private void writeHandle(int handle) throws IOException {
jaroslav@601
  1200
        bout.writeByte(TC_REFERENCE);
jaroslav@601
  1201
        bout.writeInt(baseWireHandle + handle);
jaroslav@601
  1202
    }
jaroslav@601
  1203
jaroslav@601
  1204
    /**
jaroslav@601
  1205
     * Writes representation of given class to stream.
jaroslav@601
  1206
     */
jaroslav@601
  1207
    private void writeClass(Class cl, boolean unshared) throws IOException {
jaroslav@601
  1208
        bout.writeByte(TC_CLASS);
jaroslav@601
  1209
        writeClassDesc(ObjectStreamClass.lookup(cl, true), false);
jaroslav@601
  1210
        handles.assign(unshared ? null : cl);
jaroslav@601
  1211
    }
jaroslav@601
  1212
jaroslav@601
  1213
    /**
jaroslav@601
  1214
     * Writes representation of given class descriptor to stream.
jaroslav@601
  1215
     */
jaroslav@601
  1216
    private void writeClassDesc(ObjectStreamClass desc, boolean unshared)
jaroslav@601
  1217
        throws IOException
jaroslav@601
  1218
    {
jaroslav@601
  1219
        int handle;
jaroslav@601
  1220
        if (desc == null) {
jaroslav@601
  1221
            writeNull();
jaroslav@601
  1222
        } else if (!unshared && (handle = handles.lookup(desc)) != -1) {
jaroslav@601
  1223
            writeHandle(handle);
jaroslav@601
  1224
        } else if (desc.isProxy()) {
jaroslav@601
  1225
            writeProxyDesc(desc, unshared);
jaroslav@601
  1226
        } else {
jaroslav@601
  1227
            writeNonProxyDesc(desc, unshared);
jaroslav@601
  1228
        }
jaroslav@601
  1229
    }
jaroslav@601
  1230
jaroslav@601
  1231
    /**
jaroslav@601
  1232
     * Writes class descriptor representing a dynamic proxy class to stream.
jaroslav@601
  1233
     */
jaroslav@601
  1234
    private void writeProxyDesc(ObjectStreamClass desc, boolean unshared)
jaroslav@601
  1235
        throws IOException
jaroslav@601
  1236
    {
jaroslav@601
  1237
        bout.writeByte(TC_PROXYCLASSDESC);
jaroslav@601
  1238
        handles.assign(unshared ? null : desc);
jaroslav@601
  1239
jaroslav@601
  1240
        Class cl = desc.forClass();
jaroslav@601
  1241
        Class[] ifaces = cl.getInterfaces();
jaroslav@601
  1242
        bout.writeInt(ifaces.length);
jaroslav@601
  1243
        for (int i = 0; i < ifaces.length; i++) {
jaroslav@601
  1244
            bout.writeUTF(ifaces[i].getName());
jaroslav@601
  1245
        }
jaroslav@601
  1246
jaroslav@601
  1247
        bout.setBlockDataMode(true);
jaroslav@601
  1248
        annotateProxyClass(cl);
jaroslav@601
  1249
        bout.setBlockDataMode(false);
jaroslav@601
  1250
        bout.writeByte(TC_ENDBLOCKDATA);
jaroslav@601
  1251
jaroslav@601
  1252
        writeClassDesc(desc.getSuperDesc(), false);
jaroslav@601
  1253
    }
jaroslav@601
  1254
jaroslav@601
  1255
    /**
jaroslav@601
  1256
     * Writes class descriptor representing a standard (i.e., not a dynamic
jaroslav@601
  1257
     * proxy) class to stream.
jaroslav@601
  1258
     */
jaroslav@601
  1259
    private void writeNonProxyDesc(ObjectStreamClass desc, boolean unshared)
jaroslav@601
  1260
        throws IOException
jaroslav@601
  1261
    {
jaroslav@601
  1262
        bout.writeByte(TC_CLASSDESC);
jaroslav@601
  1263
        handles.assign(unshared ? null : desc);
jaroslav@601
  1264
jaroslav@601
  1265
        if (protocol == PROTOCOL_VERSION_1) {
jaroslav@601
  1266
            // do not invoke class descriptor write hook with old protocol
jaroslav@601
  1267
            desc.writeNonProxy(this);
jaroslav@601
  1268
        } else {
jaroslav@601
  1269
            writeClassDescriptor(desc);
jaroslav@601
  1270
        }
jaroslav@601
  1271
jaroslav@601
  1272
        Class cl = desc.forClass();
jaroslav@601
  1273
        bout.setBlockDataMode(true);
jaroslav@601
  1274
        annotateClass(cl);
jaroslav@601
  1275
        bout.setBlockDataMode(false);
jaroslav@601
  1276
        bout.writeByte(TC_ENDBLOCKDATA);
jaroslav@601
  1277
jaroslav@601
  1278
        writeClassDesc(desc.getSuperDesc(), false);
jaroslav@601
  1279
    }
jaroslav@601
  1280
jaroslav@601
  1281
    /**
jaroslav@601
  1282
     * Writes given string to stream, using standard or long UTF format
jaroslav@601
  1283
     * depending on string length.
jaroslav@601
  1284
     */
jaroslav@601
  1285
    private void writeString(String str, boolean unshared) throws IOException {
jaroslav@601
  1286
        handles.assign(unshared ? null : str);
jaroslav@601
  1287
        long utflen = bout.getUTFLength(str);
jaroslav@601
  1288
        if (utflen <= 0xFFFF) {
jaroslav@601
  1289
            bout.writeByte(TC_STRING);
jaroslav@601
  1290
            bout.writeUTF(str, utflen);
jaroslav@601
  1291
        } else {
jaroslav@601
  1292
            bout.writeByte(TC_LONGSTRING);
jaroslav@601
  1293
            bout.writeLongUTF(str, utflen);
jaroslav@601
  1294
        }
jaroslav@601
  1295
    }
jaroslav@601
  1296
jaroslav@601
  1297
    /**
jaroslav@601
  1298
     * Writes given array object to stream.
jaroslav@601
  1299
     */
jaroslav@601
  1300
    private void writeArray(Object array,
jaroslav@601
  1301
                            ObjectStreamClass desc,
jaroslav@601
  1302
                            boolean unshared)
jaroslav@601
  1303
        throws IOException
jaroslav@601
  1304
    {
jaroslav@601
  1305
        bout.writeByte(TC_ARRAY);
jaroslav@601
  1306
        writeClassDesc(desc, false);
jaroslav@601
  1307
        handles.assign(unshared ? null : array);
jaroslav@601
  1308
jaroslav@601
  1309
        Class ccl = desc.forClass().getComponentType();
jaroslav@601
  1310
        if (ccl.isPrimitive()) {
jaroslav@601
  1311
            if (ccl == Integer.TYPE) {
jaroslav@601
  1312
                int[] ia = (int[]) array;
jaroslav@601
  1313
                bout.writeInt(ia.length);
jaroslav@601
  1314
                bout.writeInts(ia, 0, ia.length);
jaroslav@601
  1315
            } else if (ccl == Byte.TYPE) {
jaroslav@601
  1316
                byte[] ba = (byte[]) array;
jaroslav@601
  1317
                bout.writeInt(ba.length);
jaroslav@601
  1318
                bout.write(ba, 0, ba.length, true);
jaroslav@601
  1319
            } else if (ccl == Long.TYPE) {
jaroslav@601
  1320
                long[] ja = (long[]) array;
jaroslav@601
  1321
                bout.writeInt(ja.length);
jaroslav@601
  1322
                bout.writeLongs(ja, 0, ja.length);
jaroslav@601
  1323
            } else if (ccl == Float.TYPE) {
jaroslav@601
  1324
                float[] fa = (float[]) array;
jaroslav@601
  1325
                bout.writeInt(fa.length);
jaroslav@601
  1326
                bout.writeFloats(fa, 0, fa.length);
jaroslav@601
  1327
            } else if (ccl == Double.TYPE) {
jaroslav@601
  1328
                double[] da = (double[]) array;
jaroslav@601
  1329
                bout.writeInt(da.length);
jaroslav@601
  1330
                bout.writeDoubles(da, 0, da.length);
jaroslav@601
  1331
            } else if (ccl == Short.TYPE) {
jaroslav@601
  1332
                short[] sa = (short[]) array;
jaroslav@601
  1333
                bout.writeInt(sa.length);
jaroslav@601
  1334
                bout.writeShorts(sa, 0, sa.length);
jaroslav@601
  1335
            } else if (ccl == Character.TYPE) {
jaroslav@601
  1336
                char[] ca = (char[]) array;
jaroslav@601
  1337
                bout.writeInt(ca.length);
jaroslav@601
  1338
                bout.writeChars(ca, 0, ca.length);
jaroslav@601
  1339
            } else if (ccl == Boolean.TYPE) {
jaroslav@601
  1340
                boolean[] za = (boolean[]) array;
jaroslav@601
  1341
                bout.writeInt(za.length);
jaroslav@601
  1342
                bout.writeBooleans(za, 0, za.length);
jaroslav@601
  1343
            } else {
jaroslav@601
  1344
                throw new InternalError();
jaroslav@601
  1345
            }
jaroslav@601
  1346
        } else {
jaroslav@601
  1347
            Object[] objs = (Object[]) array;
jaroslav@601
  1348
            int len = objs.length;
jaroslav@601
  1349
            bout.writeInt(len);
jaroslav@601
  1350
            if (extendedDebugInfo) {
jaroslav@601
  1351
                debugInfoStack.push(
jaroslav@601
  1352
                    "array (class \"" + array.getClass().getName() +
jaroslav@601
  1353
                    "\", size: " + len  + ")");
jaroslav@601
  1354
            }
jaroslav@601
  1355
            try {
jaroslav@601
  1356
                for (int i = 0; i < len; i++) {
jaroslav@601
  1357
                    if (extendedDebugInfo) {
jaroslav@601
  1358
                        debugInfoStack.push(
jaroslav@601
  1359
                            "element of array (index: " + i + ")");
jaroslav@601
  1360
                    }
jaroslav@601
  1361
                    try {
jaroslav@601
  1362
                        writeObject0(objs[i], false);
jaroslav@601
  1363
                    } finally {
jaroslav@601
  1364
                        if (extendedDebugInfo) {
jaroslav@601
  1365
                            debugInfoStack.pop();
jaroslav@601
  1366
                        }
jaroslav@601
  1367
                    }
jaroslav@601
  1368
                }
jaroslav@601
  1369
            } finally {
jaroslav@601
  1370
                if (extendedDebugInfo) {
jaroslav@601
  1371
                    debugInfoStack.pop();
jaroslav@601
  1372
                }
jaroslav@601
  1373
            }
jaroslav@601
  1374
        }
jaroslav@601
  1375
    }
jaroslav@601
  1376
jaroslav@601
  1377
    /**
jaroslav@601
  1378
     * Writes given enum constant to stream.
jaroslav@601
  1379
     */
jaroslav@601
  1380
    private void writeEnum(Enum en,
jaroslav@601
  1381
                           ObjectStreamClass desc,
jaroslav@601
  1382
                           boolean unshared)
jaroslav@601
  1383
        throws IOException
jaroslav@601
  1384
    {
jaroslav@601
  1385
        bout.writeByte(TC_ENUM);
jaroslav@601
  1386
        ObjectStreamClass sdesc = desc.getSuperDesc();
jaroslav@601
  1387
        writeClassDesc((sdesc.forClass() == Enum.class) ? desc : sdesc, false);
jaroslav@601
  1388
        handles.assign(unshared ? null : en);
jaroslav@601
  1389
        writeString(en.name(), false);
jaroslav@601
  1390
    }
jaroslav@601
  1391
jaroslav@601
  1392
    /**
jaroslav@601
  1393
     * Writes representation of a "ordinary" (i.e., not a String, Class,
jaroslav@601
  1394
     * ObjectStreamClass, array, or enum constant) serializable object to the
jaroslav@601
  1395
     * stream.
jaroslav@601
  1396
     */
jaroslav@601
  1397
    private void writeOrdinaryObject(Object obj,
jaroslav@601
  1398
                                     ObjectStreamClass desc,
jaroslav@601
  1399
                                     boolean unshared)
jaroslav@601
  1400
        throws IOException
jaroslav@601
  1401
    {
jaroslav@601
  1402
        if (extendedDebugInfo) {
jaroslav@601
  1403
            debugInfoStack.push(
jaroslav@601
  1404
                (depth == 1 ? "root " : "") + "object (class \"" +
jaroslav@601
  1405
                obj.getClass().getName() + "\", " + obj.toString() + ")");
jaroslav@601
  1406
        }
jaroslav@601
  1407
        try {
jaroslav@601
  1408
            desc.checkSerialize();
jaroslav@601
  1409
jaroslav@601
  1410
            bout.writeByte(TC_OBJECT);
jaroslav@601
  1411
            writeClassDesc(desc, false);
jaroslav@601
  1412
            handles.assign(unshared ? null : obj);
jaroslav@601
  1413
            if (desc.isExternalizable() && !desc.isProxy()) {
jaroslav@601
  1414
                writeExternalData((Externalizable) obj);
jaroslav@601
  1415
            } else {
jaroslav@601
  1416
                writeSerialData(obj, desc);
jaroslav@601
  1417
            }
jaroslav@601
  1418
        } finally {
jaroslav@601
  1419
            if (extendedDebugInfo) {
jaroslav@601
  1420
                debugInfoStack.pop();
jaroslav@601
  1421
            }
jaroslav@601
  1422
        }
jaroslav@601
  1423
    }
jaroslav@601
  1424
jaroslav@601
  1425
    /**
jaroslav@601
  1426
     * Writes externalizable data of given object by invoking its
jaroslav@601
  1427
     * writeExternal() method.
jaroslav@601
  1428
     */
jaroslav@601
  1429
    private void writeExternalData(Externalizable obj) throws IOException {
jaroslav@601
  1430
        PutFieldImpl oldPut = curPut;
jaroslav@601
  1431
        curPut = null;
jaroslav@601
  1432
jaroslav@601
  1433
        if (extendedDebugInfo) {
jaroslav@601
  1434
            debugInfoStack.push("writeExternal data");
jaroslav@601
  1435
        }
jaroslav@601
  1436
        SerialCallbackContext oldContext = curContext;
jaroslav@601
  1437
        try {
jaroslav@601
  1438
            curContext = null;
jaroslav@601
  1439
            if (protocol == PROTOCOL_VERSION_1) {
jaroslav@601
  1440
                obj.writeExternal(this);
jaroslav@601
  1441
            } else {
jaroslav@601
  1442
                bout.setBlockDataMode(true);
jaroslav@601
  1443
                obj.writeExternal(this);
jaroslav@601
  1444
                bout.setBlockDataMode(false);
jaroslav@601
  1445
                bout.writeByte(TC_ENDBLOCKDATA);
jaroslav@601
  1446
            }
jaroslav@601
  1447
        } finally {
jaroslav@601
  1448
            curContext = oldContext;
jaroslav@601
  1449
            if (extendedDebugInfo) {
jaroslav@601
  1450
                debugInfoStack.pop();
jaroslav@601
  1451
            }
jaroslav@601
  1452
        }
jaroslav@601
  1453
jaroslav@601
  1454
        curPut = oldPut;
jaroslav@601
  1455
    }
jaroslav@601
  1456
jaroslav@601
  1457
    /**
jaroslav@601
  1458
     * Writes instance data for each serializable class of given object, from
jaroslav@601
  1459
     * superclass to subclass.
jaroslav@601
  1460
     */
jaroslav@601
  1461
    private void writeSerialData(Object obj, ObjectStreamClass desc)
jaroslav@601
  1462
        throws IOException
jaroslav@601
  1463
    {
jaroslav@601
  1464
        ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
jaroslav@601
  1465
        for (int i = 0; i < slots.length; i++) {
jaroslav@601
  1466
            ObjectStreamClass slotDesc = slots[i].desc;
jaroslav@601
  1467
            if (slotDesc.hasWriteObjectMethod()) {
jaroslav@601
  1468
                PutFieldImpl oldPut = curPut;
jaroslav@601
  1469
                curPut = null;
jaroslav@601
  1470
                SerialCallbackContext oldContext = curContext;
jaroslav@601
  1471
jaroslav@601
  1472
                if (extendedDebugInfo) {
jaroslav@601
  1473
                    debugInfoStack.push(
jaroslav@601
  1474
                        "custom writeObject data (class \"" +
jaroslav@601
  1475
                        slotDesc.getName() + "\")");
jaroslav@601
  1476
                }
jaroslav@601
  1477
                try {
jaroslav@601
  1478
                    curContext = new SerialCallbackContext(obj, slotDesc);
jaroslav@601
  1479
                    bout.setBlockDataMode(true);
jaroslav@601
  1480
                    slotDesc.invokeWriteObject(obj, this);
jaroslav@601
  1481
                    bout.setBlockDataMode(false);
jaroslav@601
  1482
                    bout.writeByte(TC_ENDBLOCKDATA);
jaroslav@601
  1483
                } finally {
jaroslav@601
  1484
                    curContext.setUsed();
jaroslav@601
  1485
                    curContext = oldContext;
jaroslav@601
  1486
                    if (extendedDebugInfo) {
jaroslav@601
  1487
                        debugInfoStack.pop();
jaroslav@601
  1488
                    }
jaroslav@601
  1489
                }
jaroslav@601
  1490
jaroslav@601
  1491
                curPut = oldPut;
jaroslav@601
  1492
            } else {
jaroslav@601
  1493
                defaultWriteFields(obj, slotDesc);
jaroslav@601
  1494
            }
jaroslav@601
  1495
        }
jaroslav@601
  1496
    }
jaroslav@601
  1497
jaroslav@601
  1498
    /**
jaroslav@601
  1499
     * Fetches and writes values of serializable fields of given object to
jaroslav@601
  1500
     * stream.  The given class descriptor specifies which field values to
jaroslav@601
  1501
     * write, and in which order they should be written.
jaroslav@601
  1502
     */
jaroslav@601
  1503
    private void defaultWriteFields(Object obj, ObjectStreamClass desc)
jaroslav@601
  1504
        throws IOException
jaroslav@601
  1505
    {
jaroslav@601
  1506
        // REMIND: perform conservative isInstance check here?
jaroslav@601
  1507
        desc.checkDefaultSerialize();
jaroslav@601
  1508
jaroslav@601
  1509
        int primDataSize = desc.getPrimDataSize();
jaroslav@601
  1510
        if (primVals == null || primVals.length < primDataSize) {
jaroslav@601
  1511
            primVals = new byte[primDataSize];
jaroslav@601
  1512
        }
jaroslav@601
  1513
        desc.getPrimFieldValues(obj, primVals);
jaroslav@601
  1514
        bout.write(primVals, 0, primDataSize, false);
jaroslav@601
  1515
jaroslav@601
  1516
        ObjectStreamField[] fields = desc.getFields(false);
jaroslav@601
  1517
        Object[] objVals = new Object[desc.getNumObjFields()];
jaroslav@601
  1518
        int numPrimFields = fields.length - objVals.length;
jaroslav@601
  1519
        desc.getObjFieldValues(obj, objVals);
jaroslav@601
  1520
        for (int i = 0; i < objVals.length; i++) {
jaroslav@601
  1521
            if (extendedDebugInfo) {
jaroslav@601
  1522
                debugInfoStack.push(
jaroslav@601
  1523
                    "field (class \"" + desc.getName() + "\", name: \"" +
jaroslav@601
  1524
                    fields[numPrimFields + i].getName() + "\", type: \"" +
jaroslav@601
  1525
                    fields[numPrimFields + i].getType() + "\")");
jaroslav@601
  1526
            }
jaroslav@601
  1527
            try {
jaroslav@601
  1528
                writeObject0(objVals[i],
jaroslav@601
  1529
                             fields[numPrimFields + i].isUnshared());
jaroslav@601
  1530
            } finally {
jaroslav@601
  1531
                if (extendedDebugInfo) {
jaroslav@601
  1532
                    debugInfoStack.pop();
jaroslav@601
  1533
                }
jaroslav@601
  1534
            }
jaroslav@601
  1535
        }
jaroslav@601
  1536
    }
jaroslav@601
  1537
jaroslav@601
  1538
    /**
jaroslav@601
  1539
     * Attempts to write to stream fatal IOException that has caused
jaroslav@601
  1540
     * serialization to abort.
jaroslav@601
  1541
     */
jaroslav@601
  1542
    private void writeFatalException(IOException ex) throws IOException {
jaroslav@601
  1543
        /*
jaroslav@601
  1544
         * Note: the serialization specification states that if a second
jaroslav@601
  1545
         * IOException occurs while attempting to serialize the original fatal
jaroslav@601
  1546
         * exception to the stream, then a StreamCorruptedException should be
jaroslav@601
  1547
         * thrown (section 2.1).  However, due to a bug in previous
jaroslav@601
  1548
         * implementations of serialization, StreamCorruptedExceptions were
jaroslav@601
  1549
         * rarely (if ever) actually thrown--the "root" exceptions from
jaroslav@601
  1550
         * underlying streams were thrown instead.  This historical behavior is
jaroslav@601
  1551
         * followed here for consistency.
jaroslav@601
  1552
         */
jaroslav@601
  1553
        clear();
jaroslav@601
  1554
        boolean oldMode = bout.setBlockDataMode(false);
jaroslav@601
  1555
        try {
jaroslav@601
  1556
            bout.writeByte(TC_EXCEPTION);
jaroslav@601
  1557
            writeObject0(ex, false);
jaroslav@601
  1558
            clear();
jaroslav@601
  1559
        } finally {
jaroslav@601
  1560
            bout.setBlockDataMode(oldMode);
jaroslav@601
  1561
        }
jaroslav@601
  1562
    }
jaroslav@601
  1563
jaroslav@601
  1564
    /**
jaroslav@601
  1565
     * Converts specified span of float values into byte values.
jaroslav@601
  1566
     */
jaroslav@601
  1567
    // REMIND: remove once hotspot inlines Float.floatToIntBits
jaroslav@601
  1568
    private static native void floatsToBytes(float[] src, int srcpos,
jaroslav@601
  1569
                                             byte[] dst, int dstpos,
jaroslav@601
  1570
                                             int nfloats);
jaroslav@601
  1571
jaroslav@601
  1572
    /**
jaroslav@601
  1573
     * Converts specified span of double values into byte values.
jaroslav@601
  1574
     */
jaroslav@601
  1575
    // REMIND: remove once hotspot inlines Double.doubleToLongBits
jaroslav@601
  1576
    private static native void doublesToBytes(double[] src, int srcpos,
jaroslav@601
  1577
                                              byte[] dst, int dstpos,
jaroslav@601
  1578
                                              int ndoubles);
jaroslav@601
  1579
jaroslav@601
  1580
    /**
jaroslav@601
  1581
     * Default PutField implementation.
jaroslav@601
  1582
     */
jaroslav@601
  1583
    private class PutFieldImpl extends PutField {
jaroslav@601
  1584
jaroslav@601
  1585
        /** class descriptor describing serializable fields */
jaroslav@601
  1586
        private final ObjectStreamClass desc;
jaroslav@601
  1587
        /** primitive field values */
jaroslav@601
  1588
        private final byte[] primVals;
jaroslav@601
  1589
        /** object field values */
jaroslav@601
  1590
        private final Object[] objVals;
jaroslav@601
  1591
jaroslav@601
  1592
        /**
jaroslav@601
  1593
         * Creates PutFieldImpl object for writing fields defined in given
jaroslav@601
  1594
         * class descriptor.
jaroslav@601
  1595
         */
jaroslav@601
  1596
        PutFieldImpl(ObjectStreamClass desc) {
jaroslav@601
  1597
            this.desc = desc;
jaroslav@601
  1598
            primVals = new byte[desc.getPrimDataSize()];
jaroslav@601
  1599
            objVals = new Object[desc.getNumObjFields()];
jaroslav@601
  1600
        }
jaroslav@601
  1601
jaroslav@601
  1602
        public void put(String name, boolean val) {
jaroslav@601
  1603
            Bits.putBoolean(primVals, getFieldOffset(name, Boolean.TYPE), val);
jaroslav@601
  1604
        }
jaroslav@601
  1605
jaroslav@601
  1606
        public void put(String name, byte val) {
jaroslav@601
  1607
            primVals[getFieldOffset(name, Byte.TYPE)] = val;
jaroslav@601
  1608
        }
jaroslav@601
  1609
jaroslav@601
  1610
        public void put(String name, char val) {
jaroslav@601
  1611
            Bits.putChar(primVals, getFieldOffset(name, Character.TYPE), val);
jaroslav@601
  1612
        }
jaroslav@601
  1613
jaroslav@601
  1614
        public void put(String name, short val) {
jaroslav@601
  1615
            Bits.putShort(primVals, getFieldOffset(name, Short.TYPE), val);
jaroslav@601
  1616
        }
jaroslav@601
  1617
jaroslav@601
  1618
        public void put(String name, int val) {
jaroslav@601
  1619
            Bits.putInt(primVals, getFieldOffset(name, Integer.TYPE), val);
jaroslav@601
  1620
        }
jaroslav@601
  1621
jaroslav@601
  1622
        public void put(String name, float val) {
jaroslav@601
  1623
            Bits.putFloat(primVals, getFieldOffset(name, Float.TYPE), val);
jaroslav@601
  1624
        }
jaroslav@601
  1625
jaroslav@601
  1626
        public void put(String name, long val) {
jaroslav@601
  1627
            Bits.putLong(primVals, getFieldOffset(name, Long.TYPE), val);
jaroslav@601
  1628
        }
jaroslav@601
  1629
jaroslav@601
  1630
        public void put(String name, double val) {
jaroslav@601
  1631
            Bits.putDouble(primVals, getFieldOffset(name, Double.TYPE), val);
jaroslav@601
  1632
        }
jaroslav@601
  1633
jaroslav@601
  1634
        public void put(String name, Object val) {
jaroslav@601
  1635
            objVals[getFieldOffset(name, Object.class)] = val;
jaroslav@601
  1636
        }
jaroslav@601
  1637
jaroslav@601
  1638
        // deprecated in ObjectOutputStream.PutField
jaroslav@601
  1639
        public void write(ObjectOutput out) throws IOException {
jaroslav@601
  1640
            /*
jaroslav@601
  1641
             * Applications should *not* use this method to write PutField
jaroslav@601
  1642
             * data, as it will lead to stream corruption if the PutField
jaroslav@601
  1643
             * object writes any primitive data (since block data mode is not
jaroslav@601
  1644
             * unset/set properly, as is done in OOS.writeFields()).  This
jaroslav@601
  1645
             * broken implementation is being retained solely for behavioral
jaroslav@601
  1646
             * compatibility, in order to support applications which use
jaroslav@601
  1647
             * OOS.PutField.write() for writing only non-primitive data.
jaroslav@601
  1648
             *
jaroslav@601
  1649
             * Serialization of unshared objects is not implemented here since
jaroslav@601
  1650
             * it is not necessary for backwards compatibility; also, unshared
jaroslav@601
  1651
             * semantics may not be supported by the given ObjectOutput
jaroslav@601
  1652
             * instance.  Applications which write unshared objects using the
jaroslav@601
  1653
             * PutField API must use OOS.writeFields().
jaroslav@601
  1654
             */
jaroslav@601
  1655
            if (ObjectOutputStream.this != out) {
jaroslav@601
  1656
                throw new IllegalArgumentException("wrong stream");
jaroslav@601
  1657
            }
jaroslav@601
  1658
            out.write(primVals, 0, primVals.length);
jaroslav@601
  1659
jaroslav@601
  1660
            ObjectStreamField[] fields = desc.getFields(false);
jaroslav@601
  1661
            int numPrimFields = fields.length - objVals.length;
jaroslav@601
  1662
            // REMIND: warn if numPrimFields > 0?
jaroslav@601
  1663
            for (int i = 0; i < objVals.length; i++) {
jaroslav@601
  1664
                if (fields[numPrimFields + i].isUnshared()) {
jaroslav@601
  1665
                    throw new IOException("cannot write unshared object");
jaroslav@601
  1666
                }
jaroslav@601
  1667
                out.writeObject(objVals[i]);
jaroslav@601
  1668
            }
jaroslav@601
  1669
        }
jaroslav@601
  1670
jaroslav@601
  1671
        /**
jaroslav@601
  1672
         * Writes buffered primitive data and object fields to stream.
jaroslav@601
  1673
         */
jaroslav@601
  1674
        void writeFields() throws IOException {
jaroslav@601
  1675
            bout.write(primVals, 0, primVals.length, false);
jaroslav@601
  1676
jaroslav@601
  1677
            ObjectStreamField[] fields = desc.getFields(false);
jaroslav@601
  1678
            int numPrimFields = fields.length - objVals.length;
jaroslav@601
  1679
            for (int i = 0; i < objVals.length; i++) {
jaroslav@601
  1680
                if (extendedDebugInfo) {
jaroslav@601
  1681
                    debugInfoStack.push(
jaroslav@601
  1682
                        "field (class \"" + desc.getName() + "\", name: \"" +
jaroslav@601
  1683
                        fields[numPrimFields + i].getName() + "\", type: \"" +
jaroslav@601
  1684
                        fields[numPrimFields + i].getType() + "\")");
jaroslav@601
  1685
                }
jaroslav@601
  1686
                try {
jaroslav@601
  1687
                    writeObject0(objVals[i],
jaroslav@601
  1688
                                 fields[numPrimFields + i].isUnshared());
jaroslav@601
  1689
                } finally {
jaroslav@601
  1690
                    if (extendedDebugInfo) {
jaroslav@601
  1691
                        debugInfoStack.pop();
jaroslav@601
  1692
                    }
jaroslav@601
  1693
                }
jaroslav@601
  1694
            }
jaroslav@601
  1695
        }
jaroslav@601
  1696
jaroslav@601
  1697
        /**
jaroslav@601
  1698
         * Returns offset of field with given name and type.  A specified type
jaroslav@601
  1699
         * of null matches all types, Object.class matches all non-primitive
jaroslav@601
  1700
         * types, and any other non-null type matches assignable types only.
jaroslav@601
  1701
         * Throws IllegalArgumentException if no matching field found.
jaroslav@601
  1702
         */
jaroslav@601
  1703
        private int getFieldOffset(String name, Class type) {
jaroslav@601
  1704
            ObjectStreamField field = desc.getField(name, type);
jaroslav@601
  1705
            if (field == null) {
jaroslav@601
  1706
                throw new IllegalArgumentException("no such field " + name +
jaroslav@601
  1707
                                                   " with type " + type);
jaroslav@601
  1708
            }
jaroslav@601
  1709
            return field.getOffset();
jaroslav@601
  1710
        }
jaroslav@601
  1711
    }
jaroslav@601
  1712
jaroslav@601
  1713
    /**
jaroslav@601
  1714
     * Buffered output stream with two modes: in default mode, outputs data in
jaroslav@601
  1715
     * same format as DataOutputStream; in "block data" mode, outputs data
jaroslav@601
  1716
     * bracketed by block data markers (see object serialization specification
jaroslav@601
  1717
     * for details).
jaroslav@601
  1718
     */
jaroslav@601
  1719
    private static class BlockDataOutputStream
jaroslav@601
  1720
        extends OutputStream implements DataOutput
jaroslav@601
  1721
    {
jaroslav@601
  1722
        /** maximum data block length */
jaroslav@601
  1723
        private static final int MAX_BLOCK_SIZE = 1024;
jaroslav@601
  1724
        /** maximum data block header length */
jaroslav@601
  1725
        private static final int MAX_HEADER_SIZE = 5;
jaroslav@601
  1726
        /** (tunable) length of char buffer (for writing strings) */
jaroslav@601
  1727
        private static final int CHAR_BUF_SIZE = 256;
jaroslav@601
  1728
jaroslav@601
  1729
        /** buffer for writing general/block data */
jaroslav@601
  1730
        private final byte[] buf = new byte[MAX_BLOCK_SIZE];
jaroslav@601
  1731
        /** buffer for writing block data headers */
jaroslav@601
  1732
        private final byte[] hbuf = new byte[MAX_HEADER_SIZE];
jaroslav@601
  1733
        /** char buffer for fast string writes */
jaroslav@601
  1734
        private final char[] cbuf = new char[CHAR_BUF_SIZE];
jaroslav@601
  1735
jaroslav@601
  1736
        /** block data mode */
jaroslav@601
  1737
        private boolean blkmode = false;
jaroslav@601
  1738
        /** current offset into buf */
jaroslav@601
  1739
        private int pos = 0;
jaroslav@601
  1740
jaroslav@601
  1741
        /** underlying output stream */
jaroslav@601
  1742
        private final OutputStream out;
jaroslav@601
  1743
        /** loopback stream (for data writes that span data blocks) */
jaroslav@601
  1744
        private final DataOutputStream dout;
jaroslav@601
  1745
jaroslav@601
  1746
        /**
jaroslav@601
  1747
         * Creates new BlockDataOutputStream on top of given underlying stream.
jaroslav@601
  1748
         * Block data mode is turned off by default.
jaroslav@601
  1749
         */
jaroslav@601
  1750
        BlockDataOutputStream(OutputStream out) {
jaroslav@601
  1751
            this.out = out;
jaroslav@601
  1752
            dout = new DataOutputStream(this);
jaroslav@601
  1753
        }
jaroslav@601
  1754
jaroslav@601
  1755
        /**
jaroslav@601
  1756
         * Sets block data mode to the given mode (true == on, false == off)
jaroslav@601
  1757
         * and returns the previous mode value.  If the new mode is the same as
jaroslav@601
  1758
         * the old mode, no action is taken.  If the new mode differs from the
jaroslav@601
  1759
         * old mode, any buffered data is flushed before switching to the new
jaroslav@601
  1760
         * mode.
jaroslav@601
  1761
         */
jaroslav@601
  1762
        boolean setBlockDataMode(boolean mode) throws IOException {
jaroslav@601
  1763
            if (blkmode == mode) {
jaroslav@601
  1764
                return blkmode;
jaroslav@601
  1765
            }
jaroslav@601
  1766
            drain();
jaroslav@601
  1767
            blkmode = mode;
jaroslav@601
  1768
            return !blkmode;
jaroslav@601
  1769
        }
jaroslav@601
  1770
jaroslav@601
  1771
        /**
jaroslav@601
  1772
         * Returns true if the stream is currently in block data mode, false
jaroslav@601
  1773
         * otherwise.
jaroslav@601
  1774
         */
jaroslav@601
  1775
        boolean getBlockDataMode() {
jaroslav@601
  1776
            return blkmode;
jaroslav@601
  1777
        }
jaroslav@601
  1778
jaroslav@601
  1779
        /* ----------------- generic output stream methods ----------------- */
jaroslav@601
  1780
        /*
jaroslav@601
  1781
         * The following methods are equivalent to their counterparts in
jaroslav@601
  1782
         * OutputStream, except that they partition written data into data
jaroslav@601
  1783
         * blocks when in block data mode.
jaroslav@601
  1784
         */
jaroslav@601
  1785
jaroslav@601
  1786
        public void write(int b) throws IOException {
jaroslav@601
  1787
            if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1788
                drain();
jaroslav@601
  1789
            }
jaroslav@601
  1790
            buf[pos++] = (byte) b;
jaroslav@601
  1791
        }
jaroslav@601
  1792
jaroslav@601
  1793
        public void write(byte[] b) throws IOException {
jaroslav@601
  1794
            write(b, 0, b.length, false);
jaroslav@601
  1795
        }
jaroslav@601
  1796
jaroslav@601
  1797
        public void write(byte[] b, int off, int len) throws IOException {
jaroslav@601
  1798
            write(b, off, len, false);
jaroslav@601
  1799
        }
jaroslav@601
  1800
jaroslav@601
  1801
        public void flush() throws IOException {
jaroslav@601
  1802
            drain();
jaroslav@601
  1803
            out.flush();
jaroslav@601
  1804
        }
jaroslav@601
  1805
jaroslav@601
  1806
        public void close() throws IOException {
jaroslav@601
  1807
            flush();
jaroslav@601
  1808
            out.close();
jaroslav@601
  1809
        }
jaroslav@601
  1810
jaroslav@601
  1811
        /**
jaroslav@601
  1812
         * Writes specified span of byte values from given array.  If copy is
jaroslav@601
  1813
         * true, copies the values to an intermediate buffer before writing
jaroslav@601
  1814
         * them to underlying stream (to avoid exposing a reference to the
jaroslav@601
  1815
         * original byte array).
jaroslav@601
  1816
         */
jaroslav@601
  1817
        void write(byte[] b, int off, int len, boolean copy)
jaroslav@601
  1818
            throws IOException
jaroslav@601
  1819
        {
jaroslav@601
  1820
            if (!(copy || blkmode)) {           // write directly
jaroslav@601
  1821
                drain();
jaroslav@601
  1822
                out.write(b, off, len);
jaroslav@601
  1823
                return;
jaroslav@601
  1824
            }
jaroslav@601
  1825
jaroslav@601
  1826
            while (len > 0) {
jaroslav@601
  1827
                if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1828
                    drain();
jaroslav@601
  1829
                }
jaroslav@601
  1830
                if (len >= MAX_BLOCK_SIZE && !copy && pos == 0) {
jaroslav@601
  1831
                    // avoid unnecessary copy
jaroslav@601
  1832
                    writeBlockHeader(MAX_BLOCK_SIZE);
jaroslav@601
  1833
                    out.write(b, off, MAX_BLOCK_SIZE);
jaroslav@601
  1834
                    off += MAX_BLOCK_SIZE;
jaroslav@601
  1835
                    len -= MAX_BLOCK_SIZE;
jaroslav@601
  1836
                } else {
jaroslav@601
  1837
                    int wlen = Math.min(len, MAX_BLOCK_SIZE - pos);
jaroslav@601
  1838
                    System.arraycopy(b, off, buf, pos, wlen);
jaroslav@601
  1839
                    pos += wlen;
jaroslav@601
  1840
                    off += wlen;
jaroslav@601
  1841
                    len -= wlen;
jaroslav@601
  1842
                }
jaroslav@601
  1843
            }
jaroslav@601
  1844
        }
jaroslav@601
  1845
jaroslav@601
  1846
        /**
jaroslav@601
  1847
         * Writes all buffered data from this stream to the underlying stream,
jaroslav@601
  1848
         * but does not flush underlying stream.
jaroslav@601
  1849
         */
jaroslav@601
  1850
        void drain() throws IOException {
jaroslav@601
  1851
            if (pos == 0) {
jaroslav@601
  1852
                return;
jaroslav@601
  1853
            }
jaroslav@601
  1854
            if (blkmode) {
jaroslav@601
  1855
                writeBlockHeader(pos);
jaroslav@601
  1856
            }
jaroslav@601
  1857
            out.write(buf, 0, pos);
jaroslav@601
  1858
            pos = 0;
jaroslav@601
  1859
        }
jaroslav@601
  1860
jaroslav@601
  1861
        /**
jaroslav@601
  1862
         * Writes block data header.  Data blocks shorter than 256 bytes are
jaroslav@601
  1863
         * prefixed with a 2-byte header; all others start with a 5-byte
jaroslav@601
  1864
         * header.
jaroslav@601
  1865
         */
jaroslav@601
  1866
        private void writeBlockHeader(int len) throws IOException {
jaroslav@601
  1867
            if (len <= 0xFF) {
jaroslav@601
  1868
                hbuf[0] = TC_BLOCKDATA;
jaroslav@601
  1869
                hbuf[1] = (byte) len;
jaroslav@601
  1870
                out.write(hbuf, 0, 2);
jaroslav@601
  1871
            } else {
jaroslav@601
  1872
                hbuf[0] = TC_BLOCKDATALONG;
jaroslav@601
  1873
                Bits.putInt(hbuf, 1, len);
jaroslav@601
  1874
                out.write(hbuf, 0, 5);
jaroslav@601
  1875
            }
jaroslav@601
  1876
        }
jaroslav@601
  1877
jaroslav@601
  1878
jaroslav@601
  1879
        /* ----------------- primitive data output methods ----------------- */
jaroslav@601
  1880
        /*
jaroslav@601
  1881
         * The following methods are equivalent to their counterparts in
jaroslav@601
  1882
         * DataOutputStream, except that they partition written data into data
jaroslav@601
  1883
         * blocks when in block data mode.
jaroslav@601
  1884
         */
jaroslav@601
  1885
jaroslav@601
  1886
        public void writeBoolean(boolean v) throws IOException {
jaroslav@601
  1887
            if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1888
                drain();
jaroslav@601
  1889
            }
jaroslav@601
  1890
            Bits.putBoolean(buf, pos++, v);
jaroslav@601
  1891
        }
jaroslav@601
  1892
jaroslav@601
  1893
        public void writeByte(int v) throws IOException {
jaroslav@601
  1894
            if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1895
                drain();
jaroslav@601
  1896
            }
jaroslav@601
  1897
            buf[pos++] = (byte) v;
jaroslav@601
  1898
        }
jaroslav@601
  1899
jaroslav@601
  1900
        public void writeChar(int v) throws IOException {
jaroslav@601
  1901
            if (pos + 2 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1902
                Bits.putChar(buf, pos, (char) v);
jaroslav@601
  1903
                pos += 2;
jaroslav@601
  1904
            } else {
jaroslav@601
  1905
                dout.writeChar(v);
jaroslav@601
  1906
            }
jaroslav@601
  1907
        }
jaroslav@601
  1908
jaroslav@601
  1909
        public void writeShort(int v) throws IOException {
jaroslav@601
  1910
            if (pos + 2 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1911
                Bits.putShort(buf, pos, (short) v);
jaroslav@601
  1912
                pos += 2;
jaroslav@601
  1913
            } else {
jaroslav@601
  1914
                dout.writeShort(v);
jaroslav@601
  1915
            }
jaroslav@601
  1916
        }
jaroslav@601
  1917
jaroslav@601
  1918
        public void writeInt(int v) throws IOException {
jaroslav@601
  1919
            if (pos + 4 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1920
                Bits.putInt(buf, pos, v);
jaroslav@601
  1921
                pos += 4;
jaroslav@601
  1922
            } else {
jaroslav@601
  1923
                dout.writeInt(v);
jaroslav@601
  1924
            }
jaroslav@601
  1925
        }
jaroslav@601
  1926
jaroslav@601
  1927
        public void writeFloat(float v) throws IOException {
jaroslav@601
  1928
            if (pos + 4 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1929
                Bits.putFloat(buf, pos, v);
jaroslav@601
  1930
                pos += 4;
jaroslav@601
  1931
            } else {
jaroslav@601
  1932
                dout.writeFloat(v);
jaroslav@601
  1933
            }
jaroslav@601
  1934
        }
jaroslav@601
  1935
jaroslav@601
  1936
        public void writeLong(long v) throws IOException {
jaroslav@601
  1937
            if (pos + 8 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1938
                Bits.putLong(buf, pos, v);
jaroslav@601
  1939
                pos += 8;
jaroslav@601
  1940
            } else {
jaroslav@601
  1941
                dout.writeLong(v);
jaroslav@601
  1942
            }
jaroslav@601
  1943
        }
jaroslav@601
  1944
jaroslav@601
  1945
        public void writeDouble(double v) throws IOException {
jaroslav@601
  1946
            if (pos + 8 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1947
                Bits.putDouble(buf, pos, v);
jaroslav@601
  1948
                pos += 8;
jaroslav@601
  1949
            } else {
jaroslav@601
  1950
                dout.writeDouble(v);
jaroslav@601
  1951
            }
jaroslav@601
  1952
        }
jaroslav@601
  1953
jaroslav@601
  1954
        public void writeBytes(String s) throws IOException {
jaroslav@601
  1955
            int endoff = s.length();
jaroslav@601
  1956
            int cpos = 0;
jaroslav@601
  1957
            int csize = 0;
jaroslav@601
  1958
            for (int off = 0; off < endoff; ) {
jaroslav@601
  1959
                if (cpos >= csize) {
jaroslav@601
  1960
                    cpos = 0;
jaroslav@601
  1961
                    csize = Math.min(endoff - off, CHAR_BUF_SIZE);
jaroslav@601
  1962
                    s.getChars(off, off + csize, cbuf, 0);
jaroslav@601
  1963
                }
jaroslav@601
  1964
                if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1965
                    drain();
jaroslav@601
  1966
                }
jaroslav@601
  1967
                int n = Math.min(csize - cpos, MAX_BLOCK_SIZE - pos);
jaroslav@601
  1968
                int stop = pos + n;
jaroslav@601
  1969
                while (pos < stop) {
jaroslav@601
  1970
                    buf[pos++] = (byte) cbuf[cpos++];
jaroslav@601
  1971
                }
jaroslav@601
  1972
                off += n;
jaroslav@601
  1973
            }
jaroslav@601
  1974
        }
jaroslav@601
  1975
jaroslav@601
  1976
        public void writeChars(String s) throws IOException {
jaroslav@601
  1977
            int endoff = s.length();
jaroslav@601
  1978
            for (int off = 0; off < endoff; ) {
jaroslav@601
  1979
                int csize = Math.min(endoff - off, CHAR_BUF_SIZE);
jaroslav@601
  1980
                s.getChars(off, off + csize, cbuf, 0);
jaroslav@601
  1981
                writeChars(cbuf, 0, csize);
jaroslav@601
  1982
                off += csize;
jaroslav@601
  1983
            }
jaroslav@601
  1984
        }
jaroslav@601
  1985
jaroslav@601
  1986
        public void writeUTF(String s) throws IOException {
jaroslav@601
  1987
            writeUTF(s, getUTFLength(s));
jaroslav@601
  1988
        }
jaroslav@601
  1989
jaroslav@601
  1990
jaroslav@601
  1991
        /* -------------- primitive data array output methods -------------- */
jaroslav@601
  1992
        /*
jaroslav@601
  1993
         * The following methods write out spans of primitive data values.
jaroslav@601
  1994
         * Though equivalent to calling the corresponding primitive write
jaroslav@601
  1995
         * methods repeatedly, these methods are optimized for writing groups
jaroslav@601
  1996
         * of primitive data values more efficiently.
jaroslav@601
  1997
         */
jaroslav@601
  1998
jaroslav@601
  1999
        void writeBooleans(boolean[] v, int off, int len) throws IOException {
jaroslav@601
  2000
            int endoff = off + len;
jaroslav@601
  2001
            while (off < endoff) {
jaroslav@601
  2002
                if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  2003
                    drain();
jaroslav@601
  2004
                }
jaroslav@601
  2005
                int stop = Math.min(endoff, off + (MAX_BLOCK_SIZE - pos));
jaroslav@601
  2006
                while (off < stop) {
jaroslav@601
  2007
                    Bits.putBoolean(buf, pos++, v[off++]);
jaroslav@601
  2008
                }
jaroslav@601
  2009
            }
jaroslav@601
  2010
        }
jaroslav@601
  2011
jaroslav@601
  2012
        void writeChars(char[] v, int off, int len) throws IOException {
jaroslav@601
  2013
            int limit = MAX_BLOCK_SIZE - 2;
jaroslav@601
  2014
            int endoff = off + len;
jaroslav@601
  2015
            while (off < endoff) {
jaroslav@601
  2016
                if (pos <= limit) {
jaroslav@601
  2017
                    int avail = (MAX_BLOCK_SIZE - pos) >> 1;
jaroslav@601
  2018
                    int stop = Math.min(endoff, off + avail);
jaroslav@601
  2019
                    while (off < stop) {
jaroslav@601
  2020
                        Bits.putChar(buf, pos, v[off++]);
jaroslav@601
  2021
                        pos += 2;
jaroslav@601
  2022
                    }
jaroslav@601
  2023
                } else {
jaroslav@601
  2024
                    dout.writeChar(v[off++]);
jaroslav@601
  2025
                }
jaroslav@601
  2026
            }
jaroslav@601
  2027
        }
jaroslav@601
  2028
jaroslav@601
  2029
        void writeShorts(short[] v, int off, int len) throws IOException {
jaroslav@601
  2030
            int limit = MAX_BLOCK_SIZE - 2;
jaroslav@601
  2031
            int endoff = off + len;
jaroslav@601
  2032
            while (off < endoff) {
jaroslav@601
  2033
                if (pos <= limit) {
jaroslav@601
  2034
                    int avail = (MAX_BLOCK_SIZE - pos) >> 1;
jaroslav@601
  2035
                    int stop = Math.min(endoff, off + avail);
jaroslav@601
  2036
                    while (off < stop) {
jaroslav@601
  2037
                        Bits.putShort(buf, pos, v[off++]);
jaroslav@601
  2038
                        pos += 2;
jaroslav@601
  2039
                    }
jaroslav@601
  2040
                } else {
jaroslav@601
  2041
                    dout.writeShort(v[off++]);
jaroslav@601
  2042
                }
jaroslav@601
  2043
            }
jaroslav@601
  2044
        }
jaroslav@601
  2045
jaroslav@601
  2046
        void writeInts(int[] v, int off, int len) throws IOException {
jaroslav@601
  2047
            int limit = MAX_BLOCK_SIZE - 4;
jaroslav@601
  2048
            int endoff = off + len;
jaroslav@601
  2049
            while (off < endoff) {
jaroslav@601
  2050
                if (pos <= limit) {
jaroslav@601
  2051
                    int avail = (MAX_BLOCK_SIZE - pos) >> 2;
jaroslav@601
  2052
                    int stop = Math.min(endoff, off + avail);
jaroslav@601
  2053
                    while (off < stop) {
jaroslav@601
  2054
                        Bits.putInt(buf, pos, v[off++]);
jaroslav@601
  2055
                        pos += 4;
jaroslav@601
  2056
                    }
jaroslav@601
  2057
                } else {
jaroslav@601
  2058
                    dout.writeInt(v[off++]);
jaroslav@601
  2059
                }
jaroslav@601
  2060
            }
jaroslav@601
  2061
        }
jaroslav@601
  2062
jaroslav@601
  2063
        void writeFloats(float[] v, int off, int len) throws IOException {
jaroslav@601
  2064
            int limit = MAX_BLOCK_SIZE - 4;
jaroslav@601
  2065
            int endoff = off + len;
jaroslav@601
  2066
            while (off < endoff) {
jaroslav@601
  2067
                if (pos <= limit) {
jaroslav@601
  2068
                    int avail = (MAX_BLOCK_SIZE - pos) >> 2;
jaroslav@601
  2069
                    int chunklen = Math.min(endoff - off, avail);
jaroslav@601
  2070
                    floatsToBytes(v, off, buf, pos, chunklen);
jaroslav@601
  2071
                    off += chunklen;
jaroslav@601
  2072
                    pos += chunklen << 2;
jaroslav@601
  2073
                } else {
jaroslav@601
  2074
                    dout.writeFloat(v[off++]);
jaroslav@601
  2075
                }
jaroslav@601
  2076
            }
jaroslav@601
  2077
        }
jaroslav@601
  2078
jaroslav@601
  2079
        void writeLongs(long[] v, int off, int len) throws IOException {
jaroslav@601
  2080
            int limit = MAX_BLOCK_SIZE - 8;
jaroslav@601
  2081
            int endoff = off + len;
jaroslav@601
  2082
            while (off < endoff) {
jaroslav@601
  2083
                if (pos <= limit) {
jaroslav@601
  2084
                    int avail = (MAX_BLOCK_SIZE - pos) >> 3;
jaroslav@601
  2085
                    int stop = Math.min(endoff, off + avail);
jaroslav@601
  2086
                    while (off < stop) {
jaroslav@601
  2087
                        Bits.putLong(buf, pos, v[off++]);
jaroslav@601
  2088
                        pos += 8;
jaroslav@601
  2089
                    }
jaroslav@601
  2090
                } else {
jaroslav@601
  2091
                    dout.writeLong(v[off++]);
jaroslav@601
  2092
                }
jaroslav@601
  2093
            }
jaroslav@601
  2094
        }
jaroslav@601
  2095
jaroslav@601
  2096
        void writeDoubles(double[] v, int off, int len) throws IOException {
jaroslav@601
  2097
            int limit = MAX_BLOCK_SIZE - 8;
jaroslav@601
  2098
            int endoff = off + len;
jaroslav@601
  2099
            while (off < endoff) {
jaroslav@601
  2100
                if (pos <= limit) {
jaroslav@601
  2101
                    int avail = (MAX_BLOCK_SIZE - pos) >> 3;
jaroslav@601
  2102
                    int chunklen = Math.min(endoff - off, avail);
jaroslav@601
  2103
                    doublesToBytes(v, off, buf, pos, chunklen);
jaroslav@601
  2104
                    off += chunklen;
jaroslav@601
  2105
                    pos += chunklen << 3;
jaroslav@601
  2106
                } else {
jaroslav@601
  2107
                    dout.writeDouble(v[off++]);
jaroslav@601
  2108
                }
jaroslav@601
  2109
            }
jaroslav@601
  2110
        }
jaroslav@601
  2111
jaroslav@601
  2112
        /**
jaroslav@601
  2113
         * Returns the length in bytes of the UTF encoding of the given string.
jaroslav@601
  2114
         */
jaroslav@601
  2115
        long getUTFLength(String s) {
jaroslav@601
  2116
            int len = s.length();
jaroslav@601
  2117
            long utflen = 0;
jaroslav@601
  2118
            for (int off = 0; off < len; ) {
jaroslav@601
  2119
                int csize = Math.min(len - off, CHAR_BUF_SIZE);
jaroslav@601
  2120
                s.getChars(off, off + csize, cbuf, 0);
jaroslav@601
  2121
                for (int cpos = 0; cpos < csize; cpos++) {
jaroslav@601
  2122
                    char c = cbuf[cpos];
jaroslav@601
  2123
                    if (c >= 0x0001 && c <= 0x007F) {
jaroslav@601
  2124
                        utflen++;
jaroslav@601
  2125
                    } else if (c > 0x07FF) {
jaroslav@601
  2126
                        utflen += 3;
jaroslav@601
  2127
                    } else {
jaroslav@601
  2128
                        utflen += 2;
jaroslav@601
  2129
                    }
jaroslav@601
  2130
                }
jaroslav@601
  2131
                off += csize;
jaroslav@601
  2132
            }
jaroslav@601
  2133
            return utflen;
jaroslav@601
  2134
        }
jaroslav@601
  2135
jaroslav@601
  2136
        /**
jaroslav@601
  2137
         * Writes the given string in UTF format.  This method is used in
jaroslav@601
  2138
         * situations where the UTF encoding length of the string is already
jaroslav@601
  2139
         * known; specifying it explicitly avoids a prescan of the string to
jaroslav@601
  2140
         * determine its UTF length.
jaroslav@601
  2141
         */
jaroslav@601
  2142
        void writeUTF(String s, long utflen) throws IOException {
jaroslav@601
  2143
            if (utflen > 0xFFFFL) {
jaroslav@601
  2144
                throw new UTFDataFormatException();
jaroslav@601
  2145
            }
jaroslav@601
  2146
            writeShort((int) utflen);
jaroslav@601
  2147
            if (utflen == (long) s.length()) {
jaroslav@601
  2148
                writeBytes(s);
jaroslav@601
  2149
            } else {
jaroslav@601
  2150
                writeUTFBody(s);
jaroslav@601
  2151
            }
jaroslav@601
  2152
        }
jaroslav@601
  2153
jaroslav@601
  2154
        /**
jaroslav@601
  2155
         * Writes given string in "long" UTF format.  "Long" UTF format is
jaroslav@601
  2156
         * identical to standard UTF, except that it uses an 8 byte header
jaroslav@601
  2157
         * (instead of the standard 2 bytes) to convey the UTF encoding length.
jaroslav@601
  2158
         */
jaroslav@601
  2159
        void writeLongUTF(String s) throws IOException {
jaroslav@601
  2160
            writeLongUTF(s, getUTFLength(s));
jaroslav@601
  2161
        }
jaroslav@601
  2162
jaroslav@601
  2163
        /**
jaroslav@601
  2164
         * Writes given string in "long" UTF format, where the UTF encoding
jaroslav@601
  2165
         * length of the string is already known.
jaroslav@601
  2166
         */
jaroslav@601
  2167
        void writeLongUTF(String s, long utflen) throws IOException {
jaroslav@601
  2168
            writeLong(utflen);
jaroslav@601
  2169
            if (utflen == (long) s.length()) {
jaroslav@601
  2170
                writeBytes(s);
jaroslav@601
  2171
            } else {
jaroslav@601
  2172
                writeUTFBody(s);
jaroslav@601
  2173
            }
jaroslav@601
  2174
        }
jaroslav@601
  2175
jaroslav@601
  2176
        /**
jaroslav@601
  2177
         * Writes the "body" (i.e., the UTF representation minus the 2-byte or
jaroslav@601
  2178
         * 8-byte length header) of the UTF encoding for the given string.
jaroslav@601
  2179
         */
jaroslav@601
  2180
        private void writeUTFBody(String s) throws IOException {
jaroslav@601
  2181
            int limit = MAX_BLOCK_SIZE - 3;
jaroslav@601
  2182
            int len = s.length();
jaroslav@601
  2183
            for (int off = 0; off < len; ) {
jaroslav@601
  2184
                int csize = Math.min(len - off, CHAR_BUF_SIZE);
jaroslav@601
  2185
                s.getChars(off, off + csize, cbuf, 0);
jaroslav@601
  2186
                for (int cpos = 0; cpos < csize; cpos++) {
jaroslav@601
  2187
                    char c = cbuf[cpos];
jaroslav@601
  2188
                    if (pos <= limit) {
jaroslav@601
  2189
                        if (c <= 0x007F && c != 0) {
jaroslav@601
  2190
                            buf[pos++] = (byte) c;
jaroslav@601
  2191
                        } else if (c > 0x07FF) {
jaroslav@601
  2192
                            buf[pos + 2] = (byte) (0x80 | ((c >> 0) & 0x3F));
jaroslav@601
  2193
                            buf[pos + 1] = (byte) (0x80 | ((c >> 6) & 0x3F));
jaroslav@601
  2194
                            buf[pos + 0] = (byte) (0xE0 | ((c >> 12) & 0x0F));
jaroslav@601
  2195
                            pos += 3;
jaroslav@601
  2196
                        } else {
jaroslav@601
  2197
                            buf[pos + 1] = (byte) (0x80 | ((c >> 0) & 0x3F));
jaroslav@601
  2198
                            buf[pos + 0] = (byte) (0xC0 | ((c >> 6) & 0x1F));
jaroslav@601
  2199
                            pos += 2;
jaroslav@601
  2200
                        }
jaroslav@601
  2201
                    } else {    // write one byte at a time to normalize block
jaroslav@601
  2202
                        if (c <= 0x007F && c != 0) {
jaroslav@601
  2203
                            write(c);
jaroslav@601
  2204
                        } else if (c > 0x07FF) {
jaroslav@601
  2205
                            write(0xE0 | ((c >> 12) & 0x0F));
jaroslav@601
  2206
                            write(0x80 | ((c >> 6) & 0x3F));
jaroslav@601
  2207
                            write(0x80 | ((c >> 0) & 0x3F));
jaroslav@601
  2208
                        } else {
jaroslav@601
  2209
                            write(0xC0 | ((c >> 6) & 0x1F));
jaroslav@601
  2210
                            write(0x80 | ((c >> 0) & 0x3F));
jaroslav@601
  2211
                        }
jaroslav@601
  2212
                    }
jaroslav@601
  2213
                }
jaroslav@601
  2214
                off += csize;
jaroslav@601
  2215
            }
jaroslav@601
  2216
        }
jaroslav@601
  2217
    }
jaroslav@601
  2218
jaroslav@601
  2219
    /**
jaroslav@601
  2220
     * Lightweight identity hash table which maps objects to integer handles,
jaroslav@601
  2221
     * assigned in ascending order.
jaroslav@601
  2222
     */
jaroslav@601
  2223
    private static class HandleTable {
jaroslav@601
  2224
jaroslav@601
  2225
        /* number of mappings in table/next available handle */
jaroslav@601
  2226
        private int size;
jaroslav@601
  2227
        /* size threshold determining when to expand hash spine */
jaroslav@601
  2228
        private int threshold;
jaroslav@601
  2229
        /* factor for computing size threshold */
jaroslav@601
  2230
        private final float loadFactor;
jaroslav@601
  2231
        /* maps hash value -> candidate handle value */
jaroslav@601
  2232
        private int[] spine;
jaroslav@601
  2233
        /* maps handle value -> next candidate handle value */
jaroslav@601
  2234
        private int[] next;
jaroslav@601
  2235
        /* maps handle value -> associated object */
jaroslav@601
  2236
        private Object[] objs;
jaroslav@601
  2237
jaroslav@601
  2238
        /**
jaroslav@601
  2239
         * Creates new HandleTable with given capacity and load factor.
jaroslav@601
  2240
         */
jaroslav@601
  2241
        HandleTable(int initialCapacity, float loadFactor) {
jaroslav@601
  2242
            this.loadFactor = loadFactor;
jaroslav@601
  2243
            spine = new int[initialCapacity];
jaroslav@601
  2244
            next = new int[initialCapacity];
jaroslav@601
  2245
            objs = new Object[initialCapacity];
jaroslav@601
  2246
            threshold = (int) (initialCapacity * loadFactor);
jaroslav@601
  2247
            clear();
jaroslav@601
  2248
        }
jaroslav@601
  2249
jaroslav@601
  2250
        /**
jaroslav@601
  2251
         * Assigns next available handle to given object, and returns handle
jaroslav@601
  2252
         * value.  Handles are assigned in ascending order starting at 0.
jaroslav@601
  2253
         */
jaroslav@601
  2254
        int assign(Object obj) {
jaroslav@601
  2255
            if (size >= next.length) {
jaroslav@601
  2256
                growEntries();
jaroslav@601
  2257
            }
jaroslav@601
  2258
            if (size >= threshold) {
jaroslav@601
  2259
                growSpine();
jaroslav@601
  2260
            }
jaroslav@601
  2261
            insert(obj, size);
jaroslav@601
  2262
            return size++;
jaroslav@601
  2263
        }
jaroslav@601
  2264
jaroslav@601
  2265
        /**
jaroslav@601
  2266
         * Looks up and returns handle associated with given object, or -1 if
jaroslav@601
  2267
         * no mapping found.
jaroslav@601
  2268
         */
jaroslav@601
  2269
        int lookup(Object obj) {
jaroslav@601
  2270
            if (size == 0) {
jaroslav@601
  2271
                return -1;
jaroslav@601
  2272
            }
jaroslav@601
  2273
            int index = hash(obj) % spine.length;
jaroslav@601
  2274
            for (int i = spine[index]; i >= 0; i = next[i]) {
jaroslav@601
  2275
                if (objs[i] == obj) {
jaroslav@601
  2276
                    return i;
jaroslav@601
  2277
                }
jaroslav@601
  2278
            }
jaroslav@601
  2279
            return -1;
jaroslav@601
  2280
        }
jaroslav@601
  2281
jaroslav@601
  2282
        /**
jaroslav@601
  2283
         * Resets table to its initial (empty) state.
jaroslav@601
  2284
         */
jaroslav@601
  2285
        void clear() {
jaroslav@601
  2286
            Arrays.fill(spine, -1);
jaroslav@601
  2287
            Arrays.fill(objs, 0, size, null);
jaroslav@601
  2288
            size = 0;
jaroslav@601
  2289
        }
jaroslav@601
  2290
jaroslav@601
  2291
        /**
jaroslav@601
  2292
         * Returns the number of mappings currently in table.
jaroslav@601
  2293
         */
jaroslav@601
  2294
        int size() {
jaroslav@601
  2295
            return size;
jaroslav@601
  2296
        }
jaroslav@601
  2297
jaroslav@601
  2298
        /**
jaroslav@601
  2299
         * Inserts mapping object -> handle mapping into table.  Assumes table
jaroslav@601
  2300
         * is large enough to accommodate new mapping.
jaroslav@601
  2301
         */
jaroslav@601
  2302
        private void insert(Object obj, int handle) {
jaroslav@601
  2303
            int index = hash(obj) % spine.length;
jaroslav@601
  2304
            objs[handle] = obj;
jaroslav@601
  2305
            next[handle] = spine[index];
jaroslav@601
  2306
            spine[index] = handle;
jaroslav@601
  2307
        }
jaroslav@601
  2308
jaroslav@601
  2309
        /**
jaroslav@601
  2310
         * Expands the hash "spine" -- equivalent to increasing the number of
jaroslav@601
  2311
         * buckets in a conventional hash table.
jaroslav@601
  2312
         */
jaroslav@601
  2313
        private void growSpine() {
jaroslav@601
  2314
            spine = new int[(spine.length << 1) + 1];
jaroslav@601
  2315
            threshold = (int) (spine.length * loadFactor);
jaroslav@601
  2316
            Arrays.fill(spine, -1);
jaroslav@601
  2317
            for (int i = 0; i < size; i++) {
jaroslav@601
  2318
                insert(objs[i], i);
jaroslav@601
  2319
            }
jaroslav@601
  2320
        }
jaroslav@601
  2321
jaroslav@601
  2322
        /**
jaroslav@601
  2323
         * Increases hash table capacity by lengthening entry arrays.
jaroslav@601
  2324
         */
jaroslav@601
  2325
        private void growEntries() {
jaroslav@601
  2326
            int newLength = (next.length << 1) + 1;
jaroslav@601
  2327
            int[] newNext = new int[newLength];
jaroslav@601
  2328
            System.arraycopy(next, 0, newNext, 0, size);
jaroslav@601
  2329
            next = newNext;
jaroslav@601
  2330
jaroslav@601
  2331
            Object[] newObjs = new Object[newLength];
jaroslav@601
  2332
            System.arraycopy(objs, 0, newObjs, 0, size);
jaroslav@601
  2333
            objs = newObjs;
jaroslav@601
  2334
        }
jaroslav@601
  2335
jaroslav@601
  2336
        /**
jaroslav@601
  2337
         * Returns hash value for given object.
jaroslav@601
  2338
         */
jaroslav@601
  2339
        private int hash(Object obj) {
jaroslav@601
  2340
            return System.identityHashCode(obj) & 0x7FFFFFFF;
jaroslav@601
  2341
        }
jaroslav@601
  2342
    }
jaroslav@601
  2343
jaroslav@601
  2344
    /**
jaroslav@601
  2345
     * Lightweight identity hash table which maps objects to replacement
jaroslav@601
  2346
     * objects.
jaroslav@601
  2347
     */
jaroslav@601
  2348
    private static class ReplaceTable {
jaroslav@601
  2349
jaroslav@601
  2350
        /* maps object -> index */
jaroslav@601
  2351
        private final HandleTable htab;
jaroslav@601
  2352
        /* maps index -> replacement object */
jaroslav@601
  2353
        private Object[] reps;
jaroslav@601
  2354
jaroslav@601
  2355
        /**
jaroslav@601
  2356
         * Creates new ReplaceTable with given capacity and load factor.
jaroslav@601
  2357
         */
jaroslav@601
  2358
        ReplaceTable(int initialCapacity, float loadFactor) {
jaroslav@601
  2359
            htab = new HandleTable(initialCapacity, loadFactor);
jaroslav@601
  2360
            reps = new Object[initialCapacity];
jaroslav@601
  2361
        }
jaroslav@601
  2362
jaroslav@601
  2363
        /**
jaroslav@601
  2364
         * Enters mapping from object to replacement object.
jaroslav@601
  2365
         */
jaroslav@601
  2366
        void assign(Object obj, Object rep) {
jaroslav@601
  2367
            int index = htab.assign(obj);
jaroslav@601
  2368
            while (index >= reps.length) {
jaroslav@601
  2369
                grow();
jaroslav@601
  2370
            }
jaroslav@601
  2371
            reps[index] = rep;
jaroslav@601
  2372
        }
jaroslav@601
  2373
jaroslav@601
  2374
        /**
jaroslav@601
  2375
         * Looks up and returns replacement for given object.  If no
jaroslav@601
  2376
         * replacement is found, returns the lookup object itself.
jaroslav@601
  2377
         */
jaroslav@601
  2378
        Object lookup(Object obj) {
jaroslav@601
  2379
            int index = htab.lookup(obj);
jaroslav@601
  2380
            return (index >= 0) ? reps[index] : obj;
jaroslav@601
  2381
        }
jaroslav@601
  2382
jaroslav@601
  2383
        /**
jaroslav@601
  2384
         * Resets table to its initial (empty) state.
jaroslav@601
  2385
         */
jaroslav@601
  2386
        void clear() {
jaroslav@601
  2387
            Arrays.fill(reps, 0, htab.size(), null);
jaroslav@601
  2388
            htab.clear();
jaroslav@601
  2389
        }
jaroslav@601
  2390
jaroslav@601
  2391
        /**
jaroslav@601
  2392
         * Returns the number of mappings currently in table.
jaroslav@601
  2393
         */
jaroslav@601
  2394
        int size() {
jaroslav@601
  2395
            return htab.size();
jaroslav@601
  2396
        }
jaroslav@601
  2397
jaroslav@601
  2398
        /**
jaroslav@601
  2399
         * Increases table capacity.
jaroslav@601
  2400
         */
jaroslav@601
  2401
        private void grow() {
jaroslav@601
  2402
            Object[] newReps = new Object[(reps.length << 1) + 1];
jaroslav@601
  2403
            System.arraycopy(reps, 0, newReps, 0, reps.length);
jaroslav@601
  2404
            reps = newReps;
jaroslav@601
  2405
        }
jaroslav@601
  2406
    }
jaroslav@601
  2407
jaroslav@601
  2408
    /**
jaroslav@601
  2409
     * Stack to keep debug information about the state of the
jaroslav@601
  2410
     * serialization process, for embedding in exception messages.
jaroslav@601
  2411
     */
jaroslav@601
  2412
    private static class DebugTraceInfoStack {
jaroslav@601
  2413
        private final List<String> stack;
jaroslav@601
  2414
jaroslav@601
  2415
        DebugTraceInfoStack() {
jaroslav@601
  2416
            stack = new ArrayList<>();
jaroslav@601
  2417
        }
jaroslav@601
  2418
jaroslav@601
  2419
        /**
jaroslav@601
  2420
         * Removes all of the elements from enclosed list.
jaroslav@601
  2421
         */
jaroslav@601
  2422
        void clear() {
jaroslav@601
  2423
            stack.clear();
jaroslav@601
  2424
        }
jaroslav@601
  2425
jaroslav@601
  2426
        /**
jaroslav@601
  2427
         * Removes the object at the top of enclosed list.
jaroslav@601
  2428
         */
jaroslav@601
  2429
        void pop() {
jaroslav@601
  2430
            stack.remove(stack.size()-1);
jaroslav@601
  2431
        }
jaroslav@601
  2432
jaroslav@601
  2433
        /**
jaroslav@601
  2434
         * Pushes a String onto the top of enclosed list.
jaroslav@601
  2435
         */
jaroslav@601
  2436
        void push(String entry) {
jaroslav@601
  2437
            stack.add("\t- " + entry);
jaroslav@601
  2438
        }
jaroslav@601
  2439
jaroslav@601
  2440
        /**
jaroslav@601
  2441
         * Returns a string representation of this object
jaroslav@601
  2442
         */
jaroslav@601
  2443
        public String toString() {
jaroslav@601
  2444
            StringBuilder buffer = new StringBuilder();
jaroslav@601
  2445
            if (!stack.isEmpty()) {
jaroslav@601
  2446
                for(int i = stack.size(); i > 0; i-- ) {
jaroslav@601
  2447
                    buffer.append(stack.get(i-1) + ((i != 1) ? "\n" : ""));
jaroslav@601
  2448
                }
jaroslav@601
  2449
            }
jaroslav@601
  2450
            return buffer.toString();
jaroslav@601
  2451
        }
jaroslav@601
  2452
    }
jaroslav@601
  2453
jaroslav@601
  2454
}