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