1 /* 2 * Copyright (c) 1996, 2013, 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.lang.ref.Reference; 29 import java.lang.ref.ReferenceQueue; 30 import java.lang.ref.SoftReference; 31 import java.lang.ref.WeakReference; 32 import java.lang.reflect.Constructor; 33 import java.lang.reflect.Field; 34 import java.lang.reflect.InvocationTargetException; 35 import java.lang.reflect.Member; 36 import java.lang.reflect.Method; 37 import java.lang.reflect.Modifier; 38 import java.lang.reflect.Proxy; 39 import java.security.AccessController; 40 import java.security.MessageDigest; 41 import java.security.NoSuchAlgorithmException; 42 import java.security.PrivilegedAction; 43 import java.util.ArrayList; 44 import java.util.Arrays; 45 import java.util.Collections; 46 import java.util.Comparator; 47 import java.util.HashSet; 48 import java.util.Set; 49 import java.util.concurrent.ConcurrentHashMap; 50 import java.util.concurrent.ConcurrentMap; 51 import sun.misc.Unsafe; 52 import sun.reflect.CallerSensitive; 53 import sun.reflect.Reflection; 54 import sun.reflect.ReflectionFactory; 55 import sun.reflect.misc.ReflectUtil; 56 57 /** 58 * Serialization's descriptor for classes. It contains the name and 59 * serialVersionUID of the class. The ObjectStreamClass for a specific class 60 * loaded in this Java VM can be found/created using the lookup method. 61 * 62 * <p>The algorithm to compute the SerialVersionUID is described in 63 * <a href="../../../platform/serialization/spec/class.html#4100">Object 64 * Serialization Specification, Section 4.6, Stream Unique Identifiers</a>. 65 * 66 * @author Mike Warres 67 * @author Roger Riggs 68 * @see ObjectStreamField 69 * @see <a href="../../../platform/serialization/spec/class.html">Object Serialization Specification, Section 4, Class Descriptors</a> 70 * @since 1.1 71 */ 72 public class ObjectStreamClass implements Serializable { 73 74 /** serialPersistentFields value indicating no serializable fields */ 75 public static final ObjectStreamField[] NO_FIELDS = 76 new ObjectStreamField[0]; 77 78 private static final long serialVersionUID = -6120832682080437368L; 79 private static final ObjectStreamField[] serialPersistentFields = 80 NO_FIELDS; 81 82 /** reflection factory for obtaining serialization constructors */ 83 private static final ReflectionFactory reflFactory = 84 AccessController.doPrivileged( 85 new ReflectionFactory.GetReflectionFactoryAction()); 86 87 private static class Caches { 88 /** cache mapping local classes -> descriptors */ 89 static final ConcurrentMap<WeakClassKey,Reference<?>> localDescs = 90 new ConcurrentHashMap<>(); 91 92 /** cache mapping field group/local desc pairs -> field reflectors */ 93 static final ConcurrentMap<FieldReflectorKey,Reference<?>> reflectors = 94 new ConcurrentHashMap<>(); 95 96 /** queue for WeakReferences to local classes */ 97 private static final ReferenceQueue<Class<?>> localDescsQueue = 98 new ReferenceQueue<>(); 99 /** queue for WeakReferences to field reflectors keys */ 100 private static final ReferenceQueue<Class<?>> reflectorsQueue = 101 new ReferenceQueue<>(); 102 } 103 104 /** class associated with this descriptor (if any) */ 105 private Class<?> cl; 106 /** name of class represented by this descriptor */ 107 private String name; 108 /** serialVersionUID of represented class (null if not computed yet) */ 109 private volatile Long suid; 110 111 /** true if represents dynamic proxy class */ 112 private boolean isProxy; 113 /** true if represents enum type */ 114 private boolean isEnum; 115 /** true if represented class implements Serializable */ 116 private boolean serializable; 117 /** true if represented class implements Externalizable */ 118 private boolean externalizable; 119 /** true if desc has data written by class-defined writeObject method */ 120 private boolean hasWriteObjectData; 121 /** 122 * true if desc has externalizable data written in block data format; this 123 * must be true by default to accommodate ObjectInputStream subclasses which 124 * override readClassDescriptor() to return class descriptors obtained from 125 * ObjectStreamClass.lookup() (see 4461737) 126 */ 127 private boolean hasBlockExternalData = true; 128 129 /** 130 * Contains information about InvalidClassException instances to be thrown 131 * when attempting operations on an invalid class. Note that instances of 132 * this class are immutable and are potentially shared among 133 * ObjectStreamClass instances. 134 */ 135 private static class ExceptionInfo { 136 private final String className; 137 private final String message; 138 139 ExceptionInfo(String cn, String msg) { 140 className = cn; 141 message = msg; 142 } 143 144 /** 145 * Returns (does not throw) an InvalidClassException instance created 146 * from the information in this object, suitable for being thrown by 147 * the caller. 148 */ 149 InvalidClassException newInvalidClassException() { 150 return new InvalidClassException(className, message); 151 } 152 } 153 154 /** exception (if any) thrown while attempting to resolve class */ 155 private ClassNotFoundException resolveEx; 156 /** exception (if any) to throw if non-enum deserialization attempted */ 157 private ExceptionInfo deserializeEx; 158 /** exception (if any) to throw if non-enum serialization attempted */ 159 private ExceptionInfo serializeEx; 160 /** exception (if any) to throw if default serialization attempted */ 161 private ExceptionInfo defaultSerializeEx; 162 163 /** serializable fields */ 164 private ObjectStreamField[] fields; 165 /** aggregate marshalled size of primitive fields */ 166 private int primDataSize; 167 /** number of non-primitive fields */ 168 private int numObjFields; 169 /** reflector for setting/getting serializable field values */ 170 private FieldReflector fieldRefl; 171 /** data layout of serialized objects described by this class desc */ 172 private volatile ClassDataSlot[] dataLayout; 173 174 /** serialization-appropriate constructor, or null if none */ 175 private Constructor<?> cons; 176 /** class-defined writeObject method, or null if none */ 177 private Method writeObjectMethod; 178 /** class-defined readObject method, or null if none */ 179 private Method readObjectMethod; 180 /** class-defined readObjectNoData method, or null if none */ 181 private Method readObjectNoDataMethod; 182 /** class-defined writeReplace method, or null if none */ 183 private Method writeReplaceMethod; 184 /** class-defined readResolve method, or null if none */ 185 private Method readResolveMethod; 186 187 /** local class descriptor for represented class (may point to self) */ 188 private ObjectStreamClass localDesc; 189 /** superclass descriptor appearing in stream */ 190 private ObjectStreamClass superDesc; 191 192 /** 193 * Initializes native code. 194 */ 195 private static native void initNative(); 196 static { 197 initNative(); 198 } 199 200 /** 201 * Find the descriptor for a class that can be serialized. Creates an 202 * ObjectStreamClass instance if one does not exist yet for class. Null is 203 * returned if the specified class does not implement java.io.Serializable 204 * or java.io.Externalizable. 205 * 206 * @param cl class for which to get the descriptor 207 * @return the class descriptor for the specified class 208 */ 209 public static ObjectStreamClass lookup(Class<?> cl) { 210 return lookup(cl, false); 211 } 212 213 /** 214 * Returns the descriptor for any class, regardless of whether it 215 * implements {@link Serializable}. 216 * 217 * @param cl class for which to get the descriptor 218 * @return the class descriptor for the specified class 219 * @since 1.6 220 */ 221 public static ObjectStreamClass lookupAny(Class<?> cl) { 222 return lookup(cl, true); 223 } 224 225 /** 226 * Returns the name of the class described by this descriptor. 227 * This method returns the name of the class in the format that 228 * is used by the {@link Class#getName} method. 229 * 230 * @return a string representing the name of the class 231 */ 232 public String getName() { 233 return name; 234 } 235 236 /** 237 * Return the serialVersionUID for this class. The serialVersionUID 238 * defines a set of classes all with the same name that have evolved from a 239 * common root class and agree to be serialized and deserialized using a 240 * common format. NonSerializable classes have a serialVersionUID of 0L. 241 * 242 * @return the SUID of the class described by this descriptor 243 */ 244 public long getSerialVersionUID() { 245 // REMIND: synchronize instead of relying on volatile? 246 if (suid == null) { 247 suid = AccessController.doPrivileged( 248 new PrivilegedAction<Long>() { 249 public Long run() { 250 return computeDefaultSUID(cl); 251 } 252 } 253 ); 254 } 255 return suid.longValue(); 256 } 257 258 /** 259 * Return the class in the local VM that this version is mapped to. Null 260 * is returned if there is no corresponding local class. 261 * 262 * @return the <code>Class</code> instance that this descriptor represents 263 */ 264 @CallerSensitive 265 public Class<?> forClass() { 266 if (cl == null) { 267 return null; 268 } 269 if (System.getSecurityManager() != null) { 270 Class<?> caller = Reflection.getCallerClass(); 271 if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(), cl.getClassLoader())) { 272 ReflectUtil.checkPackageAccess(cl); 273 } 274 } 275 return cl; 276 } 277 278 /** 279 * Return an array of the fields of this serializable class. 280 * 281 * @return an array containing an element for each persistent field of 282 * this class. Returns an array of length zero if there are no 283 * fields. 284 * @since 1.2 285 */ 286 public ObjectStreamField[] getFields() { 287 return getFields(true); 288 } 289 290 /** 291 * Get the field of this class by name. 292 * 293 * @param name the name of the data field to look for 294 * @return The ObjectStreamField object of the named field or null if 295 * there is no such named field. 296 */ 297 public ObjectStreamField getField(String name) { 298 return getField(name, null); 299 } 300 301 /** 302 * Return a string describing this ObjectStreamClass. 303 */ 304 public String toString() { 305 return name + ": static final long serialVersionUID = " + 306 getSerialVersionUID() + "L;"; 307 } 308 309 /** 310 * Looks up and returns class descriptor for given class, or null if class 311 * is non-serializable and "all" is set to false. 312 * 313 * @param cl class to look up 314 * @param all if true, return descriptors for all classes; if false, only 315 * return descriptors for serializable classes 316 */ 317 static ObjectStreamClass lookup(Class<?> cl, boolean all) { 318 if (!(all || Serializable.class.isAssignableFrom(cl))) { 319 return null; 320 } 321 processQueue(Caches.localDescsQueue, Caches.localDescs); 322 WeakClassKey key = new WeakClassKey(cl, Caches.localDescsQueue); 323 Reference<?> ref = Caches.localDescs.get(key); 324 Object entry = null; 325 if (ref != null) { 326 entry = ref.get(); 327 } 328 EntryFuture future = null; 329 if (entry == null) { 330 EntryFuture newEntry = new EntryFuture(); 331 Reference<?> newRef = new SoftReference<>(newEntry); 332 do { 333 if (ref != null) { 334 Caches.localDescs.remove(key, ref); 335 } 336 ref = Caches.localDescs.putIfAbsent(key, newRef); 337 if (ref != null) { 338 entry = ref.get(); 339 } 340 } while (ref != null && entry == null); 341 if (entry == null) { 342 future = newEntry; 343 } 344 } 345 346 if (entry instanceof ObjectStreamClass) { // check common case first 347 return (ObjectStreamClass) entry; 348 } 349 if (entry instanceof EntryFuture) { 350 future = (EntryFuture) entry; 351 if (future.getOwner() == Thread.currentThread()) { 352 /* 353 * Handle nested call situation described by 4803747: waiting 354 * for future value to be set by a lookup() call further up the 355 * stack will result in deadlock, so calculate and set the 356 * future value here instead. 357 */ 358 entry = null; 359 } else { 360 entry = future.get(); 361 } 362 } 363 if (entry == null) { 364 try { 365 entry = new ObjectStreamClass(cl); 366 } catch (Throwable th) { 367 entry = th; 368 } 369 if (future.set(entry)) { 370 Caches.localDescs.put(key, new SoftReference<>(entry)); 371 } else { 372 // nested lookup call already set future 373 entry = future.get(); 374 } 375 } 376 377 if (entry instanceof ObjectStreamClass) { 378 return (ObjectStreamClass) entry; 379 } else if (entry instanceof RuntimeException) { 380 throw (RuntimeException) entry; 381 } else if (entry instanceof Error) { 382 throw (Error) entry; 383 } else { 384 throw new InternalError("unexpected entry: " + entry); 385 } 386 } 387 388 /** 389 * Placeholder used in class descriptor and field reflector lookup tables 390 * for an entry in the process of being initialized. (Internal) callers 391 * which receive an EntryFuture belonging to another thread as the result 392 * of a lookup should call the get() method of the EntryFuture; this will 393 * return the actual entry once it is ready for use and has been set(). To 394 * conserve objects, EntryFutures synchronize on themselves. 395 */ 396 private static class EntryFuture { 397 398 private static final Object unset = new Object(); 399 private final Thread owner = Thread.currentThread(); 400 private Object entry = unset; 401 402 /** 403 * Attempts to set the value contained by this EntryFuture. If the 404 * EntryFuture's value has not been set already, then the value is 405 * saved, any callers blocked in the get() method are notified, and 406 * true is returned. If the value has already been set, then no saving 407 * or notification occurs, and false is returned. 408 */ 409 synchronized boolean set(Object entry) { 410 if (this.entry != unset) { 411 return false; 412 } 413 this.entry = entry; 414 notifyAll(); 415 return true; 416 } 417 418 /** 419 * Returns the value contained by this EntryFuture, blocking if 420 * necessary until a value is set. 421 */ 422 synchronized Object get() { 423 boolean interrupted = false; 424 while (entry == unset) { 425 try { 426 wait(); 427 } catch (InterruptedException ex) { 428 interrupted = true; 429 } 430 } 431 if (interrupted) { 432 AccessController.doPrivileged( 433 new PrivilegedAction<>() { 434 public Void run() { 435 Thread.currentThread().interrupt(); 436 return null; 437 } 438 } 439 ); 440 } 441 return entry; 442 } 443 444 /** 445 * Returns the thread that created this EntryFuture. 446 */ 447 Thread getOwner() { 448 return owner; 449 } 450 } 451 452 /** 453 * Creates local class descriptor representing given class. 454 */ 455 private ObjectStreamClass(final Class<?> cl) { 456 this.cl = cl; 457 name = cl.getName(); 458 isProxy = Proxy.isProxyClass(cl); 459 isEnum = Enum.class.isAssignableFrom(cl); 460 serializable = Serializable.class.isAssignableFrom(cl); 461 externalizable = Externalizable.class.isAssignableFrom(cl); 462 463 Class<?> superCl = cl.getSuperclass(); 464 superDesc = (superCl != null) ? lookup(superCl, false) : null; 465 localDesc = this; 466 467 if (serializable) { 468 AccessController.doPrivileged(new PrivilegedAction<>() { 469 public Void run() { 470 if (isEnum) { 471 suid = Long.valueOf(0); 472 fields = NO_FIELDS; 473 return null; 474 } 475 if (cl.isArray()) { 476 fields = NO_FIELDS; 477 return null; 478 } 479 480 suid = getDeclaredSUID(cl); 481 try { 482 fields = getSerialFields(cl); 483 computeFieldOffsets(); 484 } catch (InvalidClassException e) { 485 serializeEx = deserializeEx = 486 new ExceptionInfo(e.classname, e.getMessage()); 487 fields = NO_FIELDS; 488 } 489 490 if (externalizable) { 491 cons = getExternalizableConstructor(cl); 492 } else { 493 cons = getSerializableConstructor(cl); 494 writeObjectMethod = getPrivateMethod(cl, "writeObject", 495 new Class<?>[] { ObjectOutputStream.class }, 496 Void.TYPE); 497 readObjectMethod = getPrivateMethod(cl, "readObject", 498 new Class<?>[] { ObjectInputStream.class }, 499 Void.TYPE); 500 readObjectNoDataMethod = getPrivateMethod( 501 cl, "readObjectNoData", null, Void.TYPE); 502 hasWriteObjectData = (writeObjectMethod != null); 503 } 504 writeReplaceMethod = getInheritableMethod( 505 cl, "writeReplace", null, Object.class); 506 readResolveMethod = getInheritableMethod( 507 cl, "readResolve", null, Object.class); 508 return null; 509 } 510 }); 511 } else { 512 suid = Long.valueOf(0); 513 fields = NO_FIELDS; 514 } 515 516 try { 517 fieldRefl = getReflector(fields, this); 518 } catch (InvalidClassException ex) { 519 // field mismatches impossible when matching local fields vs. self 520 throw new InternalError(ex); 521 } 522 523 if (deserializeEx == null) { 524 if (isEnum) { 525 deserializeEx = new ExceptionInfo(name, "enum type"); 526 } else if (cons == null) { 527 deserializeEx = new ExceptionInfo(name, "no valid constructor"); 528 } 529 } 530 for (int i = 0; i < fields.length; i++) { 531 if (fields[i].getField() == null) { 532 defaultSerializeEx = new ExceptionInfo( 533 name, "unmatched serializable field(s) declared"); 534 } 535 } 536 } 537 538 /** 539 * Creates blank class descriptor which should be initialized via a 540 * subsequent call to initProxy(), initNonProxy() or readNonProxy(). 541 */ 542 ObjectStreamClass() { 543 } 544 545 /** 546 * Initializes class descriptor representing a proxy class. 547 */ 548 void initProxy(Class<?> cl, 549 ClassNotFoundException resolveEx, 550 ObjectStreamClass superDesc) 551 throws InvalidClassException 552 { 553 this.cl = cl; 554 this.resolveEx = resolveEx; 555 this.superDesc = superDesc; 556 isProxy = true; 557 serializable = true; 558 suid = Long.valueOf(0); 559 fields = NO_FIELDS; 560 561 if (cl != null) { 562 localDesc = lookup(cl, true); 563 if (!localDesc.isProxy) { 564 throw new InvalidClassException( 565 "cannot bind proxy descriptor to a non-proxy class"); 566 } 567 name = localDesc.name; 568 externalizable = localDesc.externalizable; 569 cons = localDesc.cons; 570 writeReplaceMethod = localDesc.writeReplaceMethod; 571 readResolveMethod = localDesc.readResolveMethod; 572 deserializeEx = localDesc.deserializeEx; 573 } 574 fieldRefl = getReflector(fields, localDesc); 575 } 576 577 /** 578 * Initializes class descriptor representing a non-proxy class. 579 */ 580 void initNonProxy(ObjectStreamClass model, 581 Class<?> cl, 582 ClassNotFoundException resolveEx, 583 ObjectStreamClass superDesc) 584 throws InvalidClassException 585 { 586 this.cl = cl; 587 this.resolveEx = resolveEx; 588 this.superDesc = superDesc; 589 name = model.name; 590 suid = Long.valueOf(model.getSerialVersionUID()); 591 isProxy = false; 592 isEnum = model.isEnum; 593 serializable = model.serializable; 594 externalizable = model.externalizable; 595 hasBlockExternalData = model.hasBlockExternalData; 596 hasWriteObjectData = model.hasWriteObjectData; 597 fields = model.fields; 598 primDataSize = model.primDataSize; 599 numObjFields = model.numObjFields; 600 601 if (cl != null) { 602 localDesc = lookup(cl, true); 603 if (localDesc.isProxy) { 604 throw new InvalidClassException( 605 "cannot bind non-proxy descriptor to a proxy class"); 606 } 607 if (isEnum != localDesc.isEnum) { 608 throw new InvalidClassException(isEnum ? 609 "cannot bind enum descriptor to a non-enum class" : 610 "cannot bind non-enum descriptor to an enum class"); 611 } 612 613 if (serializable == localDesc.serializable && 614 !cl.isArray() && 615 suid.longValue() != localDesc.getSerialVersionUID()) 616 { 617 throw new InvalidClassException(localDesc.name, 618 "local class incompatible: " + 619 "stream classdesc serialVersionUID = " + suid + 620 ", local class serialVersionUID = " + 621 localDesc.getSerialVersionUID()); 622 } 623 624 if (!classNamesEqual(name, localDesc.name)) { 625 throw new InvalidClassException(localDesc.name, 626 "local class name incompatible with stream class " + 627 "name \"" + name + "\""); 628 } 629 630 if (!isEnum) { 631 if ((serializable == localDesc.serializable) && 632 (externalizable != localDesc.externalizable)) 633 { 634 throw new InvalidClassException(localDesc.name, 635 "Serializable incompatible with Externalizable"); 636 } 637 638 if ((serializable != localDesc.serializable) || 639 (externalizable != localDesc.externalizable) || 640 !(serializable || externalizable)) 641 { 642 deserializeEx = new ExceptionInfo( 643 localDesc.name, "class invalid for deserialization"); 644 } 645 } 646 647 cons = localDesc.cons; 648 writeObjectMethod = localDesc.writeObjectMethod; 649 readObjectMethod = localDesc.readObjectMethod; 650 readObjectNoDataMethod = localDesc.readObjectNoDataMethod; 651 writeReplaceMethod = localDesc.writeReplaceMethod; 652 readResolveMethod = localDesc.readResolveMethod; 653 if (deserializeEx == null) { 654 deserializeEx = localDesc.deserializeEx; 655 } 656 } 657 fieldRefl = getReflector(fields, localDesc); 658 // reassign to matched fields so as to reflect local unshared settings 659 fields = fieldRefl.getFields(); 660 } 661 662 /** 663 * Reads non-proxy class descriptor information from given input stream. 664 * The resulting class descriptor is not fully functional; it can only be 665 * used as input to the ObjectInputStream.resolveClass() and 666 * ObjectStreamClass.initNonProxy() methods. 667 */ 668 void readNonProxy(ObjectInputStream in) 669 throws IOException, ClassNotFoundException 670 { 671 name = in.readUTF(); 672 suid = Long.valueOf(in.readLong()); 673 isProxy = false; 674 675 byte flags = in.readByte(); 676 hasWriteObjectData = 677 ((flags & ObjectStreamConstants.SC_WRITE_METHOD) != 0); 678 hasBlockExternalData = 679 ((flags & ObjectStreamConstants.SC_BLOCK_DATA) != 0); 680 externalizable = 681 ((flags & ObjectStreamConstants.SC_EXTERNALIZABLE) != 0); 682 boolean sflag = 683 ((flags & ObjectStreamConstants.SC_SERIALIZABLE) != 0); 684 if (externalizable && sflag) { 685 throw new InvalidClassException( 686 name, "serializable and externalizable flags conflict"); 687 } 688 serializable = externalizable || sflag; 689 isEnum = ((flags & ObjectStreamConstants.SC_ENUM) != 0); 690 if (isEnum && suid.longValue() != 0L) { 691 throw new InvalidClassException(name, 692 "enum descriptor has non-zero serialVersionUID: " + suid); 693 } 694 695 int numFields = in.readShort(); 696 if (isEnum && numFields != 0) { 697 throw new InvalidClassException(name, 698 "enum descriptor has non-zero field count: " + numFields); 699 } 700 fields = (numFields > 0) ? 701 new ObjectStreamField[numFields] : NO_FIELDS; 702 for (int i = 0; i < numFields; i++) { 703 char tcode = (char) in.readByte(); 704 String fname = in.readUTF(); 705 String signature = ((tcode == 'L') || (tcode == '[')) ? 706 in.readTypeString() : new String(new char[] { tcode }); 707 try { 708 fields[i] = new ObjectStreamField(fname, signature, false); 709 } catch (RuntimeException e) { 710 throw (IOException) new InvalidClassException(name, 711 "invalid descriptor for field " + fname).initCause(e); 712 } 713 } 714 computeFieldOffsets(); 715 } 716 717 /** 718 * Writes non-proxy class descriptor information to given output stream. 719 */ 720 void writeNonProxy(ObjectOutputStream out) throws IOException { 721 out.writeUTF(name); 722 out.writeLong(getSerialVersionUID()); 723 724 byte flags = 0; 725 if (externalizable) { 726 flags |= ObjectStreamConstants.SC_EXTERNALIZABLE; 727 int protocol = out.getProtocolVersion(); 728 if (protocol != ObjectStreamConstants.PROTOCOL_VERSION_1) { 729 flags |= ObjectStreamConstants.SC_BLOCK_DATA; 730 } 731 } else if (serializable) { 732 flags |= ObjectStreamConstants.SC_SERIALIZABLE; 733 } 734 if (hasWriteObjectData) { 735 flags |= ObjectStreamConstants.SC_WRITE_METHOD; 736 } 737 if (isEnum) { 738 flags |= ObjectStreamConstants.SC_ENUM; 739 } 740 out.writeByte(flags); 741 742 out.writeShort(fields.length); 743 for (int i = 0; i < fields.length; i++) { 744 ObjectStreamField f = fields[i]; 745 out.writeByte(f.getTypeCode()); 746 out.writeUTF(f.getName()); 747 if (!f.isPrimitive()) { 748 out.writeTypeString(f.getTypeString()); 749 } 750 } 751 } 752 753 /** 754 * Returns ClassNotFoundException (if any) thrown while attempting to 755 * resolve local class corresponding to this class descriptor. 756 */ 757 ClassNotFoundException getResolveException() { 758 return resolveEx; 759 } 760 761 /** 762 * Throws an InvalidClassException if object instances referencing this 763 * class descriptor should not be allowed to deserialize. This method does 764 * not apply to deserialization of enum constants. 765 */ 766 void checkDeserialize() throws InvalidClassException { 767 if (deserializeEx != null) { 768 throw deserializeEx.newInvalidClassException(); 769 } 770 } 771 772 /** 773 * Throws an InvalidClassException if objects whose class is represented by 774 * this descriptor should not be allowed to serialize. This method does 775 * not apply to serialization of enum constants. 776 */ 777 void checkSerialize() throws InvalidClassException { 778 if (serializeEx != null) { 779 throw serializeEx.newInvalidClassException(); 780 } 781 } 782 783 /** 784 * Throws an InvalidClassException if objects whose class is represented by 785 * this descriptor should not be permitted to use default serialization 786 * (e.g., if the class declares serializable fields that do not correspond 787 * to actual fields, and hence must use the GetField API). This method 788 * does not apply to deserialization of enum constants. 789 */ 790 void checkDefaultSerialize() throws InvalidClassException { 791 if (defaultSerializeEx != null) { 792 throw defaultSerializeEx.newInvalidClassException(); 793 } 794 } 795 796 /** 797 * Returns superclass descriptor. Note that on the receiving side, the 798 * superclass descriptor may be bound to a class that is not a superclass 799 * of the subclass descriptor's bound class. 800 */ 801 ObjectStreamClass getSuperDesc() { 802 return superDesc; 803 } 804 805 /** 806 * Returns the "local" class descriptor for the class associated with this 807 * class descriptor (i.e., the result of 808 * ObjectStreamClass.lookup(this.forClass())) or null if there is no class 809 * associated with this descriptor. 810 */ 811 ObjectStreamClass getLocalDesc() { 812 return localDesc; 813 } 814 815 /** 816 * Returns arrays of ObjectStreamFields representing the serializable 817 * fields of the represented class. If copy is true, a clone of this class 818 * descriptor's field array is returned, otherwise the array itself is 819 * returned. 820 */ 821 ObjectStreamField[] getFields(boolean copy) { 822 return copy ? fields.clone() : fields; 823 } 824 825 /** 826 * Looks up a serializable field of the represented class by name and type. 827 * A specified type of null matches all types, Object.class matches all 828 * non-primitive types, and any other non-null type matches assignable 829 * types only. Returns matching field, or null if no match found. 830 */ 831 ObjectStreamField getField(String name, Class<?> type) { 832 for (int i = 0; i < fields.length; i++) { 833 ObjectStreamField f = fields[i]; 834 if (f.getName().equals(name)) { 835 if (type == null || 836 (type == Object.class && !f.isPrimitive())) 837 { 838 return f; 839 } 840 Class<?> ftype = f.getType(); 841 if (ftype != null && type.isAssignableFrom(ftype)) { 842 return f; 843 } 844 } 845 } 846 return null; 847 } 848 849 /** 850 * Returns true if class descriptor represents a dynamic proxy class, false 851 * otherwise. 852 */ 853 boolean isProxy() { 854 return isProxy; 855 } 856 857 /** 858 * Returns true if class descriptor represents an enum type, false 859 * otherwise. 860 */ 861 boolean isEnum() { 862 return isEnum; 863 } 864 865 /** 866 * Returns true if represented class implements Externalizable, false 867 * otherwise. 868 */ 869 boolean isExternalizable() { 870 return externalizable; 871 } 872 873 /** 874 * Returns true if represented class implements Serializable, false 875 * otherwise. 876 */ 877 boolean isSerializable() { 878 return serializable; 879 } 880 881 /** 882 * Returns true if class descriptor represents externalizable class that 883 * has written its data in 1.2 (block data) format, false otherwise. 884 */ 885 boolean hasBlockExternalData() { 886 return hasBlockExternalData; 887 } 888 889 /** 890 * Returns true if class descriptor represents serializable (but not 891 * externalizable) class which has written its data via a custom 892 * writeObject() method, false otherwise. 893 */ 894 boolean hasWriteObjectData() { 895 return hasWriteObjectData; 896 } 897 898 /** 899 * Returns true if represented class is serializable/externalizable and can 900 * be instantiated by the serialization runtime--i.e., if it is 901 * externalizable and defines a public no-arg constructor, or if it is 902 * non-externalizable and its first non-serializable superclass defines an 903 * accessible no-arg constructor. Otherwise, returns false. 904 */ 905 boolean isInstantiable() { 906 return (cons != null); 907 } 908 909 /** 910 * Returns true if represented class is serializable (but not 911 * externalizable) and defines a conformant writeObject method. Otherwise, 912 * returns false. 913 */ 914 boolean hasWriteObjectMethod() { 915 return (writeObjectMethod != null); 916 } 917 918 /** 919 * Returns true if represented class is serializable (but not 920 * externalizable) and defines a conformant readObject method. Otherwise, 921 * returns false. 922 */ 923 boolean hasReadObjectMethod() { 924 return (readObjectMethod != null); 925 } 926 927 /** 928 * Returns true if represented class is serializable (but not 929 * externalizable) and defines a conformant readObjectNoData method. 930 * Otherwise, returns false. 931 */ 932 boolean hasReadObjectNoDataMethod() { 933 return (readObjectNoDataMethod != null); 934 } 935 936 /** 937 * Returns true if represented class is serializable or externalizable and 938 * defines a conformant writeReplace method. Otherwise, returns false. 939 */ 940 boolean hasWriteReplaceMethod() { 941 return (writeReplaceMethod != null); 942 } 943 944 /** 945 * Returns true if represented class is serializable or externalizable and 946 * defines a conformant readResolve method. Otherwise, returns false. 947 */ 948 boolean hasReadResolveMethod() { 949 return (readResolveMethod != null); 950 } 951 952 /** 953 * Creates a new instance of the represented class. If the class is 954 * externalizable, invokes its public no-arg constructor; otherwise, if the 955 * class is serializable, invokes the no-arg constructor of the first 956 * non-serializable superclass. Throws UnsupportedOperationException if 957 * this class descriptor is not associated with a class, if the associated 958 * class is non-serializable or if the appropriate no-arg constructor is 959 * inaccessible/unavailable. 960 */ 961 Object newInstance() 962 throws InstantiationException, InvocationTargetException, 963 UnsupportedOperationException 964 { 965 if (cons != null) { 966 try { 967 return cons.newInstance(); 968 } catch (IllegalAccessException ex) { 969 // should not occur, as access checks have been suppressed 970 throw new InternalError(ex); 971 } 972 } else { 973 throw new UnsupportedOperationException(); 974 } 975 } 976 977 /** 978 * Invokes the writeObject method of the represented serializable class. 979 * Throws UnsupportedOperationException if this class descriptor is not 980 * associated with a class, or if the class is externalizable, 981 * non-serializable or does not define writeObject. 982 */ 983 void invokeWriteObject(Object obj, ObjectOutputStream out) 984 throws IOException, UnsupportedOperationException 985 { 986 if (writeObjectMethod != null) { 987 try { 988 writeObjectMethod.invoke(obj, new Object[]{ out }); 989 } catch (InvocationTargetException ex) { 990 Throwable th = ex.getTargetException(); 991 if (th instanceof IOException) { 992 throw (IOException) th; 993 } else { 994 throwMiscException(th); 995 } 996 } catch (IllegalAccessException ex) { 997 // should not occur, as access checks have been suppressed 998 throw new InternalError(ex); 999 } 1000 } else { 1001 throw new UnsupportedOperationException(); 1002 } 1003 } 1004 1005 /** 1006 * Invokes the readObject method of the represented serializable class. 1007 * Throws UnsupportedOperationException if this class descriptor is not 1008 * associated with a class, or if the class is externalizable, 1009 * non-serializable or does not define readObject. 1010 */ 1011 void invokeReadObject(Object obj, ObjectInputStream in) 1012 throws ClassNotFoundException, IOException, 1013 UnsupportedOperationException 1014 { 1015 if (readObjectMethod != null) { 1016 try { 1017 readObjectMethod.invoke(obj, new Object[]{ in }); 1018 } catch (InvocationTargetException ex) { 1019 Throwable th = ex.getTargetException(); 1020 if (th instanceof ClassNotFoundException) { 1021 throw (ClassNotFoundException) th; 1022 } else if (th instanceof IOException) { 1023 throw (IOException) th; 1024 } else { 1025 throwMiscException(th); 1026 } 1027 } catch (IllegalAccessException ex) { 1028 // should not occur, as access checks have been suppressed 1029 throw new InternalError(ex); 1030 } 1031 } else { 1032 throw new UnsupportedOperationException(); 1033 } 1034 } 1035 1036 /** 1037 * Invokes the readObjectNoData method of the represented serializable 1038 * class. Throws UnsupportedOperationException if this class descriptor is 1039 * not associated with a class, or if the class is externalizable, 1040 * non-serializable or does not define readObjectNoData. 1041 */ 1042 void invokeReadObjectNoData(Object obj) 1043 throws IOException, UnsupportedOperationException 1044 { 1045 if (readObjectNoDataMethod != null) { 1046 try { 1047 readObjectNoDataMethod.invoke(obj, (Object[]) null); 1048 } catch (InvocationTargetException ex) { 1049 Throwable th = ex.getTargetException(); 1050 if (th instanceof ObjectStreamException) { 1051 throw (ObjectStreamException) th; 1052 } else { 1053 throwMiscException(th); 1054 } 1055 } catch (IllegalAccessException ex) { 1056 // should not occur, as access checks have been suppressed 1057 throw new InternalError(ex); 1058 } 1059 } else { 1060 throw new UnsupportedOperationException(); 1061 } 1062 } 1063 1064 /** 1065 * Invokes the writeReplace method of the represented serializable class and 1066 * returns the result. Throws UnsupportedOperationException if this class 1067 * descriptor is not associated with a class, or if the class is 1068 * non-serializable or does not define writeReplace. 1069 */ 1070 Object invokeWriteReplace(Object obj) 1071 throws IOException, UnsupportedOperationException 1072 { 1073 if (writeReplaceMethod != null) { 1074 try { 1075 return writeReplaceMethod.invoke(obj, (Object[]) null); 1076 } catch (InvocationTargetException ex) { 1077 Throwable th = ex.getTargetException(); 1078 if (th instanceof ObjectStreamException) { 1079 throw (ObjectStreamException) th; 1080 } else { 1081 throwMiscException(th); 1082 throw new InternalError(th); // never reached 1083 } 1084 } catch (IllegalAccessException ex) { 1085 // should not occur, as access checks have been suppressed 1086 throw new InternalError(ex); 1087 } 1088 } else { 1089 throw new UnsupportedOperationException(); 1090 } 1091 } 1092 1093 /** 1094 * Invokes the readResolve method of the represented serializable class and 1095 * returns the result. Throws UnsupportedOperationException if this class 1096 * descriptor is not associated with a class, or if the class is 1097 * non-serializable or does not define readResolve. 1098 */ 1099 Object invokeReadResolve(Object obj) 1100 throws IOException, UnsupportedOperationException 1101 { 1102 if (readResolveMethod != null) { 1103 try { 1104 return readResolveMethod.invoke(obj, (Object[]) null); 1105 } catch (InvocationTargetException ex) { 1106 Throwable th = ex.getTargetException(); 1107 if (th instanceof ObjectStreamException) { 1108 throw (ObjectStreamException) th; 1109 } else { 1110 throwMiscException(th); 1111 throw new InternalError(th); // never reached 1112 } 1113 } catch (IllegalAccessException ex) { 1114 // should not occur, as access checks have been suppressed 1115 throw new InternalError(ex); 1116 } 1117 } else { 1118 throw new UnsupportedOperationException(); 1119 } 1120 } 1121 1122 /** 1123 * Class representing the portion of an object's serialized form allotted 1124 * to data described by a given class descriptor. If "hasData" is false, 1125 * the object's serialized form does not contain data associated with the 1126 * class descriptor. 1127 */ 1128 static class ClassDataSlot { 1129 1130 /** class descriptor "occupying" this slot */ 1131 final ObjectStreamClass desc; 1132 /** true if serialized form includes data for this slot's descriptor */ 1133 final boolean hasData; 1134 1135 ClassDataSlot(ObjectStreamClass desc, boolean hasData) { 1136 this.desc = desc; 1137 this.hasData = hasData; 1138 } 1139 } 1140 1141 /** 1142 * Returns array of ClassDataSlot instances representing the data layout 1143 * (including superclass data) for serialized objects described by this 1144 * class descriptor. ClassDataSlots are ordered by inheritance with those 1145 * containing "higher" superclasses appearing first. The final 1146 * ClassDataSlot contains a reference to this descriptor. 1147 */ 1148 ClassDataSlot[] getClassDataLayout() throws InvalidClassException { 1149 // REMIND: synchronize instead of relying on volatile? 1150 if (dataLayout == null) { 1151 dataLayout = getClassDataLayout0(); 1152 } 1153 return dataLayout; 1154 } 1155 1156 private ClassDataSlot[] getClassDataLayout0() 1157 throws InvalidClassException 1158 { 1159 ArrayList<ClassDataSlot> slots = new ArrayList<>(); 1160 Class<?> start = cl, end = cl; 1161 1162 // locate closest non-serializable superclass 1163 while (end != null && Serializable.class.isAssignableFrom(end)) { 1164 end = end.getSuperclass(); 1165 } 1166 1167 HashSet<String> oscNames = new HashSet<>(3); 1168 1169 for (ObjectStreamClass d = this; d != null; d = d.superDesc) { 1170 if (oscNames.contains(d.name)) { 1171 throw new InvalidClassException("Circular reference."); 1172 } else { 1173 oscNames.add(d.name); 1174 } 1175 1176 // search up inheritance hierarchy for class with matching name 1177 String searchName = (d.cl != null) ? d.cl.getName() : d.name; 1178 Class<?> match = null; 1179 for (Class<?> c = start; c != end; c = c.getSuperclass()) { 1180 if (searchName.equals(c.getName())) { 1181 match = c; 1182 break; 1183 } 1184 } 1185 1186 // add "no data" slot for each unmatched class below match 1187 if (match != null) { 1188 for (Class<?> c = start; c != match; c = c.getSuperclass()) { 1189 slots.add(new ClassDataSlot( 1190 ObjectStreamClass.lookup(c, true), false)); 1191 } 1192 start = match.getSuperclass(); 1193 } 1194 1195 // record descriptor/class pairing 1196 slots.add(new ClassDataSlot(d.getVariantFor(match), true)); 1197 } 1198 1199 // add "no data" slot for any leftover unmatched classes 1200 for (Class<?> c = start; c != end; c = c.getSuperclass()) { 1201 slots.add(new ClassDataSlot( 1202 ObjectStreamClass.lookup(c, true), false)); 1203 } 1204 1205 // order slots from superclass -> subclass 1206 Collections.reverse(slots); 1207 return slots.toArray(new ClassDataSlot[slots.size()]); 1208 } 1209 1210 /** 1211 * Returns aggregate size (in bytes) of marshalled primitive field values 1212 * for represented class. 1213 */ 1214 int getPrimDataSize() { 1215 return primDataSize; 1216 } 1217 1218 /** 1219 * Returns number of non-primitive serializable fields of represented 1220 * class. 1221 */ 1222 int getNumObjFields() { 1223 return numObjFields; 1224 } 1225 1226 /** 1227 * Fetches the serializable primitive field values of object obj and 1228 * marshals them into byte array buf starting at offset 0. It is the 1229 * responsibility of the caller to ensure that obj is of the proper type if 1230 * non-null. 1231 */ 1232 void getPrimFieldValues(Object obj, byte[] buf) { 1233 fieldRefl.getPrimFieldValues(obj, buf); 1234 } 1235 1236 /** 1237 * Sets the serializable primitive fields of object obj using values 1238 * unmarshalled from byte array buf starting at offset 0. It is the 1239 * responsibility of the caller to ensure that obj is of the proper type if 1240 * non-null. 1241 */ 1242 void setPrimFieldValues(Object obj, byte[] buf) { 1243 fieldRefl.setPrimFieldValues(obj, buf); 1244 } 1245 1246 /** 1247 * Fetches the serializable object field values of object obj and stores 1248 * them in array vals starting at offset 0. It is the responsibility of 1249 * the caller to ensure that obj is of the proper type if non-null. 1250 */ 1251 void getObjFieldValues(Object obj, Object[] vals) { 1252 fieldRefl.getObjFieldValues(obj, vals); 1253 } 1254 1255 /** 1256 * Checks that the given values, from array vals starting at offset 0, 1257 * are assignable to the given serializable object fields. 1258 * @throws ClassCastException if any value is not assignable 1259 */ 1260 void checkObjFieldValueTypes(Object obj, Object[] vals) { 1261 fieldRefl.checkObjectFieldValueTypes(obj, vals); 1262 } 1263 1264 /** 1265 * Sets the serializable object fields of object obj using values from 1266 * array vals starting at offset 0. It is the responsibility of the caller 1267 * to ensure that obj is of the proper type if non-null. 1268 */ 1269 void setObjFieldValues(Object obj, Object[] vals) { 1270 fieldRefl.setObjFieldValues(obj, vals); 1271 } 1272 1273 /** 1274 * Calculates and sets serializable field offsets, as well as primitive 1275 * data size and object field count totals. Throws InvalidClassException 1276 * if fields are illegally ordered. 1277 */ 1278 private void computeFieldOffsets() throws InvalidClassException { 1279 primDataSize = 0; 1280 numObjFields = 0; 1281 int firstObjIndex = -1; 1282 1283 for (int i = 0; i < fields.length; i++) { 1284 ObjectStreamField f = fields[i]; 1285 switch (f.getTypeCode()) { 1286 case 'Z': 1287 case 'B': 1288 f.setOffset(primDataSize++); 1289 break; 1290 1291 case 'C': 1292 case 'S': 1293 f.setOffset(primDataSize); 1294 primDataSize += 2; 1295 break; 1296 1297 case 'I': 1298 case 'F': 1299 f.setOffset(primDataSize); 1300 primDataSize += 4; 1301 break; 1302 1303 case 'J': 1304 case 'D': 1305 f.setOffset(primDataSize); 1306 primDataSize += 8; 1307 break; 1308 1309 case '[': 1310 case 'L': 1311 f.setOffset(numObjFields++); 1312 if (firstObjIndex == -1) { 1313 firstObjIndex = i; 1314 } 1315 break; 1316 1317 default: 1318 throw new InternalError(); 1319 } 1320 } 1321 if (firstObjIndex != -1 && 1322 firstObjIndex + numObjFields != fields.length) 1323 { 1324 throw new InvalidClassException(name, "illegal field order"); 1325 } 1326 } 1327 1328 /** 1329 * If given class is the same as the class associated with this class 1330 * descriptor, returns reference to this class descriptor. Otherwise, 1331 * returns variant of this class descriptor bound to given class. 1332 */ 1333 private ObjectStreamClass getVariantFor(Class<?> cl) 1334 throws InvalidClassException 1335 { 1336 if (this.cl == cl) { 1337 return this; 1338 } 1339 ObjectStreamClass desc = new ObjectStreamClass(); 1340 if (isProxy) { 1341 desc.initProxy(cl, null, superDesc); 1342 } else { 1343 desc.initNonProxy(this, cl, null, superDesc); 1344 } 1345 return desc; 1346 } 1347 1348 /** 1349 * Returns public no-arg constructor of given class, or null if none found. 1350 * Access checks are disabled on the returned constructor (if any), since 1351 * the defining class may still be non-public. 1352 */ 1353 private static Constructor<?> getExternalizableConstructor(Class<?> cl) { 1354 try { 1355 Constructor<?> cons = cl.getDeclaredConstructor((Class<?>[]) null); 1356 cons.setAccessible(true); 1357 return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ? 1358 cons : null; 1359 } catch (NoSuchMethodException ex) { 1360 return null; 1361 } 1362 } 1363 1364 /** 1365 * Returns subclass-accessible no-arg constructor of first non-serializable 1366 * superclass, or null if none found. Access checks are disabled on the 1367 * returned constructor (if any). 1368 */ 1369 private static Constructor<?> getSerializableConstructor(Class<?> cl) { 1370 Class<?> initCl = cl; 1371 while (Serializable.class.isAssignableFrom(initCl)) { 1372 if ((initCl = initCl.getSuperclass()) == null) { 1373 return null; 1374 } 1375 } 1376 try { 1377 Constructor<?> cons = initCl.getDeclaredConstructor((Class<?>[]) null); 1378 int mods = cons.getModifiers(); 1379 if ((mods & Modifier.PRIVATE) != 0 || 1380 ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 && 1381 !packageEquals(cl, initCl))) 1382 { 1383 return null; 1384 } 1385 cons = reflFactory.newConstructorForSerialization(cl, cons); 1386 cons.setAccessible(true); 1387 return cons; 1388 } catch (NoSuchMethodException ex) { 1389 return null; 1390 } 1391 } 1392 1393 /** 1394 * Returns non-static, non-abstract method with given signature provided it 1395 * is defined by or accessible (via inheritance) by the given class, or 1396 * null if no match found. Access checks are disabled on the returned 1397 * method (if any). 1398 */ 1399 private static Method getInheritableMethod(Class<?> cl, String name, 1400 Class<?>[] argTypes, 1401 Class<?> returnType) 1402 { 1403 Method meth = null; 1404 Class<?> defCl = cl; 1405 while (defCl != null) { 1406 try { 1407 meth = defCl.getDeclaredMethod(name, argTypes); 1408 break; 1409 } catch (NoSuchMethodException ex) { 1410 defCl = defCl.getSuperclass(); 1411 } 1412 } 1413 1414 if ((meth == null) || (meth.getReturnType() != returnType)) { 1415 return null; 1416 } 1417 meth.setAccessible(true); 1418 int mods = meth.getModifiers(); 1419 if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) { 1420 return null; 1421 } else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) { 1422 return meth; 1423 } else if ((mods & Modifier.PRIVATE) != 0) { 1424 return (cl == defCl) ? meth : null; 1425 } else { 1426 return packageEquals(cl, defCl) ? meth : null; 1427 } 1428 } 1429 1430 /** 1431 * Returns non-static private method with given signature defined by given 1432 * class, or null if none found. Access checks are disabled on the 1433 * returned method (if any). 1434 */ 1435 private static Method getPrivateMethod(Class<?> cl, String name, 1436 Class<?>[] argTypes, 1437 Class<?> returnType) 1438 { 1439 try { 1440 Method meth = cl.getDeclaredMethod(name, argTypes); 1441 meth.setAccessible(true); 1442 int mods = meth.getModifiers(); 1443 return ((meth.getReturnType() == returnType) && 1444 ((mods & Modifier.STATIC) == 0) && 1445 ((mods & Modifier.PRIVATE) != 0)) ? meth : null; 1446 } catch (NoSuchMethodException ex) { 1447 return null; 1448 } 1449 } 1450 1451 /** 1452 * Returns true if classes are defined in the same runtime package, false 1453 * otherwise. 1454 */ 1455 private static boolean packageEquals(Class<?> cl1, Class<?> cl2) { 1456 return (cl1.getClassLoader() == cl2.getClassLoader() && 1457 getPackageName(cl1).equals(getPackageName(cl2))); 1458 } 1459 1460 /** 1461 * Returns package name of given class. 1462 */ 1463 private static String getPackageName(Class<?> cl) { 1464 String s = cl.getName(); 1465 int i = s.lastIndexOf('['); 1466 if (i >= 0) { 1467 s = s.substring(i + 2); 1468 } 1469 i = s.lastIndexOf('.'); 1470 return (i >= 0) ? s.substring(0, i) : ""; 1471 } 1472 1473 /** 1474 * Compares class names for equality, ignoring package names. Returns true 1475 * if class names equal, false otherwise. 1476 */ 1477 private static boolean classNamesEqual(String name1, String name2) { 1478 name1 = name1.substring(name1.lastIndexOf('.') + 1); 1479 name2 = name2.substring(name2.lastIndexOf('.') + 1); 1480 return name1.equals(name2); 1481 } 1482 1483 /** 1484 * Returns JVM type signature for given primitive. 1485 */ 1486 private static String getPrimitiveSignature(Class<?> cl) { 1487 if (cl == Integer.TYPE) 1488 return "I"; 1489 else if (cl == Byte.TYPE) 1490 return "B"; 1491 else if (cl == Long.TYPE) 1492 return "J"; 1493 else if (cl == Float.TYPE) 1494 return "F"; 1495 else if (cl == Double.TYPE) 1496 return "D"; 1497 else if (cl == Short.TYPE) 1498 return "S"; 1499 else if (cl == Character.TYPE) 1500 return "C"; 1501 else if (cl == Boolean.TYPE) 1502 return "Z"; 1503 else if (cl == Void.TYPE) 1504 return "V"; 1505 else 1506 throw new InternalError(); 1507 } 1508 1509 /** 1510 * Returns JVM type signature for given class. 1511 */ 1512 static String getClassSignature(Class<?> cl) { 1513 if (cl.isPrimitive()) 1514 return getPrimitiveSignature(cl); 1515 else 1516 return appendClassSignature(new StringBuilder(), cl).toString(); 1517 } 1518 1519 private static StringBuilder appendClassSignature(StringBuilder sbuf, Class<?> cl) { 1520 while (cl.isArray()) { 1521 sbuf.append('['); 1522 cl = cl.getComponentType(); 1523 } 1524 1525 if (cl.isPrimitive()) 1526 sbuf.append(getPrimitiveSignature(cl)); 1527 else 1528 sbuf.append('L').append(cl.getName().replace('.', '/')).append(';'); 1529 1530 return sbuf; 1531 } 1532 1533 /** 1534 * Returns JVM type signature for given list of parameters and return type. 1535 */ 1536 private static String getMethodSignature(Class<?>[] paramTypes, 1537 Class<?> retType) 1538 { 1539 StringBuilder sbuf = new StringBuilder(); 1540 sbuf.append('('); 1541 for (int i = 0; i < paramTypes.length; i++) { 1542 appendClassSignature(sbuf, paramTypes[i]); 1543 } 1544 sbuf.append(')'); 1545 appendClassSignature(sbuf, retType); 1546 return sbuf.toString(); 1547 } 1548 1549 /** 1550 * Convenience method for throwing an exception that is either a 1551 * RuntimeException, Error, or of some unexpected type (in which case it is 1552 * wrapped inside an IOException). 1553 */ 1554 private static void throwMiscException(Throwable th) throws IOException { 1555 if (th instanceof RuntimeException) { 1556 throw (RuntimeException) th; 1557 } else if (th instanceof Error) { 1558 throw (Error) th; 1559 } else { 1560 IOException ex = new IOException("unexpected exception type"); 1561 ex.initCause(th); 1562 throw ex; 1563 } 1564 } 1565 1566 /** 1567 * Returns ObjectStreamField array describing the serializable fields of 1568 * the given class. Serializable fields backed by an actual field of the 1569 * class are represented by ObjectStreamFields with corresponding non-null 1570 * Field objects. Throws InvalidClassException if the (explicitly 1571 * declared) serializable fields are invalid. 1572 */ 1573 private static ObjectStreamField[] getSerialFields(Class<?> cl) 1574 throws InvalidClassException 1575 { 1576 ObjectStreamField[] fields; 1577 if (Serializable.class.isAssignableFrom(cl) && 1578 !Externalizable.class.isAssignableFrom(cl) && 1579 !Proxy.isProxyClass(cl) && 1580 !cl.isInterface()) 1581 { 1582 if ((fields = getDeclaredSerialFields(cl)) == null) { 1583 fields = getDefaultSerialFields(cl); 1584 } 1585 Arrays.sort(fields); 1586 } else { 1587 fields = NO_FIELDS; 1588 } 1589 return fields; 1590 } 1591 1592 /** 1593 * Returns serializable fields of given class as defined explicitly by a 1594 * "serialPersistentFields" field, or null if no appropriate 1595 * "serialPersistentFields" field is defined. Serializable fields backed 1596 * by an actual field of the class are represented by ObjectStreamFields 1597 * with corresponding non-null Field objects. For compatibility with past 1598 * releases, a "serialPersistentFields" field with a null value is 1599 * considered equivalent to not declaring "serialPersistentFields". Throws 1600 * InvalidClassException if the declared serializable fields are 1601 * invalid--e.g., if multiple fields share the same name. 1602 */ 1603 private static ObjectStreamField[] getDeclaredSerialFields(Class<?> cl) 1604 throws InvalidClassException 1605 { 1606 ObjectStreamField[] serialPersistentFields = null; 1607 try { 1608 Field f = cl.getDeclaredField("serialPersistentFields"); 1609 int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL; 1610 if ((f.getModifiers() & mask) == mask) { 1611 f.setAccessible(true); 1612 serialPersistentFields = (ObjectStreamField[]) f.get(null); 1613 } 1614 } catch (Exception ex) { 1615 } 1616 if (serialPersistentFields == null) { 1617 return null; 1618 } else if (serialPersistentFields.length == 0) { 1619 return NO_FIELDS; 1620 } 1621 1622 ObjectStreamField[] boundFields = 1623 new ObjectStreamField[serialPersistentFields.length]; 1624 Set<String> fieldNames = new HashSet<>(serialPersistentFields.length); 1625 1626 for (int i = 0; i < serialPersistentFields.length; i++) { 1627 ObjectStreamField spf = serialPersistentFields[i]; 1628 1629 String fname = spf.getName(); 1630 if (fieldNames.contains(fname)) { 1631 throw new InvalidClassException( 1632 "multiple serializable fields named " + fname); 1633 } 1634 fieldNames.add(fname); 1635 1636 try { 1637 Field f = cl.getDeclaredField(fname); 1638 if ((f.getType() == spf.getType()) && 1639 ((f.getModifiers() & Modifier.STATIC) == 0)) 1640 { 1641 boundFields[i] = 1642 new ObjectStreamField(f, spf.isUnshared(), true); 1643 } 1644 } catch (NoSuchFieldException ex) { 1645 } 1646 if (boundFields[i] == null) { 1647 boundFields[i] = new ObjectStreamField( 1648 fname, spf.getType(), spf.isUnshared()); 1649 } 1650 } 1651 return boundFields; 1652 } 1653 1654 /** 1655 * Returns array of ObjectStreamFields corresponding to all non-static 1656 * non-transient fields declared by given class. Each ObjectStreamField 1657 * contains a Field object for the field it represents. If no default 1658 * serializable fields exist, NO_FIELDS is returned. 1659 */ 1660 private static ObjectStreamField[] getDefaultSerialFields(Class<?> cl) { 1661 Field[] clFields = cl.getDeclaredFields(); 1662 ArrayList<ObjectStreamField> list = new ArrayList<>(); 1663 int mask = Modifier.STATIC | Modifier.TRANSIENT; 1664 1665 for (int i = 0; i < clFields.length; i++) { 1666 if ((clFields[i].getModifiers() & mask) == 0) { 1667 list.add(new ObjectStreamField(clFields[i], false, true)); 1668 } 1669 } 1670 int size = list.size(); 1671 return (size == 0) ? NO_FIELDS : 1672 list.toArray(new ObjectStreamField[size]); 1673 } 1674 1675 /** 1676 * Returns explicit serial version UID value declared by given class, or 1677 * null if none. 1678 */ 1679 private static Long getDeclaredSUID(Class<?> cl) { 1680 try { 1681 Field f = cl.getDeclaredField("serialVersionUID"); 1682 int mask = Modifier.STATIC | Modifier.FINAL; 1683 if ((f.getModifiers() & mask) == mask) { 1684 f.setAccessible(true); 1685 return Long.valueOf(f.getLong(null)); 1686 } 1687 } catch (Exception ex) { 1688 } 1689 return null; 1690 } 1691 1692 /** 1693 * Computes the default serial version UID value for the given class. 1694 */ 1695 private static long computeDefaultSUID(Class<?> cl) { 1696 if (!Serializable.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl)) 1697 { 1698 return 0L; 1699 } 1700 1701 try { 1702 ByteArrayOutputStream bout = new ByteArrayOutputStream(); 1703 DataOutputStream dout = new DataOutputStream(bout); 1704 1705 dout.writeUTF(cl.getName()); 1706 1707 int classMods = cl.getModifiers() & 1708 (Modifier.PUBLIC | Modifier.FINAL | 1709 Modifier.INTERFACE | Modifier.ABSTRACT); 1710 1711 /* 1712 * compensate for javac bug in which ABSTRACT bit was set for an 1713 * interface only if the interface declared methods 1714 */ 1715 Method[] methods = cl.getDeclaredMethods(); 1716 if ((classMods & Modifier.INTERFACE) != 0) { 1717 classMods = (methods.length > 0) ? 1718 (classMods | Modifier.ABSTRACT) : 1719 (classMods & ~Modifier.ABSTRACT); 1720 } 1721 dout.writeInt(classMods); 1722 1723 if (!cl.isArray()) { 1724 /* 1725 * compensate for change in 1.2FCS in which 1726 * Class.getInterfaces() was modified to return Cloneable and 1727 * Serializable for array classes. 1728 */ 1729 Class<?>[] interfaces = cl.getInterfaces(); 1730 String[] ifaceNames = new String[interfaces.length]; 1731 for (int i = 0; i < interfaces.length; i++) { 1732 ifaceNames[i] = interfaces[i].getName(); 1733 } 1734 Arrays.sort(ifaceNames); 1735 for (int i = 0; i < ifaceNames.length; i++) { 1736 dout.writeUTF(ifaceNames[i]); 1737 } 1738 } 1739 1740 Field[] fields = cl.getDeclaredFields(); 1741 MemberSignature[] fieldSigs = new MemberSignature[fields.length]; 1742 for (int i = 0; i < fields.length; i++) { 1743 fieldSigs[i] = new MemberSignature(fields[i]); 1744 } 1745 Arrays.sort(fieldSigs, new Comparator<>() { 1746 public int compare(MemberSignature ms1, MemberSignature ms2) { 1747 return ms1.name.compareTo(ms2.name); 1748 } 1749 }); 1750 for (int i = 0; i < fieldSigs.length; i++) { 1751 MemberSignature sig = fieldSigs[i]; 1752 int mods = sig.member.getModifiers() & 1753 (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | 1754 Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE | 1755 Modifier.TRANSIENT); 1756 if (((mods & Modifier.PRIVATE) == 0) || 1757 ((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0)) 1758 { 1759 dout.writeUTF(sig.name); 1760 dout.writeInt(mods); 1761 dout.writeUTF(sig.signature); 1762 } 1763 } 1764 1765 if (hasStaticInitializer(cl)) { 1766 dout.writeUTF("<clinit>"); 1767 dout.writeInt(Modifier.STATIC); 1768 dout.writeUTF("()V"); 1769 } 1770 1771 Constructor<?>[] cons = cl.getDeclaredConstructors(); 1772 MemberSignature[] consSigs = new MemberSignature[cons.length]; 1773 for (int i = 0; i < cons.length; i++) { 1774 consSigs[i] = new MemberSignature(cons[i]); 1775 } 1776 Arrays.sort(consSigs, new Comparator<>() { 1777 public int compare(MemberSignature ms1, MemberSignature ms2) { 1778 return ms1.signature.compareTo(ms2.signature); 1779 } 1780 }); 1781 for (int i = 0; i < consSigs.length; i++) { 1782 MemberSignature sig = consSigs[i]; 1783 int mods = sig.member.getModifiers() & 1784 (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | 1785 Modifier.STATIC | Modifier.FINAL | 1786 Modifier.SYNCHRONIZED | Modifier.NATIVE | 1787 Modifier.ABSTRACT | Modifier.STRICT); 1788 if ((mods & Modifier.PRIVATE) == 0) { 1789 dout.writeUTF("<init>"); 1790 dout.writeInt(mods); 1791 dout.writeUTF(sig.signature.replace('/', '.')); 1792 } 1793 } 1794 1795 MemberSignature[] methSigs = new MemberSignature[methods.length]; 1796 for (int i = 0; i < methods.length; i++) { 1797 methSigs[i] = new MemberSignature(methods[i]); 1798 } 1799 Arrays.sort(methSigs, new Comparator<>() { 1800 public int compare(MemberSignature ms1, MemberSignature ms2) { 1801 int comp = ms1.name.compareTo(ms2.name); 1802 if (comp == 0) { 1803 comp = ms1.signature.compareTo(ms2.signature); 1804 } 1805 return comp; 1806 } 1807 }); 1808 for (int i = 0; i < methSigs.length; i++) { 1809 MemberSignature sig = methSigs[i]; 1810 int mods = sig.member.getModifiers() & 1811 (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | 1812 Modifier.STATIC | Modifier.FINAL | 1813 Modifier.SYNCHRONIZED | Modifier.NATIVE | 1814 Modifier.ABSTRACT | Modifier.STRICT); 1815 if ((mods & Modifier.PRIVATE) == 0) { 1816 dout.writeUTF(sig.name); 1817 dout.writeInt(mods); 1818 dout.writeUTF(sig.signature.replace('/', '.')); 1819 } 1820 } 1821 1822 dout.flush(); 1823 1824 MessageDigest md = MessageDigest.getInstance("SHA"); 1825 byte[] hashBytes = md.digest(bout.toByteArray()); 1826 long hash = 0; 1827 for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) { 1828 hash = (hash << 8) | (hashBytes[i] & 0xFF); 1829 } 1830 return hash; 1831 } catch (IOException ex) { 1832 throw new InternalError(ex); 1833 } catch (NoSuchAlgorithmException ex) { 1834 throw new SecurityException(ex.getMessage()); 1835 } 1836 } 1837 1838 /** 1839 * Returns true if the given class defines a static initializer method, 1840 * false otherwise. 1841 */ 1842 private native static boolean hasStaticInitializer(Class<?> cl); 1843 1844 /** 1845 * Class for computing and caching field/constructor/method signatures 1846 * during serialVersionUID calculation. 1847 */ 1848 private static class MemberSignature { 1849 1850 public final Member member; 1851 public final String name; 1852 public final String signature; 1853 1854 public MemberSignature(Field field) { 1855 member = field; 1856 name = field.getName(); 1857 signature = getClassSignature(field.getType()); 1858 } 1859 1860 public MemberSignature(Constructor<?> cons) { 1861 member = cons; 1862 name = cons.getName(); 1863 signature = getMethodSignature( 1864 cons.getParameterTypes(), Void.TYPE); 1865 } 1866 1867 public MemberSignature(Method meth) { 1868 member = meth; 1869 name = meth.getName(); 1870 signature = getMethodSignature( 1871 meth.getParameterTypes(), meth.getReturnType()); 1872 } 1873 } 1874 1875 /** 1876 * Class for setting and retrieving serializable field values in batch. 1877 */ 1878 // REMIND: dynamically generate these? 1879 private static class FieldReflector { 1880 1881 /** handle for performing unsafe operations */ 1882 private static final Unsafe unsafe = Unsafe.getUnsafe(); 1883 1884 /** fields to operate on */ 1885 private final ObjectStreamField[] fields; 1886 /** number of primitive fields */ 1887 private final int numPrimFields; 1888 /** unsafe field keys for reading fields - may contain dupes */ 1889 private final long[] readKeys; 1890 /** unsafe fields keys for writing fields - no dupes */ 1891 private final long[] writeKeys; 1892 /** field data offsets */ 1893 private final int[] offsets; 1894 /** field type codes */ 1895 private final char[] typeCodes; 1896 /** field types */ 1897 private final Class<?>[] types; 1898 1899 /** 1900 * Constructs FieldReflector capable of setting/getting values from the 1901 * subset of fields whose ObjectStreamFields contain non-null 1902 * reflective Field objects. ObjectStreamFields with null Fields are 1903 * treated as filler, for which get operations return default values 1904 * and set operations discard given values. 1905 */ 1906 FieldReflector(ObjectStreamField[] fields) { 1907 this.fields = fields; 1908 int nfields = fields.length; 1909 readKeys = new long[nfields]; 1910 writeKeys = new long[nfields]; 1911 offsets = new int[nfields]; 1912 typeCodes = new char[nfields]; 1913 ArrayList<Class<?>> typeList = new ArrayList<>(); 1914 Set<Long> usedKeys = new HashSet<>(); 1915 1916 1917 for (int i = 0; i < nfields; i++) { 1918 ObjectStreamField f = fields[i]; 1919 Field rf = f.getField(); 1920 long key = (rf != null) ? 1921 unsafe.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET; 1922 readKeys[i] = key; 1923 writeKeys[i] = usedKeys.add(key) ? 1924 key : Unsafe.INVALID_FIELD_OFFSET; 1925 offsets[i] = f.getOffset(); 1926 typeCodes[i] = f.getTypeCode(); 1927 if (!f.isPrimitive()) { 1928 typeList.add((rf != null) ? rf.getType() : null); 1929 } 1930 } 1931 1932 types = typeList.toArray(new Class<?>[typeList.size()]); 1933 numPrimFields = nfields - types.length; 1934 } 1935 1936 /** 1937 * Returns list of ObjectStreamFields representing fields operated on 1938 * by this reflector. The shared/unshared values and Field objects 1939 * contained by ObjectStreamFields in the list reflect their bindings 1940 * to locally defined serializable fields. 1941 */ 1942 ObjectStreamField[] getFields() { 1943 return fields; 1944 } 1945 1946 /** 1947 * Fetches the serializable primitive field values of object obj and 1948 * marshals them into byte array buf starting at offset 0. The caller 1949 * is responsible for ensuring that obj is of the proper type. 1950 */ 1951 void getPrimFieldValues(Object obj, byte[] buf) { 1952 if (obj == null) { 1953 throw new NullPointerException(); 1954 } 1955 /* assuming checkDefaultSerialize() has been called on the class 1956 * descriptor this FieldReflector was obtained from, no field keys 1957 * in array should be equal to Unsafe.INVALID_FIELD_OFFSET. 1958 */ 1959 for (int i = 0; i < numPrimFields; i++) { 1960 long key = readKeys[i]; 1961 int off = offsets[i]; 1962 switch (typeCodes[i]) { 1963 case 'Z': 1964 Bits.putBoolean(buf, off, unsafe.getBoolean(obj, key)); 1965 break; 1966 1967 case 'B': 1968 buf[off] = unsafe.getByte(obj, key); 1969 break; 1970 1971 case 'C': 1972 Bits.putChar(buf, off, unsafe.getChar(obj, key)); 1973 break; 1974 1975 case 'S': 1976 Bits.putShort(buf, off, unsafe.getShort(obj, key)); 1977 break; 1978 1979 case 'I': 1980 Bits.putInt(buf, off, unsafe.getInt(obj, key)); 1981 break; 1982 1983 case 'F': 1984 Bits.putFloat(buf, off, unsafe.getFloat(obj, key)); 1985 break; 1986 1987 case 'J': 1988 Bits.putLong(buf, off, unsafe.getLong(obj, key)); 1989 break; 1990 1991 case 'D': 1992 Bits.putDouble(buf, off, unsafe.getDouble(obj, key)); 1993 break; 1994 1995 default: 1996 throw new InternalError(); 1997 } 1998 } 1999 } 2000 2001 /** 2002 * Sets the serializable primitive fields of object obj using values 2003 * unmarshalled from byte array buf starting at offset 0. The caller 2004 * is responsible for ensuring that obj is of the proper type. 2005 */ 2006 void setPrimFieldValues(Object obj, byte[] buf) { 2007 if (obj == null) { 2008 throw new NullPointerException(); 2009 } 2010 for (int i = 0; i < numPrimFields; i++) { 2011 long key = writeKeys[i]; 2012 if (key == Unsafe.INVALID_FIELD_OFFSET) { 2013 continue; // discard value 2014 } 2015 int off = offsets[i]; 2016 switch (typeCodes[i]) { 2017 case 'Z': 2018 unsafe.putBoolean(obj, key, Bits.getBoolean(buf, off)); 2019 break; 2020 2021 case 'B': 2022 unsafe.putByte(obj, key, buf[off]); 2023 break; 2024 2025 case 'C': 2026 unsafe.putChar(obj, key, Bits.getChar(buf, off)); 2027 break; 2028 2029 case 'S': 2030 unsafe.putShort(obj, key, Bits.getShort(buf, off)); 2031 break; 2032 2033 case 'I': 2034 unsafe.putInt(obj, key, Bits.getInt(buf, off)); 2035 break; 2036 2037 case 'F': 2038 unsafe.putFloat(obj, key, Bits.getFloat(buf, off)); 2039 break; 2040 2041 case 'J': 2042 unsafe.putLong(obj, key, Bits.getLong(buf, off)); 2043 break; 2044 2045 case 'D': 2046 unsafe.putDouble(obj, key, Bits.getDouble(buf, off)); 2047 break; 2048 2049 default: 2050 throw new InternalError(); 2051 } 2052 } 2053 } 2054 2055 /** 2056 * Fetches the serializable object field values of object obj and 2057 * stores them in array vals starting at offset 0. The caller is 2058 * responsible for ensuring that obj is of the proper type. 2059 */ 2060 void getObjFieldValues(Object obj, Object[] vals) { 2061 if (obj == null) { 2062 throw new NullPointerException(); 2063 } 2064 /* assuming checkDefaultSerialize() has been called on the class 2065 * descriptor this FieldReflector was obtained from, no field keys 2066 * in array should be equal to Unsafe.INVALID_FIELD_OFFSET. 2067 */ 2068 for (int i = numPrimFields; i < fields.length; i++) { 2069 switch (typeCodes[i]) { 2070 case 'L': 2071 case '[': 2072 vals[offsets[i]] = unsafe.getObject(obj, readKeys[i]); 2073 break; 2074 2075 default: 2076 throw new InternalError(); 2077 } 2078 } 2079 } 2080 2081 /** 2082 * Checks that the given values, from array vals starting at offset 0, 2083 * are assignable to the given serializable object fields. 2084 * @throws ClassCastException if any value is not assignable 2085 */ 2086 void checkObjectFieldValueTypes(Object obj, Object[] vals) { 2087 setObjFieldValues(obj, vals, true); 2088 } 2089 2090 /** 2091 * Sets the serializable object fields of object obj using values from 2092 * array vals starting at offset 0. The caller is responsible for 2093 * ensuring that obj is of the proper type; however, attempts to set a 2094 * field with a value of the wrong type will trigger an appropriate 2095 * ClassCastException. 2096 */ 2097 void setObjFieldValues(Object obj, Object[] vals) { 2098 setObjFieldValues(obj, vals, false); 2099 } 2100 2101 private void setObjFieldValues(Object obj, Object[] vals, boolean dryRun) { 2102 if (obj == null) { 2103 throw new NullPointerException(); 2104 } 2105 for (int i = numPrimFields; i < fields.length; i++) { 2106 long key = writeKeys[i]; 2107 if (key == Unsafe.INVALID_FIELD_OFFSET) { 2108 continue; // discard value 2109 } 2110 switch (typeCodes[i]) { 2111 case 'L': 2112 case '[': 2113 Object val = vals[offsets[i]]; 2114 if (val != null && 2115 !types[i - numPrimFields].isInstance(val)) 2116 { 2117 Field f = fields[i].getField(); 2118 throw new ClassCastException( 2119 "cannot assign instance of " + 2120 val.getClass().getName() + " to field " + 2121 f.getDeclaringClass().getName() + "." + 2122 f.getName() + " of type " + 2123 f.getType().getName() + " in instance of " + 2124 obj.getClass().getName()); 2125 } 2126 if (!dryRun) 2127 unsafe.putObject(obj, key, val); 2128 break; 2129 2130 default: 2131 throw new InternalError(); 2132 } 2133 } 2134 } 2135 } 2136 2137 /** 2138 * Matches given set of serializable fields with serializable fields 2139 * described by the given local class descriptor, and returns a 2140 * FieldReflector instance capable of setting/getting values from the 2141 * subset of fields that match (non-matching fields are treated as filler, 2142 * for which get operations return default values and set operations 2143 * discard given values). Throws InvalidClassException if unresolvable 2144 * type conflicts exist between the two sets of fields. 2145 */ 2146 private static FieldReflector getReflector(ObjectStreamField[] fields, 2147 ObjectStreamClass localDesc) 2148 throws InvalidClassException 2149 { 2150 // class irrelevant if no fields 2151 Class<?> cl = (localDesc != null && fields.length > 0) ? 2152 localDesc.cl : null; 2153 processQueue(Caches.reflectorsQueue, Caches.reflectors); 2154 FieldReflectorKey key = new FieldReflectorKey(cl, fields, 2155 Caches.reflectorsQueue); 2156 Reference<?> ref = Caches.reflectors.get(key); 2157 Object entry = null; 2158 if (ref != null) { 2159 entry = ref.get(); 2160 } 2161 EntryFuture future = null; 2162 if (entry == null) { 2163 EntryFuture newEntry = new EntryFuture(); 2164 Reference<?> newRef = new SoftReference<>(newEntry); 2165 do { 2166 if (ref != null) { 2167 Caches.reflectors.remove(key, ref); 2168 } 2169 ref = Caches.reflectors.putIfAbsent(key, newRef); 2170 if (ref != null) { 2171 entry = ref.get(); 2172 } 2173 } while (ref != null && entry == null); 2174 if (entry == null) { 2175 future = newEntry; 2176 } 2177 } 2178 2179 if (entry instanceof FieldReflector) { // check common case first 2180 return (FieldReflector) entry; 2181 } else if (entry instanceof EntryFuture) { 2182 entry = ((EntryFuture) entry).get(); 2183 } else if (entry == null) { 2184 try { 2185 entry = new FieldReflector(matchFields(fields, localDesc)); 2186 } catch (Throwable th) { 2187 entry = th; 2188 } 2189 future.set(entry); 2190 Caches.reflectors.put(key, new SoftReference<>(entry)); 2191 } 2192 2193 if (entry instanceof FieldReflector) { 2194 return (FieldReflector) entry; 2195 } else if (entry instanceof InvalidClassException) { 2196 throw (InvalidClassException) entry; 2197 } else if (entry instanceof RuntimeException) { 2198 throw (RuntimeException) entry; 2199 } else if (entry instanceof Error) { 2200 throw (Error) entry; 2201 } else { 2202 throw new InternalError("unexpected entry: " + entry); 2203 } 2204 } 2205 2206 /** 2207 * FieldReflector cache lookup key. Keys are considered equal if they 2208 * refer to the same class and equivalent field formats. 2209 */ 2210 private static class FieldReflectorKey extends WeakReference<Class<?>> { 2211 2212 private final String sigs; 2213 private final int hash; 2214 private final boolean nullClass; 2215 2216 FieldReflectorKey(Class<?> cl, ObjectStreamField[] fields, 2217 ReferenceQueue<Class<?>> queue) 2218 { 2219 super(cl, queue); 2220 nullClass = (cl == null); 2221 StringBuilder sbuf = new StringBuilder(); 2222 for (int i = 0; i < fields.length; i++) { 2223 ObjectStreamField f = fields[i]; 2224 sbuf.append(f.getName()).append(f.getSignature()); 2225 } 2226 sigs = sbuf.toString(); 2227 hash = System.identityHashCode(cl) + sigs.hashCode(); 2228 } 2229 2230 public int hashCode() { 2231 return hash; 2232 } 2233 2234 public boolean equals(Object obj) { 2235 if (obj == this) { 2236 return true; 2237 } 2238 2239 if (obj instanceof FieldReflectorKey) { 2240 FieldReflectorKey other = (FieldReflectorKey) obj; 2241 Class<?> referent; 2242 return (nullClass ? other.nullClass 2243 : ((referent = get()) != null) && 2244 (referent == other.get())) && 2245 sigs.equals(other.sigs); 2246 } else { 2247 return false; 2248 } 2249 } 2250 } 2251 2252 /** 2253 * Matches given set of serializable fields with serializable fields 2254 * obtained from the given local class descriptor (which contain bindings 2255 * to reflective Field objects). Returns list of ObjectStreamFields in 2256 * which each ObjectStreamField whose signature matches that of a local 2257 * field contains a Field object for that field; unmatched 2258 * ObjectStreamFields contain null Field objects. Shared/unshared settings 2259 * of the returned ObjectStreamFields also reflect those of matched local 2260 * ObjectStreamFields. Throws InvalidClassException if unresolvable type 2261 * conflicts exist between the two sets of fields. 2262 */ 2263 private static ObjectStreamField[] matchFields(ObjectStreamField[] fields, 2264 ObjectStreamClass localDesc) 2265 throws InvalidClassException 2266 { 2267 ObjectStreamField[] localFields = (localDesc != null) ? 2268 localDesc.fields : NO_FIELDS; 2269 2270 /* 2271 * Even if fields == localFields, we cannot simply return localFields 2272 * here. In previous implementations of serialization, 2273 * ObjectStreamField.getType() returned Object.class if the 2274 * ObjectStreamField represented a non-primitive field and belonged to 2275 * a non-local class descriptor. To preserve this (questionable) 2276 * behavior, the ObjectStreamField instances returned by matchFields 2277 * cannot report non-primitive types other than Object.class; hence 2278 * localFields cannot be returned directly. 2279 */ 2280 2281 ObjectStreamField[] matches = new ObjectStreamField[fields.length]; 2282 for (int i = 0; i < fields.length; i++) { 2283 ObjectStreamField f = fields[i], m = null; 2284 for (int j = 0; j < localFields.length; j++) { 2285 ObjectStreamField lf = localFields[j]; 2286 if (f.getName().equals(lf.getName())) { 2287 if ((f.isPrimitive() || lf.isPrimitive()) && 2288 f.getTypeCode() != lf.getTypeCode()) 2289 { 2290 throw new InvalidClassException(localDesc.name, 2291 "incompatible types for field " + f.getName()); 2292 } 2293 if (lf.getField() != null) { 2294 m = new ObjectStreamField( 2295 lf.getField(), lf.isUnshared(), false); 2296 } else { 2297 m = new ObjectStreamField( 2298 lf.getName(), lf.getSignature(), lf.isUnshared()); 2299 } 2300 } 2301 } 2302 if (m == null) { 2303 m = new ObjectStreamField( 2304 f.getName(), f.getSignature(), false); 2305 } 2306 m.setOffset(f.getOffset()); 2307 matches[i] = m; 2308 } 2309 return matches; 2310 } 2311 2312 /** 2313 * Removes from the specified map any keys that have been enqueued 2314 * on the specified reference queue. 2315 */ 2316 static void processQueue(ReferenceQueue<Class<?>> queue, 2317 ConcurrentMap<? extends 2318 WeakReference<Class<?>>, ?> map) 2319 { 2320 Reference<? extends Class<?>> ref; 2321 while((ref = queue.poll()) != null) { 2322 map.remove(ref); 2323 } 2324 } 2325 2326 /** 2327 * Weak key for Class objects. 2328 * 2329 **/ 2330 static class WeakClassKey extends WeakReference<Class<?>> { 2331 /** 2332 * saved value of the referent's identity hash code, to maintain 2333 * a consistent hash code after the referent has been cleared 2334 */ 2335 private final int hash; 2336 2337 /** 2338 * Create a new WeakClassKey to the given object, registered 2339 * with a queue. 2340 */ 2341 WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) { 2342 super(cl, refQueue); 2343 hash = System.identityHashCode(cl); 2344 } 2345 2346 /** 2347 * Returns the identity hash code of the original referent. 2348 */ 2349 public int hashCode() { 2350 return hash; 2351 } 2352 2353 /** 2354 * Returns true if the given object is this identical 2355 * WeakClassKey instance, or, if this object's referent has not 2356 * been cleared, if the given object is another WeakClassKey 2357 * instance with the identical non-null referent as this one. 2358 */ 2359 public boolean equals(Object obj) { 2360 if (obj == this) { 2361 return true; 2362 } 2363 2364 if (obj instanceof WeakClassKey) { 2365 Object referent = get(); 2366 return (referent != null) && 2367 (referent == ((WeakClassKey) obj).get()); 2368 } else { 2369 return false; 2370 } 2371 } 2372 } 2373 } --- EOF ---