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