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