undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4511532
* @summary Verify that the message string of a ClassCastException thrown by
* ObjectInputStream when attempting to assign a value to a field of
* an incompatible type contains the names of the value's class, the
* field's declaring class, the field's type, and the field itself.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
private Float bar;
}
class Gub extends Foo {
private static final long serialVersionUID = 1L;
}
public class Read {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("tmp.ser");
try {
ObjectInputStream oin = new ObjectInputStream(in);
oin.readObject();
throw new Error("readObject should not succeed");
} catch (ClassCastException e) {
String s = e.getMessage();
System.out.println("ClassCastException message: " + s);
if (s == null ||
s.indexOf(Foo.class.getName()) == -1 ||
s.indexOf(Integer.class.getName()) == -1 ||
s.indexOf(Float.class.getName()) == -1 ||
s.indexOf(Gub.class.getName()) == -1 ||
s.indexOf("bar") == -1)
{
throw new Error("ClassNotFoundException message incomplete");
}
} finally {
in.close();
}
}
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4511532
*
* @clean Write Read Foo Gub
* @compile Write.java
* @run main Write
* @clean Write Read Foo Gub
* @compile Read.java
* @run main Read
*
* @summary Verify that the message string of a ClassCastException thrown by
* ObjectInputStream when attempting to assign a value to a field of
* an incompatible type contains the names of the value's class, the
* field's declaring class, the field's type, and the field itself.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
private Integer bar = 0;
}
class Gub extends Foo {
private static final long serialVersionUID = 1L;
}
public class Write {
public static void main(String[] args) throws Exception {
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream("tmp.ser"));
oout.writeObject(new Gub());
oout.close();
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4402830
* @summary Verify that the ObjectInputStream.GetField API works properly for
* serialized fields which don't exist in the receiving object.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
int blargh;
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
ObjectInputStream.GetField fields = in.readFields();
if (! fields.defaulted("blargh")) {
throw new Error();
}
try {
fields.defaulted("nonexistant");
throw new Error();
} catch (IllegalArgumentException ex) {
}
if ((fields.get("z", false) != true) ||
(fields.get("b", (byte) 0) != 5) ||
(fields.get("c", '0') != '5') ||
(fields.get("s", (short) 0) != 5) ||
(fields.get("i", 0) != 5) ||
(fields.get("j", 0l) != 5) ||
(fields.get("f", 0.0f) != 5.0f) ||
(fields.get("d", 0.0) != 5.0) ||
(! fields.get("str", null).equals("5")))
{
throw new Error();
}
}
}
public class Read {
public static void main(String[] args) throws Exception {
ObjectInputStream oin =
new ObjectInputStream(new FileInputStream("tmp.ser"));
oin.readObject();
oin.close();
}
}

View file

@ -0,0 +1,73 @@
/*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4427881
* @summary Verify that the ObjectInputStream.GetField API works properly for
* serialized fields which exist in the receiving object.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
boolean z;
byte b;
char c;
short s;
int i;
long j;
float f;
double d;
String str;
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
Object extra;
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
ObjectInputStream.GetField fields = in.readFields();
if ((fields.get("z", false) != true) ||
(fields.get("b", (byte) 0) != 5) ||
(fields.get("c", '0') != '5') ||
(fields.get("s", (short) 0) != 5) ||
(fields.get("i", 0) != 5) ||
(fields.get("j", 0l) != 5) ||
(fields.get("f", 0.0f) != 5.0f) ||
(fields.get("d", 0.0) != 5.0) ||
(! fields.get("str", null).equals("5")))
{
throw new Error();
}
}
}
public class Read2 {
public static void main(String[] args) throws Exception {
ObjectInputStream oin =
new ObjectInputStream(new FileInputStream("tmp.ser"));
oin.readObject();
oin.close();
}
}

View file

@ -0,0 +1,190 @@
/*
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8273660
* @summary Verify that ObjectInputStream ReadFields correctly reports ClassNotFoundException
* while getting the field value. The test uses Vector that calls ReadFields from its readObject.
* @library /test/lib
* @run junit ReadFieldsCNF
* @run junit/othervm -Djdk.serialGetFieldCnfeReturnsNull=true ReadFieldsCNF
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.nio.charset.StandardCharsets;
import java.util.Vector;
import jdk.test.lib.hexdump.HexPrinter;
import jdk.test.lib.hexdump.ObjectStreamPrinter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ReadFieldsCNF {
private static final boolean GETFIELD_CNFE_RETURNS_NULL =
Boolean.getBoolean("jdk.serialGetFieldCnfeReturnsNull");
/**
* Test a Vector holding a reference to a class instance that will not be found.
* @throws IOException If any other exception occurs
*/
@Test
void testVectorWithRole() throws IOException {
System.out.println("Property GETFIELD_CNFE_RETURNS_NULL: " + GETFIELD_CNFE_RETURNS_NULL);
Role role = new Role();
Vector<Role> vector = new Vector<>();
vector.add(role);
// Modify the byte stream to change the classname to be deserialized to
// XeadFieldsCNF$Role.
byte[] bytes = writeObject(vector);
// Locate the name of the class to be deserialize
String s = new String(bytes, StandardCharsets.ISO_8859_1); // Map bytes to chars
int off = s.indexOf(Role.class.getName());
System.out.printf("Role offset: %d (0x%x) : %s%n", off, off, Role.class.getName());
if (off < 0) {
HexPrinter.simple().formatter(ObjectStreamPrinter.formatter()).format(bytes);
Assertions.fail("classname not found");
}
bytes[off] = (byte) 'X'; // replace R with X -> Class not found
// Deserialize the Vector expecting a ClassNotFoundException
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
try {
Object obj = in.readObject();
System.out.println("Read: " + obj);
Assertions.fail("Should not reach here, an exception should always occur");
} catch (ClassNotFoundException cnfe) {
// Expected ClassNotFoundException
String expected = "XeadFieldsCNF$Role";
Assertions.assertEquals(expected, cnfe.getMessage(), "Wrong classname");
if (GETFIELD_CNFE_RETURNS_NULL) {
Assertions.fail("Expected IOException got ClassNotFoundException", cnfe);
}
System.out.println("Normal: OIS.readObject: " + cnfe);
} catch (StreamCorruptedException ioe) {
if (!GETFIELD_CNFE_RETURNS_NULL) {
Assertions.fail("Expected ClassNotFoundException got StreamCorruptedException ", ioe);
}
System.out.println("Normal: " + ioe);
}
// Other exceptions cause the test to fail
}
/**
* For an object holding a reference to a class that will not be found.
* @throws IOException If any other exception occurs
*/
@Test
void testHolderWithRole() throws IOException {
System.out.println("Property GETFIELD_CNFE_RETURNS_NULL: " + GETFIELD_CNFE_RETURNS_NULL);
Role role = new Role();
Holder holder = new Holder(role);
// Modify the byte stream to change the classname to be deserialized to
// XeadFieldsCNF$Role.
byte[] bytes = writeObject(holder);
String s = new String(bytes, StandardCharsets.ISO_8859_1); // Map bytes to chars
int off = s.indexOf(Role.class.getName(), 0);
off = s.indexOf(Role.class.getName(), off + 1); // 2nd occurrence of classname
System.out.printf("Role offset: %d (0x%x)%n", off, off);
if (off < 0) {
HexPrinter.simple().formatter(ObjectStreamPrinter.formatter()).format(bytes);
Assertions.fail("classname found at index: " + off + " (0x" + Integer.toHexString(off) + ")");
}
bytes[off] = (byte) 'X'; // replace R with X -> Class not found
// Deserialize the Vector expecting a ClassNotFoundException
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
try {
Holder obj = (Holder)in.readObject();
System.out.println("Read: " + obj);
Assertions.fail("Should not reach here, an exception should always occur");
} catch (ClassNotFoundException cnfe) {
// Expected ClassNotFoundException
String expected = "XeadFieldsCNF$Role";
Assertions.assertEquals(expected, cnfe.getMessage(), "Wrong classname");
System.out.println("Normal: OIS.readObject: " + cnfe);
} catch (StreamCorruptedException ioe) {
if (!GETFIELD_CNFE_RETURNS_NULL) {
Assertions.fail("Expected ClassNotFoundException got StreamCorruptedException ", ioe);
}
System.out.println("Normal: " + ioe);
}
// Other exceptions cause the test to fail
}
private static byte[] writeObject(Object o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream os = new ObjectOutputStream(baos)) {
os.writeObject(o);
}
return baos.toByteArray();
}
static class Role implements Serializable {
private static final long serialVersionUID = 0L;
Role() {}
}
static class Holder implements Serializable {
private static final long serialVersionUID = 1L;
Role role;
Holder(Role role) {
this.role = role;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = ois.readFields();
try {
Object repl = new Object();
role = (Role)fields.get("role", repl);
System.out.println("Holder.readObject Role: " + role);
} catch (Exception ex) {
// Catch CNFE and ignore it; check elsewhere that CNFE is thrown from OIS.readObject
System.out.println("Normal: exception in Holder.readObject, ignoring: " + ex);
}
}
public String toString() {
return "role: " + role;
}
}
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4402830 4427881
*
* @clean Write Read Read2 Foo
* @compile Write.java
* @run main Write
* @clean Write Foo
* @compile Read.java
* @run main Read
* @clean Read Foo
* @compile Read2.java
* @run main Read2
* @clean Read2 Foo
*
* @summary Verify proper basic functionality of the
* ObjectInputStream.GetField API
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
boolean z = true;
byte b = 5;
char c = '5';
short s = 5;
int i = 5;
long j = 5;
float f = 5.0f;
double d = 5.0;
String str = "5";
}
public class Write {
public static void main(String[] args) throws Exception {
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream("tmp.ser"));
oout.writeObject(new Foo());
oout.close();
}
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8282696
* @summary Verify message and cause handling of InvalidClassException
*/
import java.io.*;
import java.util.Objects;
public class TestIceConstructors {
public static void main(String... args) {
String reason = "reason";
Throwable cause = new RuntimeException();
testException(new InvalidClassException(reason),
reason, null);
testException(new InvalidClassException(reason, cause),
reason, cause);
testException(new InvalidClassException("prefix", reason, cause),
"prefix" + "; " + reason, cause);
}
private static void testException(InvalidClassException ice,
String expectedMessage,
Throwable expectedCause) {
var message = ice.getMessage();
if (!Objects.equals(message, expectedMessage)) {
throw new RuntimeException("Unexpected message " + message);
}
var cause = ice.getCause();
if (cause != expectedCause) {
throw new RuntimeException("Unexpected cause");
}
}
}

View file

@ -0,0 +1,220 @@
/*
* Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4093279
* @compile DefaultPackage.java
* @run main DefaultPackage
* @summary Raise InvalidClassException if 1st NonSerializable superclass' no-arg constructor is not accessible. This test verifies default package access.
*/
import java.io.*;
class DefaultPackagePublicConstructor {
public DefaultPackagePublicConstructor() {
}
};
class DefaultPackageProtectedConstructor {
protected DefaultPackageProtectedConstructor() {
}
};
class DefaultPackageDefaultAccessConstructor {
DefaultPackageDefaultAccessConstructor() {
}
};
class DefaultPackagePrivateConstructor {
private DefaultPackagePrivateConstructor() {
}
/* need to have at least one protected constructor to extend this class.*/
protected DefaultPackagePrivateConstructor(int i) {
}
};
class DefaultPublicSerializable
extends DefaultPackagePublicConstructor implements Serializable
{
private static final long serialVersionUID = 1L;
int field1 = 5;
};
class DefaultProtectedSerializable
extends DefaultPackageProtectedConstructor implements Serializable
{
private static final long serialVersionUID = 1L;
int field1 = 5;
};
class DefaultAccessSerializable
extends DefaultPackageDefaultAccessConstructor implements Serializable
{
private static final long serialVersionUID = 1L;
int field1 = 5;
};
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
class DefaultPrivateSerializable
extends DefaultPackagePrivateConstructor implements Serializable
{
private static final long serialVersionUID = 1L;
int field1 = 5;
DefaultPrivateSerializable() {
super(1);
}
};
class ExternalizablePublicConstructor implements Externalizable {
private static final long serialVersionUID = 1L;
public ExternalizablePublicConstructor() {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
}
};
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
class ExternalizableProtectedConstructor implements Externalizable {
private static final long serialVersionUID = 1L;
protected ExternalizableProtectedConstructor() {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
}
};
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
class ExternalizableAccessConstructor implements Externalizable {
private static final long serialVersionUID = 1L;
ExternalizableAccessConstructor() {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
}
};
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
class ExternalizablePrivateConstructor implements Externalizable {
private static final long serialVersionUID = 1L;
private ExternalizablePrivateConstructor() {
}
public ExternalizablePrivateConstructor(int i) {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
}
};
public class DefaultPackage {
public static void main(String args[])
throws IOException, ClassNotFoundException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(new DefaultPublicSerializable());
out.writeObject(new DefaultProtectedSerializable());
out.writeObject(new DefaultAccessSerializable());
out.writeObject(new DefaultPrivateSerializable());
InputStream is = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream in = new ObjectInputStream(is);
/* (DefaultPublicSerializable) */ in.readObject();
/* (DefaultProtectedSerializable) */ in.readObject();
/* (DefaultAcccessSerializable) */ in.readObject();
try {
/* (DefaultPrivateSerializable) */ in.readObject();
throw new Error("Expected InvalidClassException reading DefaultPrivateSerialziable");
} catch (InvalidClassException e) {
}
in.close();
baos.reset();
out = new ObjectOutputStream(baos);
out.writeObject(new ExternalizablePublicConstructor());
in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
/* (ExternalizablePublicConstructor) */ in.readObject();
in.close();
baos.reset();
out = new ObjectOutputStream(baos);
out.writeObject(new ExternalizableProtectedConstructor());
in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
try {
/* (ExternalizableProtectedConstructor) */ in.readObject();
throw new Error("Expected InvalidClassException reading ExternalizableProtectedConstructor");
} catch (InvalidClassException e) {
}
in.close();
baos.reset();
out = new ObjectOutputStream(baos);
out.writeObject(new ExternalizableAccessConstructor());
in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
try {
/* (ExternalizableAccessConstructor) */ in.readObject();
throw new Error("Expected InvalidClassException reading ExternalizableAccessConstructor");
} catch (InvalidClassException e) {
}
in.close();
baos.reset();
out = new ObjectOutputStream(baos);
out.writeObject(new ExternalizablePrivateConstructor(2));
in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
try {
/* (ExternalizablePrivateConstructor) */ in.readObject();
throw new Error("Expected InvalidClassException reading ExternalizablePrivateConstructor");
} catch (InvalidClassException e) {
}
out.close();
in.close();
}
}

View file

@ -0,0 +1,35 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4093279
*/
package NonSerializable;
public class PackageCtor {
PackageCtor() {
}
public PackageCtor(int l) {
}
};

View file

@ -0,0 +1,36 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4093279
*/
package NonSerializable;
public class PrivateCtor {
private PrivateCtor() {
}
/* need to have at least one protected constructor to extend this class.*/
public PrivateCtor(int i) {
}
};

View file

@ -0,0 +1,33 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4093279
*/
package NonSerializable;
public class ProtectedCtor {
protected ProtectedCtor() {
}
};

View file

@ -0,0 +1,33 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4093279
*/
package NonSerializable;
public class PublicCtor {
public PublicCtor() {
}
};

View file

@ -0,0 +1,33 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4093279
*/
package Serialize;
public class SamePackageCtor {
SamePackageCtor() {
}
};

View file

