jaroslav@601: /* jaroslav@601: * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved. jaroslav@601: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@601: * jaroslav@601: * This code is free software; you can redistribute it and/or modify it jaroslav@601: * under the terms of the GNU General Public License version 2 only, as jaroslav@601: * published by the Free Software Foundation. Oracle designates this jaroslav@601: * particular file as subject to the "Classpath" exception as provided jaroslav@601: * by Oracle in the LICENSE file that accompanied this code. jaroslav@601: * jaroslav@601: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@601: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@601: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@601: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@601: * accompanied this code). jaroslav@601: * jaroslav@601: * You should have received a copy of the GNU General Public License version jaroslav@601: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@601: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@601: * jaroslav@601: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@601: * or visit www.oracle.com if you need additional information or have any jaroslav@601: * questions. jaroslav@601: */ jaroslav@601: jaroslav@601: package java.io; jaroslav@601: jaroslav@601: import java.io.ObjectStreamClass.WeakClassKey; jaroslav@601: import java.lang.ref.ReferenceQueue; jaroslav@601: import java.lang.reflect.Array; jaroslav@601: import java.lang.reflect.Modifier; jaroslav@601: import java.lang.reflect.Proxy; jaroslav@601: import java.security.AccessControlContext; jaroslav@601: import java.security.AccessController; jaroslav@601: import java.security.PrivilegedAction; jaroslav@601: import java.security.PrivilegedActionException; jaroslav@601: import java.security.PrivilegedExceptionAction; jaroslav@601: import java.util.Arrays; jaroslav@601: import java.util.HashMap; jaroslav@601: import java.util.concurrent.ConcurrentHashMap; jaroslav@601: import java.util.concurrent.ConcurrentMap; jaroslav@601: import java.util.concurrent.atomic.AtomicBoolean; jaroslav@601: import static java.io.ObjectStreamClass.processQueue; jaroslav@601: jaroslav@601: /** jaroslav@601: * An ObjectInputStream deserializes primitive data and objects previously jaroslav@601: * written using an ObjectOutputStream. jaroslav@601: * jaroslav@601: *
ObjectOutputStream and ObjectInputStream can provide an application with jaroslav@601: * persistent storage for graphs of objects when used with a FileOutputStream jaroslav@601: * and FileInputStream respectively. ObjectInputStream is used to recover jaroslav@601: * those objects previously serialized. Other uses include passing objects jaroslav@601: * between hosts using a socket stream or for marshaling and unmarshaling jaroslav@601: * arguments and parameters in a remote communication system. jaroslav@601: * jaroslav@601: *
ObjectInputStream ensures that the types of all objects in the graph jaroslav@601: * created from the stream match the classes present in the Java Virtual jaroslav@601: * Machine. Classes are loaded as required using the standard mechanisms. jaroslav@601: * jaroslav@601: *
Only objects that support the java.io.Serializable or jaroslav@601: * java.io.Externalizable interface can be read from streams. jaroslav@601: * jaroslav@601: *
The method readObject
is used to read an object from the
jaroslav@601: * stream. Java's safe casting should be used to get the desired type. In
jaroslav@601: * Java, strings and arrays are objects and are treated as objects during
jaroslav@601: * serialization. When read they need to be cast to the expected type.
jaroslav@601: *
jaroslav@601: *
Primitive data types can be read from the stream using the appropriate jaroslav@601: * method on DataInput. jaroslav@601: * jaroslav@601: *
The default deserialization mechanism for objects restores the contents jaroslav@601: * of each field to the value and type it had when it was written. Fields jaroslav@601: * declared as transient or static are ignored by the deserialization process. jaroslav@601: * References to other objects cause those objects to be read from the stream jaroslav@601: * as necessary. Graphs of objects are restored correctly using a reference jaroslav@601: * sharing mechanism. New objects are always allocated when deserializing, jaroslav@601: * which prevents existing objects from being overwritten. jaroslav@601: * jaroslav@601: *
Reading an object is analogous to running the constructors of a new jaroslav@601: * object. Memory is allocated for the object and initialized to zero (NULL). jaroslav@601: * No-arg constructors are invoked for the non-serializable classes and then jaroslav@601: * the fields of the serializable classes are restored from the stream starting jaroslav@601: * with the serializable class closest to java.lang.object and finishing with jaroslav@601: * the object's most specific class. jaroslav@601: * jaroslav@601: *
For example to read from a stream as written by the example in
jaroslav@601: * ObjectOutputStream:
jaroslav@601: *
jaroslav@601: *
jaroslav@601: * FileInputStream fis = new FileInputStream("t.tmp"); jaroslav@601: * ObjectInputStream ois = new ObjectInputStream(fis); jaroslav@601: * jaroslav@601: * int i = ois.readInt(); jaroslav@601: * String today = (String) ois.readObject(); jaroslav@601: * Date date = (Date) ois.readObject(); jaroslav@601: * jaroslav@601: * ois.close(); jaroslav@601: *jaroslav@601: * jaroslav@601: *
Classes control how they are serialized by implementing either the jaroslav@601: * java.io.Serializable or java.io.Externalizable interfaces. jaroslav@601: * jaroslav@601: *
Implementing the Serializable interface allows object serialization to jaroslav@601: * save and restore the entire state of the object and it allows classes to jaroslav@601: * evolve between the time the stream is written and the time it is read. It jaroslav@601: * automatically traverses references between objects, saving and restoring jaroslav@601: * entire graphs. jaroslav@601: * jaroslav@601: *
Serializable classes that require special handling during the jaroslav@601: * serialization and deserialization process should implement the following jaroslav@601: * methods:
jaroslav@601: * jaroslav@601: *
jaroslav@601: * private void writeObject(java.io.ObjectOutputStream stream) jaroslav@601: * throws IOException; jaroslav@601: * private void readObject(java.io.ObjectInputStream stream) jaroslav@601: * throws IOException, ClassNotFoundException; jaroslav@601: * private void readObjectNoData() jaroslav@601: * throws ObjectStreamException; jaroslav@601: *jaroslav@601: * jaroslav@601: *
The readObject method is responsible for reading and restoring the state jaroslav@601: * of the object for its particular class using data written to the stream by jaroslav@601: * the corresponding writeObject method. The method does not need to concern jaroslav@601: * itself with the state belonging to its superclasses or subclasses. State is jaroslav@601: * restored by reading data from the ObjectInputStream for the individual jaroslav@601: * fields and making assignments to the appropriate fields of the object. jaroslav@601: * Reading primitive data types is supported by DataInput. jaroslav@601: * jaroslav@601: *
Any attempt to read object data which exceeds the boundaries of the jaroslav@601: * custom data written by the corresponding writeObject method will cause an jaroslav@601: * OptionalDataException to be thrown with an eof field value of true. jaroslav@601: * Non-object reads which exceed the end of the allotted data will reflect the jaroslav@601: * end of data in the same way that they would indicate the end of the stream: jaroslav@601: * bytewise reads will return -1 as the byte read or number of bytes read, and jaroslav@601: * primitive reads will throw EOFExceptions. If there is no corresponding jaroslav@601: * writeObject method, then the end of default serialized data marks the end of jaroslav@601: * the allotted data. jaroslav@601: * jaroslav@601: *
Primitive and object read calls issued from within a readExternal method
jaroslav@601: * behave in the same manner--if the stream is already positioned at the end of
jaroslav@601: * data written by the corresponding writeExternal method, object reads will
jaroslav@601: * throw OptionalDataExceptions with eof set to true, bytewise reads will
jaroslav@601: * return -1, and primitive reads will throw EOFExceptions. Note that this
jaroslav@601: * behavior does not hold for streams written with the old
jaroslav@601: * ObjectStreamConstants.PROTOCOL_VERSION_1
protocol, in which the
jaroslav@601: * end of data written by writeExternal methods is not demarcated, and hence
jaroslav@601: * cannot be detected.
jaroslav@601: *
jaroslav@601: *
The readObjectNoData method is responsible for initializing the state of jaroslav@601: * the object for its particular class in the event that the serialization jaroslav@601: * stream does not list the given class as a superclass of the object being jaroslav@601: * deserialized. This may occur in cases where the receiving party uses a jaroslav@601: * different version of the deserialized instance's class than the sending jaroslav@601: * party, and the receiver's version extends classes that are not extended by jaroslav@601: * the sender's version. This may also occur if the serialization stream has jaroslav@601: * been tampered; hence, readObjectNoData is useful for initializing jaroslav@601: * deserialized objects properly despite a "hostile" or incomplete source jaroslav@601: * stream. jaroslav@601: * jaroslav@601: *
Serialization does not read or assign values to the fields of any object jaroslav@601: * that does not implement the java.io.Serializable interface. Subclasses of jaroslav@601: * Objects that are not serializable can be serializable. In this case the jaroslav@601: * non-serializable class must have a no-arg constructor to allow its fields to jaroslav@601: * be initialized. In this case it is the responsibility of the subclass to jaroslav@601: * save and restore the state of the non-serializable class. It is frequently jaroslav@601: * the case that the fields of that class are accessible (public, package, or jaroslav@601: * protected) or that there are get and set methods that can be used to restore jaroslav@601: * the state. jaroslav@601: * jaroslav@601: *
Any exception that occurs while deserializing an object will be caught by jaroslav@601: * the ObjectInputStream and abort the reading process. jaroslav@601: * jaroslav@601: *
Implementing the Externalizable interface allows the object to assume jaroslav@601: * complete control over the contents and format of the object's serialized jaroslav@601: * form. The methods of the Externalizable interface, writeExternal and jaroslav@601: * readExternal, are called to save and restore the objects state. When jaroslav@601: * implemented by a class they can write and read their own state using all of jaroslav@601: * the methods of ObjectOutput and ObjectInput. It is the responsibility of jaroslav@601: * the objects to handle any versioning that occurs. jaroslav@601: * jaroslav@601: *
Enum constants are deserialized differently than ordinary serializable or
jaroslav@601: * externalizable objects. The serialized form of an enum constant consists
jaroslav@601: * solely of its name; field values of the constant are not transmitted. To
jaroslav@601: * deserialize an enum constant, ObjectInputStream reads the constant name from
jaroslav@601: * the stream; the deserialized constant is then obtained by calling the static
jaroslav@601: * method If a security manager is installed, this constructor will check for
jaroslav@601: * the "enableSubclassImplementation" SerializablePermission when invoked
jaroslav@601: * directly or indirectly by the constructor of a subclass which overrides
jaroslav@601: * the ObjectInputStream.readFields or ObjectInputStream.readUnshared
jaroslav@601: * methods.
jaroslav@601: *
jaroslav@601: * @param in input stream to read from
jaroslav@601: * @throws StreamCorruptedException if the stream header is incorrect
jaroslav@601: * @throws IOException if an I/O error occurs while reading stream header
jaroslav@601: * @throws SecurityException if untrusted subclass illegally overrides
jaroslav@601: * security-sensitive methods
jaroslav@601: * @throws NullPointerException if If there is a security manager installed, this method first calls the
jaroslav@601: * security manager's The root object is completely restored when all of its fields and the
jaroslav@601: * objects it references are completely restored. At this point the object
jaroslav@601: * validation callbacks are executed in order based on their registered
jaroslav@601: * priorities. The callbacks are registered by objects (in the readObject
jaroslav@601: * special methods) as they are individually restored.
jaroslav@601: *
jaroslav@601: * Exceptions are thrown for problems with the InputStream and for
jaroslav@601: * classes that should not be deserialized. All exceptions are fatal to
jaroslav@601: * the InputStream and leave it in an indeterminate state; it is up to the
jaroslav@601: * caller to ignore or recover the stream state.
jaroslav@601: *
jaroslav@601: * @throws ClassNotFoundException Class of a serialized object cannot be
jaroslav@601: * found.
jaroslav@601: * @throws InvalidClassException Something is wrong with a class used by
jaroslav@601: * serialization.
jaroslav@601: * @throws StreamCorruptedException Control information in the
jaroslav@601: * stream is inconsistent.
jaroslav@601: * @throws OptionalDataException Primitive data was found in the
jaroslav@601: * stream instead of objects.
jaroslav@601: * @throws IOException Any of the usual Input/Output related exceptions.
jaroslav@601: */
jaroslav@601: public final Object readObject()
jaroslav@601: throws IOException, ClassNotFoundException
jaroslav@601: {
jaroslav@601: if (enableOverride) {
jaroslav@601: return readObjectOverride();
jaroslav@601: }
jaroslav@601:
jaroslav@601: // if nested read, passHandle contains handle of enclosing object
jaroslav@601: int outerHandle = passHandle;
jaroslav@601: try {
jaroslav@601: Object obj = readObject0(false);
jaroslav@601: handles.markDependency(outerHandle, passHandle);
jaroslav@601: ClassNotFoundException ex = handles.lookupException(passHandle);
jaroslav@601: if (ex != null) {
jaroslav@601: throw ex;
jaroslav@601: }
jaroslav@601: if (depth == 0) {
jaroslav@601: vlist.doCallbacks();
jaroslav@601: }
jaroslav@601: return obj;
jaroslav@601: } finally {
jaroslav@601: passHandle = outerHandle;
jaroslav@601: if (closed && depth == 0) {
jaroslav@601: clear();
jaroslav@601: }
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * This method is called by trusted subclasses of ObjectOutputStream that
jaroslav@601: * constructed ObjectOutputStream using the protected no-arg constructor.
jaroslav@601: * The subclass is expected to provide an override method with the modifier
jaroslav@601: * "final".
jaroslav@601: *
jaroslav@601: * @return the Object read from the stream.
jaroslav@601: * @throws ClassNotFoundException Class definition of a serialized object
jaroslav@601: * cannot be found.
jaroslav@601: * @throws OptionalDataException Primitive data was found in the stream
jaroslav@601: * instead of objects.
jaroslav@601: * @throws IOException if I/O errors occurred while reading from the
jaroslav@601: * underlying stream
jaroslav@601: * @see #ObjectInputStream()
jaroslav@601: * @see #readObject()
jaroslav@601: * @since 1.2
jaroslav@601: */
jaroslav@601: protected Object readObjectOverride()
jaroslav@601: throws IOException, ClassNotFoundException
jaroslav@601: {
jaroslav@601: return null;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads an "unshared" object from the ObjectInputStream. This method is
jaroslav@601: * identical to readObject, except that it prevents subsequent calls to
jaroslav@601: * readObject and readUnshared from returning additional references to the
jaroslav@601: * deserialized instance obtained via this call. Specifically:
jaroslav@601: * ObjectInputStream subclasses which override this method can only be
jaroslav@601: * constructed in security contexts possessing the
jaroslav@601: * "enableSubclassImplementation" SerializablePermission; any attempt to
jaroslav@601: * instantiate such a subclass without this permission will cause a
jaroslav@601: * SecurityException to be thrown.
jaroslav@601: *
jaroslav@601: * @return reference to deserialized object
jaroslav@601: * @throws ClassNotFoundException if class of an object to deserialize
jaroslav@601: * cannot be found
jaroslav@601: * @throws StreamCorruptedException if control information in the stream
jaroslav@601: * is inconsistent
jaroslav@601: * @throws ObjectStreamException if object to deserialize has already
jaroslav@601: * appeared in stream
jaroslav@601: * @throws OptionalDataException if primitive data is next in stream
jaroslav@601: * @throws IOException if an I/O error occurs during deserialization
jaroslav@601: * @since 1.4
jaroslav@601: */
jaroslav@601: public Object readUnshared() throws IOException, ClassNotFoundException {
jaroslav@601: // if nested read, passHandle contains handle of enclosing object
jaroslav@601: int outerHandle = passHandle;
jaroslav@601: try {
jaroslav@601: Object obj = readObject0(true);
jaroslav@601: handles.markDependency(outerHandle, passHandle);
jaroslav@601: ClassNotFoundException ex = handles.lookupException(passHandle);
jaroslav@601: if (ex != null) {
jaroslav@601: throw ex;
jaroslav@601: }
jaroslav@601: if (depth == 0) {
jaroslav@601: vlist.doCallbacks();
jaroslav@601: }
jaroslav@601: return obj;
jaroslav@601: } finally {
jaroslav@601: passHandle = outerHandle;
jaroslav@601: if (closed && depth == 0) {
jaroslav@601: clear();
jaroslav@601: }
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Read the non-static and non-transient fields of the current class from
jaroslav@601: * this stream. This may only be called from the readObject method of the
jaroslav@601: * class being deserialized. It will throw the NotActiveException if it is
jaroslav@601: * called otherwise.
jaroslav@601: *
jaroslav@601: * @throws ClassNotFoundException if the class of a serialized object
jaroslav@601: * could not be found.
jaroslav@601: * @throws IOException if an I/O error occurs.
jaroslav@601: * @throws NotActiveException if the stream is not currently reading
jaroslav@601: * objects.
jaroslav@601: */
jaroslav@601: public void defaultReadObject()
jaroslav@601: throws IOException, ClassNotFoundException
jaroslav@601: {
jaroslav@601: if (curContext == null) {
jaroslav@601: throw new NotActiveException("not in call to readObject");
jaroslav@601: }
jaroslav@601: Object curObj = curContext.getObj();
jaroslav@601: ObjectStreamClass curDesc = curContext.getDesc();
jaroslav@601: bin.setBlockDataMode(false);
jaroslav@601: defaultReadFields(curObj, curDesc);
jaroslav@601: bin.setBlockDataMode(true);
jaroslav@601: if (!curDesc.hasWriteObjectData()) {
jaroslav@601: /*
jaroslav@601: * Fix for 4360508: since stream does not contain terminating
jaroslav@601: * TC_ENDBLOCKDATA tag, set flag so that reading code elsewhere
jaroslav@601: * knows to simulate end-of-custom-data behavior.
jaroslav@601: */
jaroslav@601: defaultDataEnd = true;
jaroslav@601: }
jaroslav@601: ClassNotFoundException ex = handles.lookupException(passHandle);
jaroslav@601: if (ex != null) {
jaroslav@601: throw ex;
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads the persistent fields from the stream and makes them available by
jaroslav@601: * name.
jaroslav@601: *
jaroslav@601: * @return the The corresponding method in The default implementation of this method in
jaroslav@601: * This method is called exactly once for each unique proxy class
jaroslav@601: * descriptor in the stream.
jaroslav@601: *
jaroslav@601: * The corresponding method in The default implementation of this method in
jaroslav@601: * This method is called after an object has been read but before it is
jaroslav@601: * returned from readObject. The default resolveObject method just returns
jaroslav@601: * the same object.
jaroslav@601: *
jaroslav@601: * When a subclass is replacing objects it must insure that the
jaroslav@601: * substituted object is compatible with every field where the reference
jaroslav@601: * will be stored. Objects whose type is not a subclass of the type of the
jaroslav@601: * field or array element abort the serialization by raising an exception
jaroslav@601: * and the object is not be stored.
jaroslav@601: *
jaroslav@601: * This method is called only once when each object is first
jaroslav@601: * encountered. All subsequent references to the object will be redirected
jaroslav@601: * to the new object.
jaroslav@601: *
jaroslav@601: * @param obj object to be substituted
jaroslav@601: * @return the substituted object
jaroslav@601: * @throws IOException Any of the usual Input/Output exceptions.
jaroslav@601: */
jaroslav@601: protected Object resolveObject(Object obj) throws IOException {
jaroslav@601: return obj;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Enable the stream to allow objects read from the stream to be replaced.
jaroslav@601: * When enabled, the resolveObject method is called for every object being
jaroslav@601: * deserialized.
jaroslav@601: *
jaroslav@601: * If enable is true, and there is a security manager installed,
jaroslav@601: * this method first calls the security manager's
jaroslav@601: * General use of the table is as follows: during deserialization, a
jaroslav@601: * given object is first assigned a handle by calling the assign method.
jaroslav@601: * This method leaves the assigned handle in an "open" state, wherein
jaroslav@601: * dependencies on the exception status of other handles can be registered
jaroslav@601: * by calling the markDependency method, or an exception can be directly
jaroslav@601: * associated with the handle by calling markException. When a handle is
jaroslav@601: * tagged with an exception, the HandleTable assumes responsibility for
jaroslav@601: * propagating the exception to any other objects which depend
jaroslav@601: * (transitively) on the exception-tagged object.
jaroslav@601: *
jaroslav@601: * Once all exception information/dependencies for the handle have been
jaroslav@601: * registered, the handle should be "closed" by calling the finish method
jaroslav@601: * on it. The act of finishing a handle allows the exception propagation
jaroslav@601: * algorithm to aggressively prune dependency links, lessening the
jaroslav@601: * performance/memory impact of exception tracking.
jaroslav@601: *
jaroslav@601: * Note that the exception propagation algorithm used depends on handles
jaroslav@601: * being assigned/finished in LIFO order; however, for simplicity as well
jaroslav@601: * as memory conservation, it does not enforce this constraint.
jaroslav@601: */
jaroslav@601: // REMIND: add full description of exception propagation algorithm?
jaroslav@601: private static class HandleTable {
jaroslav@601:
jaroslav@601: /* status codes indicating whether object has associated exception */
jaroslav@601: private static final byte STATUS_OK = 1;
jaroslav@601: private static final byte STATUS_UNKNOWN = 2;
jaroslav@601: private static final byte STATUS_EXCEPTION = 3;
jaroslav@601:
jaroslav@601: /** array mapping handle -> object status */
jaroslav@601: byte[] status;
jaroslav@601: /** array mapping handle -> object/exception (depending on status) */
jaroslav@601: Object[] entries;
jaroslav@601: /** array mapping handle -> list of dependent handles (if any) */
jaroslav@601: HandleList[] deps;
jaroslav@601: /** lowest unresolved dependency */
jaroslav@601: int lowDep = -1;
jaroslav@601: /** number of handles in table */
jaroslav@601: int size = 0;
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Creates handle table with the given initial capacity.
jaroslav@601: */
jaroslav@601: HandleTable(int initialCapacity) {
jaroslav@601: status = new byte[initialCapacity];
jaroslav@601: entries = new Object[initialCapacity];
jaroslav@601: deps = new HandleList[initialCapacity];
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Assigns next available handle to given object, and returns assigned
jaroslav@601: * handle. Once object has been completely deserialized (and all
jaroslav@601: * dependencies on other objects identified), the handle should be
jaroslav@601: * "closed" by passing it to finish().
jaroslav@601: */
jaroslav@601: int assign(Object obj) {
jaroslav@601: if (size >= entries.length) {
jaroslav@601: grow();
jaroslav@601: }
jaroslav@601: status[size] = STATUS_UNKNOWN;
jaroslav@601: entries[size] = obj;
jaroslav@601: return size++;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Registers a dependency (in exception status) of one handle on
jaroslav@601: * another. The dependent handle must be "open" (i.e., assigned, but
jaroslav@601: * not finished yet). No action is taken if either dependent or target
jaroslav@601: * handle is NULL_HANDLE.
jaroslav@601: */
jaroslav@601: void markDependency(int dependent, int target) {
jaroslav@601: if (dependent == NULL_HANDLE || target == NULL_HANDLE) {
jaroslav@601: return;
jaroslav@601: }
jaroslav@601: switch (status[dependent]) {
jaroslav@601:
jaroslav@601: case STATUS_UNKNOWN:
jaroslav@601: switch (status[target]) {
jaroslav@601: case STATUS_OK:
jaroslav@601: // ignore dependencies on objs with no exception
jaroslav@601: break;
jaroslav@601:
jaroslav@601: case STATUS_EXCEPTION:
jaroslav@601: // eagerly propagate exception
jaroslav@601: markException(dependent,
jaroslav@601: (ClassNotFoundException) entries[target]);
jaroslav@601: break;
jaroslav@601:
jaroslav@601: case STATUS_UNKNOWN:
jaroslav@601: // add to dependency list of target
jaroslav@601: if (deps[target] == null) {
jaroslav@601: deps[target] = new HandleList();
jaroslav@601: }
jaroslav@601: deps[target].add(dependent);
jaroslav@601:
jaroslav@601: // remember lowest unresolved target seen
jaroslav@601: if (lowDep < 0 || lowDep > target) {
jaroslav@601: lowDep = target;
jaroslav@601: }
jaroslav@601: break;
jaroslav@601:
jaroslav@601: default:
jaroslav@601: throw new InternalError();
jaroslav@601: }
jaroslav@601: break;
jaroslav@601:
jaroslav@601: case STATUS_EXCEPTION:
jaroslav@601: break;
jaroslav@601:
jaroslav@601: default:
jaroslav@601: throw new InternalError();
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Associates a ClassNotFoundException (if one not already associated)
jaroslav@601: * with the currently active handle and propagates it to other
jaroslav@601: * referencing objects as appropriate. The specified handle must be
jaroslav@601: * "open" (i.e., assigned, but not finished yet).
jaroslav@601: */
jaroslav@601: void markException(int handle, ClassNotFoundException ex) {
jaroslav@601: switch (status[handle]) {
jaroslav@601: case STATUS_UNKNOWN:
jaroslav@601: status[handle] = STATUS_EXCEPTION;
jaroslav@601: entries[handle] = ex;
jaroslav@601:
jaroslav@601: // propagate exception to dependents
jaroslav@601: HandleList dlist = deps[handle];
jaroslav@601: if (dlist != null) {
jaroslav@601: int ndeps = dlist.size();
jaroslav@601: for (int i = 0; i < ndeps; i++) {
jaroslav@601: markException(dlist.get(i), ex);
jaroslav@601: }
jaroslav@601: deps[handle] = null;
jaroslav@601: }
jaroslav@601: break;
jaroslav@601:
jaroslav@601: case STATUS_EXCEPTION:
jaroslav@601: break;
jaroslav@601:
jaroslav@601: default:
jaroslav@601: throw new InternalError();
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Marks given handle as finished, meaning that no new dependencies
jaroslav@601: * will be marked for handle. Calls to the assign and finish methods
jaroslav@601: * must occur in LIFO order.
jaroslav@601: */
jaroslav@601: void finish(int handle) {
jaroslav@601: int end;
jaroslav@601: if (lowDep < 0) {
jaroslav@601: // no pending unknowns, only resolve current handle
jaroslav@601: end = handle + 1;
jaroslav@601: } else if (lowDep >= handle) {
jaroslav@601: // pending unknowns now clearable, resolve all upward handles
jaroslav@601: end = size;
jaroslav@601: lowDep = -1;
jaroslav@601: } else {
jaroslav@601: // unresolved backrefs present, can't resolve anything yet
jaroslav@601: return;
jaroslav@601: }
jaroslav@601:
jaroslav@601: // change STATUS_UNKNOWN -> STATUS_OK in selected span of handles
jaroslav@601: for (int i = handle; i < end; i++) {
jaroslav@601: switch (status[i]) {
jaroslav@601: case STATUS_UNKNOWN:
jaroslav@601: status[i] = STATUS_OK;
jaroslav@601: deps[i] = null;
jaroslav@601: break;
jaroslav@601:
jaroslav@601: case STATUS_OK:
jaroslav@601: case STATUS_EXCEPTION:
jaroslav@601: break;
jaroslav@601:
jaroslav@601: default:
jaroslav@601: throw new InternalError();
jaroslav@601: }
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Assigns a new object to the given handle. The object previously
jaroslav@601: * associated with the handle is forgotten. This method has no effect
jaroslav@601: * if the given handle already has an exception associated with it.
jaroslav@601: * This method may be called at any time after the handle is assigned.
jaroslav@601: */
jaroslav@601: void setObject(int handle, Object obj) {
jaroslav@601: switch (status[handle]) {
jaroslav@601: case STATUS_UNKNOWN:
jaroslav@601: case STATUS_OK:
jaroslav@601: entries[handle] = obj;
jaroslav@601: break;
jaroslav@601:
jaroslav@601: case STATUS_EXCEPTION:
jaroslav@601: break;
jaroslav@601:
jaroslav@601: default:
jaroslav@601: throw new InternalError();
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Looks up and returns object associated with the given handle.
jaroslav@601: * Returns null if the given handle is NULL_HANDLE, or if it has an
jaroslav@601: * associated ClassNotFoundException.
jaroslav@601: */
jaroslav@601: Object lookupObject(int handle) {
jaroslav@601: return (handle != NULL_HANDLE &&
jaroslav@601: status[handle] != STATUS_EXCEPTION) ?
jaroslav@601: entries[handle] : null;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Looks up and returns ClassNotFoundException associated with the
jaroslav@601: * given handle. Returns null if the given handle is NULL_HANDLE, or
jaroslav@601: * if there is no ClassNotFoundException associated with the handle.
jaroslav@601: */
jaroslav@601: ClassNotFoundException lookupException(int handle) {
jaroslav@601: return (handle != NULL_HANDLE &&
jaroslav@601: status[handle] == STATUS_EXCEPTION) ?
jaroslav@601: (ClassNotFoundException) entries[handle] : null;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Resets table to its initial state.
jaroslav@601: */
jaroslav@601: void clear() {
jaroslav@601: Arrays.fill(status, 0, size, (byte) 0);
jaroslav@601: Arrays.fill(entries, 0, size, null);
jaroslav@601: Arrays.fill(deps, 0, size, null);
jaroslav@601: lowDep = -1;
jaroslav@601: size = 0;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Returns number of handles registered in table.
jaroslav@601: */
jaroslav@601: int size() {
jaroslav@601: return size;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Expands capacity of internal arrays.
jaroslav@601: */
jaroslav@601: private void grow() {
jaroslav@601: int newCapacity = (entries.length << 1) + 1;
jaroslav@601:
jaroslav@601: byte[] newStatus = new byte[newCapacity];
jaroslav@601: Object[] newEntries = new Object[newCapacity];
jaroslav@601: HandleList[] newDeps = new HandleList[newCapacity];
jaroslav@601:
jaroslav@601: System.arraycopy(status, 0, newStatus, 0, size);
jaroslav@601: System.arraycopy(entries, 0, newEntries, 0, size);
jaroslav@601: System.arraycopy(deps, 0, newDeps, 0, size);
jaroslav@601:
jaroslav@601: status = newStatus;
jaroslav@601: entries = newEntries;
jaroslav@601: deps = newDeps;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Simple growable list of (integer) handles.
jaroslav@601: */
jaroslav@601: private static class HandleList {
jaroslav@601: private int[] list = new int[4];
jaroslav@601: private int size = 0;
jaroslav@601:
jaroslav@601: public HandleList() {
jaroslav@601: }
jaroslav@601:
jaroslav@601: public void add(int handle) {
jaroslav@601: if (size >= list.length) {
jaroslav@601: int[] newList = new int[list.length << 1];
jaroslav@601: System.arraycopy(list, 0, newList, 0, list.length);
jaroslav@601: list = newList;
jaroslav@601: }
jaroslav@601: list[size++] = handle;
jaroslav@601: }
jaroslav@601:
jaroslav@601: public int get(int index) {
jaroslav@601: if (index >= size) {
jaroslav@601: throw new ArrayIndexOutOfBoundsException();
jaroslav@601: }
jaroslav@601: return list[index];
jaroslav@601: }
jaroslav@601:
jaroslav@601: public int size() {
jaroslav@601: return size;
jaroslav@601: }
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Method for cloning arrays in case of using unsharing reading
jaroslav@601: */
jaroslav@601: private static Object cloneArray(Object array) {
jaroslav@601: if (array instanceof Object[]) {
jaroslav@601: return ((Object[]) array).clone();
jaroslav@601: } else if (array instanceof boolean[]) {
jaroslav@601: return ((boolean[]) array).clone();
jaroslav@601: } else if (array instanceof byte[]) {
jaroslav@601: return ((byte[]) array).clone();
jaroslav@601: } else if (array instanceof char[]) {
jaroslav@601: return ((char[]) array).clone();
jaroslav@601: } else if (array instanceof double[]) {
jaroslav@601: return ((double[]) array).clone();
jaroslav@601: } else if (array instanceof float[]) {
jaroslav@601: return ((float[]) array).clone();
jaroslav@601: } else if (array instanceof int[]) {
jaroslav@601: return ((int[]) array).clone();
jaroslav@601: } else if (array instanceof long[]) {
jaroslav@601: return ((long[]) array).clone();
jaroslav@601: } else if (array instanceof short[]) {
jaroslav@601: return ((short[]) array).clone();
jaroslav@601: } else {
jaroslav@601: throw new AssertionError();
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: }
Enum.valueOf(Class, String)
with the enum constant's
jaroslav@601: * base type and the received constant name as arguments. Like other
jaroslav@601: * serializable or externalizable objects, enum constants can function as the
jaroslav@601: * targets of back references appearing subsequently in the serialization
jaroslav@601: * stream. The process by which enum constants are deserialized cannot be
jaroslav@601: * customized: any class-specific readObject, readObjectNoData, and readResolve
jaroslav@601: * methods defined by enum types are ignored during deserialization.
jaroslav@601: * Similarly, any serialPersistentFields or serialVersionUID field declarations
jaroslav@601: * are also ignored--all enum types have a fixed serialVersionUID of 0L.
jaroslav@601: *
jaroslav@601: * @author Mike Warres
jaroslav@601: * @author Roger Riggs
jaroslav@601: * @see java.io.DataInput
jaroslav@601: * @see java.io.ObjectOutputStream
jaroslav@601: * @see java.io.Serializable
jaroslav@601: * @see Object Serialization Specification, Section 3, Object Input Classes
jaroslav@601: * @since JDK1.1
jaroslav@601: */
jaroslav@601: public class ObjectInputStream
jaroslav@601: extends InputStream implements ObjectInput, ObjectStreamConstants
jaroslav@601: {
jaroslav@601: /** handle value representing null */
jaroslav@601: private static final int NULL_HANDLE = -1;
jaroslav@601:
jaroslav@601: /** marker for unshared objects in internal handle table */
jaroslav@601: private static final Object unsharedMarker = new Object();
jaroslav@601:
jaroslav@601: /** table mapping primitive type names to corresponding class objects */
jaroslav@601: private static final HashMapin
is null
jaroslav@601: * @see ObjectInputStream#ObjectInputStream()
jaroslav@601: * @see ObjectInputStream#readFields()
jaroslav@601: * @see ObjectOutputStream#ObjectOutputStream(OutputStream)
jaroslav@601: */
jaroslav@601: public ObjectInputStream(InputStream in) throws IOException {
jaroslav@601: verifySubclass();
jaroslav@601: bin = new BlockDataInputStream(in);
jaroslav@601: handles = new HandleTable(10);
jaroslav@601: vlist = new ValidationList();
jaroslav@601: enableOverride = false;
jaroslav@601: readStreamHeader();
jaroslav@601: bin.setBlockDataMode(true);
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Provide a way for subclasses that are completely reimplementing
jaroslav@601: * ObjectInputStream to not have to allocate private data just used by this
jaroslav@601: * implementation of ObjectInputStream.
jaroslav@601: *
jaroslav@601: * checkPermission
method with the
jaroslav@601: * SerializablePermission("enableSubclassImplementation")
jaroslav@601: * permission to ensure it's ok to enable subclassing.
jaroslav@601: *
jaroslav@601: * @throws SecurityException if a security manager exists and its
jaroslav@601: * checkPermission
method denies enabling
jaroslav@601: * subclassing.
jaroslav@601: * @see SecurityManager#checkPermission
jaroslav@601: * @see java.io.SerializablePermission
jaroslav@601: */
jaroslav@601: protected ObjectInputStream() throws IOException, SecurityException {
jaroslav@601: SecurityManager sm = System.getSecurityManager();
jaroslav@601: if (sm != null) {
jaroslav@601: sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
jaroslav@601: }
jaroslav@601: bin = null;
jaroslav@601: handles = null;
jaroslav@601: vlist = null;
jaroslav@601: enableOverride = true;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Read an object from the ObjectInputStream. The class of the object, the
jaroslav@601: * signature of the class, and the values of the non-transient and
jaroslav@601: * non-static fields of the class and all of its supertypes are read.
jaroslav@601: * Default deserializing for a class can be overriden using the writeObject
jaroslav@601: * and readObject methods. Objects referenced by this object are read
jaroslav@601: * transitively so that a complete equivalent graph of objects is
jaroslav@601: * reconstructed by readObject.
jaroslav@601: *
jaroslav@601: *
jaroslav@601: *
jaroslav@601: * Deserializing an object via readUnshared invalidates the stream handle
jaroslav@601: * associated with the returned object. Note that this in itself does not
jaroslav@601: * always guarantee that the reference returned by readUnshared is unique;
jaroslav@601: * the deserialized object may define a readResolve method which returns an
jaroslav@601: * object visible to other parties, or readUnshared may return a Class
jaroslav@601: * object or enum constant obtainable elsewhere in the stream or through
jaroslav@601: * external means. If the deserialized object defines a readResolve method
jaroslav@601: * and the invocation of that method returns an array, then readUnshared
jaroslav@601: * returns a shallow clone of that array; this guarantees that the returned
jaroslav@601: * array object is unique and cannot be obtained a second time from an
jaroslav@601: * invocation of readObject or readUnshared on the ObjectInputStream,
jaroslav@601: * even if the underlying data stream has been manipulated.
jaroslav@601: *
jaroslav@601: * GetField
object representing the persistent
jaroslav@601: * fields of the object being deserialized
jaroslav@601: * @throws ClassNotFoundException if the class of a serialized object
jaroslav@601: * could not be found.
jaroslav@601: * @throws IOException if an I/O error occurs.
jaroslav@601: * @throws NotActiveException if the stream is not currently reading
jaroslav@601: * objects.
jaroslav@601: * @since 1.2
jaroslav@601: */
jaroslav@601: public ObjectInputStream.GetField readFields()
jaroslav@601: throws IOException, ClassNotFoundException
jaroslav@601: {
jaroslav@601: if (curContext == null) {
jaroslav@601: throw new NotActiveException("not in call to readObject");
jaroslav@601: }
jaroslav@601: Object curObj = curContext.getObj();
jaroslav@601: ObjectStreamClass curDesc = curContext.getDesc();
jaroslav@601: bin.setBlockDataMode(false);
jaroslav@601: GetFieldImpl getField = new GetFieldImpl(curDesc);
jaroslav@601: getField.readFields();
jaroslav@601: bin.setBlockDataMode(true);
jaroslav@601: if (!curDesc.hasWriteObjectData()) {
jaroslav@601: /*
jaroslav@601: * Fix for 4360508: since stream does not contain terminating
jaroslav@601: * TC_ENDBLOCKDATA tag, set flag so that reading code elsewhere
jaroslav@601: * knows to simulate end-of-custom-data behavior.
jaroslav@601: */
jaroslav@601: defaultDataEnd = true;
jaroslav@601: }
jaroslav@601:
jaroslav@601: return getField;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Register an object to be validated before the graph is returned. While
jaroslav@601: * similar to resolveObject these validations are called after the entire
jaroslav@601: * graph has been reconstituted. Typically, a readObject method will
jaroslav@601: * register the object with the stream so that when all of the objects are
jaroslav@601: * restored a final set of validations can be performed.
jaroslav@601: *
jaroslav@601: * @param obj the object to receive the validation callback.
jaroslav@601: * @param prio controls the order of callbacks;zero is a good default.
jaroslav@601: * Use higher numbers to be called back earlier, lower numbers for
jaroslav@601: * later callbacks. Within a priority, callbacks are processed in
jaroslav@601: * no particular order.
jaroslav@601: * @throws NotActiveException The stream is not currently reading objects
jaroslav@601: * so it is invalid to register a callback.
jaroslav@601: * @throws InvalidObjectException The validation object is null.
jaroslav@601: */
jaroslav@601: public void registerValidation(ObjectInputValidation obj, int prio)
jaroslav@601: throws NotActiveException, InvalidObjectException
jaroslav@601: {
jaroslav@601: if (depth == 0) {
jaroslav@601: throw new NotActiveException("stream inactive");
jaroslav@601: }
jaroslav@601: vlist.register(obj, prio);
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Load the local class equivalent of the specified stream class
jaroslav@601: * description. Subclasses may implement this method to allow classes to
jaroslav@601: * be fetched from an alternate source.
jaroslav@601: *
jaroslav@601: * ObjectOutputStream
is
jaroslav@601: * annotateClass
. This method will be invoked only once for
jaroslav@601: * each unique class in the stream. This method can be implemented by
jaroslav@601: * subclasses to use an alternate loading mechanism but must return a
jaroslav@601: * Class
object. Once returned, if the class is not an array
jaroslav@601: * class, its serialVersionUID is compared to the serialVersionUID of the
jaroslav@601: * serialized class, and if there is a mismatch, the deserialization fails
jaroslav@601: * and an {@link InvalidClassException} is thrown.
jaroslav@601: *
jaroslav@601: * ObjectInputStream
returns the result of calling
jaroslav@601: *
jaroslav@601: * Class.forName(desc.getName(), false, loader)
jaroslav@601: *
jaroslav@601: * where loader
is determined as follows: if there is a
jaroslav@601: * method on the current thread's stack whose declaring class was
jaroslav@601: * defined by a user-defined class loader (and was not a generated to
jaroslav@601: * implement reflective invocations), then loader
is class
jaroslav@601: * loader corresponding to the closest such method to the currently
jaroslav@601: * executing frame; otherwise, loader
is
jaroslav@601: * null
. If this call results in a
jaroslav@601: * ClassNotFoundException
and the name of the passed
jaroslav@601: * ObjectStreamClass
instance is the Java language keyword
jaroslav@601: * for a primitive type or void, then the Class
object
jaroslav@601: * representing that primitive type or void will be returned
jaroslav@601: * (e.g., an ObjectStreamClass
with the name
jaroslav@601: * "int"
will be resolved to Integer.TYPE
).
jaroslav@601: * Otherwise, the ClassNotFoundException
will be thrown to
jaroslav@601: * the caller of this method.
jaroslav@601: *
jaroslav@601: * @param desc an instance of class ObjectStreamClass
jaroslav@601: * @return a Class
object corresponding to desc
jaroslav@601: * @throws IOException any of the usual Input/Output exceptions.
jaroslav@601: * @throws ClassNotFoundException if class of a serialized object cannot
jaroslav@601: * be found.
jaroslav@601: */
jaroslav@601: protected Class> resolveClass(ObjectStreamClass desc)
jaroslav@601: throws IOException, ClassNotFoundException
jaroslav@601: {
jaroslav@601: String name = desc.getName();
jaroslav@601: try {
jaroslav@601: return Class.forName(name, false, latestUserDefinedLoader());
jaroslav@601: } catch (ClassNotFoundException ex) {
jaroslav@601: Class> cl = primClasses.get(name);
jaroslav@601: if (cl != null) {
jaroslav@601: return cl;
jaroslav@601: } else {
jaroslav@601: throw ex;
jaroslav@601: }
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Returns a proxy class that implements the interfaces named in a proxy
jaroslav@601: * class descriptor; subclasses may implement this method to read custom
jaroslav@601: * data from the stream along with the descriptors for dynamic proxy
jaroslav@601: * classes, allowing them to use an alternate loading mechanism for the
jaroslav@601: * interfaces and the proxy class.
jaroslav@601: *
jaroslav@601: * ObjectOutputStream
is
jaroslav@601: * annotateProxyClass
. For a given subclass of
jaroslav@601: * ObjectInputStream
that overrides this method, the
jaroslav@601: * annotateProxyClass
method in the corresponding subclass of
jaroslav@601: * ObjectOutputStream
must write any data or objects read by
jaroslav@601: * this method.
jaroslav@601: *
jaroslav@601: * ObjectInputStream
returns the result of calling
jaroslav@601: * Proxy.getProxyClass
with the list of Class
jaroslav@601: * objects for the interfaces that are named in the interfaces
jaroslav@601: * parameter. The Class
object for each interface name
jaroslav@601: * i
is the value returned by calling
jaroslav@601: *
jaroslav@601: * Class.forName(i, false, loader)
jaroslav@601: *
jaroslav@601: * where loader
is that of the first non-null
jaroslav@601: * class loader up the execution stack, or null
if no
jaroslav@601: * non-null
class loaders are on the stack (the same class
jaroslav@601: * loader choice used by the resolveClass
method). Unless any
jaroslav@601: * of the resolved interfaces are non-public, this same value of
jaroslav@601: * loader
is also the class loader passed to
jaroslav@601: * Proxy.getProxyClass
; if non-public interfaces are present,
jaroslav@601: * their class loader is passed instead (if more than one non-public
jaroslav@601: * interface class loader is encountered, an
jaroslav@601: * IllegalAccessError
is thrown).
jaroslav@601: * If Proxy.getProxyClass
throws an
jaroslav@601: * IllegalArgumentException
, resolveProxyClass
jaroslav@601: * will throw a ClassNotFoundException
containing the
jaroslav@601: * IllegalArgumentException
.
jaroslav@601: *
jaroslav@601: * @param interfaces the list of interface names that were
jaroslav@601: * deserialized in the proxy class descriptor
jaroslav@601: * @return a proxy class for the specified interfaces
jaroslav@601: * @throws IOException any exception thrown by the underlying
jaroslav@601: * InputStream
jaroslav@601: * @throws ClassNotFoundException if the proxy class or any of the
jaroslav@601: * named interfaces could not be found
jaroslav@601: * @see ObjectOutputStream#annotateProxyClass(Class)
jaroslav@601: * @since 1.3
jaroslav@601: */
jaroslav@601: protected Class> resolveProxyClass(String[] interfaces)
jaroslav@601: throws IOException, ClassNotFoundException
jaroslav@601: {
jaroslav@601: ClassLoader latestLoader = latestUserDefinedLoader();
jaroslav@601: ClassLoader nonPublicLoader = null;
jaroslav@601: boolean hasNonPublicInterface = false;
jaroslav@601:
jaroslav@601: // define proxy in class loader of non-public interface(s), if any
jaroslav@601: Class[] classObjs = new Class[interfaces.length];
jaroslav@601: for (int i = 0; i < interfaces.length; i++) {
jaroslav@601: Class cl = Class.forName(interfaces[i], false, latestLoader);
jaroslav@601: if ((cl.getModifiers() & Modifier.PUBLIC) == 0) {
jaroslav@601: if (hasNonPublicInterface) {
jaroslav@601: if (nonPublicLoader != cl.getClassLoader()) {
jaroslav@601: throw new IllegalAccessError(
jaroslav@601: "conflicting non-public interface class loaders");
jaroslav@601: }
jaroslav@601: } else {
jaroslav@601: nonPublicLoader = cl.getClassLoader();
jaroslav@601: hasNonPublicInterface = true;
jaroslav@601: }
jaroslav@601: }
jaroslav@601: classObjs[i] = cl;
jaroslav@601: }
jaroslav@601: try {
jaroslav@601: return Proxy.getProxyClass(
jaroslav@601: hasNonPublicInterface ? nonPublicLoader : latestLoader,
jaroslav@601: classObjs);
jaroslav@601: } catch (IllegalArgumentException e) {
jaroslav@601: throw new ClassNotFoundException(null, e);
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * This method will allow trusted subclasses of ObjectInputStream to
jaroslav@601: * substitute one object for another during deserialization. Replacing
jaroslav@601: * objects is disabled until enableResolveObject is called. The
jaroslav@601: * enableResolveObject method checks that the stream requesting to resolve
jaroslav@601: * object can be trusted. Every reference to serializable objects is passed
jaroslav@601: * to resolveObject. To insure that the private state of objects is not
jaroslav@601: * unintentionally exposed only trusted streams may use resolveObject.
jaroslav@601: *
jaroslav@601: * checkPermission
method with the
jaroslav@601: * SerializablePermission("enableSubstitution")
permission to
jaroslav@601: * ensure it's ok to enable the stream to allow objects read from the
jaroslav@601: * stream to be replaced.
jaroslav@601: *
jaroslav@601: * @param enable true for enabling use of resolveObject
for
jaroslav@601: * every object being deserialized
jaroslav@601: * @return the previous setting before this method was invoked
jaroslav@601: * @throws SecurityException if a security manager exists and its
jaroslav@601: * checkPermission
method denies enabling the stream
jaroslav@601: * to allow objects read from the stream to be replaced.
jaroslav@601: * @see SecurityManager#checkPermission
jaroslav@601: * @see java.io.SerializablePermission
jaroslav@601: */
jaroslav@601: protected boolean enableResolveObject(boolean enable)
jaroslav@601: throws SecurityException
jaroslav@601: {
jaroslav@601: if (enable == enableResolve) {
jaroslav@601: return enable;
jaroslav@601: }
jaroslav@601: if (enable) {
jaroslav@601: SecurityManager sm = System.getSecurityManager();
jaroslav@601: if (sm != null) {
jaroslav@601: sm.checkPermission(SUBSTITUTION_PERMISSION);
jaroslav@601: }
jaroslav@601: }
jaroslav@601: enableResolve = enable;
jaroslav@601: return !enableResolve;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * The readStreamHeader method is provided to allow subclasses to read and
jaroslav@601: * verify their own stream headers. It reads and verifies the magic number
jaroslav@601: * and version number.
jaroslav@601: *
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws StreamCorruptedException if control information in the stream
jaroslav@601: * is inconsistent
jaroslav@601: */
jaroslav@601: protected void readStreamHeader()
jaroslav@601: throws IOException, StreamCorruptedException
jaroslav@601: {
jaroslav@601: short s0 = bin.readShort();
jaroslav@601: short s1 = bin.readShort();
jaroslav@601: if (s0 != STREAM_MAGIC || s1 != STREAM_VERSION) {
jaroslav@601: throw new StreamCorruptedException(
jaroslav@601: String.format("invalid stream header: %04X%04X", s0, s1));
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Read a class descriptor from the serialization stream. This method is
jaroslav@601: * called when the ObjectInputStream expects a class descriptor as the next
jaroslav@601: * item in the serialization stream. Subclasses of ObjectInputStream may
jaroslav@601: * override this method to read in class descriptors that have been written
jaroslav@601: * in non-standard formats (by subclasses of ObjectOutputStream which have
jaroslav@601: * overridden the writeClassDescriptor
method). By default,
jaroslav@601: * this method reads class descriptors according to the format defined in
jaroslav@601: * the Object Serialization specification.
jaroslav@601: *
jaroslav@601: * @return the class descriptor read
jaroslav@601: * @throws IOException If an I/O error has occurred.
jaroslav@601: * @throws ClassNotFoundException If the Class of a serialized object used
jaroslav@601: * in the class descriptor representation cannot be found
jaroslav@601: * @see java.io.ObjectOutputStream#writeClassDescriptor(java.io.ObjectStreamClass)
jaroslav@601: * @since 1.3
jaroslav@601: */
jaroslav@601: protected ObjectStreamClass readClassDescriptor()
jaroslav@601: throws IOException, ClassNotFoundException
jaroslav@601: {
jaroslav@601: ObjectStreamClass desc = new ObjectStreamClass();
jaroslav@601: desc.readNonProxy(this);
jaroslav@601: return desc;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads a byte of data. This method will block if no input is available.
jaroslav@601: *
jaroslav@601: * @return the byte read, or -1 if the end of the stream is reached.
jaroslav@601: * @throws IOException If an I/O error has occurred.
jaroslav@601: */
jaroslav@601: public int read() throws IOException {
jaroslav@601: return bin.read();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads into an array of bytes. This method will block until some input
jaroslav@601: * is available. Consider using java.io.DataInputStream.readFully to read
jaroslav@601: * exactly 'length' bytes.
jaroslav@601: *
jaroslav@601: * @param buf the buffer into which the data is read
jaroslav@601: * @param off the start offset of the data
jaroslav@601: * @param len the maximum number of bytes read
jaroslav@601: * @return the actual number of bytes read, -1 is returned when the end of
jaroslav@601: * the stream is reached.
jaroslav@601: * @throws IOException If an I/O error has occurred.
jaroslav@601: * @see java.io.DataInputStream#readFully(byte[],int,int)
jaroslav@601: */
jaroslav@601: public int read(byte[] buf, int off, int len) throws IOException {
jaroslav@601: if (buf == null) {
jaroslav@601: throw new NullPointerException();
jaroslav@601: }
jaroslav@601: int endoff = off + len;
jaroslav@601: if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
jaroslav@601: throw new IndexOutOfBoundsException();
jaroslav@601: }
jaroslav@601: return bin.read(buf, off, len, false);
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Returns the number of bytes that can be read without blocking.
jaroslav@601: *
jaroslav@601: * @return the number of available bytes.
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: */
jaroslav@601: public int available() throws IOException {
jaroslav@601: return bin.available();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Closes the input stream. Must be called to release any resources
jaroslav@601: * associated with the stream.
jaroslav@601: *
jaroslav@601: * @throws IOException If an I/O error has occurred.
jaroslav@601: */
jaroslav@601: public void close() throws IOException {
jaroslav@601: /*
jaroslav@601: * Even if stream already closed, propagate redundant close to
jaroslav@601: * underlying stream to stay consistent with previous implementations.
jaroslav@601: */
jaroslav@601: closed = true;
jaroslav@601: if (depth == 0) {
jaroslav@601: clear();
jaroslav@601: }
jaroslav@601: bin.close();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads in a boolean.
jaroslav@601: *
jaroslav@601: * @return the boolean read.
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public boolean readBoolean() throws IOException {
jaroslav@601: return bin.readBoolean();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads an 8 bit byte.
jaroslav@601: *
jaroslav@601: * @return the 8 bit byte read.
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public byte readByte() throws IOException {
jaroslav@601: return bin.readByte();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads an unsigned 8 bit byte.
jaroslav@601: *
jaroslav@601: * @return the 8 bit byte read.
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public int readUnsignedByte() throws IOException {
jaroslav@601: return bin.readUnsignedByte();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads a 16 bit char.
jaroslav@601: *
jaroslav@601: * @return the 16 bit char read.
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public char readChar() throws IOException {
jaroslav@601: return bin.readChar();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads a 16 bit short.
jaroslav@601: *
jaroslav@601: * @return the 16 bit short read.
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public short readShort() throws IOException {
jaroslav@601: return bin.readShort();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads an unsigned 16 bit short.
jaroslav@601: *
jaroslav@601: * @return the 16 bit short read.
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public int readUnsignedShort() throws IOException {
jaroslav@601: return bin.readUnsignedShort();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads a 32 bit int.
jaroslav@601: *
jaroslav@601: * @return the 32 bit integer read.
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public int readInt() throws IOException {
jaroslav@601: return bin.readInt();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads a 64 bit long.
jaroslav@601: *
jaroslav@601: * @return the read 64 bit long.
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public long readLong() throws IOException {
jaroslav@601: return bin.readLong();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads a 32 bit float.
jaroslav@601: *
jaroslav@601: * @return the 32 bit float read.
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public float readFloat() throws IOException {
jaroslav@601: return bin.readFloat();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads a 64 bit double.
jaroslav@601: *
jaroslav@601: * @return the 64 bit double read.
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public double readDouble() throws IOException {
jaroslav@601: return bin.readDouble();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads bytes, blocking until all bytes are read.
jaroslav@601: *
jaroslav@601: * @param buf the buffer into which the data is read
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public void readFully(byte[] buf) throws IOException {
jaroslav@601: bin.readFully(buf, 0, buf.length, false);
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads bytes, blocking until all bytes are read.
jaroslav@601: *
jaroslav@601: * @param buf the buffer into which the data is read
jaroslav@601: * @param off the start offset of the data
jaroslav@601: * @param len the maximum number of bytes to read
jaroslav@601: * @throws EOFException If end of file is reached.
jaroslav@601: * @throws IOException If other I/O error has occurred.
jaroslav@601: */
jaroslav@601: public void readFully(byte[] buf, int off, int len) throws IOException {
jaroslav@601: int endoff = off + len;
jaroslav@601: if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
jaroslav@601: throw new IndexOutOfBoundsException();
jaroslav@601: }
jaroslav@601: bin.readFully(buf, off, len, false);
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Skips bytes.
jaroslav@601: *
jaroslav@601: * @param len the number of bytes to be skipped
jaroslav@601: * @return the actual number of bytes skipped.
jaroslav@601: * @throws IOException If an I/O error has occurred.
jaroslav@601: */
jaroslav@601: public int skipBytes(int len) throws IOException {
jaroslav@601: return bin.skipBytes(len);
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads in a line that has been terminated by a \n, \r, \r\n or EOF.
jaroslav@601: *
jaroslav@601: * @return a String copy of the line.
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @deprecated This method does not properly convert bytes to characters.
jaroslav@601: * see DataInputStream for the details and alternatives.
jaroslav@601: */
jaroslav@601: @Deprecated
jaroslav@601: public String readLine() throws IOException {
jaroslav@601: return bin.readLine();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Reads a String in
jaroslav@601: * modified UTF-8
jaroslav@601: * format.
jaroslav@601: *
jaroslav@601: * @return the String.
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws UTFDataFormatException if read bytes do not represent a valid
jaroslav@601: * modified UTF-8 encoding of a string
jaroslav@601: */
jaroslav@601: public String readUTF() throws IOException {
jaroslav@601: return bin.readUTF();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Provide access to the persistent fields read from the input stream.
jaroslav@601: */
jaroslav@601: public static abstract class GetField {
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Get the ObjectStreamClass that describes the fields in the stream.
jaroslav@601: *
jaroslav@601: * @return the descriptor class that describes the serializable fields
jaroslav@601: */
jaroslav@601: public abstract ObjectStreamClass getObjectStreamClass();
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Return true if the named field is defaulted and has no value in this
jaroslav@601: * stream.
jaroslav@601: *
jaroslav@601: * @param name the name of the field
jaroslav@601: * @return true, if and only if the named field is defaulted
jaroslav@601: * @throws IOException if there are I/O errors while reading from
jaroslav@601: * the underlying InputStream
jaroslav@601: * @throws IllegalArgumentException if name
does not
jaroslav@601: * correspond to a serializable field
jaroslav@601: */
jaroslav@601: public abstract boolean defaulted(String name) throws IOException;
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Get the value of the named boolean field from the persistent field.
jaroslav@601: *
jaroslav@601: * @param name the name of the field
jaroslav@601: * @param val the default value to use if name
does not
jaroslav@601: * have a value
jaroslav@601: * @return the value of the named boolean
field
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws IllegalArgumentException if type of name
is
jaroslav@601: * not serializable or if the field type is incorrect
jaroslav@601: */
jaroslav@601: public abstract boolean get(String name, boolean val)
jaroslav@601: throws IOException;
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Get the value of the named byte field from the persistent field.
jaroslav@601: *
jaroslav@601: * @param name the name of the field
jaroslav@601: * @param val the default value to use if name
does not
jaroslav@601: * have a value
jaroslav@601: * @return the value of the named byte
field
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws IllegalArgumentException if type of name
is
jaroslav@601: * not serializable or if the field type is incorrect
jaroslav@601: */
jaroslav@601: public abstract byte get(String name, byte val) throws IOException;
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Get the value of the named char field from the persistent field.
jaroslav@601: *
jaroslav@601: * @param name the name of the field
jaroslav@601: * @param val the default value to use if name
does not
jaroslav@601: * have a value
jaroslav@601: * @return the value of the named char
field
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws IllegalArgumentException if type of name
is
jaroslav@601: * not serializable or if the field type is incorrect
jaroslav@601: */
jaroslav@601: public abstract char get(String name, char val) throws IOException;
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Get the value of the named short field from the persistent field.
jaroslav@601: *
jaroslav@601: * @param name the name of the field
jaroslav@601: * @param val the default value to use if name
does not
jaroslav@601: * have a value
jaroslav@601: * @return the value of the named short
field
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws IllegalArgumentException if type of name
is
jaroslav@601: * not serializable or if the field type is incorrect
jaroslav@601: */
jaroslav@601: public abstract short get(String name, short val) throws IOException;
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Get the value of the named int field from the persistent field.
jaroslav@601: *
jaroslav@601: * @param name the name of the field
jaroslav@601: * @param val the default value to use if name
does not
jaroslav@601: * have a value
jaroslav@601: * @return the value of the named int
field
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws IllegalArgumentException if type of name
is
jaroslav@601: * not serializable or if the field type is incorrect
jaroslav@601: */
jaroslav@601: public abstract int get(String name, int val) throws IOException;
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Get the value of the named long field from the persistent field.
jaroslav@601: *
jaroslav@601: * @param name the name of the field
jaroslav@601: * @param val the default value to use if name
does not
jaroslav@601: * have a value
jaroslav@601: * @return the value of the named long
field
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws IllegalArgumentException if type of name
is
jaroslav@601: * not serializable or if the field type is incorrect
jaroslav@601: */
jaroslav@601: public abstract long get(String name, long val) throws IOException;
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Get the value of the named float field from the persistent field.
jaroslav@601: *
jaroslav@601: * @param name the name of the field
jaroslav@601: * @param val the default value to use if name
does not
jaroslav@601: * have a value
jaroslav@601: * @return the value of the named float
field
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws IllegalArgumentException if type of name
is
jaroslav@601: * not serializable or if the field type is incorrect
jaroslav@601: */
jaroslav@601: public abstract float get(String name, float val) throws IOException;
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Get the value of the named double field from the persistent field.
jaroslav@601: *
jaroslav@601: * @param name the name of the field
jaroslav@601: * @param val the default value to use if name
does not
jaroslav@601: * have a value
jaroslav@601: * @return the value of the named double
field
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws IllegalArgumentException if type of name
is
jaroslav@601: * not serializable or if the field type is incorrect
jaroslav@601: */
jaroslav@601: public abstract double get(String name, double val) throws IOException;
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Get the value of the named Object field from the persistent field.
jaroslav@601: *
jaroslav@601: * @param name the name of the field
jaroslav@601: * @param val the default value to use if name
does not
jaroslav@601: * have a value
jaroslav@601: * @return the value of the named Object
field
jaroslav@601: * @throws IOException if there are I/O errors while reading from the
jaroslav@601: * underlying InputStream
jaroslav@601: * @throws IllegalArgumentException if type of name
is
jaroslav@601: * not serializable or if the field type is incorrect
jaroslav@601: */
jaroslav@601: public abstract Object get(String name, Object val) throws IOException;
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Verifies that this (possibly subclass) instance can be constructed
jaroslav@601: * without violating security constraints: the subclass must not override
jaroslav@601: * security-sensitive non-final methods, or else the
jaroslav@601: * "enableSubclassImplementation" SerializablePermission is checked.
jaroslav@601: */
jaroslav@601: private void verifySubclass() {
jaroslav@601: Class cl = getClass();
jaroslav@601: if (cl == ObjectInputStream.class) {
jaroslav@601: return;
jaroslav@601: }
jaroslav@601: SecurityManager sm = System.getSecurityManager();
jaroslav@601: if (sm == null) {
jaroslav@601: return;
jaroslav@601: }
jaroslav@601: processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
jaroslav@601: WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
jaroslav@601: Boolean result = Caches.subclassAudits.get(key);
jaroslav@601: if (result == null) {
jaroslav@601: result = Boolean.valueOf(auditSubclass(cl));
jaroslav@601: Caches.subclassAudits.putIfAbsent(key, result);
jaroslav@601: }
jaroslav@601: if (result.booleanValue()) {
jaroslav@601: return;
jaroslav@601: }
jaroslav@601: sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Performs reflective checks on given subclass to verify that it doesn't
jaroslav@601: * override security-sensitive non-final methods. Returns true if subclass
jaroslav@601: * is "safe", false otherwise.
jaroslav@601: */
jaroslav@601: private static boolean auditSubclass(final Class> subcl) {
jaroslav@601: Boolean result = AccessController.doPrivileged(
jaroslav@601: new PrivilegedAction