1 /*
2  * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */

25
26 package java.io;
27
28 import java.io.ObjectStreamClass.WeakClassKey;
29 import java.lang.ref.ReferenceQueue;
30 import java.security.AccessController;
31 import java.security.PrivilegedAction;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.List;
35 import java.util.StringJoiner;
36 import java.util.concurrent.ConcurrentHashMap;
37 import java.util.concurrent.ConcurrentMap;
38 import static java.io.ObjectStreamClass.processQueue;
39 import 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 (publicpackage, 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="{@docRoot}/../specs/serialization/output.html">
160  *     Object Serialization Specification, Section 2, Object Output Classes</a>
161  * @since       1.1
162  */

163 public class ObjectOutputStream
164     extends OutputStream implements ObjectOutput, ObjectStreamConstants
165 {
166
167     private static class Caches {
168         /** cache of subclass security audit results */
169         static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
170             new ConcurrentHashMap<>();
171
172         /** queue for WeakReferences to audited subclasses */
173         static final ReferenceQueue<Class<?>> subclassAuditsQueue =
174             new ReferenceQueue<>();
175     }
176
177     /** filter stream for handling block data conversion */
178     private final BlockDataOutputStream bout;
179     /** obj -> wire handle map */
180     private final HandleTable handles;
181     /** obj -> replacement obj map */
182     private final ReplaceTable subs;
183     /** stream protocol version */
184     private int protocol = PROTOCOL_VERSION_2;
185     /** recursion depth */
186     private int depth;
187
188     /** buffer for writing primitive field values */
189     private byte[] primVals;
190
191     /** if true, invoke writeObjectOverride() instead of writeObject() */
192     private final boolean enableOverride;
193     /** if true, invoke replaceObject() */
194     private boolean enableReplace;
195
196     // values below valid only during upcalls to writeObject()/writeExternal()
197     /**
198      * Context during upcalls to class-defined writeObject methods; holds
199      * object currently being serialized and descriptor for current class.
200      * Null when not during writeObject upcall.
201      */

202     private SerialCallbackContext curContext;
203     /** current PutField object */
204     private PutFieldImpl curPut;
205
206     /** custom storage for debug trace info */
207     private final DebugTraceInfoStack debugInfoStack;
208
209     /**
210      * value of "sun.io.serialization.extendedDebugInfo" property,
211      * as true or false for extended information about exception's place
212      */

213     private static final boolean extendedDebugInfo =
214         java.security.AccessController.doPrivileged(
215             new sun.security.action.GetBooleanAction(
216                 "sun.io.serialization.extendedDebugInfo")).booleanValue();
217
218     /**
219      * Creates an ObjectOutputStream that writes to the specified OutputStream.
220      * This constructor writes the serialization stream header to the
221      * underlying stream; callers may wish to flush the stream immediately to
222      * ensure that constructors for receiving ObjectInputStreams will not block
223      * when reading the header.
224      *
225      * <p>If a security manager is installed, this constructor will check for
226      * the "enableSubclassImplementation" SerializablePermission when invoked
227      * directly or indirectly by the constructor of a subclass which overrides
228      * the ObjectOutputStream.putFields or ObjectOutputStream.writeUnshared
229      * methods.
230      *
231      * @param   out output stream to write to
232      * @throws  IOException if an I/O error occurs while writing stream header
233      * @throws  SecurityException if untrusted subclass illegally overrides
234      *          security-sensitive methods
235      * @throws  NullPointerException if <code>out</code> is <code>null</code>
236      * @since   1.4
237      * @see     ObjectOutputStream#ObjectOutputStream()
238      * @see     ObjectOutputStream#putFields()
239      * @see     ObjectInputStream#ObjectInputStream(InputStream)
240      */

241     public ObjectOutputStream(OutputStream out) throws IOException {
242         verifySubclass();
243         bout = new BlockDataOutputStream(out);
244         handles = new HandleTable(10, (float) 3.00);
245         subs = new ReplaceTable(10, (float) 3.00);
246         enableOverride = false;
247         writeStreamHeader();
248         bout.setBlockDataMode(true);
249         if (extendedDebugInfo) {
250             debugInfoStack = new DebugTraceInfoStack();
251         } else {
252             debugInfoStack = null;
253         }
254     }
255
256     /**
257      * Provide a way for subclasses that are completely reimplementing
258      * ObjectOutputStream to not have to allocate private data just used by
259      * this implementation of ObjectOutputStream.
260      *
261      * <p>If there is a security manager installed, this method first calls the
262      * security manager's <code>checkPermission</code> method with a
263      * <code>SerializablePermission("enableSubclassImplementation")</code>
264      * permission to ensure it's ok to enable subclassing.
265      *
266      * @throws  SecurityException if a security manager exists and its
267      *          <code>checkPermission</code> method denies enabling
268      *          subclassing.
269      * @throws  IOException if an I/O error occurs while creating this stream
270      * @see SecurityManager#checkPermission
271      * @see java.io.SerializablePermission
272      */

273     protected ObjectOutputStream() throws IOException, SecurityException {
274         SecurityManager sm = System.getSecurityManager();
275         if (sm != null) {
276             sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
277         }
278         bout = null;
279         handles = null;
280         subs = null;
281         enableOverride = true;
282         debugInfoStack = null;
283     }
284
285     /**
286      * Specify stream protocol version to use when writing the stream.
287      *
288      * <p>This routine provides a hook to enable the current version of
289      * Serialization to write in a format that is backwards compatible to a
290      * previous version of the stream format.
291      *
292      * <p>Every effort will be made to avoid introducing additional
293      * backwards incompatibilities; however, sometimes there is no
294      * other alternative.
295      *
296      * @param   version use ProtocolVersion from java.io.ObjectStreamConstants.
297      * @throws  IllegalStateException if called after any objects
298      *          have been serialized.
299      * @throws  IllegalArgumentException if invalid version is passed in.
300      * @throws  IOException if I/O errors occur
301      * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1
302      * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_2
303      * @since   1.2
304      */

305     public void useProtocolVersion(int version) throws IOException {
306         if (handles.size() != 0) {
307             // REMIND: implement better check for pristine stream?
308             throw new IllegalStateException("stream non-empty");
309         }
310         switch (version) {
311             case PROTOCOL_VERSION_1:
312             case PROTOCOL_VERSION_2:
313                 protocol = version;
314                 break;
315
316             default:
317                 throw new IllegalArgumentException(
318                     "unknown version: " + version);
319         }
320     }
321
322     /**
323      * Write the specified object to the ObjectOutputStream.  The class of the
324      * object, the signature of the class, and the values of the non-transient
325      * and non-static fields of the class and all of its supertypes are
326      * written.  Default serialization for a class can be overridden using the
327      * writeObject and the readObject methods.  Objects referenced by this
328      * object are written transitively so that a complete equivalent graph of
329      * objects can be reconstructed by an ObjectInputStream.
330      *
331      * <p>Exceptions are thrown for problems with the OutputStream and for
332      * classes that should not be serialized.  All exceptions are fatal to the
333      * OutputStream, which is left in an indeterminate state, and it is up to
334      * the caller to ignore or recover the stream state.
335      *
336      * @throws  InvalidClassException Something is wrong with a class used by
337      *          serialization.
338      * @throws  NotSerializableException Some object to be serialized does not
339      *          implement the java.io.Serializable interface.
340      * @throws  IOException Any exception thrown by the underlying
341      *          OutputStream.
342      */

343     public final void writeObject(Object obj) throws IOException {
344         if (enableOverride) {
345             writeObjectOverride(obj);
346             return;
347         }
348         try {
349             writeObject0(obj, false);
350         } catch (IOException ex) {
351             if (depth == 0) {
352                 writeFatalException(ex);
353             }
354             throw ex;
355         }
356     }
357
358     /**
359      * Method used by subclasses to override the default writeObject method.
360      * This method is called by trusted subclasses of ObjectInputStream that
361      * constructed ObjectInputStream using the protected no-arg constructor.
362      * The subclass is expected to provide an override method with the modifier
363      * "final".
364      *
365      * @param   obj object to be written to the underlying stream
366      * @throws  IOException if there are I/O errors while writing to the
367      *          underlying stream
368      * @see #ObjectOutputStream()
369      * @see #writeObject(Object)
370      * @since 1.2
371      */

372     protected void writeObjectOverride(Object obj) throws IOException {
373     }
374
375     /**
376      * Writes an "unshared" object to the ObjectOutputStream.  This method is
377      * identical to writeObject, except that it always writes the given object
378      * as a new, unique object in the stream (as opposed to a back-reference
379      * pointing to a previously serialized instance).  Specifically:
380      * <ul>
381      *   <li>An object written via writeUnshared is always serialized in the
382      *       same manner as a newly appearing object (an object that has not
383      *       been written to the stream yet), regardless of whether or not the
384      *       object has been written previously.
385      *
386      *   <li>If writeObject is used to write an object that has been previously
387      *       written with writeUnshared, the previous writeUnshared operation
388      *       is treated as if it were a write of a separate object.  In other
389      *       words, ObjectOutputStream will never generate back-references to
390      *       object data written by calls to writeUnshared.
391      * </ul>
392      * While writing an object via writeUnshared does not in itself guarantee a
393      * unique reference to the object when it is deserialized, it allows a
394      * single object to be defined multiple times in a stream, so that multiple
395      * calls to readUnshared by the receiver will not conflict.  Note that the
396      * rules described above only apply to the base-level object written with
397      * writeUnshared, and not to any transitively referenced sub-objects in the
398      * object graph to be serialized.
399      *
400      * <p>ObjectOutputStream subclasses which override this method can only be
401      * constructed in security contexts possessing the
402      * "enableSubclassImplementation" SerializablePermission; any attempt to
403      * instantiate such a subclass without this permission will cause a
404      * SecurityException to be thrown.
405      *
406      * @param   obj object to write to stream
407      * @throws  NotSerializableException if an object in the graph to be
408      *          serialized does not implement the Serializable interface
409      * @throws  InvalidClassException if a problem exists with the class of an
410      *          object to be serialized
411      * @throws  IOException if an I/O error occurs during serialization
412      * @since 1.4
413      */

414     public void writeUnshared(Object obj) throws IOException {
415         try {
416             writeObject0(obj, true);
417         } catch (IOException ex) {
418             if (depth == 0) {
419                 writeFatalException(ex);
420             }
421             throw ex;
422         }
423     }
424
425     /**
426      * Write the non-static and non-transient fields of the current class to
427      * this stream.  This may only be called from the writeObject method of the
428      * class being serialized. It will throw the NotActiveException if it is
429      * called otherwise.
430      *
431      * @throws  IOException if I/O errors occur while writing to the underlying
432      *          <code>OutputStream</code>
433      */

434     public void defaultWriteObject() throws IOException {
435         SerialCallbackContext ctx = curContext;
436         if (ctx == null) {
437             throw new NotActiveException("not in call to writeObject");
438         }
439         Object curObj = ctx.getObj();
440         ObjectStreamClass curDesc = ctx.getDesc();
441         bout.setBlockDataMode(false);
442         defaultWriteFields(curObj, curDesc);
443         bout.setBlockDataMode(true);
444     }
445
446     /**
447      * Retrieve the object used to buffer persistent fields to be written to
448      * the stream.  The fields will be written to the stream when writeFields
449      * method is called.
450      *
451      * @return  an instance of the class Putfield that holds the serializable
452      *          fields
453      * @throws  IOException if I/O errors occur
454      * @since 1.2
455      */

456     public ObjectOutputStream.PutField putFields() throws IOException {
457         if (curPut == null) {
458             SerialCallbackContext ctx = curContext;
459             if (ctx == null) {
460                 throw new NotActiveException("not in call to writeObject");
461             }
462             ctx.checkAndSetUsed();
463             ObjectStreamClass curDesc = ctx.getDesc();
464             curPut = new PutFieldImpl(curDesc);
465         }
466         return curPut;
467     }
468
469     /**
470      * Write the buffered fields to the stream.
471      *
472      * @throws  IOException if I/O errors occur while writing to the underlying
473      *          stream
474      * @throws  NotActiveException Called when a classes writeObject method was
475      *          not called to write the state of the object.
476      * @since 1.2
477      */

478     public void writeFields() throws IOException {
479         if (curPut == null) {
480             throw new NotActiveException("no current PutField object");
481         }
482         bout.setBlockDataMode(false);
483         curPut.writeFields();
484         bout.setBlockDataMode(true);
485     }
486
487     /**
488      * Reset will disregard the state of any objects already written to the
489      * stream.  The state is reset to be the same as a new ObjectOutputStream.
490      * The current point in the stream is marked as reset so the corresponding
491      * ObjectInputStream will be reset at the same point.  Objects previously
492      * written to the stream will not be referred to as already being in the
493      * stream.  They will be written to the stream again.
494      *
495      * @throws  IOException if reset() is invoked while serializing an object.
496      */

497     public void reset() throws IOException {
498         if (depth != 0) {
499             throw new IOException("stream active");
500         }
501         bout.setBlockDataMode(false);
502         bout.writeByte(TC_RESET);
503         clear();
504         bout.setBlockDataMode(true);
505     }
506
507     /**
508      * Subclasses may implement this method to allow class data to be stored in
509      * the stream. By default this method does nothing.  The corresponding
510      * method in ObjectInputStream is resolveClass.  This method is called
511      * exactly once for each unique class in the stream.  The class name and
512      * signature will have already been written to the stream.  This method may
513      * make free use of the ObjectOutputStream to save any representation of
514      * the class it deems suitable (for example, the bytes of the class file).
515      * The resolveClass method in the corresponding subclass of
516      * ObjectInputStream must read and use any data or objects written by
517      * annotateClass.
518      *
519      * @param   cl the class to annotate custom data for
520      * @throws  IOException Any exception thrown by the underlying
521      *          OutputStream.
522      */

523     protected void annotateClass(Class<?> cl) throws IOException {
524     }
525
526     /**
527      * Subclasses may implement this method to store custom data in the stream
528      * along with descriptors for dynamic proxy classes.
529      *
530      * <p>This method is called exactly once for each unique proxy class
531      * descriptor in the stream.  The default implementation of this method in
532      * <code>ObjectOutputStream</code> does nothing.
533      *
534      * <p>The corresponding method in <code>ObjectInputStream</code> is
535      * <code>resolveProxyClass</code>.  For a given subclass of
536      * <code>ObjectOutputStream</code> that overrides this method, the
537      * <code>resolveProxyClass</code> method in the corresponding subclass of
538      * <code>ObjectInputStream</code> must read any data or objects written by
539      * <code>annotateProxyClass</code>.
540      *
541      * @param   cl the proxy class to annotate custom data for
542      * @throws  IOException any exception thrown by the underlying
543      *          <code>OutputStream</code>
544      * @see ObjectInputStream#resolveProxyClass(String[])
545      * @since   1.3
546      */

547     protected void annotateProxyClass(Class<?> cl) throws IOException {
548     }
549
550     /**
551      * This method will allow trusted subclasses of ObjectOutputStream to
552      * substitute one object for another during serialization. Replacing
553      * objects is disabled until enableReplaceObject is called. The
554      * enableReplaceObject method checks that the stream requesting to do
555      * replacement can be trusted.  The first occurrence of each object written
556      * into the serialization stream is passed to replaceObject.  Subsequent
557      * references to the object are replaced by the object returned by the
558      * original call to replaceObject.  To ensure that the private state of
559      * objects is not unintentionally exposed, only trusted streams may use
560      * replaceObject.
561      *
562      * <p>The ObjectOutputStream.writeObject method takes a parameter of type
563      * Object (as opposed to type Serializable) to allow for cases where
564      * non-serializable objects are replaced by serializable ones.
565      *
566      * <p>When a subclass is replacing objects it must insure that either a
567      * complementary substitution must be made during deserialization or that
568      * the substituted object is compatible with every field where the
569      * reference will be stored.  Objects whose type is not a subclass of the
570      * type of the field or array element abort the serialization by raising an
571      * exception and the object is not be stored.
572      *
573      * <p>This method is called only once when each object is first
574      * encountered.  All subsequent references to the object will be redirected
575      * to the new object. This method should return the object to be
576      * substituted or the original object.
577      *
578      * <p>Null can be returned as the object to be substituted, but may cause
579      * NullReferenceException in classes that contain references to the
580      * original object since they may be expecting an object instead of
581      * null.
582      *
583      * @param   obj the object to be replaced
584      * @return  the alternate object that replaced the specified one
585      * @throws  IOException Any exception thrown by the underlying
586      *          OutputStream.
587      */

588     protected Object replaceObject(Object obj) throws IOException {
589         return obj;
590     }
591
592     /**
593      * Enables the stream to do replacement of objects written to the stream.  When
594      * enabled, the {@link #replaceObject} method is called for every object being
595      * serialized.
596      *
597      * <p>If object replacement is currently not enabled, and
598      * {@code enable} is true, and there is a security manager installed,
599      * this method first calls the security manager's
600      * {@code checkPermission} method with the
601      * {@code SerializablePermission("enableSubstitution")} permission to
602      * ensure that the caller is permitted to enable the stream to do replacement
603      * of objects written to the stream.
604      *
605      * @param   enable true for enabling use of {@code replaceObject} for
606      *          every object being serialized
607      * @return  the previous setting before this method was invoked
608      * @throws  SecurityException if a security manager exists and its
609      *          {@code checkPermission} method denies enabling the stream
610      *          to do replacement of objects written to the stream.
611      * @see SecurityManager#checkPermission
612      * @see java.io.SerializablePermission
613      */

614     protected boolean enableReplaceObject(boolean enable)
615         throws SecurityException
616     {
617         if (enable == enableReplace) {
618             return enable;
619         }
620         if (enable) {
621             SecurityManager sm = System.getSecurityManager();
622             if (sm != null) {
623                 sm.checkPermission(SUBSTITUTION_PERMISSION);
624             }
625         }
626         enableReplace = enable;
627         return !enableReplace;
628     }
629
630     /**
631      * The writeStreamHeader method is provided so subclasses can append or
632      * prepend their own header to the stream.  It writes the magic number and
633      * version to the stream.
634      *
635      * @throws  IOException if I/O errors occur while writing to the underlying
636      *          stream
637      */

638     protected void writeStreamHeader() throws IOException {
639         bout.writeShort(STREAM_MAGIC);
640         bout.writeShort(STREAM_VERSION);
641     }
642
643     /**
644      * Write the specified class descriptor to the ObjectOutputStream.  Class
645      * descriptors are used to identify the classes of objects written to the
646      * stream.  Subclasses of ObjectOutputStream may override this method to
647      * customize the way in which class descriptors are written to the
648      * serialization stream.  The corresponding method in ObjectInputStream,
649      * <code>readClassDescriptor</code>, should then be overridden to
650      * reconstitute the class descriptor from its custom stream representation.
651      * By defaultthis method writes class descriptors according to the format
652      * defined in the Object Serialization specification.
653      *
654      * <p>Note that this method will only be called if the ObjectOutputStream
655      * is not using the old serialization stream format (set by calling
656      * ObjectOutputStream's <code>useProtocolVersion</code> method).  If this
657      * serialization stream is using the old format
658      * (<code>PROTOCOL_VERSION_1</code>), the class descriptor will be written
659      * internally in a manner that cannot be overridden or customized.
660      *
661      * @param   desc class descriptor to write to the stream
662      * @throws  IOException If an I/O error has occurred.
663      * @see java.io.ObjectInputStream#readClassDescriptor()
664      * @see #useProtocolVersion(int)
665      * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1
666      * @since 1.3
667      */

668     protected void writeClassDescriptor(ObjectStreamClass desc)
669         throws IOException
670     {
671         desc.writeNonProxy(this);
672     }
673
674     /**
675      * Writes a byte. This method will block until the byte is actually
676      * written.
677      *
678      * @param   val the byte to be written to the stream
679      * @throws  IOException If an I/O error has occurred.
680      */

681     public void write(int val) throws IOException {
682         bout.write(val);
683     }
684
685     /**
686      * Writes an array of bytes. This method will block until the bytes are
687      * actually written.
688      *
689      * @param   buf the data to be written
690      * @throws  IOException If an I/O error has occurred.
691      */

692     public void write(byte[] buf) throws IOException {
693         bout.write(buf, 0, buf.length, false);
694     }
695
696     /**
697      * Writes a sub array of bytes.
698      *
699      * @param   buf the data to be written
700      * @param   off the start offset in the data
701      * @param   len the number of bytes that are written
702      * @throws  IOException If an I/O error has occurred.
703      */

704     public void write(byte[] buf, int off, int len) throws IOException {
705         if (buf == null) {
706             throw new NullPointerException();
707         }
708         int endoff = off + len;
709         if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
710             throw new IndexOutOfBoundsException();
711         }
712         bout.write(buf, off, len, false);
713     }
714
715     /**
716      * Flushes the stream. This will write any buffered output bytes and flush
717      * through to the underlying stream.
718      *
719      * @throws  IOException If an I/O error has occurred.
720      */

721     public void flush() throws IOException {
722         bout.flush();
723     }
724
725     /**
726      * Drain any buffered data in ObjectOutputStream.  Similar to flush but
727      * does not propagate the flush to the underlying stream.
728      *
729      * @throws  IOException if I/O errors occur while writing to the underlying
730      *          stream
731      */

732     protected void drain() throws IOException {
733         bout.drain();
734     }
735
736     /**
737      * Closes the stream. This method must be called to release any resources
738      * associated with the stream.
739      *
740      * @throws  IOException If an I/O error has occurred.
741      */

742     public void close() throws IOException {
743         flush();
744         clear();
745         bout.close();
746     }
747
748     /**
749      * Writes a boolean.
750      *
751      * @param   val the boolean to be written
752      * @throws  IOException if I/O errors occur while writing to the underlying
753      *          stream
754      */

755     public void writeBoolean(boolean val) throws IOException {
756         bout.writeBoolean(val);
757     }
758
759     /**
760      * Writes an 8 bit byte.
761      *
762      * @param   val the byte value to be written
763      * @throws  IOException if I/O errors occur while writing to the underlying
764      *          stream
765      */

766     public void writeByte(int val) throws IOException  {
767         bout.writeByte(val);
768     }
769
770     /**
771      * Writes a 16 bit short.
772      *
773      * @param   val the short value to be written
774      * @throws  IOException if I/O errors occur while writing to the underlying
775      *          stream
776      */

777     public void writeShort(int val)  throws IOException {
778         bout.writeShort(val);
779     }
780
781     /**
782      * Writes a 16 bit char.
783      *
784      * @param   val the char value to be written
785      * @throws  IOException if I/O errors occur while writing to the underlying
786      *          stream
787      */

788     public void writeChar(int val)  throws IOException {
789         bout.writeChar(val);
790     }
791
792     /**
793      * Writes a 32 bit int.
794      *
795      * @param   val the integer value to be written
796      * @throws  IOException if I/O errors occur while writing to the underlying
797      *          stream
798      */

799     public void writeInt(int val)  throws IOException {
800         bout.writeInt(val);
801     }
802
803     /**
804      * Writes a 64 bit long.
805      *
806      * @param   val the long value to be written
807      * @throws  IOException if I/O errors occur while writing to the underlying
808      *          stream
809      */

810     public void writeLong(long val)  throws IOException {
811         bout.writeLong(val);
812     }
813
814     /**
815      * Writes a 32 bit float.
816      *
817      * @param   val the float value to be written
818      * @throws  IOException if I/O errors occur while writing to the underlying
819      *          stream
820      */

821     public void writeFloat(float val) throws IOException {
822         bout.writeFloat(val);
823     }
824
825     /**
826      * Writes a 64 bit double.
827      *
828      * @param   val the double value to be written
829      * @throws  IOException if I/O errors occur while writing to the underlying
830      *          stream
831      */

832     public void writeDouble(double val) throws IOException {
833         bout.writeDouble(val);
834     }
835
836     /**
837      * Writes a String as a sequence of bytes.
838      *
839      * @param   str the String of bytes to be written
840      * @throws  IOException if I/O errors occur while writing to the underlying
841      *          stream
842      */

843     public void writeBytes(String str) throws IOException {
844         bout.writeBytes(str);
845     }
846
847     /**
848      * Writes a String as a sequence of chars.
849      *
850      * @param   str the String of chars to be written
851      * @throws  IOException if I/O errors occur while writing to the underlying
852      *          stream
853      */

854     public void writeChars(String str) throws IOException {
855         bout.writeChars(str);
856     }
857
858     /**
859      * Primitive data write of this String in
860      * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
861      * format.  Note that there is a
862      * significant difference between writing a String into the stream as
863      * primitive data or as an Object. A String instance written by writeObject
864      * is written into the stream as a String initially. Future writeObject()
865      * calls write references to the string into the stream.
866      *
867      * @param   str the String to be written
868      * @throws  IOException if I/O errors occur while writing to the underlying
869      *          stream
870      */

871     public void writeUTF(String str) throws IOException {
872         bout.writeUTF(str);
873     }
874
875     /**
876      * Provide programmatic access to the persistent fields to be written
877      * to ObjectOutput.
878      *
879      * @since 1.2
880      */

881     public abstract static class PutField {
882
883         /**
884          * Put the value of the named boolean field into the persistent field.
885          *
886          * @param  name the name of the serializable field
887          * @param  val the value to assign to the field
888          * @throws IllegalArgumentException if <code>name</code> does not
889          * match the name of a serializable field for the class whose fields
890          * are being written, or if the type of the named field is not
891          * <code>boolean</code>
892          */

893         public abstract void put(String name, boolean val);
894
895         /**
896          * Put the value of the named byte field into the persistent field.
897          *
898          * @param  name the name of the serializable field
899          * @param  val the value to assign to the field
900          * @throws IllegalArgumentException if <code>name</code> does not
901          * match the name of a serializable field for the class whose fields
902          * are being written, or if the type of the named field is not
903          * <code>byte</code>
904          */

905         public abstract void put(String name, byte val);
906
907         /**
908          * Put the value of the named char field into the persistent field.
909          *
910          * @param  name the name of the serializable field
911          * @param  val the value to assign to the field
912          * @throws IllegalArgumentException if <code>name</code> does not
913          * match the name of a serializable field for the class whose fields
914          * are being written, or if the type of the named field is not
915          * <code>char</code>
916          */

917         public abstract void put(String name, char val);
918
919         /**
920          * Put the value of the named short field into the persistent field.
921          *
922          * @param  name the name of the serializable field
923          * @param  val the value to assign to the field
924          * @throws IllegalArgumentException if <code>name</code> does not
925          * match the name of a serializable field for the class whose fields
926          * are being written, or if the type of the named field is not
927          * <code>short</code>
928          */

929         public abstract void put(String name, short val);
930
931         /**
932          * Put the value of the named int field into the persistent field.
933          *
934          * @param  name the name of the serializable field
935          * @param  val the value to assign to the field
936          * @throws IllegalArgumentException if <code>name</code> does not
937          * match the name of a serializable field for the class whose fields
938          * are being written, or if the type of the named field is not
939          * <code>int</code>
940          */

941         public abstract void put(String name, int val);
942
943         /**
944          * Put the value of the named long field into the persistent field.
945          *
946          * @param  name the name of the serializable field
947          * @param  val the value to assign to the field
948          * @throws IllegalArgumentException if <code>name</code> does not
949          * match the name of a serializable field for the class whose fields
950          * are being written, or if the type of the named field is not
951          * <code>long</code>
952          */

953         public abstract void put(String name, long val);
954
955         /**
956          * Put the value of the named float field into the persistent field.
957          *
958          * @param  name the name of the serializable field
959          * @param  val the value to assign to the field
960          * @throws IllegalArgumentException if <code>name</code> does not
961          * match the name of a serializable field for the class whose fields
962          * are being written, or if the type of the named field is not
963          * <code>float</code>
964          */

965         public abstract void put(String name, float val);
966
967         /**
968          * Put the value of the named double field into the persistent field.
969          *
970          * @param  name the name of the serializable field
971          * @param  val the value to assign to the field
972          * @throws IllegalArgumentException if <code>name</code> does not
973          * match the name of a serializable field for the class whose fields
974          * are being written, or if the type of the named field is not
975          * <code>double</code>
976          */

977         public abstract void put(String name, double val);
978
979         /**
980          * Put the value of the named Object field into the persistent field.
981          *
982          * @param  name the name of the serializable field
983          * @param  val the value to assign to the field
984          *         (which may be <code>null</code>)
985          * @throws IllegalArgumentException if <code>name</code> does not
986          * match the name of a serializable field for the class whose fields
987          * are being written, or if the type of the named field is not a
988          * reference type
989          */

990         public abstract void put(String name, Object val);
991
992         /**
993          * Write the data and fields to the specified ObjectOutput stream,
994          * which must be the same stream that produced this
995          * <code>PutField</code> object.
996          *
997          * @param  out the stream to write the data and fields to
998          * @throws IOException if I/O errors occur while writing to the
999          *         underlying stream
1000          * @throws IllegalArgumentException if the specified stream is not
1001          *         the same stream that produced this <code>PutField</code>
1002          *         object
1003          * @deprecated This method does not write the values contained by this
1004          *         <code>PutField</code> object in a proper format, and may
1005          *         result in corruption of the serialization stream.  The
1006          *         correct way to write <code>PutField</code> data is by
1007          *         calling the {@link java.io.ObjectOutputStream#writeFields()}
1008          *         method.
1009          */

1010         @Deprecated
1011         public abstract void write(ObjectOutput out) throws IOException;
1012     }
1013
1014
1015     /**
1016      * Returns protocol version in use.
1017      */

1018     int getProtocolVersion() {
1019         return protocol;
1020     }
1021
1022     /**
1023      * Writes string without allowing it to be replaced in stream.  Used by
1024      * ObjectStreamClass to write class descriptor type strings.
1025      */

1026     void writeTypeString(String str) throws IOException {
1027         int handle;
1028         if (str == null) {
1029             writeNull();
1030         } else if ((handle = handles.lookup(str)) != -1) {
1031             writeHandle(handle);
1032         } else {
1033             writeString(str, false);
1034         }
1035     }
1036
1037     /**
1038      * Verifies that this (possibly subclass) instance can be constructed
1039      * without violating security constraints: the subclass must not override
1040      * security-sensitive non-final methods, or else the
1041      * "enableSubclassImplementation" SerializablePermission is checked.
1042      */

1043     private void verifySubclass() {
1044         Class<?> cl = getClass();
1045         if (cl == ObjectOutputStream.class) {
1046             return;
1047         }
1048         SecurityManager sm = System.getSecurityManager();
1049         if (sm == null) {
1050             return;
1051         }
1052         processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
1053         WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
1054         Boolean result = Caches.subclassAudits.get(key);
1055         if (result == null) {
1056             result = auditSubclass(cl);
1057             Caches.subclassAudits.putIfAbsent(key, result);
1058         }
1059         if (!result) {
1060             sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
1061         }
1062     }
1063
1064     /**
1065      * Performs reflective checks on given subclass to verify that it doesn't
1066      * override security-sensitive non-final methods.  Returns TRUE if subclass
1067      * is "safe", FALSE otherwise.
1068      */

1069     private static Boolean auditSubclass(Class<?> subcl) {
1070         return AccessController.doPrivileged(
1071             new PrivilegedAction<>() {
1072                 public Boolean run() {
1073                     for (Class<?> cl = subcl;
1074                          cl != ObjectOutputStream.class;
1075                          cl = cl.getSuperclass())
1076                     {
1077                         try {
1078                             cl.getDeclaredMethod(
1079                                 "writeUnshared"new Class<?>[] { Object.class });
1080                             return Boolean.FALSE;
1081                         } catch (NoSuchMethodException ex) {
1082                         }
1083                         try {
1084                             cl.getDeclaredMethod("putFields", (Class<?>[]) null);
1085                             return Boolean.FALSE;
1086                         } catch (NoSuchMethodException ex) {
1087                         }
1088                     }
1089                     return Boolean.TRUE;
1090                 }
1091             }
1092         );
1093     }
1094
1095     /**
1096      * Clears internal data structures.
1097      */

1098     private void clear() {
1099         subs.clear();
1100         handles.clear();
1101     }
1102
1103     /**
1104      * Underlying writeObject/writeUnshared implementation.
1105      */

1106     private void writeObject0(Object obj, boolean unshared)
1107         throws IOException
1108     {
1109         boolean oldMode = bout.setBlockDataMode(false);
1110         depth++;
1111         try {
1112             // handle previously written and non-replaceable objects
1113             int h;
1114             if ((obj = subs.lookup(obj)) == null) {
1115                 writeNull();
1116                 return;
1117             } else if (!unshared && (h = handles.lookup(obj)) != -1) {
1118                 writeHandle(h);
1119                 return;
1120             } else if (obj instanceof Class) {
1121                 writeClass((Class) obj, unshared);
1122                 return;
1123             } else if (obj instanceof ObjectStreamClass) {
1124                 writeClassDesc((ObjectStreamClass) obj, unshared);
1125                 return;
1126             }
1127
1128             // check for replacement object
1129             Object orig = obj;
1130             Class<?> cl = obj.getClass();
1131             ObjectStreamClass desc;
1132             for (;;) {
1133                 // REMIND: skip this check for strings/arrays?
1134                 Class<?> repCl;
1135                 desc = ObjectStreamClass.lookup(cl, true);
1136                 if (!desc.hasWriteReplaceMethod() ||
1137                     (obj = desc.invokeWriteReplace(obj)) == null ||
1138                     (repCl = obj.getClass()) == cl)
1139                 {
1140                     break;
1141                 }
1142                 cl = repCl;
1143             }
1144             if (enableReplace) {
1145                 Object rep = replaceObject(obj);
1146                 if (rep != obj && rep != null) {
1147                     cl = rep.getClass();
1148                     desc = ObjectStreamClass.lookup(cl, true);
1149                 }
1150                 obj = rep;
1151             }
1152
1153             // if object replaced, run through original checks a second time
1154             if (obj != orig) {
1155                 subs.assign(orig, obj);
1156                 if (obj == null) {
1157                     writeNull();
1158                     return;
1159                 } else if (!unshared && (h = handles.lookup(obj)) != -1) {
1160                     writeHandle(h);
1161                     return;
1162                 } else if (obj instanceof Class) {
1163                     writeClass((Class) obj, unshared);
1164                     return;
1165                 } else if (obj instanceof ObjectStreamClass) {
1166                     writeClassDesc((ObjectStreamClass) obj, unshared);
1167                     return;
1168                 }
1169             }
1170
1171             // remaining cases
1172             if (obj instanceof String) {
1173                 writeString((String) obj, unshared);
1174             } else if (cl.isArray()) {
1175                 writeArray(obj, desc, unshared);
1176             } else if (obj instanceof Enum) {
1177                 writeEnum((Enum<?>) obj, desc, unshared);
1178             } else if (obj instanceof Serializable) {
1179                 writeOrdinaryObject(obj, desc, unshared);
1180             } else {
1181                 if (extendedDebugInfo) {
1182                     throw new NotSerializableException(
1183                         cl.getName() + "\n" + debugInfoStack.toString());
1184                 } else {
1185                     throw new NotSerializableException(cl.getName());
1186                 }
1187             }
1188         } finally {
1189             depth--;
1190             bout.setBlockDataMode(oldMode);
1191         }
1192     }
1193
1194     /**
1195      * Writes null code to stream.
1196      */

1197     private void writeNull() throws IOException {
1198         bout.writeByte(TC_NULL);
1199     }
1200
1201     /**
1202      * Writes given object handle to stream.
1203      */

1204     private void writeHandle(int handle) throws IOException {
1205         bout.writeByte(TC_REFERENCE);
1206         bout.writeInt(baseWireHandle + handle);
1207     }
1208
1209     /**
1210      * Writes representation of given class to stream.
1211      */

1212     private void writeClass(Class<?> cl, boolean unshared) throws IOException {
1213         bout.writeByte(TC_CLASS);
1214         writeClassDesc(ObjectStreamClass.lookup(cl, true), false);
1215         handles.assign(unshared ? null : cl);
1216     }
1217
1218     /**
1219      * Writes representation of given class descriptor to stream.
1220      */

1221     private void writeClassDesc(ObjectStreamClass desc, boolean unshared)
1222         throws IOException
1223     {
1224         int handle;
1225         if (desc == null) {
1226             writeNull();
1227         } else if (!unshared && (handle = handles.lookup(desc)) != -1) {
1228             writeHandle(handle);
1229         } else if (desc.isProxy()) {
1230             writeProxyDesc(desc, unshared);
1231         } else {
1232             writeNonProxyDesc(desc, unshared);
1233         }
1234     }
1235
1236     private boolean isCustomSubclass() {
1237         // Return true if this class is a custom subclass of ObjectOutputStream
1238         return getClass().getClassLoader()
1239                    != ObjectOutputStream.class.getClassLoader();
1240     }
1241
1242     /**
1243      * Writes class descriptor representing a dynamic proxy class to stream.
1244      */

1245     private void writeProxyDesc(ObjectStreamClass desc, boolean unshared)
1246         throws IOException
1247     {
1248         bout.writeByte(TC_PROXYCLASSDESC);
1249         handles.assign(unshared ? null : desc);
1250
1251         Class<?> cl = desc.forClass();
1252         Class<?>[] ifaces = cl.getInterfaces();
1253         bout.writeInt(ifaces.length);
1254         for (int i = 0; i < ifaces.length; i++) {
1255             bout.writeUTF(ifaces[i].getName());
1256         }
1257
1258         bout.setBlockDataMode(true);
1259         if (cl != null && isCustomSubclass()) {
1260             ReflectUtil.checkPackageAccess(cl);
1261         }
1262         annotateProxyClass(cl);
1263         bout.setBlockDataMode(false);
1264         bout.writeByte(TC_ENDBLOCKDATA);
1265
1266         writeClassDesc(desc.getSuperDesc(), false);
1267     }
1268
1269     /**
1270      * Writes class descriptor representing a standard (i.e., not a dynamic
1271      * proxy) class to stream.
1272      */

1273     private void writeNonProxyDesc(ObjectStreamClass desc, boolean unshared)
1274         throws IOException
1275     {
1276         bout.writeByte(TC_CLASSDESC);
1277         handles.assign(unshared ? null : desc);
1278
1279         if (protocol == PROTOCOL_VERSION_1) {
1280             // do not invoke class descriptor write hook with old protocol
1281             desc.writeNonProxy(this);
1282         } else {
1283             writeClassDescriptor(desc);
1284         }
1285
1286         Class<?> cl = desc.forClass();
1287         bout.setBlockDataMode(true);
1288         if (cl != null && isCustomSubclass()) {
1289             ReflectUtil.checkPackageAccess(cl);
1290         }
1291         annotateClass(cl);
1292         bout.setBlockDataMode(false);
1293         bout.writeByte(TC_ENDBLOCKDATA);
1294
1295         writeClassDesc(desc.getSuperDesc(), false);
1296     }
1297
1298     /**
1299      * Writes given string to stream, using standard or long UTF format
1300      * depending on string length.
1301      */

1302     private void writeString(String str, boolean unshared) throws IOException {
1303         handles.assign(unshared ? null : str);
1304         long utflen = bout.getUTFLength(str);
1305         if (utflen <= 0xFFFF) {
1306             bout.writeByte(TC_STRING);
1307             bout.writeUTF(str, utflen);
1308         } else {
1309             bout.writeByte(TC_LONGSTRING);
1310             bout.writeLongUTF(str, utflen);
1311         }
1312     }
1313
1314     /**
1315      * Writes given array object to stream.
1316      */

1317     private void writeArray(Object array,
1318                             ObjectStreamClass desc,
1319                             boolean unshared)
1320         throws IOException
1321     {
1322         bout.writeByte(TC_ARRAY);
1323         writeClassDesc(desc, false);
1324         handles.assign(unshared ? null : array);
1325
1326         Class<?> ccl = desc.forClass().getComponentType();
1327         if (ccl.isPrimitive()) {
1328             if (ccl == Integer.TYPE) {
1329                 int[] ia = (int[]) array;
1330                 bout.writeInt(ia.length);
1331                 bout.writeInts(ia, 0, ia.length);
1332             } else if (ccl == Byte.TYPE) {
1333                 byte[] ba = (byte[]) array;
1334                 bout.writeInt(ba.length);
1335                 bout.write(ba, 0, ba.length, true);
1336             } else if (ccl == Long.TYPE) {
1337                 long[] ja = (long[]) array;
1338                 bout.writeInt(ja.length);
1339                 bout.writeLongs(ja, 0, ja.length);
1340             } else if (ccl == Float.TYPE) {
1341                 float[] fa = (float[]) array;
1342                 bout.writeInt(fa.length);
1343                 bout.writeFloats(fa, 0, fa.length);
1344             } else if (ccl == Double.TYPE) {
1345                 double[] da = (double[]) array;
1346                 bout.writeInt(da.length);
1347                 bout.writeDoubles(da, 0, da.length);
1348             } else if (ccl == Short.TYPE) {
1349                 short[] sa = (short[]) array;
1350                 bout.writeInt(sa.length);
1351                 bout.writeShorts(sa, 0, sa.length);
1352             } else if (ccl == Character.TYPE) {
1353                 char[] ca = (char[]) array;
1354                 bout.writeInt(ca.length);
1355                 bout.writeChars(ca, 0, ca.length);
1356             } else if (ccl == Boolean.TYPE) {
1357                 boolean[] za = (boolean[]) array;
1358                 bout.writeInt(za.length);
1359                 bout.writeBooleans(za, 0, za.length);
1360             } else {
1361                 throw new InternalError();
1362             }
1363         } else {
1364             Object[] objs = (Object[]) array;
1365             int len = objs.length;
1366             bout.writeInt(len);
1367             if (extendedDebugInfo) {
1368                 debugInfoStack.push(
1369                     "array (class \"" + array.getClass().getName() +
1370                     "\", size: " + len  + ")");
1371             }
1372             try {
1373                 for (int i = 0; i < len; i++) {
1374                     if (extendedDebugInfo) {
1375                         debugInfoStack.push(
1376                             "element of array (index: " + i + ")");
1377                     }
1378                     try {
1379                         writeObject0(objs[i], false);
1380                     } finally {
1381                         if (extendedDebugInfo) {
1382                             debugInfoStack.pop();
1383                         }
1384                     }
1385                 }
1386             } finally {
1387                 if (extendedDebugInfo) {
1388                     debugInfoStack.pop();
1389                 }
1390             }
1391         }
1392     }
1393
1394     /**
1395      * Writes given enum constant to stream.
1396      */

1397     private void writeEnum(Enum<?> en,
1398                            ObjectStreamClass desc,
1399                            boolean unshared)
1400         throws IOException
1401     {
1402         bout.writeByte(TC_ENUM);
1403         ObjectStreamClass sdesc = desc.getSuperDesc();
1404         writeClassDesc((sdesc.forClass() == Enum.class) ? desc : sdesc, false);
1405         handles.assign(unshared ? null : en);
1406         writeString(en.name(), false);
1407     }
1408
1409     /**
1410      * Writes representation of a "ordinary" (i.e., not a String, Class,
1411      * ObjectStreamClass, array, or enum constant) serializable object to the
1412      * stream.
1413      */

1414     private void writeOrdinaryObject(Object obj,
1415                                      ObjectStreamClass desc,
1416                                      boolean unshared)
1417         throws IOException
1418     {
1419         if (extendedDebugInfo) {
1420             debugInfoStack.push(
1421                 (depth == 1 ? "root " : "") + "object (class \"" +
1422                 obj.getClass().getName() + "\"" + obj.toString() + ")");
1423         }
1424         try {
1425             desc.checkSerialize();
1426
1427             bout.writeByte(TC_OBJECT);
1428             writeClassDesc(desc, false);
1429             handles.assign(unshared ? null : obj);
1430             if (desc.isExternalizable() && !desc.isProxy()) {
1431                 writeExternalData((Externalizable) obj);
1432             } else {
1433                 writeSerialData(obj, desc);
1434             }
1435         } finally {
1436             if (extendedDebugInfo) {
1437                 debugInfoStack.pop();
1438             }
1439         }
1440     }
1441
1442     /**
1443      * Writes externalizable data of given object by invoking its
1444      * writeExternal() method.
1445      */

1446     private void writeExternalData(Externalizable obj) throws IOException {
1447         PutFieldImpl oldPut = curPut;
1448         curPut = null;
1449
1450         if (extendedDebugInfo) {
1451             debugInfoStack.push("writeExternal data");
1452         }
1453         SerialCallbackContext oldContext = curContext;
1454         try {
1455             curContext = null;
1456             if (protocol == PROTOCOL_VERSION_1) {
1457                 obj.writeExternal(this);
1458             } else {
1459                 bout.setBlockDataMode(true);
1460                 obj.writeExternal(this);
1461                 bout.setBlockDataMode(false);
1462                 bout.writeByte(TC_ENDBLOCKDATA);
1463             }
1464         } finally {
1465             curContext = oldContext;
1466             if (extendedDebugInfo) {
1467                 debugInfoStack.pop();
1468             }
1469         }
1470
1471         curPut = oldPut;
1472     }
1473
1474     /**
1475      * Writes instance data for each serializable class of given object, from
1476      * superclass to subclass.
1477      */

1478     private void writeSerialData(Object obj, ObjectStreamClass desc)
1479         throws IOException
1480     {
1481         ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
1482         for (int i = 0; i < slots.length; i++) {
1483             ObjectStreamClass slotDesc = slots[i].desc;
1484             if (slotDesc.hasWriteObjectMethod()) {
1485                 PutFieldImpl oldPut = curPut;
1486                 curPut = null;
1487                 SerialCallbackContext oldContext = curContext;
1488
1489                 if (extendedDebugInfo) {
1490                     debugInfoStack.push(
1491                         "custom writeObject data (class \"" +
1492                         slotDesc.getName() + "\")");
1493                 }
1494                 try {
1495                     curContext = new SerialCallbackContext(obj, slotDesc);
1496                     bout.setBlockDataMode(true);
1497                     slotDesc.invokeWriteObject(obj, this);
1498                     bout.setBlockDataMode(false);
1499                     bout.writeByte(TC_ENDBLOCKDATA);
1500                 } finally {
1501                     curContext.setUsed();
1502                     curContext = oldContext;
1503                     if (extendedDebugInfo) {
1504                         debugInfoStack.pop();
1505                     }
1506                 }
1507
1508                 curPut = oldPut;
1509             } else {
1510                 defaultWriteFields(obj, slotDesc);
1511             }
1512         }
1513     }
1514
1515     /**
1516      * Fetches and writes values of serializable fields of given object to
1517      * stream.  The given class descriptor specifies which field values to
1518      * write, and in which order they should be written.
1519      */

1520     private void defaultWriteFields(Object obj, ObjectStreamClass desc)
1521         throws IOException
1522     {
1523         Class<?> cl = desc.forClass();
1524         if (cl != null && obj != null && !cl.isInstance(obj)) {
1525             throw new ClassCastException();
1526         }
1527
1528         desc.checkDefaultSerialize();
1529
1530         int primDataSize = desc.getPrimDataSize();
1531         if (primDataSize > 0) {
1532             if (primVals == null || primVals.length < primDataSize) {
1533                 primVals = new byte[primDataSize];
1534             }
1535             desc.getPrimFieldValues(obj, primVals);
1536             bout.write(primVals, 0, primDataSize, false);
1537         }
1538
1539         int numObjFields = desc.getNumObjFields();
1540         if (numObjFields > 0) {
1541             ObjectStreamField[] fields = desc.getFields(false);
1542             Object[] objVals = new Object[numObjFields];
1543             int numPrimFields = fields.length - objVals.length;
1544             desc.getObjFieldValues(obj, objVals);
1545             for (int i = 0; i < objVals.length; i++) {
1546                 if (extendedDebugInfo) {
1547                     debugInfoStack.push(
1548                         "field (class \"" + desc.getName() + "\", name: \"" +
1549                         fields[numPrimFields + i].getName() + "\", type: \"" +
1550                         fields[numPrimFields + i].getType() + "\")");
1551                 }
1552                 try {
1553                     writeObject0(objVals[i],
1554                                  fields[numPrimFields + i].isUnshared());
1555                 } finally {
1556                     if (extendedDebugInfo) {
1557                         debugInfoStack.pop();
1558                     }
1559                 }
1560             }
1561         }
1562     }
1563
1564     /**
1565      * Attempts to write to stream fatal IOException that has caused
1566      * serialization to abort.
1567      */

1568     private void writeFatalException(IOException ex) throws IOException {
1569         /*
1570          * Note: the serialization specification states that if a second
1571          * IOException occurs while attempting to serialize the original fatal
1572          * exception to the stream, then a StreamCorruptedException should be
1573          * thrown (section 2.1).  However, due to a bug in previous
1574          * implementations of serialization, StreamCorruptedExceptions were
1575          * rarely (if ever) actually thrown--the "root" exceptions from
1576          * underlying streams were thrown instead.  This historical behavior is
1577          * followed here for consistency.
1578          */

1579         clear();
1580         boolean oldMode = bout.setBlockDataMode(false);
1581         try {
1582             bout.writeByte(TC_EXCEPTION);
1583             writeObject0(ex, false);
1584             clear();
1585         } finally {
1586             bout.setBlockDataMode(oldMode);
1587         }
1588     }
1589
1590     /**
1591      * Converts specified span of float values into byte values.
1592      */

1593     // REMIND: remove once hotspot inlines Float.floatToIntBits
1594     private static native void floatsToBytes(float[] src, int srcpos,
1595                                              byte[] dst, int dstpos,
1596                                              int nfloats);
1597
1598     /**
1599      * Converts specified span of double values into byte values.
1600      */

1601     // REMIND: remove once hotspot inlines Double.doubleToLongBits
1602     private static native void doublesToBytes(double[] src, int srcpos,
1603                                               byte[] dst, int dstpos,
1604                                               int ndoubles);
1605
1606     /**
1607      * Default PutField implementation.
1608      */

1609     private class PutFieldImpl extends PutField {
1610
1611         /** class descriptor describing serializable fields */
1612         private final ObjectStreamClass desc;
1613         /** primitive field values */
1614         private final byte[] primVals;
1615         /** object field values */
1616         private final Object[] objVals;
1617
1618         /**
1619          * Creates PutFieldImpl object for writing fields defined in given
1620          * class descriptor.
1621          */

1622         PutFieldImpl(ObjectStreamClass desc) {
1623             this.desc = desc;
1624             primVals = new byte[desc.getPrimDataSize()];
1625             objVals = new Object[desc.getNumObjFields()];
1626         }
1627
1628         public void put(String name, boolean val) {
1629             Bits.putBoolean(primVals, getFieldOffset(name, Boolean.TYPE), val);
1630         }
1631
1632         public void put(String name, byte val) {
1633             primVals[getFieldOffset(name, Byte.TYPE)] = val;
1634         }
1635
1636         public void put(String name, char val) {
1637             Bits.putChar(primVals, getFieldOffset(name, Character.TYPE), val);
1638         }
1639
1640         public void put(String name, short val) {
1641             Bits.putShort(primVals, getFieldOffset(name, Short.TYPE), val);
1642         }
1643
1644         public void put(String name, int val) {
1645             Bits.putInt(primVals, getFieldOffset(name, Integer.TYPE), val);
1646         }
1647
1648         public void put(String name, float val) {
1649             Bits.putFloat(primVals, getFieldOffset(name, Float.TYPE), val);
1650         }
1651
1652         public void put(String name, long val) {
1653             Bits.putLong(primVals, getFieldOffset(name, Long.TYPE), val);
1654         }
1655
1656         public void put(String name, double val) {
1657             Bits.putDouble(primVals, getFieldOffset(name, Double.TYPE), val);
1658         }
1659
1660         public void put(String name, Object val) {
1661             objVals[getFieldOffset(name, Object.class)] = val;
1662         }
1663
1664         // deprecated in ObjectOutputStream.PutField
1665         public void write(ObjectOutput out) throws IOException {
1666             /*
1667              * Applications should *not* use this method to write PutField
1668              * data, as it will lead to stream corruption if the PutField
1669              * object writes any primitive data (since block data mode is not
1670              * unset/set properly, as is done in OOS.writeFields()).  This
1671              * broken implementation is being retained solely for behavioral
1672              * compatibility, in order to support applications which use
1673              * OOS.PutField.write() for writing only non-primitive data.
1674              *
1675              * Serialization of unshared objects is not implemented here since
1676              * it is not necessary for backwards compatibility; also, unshared
1677              * semantics may not be supported by the given ObjectOutput
1678              * instance.  Applications which write unshared objects using the
1679              * PutField API must use OOS.writeFields().
1680              */

1681             if (ObjectOutputStream.this != out) {
1682                 throw new IllegalArgumentException("wrong stream");
1683             }
1684             out.write(primVals, 0, primVals.length);
1685
1686             ObjectStreamField[] fields = desc.getFields(false);
1687             int numPrimFields = fields.length - objVals.length;
1688             // REMIND: warn if numPrimFields > 0?
1689             for (int i = 0; i < objVals.length; i++) {
1690                 if (fields[numPrimFields + i].isUnshared()) {
1691                     throw new IOException("cannot write unshared object");
1692                 }
1693                 out.writeObject(objVals[i]);
1694             }
1695         }
1696
1697         /**
1698          * Writes buffered primitive data and object fields to stream.
1699          */

1700         void writeFields() throws IOException {
1701             bout.write(primVals, 0, primVals.length, false);
1702
1703             ObjectStreamField[] fields = desc.getFields(false);
1704             int numPrimFields = fields.length - objVals.length;
1705             for (int i = 0; i < objVals.length; i++) {
1706                 if (extendedDebugInfo) {
1707                     debugInfoStack.push(
1708                         "field (class \"" + desc.getName() + "\", name: \"" +
1709                         fields[numPrimFields + i].getName() + "\", type: \"" +
1710                         fields[numPrimFields + i].getType() + "\")");
1711                 }
1712                 try {
1713                     writeObject0(objVals[i],
1714                                  fields[numPrimFields + i].isUnshared());
1715                 } finally {
1716                     if (extendedDebugInfo) {
1717                         debugInfoStack.pop();
1718                     }
1719                 }
1720             }
1721         }
1722
1723         /**
1724          * Returns offset of field with given name and type.  A specified type
1725          * of null matches all types, Object.class matches all non-primitive
1726          * types, and any other non-null type matches assignable types only.
1727          * Throws IllegalArgumentException if no matching field found.
1728          */

1729         private int getFieldOffset(String name, Class<?> type) {
1730             ObjectStreamField field = desc.getField(name, type);
1731             if (field == null) {
1732                 throw new IllegalArgumentException("no such field " + name +
1733                                                    " with type " + type);
1734             }
1735             return field.getOffset();
1736         }
1737     }
1738
1739     /**
1740      * Buffered output stream with two modes: in default mode, outputs data in
1741      * same format as DataOutputStream; in "block data" mode, outputs data
1742      * bracketed by block data markers (see object serialization specification
1743      * for details).
1744      */

1745     private static class BlockDataOutputStream
1746         extends OutputStream implements DataOutput
1747     {
1748         /** maximum data block length */
1749         private static final int MAX_BLOCK_SIZE = 1024;
1750         /** maximum data block header length */
1751         private static final int MAX_HEADER_SIZE = 5;
1752         /** (tunable) length of char buffer (for writing strings) */
1753         private static final int CHAR_BUF_SIZE = 256;
1754
1755         /** buffer for writing general/block data */
1756         private final byte[] buf = new byte[MAX_BLOCK_SIZE];
1757         /** buffer for writing block data headers */
1758         private final byte[] hbuf = new byte[MAX_HEADER_SIZE];
1759         /** char buffer for fast string writes */
1760         private final char[] cbuf = new char[CHAR_BUF_SIZE];
1761
1762         /** block data mode */
1763         private boolean blkmode = false;
1764         /** current offset into buf */
1765         private int pos = 0;
1766
1767         /** underlying output stream */
1768         private final OutputStream out;
1769         /** loopback stream (for data writes that span data blocks) */
1770         private final DataOutputStream dout;
1771
1772         /**
1773          * Creates new BlockDataOutputStream on top of given underlying stream.
1774          * Block data mode is turned off by default.
1775          */

1776         BlockDataOutputStream(OutputStream out) {
1777             this.out = out;
1778             dout = new DataOutputStream(this);
1779         }
1780
1781         /**
1782          * Sets block data mode to the given mode (true == on, false == off)
1783          * and returns the previous mode value.  If the new mode is the same as
1784          * the old mode, no action is taken.  If the new mode differs from the
1785          * old mode, any buffered data is flushed before switching to the new
1786          * mode.
1787          */

1788         boolean setBlockDataMode(boolean mode) throws IOException {
1789             if (blkmode == mode) {
1790                 return blkmode;
1791             }
1792             drain();
1793             blkmode = mode;
1794             return !blkmode;
1795         }
1796
1797         /**
1798          * Returns true if the stream is currently in block data mode, false
1799          * otherwise.
1800          */

1801         boolean getBlockDataMode() {
1802             return blkmode;
1803         }
1804
1805         /* ----------------- generic output stream methods ----------------- */
1806         /*
1807          * The following methods are equivalent to their counterparts in
1808          * OutputStream, except that they partition written data into data
1809          * blocks when in block data mode.
1810          */

1811
1812         public void write(int b) throws IOException {
1813             if (pos >= MAX_BLOCK_SIZE) {
1814                 drain();
1815             }
1816             buf[pos++] = (byte) b;
1817         }
1818
1819         public void write(byte[] b) throws IOException {
1820             write(b, 0, b.length, false);
1821         }
1822
1823         public void write(byte[] b, int off, int len) throws IOException {
1824             write(b, off, len, false);
1825         }
1826
1827         public void flush() throws IOException {
1828             drain();
1829             out.flush();
1830         }
1831
1832         public void close() throws IOException {
1833             flush();
1834             out.close();
1835         }
1836
1837         /**
1838          * Writes specified span of byte values from given array.  If copy is
1839          * true, copies the values to an intermediate buffer before writing
1840          * them to underlying stream (to avoid exposing a reference to the
1841          * original byte array).
1842          */

1843         void write(byte[] b, int off, int len, boolean copy)
1844             throws IOException
1845         {
1846             if (!(copy || blkmode)) {           // write directly
1847                 drain();
1848                 out.write(b, off, len);
1849                 return;
1850             }
1851
1852             while (len > 0) {
1853                 if (pos >= MAX_BLOCK_SIZE) {
1854                     drain();
1855                 }
1856                 if (len >= MAX_BLOCK_SIZE && !copy && pos == 0) {
1857                     // avoid unnecessary copy
1858                     writeBlockHeader(MAX_BLOCK_SIZE);
1859                     out.write(b, off, MAX_BLOCK_SIZE);
1860                     off += MAX_BLOCK_SIZE;
1861                     len -= MAX_BLOCK_SIZE;
1862                 } else {
1863                     int wlen = Math.min(len, MAX_BLOCK_SIZE - pos);
1864                     System.arraycopy(b, off, buf, pos, wlen);
1865                     pos += wlen;
1866                     off += wlen;
1867                     len -= wlen;
1868                 }
1869             }
1870         }
1871
1872         /**
1873          * Writes all buffered data from this stream to the underlying stream,
1874          * but does not flush underlying stream.
1875          */

1876         void drain() throws IOException {
1877             if (pos == 0) {
1878                 return;
1879             }
1880             if (blkmode) {
1881                 writeBlockHeader(pos);
1882             }
1883             out.write(buf, 0, pos);
1884             pos = 0;
1885         }
1886
1887         /**
1888          * Writes block data header.  Data blocks shorter than 256 bytes are
1889          * prefixed with a 2-byte header; all others start with a 5-byte
1890          * header.
1891          */

1892         private void writeBlockHeader(int len) throws IOException {
1893             if (len <= 0xFF) {
1894                 hbuf[0] = TC_BLOCKDATA;
1895                 hbuf[1] = (byte) len;
1896                 out.write(hbuf, 0, 2);
1897             } else {
1898                 hbuf[0] = TC_BLOCKDATALONG;
1899                 Bits.putInt(hbuf, 1, len);
1900                 out.write(hbuf, 0, 5);
1901             }
1902         }
1903
1904
1905         /* ----------------- primitive data output methods ----------------- */
1906         /*
1907          * The following methods are equivalent to their counterparts in
1908          * DataOutputStream, except that they partition written data into data
1909          * blocks when in block data mode.
1910          */

1911
1912         public void writeBoolean(boolean v) throws IOException {
1913             if (pos >= MAX_BLOCK_SIZE) {
1914                 drain();
1915             }
1916             Bits.putBoolean(buf, pos++, v);
1917         }
1918
1919         public void writeByte(int v) throws IOException {
1920             if (pos >= MAX_BLOCK_SIZE) {
1921                 drain();
1922             }
1923             buf[pos++] = (byte) v;
1924         }
1925
1926         public void writeChar(int v) throws IOException {
1927             if (pos + 2 <= MAX_BLOCK_SIZE) {
1928                 Bits.putChar(buf, pos, (char) v);
1929                 pos += 2;
1930             } else {
1931                 dout.writeChar(v);
1932             }
1933         }
1934
1935         public void writeShort(int v) throws IOException {
1936             if (pos + 2 <= MAX_BLOCK_SIZE) {
1937                 Bits.putShort(buf, pos, (short) v);
1938                 pos += 2;
1939             } else {
1940                 dout.writeShort(v);
1941             }
1942         }
1943
1944         public void writeInt(int v) throws IOException {
1945             if (pos + 4 <= MAX_BLOCK_SIZE) {
1946                 Bits.putInt(buf, pos, v);
1947                 pos += 4;
1948             } else {
1949                 dout.writeInt(v);
1950             }
1951         }
1952
1953         public void writeFloat(float v) throws IOException {
1954             if (pos + 4 <= MAX_BLOCK_SIZE) {
1955                 Bits.putFloat(buf, pos, v);
1956                 pos += 4;
1957             } else {
1958                 dout.writeFloat(v);
1959             }
1960         }
1961
1962         public void writeLong(long v) throws IOException {
1963             if (pos + 8 <= MAX_BLOCK_SIZE) {
1964                 Bits.putLong(buf, pos, v);
1965                 pos += 8;
1966             } else {
1967                 dout.writeLong(v);
1968             }
1969         }
1970
1971         public void writeDouble(double v) throws IOException {
1972             if (pos + 8 <= MAX_BLOCK_SIZE) {
1973                 Bits.putDouble(buf, pos, v);
1974                 pos += 8;
1975             } else {
1976                 dout.writeDouble(v);
1977             }
1978         }
1979
1980         public void writeBytes(String s) throws IOException {
1981             int endoff = s.length();
1982             int cpos = 0;
1983             int csize = 0;
1984             for (int off = 0; off < endoff; ) {
1985                 if (cpos >= csize) {
1986                     cpos = 0;
1987                     csize = Math.min(endoff - off, CHAR_BUF_SIZE);
1988                     s.getChars(off, off + csize, cbuf, 0);
1989                 }
1990                 if (pos >= MAX_BLOCK_SIZE) {
1991                     drain();
1992                 }
1993                 int n = Math.min(csize - cpos, MAX_BLOCK_SIZE - pos);
1994                 int stop = pos + n;
1995                 while (pos < stop) {
1996                     buf[pos++] = (byte) cbuf[cpos++];
1997                 }
1998                 off += n;
1999             }
2000         }
2001
2002         public void writeChars(String s) throws IOException {
2003             int endoff = s.length();
2004             for (int off = 0; off < endoff; ) {
2005                 int csize = Math.min(endoff - off, CHAR_BUF_SIZE);
2006                 s.getChars(off, off + csize, cbuf, 0);
2007                 writeChars(cbuf, 0, csize);
2008                 off += csize;
2009             }
2010         }
2011
2012         public void writeUTF(String s) throws IOException {
2013             writeUTF(s, getUTFLength(s));
2014         }
2015
2016
2017         /* -------------- primitive data array output methods -------------- */
2018         /*
2019          * The following methods write out spans of primitive data values.
2020          * Though equivalent to calling the corresponding primitive write
2021          * methods repeatedly, these methods are optimized for writing groups
2022          * of primitive data values more efficiently.
2023          */

2024
2025         void writeBooleans(boolean[] v, int off, int len) throws IOException {
2026             int endoff = off + len;
2027             while (off < endoff) {
2028                 if (pos >= MAX_BLOCK_SIZE) {
2029                     drain();
2030                 }
2031                 int stop = Math.min(endoff, off + (MAX_BLOCK_SIZE - pos));
2032                 while (off < stop) {
2033                     Bits.putBoolean(buf, pos++, v[off++]);
2034                 }
2035             }
2036         }
2037
2038         void writeChars(char[] v, int off, int len) throws IOException {
2039             int limit = MAX_BLOCK_SIZE - 2;
2040             int endoff = off + len;
2041             while (off < endoff) {
2042                 if (pos <= limit) {
2043                     int avail = (MAX_BLOCK_SIZE - pos) >> 1;
2044                     int stop = Math.min(endoff, off + avail);
2045                     while (off < stop) {
2046                         Bits.putChar(buf, pos, v[off++]);
2047                         pos += 2;
2048                     }
2049                 } else {
2050                     dout.writeChar(v[off++]);
2051                 }
2052             }
2053         }
2054
2055         void writeShorts(short[] v, int off, int len) throws IOException {
2056             int limit = MAX_BLOCK_SIZE - 2;
2057             int endoff = off + len;
2058             while (off < endoff) {
2059                 if (pos <= limit) {
2060                     int avail = (MAX_BLOCK_SIZE - pos) >> 1;
2061                     int stop = Math.min(endoff, off + avail);
2062                     while (off < stop) {
2063                         Bits.putShort(buf, pos, v[off++]);
2064                         pos += 2;
2065                     }
2066                 } else {
2067                     dout.writeShort(v[off++]);
2068                 }
2069             }
2070         }
2071
2072         void writeInts(int[] v, int off, int len) throws IOException {
2073             int limit = MAX_BLOCK_SIZE - 4;
2074             int endoff = off + len;
2075             while (off < endoff) {
2076                 if (pos <= limit) {
2077                     int avail = (MAX_BLOCK_SIZE - pos) >> 2;
2078                     int stop = Math.min(endoff, off + avail);
2079                     while (off < stop) {
2080                         Bits.putInt(buf, pos, v[off++]);
2081                         pos += 4;
2082                     }
2083                 } else {
2084                     dout.writeInt(v[off++]);
2085                 }
2086             }
2087         }
2088
2089         void writeFloats(float[] v, int off, int len) throws IOException {
2090             int limit = MAX_BLOCK_SIZE - 4;
2091             int endoff = off + len;
2092             while (off < endoff) {
2093                 if (pos <= limit) {
2094                     int avail = (MAX_BLOCK_SIZE - pos) >> 2;
2095                     int chunklen = Math.min(endoff - off, avail);
2096                     floatsToBytes(v, off, buf, pos, chunklen);
2097                     off += chunklen;
2098                     pos += chunklen << 2;
2099                 } else {
2100                     dout.writeFloat(v[off++]);
2101                 }
2102             }
2103         }
2104
2105         void writeLongs(long[] v, int off, int len) throws IOException {
2106             int limit = MAX_BLOCK_SIZE - 8;
2107             int endoff = off + len;
2108             while (off < endoff) {
2109                 if (pos <= limit) {
2110                     int avail = (MAX_BLOCK_SIZE - pos) >> 3;
2111                     int stop = Math.min(endoff, off + avail);
2112                     while (off < stop) {
2113                         Bits.putLong(buf, pos, v[off++]);
2114                         pos += 8;
2115                     }
2116                 } else {
2117                     dout.writeLong(v[off++]);
2118                 }
2119             }
2120         }
2121
2122         void writeDoubles(double[] v, int off, int len) throws IOException {
2123             int limit = MAX_BLOCK_SIZE - 8;
2124             int endoff = off + len;
2125             while (off < endoff) {
2126                 if (pos <= limit) {
2127                     int avail = (MAX_BLOCK_SIZE - pos) >> 3;
2128                     int chunklen = Math.min(endoff - off, avail);
2129                     doublesToBytes(v, off, buf, pos, chunklen);
2130                     off += chunklen;
2131                     pos += chunklen << 3;
2132                 } else {
2133                     dout.writeDouble(v[off++]);
2134                 }
2135             }
2136         }
2137
2138         /**
2139          * Returns the length in bytes of the UTF encoding of the given string.
2140          */

2141         long getUTFLength(String s) {
2142             int len = s.length();
2143             long utflen = 0;
2144             for (int off = 0; off < len; ) {
2145                 int csize = Math.min(len - off, CHAR_BUF_SIZE);
2146                 s.getChars(off, off + csize, cbuf, 0);
2147                 for (int cpos = 0; cpos < csize; cpos++) {
2148                     char c = cbuf[cpos];
2149                     if (c >= 0x0001 && c <= 0x007F) {
2150                         utflen++;
2151                     } else if (c > 0x07FF) {
2152                         utflen += 3;
2153                     } else {
2154                         utflen += 2;
2155                     }
2156                 }
2157                 off += csize;
2158             }
2159             return utflen;
2160         }
2161
2162         /**
2163          * Writes the given string in UTF format.  This method is used in
2164          * situations where the UTF encoding length of the string is already
2165          * known; specifying it explicitly avoids a prescan of the string to
2166          * determine its UTF length.
2167          */

2168         void writeUTF(String s, long utflen) throws IOException {
2169             if (utflen > 0xFFFFL) {
2170                 throw new UTFDataFormatException();
2171             }
2172             writeShort((int) utflen);
2173             if (utflen == (long) s.length()) {
2174                 writeBytes(s);
2175             } else {
2176                 writeUTFBody(s);
2177             }
2178         }
2179
2180         /**
2181          * Writes given string in "long" UTF format.  "Long" UTF format is
2182          * identical to standard UTF, except that it uses an 8 byte header
2183          * (instead of the standard 2 bytes) to convey the UTF encoding length.
2184          */

2185         void writeLongUTF(String s) throws IOException {
2186             writeLongUTF(s, getUTFLength(s));
2187         }
2188
2189         /**
2190          * Writes given string in "long" UTF format, where the UTF encoding
2191          * length of the string is already known.
2192          */

2193         void writeLongUTF(String s, long utflen) throws IOException {
2194             writeLong(utflen);
2195             if (utflen == (long) s.length()) {
2196                 writeBytes(s);
2197             } else {
2198                 writeUTFBody(s);
2199             }
2200         }
2201
2202         /**
2203          * Writes the "body" (i.e., the UTF representation minus the 2-byte or
2204          * 8-byte length header) of the UTF encoding for the given string.
2205          */

2206         private void writeUTFBody(String s) throws IOException {
2207             int limit = MAX_BLOCK_SIZE - 3;
2208             int len = s.length();
2209             for (int off = 0; off < len; ) {
2210                 int csize = Math.min(len - off, CHAR_BUF_SIZE);
2211                 s.getChars(off, off + csize, cbuf, 0);
2212                 for (int cpos = 0; cpos < csize; cpos++) {
2213                     char c = cbuf[cpos];
2214                     if (pos <= limit) {
2215                         if (c <= 0x007F && c != 0) {
2216                             buf[pos++] = (byte) c;
2217                         } else if (c > 0x07FF) {
2218                             buf[pos + 2] = (byte) (0x80 | ((c >> 0) & 0x3F));
2219                             buf[pos + 1] = (byte) (0x80 | ((c >> 6) & 0x3F));
2220                             buf[pos + 0] = (byte) (0xE0 | ((c >> 12) & 0x0F));
2221                             pos += 3;
2222                         } else {
2223                             buf[pos + 1] = (byte) (0x80 | ((c >> 0) & 0x3F));
2224                             buf[pos + 0] = (byte) (0xC0 | ((c >> 6) & 0x1F));
2225                             pos += 2;
2226                         }
2227                     } else {    // write one byte at a time to normalize block
2228                         if (c <= 0x007F && c != 0) {
2229                             write(c);
2230                         } else if (c > 0x07FF) {
2231                             write(0xE0 | ((c >> 12) & 0x0F));
2232                             write(0x80 | ((c >> 6) & 0x3F));
2233                             write(0x80 | ((c >> 0) & 0x3F));
2234                         } else {
2235                             write(0xC0 | ((c >> 6) & 0x1F));
2236                             write(0x80 | ((c >> 0) & 0x3F));
2237                         }
2238                     }
2239                 }
2240                 off += csize;
2241             }
2242         }
2243     }
2244
2245     /**
2246      * Lightweight identity hash table which maps objects to integer handles,
2247      * assigned in ascending order.
2248      */

2249     private static class HandleTable {
2250
2251         /* number of mappings in table/next available handle */
2252         private int size;
2253         /* size threshold determining when to expand hash spine */
2254         private int threshold;
2255         /* factor for computing size threshold */
2256         private final float loadFactor;
2257         /* maps hash value -> candidate handle value */
2258         private int[] spine;
2259         /* maps handle value -> next candidate handle value */
2260         private int[] next;
2261         /* maps handle value -> associated object */
2262         private Object[] objs;
2263
2264         /**
2265          * Creates new HandleTable with given capacity and load factor.
2266          */

2267         HandleTable(int initialCapacity, float loadFactor) {
2268             this.loadFactor = loadFactor;
2269             spine = new int[initialCapacity];
2270             next = new int[initialCapacity];
2271             objs = new Object[initialCapacity];
2272             threshold = (int) (initialCapacity * loadFactor);
2273             clear();
2274         }
2275
2276         /**
2277          * Assigns next available handle to given object, and returns handle
2278          * value.  Handles are assigned in ascending order starting at 0.
2279          */

2280         int assign(Object obj) {
2281             if (size >= next.length) {
2282                 growEntries();
2283             }
2284             if (size >= threshold) {
2285                 growSpine();
2286             }
2287             insert(obj, size);
2288             return size++;
2289         }
2290
2291         /**
2292          * Looks up and returns handle associated with given object, or -1 if
2293          * no mapping found.
2294          */

2295         int lookup(Object obj) {
2296             if (size == 0) {
2297                 return -1;
2298             }
2299             int index = hash(obj) % spine.length;
2300             for (int i = spine[index]; i >= 0; i = next[i]) {
2301                 if (objs[i] == obj) {
2302                     return i;
2303                 }
2304             }
2305             return -1;
2306         }
2307
2308         /**
2309          * Resets table to its initial (empty) state.
2310          */

2311         void clear() {
2312             Arrays.fill(spine, -1);
2313             Arrays.fill(objs, 0, size, null);
2314             size = 0;
2315         }
2316
2317         /**
2318          * Returns the number of mappings currently in table.
2319          */

2320         int size() {
2321             return size;
2322         }
2323
2324         /**
2325          * Inserts mapping object -> handle mapping into table.  Assumes table
2326          * is large enough to accommodate new mapping.
2327          */

2328         private void insert(Object obj, int handle) {
2329             int index = hash(obj) % spine.length;
2330             objs[handle] = obj;
2331             next[handle] = spine[index];
2332             spine[index] = handle;
2333         }
2334
2335         /**
2336          * Expands the hash "spine" -- equivalent to increasing the number of
2337          * buckets in a conventional hash table.
2338          */

2339         private void growSpine() {
2340             spine = new int[(spine.length << 1) + 1];
2341             threshold = (int) (spine.length * loadFactor);
2342             Arrays.fill(spine, -1);
2343             for (int i = 0; i < size; i++) {
2344                 insert(objs[i], i);
2345             }
2346         }
2347
2348         /**
2349          * Increases hash table capacity by lengthening entry arrays.
2350          */

2351         private void growEntries() {
2352             int newLength = (next.length << 1) + 1;
2353             int[] newNext = new int[newLength];
2354             System.arraycopy(next, 0, newNext, 0, size);
2355             next = newNext;
2356
2357             Object[] newObjs = new Object[newLength];
2358             System.arraycopy(objs, 0, newObjs, 0, size);
2359             objs = newObjs;
2360         }
2361
2362         /**
2363          * Returns hash value for given object.
2364          */

2365         private int hash(Object obj) {
2366             return System.identityHashCode(obj) & 0x7FFFFFFF;
2367         }
2368     }
2369
2370     /**
2371      * Lightweight identity hash table which maps objects to replacement
2372      * objects.
2373      */

2374     private static class ReplaceTable {
2375
2376         /* maps object -> index */
2377         private final HandleTable htab;
2378         /* maps index -> replacement object */
2379         private Object[] reps;
2380
2381         /**
2382          * Creates new ReplaceTable with given capacity and load factor.
2383          */

2384         ReplaceTable(int initialCapacity, float loadFactor) {
2385             htab = new HandleTable(initialCapacity, loadFactor);
2386             reps = new Object[initialCapacity];
2387         }
2388
2389         /**
2390          * Enters mapping from object to replacement object.
2391          */

2392         void assign(Object obj, Object rep) {
2393             int index = htab.assign(obj);
2394             while (index >= reps.length) {
2395                 grow();
2396             }
2397             reps[index] = rep;
2398         }
2399
2400         /**
2401          * Looks up and returns replacement for given object.  If no
2402          * replacement is found, returns the lookup object itself.
2403          */

2404         Object lookup(Object obj) {
2405             int index = htab.lookup(obj);
2406             return (index >= 0) ? reps[index] : obj;
2407         }
2408
2409         /**
2410          * Resets table to its initial (empty) state.
2411          */

2412         void clear() {
2413             Arrays.fill(reps, 0, htab.size(), null);
2414             htab.clear();
2415         }
2416
2417         /**
2418          * Returns the number of mappings currently in table.
2419          */

2420         int size() {
2421             return htab.size();
2422         }
2423
2424         /**
2425          * Increases table capacity.
2426          */

2427         private void grow() {
2428             Object[] newReps = new Object[(reps.length << 1) + 1];
2429             System.arraycopy(reps, 0, newReps, 0, reps.length);
2430             reps = newReps;
2431         }
2432     }
2433
2434     /**
2435      * Stack to keep debug information about the state of the
2436      * serialization process, for embedding in exception messages.
2437      */

2438     private static class DebugTraceInfoStack {
2439         private final List<String> stack;
2440
2441         DebugTraceInfoStack() {
2442             stack = new ArrayList<>();
2443         }
2444
2445         /**
2446          * Removes all of the elements from enclosed list.
2447          */

2448         void clear() {
2449             stack.clear();
2450         }
2451
2452         /**
2453          * Removes the object at the top of enclosed list.
2454          */

2455         void pop() {
2456             stack.remove(stack.size()-1);
2457         }
2458
2459         /**
2460          * Pushes a String onto the top of enclosed list.
2461          */

2462         void push(String entry) {
2463             stack.add("\t- " + entry);
2464         }
2465
2466         /**
2467          * Returns a string representation of this object
2468          */

2469         public String toString() {
2470             StringJoiner sj = new StringJoiner("\n");
2471             for (int i = stack.size() - 1; i >= 0; i--) {
2472                 sj.add(stack.get(i));
2473             }
2474             return sj.toString();
2475         }
2476     }
2477
2478 }
2479