@ -0,0 +1,268 @@
/*
* Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4093279
* REMOVED test, build and run tag since could not get this to work.
* Test is run via shell script, run.sh.
*/
package Serialize;
import java.io.*;
class PublicSerializable
extends NonSerializable.PublicCtor implements Serializable
{
private static final long serialVersionUID = 1L;
int field1 = 5;
};
class ProtectedSerializable
extends NonSerializable.ProtectedCtor implements Serializable
{
private static final long serialVersionUID = 1L;
int field1 = 5;
};
class DifferentPackageSerializable
extends NonSerializable.PackageCtor implements Serializable
{
private static final long serialVersionUID = 1L;
int field1 = 5;
DifferentPackageSerializable() {
super(1);
}
};
class SamePackageSerializable
extends Serialize.SamePackageCtor implements Serializable
{
private static final long serialVersionUID = 1L;
SamePackageSerializable() {
}
};
class SamePackageProtectedCtor {
private static final long serialVersionUID = 1L;
protected SamePackageProtectedCtor() {
}
};
class SamePackageProtectedSerializable
extends Serialize.SamePackageProtectedCtor implements Serializable
{
private static final long serialVersionUID = 1L;
SamePackageProtectedSerializable() {
}
};
class SamePackagePrivateCtor {
private static final long serialVersionUID = 1L;
private SamePackagePrivateCtor() {
}
public SamePackagePrivateCtor(int l) {
}
};
class SamePackagePrivateSerializable
extends Serialize.SamePackagePrivateCtor implements Serializable
{
private static final long serialVersionUID = 1L;
SamePackagePrivateSerializable() {
super(1);
}
};
class PrivateSerializable
extends NonSerializable.PrivateCtor implements Serializable
{
private static final long serialVersionUID = 1L;
int field1 = 5;
PrivateSerializable() {
super(1);
}
};
class ExternalizablePublicCtor implements Externalizable {
private static final long serialVersionUID = 1L;
public ExternalizablePublicCtor() {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
}
};
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
class ExternalizableProtectedCtor implements Externalizable {
private static final long serialVersionUID = 1L;
protected ExternalizableProtectedCtor() {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
}
};
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
class ExternalizablePackageCtor implements Externalizable {
private static final long serialVersionUID = 1L;
ExternalizablePackageCtor() {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
}
};
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
class ExternalizablePrivateCtor implements Externalizable {
private static final long serialVersionUID = 1L;
private ExternalizablePrivateCtor() {
}
public ExternalizablePrivateCtor(int i) {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
}
};
public class SubclassAcrossPackage {
public static void main(String args[])
throws IOException, ClassNotFoundException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(new PublicSerializable());
out.writeObject(new ProtectedSerializable());
out.writeObject(new SamePackageSerializable());
out.writeObject(new SamePackageProtectedSerializable());
out.writeObject(new DifferentPackageSerializable());
InputStream is = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream in = new ObjectInputStream(is);
/* (PublicSerializable)*/ in.readObject();
/* (ProtectedSerializable) */ in.readObject();
/* (SamePackageSerializable) */ in.readObject();
/* (SamePackageProtectedSerializable) */ in.readObject();
try {
/* (DifferentPackageSerializable) */ in.readObject();
} catch (InvalidClassException e) {
}
in.close();
baos.reset();
out = new ObjectOutputStream(baos);
out.writeObject(new PrivateSerializable());
in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
try {
/* (PrivateSerializable) */ in.readObject();
throw new Error("Expected InvalidClassException reading PrivateSerialziable");
} catch (InvalidClassException e) {
}
in.close();
baos.reset();
out = new ObjectOutputStream(baos);
out.writeObject(new SamePackagePrivateSerializable());
in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
try {
/* (SamePackagePrivateSerializable) */ in.readObject();
throw new Error("Expected InvalidClassException reading PrivateSerialziable");
} catch (InvalidClassException e) {
}
in.close();
baos.reset();
out = new ObjectOutputStream(baos);
out.writeObject(new ExternalizablePublicCtor());
in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
/* (ExternalizablePublicCtor) */ in.readObject();
in.close();
baos.reset();
out = new ObjectOutputStream(baos);
out.writeObject(new ExternalizableProtectedCtor());
in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
try {
/* (ExternalizableProtectedCtor) */ in.readObject();
throw new Error("Expected InvalidClassException reading ExternalizableProtectedCtor");
} catch (InvalidClassException e) {
}
in.close();
baos.reset();
out = new ObjectOutputStream(baos);
out.writeObject(new ExternalizablePackageCtor());
in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
try {
/* (ExternalizablePackageCtor) */ in.readObject();
throw new Error("Expected InvalidClassException reading ExternalizablePackageCtor");
} catch (InvalidClassException e) {
}
in.close();
baos.reset();
out = new ObjectOutputStream(baos);
out.writeObject(new ExternalizablePrivateCtor(2));
in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
try {
/* (ExternalizablePrivateCtor) */ in.readObject();
throw new Error("Expected InvalidClassException reading ExternalizablePrivateCtor");
} catch (InvalidClassException e) {
}
out.close();
in.close();
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 1998, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4093279
* @summary Validate accessibility checking to NonSerializable superclass constuctor.
* @library NonSerialize Serialize
* @compile NonSerialize/PrivateCtor.java NonSerialize/ProtectedCtor.java NonSerialize/PackageCtor.java NonSerialize/PublicCtor.java
* @compile Serialize/SubclassAcrossPackage.java Serialize/SamePackageCtor.java
* @run main Test
*/
import java.io.*;
import Serialize.SubclassAcrossPackage;
public class Test {
public static void main(String[] args)
throws IOException, ClassNotFoundException {
Serialize.SubclassAcrossPackage.main(args);
}
}

View file

@ -0,0 +1,56 @@
/*
* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8282696
* @summary Verify message and cause handling of InvalidObjectException
*/
import java.io.*;
import java.util.Objects;
public class TestIoeConstructors {
public static void main(String... args) {
String reason = "reason";
Throwable cause = new RuntimeException();
testException(new InvalidObjectException(reason),
reason, null);
testException(new InvalidObjectException(reason, cause),
reason, cause);
}
private static void testException(InvalidObjectException ioe,
String expectedMessage,
Throwable expectedCause) {
var message = ioe.getMessage();
if (!Objects.equals(message, expectedMessage)) {
throw new RuntimeException("Unexpected message " + message);
}
var cause = ioe.getCause();
if (cause != expectedCause) {
throw new RuntimeException("Unexpected cause");
}
}
}

View file

@ -0,0 +1,80 @@
/*
* Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 6541870
* @summary this test checks that ObjectInputStream throws an IOException
* instead of a NullPointerException when deserializing an ArrayList
* of Externalizables if there is an IOException while deserializing
* one of these Externalizables.
*
* @author Andrey Ozerov
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class NPEProvoker implements java.io.Externalizable {
private static final long serialVersionUID = 1L;
private String test = "test";
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException
{
throw new IOException(); //io exception for whatever reason
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(test);
}
public static void main(String[] args) {
System.err.println("\n Regression test for bug 6541870\n");
try {
ArrayList<NPEProvoker> list = new ArrayList<>();
list.add(new NPEProvoker());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(list);
ObjectInputStream ois =
new ObjectInputStream(new ByteArrayInputStream(
baos.toByteArray()));
ois.readObject();
throw new Error();
} catch (IOException e) {
System.err.println("\nTEST PASSED");
} catch (ClassNotFoundException e) {
throw new Error();
} catch (NullPointerException e) {
throw new Error();
}
}
}

View file

@ -0,0 +1,114 @@
/*
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4205440
* @summary When ObjectInputStream.inputClassDescriptor calls its protected
* resolveClass, if a NoClassDefFoundError is thrown, that Error should be
* propagated to the caller, instead of being trapped and transformed into
* a ClassNotFoundException for the class being resolved.
* @author Peter Jones
*
* @build NoClassDefFoundErrorTrap
* @run main NoClassDefFoundErrorTrap
*/
import java.io.*;
public class NoClassDefFoundErrorTrap {
private static NoClassDefFoundError ncdfe;
public interface Bar {}
public static class Foo implements Bar, java.io.Serializable {
private static final long serialVersionUID = 1L;
}
/**
* Test subclass of ObjectInputStream that overrides resolveClass
* to throw a NoClassDefFoundError if our test class "Foo" is to
* be resolved.
*/
public static class TestObjectInputStream extends ObjectInputStream {
public TestObjectInputStream(InputStream in)
throws IOException
{
super(in);
}
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException
{
String name = desc.getName();
if (name.equals(Foo.class.getName())) {
ncdfe = new NoClassDefFoundError("Bar");
throw ncdfe;
} else {
return super.resolveClass(desc);
}
}
}
public static void main(String[] args) {
System.err.println("\nRegression test for bug 4205440\n");
try {
/*
* Serialize a Foo instance to a byte array.
*/
Foo foo = new Foo();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(foo);
byte[] stream = bout.toByteArray();
/*
* Deserialize the Foo instance using our test subclass of
* ObjectInputStream that will throw NoClassDefFoundError.
*/
ByteArrayInputStream bin = new ByteArrayInputStream(stream);
ObjectInputStream in = new TestObjectInputStream(bin);
/*
* The test succeeds if we get the NoClassDefFoundError.
*/
try {
in.readObject();
} catch (NoClassDefFoundError e) {
if (e == ncdfe) {
System.err.println("TEST PASSED: " + e.toString());
} else {
throw e;
}
}
} catch (Exception e) {
System.err.println("\nTEST FAILED:");
e.printStackTrace();
throw new RuntimeException("TEST FAILED: " + e.toString());
}
}
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @summary Verify that the ObjectOutputStream.PutField API works as
* advertised.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
boolean z;
byte b;
char c;
short s;
int i;
long j;
float f;
double d;
String str;
}
public class Read {
public static void main(String[] args) throws Exception {
ObjectInputStream oin =
new ObjectInputStream(new FileInputStream("tmp.ser"));
Foo foo = (Foo) oin.readObject();
oin.close();
if ((! foo.z) ||
(foo.b != 5) ||
(foo.c != '5') ||
(foo.s != 5) ||
(foo.i != 5) ||
(foo.j != 5) ||
(foo.f != 5.0f) ||
(foo.d != 5.0) ||
(! foo.str.equals("5")))
{
throw new Error();
}
}
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4453723
* @summary Verify that ObjectOutputStream.PutField.write() works for objects
* that do not define primitive serializable fields.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
String s1, s2;
}
public class Read2 {
public static void main(String[] args) throws Exception {
ObjectInputStream oin =
new ObjectInputStream(new FileInputStream("tmp.ser"));
Foo foo = (Foo) oin.readObject();
oin.close();
if (!(foo.s1.equals("qwerty") && foo.s2.equals("asdfg"))) {
throw new Error();
}
}
}

View file

@ -0,0 +1,75 @@
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
*
* @clean Write Read Foo
* @compile Write.java
* @run main Write
* @clean Write Read Foo
* @compile Read.java
* @run main Read
*
* @summary Verify that the ObjectOutputStream.PutField API works as
* advertised.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("z", boolean.class),
new ObjectStreamField("b", byte.class),
new ObjectStreamField("c", char.class),
new ObjectStreamField("s", short.class),
new ObjectStreamField("i", int.class),
new ObjectStreamField("j", long.class),
new ObjectStreamField("f", float.class),
new ObjectStreamField("d", double.class),
new ObjectStreamField("str", String.class),
};
private void writeObject(ObjectOutputStream out) throws IOException {
ObjectOutputStream.PutField fields = out.putFields();
fields.put("z", true);
fields.put("b", (byte) 5);
fields.put("c", '5');
fields.put("s", (short) 5);
fields.put("i", 5);
fields.put("j", 5l);
fields.put("f", 5.0f);
fields.put("d", 5.0);
fields.put("str", "5");
out.writeFields();
}
}
public class Write {
public static void main(String[] args) throws Exception {
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream("tmp.ser"));
oout.writeObject(new Foo());
oout.close();
}
}

View file

@ -0,0 +1,63 @@
/*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4453723
*
* @clean Write2 Read2 Foo
* @compile Write2.java
* @run main Write2
* @clean Write2 Read2 Foo
* @compile Read2.java
* @run main Read2
*
* @summary Verify that ObjectOutputStream.PutField.write() works for objects
* that do not define primitive serializable fields.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("s1", String.class),
new ObjectStreamField("s2", String.class)
};
@SuppressWarnings("deprecation")
private void writeObject(ObjectOutputStream out) throws IOException {
ObjectOutputStream.PutField fields = out.putFields();
fields.put("s1", "qwerty");
fields.put("s2", "asdfg");
fields.write(out);
}
}
public class Write2 {
public static void main(String[] args) throws Exception {
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream("tmp.ser"));
oout.writeObject(new Foo());
oout.close();
}
}

View file

@ -0,0 +1,32 @@
/*
* Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4490677
* @summary Verify that array serialVersionUID conflicts caused by changes in
* package scope do not cause deserialization to fail.
*/
public class Foo implements java.io.Serializable {
private static final long serialVersionUID = 0L;
}

View file

@ -0,0 +1,43 @@
/*
* Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4490677
* @summary Verify that array serialVersionUID conflicts caused by changes in
* package scope do not cause deserialization to fail.
*/
import java.io.*;
class Foo {
private static final long serialVersionUID = 0L;
}
public class Read {
public static void main(String[] args) throws Exception {
ObjectInputStream oin =
new ObjectInputStream(new FileInputStream("tmp.ser"));
Foo[] obj = (Foo[]) oin.readObject();
oin.close();
}
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4490677
*
* @clean Write Read Foo
* @compile Write.java Foo.java
* @run main Write
* @clean Write Read Foo
* @compile Read.java
* @run main Read
*
* @summary Verify that array serialVersionUID conflicts caused by changes in
* package scope do not cause deserialization to fail.
*/
import java.io.*;
public class Write {
public static void main(String[] args) throws Exception {
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream("tmp.ser"));
oout.writeObject(new Foo[0]);
oout.close();
}
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4311940
* @summary Verify that ObjectOutputStream and ObjectInputStream can be constructed
* @build AuditStreamSubclass
* @run main AuditStreamSubclass
*/
import java.io.*;
class GoodOOS1 extends ObjectOutputStream {
GoodOOS1(OutputStream out) throws IOException { super(out); }
}
class GoodOOS2 extends GoodOOS1 {
GoodOOS2(OutputStream out) throws IOException { super(out); }
}
class GoodOIS1 extends ObjectInputStream {
GoodOIS1(InputStream in) throws IOException { super(in); }
}
class GoodOIS2 extends GoodOIS1 {
GoodOIS2(InputStream in) throws IOException { super(in); }
}
public class AuditStreamSubclass {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.flush();
byte[] buf = bout.toByteArray();
new GoodOOS1(bout);
new GoodOOS2(bout);
new GoodOIS1(new ByteArrayInputStream(buf));
new GoodOIS2(new ByteArrayInputStream(buf));
}
}

View file

@ -0,0 +1,88 @@
/*
* Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4400571
* @summary Verify that ObjectInputStream.available() functions properly when
* called at the beginning of a data block, and that it does not
* attempt any read operations that may potentially block.
*/
import java.io.*;
public class Available {
public static void main(String[] args) throws Exception {
ObjectOutputStream oout;
ByteArrayOutputStream bout;
byte[] buf;
// write stream containing short data block
oout = new ObjectOutputStream(bout = new ByteArrayOutputStream());
oout.write(new byte[100]);
oout.close();
buf = bout.toByteArray();
// 4 byte stream header + 2 byte block header + data
if ((getAvailable(buf, 4) != 0) || (getAvailable(buf, 5) != 0)) {
throw new Error();
}
for (int i = 0; i < 100; i++) {
if (getAvailable(buf, 6 + i) != i) {
throw new Error();
}
}
// write stream containing long data block
oout = new ObjectOutputStream(bout = new ByteArrayOutputStream());
oout.write(new byte[500]);
oout.close();
buf = bout.toByteArray();
// 4 byte stream header + 5 byte block header + data
for (int i = 4; i < 9; i++) {
if (getAvailable(buf, i) != 0) {
throw new Error();
}
}
for (int i = 0; i < 500; i++) {
if (getAvailable(buf, 9 + i) != i) {
throw new Error();
}
}
}
/**
* Given a byte array containing a serialized stream, creates a copy of the
* given data truncated to the specified length, then returns the result of
* a call to available() on an ObjectInputStream created on top of the
* truncated data. As a side effect, a StreamCorrupted or EOFException
* will get thrown if the available() call attempts to read past the
* underlying stream's available data.
*/
static int getAvailable(byte[] data, int truncateLen) throws IOException {
byte[] trunc = new byte[truncateLen];
System.arraycopy(data, 0, trunc, 0, truncateLen);
return new ObjectInputStream(
new ByteArrayInputStream(trunc)).available();
}
}

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4312433
* @summary Verify that reading a back reference to a previously skipped value
* whose class is not available will throw a ClassNotFoundException
*/
import java.io.*;
class A implements Serializable {
private static final long serialVersionUID = 0L;
// field b skipped
}
// class B not available
public class Read {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("tmp.ser");
try {
ObjectInputStream oin = new ObjectInputStream(in);
oin.readObject();
try {
oin.readObject();
throw new Error("back reference read succeeded");
} catch (ClassNotFoundException ex) {
}
} finally {
in.close();
}
}
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4312433
*
* @clean Write Read A B
* @compile Write.java
* @run main Write
* @clean Write Read A B
* @compile Read.java
* @run main Read
*
* @summary Verify that reading a back reference to a previously skipped value
* whose class is not available will throw a ClassNotFoundException
*/
import java.io.*;
class A implements Serializable {
private static final long serialVersionUID = 0L;
B b = new B();
}
class B implements Serializable { // class not present on reading side
private static final long serialVersionUID = 0L;
}
public class Write {
public static void main(String[] args) throws Exception {
A a = new A();
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream("tmp.ser"));
oout.writeObject(a);
oout.writeObject(a.b);
oout.close();
}
}

View file

@ -0,0 +1,81 @@
/*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4387368
* @summary Verify that object whose class declared a serial persistent field
* that does not match any actual field cannot be serialized via
* default serialization.
*/
import java.io.*;
class A implements Serializable {
private static final long serialVersionUID = 1L;
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("nonexistent", int.class)
};
}
class B implements Serializable {
private static final long serialVersionUID = 1L;
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("mismatched", int.class)
};
private float mismatched;
}
class C implements Serializable {
private static final long serialVersionUID = 1L;
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("existent", int.class)
};
private int existent;
}
public class BadSerialPersistentField {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout;
oout = new ObjectOutputStream(bout);
try {
oout.writeObject(new A());
throw new Error();
} catch (InvalidClassException ex) {
}
oout = new ObjectOutputStream(bout);
try {
oout.writeObject(new B());
throw new Error();
} catch (InvalidClassException ex) {
}
oout = new ObjectOutputStream(bout);
oout.writeObject(new C());
}
}

View file

@ -0,0 +1,90 @@
/*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4431318
* @summary Verify that when serialVersionUID is declared with a type other
* than long, values that can be promoted to long will be used, and
* those that can't be will be ignored (but will not result in
* unchecked exceptions).
*/
import java.io.*;
class Z implements Serializable {
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final boolean serialVersionUID = false;
}
class B implements Serializable {
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final byte serialVersionUID = 5;
}
class C implements Serializable {
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final char serialVersionUID = 5;
}
class S implements Serializable {
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final short serialVersionUID = 5;
}
class I implements Serializable {
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final int serialVersionUID = 5;
}
class F implements Serializable {
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final float serialVersionUID = 5.0F;
}
class D implements Serializable {
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final double serialVersionUID = 5.0;
}
class L implements Serializable {
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final Object serialVersionUID = "5";
}
public class BadSerialVersionUID {
public static void main(String[] args) throws Exception {
Class<?>[] ignore = { Z.class, F.class, D.class, L.class };
Class<?>[] convert = { B.class, C.class, S.class, I.class };
for (int i = 0; i < ignore.length; i++) {
ObjectStreamClass.lookup(ignore[i]).getSerialVersionUID();
}
for (int i = 0; i < convert.length; i++) {
ObjectStreamClass desc = ObjectStreamClass.lookup(convert[i]);
if (desc.getSerialVersionUID() != 5L) {
throw new Error();
}
}
}
}

