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