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