View file

@ -0,0 +1,80 @@
/*
* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @summary Verify that ClassCastException is thrown when deserializing
* an object and one of its object fields is incompatibly replaced
* by either replaceObject/resolveObject.
*
*/
import java.io.*;
class A implements Serializable {
private static final long serialVersionUID = 1L;
}
class B implements Serializable {
private static final long serialVersionUID = 1L;
}
class Container implements Serializable {
private static final long serialVersionUID = 1L;
A a = new A();
}
class ReplacerObjectOutputStream extends ObjectOutputStream {
static B b = new B();
public ReplacerObjectOutputStream(OutputStream out) throws IOException {
super(out);
enableReplaceObject(true);
}
protected Object replaceObject(Object obj) throws IOException {
if(obj instanceof A) {
System.err.println("replaceObject(" + obj.toString() + ") with " +
b.toString());
return b;
} else return obj;
}
}
public class BadSubstByReplace {
public static void main(String args[]) throws IOException, ClassNotFoundException {
Container c = new Container();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ReplacerObjectOutputStream out = new ReplacerObjectOutputStream(baos);
out.writeObject(c);
out.close();
ObjectInputStream in =
new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
try {
c = (Container)in.readObject(); // throws IllegalArgumentException.
throw new Error("Should have thrown ClassCastException");
} catch ( ClassCastException e) {
System.err.println("Caught expected exception " + e.toString());
e.printStackTrace();
} finally {
in.close();
}
}
}

View file

@ -0,0 +1,262 @@
/*
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4214888
* @clean CheckModifiers TestClass1 TestClass2
* @build CheckModifiers
* @run main CheckModifiers
* @summary Make sure that serialpersistentFields data member is used to
* represent tyhe serializable fields only if it has the modfiers
* static, final, private and the type is ObjectStreamField.
* No need to check for static, as ObjectStreamField class is not
* serializable.
*
*/
import java.io.*;
class TestClass1 implements Serializable {
private static final long serialVersionUID = 1L;
// Missing the "final" modifier
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("field1", Integer.class),
new ObjectStreamField("field2", Double.TYPE),
};
Integer field1;
double field2;
int field3;
String field4;
public TestClass1(Integer f1, double f2, int f3, String f4) {
field1 = f1;
field2 = f2;
field3 = f3;
field4 = f4;
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
ObjectInputStream.GetField pfields = ois.readFields();
field1 = (Integer) pfields.get("field1", Integer.valueOf(100));
field2 = pfields.get("field2", 99.99);
/* These fields must be present in the stream */
try {
field3 = pfields.get("field3", 99);
System.out.println("Passes test 1a");
} catch(IllegalArgumentException e) {
throw new Error("data field: field3 not in the persistent stream");
}
try {
field4 = (String) pfields.get("field4", "Default string");
System.out.println("Passes test 1b");
} catch(IllegalArgumentException e) {
throw new Error("data field: field4 not in the persistent stream");
}
}
};
class TestClass2 implements Serializable {
private static final long serialVersionUID = 1L;
// public instead of private
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
public static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("field1", Integer.class),
new ObjectStreamField("field2", Double.TYPE),
};
Integer field1;
double field2;
int field3;
String field4;
public TestClass2(Integer f1, double f2, int f3, String f4) {
field1 = f1;
field2 = f2;
field3 = f3;
field4 = f4;
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
ObjectInputStream.GetField pfields = ois.readFields();
field1 = (Integer) pfields.get("field1", Integer.valueOf(100));
field2 = pfields.get("field2", 99.99);
/* These fields must be present in the stream */
try {
field3 = pfields.get("field3", 99);
System.out.println("Passes test 2a");
} catch(IllegalArgumentException e) {
throw new Error("data field: field3 not in the persistent stream");
}
try {
field4 = (String) pfields.get("field4", "Default string");
System.out.println("Passes test 2b");
} catch(IllegalArgumentException e) {
throw new Error("data field: field4 not in the persistent stream");
}
}
};
class TestClass3 implements Serializable{
private static final long serialVersionUID = 1L;
// Not of type ObjectStreamField
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private final String[] serialPersistentFields = {"Foo","Foobar"};;
Integer field1;
double field2;
int field3;
String field4;
public TestClass3(Integer f1, double f2, int f3, String f4) {
field1 = f1;
field2 = f2;
field3 = f3;
field4 = f4;
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
ObjectInputStream.GetField pfields = ois.readFields();
field1 = (Integer) pfields.get("field1", Integer.valueOf(100));
field2 = pfields.get("field2", 99.99);
field3 = pfields.get("field3", 99);
field4 = (String) pfields.get("field4", "Default string");
try {
String[] tserialPersistentFields =
(String[])pfields.get("serialPersistentFields", null);
System.out.println("Passes test 3");
} catch(IllegalArgumentException e) {
throw new Error("non-static field: " +
"serialPersistentFields must be in the persistent stream");
}
}
};
class TestClass4 implements Serializable {
private static final long serialVersionUID = 1L;
// Correct format
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("field1", Integer.class),
new ObjectStreamField("field2", Double.TYPE),
};
Integer field1;
double field2;
int field3;
String field4;
public TestClass4(Integer f1, double f2, int f3, String f4) {
field1 = f1;
field2 = f2;
field3 = f3;
field4 = f4;
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
ObjectInputStream.GetField pfields = ois.readFields();
field1 = (Integer) pfields.get("field1", Integer.valueOf(100));
field2 = pfields.get("field2", 99.99);
try {
field3 = pfields.get("field3", 99);
throw new Error("data field: field3 in the persistent stream");
} catch(IllegalArgumentException e) {
System.out.println("Passes test 4a");
}
try {
field4 = (String) pfields.get("field4", "Default string");
throw new Error("data field: field4 in the persistent stream");
} catch(IllegalArgumentException e) {
System.out.println("Passes test 4b");
}
}
};
public class CheckModifiers {
public static void main(String[] args)
throws ClassNotFoundException, IOException{
TestClass1 tc1 = new TestClass1(100, 25.56, 2000,
new String("Test modifiers of serialPersistentFields"));
TestClass2 tc2 = new TestClass2(100, 25.56, 2000,
new String("Test modifiers of serialPersistentFields"));
TestClass3 tc3 = new TestClass3(100, 25.56, 2000,
new String("Test Type of serialPersistentFields"));
TestClass4 tc4 = new TestClass4(100, 25.56, 2000,
new String("Test modifiers of serialPersistentFields"));
FileOutputStream fos = new FileOutputStream("fields.ser");
try {
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("Writing obj 1");
oos.writeObject(tc1);
System.out.println("Writing obj 2");
oos.writeObject(tc2);
System.out.println("Writing obj 3");
oos.writeObject(tc3);
System.out.println("Writing obj 4");
oos.writeObject(tc4);
oos.flush();
} finally {
fos.close();
}
FileInputStream fis = new FileInputStream("fields.ser");
try {
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println("Test modifiers for serialPeristentFields ");
System.out.println("---------------------------------------- ");
System.out.println("Declaration missing final modifier");
ois.readObject();
System.out.println();
System.out.println("Declaration with public instead of private access");
ois.readObject();
System.out.println();
System.out.println("Declaration with different type");
ois.readObject();
System.out.println();
System.out.println("Declaration as in specification");
ois.readObject();
} finally {
fis.close();
}
}
};

View file

@ -0,0 +1,27 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
public class A {
int field1;
};

View file

@ -0,0 +1,27 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
public class A {
int field1;
int field2;
};

View file

@ -0,0 +1,115 @@
/*
* Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4075221
* @library /test/lib
* @build jdk.test.lib.compiler.CompilerUtils
* jdk.test.lib.Utils
* jdk.test.lib.Asserts
* jdk.test.lib.JDKToolFinder
* jdk.test.lib.JDKToolLauncher
* jdk.test.lib.Platform
* jdk.test.lib.process.*
* @run junit/timeout=300 NonSerializableTest
* @summary Enable serialize of nonSerializable Class descriptor.
*/
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import jdk.test.lib.compiler.CompilerUtils;
import jdk.test.lib.process.ProcessTools;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class NonSerializableTest {
@BeforeAll
public static void setup() throws Exception {
boolean b = CompilerUtils.compile(
Paths.get(System.getProperty("test.src"), "TestEntry.java"),
Paths.get(System.getProperty("user.dir")));
assertTrue(b, "Compilation failed");
}
// Test cases to compile and run
public static Stream<List<String>> provider() {
return Stream.of(
// Write NonSerial1, Read NonSerial1
List.of("NonSerialA_1", "-cp", ".", "TestEntry", "-s", "A"),
List.of("NonSerialA_1", "-cp", ".", "TestEntry", "-d"),
// Write NonSerial1, Read NonSerial2
List.of("NonSerialA_1", "-cp", ".", "TestEntry", "-s", "A"),
List.of("NonSerialA_2", "-cp", ".", "TestEntry", "-d"),
// Write NonSerial1, Read Serial1
List.of("NonSerialA_1", "-cp", ".", "TestEntry", "-s", "A"),
List.of("SerialA_1", "-cp", ".", "TestEntry", "-d"),
// Write Serial1, Read NonSerial1
List.of("SerialA_1", "-cp", ".", "TestEntry", "-s", "A"),
List.of("NonSerialA_1", "-cp", ".", "TestEntry", "-doe"),
// Write Serial1, Read Serial2
List.of("SerialA_1", "-cp", ".", "TestEntry", "-s", "A"),
List.of("SerialA_2", "-cp", ".", "TestEntry", "-d"),
// Write Serial2, Read Serial1
List.of("SerialA_2", "-cp", ".", "TestEntry", "-s", "A"),
List.of("SerialA_1", "-cp", ".", "TestEntry", "-d"),
// Write Serial1, Read Serial3
List.of("SerialA_1", "-cp", ".", "TestEntry", "-s", "A"),
List.of("SerialA_3", "-cp", ".", "TestEntry", "-de"),
// Write Serial3, Read Serial1
List.of("SerialA_3", "-cp", ".", "TestEntry", "-s", "A"),
List.of("SerialA_1", "-cp", ".", "TestEntry", "-de"));
}
@ParameterizedTest
@MethodSource("provider")
public void test(List<String> argList) throws Exception {
String[] args = argList.toArray(new String[0]);
boolean b = CompilerUtils.compile(Paths.get(System.getProperty("test.src"), args[0]),
Paths.get(System.getProperty("user.dir")));
assertTrue(b, "Compilation failed");
String[] params = Arrays.copyOfRange(args, 1, args.length);
ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(params);
try (Process p = ProcessTools.startProcess("Serializable Test", pb)) {
int exitValue = p.waitFor();
assertEquals(0, exitValue, "Test failed");
}
}
}

View file

@ -0,0 +1,28 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.Serializable;
public class A implements Serializable {
int field1;
};

View file

@ -0,0 +1,31 @@
/*
* Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.Serializable;
public class A implements Serializable {
private static final long serialVersionUID = 746945609796141988L;
int field1;
int field2;
};

View file

@ -0,0 +1,31 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.Serializable;
/* THis class is purposely not compatible with previous versions of class.*/
public class A implements Serializable {
int field1;
int field2;
int field3;
};

View file

@ -0,0 +1,87 @@
/*
* Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4075221
* @summary Enable serialize of nonSerializable Class descriptor.
*/
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
class TestEntry {
public static void main(String args[]) throws Exception {
File f = new File("tmp.ser");
if (args[0].compareTo("-s") == 0) {
FileOutputStream of = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(of);
Class cl = Class.forName(args[1]);
oos.writeObject(cl);
if (ObjectStreamClass.lookup(cl) != null)
oos.writeObject(cl.newInstance());
oos.close();
System.out.println("Serialized Class " + cl.getName());
} else if (args[0].compareTo("-de") == 0) {
FileInputStream inf = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(inf);
Class cl = null;
try {
cl = (Class)ois.readObject();
throw new Error("Expected InvalidClassException to be thrown");
} catch (InvalidClassException e) {
System.out.println("Caught expected exception DeSerializing class " + e.getMessage());
}
ois.close();
} else if (args[0].compareTo("-doe") == 0) {
FileInputStream inf = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(inf);
Class cl = null;
cl = (Class)ois.readObject();
try {
ois.readObject();
throw new Error("Expected InvalidClassException to be thrown");
} catch (InvalidClassException e) {
System.out.println("Caught expected exception DeSerializing class " + e.getMessage());
}
ois.close();
} else if (args[0].compareTo("-d") == 0) {
FileInputStream inf = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(inf);
Class cl = (Class)ois.readObject();
try {
ois.readObject();
} catch (EOFException e) {
}
ois.close();
System.out.println("DeSerialized Class " + cl.getName());
} else {
throw new RuntimeException("Unrecognized argument");
}
}
}

View file

@ -0,0 +1,38 @@
/*
* Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4632671
* @summary Verify that reading an object whose class descriptor has both
* SC_SERIALIZABLE and SC_EXTERNALIZABLE bits set results in an
* InvalidClassException.
*/
import java.io.*;
public class Foo implements Externalizable {
private static final long serialVersionUID = 1L;
public void writeExternal(ObjectOutput out) throws IOException {}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {}
}

View file

@ -0,0 +1,57 @@
/*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4632671
* @summary Verify that reading an object whose class descriptor has both
* SC_SERIALIZABLE and SC_EXTERNALIZABLE bits set results in an
* InvalidClassException.
*
* @build Foo
* @run main/othervm Read
*/
import java.io.*;
public class Read {
public static void main(String[] args) throws Exception {
try {
/*
* Foo.ser contains a doctored serialized representation of an
* instance of class Foo, in which both SC_SERIALIZABLE and
* SC_EXTERNALIZABLE flags have been set for Foo's class
* descriptor.
*/
File f = new File(System.getProperty("test.src", "."), "Foo.ser");
FileInputStream in = new FileInputStream(f);
try {
new ObjectInputStream(in).readObject();
throw new Error(
"read succeeded for object whose class descriptor has " +
"both SC_SERIALIZABLE and SC_EXTERNALIZABLE flags set");
} finally {
in.close();
}
} catch (InvalidClassException e) {
}
}
}

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4180735
* @clean Foo GetField
* @build GetField
* @run main GetField
*
* @summary Make sure that getField() of ObjectStreamClass works correctly for
* object types.
*/
import java.io.*;
public class GetField implements Serializable{
private static final long serialVersionUID = 1L;
String str;
int i;
public static void main(String[] args) throws Exception {
ObjectStreamClass cl = ObjectStreamClass.lookup(GetField.class);
if (cl == null)
throw new RuntimeException("Cannot resolve class : GetField");
if (cl.getField("str") == null)
throw new RuntimeException(
"ObjectStreamClass.getField() failed for object type");
if (cl.getField("i") == null)
throw new RuntimeException(
"ObjectStreamClass.getField() failed for primitive type");
}
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4931314
* @summary Verify that a ClassNotFoundException thrown by the
* readClassDescriptor method is reflected to the caller as an
* InvalidClassException with the ClassNotFoundException as its cause.
*/
import java.io.*;
class CNFInputStream extends ObjectInputStream {
CNFInputStream(InputStream in) throws IOException {
super(in);
}
protected ObjectStreamClass readClassDescriptor()
throws IOException, ClassNotFoundException
{
throw new ClassNotFoundException("foobar");
}
}
public class CNFException {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(5);
oout.close();
ObjectInputStream oin =
new CNFInputStream(new ByteArrayInputStream(bout.toByteArray()));
try {
oin.readObject();
throw new Error("expected InvalidClassException");
} catch (InvalidClassException e) {
Throwable cause = e.getCause();
if (!(cause instanceof ClassNotFoundException)) {
throw new Error(
"expected ClassNotFoundException as cause, not " + cause);
}
}
}
}

View file

@ -0,0 +1,152 @@
/*
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4227189
* @summary Ensure that class descriptor read, write hooks exist, are backwards
* compatible, and work as advertised.
*/
import java.io.*;
import java.util.*;
class Foo implements Serializable {
private static final long serialVersionUID = 1L;
Short s = (short) 1;
Integer i = 2;
Long l = 3L;
public boolean equals(Object obj) {
if (obj instanceof Foo) {
Foo ofoo = (Foo) obj;
return s.equals(ofoo.s) && i.equals(ofoo.i) && l.equals(ofoo.l);
}
return false;
}
public int hashCode() {
return i;
}
}
class CustomOutputStream extends ObjectOutputStream {
boolean hookCalled = false;
CustomOutputStream(OutputStream out) throws IOException {
super(out);
useProtocolVersion(PROTOCOL_VERSION_2);
}
protected void writeClassDescriptor(ObjectStreamClass desc)
throws IOException
{
writeUTF(desc.getName());
hookCalled = true;
}
}
class CustomInputStream extends ObjectInputStream {
boolean hookCalled = false;
CustomInputStream(InputStream in) throws IOException {
super(in);
}
protected ObjectStreamClass readClassDescriptor()
throws IOException, ClassNotFoundException
{
hookCalled = true;
return ObjectStreamClass.lookup(Class.forName(readUTF()));
}
}
public class ClassDescHooks implements ObjectStreamConstants {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout;
ByteArrayInputStream bin;
ObjectOutputStream oout;
ObjectInputStream oin;
FileInputStream fin;
File foof;
CustomOutputStream cout;
CustomInputStream cin;
// test for backwards compatibility
bout = new ByteArrayOutputStream();
foof = new File(System.getProperty("test.src", "."), "Foo.ser");
fin = new FileInputStream(foof);
try {
while (fin.available() > 0)
bout.write(fin.read());
} finally {
fin.close();
}
byte[] buf1 = bout.toByteArray();
bout = new ByteArrayOutputStream();
oout = new ObjectOutputStream(bout);
Foo foo = new Foo();
oout.writeObject(foo);
oout.flush();
byte[] buf2 = bout.toByteArray();
if (! Arrays.equals(buf1, buf2))
throw new Error("Incompatible stream format (write)");
Foo foocopy;
fin = new FileInputStream(foof);
try {
oin = new ObjectInputStream(fin);
foocopy = (Foo) oin.readObject();
if (! foo.equals(foocopy))
throw new Error("Incompatible stream format (read)");
} finally {
fin.close();
}
// make sure write hook not called when old protocol in use
bout = new ByteArrayOutputStream();
cout = new CustomOutputStream(bout);
cout.useProtocolVersion(PROTOCOL_VERSION_1);
cout.writeObject(foo);
if (cout.hookCalled)
throw new Error("write descriptor hook should not be called");
// write custom class descriptor representations
bout = new ByteArrayOutputStream();
cout = new CustomOutputStream(bout);
cout.writeObject(foo);
cout.flush();
bin = new ByteArrayInputStream(bout.toByteArray());
cin = new CustomInputStream(bin);
foocopy = (Foo) cin.readObject();
if (! cout.hookCalled)
throw new Error("write descriptor hook never called");
if (! cin.hookCalled)
throw new Error("read descriptor hook never called");
if (! foo.equals(foocopy))
throw new Error("serialization failed when hooks active");
}
}

