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