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