View file

@ -0,0 +1,127 @@
/*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4461737
* @summary Verify that serialization functions properly for externalizable
* classes if ObjectInputStream.readClassDescriptor() returns a local
* class descriptor.
*/
import java.io.*;
import java.util.*;
class LoopbackOutputStream extends ObjectOutputStream {
LinkedList<ObjectStreamClass> descs;
LoopbackOutputStream(OutputStream out, LinkedList<ObjectStreamClass> descs)
throws IOException
{
super(out);
this.descs = descs;
}
protected void writeClassDescriptor(ObjectStreamClass desc)
throws IOException
{
descs.add(desc);
}
}
class LoopbackInputStream extends ObjectInputStream {
LinkedList<ObjectStreamClass> descs;
LoopbackInputStream(InputStream in, LinkedList<ObjectStreamClass> descs) throws IOException {
super(in);
this.descs = descs;
}
protected ObjectStreamClass readClassDescriptor()
throws IOException, ClassNotFoundException
{
return descs.removeFirst();
}
}
public class ExternLoopback implements Externalizable {
private static final long serialVersionUID = 1L;
String a, b, c;
public ExternLoopback() {
}
ExternLoopback(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeBoolean(false);
out.writeObject(a);
out.writeObject(b);
out.writeObject(c);
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
in.readBoolean();
a = (String) in.readObject();
b = (String) in.readObject();
c = (String) in.readObject();
}
public boolean equals(Object obj) {
if (!(obj instanceof ExternLoopback)) {
return false;
}
ExternLoopback other = (ExternLoopback) obj;
return streq(a, other.a) && streq(b, other.b) && streq(c, other.c);
}
public int hashCode() {
return a.hashCode();
}
static boolean streq(String s1, String s2) {
return (s1 != null) ? s1.equals(s2) : (s2 == null);
}
public static void main(String[] args) throws Exception {
ExternLoopback lb = new ExternLoopback("foo", "bar", "baz");
LinkedList<ObjectStreamClass> descs = new LinkedList<>();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
LoopbackOutputStream lout = new LoopbackOutputStream(bout, descs);
lout.writeObject(lb);
lout.close();
LoopbackInputStream lin = new LoopbackInputStream(
new ByteArrayInputStream(bout.toByteArray()), descs);
ExternLoopback lbcopy = (ExternLoopback) lin.readObject();
if (!lb.equals(lbcopy)) {
throw new Error();
}
}
}

Binary file not shown.

View file

@ -0,0 +1,90 @@
/*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4461299
* @summary Verify that serialization functions properly if
* ObjectInputStream.readClassDescriptor() returns a local class
* descriptor for which the serialVersionUID has not yet been
* calculated.
*/
import java.io.*;
import java.util.*;
class LoopbackOutputStream extends ObjectOutputStream {
LinkedList<ObjectStreamClass> descs;
LoopbackOutputStream(OutputStream out, LinkedList<ObjectStreamClass> descs)
throws IOException
{
super(out);
this.descs = descs;
}
protected void writeClassDescriptor(ObjectStreamClass desc)
throws IOException
{
descs.add(desc);
}
}
class LoopbackInputStream extends ObjectInputStream {
LinkedList<ObjectStreamClass> descs;
LoopbackInputStream(InputStream in, LinkedList<ObjectStreamClass> descs) throws IOException {
super(in);
this.descs = descs;
}
protected ObjectStreamClass readClassDescriptor()
{
return descs.removeFirst();
}
}
public class Loopback implements Serializable {
private static final long serialVersionUID = 1L;
String str;
Loopback(String str) {
this.str = str;
}
public static void main(String[] args) throws Exception {
Loopback lb = new Loopback("foo");
LinkedList<ObjectStreamClass> descs = new LinkedList<>();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
LoopbackOutputStream lout = new LoopbackOutputStream(bout, descs);
lout.writeObject(lb);
lout.close();
LoopbackInputStream lin = new LoopbackInputStream(
new ByteArrayInputStream(bout.toByteArray()), descs);
Loopback lbcopy = (Loopback) lin.readObject();
if (!lb.str.equals(lbcopy.str)) {
throw new Error();
}
}
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4332184
* @summary Ensure that ObjectOutputStream properly releases strong references
* to written objects when reset() is called.
*/
import java.io.*;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ClearHandleTable {
private static final int TIMES = 1000;
public static void main(String[] args) throws Exception {
final int nreps = 100;
ObjectOutputStream oout =
new ObjectOutputStream(new ByteArrayOutputStream());
List<WeakReference<?>> refs = new ArrayList<>(nreps);
for (int i = 0; i < nreps; i++) {
String str = new String("blargh");
oout.writeObject(str);
refs.add(new WeakReference<Object>(str));
}
oout.reset();
int count = 0;
for (int i=0; i<TIMES; i++) {
// relying on, possibly multiple, System.gc calls to clear weak references
System.gc();
Iterator<WeakReference<?>> itr = refs.iterator();
while(itr.hasNext()) {
WeakReference<?> ref = itr.next();
if (ref.get() == null) {
itr.remove();
}
}
if (refs.isEmpty())
break;
Thread.sleep(20);
count++;
if (count % 10 == 0)
System.out.println("Looping " + count + " times");
}
if (!refs.isEmpty()) {
throw new Error("failed to garbage collect object");
}
}
}

View file

@ -0,0 +1,90 @@
/*
* Copyright (c) 2010, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 6990094
* @summary Verify ObjectInputStream.cloneArray works on many kinds of arrays
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
public class CloneArray {
static Object replacement;
static class Resolver implements Serializable {
private static final long serialVersionUID = 1L;
private Object readResolve() throws ObjectStreamException {
return replacement;
}
}
private static void test(Object rep)
throws IOException, ClassNotFoundException {
try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
try(ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(new Resolver());
oos.writeObject(new Resolver());
}
Object o1;
Object o2;
try(ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais)) {
replacement = rep;
o1 = ois.readUnshared();
o2 = ois.readUnshared();
}
if (o1 == o2)
throw new AssertionError("o1 and o2 must not be identical");
}
}
public static void main(String[] args)
throws IOException, ClassNotFoundException {
Object[] replacements = {
new byte[] {1},
new char[] {'2'},
new short[] {3},
new int[] {4},
new long[] {5},
new float[] {6.0f},
new double[] {7.0},
new boolean[] {true},
new Object[] {"A string."}
};
for(Object replacement : replacements) {
test(replacement);
}
}
}

View file

@ -0,0 +1,140 @@
/*
* Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @summary Verify that concurrent class descriptor lookups function properly,
* even when class descriptor initialization is slow or throws an
* exception.
*/
import java.io.*;
import java.util.concurrent.CountDownLatch;
class Good implements Serializable {
private static final long serialVersionUID = 6319710844400051132L;
static {
try { Thread.sleep(1000); } catch (InterruptedException ex) {}
}
}
class Bad implements Serializable {
// explicit suid triggers class initialization during classdesc lookup
private static final long serialVersionUID = 0xBAD;
static {
try { Thread.sleep(1000); } catch (InterruptedException ex) {}
if ("foo".equals("foo")) {
throw new RuntimeException();
}
}
}
class SuccessfulLookup extends Thread {
Class<?> cl;
long suid;
final CountDownLatch lookupLatch;
boolean ok;
SuccessfulLookup(Class<?> cl, long suid, CountDownLatch lookupLatch) {
this.cl = cl;
this.suid = suid;
this.lookupLatch = lookupLatch;
}
public void run() {
lookupLatch.countDown(); // let others know we are ready
try {
lookupLatch.await(); // await for others
} catch (InterruptedException ex) {}
for (int i = 0; i < 100; i++) {
if (ObjectStreamClass.lookup(cl).getSerialVersionUID() != suid) {
return;
}
}
ok = true;
}
}
class FailingLookup extends Thread {
Class<?> cl;
final CountDownLatch lookupLatch;
boolean ok;
FailingLookup(Class<?> cl, CountDownLatch lookupLatch) {
this.cl = cl;
this.lookupLatch = lookupLatch;
}
public void run() {
lookupLatch.countDown(); // let others know we are ready
try {
lookupLatch.await(); // await for others
} catch (InterruptedException ex) {}
for (int i = 0; i < 100; i++) {
try {
ObjectStreamClass.lookup(cl);
return;
} catch (Throwable th) {
}
}
ok = true;
}
}
public class ConcurrentClassDescLookup {
public static void main(String[] args) throws Exception {
ClassLoader loader = ConcurrentClassDescLookup.class.getClassLoader();
Class<?> cl = Class.forName("Good", false, loader);
int numSuccessfulLookups = 50;
CountDownLatch sLookupLatch = new CountDownLatch(numSuccessfulLookups);
SuccessfulLookup[] slookups = new SuccessfulLookup[numSuccessfulLookups];
for (int i = 0; i < slookups.length; i++) {
slookups[i] = new SuccessfulLookup(cl, 6319710844400051132L, sLookupLatch);
slookups[i].start();
}
System.out.println("awaiting completion of " + slookups.length + " SuccessfulLookup");
for (int i = 0; i < slookups.length; i++) {
slookups[i].join();
if (!slookups[i].ok) {
throw new Error();
}
}
System.out.println("all " + slookups.length + " SuccessfulLookup completed");
cl = Class.forName("Bad", false, loader);
int numFailingLookups = 50;
CountDownLatch fLookupLatch = new CountDownLatch(numFailingLookups);
FailingLookup[] flookups = new FailingLookup[numFailingLookups];
for (int i = 0; i < flookups.length; i++) {
flookups[i] = new FailingLookup(cl, fLookupLatch);
flookups[i].start();
}
System.out.println("awaiting completion of " + flookups.length + " FailingLookup");
for (int i = 0; i < flookups.length; i++) {
flookups[i].join();
if (!flookups[i].ok) {
throw new Error();
}
}
System.out.println("all " + flookups.length + " FailingLookup completed");
}
}

View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4450867
* @summary Although technically the behavior of ObjectInputStream following a
* UTFDataFormatException is unspecified, verify that
* ObjectInputStream consumes at most the expected number of utf
* bytes, even if the last byte(s) of the utf string indicate that the
* string overflows its expected length.
* @key randomness
*/
import java.io.*;
import java.util.Random;
public class CorruptedUTFConsumption {
static Random rand = new Random(System.currentTimeMillis());
public static void main(String[] args) throws Exception {
StringBuffer sbuf = new StringBuffer();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
for (int i = 0; i < 1200; i++) {
sbuf.append(i % 10);
bout.reset();
dout.writeUTF(sbuf.toString());
byte[] utf = bout.toByteArray();
// set last byte to first byte of 2-char sequence
utf[utf.length - 1] = (byte) (0xC0 | rand.nextInt() & 0x1F);
checkConsume(utf);
// set last byte to first byte of 3-char sequence
utf[utf.length - 1] = (byte) (0xE0 | rand.nextInt() & 0x0F);
checkConsume(utf);
if (utf.length >= 4) { // don't touch utf length bytes
// set last 2 bytes to first, second byte of 3-char sequence
utf[utf.length - 2] = (byte) (0xE0 | rand.nextInt() & 0x0F);
utf[utf.length - 1] = (byte) (0x80 | rand.nextInt() & 0x3F);
checkConsume(utf);
}
}
}
static void checkConsume(byte[] utf) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.write(utf);
oout.writeByte(0); // leave one byte of padding
oout.close();
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
try {
oin.readUTF();
throw new Error();
} catch (UTFDataFormatException ex) {
}
// if readUTF consumed padding byte, readByte will throw EOFException
oin.readByte();
}
}

View file

@ -0,0 +1,155 @@
/*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4360508
* @summary Verify that a custom readObject() method reading in data written
* via default serialization cannot read past the end of the default
* data.
*/
import java.io.*;
class A implements Serializable {
private static final long serialVersionUID = 1L;
int i1 = 1, i2 = 2;
String s1 = "foo", s2 = "bar";
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
if (in.read() != -1) {
throw new Error();
}
try {
in.readInt();
throw new Error();
} catch (EOFException ex) {
}
try {
in.readObject();
throw new Error();
} catch (OptionalDataException ex) {
if (!ex.eof) {
throw new Error();
}
}
try {
in.readUnshared();
throw new Error();
} catch (OptionalDataException ex) {
if (!ex.eof) {
throw new Error();
}
}
}
}
class B implements Serializable {
private static final long serialVersionUID = 1L;
int i1 = 1, i2 = 2;
String s1 = "foo", s2 = "bar";
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.readFields();
try {
in.readObject();
throw new Error();
} catch (OptionalDataException ex) {
if (!ex.eof) {
throw new Error();
}
}
try {
in.readUnshared();
throw new Error();
} catch (OptionalDataException ex) {
if (!ex.eof) {
throw new Error();
}
}
if (in.read() != -1) {
throw new Error();
}
try {
in.readInt();
throw new Error();
} catch (EOFException ex) {
}
}
}
class C implements Serializable {
private static final long serialVersionUID = 1L;
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
try {
in.readObject();
throw new Error();
} catch (OptionalDataException ex) {
if (!ex.eof) {
throw new Error();
}
}
try {
in.readUnshared();
throw new Error();
} catch (OptionalDataException ex) {
if (!ex.eof) {
throw new Error();
}
}
if (in.read() != -1) {
throw new Error();
}
try {
in.readInt();
throw new Error();
} catch (EOFException ex) {
}
}
}
public class DefaultDataEnd {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(new A());
oout.writeObject(new B());
oout.writeObject(new C());
oout.close();
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
oin.readObject();
oin.readObject();
oin.readObject();
}
}

View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4662327
* @summary Verify that ObjectInputStream.defaultReadObject() throws a
* ClassNotFoundException if any of the non-primitive field values it
* reads in are tagged with ClassNotFoundExceptions.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 1L;
@SuppressWarnings("serial") /* Incorrect use is being tested */
Object obj = new Bar();
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
if (obj == null) {
throw new Error(
"ClassNotFoundException masked by defaultReadObject()");
}
}
}
class Bar implements Serializable {
private static final long serialVersionUID = 1L;
}
class TestObjectInputStream extends ObjectInputStream {
TestObjectInputStream(InputStream in) throws IOException { super(in); }
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException
{
if (desc.getName().equals(Bar.class.getName())) {
throw new ClassNotFoundException();
}
return super.resolveClass(desc);
}
}
public class DefaultReadObjectCNFException {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(new Foo());
oout.writeObject("after");
oout.close();
ObjectInputStream oin = new TestObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
try {
oin.readObject();
} catch (ClassNotFoundException e) {
// expected
}
if (!oin.readObject().equals("after")) {
throw new Error("subsequent object corrupted");
}
}
}

View file

@ -0,0 +1,111 @@
/*
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4180735
* @summary Make sure that fields that are defaulted can be of primitive and
* object type.
*
*/
import java.io.*;
class TestClass implements Serializable {
public static final Integer DEFAULT_OBJECT_I = 99;
public static final Foo DEFAULT_OBJECT_F = new Foo();
private static final long serialVersionUID = 5748652654655279289L;
// Fields to be serialized.
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("objectI", Integer.class),
new ObjectStreamField("primitiveI", Integer.TYPE),
new ObjectStreamField("foo", Foo.class)
};
Integer objectI;
int primitiveI;
Foo foo;
public TestClass(Foo f, Integer I, int i) {
foo = f;
objectI = I;
primitiveI = i;
}
/**
* Verify GetField.defaulted("fieldName") works for primitive and
* object fields.
*/
private void readObject(ObjectInputStream in)
throws ClassNotFoundException, IOException
{
ObjectInputStream.GetField pfields = in.readFields();
primitiveI = pfields.get("primitiveI", 99);
System.out.println("The primitiveI : " + primitiveI);
objectI = (Integer)pfields.get("objectI", DEFAULT_OBJECT_I);
System.out.println("The ObjectI : " + objectI);
foo = (Foo)pfields.get("foo", DEFAULT_OBJECT_F);
System.out.println("The foo : " + foo);
try {
boolean b = pfields.defaulted("primitiveI");
System.out.println("Defaulted prim : " + b);
if (b == false) {
throw new Error("Bad return value for defaulted() with " +
"primitive type fields");
}
b = pfields.defaulted("objectI");
System.out.println("Defaulted ObjectI : " + b);
if (b == true) {
throw new Error("Bad return value for defaulted() with " +
"object type fields");
}
b = pfields.defaulted("foo");
System.out.println("Defaulted Foo : " + b);
if (b == false) {
throw new Error("Bad return value for defaulted() with " +
"object type fields");
}
} catch (IllegalArgumentException e) {
System.out.println("Exception " + e.getMessage() +
": handled calling " +
"GetField.defaulted(\"fieldName referring to an object\")");
throw e;
}
}
};
public class GetFieldRead {
public static void main(String[] args)
throws ClassNotFoundException, IOException
{
FileInputStream fis = new FileInputStream("data.ser");
ObjectInputStream in = new ObjectInputStream(fis);
TestClass obj = (TestClass) in.readObject();
in.close();
}
};

