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