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