View file

@ -0,0 +1,90 @@
/*
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4180735
*
* @clean GetFieldWrite Foo TestClass
* @build GetFieldWrite
* @run main GetFieldWrite
* @clean GetFieldRead TestClass
* @build GetFieldRead
* @run main GetFieldRead
*
* @summary Make sure that fields that are defaulted can be of primitive and
* object type.
*
*/
import java.io.*;
class TestClass implements Serializable {
private static final long serialVersionUID = 5748652654655279289L;
// Fields to be serialized.
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("objectI", Integer.class)};
Integer objectI;
int primitiveI;
Foo foo;
public TestClass(Foo f, Integer I, int i) {
foo = f;
objectI = I;
primitiveI = i;
}
};
public class GetFieldWrite {
public static void main(String[] args)
throws ClassNotFoundException, IOException
{
FileOutputStream fos = new FileOutputStream("data.ser");
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(new TestClass(new Foo(100, 200), 100, 200));
out.close();
}
};
/*
* Test class to be used as data field
*/
class Foo implements Serializable{
private static final long serialVersionUID = 1L;
int a;
int b;
public Foo() {
a = 10; b= 20;
}
public Foo(int a1, int b1)
{
a = a1; b = b1;
}
public String toString() {
return new String("a = " + a + " b = " + b);
}
}

View file

@ -0,0 +1,57 @@
/*
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4764280
* @summary Verify that if a serializable class declares multiple
* serialPersistentFields that share the same name, calling
* ObjectStreamClass.lookup() for that class will not result in an
* InternalError, and that attempts at default serialization or
* deserialization of such a class will result in
* InvalidClassExceptions.
*/
import java.io.*;
class A implements Serializable {
private static final long serialVersionUID = 0L;
int i;
}
class B implements Serializable {
private static final long serialVersionUID = 0L;
int i;
}
public class Setup {
public static void main(String[] args) throws Exception {
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream("a.ser"));
oout.writeObject(new A());
oout.close();
oout = new ObjectOutputStream(new FileOutputStream("b.ser"));
oout.writeObject(new B());
oout.close();
}
}

View file

@ -0,0 +1,107 @@
/*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4764280
*
* @clean Setup Test A B
* @compile Setup.java
* @run main Setup
* @clean Setup A B
* @compile Test.java
* @run main Test
*
* @summary Verify that if a serializable class declares multiple
* serialPersistentFields that share the same name, calling
* ObjectStreamClass.lookup() for that class will not result in an
* InternalError, and that attempts at default serialization or
* deserialization of such a class will result in
* InvalidClassExceptions.
*/
import java.io.*;
class A implements Serializable {
private static final long serialVersionUID = 0L;
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("i", int.class),
new ObjectStreamField("i", int.class)
};
int i;
}
class B implements Serializable {
private static final long serialVersionUID = 0L;
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("i", int.class),
new ObjectStreamField("i", String.class)
};
int i;
}
public class Test {
public static void main(String[] args) throws Exception {
ObjectStreamClass.lookup(A.class);
ObjectStreamClass.lookup(B.class);
ObjectOutputStream oout =
new ObjectOutputStream(new ByteArrayOutputStream());
try {
oout.writeObject(new A());
throw new Error(
"write of A should fail with InvalidClassException");
} catch (InvalidClassException e) {
}
oout = new ObjectOutputStream(new ByteArrayOutputStream());
try {
oout.writeObject(new B());
throw new Error(
"write of B should fail with InvalidClassException");
} catch (InvalidClassException e) {
}
FileInputStream in = new FileInputStream("a.ser");
try {
ObjectInputStream oin = new ObjectInputStream(in);
oin.readObject();
throw new Error(
"read of A should fail with InvalidClassException");
} catch (InvalidClassException e) {
} finally {
in.close();
}
in = new FileInputStream("b.ser");
try {
ObjectInputStream oin = new ObjectInputStream(in);
oin.readObject();
throw new Error(
"read of B should fail with InvalidClassException");
} catch (InvalidClassException e) {
} finally {
in.close();
}
}
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4838379
* @summary Verify that serialization of enum constant arrays functions
* properly.
*/
import java.io.*;
import java.util.Arrays;
enum Foo { klaatu, barada { int i = 1; }, nikto }
public class Test {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
Foo[] fa = Foo.values();
Object[] oa = Arrays.asList(fa).toArray();
oout.writeObject(oa);
oout.writeObject(fa);
oout.close();
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
Object[] oa2 = (Object[]) oin.readObject();
if (!elementsIdentical(oa, oa2)) {
throw new Error("arrays differ: " +
Arrays.asList(oa) + ", " + Arrays.asList(oa2));
}
Foo[] fa2 = (Foo[]) oin.readObject();
if (!elementsIdentical(fa, fa2)) {
throw new Error("arrays differ: " +
Arrays.asList(fa) + ", " + Arrays.asList(fa2));
}
}
static boolean elementsIdentical(Object[] a1, Object[] a2) {
if (a1.length != a2.length) {
return false;
}
for (int i = 0; i < a1.length; i++) {
if (a1[i] != a2[i]) {
return false;
}
}
return true;
}
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4838379
* @summary Verify that enum classes present in a serialization stream cannot
* be resolved by the receiver to non-enum classes, and vice-versa.
*/
import java.io.*;
class EnumToNonEnum implements Serializable {
private static final long serialVersionUID = 0L;
}
enum NonEnumToEnum { foo }
public class Read {
public static void main(String[] args) throws Exception {
read("0.ser");
read("1.ser");
read("2.ser");
read("3.ser");
}
static void read(String filename) throws Exception {
FileInputStream in = new FileInputStream(filename);
try {
ObjectInputStream oin = new ObjectInputStream(in);
Object obj = oin.readObject();
throw new Error("read of " + obj + " should not have succeeded");
} catch (InvalidClassException e) {
System.out.println("caught expected exception " + e);
} finally {
in.close();
}
}
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4838379
* @summary Verify that enum classes present in a serialization stream cannot
* be resolved by the receiver to non-enum classes, and vice-versa.
*
* @compile Write.java
* @run main Write
* @clean Write
* @compile Read.java
* @run main Read
* @clean Read
*/
import java.io.*;
enum EnumToNonEnum { foo }
class NonEnumToEnum implements Serializable {
private static final long serialVersionUID = 0L;
}
public class Write {
public static void main(String[] args) throws Exception {
write(EnumToNonEnum.class, "0.ser");
write(NonEnumToEnum.class, "1.ser");
write(EnumToNonEnum.foo, "2.ser");
write(new NonEnumToEnum(), "3.ser");
}
static void write(Object obj, String filename) throws Exception {
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream(filename));
oout.writeObject(obj);
oout.close();
}
}

View file

@ -0,0 +1,51 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4838379
* @summary Verify that basic serialization of non-specialized enum constants
* functions properly.
*/
import java.io.*;
enum Foo { klaatu, barada, nikto }
public class Test {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
for (Foo f : Foo.values()) {
oout.writeObject(f);
}
oout.close();
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
for (Foo f : Foo.values()) {
Object obj = oin.readObject();
if (obj != f) {
throw new Error("expected " + f + ", got " + obj);
}
}
}
}

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4838379
* @summary Verify that serialization of Class objects for enum types works
* properly.
*/
import java.io.*;
enum Foo { foo, bar { int i = 0; }, baz { double d = 3.0; } }
public class Test {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
Class<?>[] classes = { Enum.class, Foo.foo.getClass(),
Foo.bar.getClass(), Foo.baz.getClass() };
for (int i = 0; i < classes.length; i++) {
oout.writeObject(classes[i]);
}
oout.close();
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
for (int i = 0; i < classes.length; i++) {
Object obj = oin.readObject();
if (obj != classes[i]) {
throw new Error("expected " + classes[i] + ", got " + obj);
}
}
}
}

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4838379
* @summary Verify that serialization of enum constants that are instances of
* constant-specific subclasses functions properly.
*/
import java.io.*;
enum Foo {
a,
b { byte b = 3; },
c,
d { double d = 6.0; }
}
public class Read {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("foo.ser");
try {
ObjectInputStream oin = new ObjectInputStream(in);
for (Foo f : Foo.values()) {
Object obj = oin.readObject();
if (obj != f) {
throw new Error("expected " + f + ", got " + obj);
}
}
} finally {
in.close();
}
}
}

View file

@ -0,0 +1,55 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4838379
* @summary Verify that serialization of enum constants that are instances of
* constant-specific subclasses functions properly.
*
* @compile Write.java
* @run main Write
* @clean Write
* @compile Read.java
* @run main Read
* @clean Read
*/
import java.io.*;
enum Foo {
a,
b,
c { int i = 5; },
d { float f = 5.0f; }
}
public class Write {
public static void main(String[] args) throws Exception {
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream("foo.ser"));
for (Foo f : Foo.values()) {
oout.writeObject(f);
}
oout.close();
}
}

View file

@ -0,0 +1,74 @@
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4838379
* @summary Verify that serialVersionUID and serialPersistentFields
* declarations made by enum types and constants are ignored.
*/
import java.io.*;
import java.util.Arrays;
enum Foo {
foo,
bar {
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final long serialVersionUID = 2L;
// bar is implemented as an inner class instance, so the following
// declaration would cause a compile-time error
// private static final ObjectStreamField[] serialPersistentFields = {
// new ObjectStreamField("gub", Float.TYPE)
// };
};
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final long serialVersionUID = 1L;
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("blargh", Integer.TYPE)
};
}
public class Test {
public static void main(String[] args) throws Exception {
Class<?>[] classes =
{ Foo.class, Foo.foo.getClass(), Foo.bar.getClass() };
for (int i = 0; i < classes.length; i++) {
ObjectStreamClass desc = ObjectStreamClass.lookup(classes[i]);
if (desc.getSerialVersionUID() != 0L) {
throw new Error(
classes[i] + " has non-zero serialVersionUID: " +
desc.getSerialVersionUID());
}
ObjectStreamField[] fields = desc.getFields();
if (fields.length > 0) {
throw new Error(
classes[i] + " has non-empty list of fields: " +
Arrays.asList(fields));
}
}
}
}

View file

@ -0,0 +1,93 @@
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4838379
* @summary Verify that custom serialization methods defined by enum types are
* not invoked during serialization or deserialization.
*/
import java.io.*;
enum Foo {
foo,
bar {
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private void writeObject(ObjectOutputStream out) throws IOException {
throw new Error("bar.writeObject invoked");
}
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
throw new Error("bar.readObject invoked");
}
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
Object writeReplace() throws ObjectStreamException {
throw new Error("bar.writeReplace invoked");
}
// readResolve cannot be defined until Enum.readResolve is removed
// Object readResolve() throws ObjectStreamException {
// throw new Error("bar.readResolve invoked");
// }
};
@SuppressWarnings("serial") /* Incorrect use is being tested */
private void writeObject(ObjectOutputStream out) throws IOException {
throw new Error("Foo.writeObject invoked");
}
@SuppressWarnings("serial") /* Incorrect use is being tested */
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
throw new Error("Foo.readObject invoked");
}
@SuppressWarnings("serial") /* Incorrect use is being tested */
Object writeReplace() throws ObjectStreamException {
throw new Error("Foo.writeReplace invoked");
}
// readResolve cannot be defined until Enum.readResolve is removed
// Object readResolve() throws ObjectStreamException {
// throw new Error("Foo.readResolve invoked");
// }
}
public class Test {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
for (Foo f : Foo.values()) {
oout.writeObject(f);
}
oout.close();
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
for (Foo f : Foo.values()) {
Object obj = oin.readObject();
if (obj != f) {
throw new Error("expected " + f + ", got " + obj);
}
}
}
}

View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4838379
* @summary Verify that TC_OBJECT followed by a class descriptor for an enum
* class results in an InvalidClassException, as does TC_ENUM followed
* by a class descriptor for a non-enum class.
*/
import java.io.*;
enum Foo { bar }
class TestObjectOutputStream extends ObjectOutputStream {
static ObjectStreamClass fooDesc = ObjectStreamClass.lookup(Foo.class);
static ObjectStreamClass integerDesc =
ObjectStreamClass.lookup(Integer.class);
TestObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
protected void writeClassDescriptor(ObjectStreamClass desc)
throws IOException
{
if (desc == fooDesc) {
super.writeClassDescriptor(integerDesc);
} else if (desc == integerDesc) {
super.writeClassDescriptor(fooDesc);
} else {
super.writeClassDescriptor(desc);
}
}
}
public class Test {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new TestObjectOutputStream(bout);
oout.writeObject(Foo.bar);
oout.close();
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
try {
Object obj = oin.readObject();
throw new Error("read of " + obj + " should not have succeeded");
} catch (InvalidClassException e) {
System.out.println("caught expected exception " + e);
}
oout = new TestObjectOutputStream(bout = new ByteArrayOutputStream());
oout.writeObject(5);
oout.close();
oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
try {
Object obj = oin.readObject();
throw new Error("read of " + obj + " should not have succeeded");
} catch (InvalidClassException e) {
System.out.println("caught expected exception " + e);
}
}
}

View file

@ -0,0 +1,55 @@
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4838379
* @summary Verify that deserialization of an enum constant that does not exist
* on the receiving side results in an InvalidObjectException.
*/
import java.io.*;
enum Foo { foo, bar }
public class Read {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("foo.ser");
try {
ObjectInputStream oin = new ObjectInputStream(in);
for (Foo f : Foo.values()) {
Object obj = oin.readObject();
if (obj != f) {
throw new Error("expected " + f + ", got " + obj);
}
}
try {
Object obj = oin.readObject();
throw new Error("read of " + obj + " should not succeed");
} catch (InvalidObjectException e) {
System.out.println("caught expected exception: " + e);
}
} finally {
in.close();
}
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4838379
* @summary Verify that deserialization of an enum constant that does not exist
* on the receiving side results in an InvalidObjectException.
*
* @compile Write.java
* @run main Write
* @clean Write
* @compile Read.java
* @run main Read
* @clean Read
*/
import java.io.*;
enum Foo { foo, bar, baz }
public class Write {
public static void main(String[] args) throws Exception {
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream("foo.ser"));
for (Foo f : Foo.values()) {
oout.writeObject(f);
}
oout.close();
}
}

View file

@ -0,0 +1,133 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4838379
* @summary Verify that unshared write and read operations work properly with
* enum constants.
*/
import java.io.*;
enum Foo { foo, bar, baz }
abstract class WriteReadTest {
abstract void write(ObjectOutputStream out) throws Exception;
abstract void read(ObjectInputStream in) throws Exception;
void run() throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
write(oout);
oout.close();
read(new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray())));
}
}
public class Test {
public static void main(String[] args) throws Exception {
WriteReadTest[] tests = {
new WriteReadTest() {
void write(ObjectOutputStream out) throws Exception {
out.writeObject(Foo.foo);
out.writeObject(Foo.foo);
}
void read(ObjectInputStream in) throws Exception {
Object obj = in.readObject();
if (obj != Foo.foo) {
throw new Error(
"expected " + Foo.foo + " instead of " + obj);
}
try {
obj = in.readUnshared();
throw new Error(
"read of " + obj + " should not have succeeded");
} catch (ObjectStreamException e) {
System.out.println("caught expected exception " + e);
}
}
},
new WriteReadTest() {
void write(ObjectOutputStream out) throws Exception {
out.writeObject(Foo.foo);
out.writeObject(Foo.foo);
}
void read(ObjectInputStream in) throws Exception {
Object obj = in.readUnshared();
if (obj != Foo.foo) {
throw new Error(
"expected " + Foo.foo + " instead of " + obj);
}
try {
obj = in.readObject();
throw new Error(
"read of " + obj + " should not have succeeded");
} catch (ObjectStreamException e) {
System.out.println("caught expected exception " + e);
}
}
},
new WriteReadTest() {
void write(ObjectOutputStream out) throws Exception {
out.writeObject(Foo.foo);
out.writeUnshared(Foo.foo);
}
void read(ObjectInputStream in) throws Exception {
Object obj = in.readUnshared();
if (obj != Foo.foo) {
throw new Error(
"expected " + Foo.foo + " instead of " + obj);
}
obj = in.readUnshared();
if (obj != Foo.foo) {
throw new Error(
"expected " + Foo.foo + " instead of " + obj);
}
}
},
new WriteReadTest() {
void write(ObjectOutputStream out) throws Exception {
out.writeUnshared(Foo.foo);
out.writeObject(Foo.foo);
}
void read(ObjectInputStream in) throws Exception {
Object obj = in.readUnshared();
if (obj != Foo.foo) {
throw new Error(
"expected " + Foo.foo + " instead of " + obj);
}
obj = in.readUnshared();
if (obj != Foo.foo) {
throw new Error(
"expected " + Foo.foo + " instead of " + obj);
}
}
}
};
for (int i = 0; i < tests.length; i++) {
tests[i].run();
}
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4088176
* @summary Evolution: read evolved class with new field of a non-existing Externalizable class.
*/
import java.io.*;
class A implements Serializable {
// Version 1.0 of class A.
private static final long serialVersionUID = 1L;
public int bar;
public D zoo;
}
class D implements Serializable {
private static final long serialVersionUID = 1L;
public int x;
D(int y) {
x = y;
}
}
public class ReadAddedField {
public static void main(String args[])
throws IOException, ClassNotFoundException
{
File f = new File("tmp.ser");
ObjectInput in =
new ObjectInputStream(new FileInputStream(f));
A a = (A)in.readObject();
A b = (A)in.readObject();
if (a.bar != 4)
throw new RuntimeException("a.bar does not equal 4, it equals " +
a.bar);
if (a.zoo.x != 22)
throw new RuntimeException("a.zoo.x does not equal 22 equals " +
a.zoo.x);
if (b.bar != 4)
throw new RuntimeException("b.bar does not equal 4, it equals " +
b.bar);
if (b.zoo.x != 22)
throw new RuntimeException("b.zoo.x does not equal 22 equals " +
b.zoo.x);
in.close();
}
}

View file

@ -0,0 +1,97 @@
/*
* Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4088176
*
* @clean A D NewExternFieldClass ReadAddedField WriteAddedField
* @compile WriteAddedField.java
* @run main WriteAddedField
* @clean A D NewExternFieldClass ReadAddedField WriteAddedField
* @compile ReadAddedField.java
* @run main ReadAddedField
*
* @summary Evolution: read evolved class with new field of a non-existing Externalizable class.
*/
import java.io.*;
class NewExternFieldClass implements Externalizable {
private static final long serialVersionUID = 1L;
byte l;
public NewExternFieldClass() {
l = 0;
}
public NewExternFieldClass(byte value) {
l = value;
}
public void readExternal(ObjectInput s)
throws IOException, ClassNotFoundException
{
l = s.readByte();
System.out.println("readExternal read " + l);
}
public void writeExternal(ObjectOutput s) throws IOException
{
s.writeByte(l);
}
}
class D implements Serializable {
private static final long serialVersionUID = 1L;
public int x;
D(int y) {
x = y;
}
}
class A implements Serializable {
// Version 1.1 of class A. Added superclass NewSerializableSuper.
private static final long serialVersionUID = 1L;
NewExternFieldClass foo;
D zoo;
int bar;
A() {
bar = 4;
foo = new NewExternFieldClass((byte)66);
zoo = new D(22);
}
}
public class WriteAddedField {
public static void main(String args[]) throws IOException {
A a = new A();
File f = new File("tmp.ser");
ObjectOutput out =
new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(a);
out.writeObject(new A());
out.close();
}
}

View file

@ -0,0 +1,114 @@
/*
* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4088176
* @build WriteAddedField ReadAddedField
* @run main ReadAddedField
*
* @summary Deserialize an evolved class with a new field, field type is new.
*
*/
import java.io.*;
class IncompatibleFieldClass implements Serializable {
private static final long serialVersionUID = 3L;
int x = 5;
};
class A implements Serializable {
// Version 1.0 of class A.
private static final long serialVersionUID = 1L;
public int bar;
}
/** Test serial persistent fields w/o using Alternate API.
*/
class B implements Serializable {
private static final long serialVersionUID = 2L;
int bar;
B() {
bar = 4;
}
}
/** Test serial persistent fields using Alternate API.
* Also make sure that optional data to non-existent classes can be skipped.
*/
class C implements Serializable {
private static final long serialVersionUID = 3L;
int bar;
C() {
bar = 4;
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
}
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
}
}
public class ReadAddedField {
public static void main(String args[])
throws IOException, ClassNotFoundException
{
File f = new File("tmp.ser");
ObjectInput in =
new ObjectInputStream(new FileInputStream(f));
A a = (A)in.readObject();
if (a.bar != 4)
throw new RuntimeException("a.bar does not equal 4, it equals " +
a.bar);
B b = (B)in.readObject();
if (b.bar != 4)
throw new RuntimeException("b.bar does not equal 4, it equals " +
b.bar);
C c = (C)in.readObject();
if (c.bar != 4)
throw new RuntimeException("c.bar does not equal 4, it equals " +
c.bar);
A aa = (A)in.readObject();
if (aa.bar != 4)
throw new RuntimeException("a.bar does not equal 4, it equals " +
aa.bar);
B bb = (B)in.readObject();
if (bb.bar != 4)
throw new RuntimeException("b.bar does not equal 4, it equals " +
bb.bar);
C cc = (C)in.readObject();
if (cc.bar != 4)
throw new RuntimeException("c.bar does not equal 4, it equals " +
cc.bar);
in.close();
}
}

View file

@ -0,0 +1,211 @@
/*
* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4088176
* @summary Deserialize an evolved class with a new field, field type is new.
*
* @clean A B C NewExternField NewFieldClass ReadAddedField WriteAddedField
* @compile WriteAddedField.java
* @run main WriteAddedField
* @clean A B C NewExternField NewFieldClass ReadAddedField WriteAddedField
* @compile ReadAddedField.java
* @run main ReadAddedField
*/
import java.io.*;
class NewFieldClass implements Serializable {
private static final long serialVersionUID = 1L;
int k;
NewFieldClass(int value) {
k = value;
}
};
class IncompatibleFieldClass implements Serializable {
private static final long serialVersionUID = 3L;
int x = 5;
};
@SuppressWarnings("serial") /* Incorrect use is being tested */
class NewExternFieldClass implements Externalizable {
private static final long serialVersionUID = 1L;
byte l;
public NewExternFieldClass(int value) {
l = (byte)value;
}
public void readExternal(ObjectInput s)
throws IOException, ClassNotFoundException
{
l = s.readByte();
}
public void writeExternal(ObjectOutput s) throws IOException
{
s.writeByte(l);
}
}
class A implements Serializable {
// Version 1.1 of class A. Added superclass NewSerializableSuper.
private static final long serialVersionUID = 1L;
NewFieldClass foo;
NewFieldClass fooarray[];
IncompatibleFieldClass boo;
IncompatibleFieldClass booarray[];
/* Excluded due to Bug 4089540
NewExternFieldClass abc;
NewExternFieldClass farray[];
*/
int bar;
A() {
foo = new NewFieldClass(23);
fooarray = new NewFieldClass[24];
for (int i = 0; i < fooarray.length; i++)
fooarray[i] = new NewFieldClass(i);
boo = new IncompatibleFieldClass();
booarray = new IncompatibleFieldClass[24];
for (int i = 0; i < booarray.length; i++)
booarray[i] = new IncompatibleFieldClass();
bar = 4;
/* Excluded due to Bug 4089540
abc = new NewExternFieldClass(66);
farray = new NewExternFieldClass[10];
for (int k = 0; k < farray.length; k++)
farray[k] = new NewExternFieldClass(k);
*/
}
}
/** Test serial persistent fields w/o using Alternate API.
*/
class B implements Serializable {
private static final long serialVersionUID = 2L;
NewFieldClass foo;
NewFieldClass[] array;
IncompatibleFieldClass boo;
IncompatibleFieldClass booarray[];
transient NewExternFieldClass abc;
transient NewExternFieldClass farray[];
int bar;
B() {
foo = new NewFieldClass(12);
array = new NewFieldClass[12];
for (int i = 0; i < array.length; i++)
array[i] = new NewFieldClass(i);
bar = 4;
abc = new NewExternFieldClass(66);
farray = new NewExternFieldClass[10];
for (int k = 0; k < farray.length; k++)
farray[k] = new NewExternFieldClass(k);
}
}
/** Test serial persistent fields using Alternate API.
* Also make sure that optional data to non-existent classes can be skipped.
*/
class C implements Serializable {
private static final long serialVersionUID = 3L;
NewFieldClass foo;
NewFieldClass[] array;
int bar;
transient NewExternFieldClass abc;
transient NewExternFieldClass farray[];
C() {
foo = new NewFieldClass(12);
array = new NewFieldClass[12];
for (int i = 0; i < array.length; i++)
array[i] = new NewFieldClass(i);
bar = 4;
abc = new NewExternFieldClass(3);
farray = new NewExternFieldClass[10];
for (int k = 0; k < farray.length; k++)
farray[k] = new NewExternFieldClass(k);
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
/* Excluded due to Bug 4089540
abc = (NewExternFieldClass)fields.get("abc", null);
farray = (NewExternFieldClass[])fields.get("farray", null);
*/
/* read optional data */
NewFieldClass tmpfoo = (NewFieldClass)s.readObject();
NewFieldClass[] tmparray= (NewFieldClass[])s.readObject();
int tmpbar = s.readInt();
/* Excluded due to Bug 4089540
NewExternFieldClass tmpabc = (NewExternFieldClass)s.readObject();
NewExternFieldClass[] tmpfarray = (NewExternFieldClass[])s.readObject();
*/
}
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
/* write optional data */
s.writeObject(foo);
s.writeObject(array);
s.writeInt(bar);
/* Excluded due to Bug 4089540
s.writeObject(abc);
s.writeObject(farray);
*/
}
}
public class WriteAddedField {
public static void main(String args[]) throws IOException {
A a = new A();
B b = new B();
C c = new C();
File f = new File("tmp.ser");
ObjectOutput out =
new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(a);
out.writeObject(b);
out.writeObject(c);
a = new A();
b = new B();
c = new C();
out.writeObject(a);
out.writeObject(b);
out.writeObject(c);
out.close();
}
}

View file

@ -0,0 +1,31 @@
#
# Copyright (c) 1997, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
rm *.class tmp.ser
javac WriteAddedField.java
java WriteAddedField
rm *.class
javac ReadAddedField.java
java ReadAddedField
rm *.class

View file

@ -0,0 +1,14 @@
#Here is the script I used to run this test. The "rm" are critical to
#the test.
java -version
javac WriteAddedSuperClass.java
java WriteAddedSuperClass
rm A.class AddedSuperClass.class
javac ReadAddedSuperClass.java
java ReadAddedSuperClass
rm A.class
javac WriteAddedSuperClass.java
java WriteAddedSuperClass
rm A.class AddedSuperClass.class
javac ReadAddedSuperClass2.java
java ReadAddedSuperClass2

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4070080
*
* @build WriteAddedSuperClass ReadAddedSuperClass
* @run main ReadAddedSuperClass
* @summary Test reading an evolved class serialization into the original class
* version. Class evolved by adding a superclass.
* This is a compatible class evolution.
*
* Part a of test serializes an instance of an evolved class to a serialization stream.
* Part b of test deserializes the serialization stream into an instance of
* the original class.
*
* Description of failure:
*
* If you delete AddedSuperClass.class before running this test,
* both JDK 1.1.x and 1.2 result in ClassNotFoundException for class
* AddedSuperClass. If the .class file is not deleted, 1.2 does not
* fail. However, JDK 1.1.4 core dumps dereferencing a null class handle
* in the native method for inputClassDescriptor.
*/
import java.io.*;
class A implements Serializable {
// Version 1.0 of class A.
private static final long serialVersionUID = 1L;
}
public class ReadAddedSuperClass {
public static void main(String args[]) throws IOException, ClassNotFoundException {
File f = new File("tmp.ser");
ObjectInput in =
new ObjectInputStream(new FileInputStream(f));
A a = (A)in.readObject();
in.close();
}
}

View file

@ -0,0 +1,64 @@
/*
* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4070080
*
* @build WriteAddedSuperClass ReadAddedSuperClass2
* @run main ReadAddedSuperClass2
* @summary 2nd part of test deserializes the serialization stream into an
* instance of the original class WHEN the AddedSuperClass exists
* locally.
*
* Description of failure:
*
* If you delete AddedSuperClass.class before running this test,
* both JDK 1.1.x and 1.2 result in ClassNotFoundException for class
* AddedSuperClass. If the .class file is not deleted, 1.2 does not
* fail. However, JDK 1.1.4 core dumps dereferencing a null class handle
* in the native method for inputClassDescriptor.
*/
import java.io.*;
class AddedSuperClass implements Serializable {
private static final long serialVersionUID = 1L;
// Needed at least one field to recreate failure.
int field;
}
class A implements Serializable {
// Version 1.0 of class A.
private static final long serialVersionUID = 1L;
}
public class ReadAddedSuperClass2 {
public static void main(String args[]) throws IOException, ClassNotFoundException {
File f = new File("tmp.ser");
ObjectInput in =
new ObjectInputStream(new FileInputStream(f));
A a = (A)in.readObject();
in.close();
}
}

View file

@ -0,0 +1,75 @@
/*
* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4070080
*
* @summary Test reading an evolved class serialization into the original class
* version. Class evolved by adding a superclass.
*
* @clean A WriteAddedSuperClass ReadAddedSuperClass ReadAddedSuperClass2
* @compile WriteAddedSuperClass.java
* @run main WriteAddedSuperClass
* @clean A AddedSuperClass
* @compile ReadAddedSuperClass.java
* @run main ReadAddedSuperClass
* @clean A
* @compile WriteAddedSuperClass.java
* @run main WriteAddedSuperClass
* @clean A AddedSuperClass
* @compile ReadAddedSuperClass2.java
* @run main ReadAddedSuperClass2
*
*/
/*
* Part a of test serializes an instance of an evolved class to a serialization stream.
* Part b of test deserializes the serialization stream into an instance of
* the original class.
*
*/
import java.io.*;
class AddedSuperClass implements Serializable {
private static final long serialVersionUID = 1L;
// Needed at least one field to recreate failure.
int field;
}
class A extends AddedSuperClass implements Serializable {
// Version 1.1 of class A. Added superclass NewSerializableSuper.
private static final long serialVersionUID = 1L;
}
public class WriteAddedSuperClass {
public static void main(String args[]) throws IOException {
A a = new A();
File f = new File("tmp.ser");
ObjectOutput out =
new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(a);
out.close();
}
}

View file

@ -0,0 +1,112 @@
/*
* Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4087295 4785472
* @library /test/lib
* @build jdk.test.lib.compiler.CompilerUtils
* jdk.test.lib.Utils
* jdk.test.lib.Asserts
* jdk.test.lib.JDKToolFinder
* jdk.test.lib.JDKToolLauncher
* jdk.test.lib.Platform
* jdk.test.lib.process.*
* @build RenamePackageTest
* @run main RenamePackageTest
* @summary Enable resolveClass() to accommodate package renaming.
* This fix enables one to implement a resolveClass method that maps a
* Serialiazable class within a serialization stream to the same class
* in a different package within the JVM runtime. See run shell script
* for instructions on how to run this test.
*/
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import jdk.test.lib.compiler.CompilerUtils;
import jdk.test.lib.process.ProcessTools;
public class RenamePackageTest {
public static void main(String args[]) throws Exception {
setup();
runTestSerialDriver();
runInstallSerialDriver();
runInstallSerialDriver();
runTestSerialDriver();
}
private static final Path SHARE = Paths.get(System.getProperty("test.classes"), "share");
private static final Path OCLASSES = Paths.get(System.getProperty("test.classes"), "oclasses");
private static final Path NCLASSES = Paths.get(System.getProperty("test.classes"), "nclasses");
private static void setup() throws Exception {
boolean b = CompilerUtils.compile(Paths.get(System.getProperty("test.src"), "extension"),
SHARE);
assertTrue(b);
b = CompilerUtils.compile(Paths.get(System.getProperty("test.src"), "test"),
OCLASSES,
"-classpath",
SHARE.toString());
assertTrue(b);
b = CompilerUtils.compile(Paths.get(System.getProperty("test.src"), "install"),
NCLASSES,
"-classpath",
SHARE.toString());
assertTrue(b);
}
private static void runTestSerialDriver() throws Exception {
ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
"-classpath",
SHARE.toString()
+ File.pathSeparator
+ OCLASSES.toString(),
"test.SerialDriver", "-s");
Process p = ProcessTools.startProcess("test SerialDriver", pb);
p.waitFor();
assertTrue(p.exitValue() == 0);
}
private static void runInstallSerialDriver() throws Exception {
ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
"-classpath",
SHARE.toString()
+ File.pathSeparator
+ NCLASSES.toString(),
"install.SerialDriver", "-d");
Process p = ProcessTools.startProcess("install SerialDriver", pb);
p.waitFor();
assertTrue(p.exitValue() == 0);
}
private static void assertTrue(boolean b) {
if (!b) {
throw new RuntimeException("expected true, get false");
}
}
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package extension;
import java.util.Hashtable;
import java.io.*;
public class ExtendedObjectInputStream extends ObjectInputStream {
private static Hashtable renamedClassMap;
public ExtendedObjectInputStream(InputStream si)
throws IOException, StreamCorruptedException
{
super(si);
}
protected Class resolveClass(ObjectStreamClass v)
throws IOException, ClassNotFoundException
{
if (renamedClassMap != null) {
// System.out.println("resolveClass(" + v.getName() + ")");
Class newClass = (Class)renamedClassMap.get(v.getName());
if (newClass != null) {
v = ObjectStreamClass.lookup(newClass);
}
}
return super.resolveClass(v);
}
public static void addRenamedClassName(String oldName, String newName)
throws ClassNotFoundException
{
Class cl = null;
if (renamedClassMap == null)
renamedClassMap = new Hashtable(10);
if (newName.startsWith("[L")) {
// System.out.println("Array processing");
Class componentType =
Class.forName(newName.substring(2));
//System.out.println("ComponentType=" + componentType.getName());
Object dummy =
java.lang.reflect.Array.newInstance(componentType, 3);
cl = dummy.getClass();
// System.out.println("Class=" + cl.getName());
}
else
cl = Class.forName(newName);
//System.out.println("oldName=" + oldName +
// " newName=" + cl.getName());
renamedClassMap.put(oldName, cl);
}
}

View file

@ -0,0 +1,139 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
*
* @bug 4087295
* @build install/SerialDriver.java test/SerialDriver.java extension/ExtendedObjectInputStream.java
* @summary Enable resolveClass() to accommodate package renaming.
* This fix enables one to implement a resolveClass method that maps a
* Serializable class within a serialization stream to the same class
* in a different package within the JVM runtime. See run shell script
* for instructions on how to run this test.
*/
package install;
import java.io.*;
import extension.ExtendedObjectInputStream;
public class SerialDriver implements Serializable {
private static final long serialVersionUID = 1L;
String name;
SerialDriver next;
transient Object objarray[];
public SerialDriver() {
name = "<terminator>";
next = null;
}
public SerialDriver(String name, SerialDriver next) {
this.name = name;
this.next = next;
}
static boolean serialize;
static boolean deserialize;
public static void main(String args[]) throws Exception {
SerialDriver obj = new SerialDriver("SerialDriver_2",
new SerialDriver());
SerialDriver[] array = new SerialDriver[5];
for (int i = 0; i < array.length; i++)
array[i] = new SerialDriver("SerialDriver_1_" + i, new SerialDriver());
/*
* see if we are serializing or deserializing.
* The ability to deserialize or serialize allows
* us to see the bidirectional readability and writeability
*/
if (args.length == 1) {
if (args[0].equals("-d")) {
deserialize = true;
} else if (args[0].equals("-s")) {
serialize = true;
} else {
usage();
throw new Exception("incorrect command line arguments");
}
} else {
usage();
throw new Exception("incorrect command line arguments");
}
File f = new File("stream.ser");
if (serialize) {
// Serialize the subclass
try (FileOutputStream fo = new FileOutputStream(f);
ObjectOutputStream so = new ObjectOutputStream(fo))
{
so.writeObject(obj);
/* Skip arrays since they do not work with rename yet.
The serialVersionUID changes due to the name change
and there is no way to set the serialVersionUID for an
array. */
so.writeObject(array);
} catch (Exception e) {
System.out.println(e);
throw e;
}
}
if (deserialize) {
// Deserialize the subclass
try (FileInputStream fi = new FileInputStream(f);
ExtendedObjectInputStream si = new ExtendedObjectInputStream(fi))
{
si.addRenamedClassName("test.SerialDriver", "install.SerialDriver");
si.addRenamedClassName("[Ltest.SerialDriver;",
"[Linstall.SerialDriver");
obj = (SerialDriver) si.readObject();
array = (SerialDriver[]) si.readObject();
} catch (Exception e) {
System.out.println(e);
throw e;
}
System.out.println();
System.out.println("Printing deserialized class: ");
System.out.println();
System.out.println(obj.toString());
System.out.println();
}
}
public String toString() {
String nextString = next != null ? next.toString() : "<null>";
return "name =" + name + " next = <" + nextString + ">";
}
/**
* Prints out the usage
*/
static void usage() {
System.out.println("Usage:");
System.out.println(" -s (in order to serialize)");
System.out.println(" -d (in order to deserialize)");
}
}

View file

@ -0,0 +1,135 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
*
* @bug 4087295
* @build install/SerialDriver.java test/SerialDriver.java extension/ExtendedObjectInputStream.java
* @summary Enable resolveClass() to accommodate package renaming.
* This fix enables one to implement a resolveClass method that maps a
* Serializable class within a serialization stream to the same class
* in a different package within the JVM runtime. See run shell script
* for instructions on how to run this test.
*/
package test;
import java.io.*;
import extension.ExtendedObjectInputStream;
public class SerialDriver implements Serializable {
private static final long serialVersionUID = 1L;
String name;
SerialDriver next;
public SerialDriver() {
name = "<terminator>";
next = null;
}
public SerialDriver(String name, SerialDriver next) {
this.name = name;
this.next = next;
}
static boolean serialize = false;
static boolean deserialize = false;
public static void main(String args[]) throws Exception {
SerialDriver obj = new SerialDriver("SerialDriver_1", new SerialDriver());
SerialDriver[] array = new SerialDriver[5];
for (int i = 0; i < array.length; i++)
array[i] = new SerialDriver("SerialDriver_1_" + i, new SerialDriver());
/*
* see if we are serializing or deserializing.
* The ability to deserialize or serialize allows
* us to see the bidirectional readability and writeability
*/
if (args.length == 1) {
if (args[0].equals("-d")) {
deserialize = true;
} else if (args[0].equals("-s")) {
serialize = true;
} else {
usage();
throw new Exception("incorrect command line arguments");
}
} else {
usage();
throw new Exception("incorrect command line arguments");
}
File f = new File("stream.ser");
if (serialize) {
// Serialize the subclass
try (FileOutputStream fo = new FileOutputStream(f);
ObjectOutputStream so = new ObjectOutputStream(fo))
{
so.writeObject(obj);
/* Comment out since renaming arrays does not work
since it changes the serialVersionUID. */
so.writeObject(array);
} catch (Exception e) {
System.out.println(e);
throw e;
}
}
if (deserialize) {
// Deserialize the subclass
try (FileInputStream fi = new FileInputStream(f);
ExtendedObjectInputStream si = new ExtendedObjectInputStream(fi))
{
si.addRenamedClassName("install.SerialDriver",
"test.SerialDriver");
si.addRenamedClassName("[Linstall.SerialDriver;",
"[Ltest.SerialDriver");
obj = (SerialDriver) si.readObject();
array = (SerialDriver[]) si.readObject();
} catch (Exception e) {
System.out.println(e);
throw e;
}
System.out.println();
System.out.println("Printing deserialized class: ");
System.out.println();
System.out.println(obj.toString());
System.out.println();
}
}
public String toString() {
String nextString = next != null ? next.toString() : "<null>";
return "name =" + name + " next = <" + nextString + ">";
}
/**
* Prints out the usage
*/
static void usage() {
System.out.println("Usage:");
System.out.println(" -s (in order to serialize)");
System.out.println(" -d (in order to deserialize)");
}
}

View file

@ -0,0 +1,113 @@
/*
* Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 6317435 7110700
* @summary Verify that stack trace contains a proper cause of
* InvalidClassException (methods: checkSerialize,
* checkDeserialize or checkDefaultSerialize)
*
* @author Andrey Ozerov
*
*/
import java.io.*;
class NotSerializableObject {
private String m_str;
private Integer m_int;
public NotSerializableObject(String m_str, Integer m_int) {
this.m_str = m_str;
this.m_int = m_int;
}
}
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
class SerializableObject extends NotSerializableObject
implements Serializable
{
private static final long serialVersionUID = 1L;
public SerializableObject(String m_str, Integer m_int) {
super(m_str, m_int);
}
public SerializableObject() {
super("test", 10);
}
}
public class ExpectedStackTrace {
private static final String SER_METHOD_NAME = "checkSerializable";
public static final void main(String[] args) throws Exception {
System.err.println("\nRegression test for CRs 6317435, 7110700");
checkSerializable(getObject());
}
private static Object getObject() throws Exception {
ObjectStreamClass osc =
ObjectStreamClass.lookup(SerializableObject.class);
SerializableObject initObj =
(SerializableObject) osc.forClass().getConstructor().newInstance();
return initObj;
}
private static void checkSerializable(Object initObj) throws Exception {
try {
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
ObjectOutputStream out = new ObjectOutputStream(bos) ;
out.writeObject(initObj);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
// Deserialize from a byte array
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
ObjectInputStream in = new ObjectInputStream(bais);
SerializableObject finObj = (SerializableObject) in.readObject();
in.close();
throw new Error();
} catch(ObjectStreamException ex) {
StackTraceElement[] stes = ex.getStackTrace();
boolean found = false;
for (int i = 0; i<stes.length-1; i++) {
StackTraceElement ste = stes[i];
String nme = ste.getMethodName();
if (nme.equals(SER_METHOD_NAME)) {
found = true;
}
}
if (found) {
if (ex.getCause() != null) {
throw new Error("\nTest for CR 7110700 FAILED");
}
System.err.println("\nTEST PASSED");
} else {
throw new Error("\nTest for CR 6317435 FAILED");
}
}
}
}

View file

@ -0,0 +1,79 @@
/*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4407956
* @summary Verify that ClassNotFoundExceptions explicitly constructed and
* thrown from with custom readObject/readExternal methods are
* propagated properly.
*/
import java.io.*;
class A implements Serializable {
private static final long serialVersionUID = 1L;
private void readObject(ObjectInputStream in)
throws ClassNotFoundException, IOException
{
throw new ClassNotFoundException();
}
}
class B implements Externalizable {
private static final long serialVersionUID = 1L;
public B() {}
public void writeExternal(ObjectOutput out) throws IOException {}
public void readExternal(ObjectInput in)
throws ClassNotFoundException, IOException
{
throw new ClassNotFoundException();
}
}
public class ExplicitCNFException {
public static void main(String[] args) throws Exception {
test(new A());
test(new Object[]{ new A() });
test(new B());
test(new Object[]{ new B() });
}
static void test(Object obj) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_2);
oout.writeObject(obj);
oout.close();
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
try {
oin.readObject();
throw new Error(); // should not succeed
} catch (ClassNotFoundException ex) {
}
}
}

View file

@ -0,0 +1,64 @@
/*
* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package $package;
import java.io.IOException;
import java.io.Serializable;
import failureAtomicity.SerialRef;
public class Bar extends Foo implements Serializable {
private static final long serialVersionUID = -0L;
public final long barPrim;
public final String barRef;
public final SerialRef ref; // So we can retrieve a reference to check
public $zebra_type zebraBar; // ordered alphabetically, must be last
public Bar(int fooPrim, String fooRef, $foo_zebra_type fooZebra,
long barPrim, String barRef, $zebra_type zebra) {
super(fooPrim, fooRef, fooZebra);
this.barPrim = barPrim;
this.barRef = barRef;
this.zebraBar = zebra;
this.ref = new SerialRef(this);
}
@Override
public String toString() {
return new StringBuilder()
.append("$package.Bar[")
.append("barPrim:").append(barPrim)
.append(", barRef:").append(barRef)
.append(", zebraBar:").append(zebraBar)
.append(", " + super.toString())
.toString();
}
//$has_readObject private void readObject(java.io.ObjectInputStream in)
//$has_readObject throws IOException, ClassNotFoundException
//$has_readObject {
//$has_readObject in.defaultReadObject();
//$has_readObject }
}

View file

@ -0,0 +1,423 @@
/*
* Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8071474
* @summary Better failure atomicity for default read object.
* @modules jdk.compiler
* @library /test/lib
* @build jdk.test.lib.Platform
* jdk.test.lib.util.FileUtils
* @compile FailureAtomicity.java SerialRef.java
* @run main failureAtomicity.FailureAtomicity
*/
package failureAtomicity;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.UncheckedIOException;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import jdk.test.lib.util.FileUtils;
@SuppressWarnings("unchecked")
public class FailureAtomicity {
static final Path TEST_SRC = Paths.get(System.getProperty("test.src", "."));
static final Path TEST_CLASSES = Paths.get(System.getProperty("test.classes", "."));
static final Path fooTemplate = TEST_SRC.resolve("Foo.template");
static final Path barTemplate = TEST_SRC.resolve("Bar.template");
static final String[] PKGS = { "a.b.c", "x.y.z" };
public static void main(String[] args) throws Exception {
test_Foo();
test_BadFoo(); // 'Bad' => incompatible type; cannot be "fully" deserialized
test_FooWithReadObject();
test_BadFooWithReadObject();
test_Foo_Bar();
test_Foo_BadBar();
test_BadFoo_Bar();
test_BadFoo_BadBar();
test_Foo_BarWithReadObject();
test_Foo_BadBarWithReadObject();
test_BadFoo_BarWithReadObject();
test_BadFoo_BadBarWithReadObject();
test_FooWithReadObject_Bar();
test_FooWithReadObject_BadBar();
test_BadFooWithReadObject_Bar();
test_BadFooWithReadObject_BadBar();
}
static final BiConsumer<Object,Object> FOO_FIELDS_EQUAL = (a,b) -> {
try {
int aPrim = a.getClass().getField("fooPrim").getInt(a);
int bPrim = b.getClass().getField("fooPrim").getInt(b);
if (aPrim != bPrim)
throw new AssertionError("Not equal: (" + aPrim + "!=" + bPrim
+ "), in [" + a + "] [" + b + "]");
Object aRef = a.getClass().getField("fooRef").get(a);
Object bRef = b.getClass().getField("fooRef").get(b);
if (!aRef.equals(bRef))
throw new RuntimeException("Not equal: (" + aRef + "!=" + bRef
+ "), in [" + a + "] [" + b + "]");
} catch (NoSuchFieldException | IllegalAccessException x) {
throw new InternalError(x);
}
};
static final BiConsumer<Object,Object> FOO_FIELDS_DEFAULT = (ignore,b) -> {
try {
int aPrim = b.getClass().getField("fooPrim").getInt(b);
if (aPrim != 0)
throw new AssertionError("Expected 0, got:" + aPrim
+ ", in [" + b + "]");
Object aRef = b.getClass().getField("fooRef").get(b);
if (aRef != null)
throw new RuntimeException("Expected null, got:" + aRef
+ ", in [" + b + "]");
} catch (NoSuchFieldException | IllegalAccessException x) {
throw new InternalError(x);
}
};
static final BiConsumer<Object,Object> BAR_FIELDS_EQUAL = (a,b) -> {
try {
long aPrim = a.getClass().getField("barPrim").getLong(a);
long bPrim = b.getClass().getField("barPrim").getLong(b);
if (aPrim != bPrim)
throw new AssertionError("Not equal: (" + aPrim + "!=" + bPrim
+ "), in [" + a + "] [" + b + "]");
Object aRef = a.getClass().getField("barRef").get(a);
Object bRef = b.getClass().getField("barRef").get(b);
if (!aRef.equals(bRef))
throw new RuntimeException("Not equal: (" + aRef + "!=" + bRef
+ "), in [" + a + "] [" + b + "]");
} catch (NoSuchFieldException | IllegalAccessException x) {
throw new InternalError(x);
}
};
static final BiConsumer<Object,Object> BAR_FIELDS_DEFAULT = (ignore,b) -> {
try {
long aPrim = b.getClass().getField("barPrim").getLong(b);
if (aPrim != 0L)
throw new AssertionError("Expected 0, got:" + aPrim
+ ", in [" + b + "]");
Object aRef = b.getClass().getField("barRef").get(b);
if (aRef != null)
throw new RuntimeException("Expected null, got:" + aRef
+ ", in [" + b + "]");
} catch (NoSuchFieldException | IllegalAccessException x) {
throw new InternalError(x);
}
};
static void test_Foo() {
testFoo("Foo", "String", false, false, FOO_FIELDS_EQUAL); }
static void test_BadFoo() {
testFoo("BadFoo", "byte[]", true, false, FOO_FIELDS_DEFAULT); }
static void test_FooWithReadObject() {
testFoo("FooWithReadObject", "String", false, true, FOO_FIELDS_EQUAL); }
static void test_BadFooWithReadObject() {
testFoo("BadFooWithReadObject", "byte[]", true, true, FOO_FIELDS_DEFAULT); }
static void testFoo(String testName, String xyzZebraType,
boolean expectCCE, boolean withReadObject,
BiConsumer<Object,Object>... resultCheckers) {
System.out.println("\nTesting " + testName);
try {
Path testRoot = testDir(testName);
Path srcRoot = Files.createDirectory(testRoot.resolve("src"));
List<Path> srcFiles = new ArrayList<>();
srcFiles.add(createSrc(PKGS[0], fooTemplate, srcRoot, "String", withReadObject));
srcFiles.add(createSrc(PKGS[1], fooTemplate, srcRoot, xyzZebraType, withReadObject));
Path build = Files.createDirectory(testRoot.resolve("build"));
javac(build, srcFiles);
URLClassLoader loader = new URLClassLoader(new URL[]{ build.toUri().toURL() },
FailureAtomicity.class.getClassLoader());
Class<?> fooClass = Class.forName(PKGS[0] + ".Foo", true, loader);
Constructor<?> ctr = fooClass.getConstructor(
new Class<?>[]{int.class, String.class, String.class});
Object abcFoo = ctr.newInstance(5, "chegar", "zebra");
try {
toOtherPkgInstance(abcFoo, loader);
if (expectCCE)
throw new AssertionError("Expected CCE not thrown");
} catch (ClassCastException e) {
if (!expectCCE)
throw new AssertionError("UnExpected CCE: " + e);
}
Object deserialInstance = failureAtomicity.SerialRef.obj;
System.out.println("abcFoo: " + abcFoo);
System.out.println("deserialInstance: " + deserialInstance);
for (BiConsumer<Object, Object> rc : resultCheckers)
rc.accept(abcFoo, deserialInstance);
} catch (IOException x) {
throw new UncheckedIOException(x);
} catch (ReflectiveOperationException x) {
throw new InternalError(x);
}
}
static void test_Foo_Bar() {
testFooBar("Foo_Bar", "String", "String", false, false, false,
FOO_FIELDS_EQUAL, BAR_FIELDS_EQUAL);
}
static void test_Foo_BadBar() {
testFooBar("Foo_BadBar", "String", "byte[]", true, false, false,
FOO_FIELDS_DEFAULT, BAR_FIELDS_DEFAULT);
}
static void test_BadFoo_Bar() {
testFooBar("BadFoo_Bar", "byte[]", "String", true, false, false,
FOO_FIELDS_DEFAULT, BAR_FIELDS_DEFAULT);
}
static void test_BadFoo_BadBar() {
testFooBar("BadFoo_BadBar", "byte[]", "byte[]", true, false, false,
FOO_FIELDS_DEFAULT, BAR_FIELDS_DEFAULT);
}
static void test_Foo_BarWithReadObject() {
testFooBar("Foo_BarWithReadObject", "String", "String", false, false, true,
FOO_FIELDS_EQUAL, BAR_FIELDS_EQUAL);
}
static void test_Foo_BadBarWithReadObject() {
testFooBar("Foo_BadBarWithReadObject", "String", "byte[]", true, false, true,
FOO_FIELDS_EQUAL, BAR_FIELDS_DEFAULT);
}
static void test_BadFoo_BarWithReadObject() {
testFooBar("BadFoo_BarWithReadObject", "byte[]", "String", true, false, true,
FOO_FIELDS_DEFAULT, BAR_FIELDS_DEFAULT);
}
static void test_BadFoo_BadBarWithReadObject() {
testFooBar("BadFoo_BadBarWithReadObject", "byte[]", "byte[]", true, false, true,
FOO_FIELDS_DEFAULT, BAR_FIELDS_DEFAULT);
}
static void test_FooWithReadObject_Bar() {
testFooBar("FooWithReadObject_Bar", "String", "String", false, true, false,
FOO_FIELDS_EQUAL, BAR_FIELDS_EQUAL);
}
static void test_FooWithReadObject_BadBar() {
testFooBar("FooWithReadObject_BadBar", "String", "byte[]", true, true, false,
FOO_FIELDS_EQUAL, BAR_FIELDS_DEFAULT);
}
static void test_BadFooWithReadObject_Bar() {
testFooBar("BadFooWithReadObject_Bar", "byte[]", "String", true, true, false,
FOO_FIELDS_DEFAULT, BAR_FIELDS_DEFAULT);
}
static void test_BadFooWithReadObject_BadBar() {
testFooBar("BadFooWithReadObject_BadBar", "byte[]", "byte[]", true, true, false,
FOO_FIELDS_DEFAULT, BAR_FIELDS_DEFAULT);
}
static void testFooBar(String testName, String xyzFooZebraType,
String xyzBarZebraType, boolean expectCCE,
boolean fooWithReadObject, boolean barWithReadObject,
BiConsumer<Object,Object>... resultCheckers) {
System.out.println("\nTesting " + testName);
try {
Path testRoot = testDir(testName);
Path srcRoot = Files.createDirectory(testRoot.resolve("src"));
List<Path> srcFiles = new ArrayList<>();
srcFiles.add(createSrc(PKGS[0], fooTemplate, srcRoot, "String",
fooWithReadObject, "String"));
srcFiles.add(createSrc(PKGS[1], fooTemplate, srcRoot, xyzFooZebraType,
fooWithReadObject, xyzFooZebraType));
srcFiles.add(createSrc(PKGS[0], barTemplate, srcRoot, "String",
barWithReadObject, "String"));
srcFiles.add(createSrc(PKGS[1], barTemplate, srcRoot, xyzBarZebraType,
barWithReadObject, xyzFooZebraType));
Path build = Files.createDirectory(testRoot.resolve("build"));
javac(build, srcFiles);
URLClassLoader loader = new URLClassLoader(new URL[]{ build.toUri().toURL() },
FailureAtomicity.class.getClassLoader());
Class<?> fooClass = Class.forName(PKGS[0] + ".Bar", true, loader);
Constructor<?> ctr = fooClass.getConstructor(
new Class<?>[]{int.class, String.class, String.class,
long.class, String.class, String.class});
Object abcBar = ctr.newInstance( 5, "chegar", "zebraFoo", 111L, "aBar", "zebraBar");
try {
toOtherPkgInstance(abcBar, loader);
if (expectCCE)
throw new AssertionError("Expected CCE not thrown");
} catch (ClassCastException e) {
if (!expectCCE)
throw new AssertionError("UnExpected CCE: " + e);
}
Object deserialInstance = failureAtomicity.SerialRef.obj;
System.out.println("abcBar: " + abcBar);
System.out.println("deserialInstance: " + deserialInstance);
for (BiConsumer<Object, Object> rc : resultCheckers)
rc.accept(abcBar, deserialInstance);
} catch (IOException x) {
throw new UncheckedIOException(x);
} catch (ReflectiveOperationException x) {
throw new InternalError(x);
}
}
static Path testDir(String name) throws IOException {
Path testRoot = Paths.get("FailureAtomicity-" + name);
if (Files.exists(testRoot))
FileUtils.deleteFileTreeWithRetry(testRoot);
Files.createDirectory(testRoot);
return testRoot;
}
static String platformPath(String p) { return p.replace("/", File.separator); }
static String binaryName(String name) { return name.replace(".", "/"); }
static String condRemove(String line, String pattern, boolean hasReadObject) {
if (hasReadObject) { return line.replaceAll(pattern, ""); }
else { return line; }
}
static String condReplace(String line, String... zebraFooType) {
if (zebraFooType.length == 1) {
return line.replaceAll("\\$foo_zebra_type", zebraFooType[0]);
} else { return line; }
}
static String nameFromTemplate(Path template) {
return template.getFileName().toString().replaceAll(".template", "");
}
static Path createSrc(String pkg, Path srcTemplate, Path srcRoot,
String zebraType, boolean hasReadObject,
String... zebraFooType)
throws IOException
{
Path srcDst = srcRoot.resolve(platformPath(binaryName(pkg)));
Files.createDirectories(srcDst);
Path srcFile = srcDst.resolve(nameFromTemplate(srcTemplate) + ".java");
List<String> lines = Files.lines(srcTemplate)
.map(s -> s.replaceAll("\\$package", pkg))
.map(s -> s.replaceAll("\\$zebra_type", zebraType))
.map(s -> condReplace(s, zebraFooType))
.map(s -> condRemove(s, "//\\$has_readObject", hasReadObject))
.collect(Collectors.toList());
Files.write(srcFile, lines);
return srcFile;
}
static void javac(Path dest, List<Path> sourceFiles) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fileManager =
compiler.getStandardFileManager(null, null, null)) {
List<File> files = sourceFiles.stream()
.map(p -> p.toFile())
.collect(Collectors.toList());
Iterable<? extends JavaFileObject> compilationUnits =
fileManager.getJavaFileObjectsFromFiles(files);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
Arrays.asList(dest.toFile()));
fileManager.setLocation(StandardLocation.CLASS_PATH,
Arrays.asList(TEST_CLASSES.toFile()));
JavaCompiler.CompilationTask task = compiler
.getTask(null, fileManager, null, null, null, compilationUnits);
boolean passed = task.call();
if (!passed)
throw new RuntimeException("Error compiling " + files);
}
}
static Object toOtherPkgInstance(Object obj, ClassLoader loader)
throws IOException, ClassNotFoundException
{
byte[] bytes = serialize(obj);
bytes = replacePkg(bytes);
return deserialize(bytes, loader);
}
@SuppressWarnings("deprecation")
static byte[] replacePkg(byte[] bytes) {
String str = new String(bytes, 0);
str = str.replaceAll(PKGS[0], PKGS[1]);
str.getBytes(0, bytes.length, bytes, 0);
return bytes;
}
static byte[] serialize(Object obj) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);) {
out.writeObject(obj);
return baos.toByteArray();
}
}
static Object deserialize(byte[] data, ClassLoader l)
throws IOException, ClassNotFoundException
{
return new WithLoaderObjectInputStream(new ByteArrayInputStream(data), l)
.readObject();
}
static class WithLoaderObjectInputStream extends ObjectInputStream {
final ClassLoader loader;
WithLoaderObjectInputStream(InputStream is, ClassLoader loader)
throws IOException
{
super(is);
this.loader = loader;
}
@Override
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException {
try {
return super.resolveClass(desc);
} catch (ClassNotFoundException x) {
String name = desc.getName();
return Class.forName(name, false, loader);
}
}
}
}

View file

@ -0,0 +1,62 @@
/*
* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package $package;
import java.io.IOException;
import java.io.Serializable;
import failureAtomicity.SerialRef;
public class Foo implements Serializable {
private static final long serialVersionUID = -0L;
public final int fooPrim;
public final String fooRef;
public final SerialRef ref; // So we can retrieve a reference to check
public $zebra_type zebraFoo; // ordered alphabetically, must be last
public Foo(int fooPrim, String fooRef, $zebra_type zebra) {
this.fooPrim = fooPrim;
this.fooRef = fooRef;
this.zebraFoo = zebra;
this.ref = new SerialRef(this);
}
@Override
public String toString() {
return new StringBuilder()
.append("$package.Foo[")
.append("fooPrim:").append(fooPrim)
.append(", fooRef:").append(fooRef)
.append(", zebraFoo:").append(zebraFoo).append("]")
.toString();
}
//$has_readObject private void readObject(java.io.ObjectInputStream in)
//$has_readObject throws IOException, ClassNotFoundException
//$has_readObject {
//$has_readObject in.defaultReadObject();
//$has_readObject }
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package failureAtomicity;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
// For verification purposes only.
public class SerialRef implements Serializable {
private static final long serialVersionUID = -0L;
public static Object obj;
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
private final Object ref;
public SerialRef(Object ref) {
this.ref = ref;
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
SerialRef.obj = ref;
}
}

View file

@ -0,0 +1,73 @@
/*
* Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @bug 4404696
* @summary Verify that serialization does not require matching type strings
* for non-primitive fields.
*
* NOTE: This test should be removed if it is determined that serialization
* *should* consider type strings when matching non-primitive fields.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
String obj; // writer defines this field as type Object
}
class Bar implements Serializable {
private static final long serialVersionUID = 0L;
short q; // writer defines this field as type int
}
public class Read {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("foo.ser");
try {
ObjectInputStream oin = new ObjectInputStream(in);
Foo foo = (Foo) oin.readObject();
if (! foo.obj.equals("foo")) {
throw new Error();
}
try {
oin.readObject();
throw new Error();
} catch (ClassCastException ex) {
}
} finally {
in.close();
}
in = new FileInputStream("bar.ser");
try {
ObjectInputStream oin = new ObjectInputStream(in);
oin.readObject();
throw new Error();
} catch (InvalidClassException ex) {
} finally {
in.close();
}
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4404696
*
* @clean Write Read Foo Bar
* @compile Write.java
* @run main Write
* @clean Write Read Foo Bar
* @compile Read.java
* @run main Read
*
* @summary Verify that serialization does not require matching type strings
* for non-primitive fields.
*
* NOTE: This test should be removed if it is determined that serialization
* *should* consider type strings when matching non-primitive fields.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 0L;
@SuppressWarnings("serial") /* Incorrect declarations are being tested */
Object obj;
Foo(Object obj) {
this.obj = obj;
}
}
class Bar implements Serializable {
private static final long serialVersionUID = 0L;
int q;
}
public class Write {
public static void main(String[] args) throws Exception {
ObjectOutputStream oout =
new ObjectOutputStream(new FileOutputStream("foo.ser"));
oout.writeObject(new Foo("foo"));
oout.writeObject(new Foo(0));
oout.close();
oout = new ObjectOutputStream(new FileOutputStream("bar.ser"));
oout.writeObject(new Bar());
oout.close();
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4174797
* @summary Ensure that ObjectInputStream can set final fields.
*/
import java.io.*;
class Foo implements Serializable {
private static final long serialVersionUID = 1L;
final int i;
Foo(int i) {
this.i = i;
}
public boolean equals(Object obj) {
if (! (obj instanceof Foo))
return false;
Foo f = (Foo) obj;
return (i == f.i);
}
public int hashCode() {
return i;
}
}
public class FinalFields {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout;
ByteArrayInputStream bin;
ObjectOutputStream oout;
ObjectInputStream oin;
Foo f1, f2, f1copy, f2copy;
bout = new ByteArrayOutputStream();
oout = new ObjectOutputStream(bout);
f1 = new Foo(1);
f2 = new Foo(2);
oout.writeObject(f1);
oout.writeObject(f2);
oout.flush();
bin = new ByteArrayInputStream(bout.toByteArray());
oin = new ObjectInputStream(bin);
f1copy = (Foo) oin.readObject();
f2copy = (Foo) oin.readObject();
if (! (f1.equals(f1copy) && f2.equals(f2copy)))
throw new Error("copies don't match originals");
}
}

View file

@ -0,0 +1,109 @@
/*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4482966
* @summary Verify that ObjectStreamClass.getSerialVersionUID() will not mask
* Errors (other than NoSuchMethodError) triggered by JNI query for
* static initializer method.
*/
import java.io.*;
@SuppressWarnings("serial") /* Incorrect declarations are being tested. */
class A implements Serializable {
static {
// compiler prohibits direct throw
throwMe(new RuntimeException("blargh"));
}
static void throwMe(RuntimeException ex) throws RuntimeException {
throw ex;
}
}
@SuppressWarnings("serial") /* Incorrect declarations are being tested. */
class B implements Serializable {
}
@SuppressWarnings("serial") /* Incorrect declarations are being tested. */
class C implements Serializable {
static { System.out.println("C.<clinit>"); }
}
@SuppressWarnings("serial") /* Incorrect declarations are being tested. */
class B1 extends B {
}
@SuppressWarnings("serial") /* Incorrect declarations are being tested. */
class B2 extends B {
static { System.out.println("B2.<clinit>"); }
}
@SuppressWarnings("serial") /* Incorrect declarations are being tested. */
class C1 extends C {
}
@SuppressWarnings("serial") /* Incorrect declarations are being tested. */
class C2 extends C {
static { System.out.println("C2.<clinit>"); }
}
public class GetSuidClinitError {
public static void main(String[] args) throws Exception {
Class<?> cl = Class.forName(
"A", false, GetSuidClinitError.class.getClassLoader());
for (int i = 0; i < 2; i++) {
try {
ObjectStreamClass.lookup(cl).getSerialVersionUID();
throw new Error();
} catch (ExceptionInInitializerError er) {
} catch (NoClassDefFoundError er) {
/*
* er _should_ be an ExceptionInInitializerError; however,
* hotspot currently throws a NoClassDefFoundError in this
* case, which runs against the JNI spec. For the purposes of
* testing this fix, however, permit either.
*/
System.out.println("warning: caught " + er +
" instead of ExceptionInInitializerError");
}
}
Class<?>[] cls = {
B.class, B1.class, B2.class,
C.class, C1.class, C2.class
};
long[] suids = new long[] { // 1.3.1 default serialVersionUIDs
369445310364440919L, 7585771686008346939L, -8952923334200087495L,
3145821251853463625L, 327577314910517070L, -92102021266426451L
};
for (int i = 0; i < cls.length; i++) {
if (ObjectStreamClass.lookup(cls[i]).getSerialVersionUID() !=
suids[i])
{
throw new Error();
}
}
}
}

View file

@ -0,0 +1,68 @@
/*
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4357979
* @summary Verify that ObjectInputStream throws a StreamCorruptedException if
* it reads in an out-of-bounds handle value.
*/
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
String base = System.getProperty("test.src", ".");
/*
* Files negativeHandle.ser and tooHighHandle.ser each contain a
* serialized String object followed by an illegal handle
*/
File f = new File(base, "negativeHandle.ser");
FileInputStream in = new FileInputStream(f);
try {
ObjectInputStream oin = new ObjectInputStream(in);
oin.readObject();
try {
oin.readObject();
throw new Error("negative handle read should not succeed");
} catch (StreamCorruptedException ex) {
}
} finally {
in.close();
}
f = new File(base, "tooHighHandle.ser");
in = new FileInputStream(f);
try {
ObjectInputStream oin = new ObjectInputStream(in);
oin.readObject();
try {
oin.readObject();
throw new Error("too-high handle read should not succeed");
} catch (StreamCorruptedException ex) {
}
} finally {
in.close();
}
}
}

View file

@ -0,0 +1,49 @@
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4400609
* @summary Verify that ObjectInputStream.registerValidation() throws a
* NotActiveException when invoked on inactive stream.
*/
import java.io.*;
public class InactiveRegistration {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject("foo");
oout.close();
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
try {
oin.registerValidation(new ObjectInputValidation() {
public void validateObject() throws InvalidObjectException {}
}, 0);
throw new Error(
"registerValidation should fail on inactive stream");
} catch (NotActiveException ex) {
}
}
}

View file

@ -0,0 +1,93 @@
/*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4217676
* @summary Ensure that object streams support serialization of long strings
* (strings whose UTF representation > 64k in length)
* @key randomness
*/
import java.io.*;
import java.util.*;
public class LongString {
public static void main(String[] args) throws Exception {
Random rand = new Random(System.currentTimeMillis());
ByteArrayOutputStream bout;
ByteArrayInputStream bin;
ObjectOutputStream oout;
ObjectInputStream oin;
FileInputStream fin;
File mesgf;
// generate a long random string
StringBuffer sbuf = new StringBuffer();
for (int i = 0; i < 100000; i++)
sbuf.append((char) rand.nextInt(Character.MAX_VALUE + 1));
String str = sbuf.toString();
// write and read long string
bout = new ByteArrayOutputStream();
oout = new ObjectOutputStream(bout);
oout.writeObject(str);
oout.flush();
bin = new ByteArrayInputStream(bout.toByteArray());
oin = new ObjectInputStream(bin);
String strcopy = (String) oin.readObject();
if (! str.equals(strcopy))
throw new Error("deserialized long string not equal to original");
// test backwards compatibility
String mesg = "Message in golden file";
bout = new ByteArrayOutputStream();
oout = new ObjectOutputStream(bout);
oout.writeObject(mesg);
oout.flush();
byte[] buf1 = bout.toByteArray();
mesgf = new File(System.getProperty("test.src", "."), "mesg.ser");
fin = new FileInputStream(mesgf);
bout = new ByteArrayOutputStream();
try {
while (fin.available() > 0)
bout.write(fin.read());
} finally {
fin.close();
}
byte[] buf2 = bout.toByteArray();
if (! Arrays.equals(buf1, buf2))
throw new Error("incompatible string format (write)");
fin = new FileInputStream(mesgf);
try {
oin = new ObjectInputStream(fin);
String mesgcopy = (String) oin.readObject();
if (! mesg.equals(mesgcopy))
throw new Error("incompatible string format (read)");
} finally {
fin.close();
}
}
}

Some files were not shown because too many files have changed in this diff Show more