From 8097a011b2ad166602b2495de0ce6e7578424c6f Mon Sep 17 00:00:00 2001 From: Eric Yang Date: Fri, 4 Feb 2022 12:00:52 -0800 Subject: [PATCH] Separate tests that rely on SecurityManager (Java8andUp) SecurityManager will be removed in a future jdk. Separate tests that rely on it so that they can be easily disabled in the future. Issue: #14412 Signed-off-by: Eric Yang --- test/functional/Java8andUp/build.xml | 68 +-- test/functional/Java8andUp/playlist.xml | 179 +++++++- .../Test_PackageAnnotation.java | 20 +- .../test/java/lang/Test_ClassLoader.java | 111 +---- .../test/java/lang/Test_ClassLoader_SM.java | 140 +++++++ .../openj9/test/java/lang/Test_Class_SM.java | 338 +++++++++++++++ .../java/lang/Test_J9VMInternalsImpl.java | 240 +---------- .../java/lang/Test_J9VMInternalsImpl_SM.java | 275 ++++++++++++ .../test/java/lang/Test_J9VMInternals_SM.java | 39 ++ .../openj9/test/java/lang/Test_System_SM.java | 144 +++++++ .../openj9/test/java/lang/Test_Thread.java | 220 +--------- .../test/java/lang/Test_ThreadGroup.java | 237 +---------- .../test/java/lang/Test_ThreadGroup_SM.java | 390 ++++++++++++++++++ .../openj9/test/java/lang/Test_Thread_SM.java | 273 ++++++++++++ .../lang/invoke/Test_MethodHandleInfo.java | 166 +------- .../lang/invoke/Test_MethodHandleInfo_SM.java | 199 +++++++++ .../Support_ExtendedTestEnvironment.java | 25 +- .../test/vmArguments/VmArgumentTests.java | 57 ++- .../org/openj9/test/java/lang/Test_Class.java | 289 +------------ .../openj9/test/java/lang/Test_System.java | 109 +---- .../org/openj9/test/java/lang/Test_Class.java | 306 +------------- .../openj9/test/java/lang/Test_System.java | 87 +--- test/functional/Java8andUp/testng.xml | 5 +- test/functional/Java8andUp/testng_sm.xml | 205 +++++++++ 24 files changed, 2274 insertions(+), 1848 deletions(-) create mode 100644 test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ClassLoader_SM.java create mode 100644 test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Class_SM.java create mode 100644 test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternalsImpl_SM.java create mode 100644 test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternals_SM.java create mode 100644 test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_System_SM.java create mode 100644 test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ThreadGroup_SM.java create mode 100644 test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Thread_SM.java create mode 100644 test/functional/Java8andUp/src/org/openj9/test/java/lang/invoke/Test_MethodHandleInfo_SM.java create mode 100644 test/functional/Java8andUp/testng_sm.xml diff --git a/test/functional/Java8andUp/build.xml b/test/functional/Java8andUp/build.xml index b7eec15d29d..00b08e282a8 100644 --- a/test/functional/Java8andUp/build.xml +++ b/test/functional/Java8andUp/build.xml @@ -33,6 +33,7 @@ SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-excepti + @@ -264,33 +265,46 @@ SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-excepti ===addExports: ${addExports} - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/functional/Java8andUp/playlist.xml b/test/functional/Java8andUp/playlist.xml index 59b45a42c7e..5ee28d14367 100644 --- a/test/functional/Java8andUp/playlist.xml +++ b/test/functional/Java8andUp/playlist.xml @@ -1065,6 +1065,52 @@ ibm + + JCL_Test_SM + + NoOptions + -XX:RecreateClassfileOnload + -XX:+CompactStrings + + $(JAVA_COMMAND) $(JAVA_SECURITY_MANAGER) $(JVM_OPTIONS) -verbose:stacktrace -Djava.security.policy=$(Q)$(TEST_RESROOT)$(D)java.policy$(Q) \ + -Drowset.provider.classname=org.openj9.resources.classloader.CustomSyncProvider \ + --add-modules openj9.sharedclasses $(ADD_MODULE_JAVA_SE_EE) \ + --add-exports java.base/com.ibm.oti.vm=ALL-UNNAMED \ + --add-exports java.base/com.ibm.oti.util=ALL-UNNAMED \ + --add-exports java.base/jdk.internal.vm.annotation=ALL-UNNAMED \ + --add-exports java.base/jdk.internal.misc=ALL-UNNAMED $(ADD_EXPORTS_JDK_INTERNAL_REFLECT) \ + --add-exports java.base/com.ibm.jit.crypto=ALL-UNNAMED \ + --add-exports java.base/com.ibm.oti.reflect=ALL-UNNAMED \ + --add-exports java.base/sun.net.www.protocol.jrt=ALL-UNNAMED \ + --add-opens=java.base/java.lang=ALL-UNNAMED \ + --add-opens=java.base/java.security=ALL-UNNAMED \ + $(ADD_EXPORTS_JDK_INTERNAL_ACCESS) \ + -cp $(Q)$(RESOURCES_DIR)$(P)$(TESTNG)$(P)$(TEST_RESROOT)$(D)GeneralTest.jar$(P)$(TEST_RESROOT)$(D)TestResources.jar$(P)$(LIB_DIR)$(D)asm-all.jar$(JAXB_API_JAR)$(Q) \ + org.testng.TestNG -d $(REPORTDIR) $(Q)$(TEST_RESROOT)$(D)testng_sm.xml$(Q) \ + -testnames \ + JCL_TEST_Java-Lang_SM,\ + JCL_TEST_Java-Lang-Invoke_SM,\ + JCL_TEST_Java-Lang_ClassLoader_SM,\ + JCL_TEST_IBM-VM_SM \ + -groups $(TEST_GROUP) \ + -excludegroups $(DEFAULT_EXCLUDE); \ + $(TEST_STATUS) + + sanity + + + functional + + + 11 + 17 + 18 + + + openj9 + ibm + + JCL_Test_Native @@ -1169,6 +1215,51 @@ ibm + + JCL_Test_SM_none_SCC + + -Xshareclasses:none + -Xshareclasses:none -XX:RecreateClassfileOnload + + $(JAVA_COMMAND) $(JAVA_SECURITY_MANAGER) $(JVM_OPTIONS) -verbose:stacktrace -Djava.security.policy=$(Q)$(TEST_RESROOT)$(D)java.policy$(Q) \ + -Drowset.provider.classname=org.openj9.resources.classloader.CustomSyncProvider \ + --add-modules openj9.sharedclasses $(ADD_MODULE_JAVA_SE_EE) \ + --add-exports java.base/com.ibm.oti.vm=ALL-UNNAMED \ + --add-exports java.base/com.ibm.oti.util=ALL-UNNAMED \ + --add-exports java.base/jdk.internal.vm.annotation=ALL-UNNAMED \ + --add-exports java.base/jdk.internal.misc=ALL-UNNAMED $(ADD_EXPORTS_JDK_INTERNAL_REFLECT) \ + --add-exports java.base/com.ibm.jit.crypto=ALL-UNNAMED \ + --add-exports java.base/com.ibm.oti.reflect=ALL-UNNAMED \ + --add-exports java.base/sun.net.www.protocol.jrt=ALL-UNNAMED \ + --add-opens=java.base/java.lang=ALL-UNNAMED \ + --add-opens=java.base/java.security=ALL-UNNAMED \ + $(ADD_EXPORTS_JDK_INTERNAL_ACCESS) \ + -cp $(Q)$(RESOURCES_DIR)$(P)$(TESTNG)$(P)$(TEST_RESROOT)$(D)GeneralTest.jar$(P)$(TEST_RESROOT)$(D)TestResources.jar$(P)$(LIB_DIR)$(D)asm-all.jar$(JAXB_API_JAR)$(Q) \ + org.testng.TestNG -d $(REPORTDIR) $(Q)$(TEST_RESROOT)$(D)testng_sm.xml$(Q) \ + -testnames \ + JCL_TEST_Java-Lang_SM,\ + JCL_TEST_Java-Lang-Invoke_SM,\ + JCL_TEST_Java-Lang_ClassLoader_SM,\ + JCL_TEST_IBM-VM_SM \ + -groups $(TEST_GROUP) \ + -excludegroups $(DEFAULT_EXCLUDE); \ + $(TEST_STATUS) + + sanity + + + functional + + + 11 + 17 + 18 + + + openj9 + ibm + + JCL_Test_none_SCC_Native @@ -1264,7 +1355,7 @@ $(JAVA_COMMAND) $(JVM_OPTIONS) -verbose:stacktrace -Djava.security.policy=$(Q)$(TEST_RESROOT)$(D)java.policy$(Q) \ -cp $(Q)$(RESOURCES_DIR)$(P)$(TESTNG)$(P)$(TEST_RESROOT)$(D)GeneralTest.jar$(P)$(TEST_RESROOT)$(D)TestResources.jar$(P)$(LIB_DIR)$(D)asm-all.jar$(Q) \ -Drowset.provider.classname=org.openj9.resources.classloader.CustomSyncProvider \ - org.testng.TestNG -d $(REPORTDIR) $(Q)$(TEST_RESROOT)$(D)testng.xml$(Q) \ + org.testng.TestNG -d $(REPORTDIR) $(Q)$(TEST_RESROOT)$(D)testng_sm.xml$(Q) \ -testnames \ JCL_TEST_Test-TypeAnnotation,\ JCL_TEST_Test-Annotation,\ @@ -1272,11 +1363,14 @@ JCL_TEST_Test-Annotation-ClassLoader,\ JCL_TEST_Test-Annotation-Package,\ JCL_TEST_Java-Lang_ClassLoader,\ + JCL_TEST_Java-Lang_ClassLoader_SM,\ JCL_TEST_Test-Defects,\ JCL_TEST_Test-UnsafeFence,\ JCL_TEST_IBM-VM,\ JCL_TEST_Java-Lang,\ + JCL_TEST_Java-Lang_SM,\ JCL_TEST_Java-Lang-Invoke,\ + JCL_TEST_Java-Lang-Invoke_SM,\ JCL_TEST_Java-Lang-Ref,\ JCL_TEST_Java-Lang-Reflect,\ JCL_TEST_Java-Math,\ @@ -1383,7 +1477,6 @@ -groups $(TEST_GROUP) \ -excludegroups $(DEFAULT_EXCLUDE); \ $(TEST_STATUS) - ^vm.hrt sanity @@ -1391,7 +1484,41 @@ functional - 9+ + 11 + 17 + 18 + + + openj9 + ibm + + + + J9VMInternals_Test_SM + + NoOptions + + $(MKDIR) -p $(REPORTDIR); \ + cd $(REPORTDIR); \ + $(JAVA_COMMAND) $(JAVA_SECURITY_MANAGER) $(JVM_OPTIONS) -verbose:stacktrace \ + -Djava.security.policy=$(Q)$(TEST_RESROOT)$(D)java.policy$(Q) \ + -Xbootclasspath/a:$(TEST_RESROOT)$(D)TestResources.jar \ + -cp $(Q)$(RESOURCES_DIR)$(P)$(TESTNG)$(P)$(TEST_RESROOT)$(D)GeneralTest.jar$(P)$(TEST_RESROOT)$(D)TestResources.jar$(P)$(LIB_DIR)$(D)asm-all.jar$(Q) \ + org.testng.TestNG -d $(REPORTDIR) $(Q)$(TEST_RESROOT)$(D)testng_sm.xml$(Q) \ + -testnames JCL_TEST_Java-Internals_SM \ + -groups $(TEST_GROUP) \ + -excludegroups $(DEFAULT_EXCLUDE); \ + $(TEST_STATUS) + + sanity + + + functional + + + 11 + 17 + 18 openj9 @@ -1410,8 +1537,10 @@ -Djava.security.policy=$(Q)$(TEST_RESROOT)$(D)java.policy$(Q) \ -Xbootclasspath/a:$(TEST_RESROOT)$(D)TestResources.jar \ -cp $(Q)$(RESOURCES_DIR)$(P)$(TESTNG)$(P)$(TEST_RESROOT)$(D)GeneralTest.jar$(P)$(TEST_RESROOT)$(D)TestResources.jar$(P)$(LIB_DIR)$(D)asm-all.jar$(Q) \ - org.testng.TestNG -d $(REPORTDIR) $(Q)$(TEST_RESROOT)$(D)testng.xml$(Q) \ - -testnames JCL_TEST_Java-Internals \ + org.testng.TestNG -d $(REPORTDIR) $(Q)$(TEST_RESROOT)$(D)testng_sm.xml$(Q) \ + -testnames \ + JCL_TEST_Java-Internals,\ + JCL_TEST_Java-Internals_SM \ -groups $(TEST_GROUP) \ -excludegroups $(DEFAULT_EXCLUDE); \ $(TEST_STATUS) @@ -1443,8 +1572,10 @@ -Djava.security.policy=$(Q)$(TEST_RESROOT)$(D)testacc.policy$(Q) \ -Xbootclasspath/a:$(TEST_RESROOT)$(D)TestResources.jar \ -cp $(Q)$(RESOURCES_DIR)$(P)$(TESTNG)$(P)$(TEST_RESROOT)$(D)GeneralTest.jar$(P)$(TEST_RESROOT)$(D)TestResources.jar$(P)$(LIB_DIR)$(D)asm-all.jar$(Q) \ - org.testng.TestNG -d $(REPORTDIR) $(Q)$(TEST_RESROOT)$(D)testng.xml$(Q) \ - -testnames JCL_TEST_Java-Security \ + org.testng.TestNG -d $(REPORTDIR) $(Q)$(TEST_RESROOT)$(D)testng_sm.xml$(Q) \ + -testnames \ + JCL_TEST_Java-Security,\ + JCL_TEST_Java-Security_SM \ -groups $(TEST_GROUP) \ -excludegroups $(DEFAULT_EXCLUDE); \ $(TEST_STATUS) @@ -1504,6 +1635,40 @@ ibm + + JCL_TEST_Java-Security_SM + + NoOptions + + $(JAVA_COMMAND) $(JAVA_SECURITY_MANAGER) $(JVM_OPTIONS) -verbose:stacktrace \ + --add-modules openj9.sharedclasses $(ADD_MODULE_JAVA_SE_EE) \ + --add-exports java.base/com.ibm.oti.util=ALL-UNNAMED \ + --add-opens=java.base/java.lang=ALL-UNNAMED \ + --add-opens=java.base/java.security=ALL-UNNAMED \ + -Djava.security.policy=$(Q)$(TEST_RESROOT)$(D)testacc.policy$(Q) \ + -Xbootclasspath/a:$(TEST_RESROOT)$(D)TestResources.jar \ + -cp $(Q)$(RESOURCES_DIR)$(P)$(TESTNG)$(P)$(TEST_RESROOT)$(D)GeneralTest.jar$(P)$(TEST_RESROOT)$(D)TestResources.jar$(P)$(LIB_DIR)$(D)asm-all.jar$(Q) \ + org.testng.TestNG -d $(REPORTDIR) $(Q)$(TEST_RESROOT)$(D)testng_sm.xml$(Q) \ + -testnames JCL_TEST_Java-Security_SM \ + -groups $(TEST_GROUP) \ + -excludegroups $(DEFAULT_EXCLUDE); \ + $(TEST_STATUS) + + sanity + + + functional + + + 11 + 17 + 18 + + + openj9 + ibm + + JCL_Test_JITHelpers_SE80 $(JAVA_COMMAND) $(JVM_OPTIONS) \ diff --git a/test/functional/Java8andUp/src/org/openj9/test/annotationPackage/Test_PackageAnnotation.java b/test/functional/Java8andUp/src/org/openj9/test/annotationPackage/Test_PackageAnnotation.java index c5f0e4ea3f6..c7bd609a89a 100644 --- a/test/functional/Java8andUp/src/org/openj9/test/annotationPackage/Test_PackageAnnotation.java +++ b/test/functional/Java8andUp/src/org/openj9/test/annotationPackage/Test_PackageAnnotation.java @@ -7,7 +7,7 @@ import org.testng.AssertJUnit; /******************************************************************************* - * Copyright (c) 2010, 2018 IBM Corp. and others + * Copyright (c) 2010, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -29,8 +29,6 @@ *******************************************************************************/ import java.net.URL; import java.net.URLClassLoader; -import java.security.AccessController; -import java.security.PrivilegedAction; import javax.xml.bind.annotation.XmlSchema; @Test(groups = { "level.sanity" }) @@ -123,16 +121,12 @@ private static String toString(Class clazz) { } private static ClassLoader getClassLoader(final Class clazz) { - return AccessController.doPrivileged(new PrivilegedAction() { - public ClassLoader run() { - ClassLoader cl = null; - try { - cl = clazz.getClassLoader(); - } catch (SecurityException ex) { - } - return cl; - } - }); + ClassLoader cl = null; + try { + cl = clazz.getClassLoader(); + } catch (SecurityException ex) { + } + return cl; } } diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ClassLoader.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ClassLoader.java index 6eb03e4f1c3..af1bad1ac49 100644 --- a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ClassLoader.java +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ClassLoader.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 1998, 2019 IBM Corp. and others + * Copyright (c) 1998, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -416,113 +416,4 @@ void loadClassInParallelHelper(MyClassLoader mcl) { } } - /** - * [PR Jazz103 76960] - * - * @tests java.lang.ClassLoader#getParent() Test the case when in - * getParent() the callerClassLoader is same as child of this - * classloader. getParent() should throw SecurityException in such - * case. - */ - @Test - public void test_getParent1() { - ClassLoader cl = this.getClass().getClassLoader(); - ClassLoader parentCl = cl.getParent(); - - SecurityManager manager = new SecurityManager(); - System.setSecurityManager(manager); - try { - parentCl.getParent(); - Assert.fail("expected the above call to getParent() to throw SecurityException"); - } catch (SecurityException e) { - /* expected exception */ - } finally { - System.setSecurityManager(null); - } - } - - /** - * [PR Jazz103 76960] - * - * @tests java.lang.ClassLoader#getParent() Test the case when in - * getParent() the callerClassLoader is same as this classloader. - * getParent() should throw SecurityException in such case. - */ - @Test - public void test_getParent2() { - ClassLoader cl = this.getClass().getClassLoader(); - SecurityManager manager = new SecurityManager(); - - System.setSecurityManager(manager); - try { - cl.getParent(); - Assert.fail("expected the above call to getParent() to throw SecurityException"); - } catch (SecurityException e) { - /* expected exception */ - } finally { - System.setSecurityManager(null); - } - } - - /** - * @tests java.lang.ClassLoader#getParent() Test the case when in - * getParent() the callerClassLoader is same as parent of this - * classloader. This should cause the condition (callerClassLoader != - * requested) in ClassLoader.needsClassLoaderPermissionCheck() to - * fail, thus preventing any security checks in getParent(). - */ - @Test - public void test_getParent3() { - class ChildClassLoader extends ClassLoader { - public ChildClassLoader(ClassLoader parent) { - super(parent); - } - } - - ClassLoader cl = this.getClass().getClassLoader(); - ChildClassLoader childCL = new ChildClassLoader(cl); - - SecurityManager manager = new SecurityManager(); - System.setSecurityManager(manager); - try { - childCL.getParent(); - } catch (SecurityException e) { - Assert.fail("unexpected exception: " + e); - } finally { - System.setSecurityManager(null); - } - } - - /** - * @tests java.lang.ClassLoader#getParent() Test the case when in - * getParent() the callerClassLoader is same as grand parent of this - * classloader (that is an ancestor of the parent of this - * classloader) This should cause the condition - * !callerClassLoader.isAncestorOf(requested) in - * ClassLoader.needsClassLoaderPermissionCheck() to fail, thus - * preventing any security checks in getParent(). - */ - @Test - public void test_getParent4() { - class ChildClassLoader extends ClassLoader { - public ChildClassLoader(ClassLoader parent) { - super(parent); - } - } - - ClassLoader cl = this.getClass().getClassLoader(); - ChildClassLoader child = new ChildClassLoader(cl); - ChildClassLoader grandChild = new ChildClassLoader(child); - - SecurityManager manager = new SecurityManager(); - System.setSecurityManager(manager); - try { - grandChild.getParent(); - } catch (SecurityException e) { - Assert.fail("unexpected exception: " + e); - } finally { - System.setSecurityManager(null); - } - } - } diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ClassLoader_SM.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ClassLoader_SM.java new file mode 100644 index 00000000000..80f111204fe --- /dev/null +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ClassLoader_SM.java @@ -0,0 +1,140 @@ +/******************************************************************************* + * Copyright (c) 2022, 2022 IBM Corp. and others + * + * This program and the accompanying materials are made available under + * the terms of the Eclipse Public License 2.0 which accompanies this + * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ + * or the Apache License, Version 2.0 which accompanies this distribution and + * is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * This Source Code may also be made available under the following + * Secondary Licenses when the conditions for such availability set + * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU + * General Public License, version 2 with the GNU Classpath + * Exception [1] and GNU General Public License, version 2 with the + * OpenJDK Assembly Exception [2]. + * + * [1] https://www.gnu.org/software/classpath/license.html + * [2] http://openjdk.java.net/legal/assembly-exception.html + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception + *******************************************************************************/ +package org.openj9.test.java.lang; + +import org.testng.annotations.Test; +import org.testng.Assert; +import org.testng.AssertJUnit; + +@Test(groups = { "level.sanity" }) +public class Test_ClassLoader_SM { + + /** + * [PR Jazz103 76960] + * + * @tests java.lang.ClassLoader#getParent() Test the case when in + * getParent() the callerClassLoader is same as child of this + * classloader. getParent() should throw SecurityException in such + * case. + */ + @Test + public void test_getParent1() { + ClassLoader cl = this.getClass().getClassLoader(); + ClassLoader parentCl = cl.getParent(); + + SecurityManager manager = new SecurityManager(); + System.setSecurityManager(manager); + try { + parentCl.getParent(); + Assert.fail("expected the above call to getParent() to throw SecurityException"); + } catch (SecurityException e) { + /* expected exception */ + } finally { + System.setSecurityManager(null); + } + } + + /** + * [PR Jazz103 76960] + * + * @tests java.lang.ClassLoader#getParent() Test the case when in + * getParent() the callerClassLoader is same as this classloader. + * getParent() should throw SecurityException in such case. + */ + @Test + public void test_getParent2() { + ClassLoader cl = this.getClass().getClassLoader(); + SecurityManager manager = new SecurityManager(); + + System.setSecurityManager(manager); + try { + cl.getParent(); + Assert.fail("expected the above call to getParent() to throw SecurityException"); + } catch (SecurityException e) { + /* expected exception */ + } finally { + System.setSecurityManager(null); + } + } + + /** + * @tests java.lang.ClassLoader#getParent() Test the case when in + * getParent() the callerClassLoader is same as parent of this + * classloader. This should cause the condition (callerClassLoader != + * requested) in ClassLoader.needsClassLoaderPermissionCheck() to + * fail, thus preventing any security checks in getParent(). + */ + @Test + public void test_getParent3() { + class ChildClassLoader extends ClassLoader { + public ChildClassLoader(ClassLoader parent) { + super(parent); + } + } + + ClassLoader cl = this.getClass().getClassLoader(); + ChildClassLoader childCL = new ChildClassLoader(cl); + + SecurityManager manager = new SecurityManager(); + System.setSecurityManager(manager); + try { + childCL.getParent(); + } catch (SecurityException e) { + Assert.fail("unexpected exception: " + e); + } finally { + System.setSecurityManager(null); + } + } + + /** + * @tests java.lang.ClassLoader#getParent() Test the case when in + * getParent() the callerClassLoader is same as grand parent of this + * classloader (that is an ancestor of the parent of this + * classloader) This should cause the condition + * !callerClassLoader.isAncestorOf(requested) in + * ClassLoader.needsClassLoaderPermissionCheck() to fail, thus + * preventing any security checks in getParent(). + */ + @Test + public void test_getParent4() { + class ChildClassLoader extends ClassLoader { + public ChildClassLoader(ClassLoader parent) { + super(parent); + } + } + + ClassLoader cl = this.getClass().getClassLoader(); + ChildClassLoader child = new ChildClassLoader(cl); + ChildClassLoader grandChild = new ChildClassLoader(child); + + SecurityManager manager = new SecurityManager(); + System.setSecurityManager(manager); + try { + grandChild.getParent(); + } catch (SecurityException e) { + Assert.fail("unexpected exception: " + e); + } finally { + System.setSecurityManager(null); + } + } + +} diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Class_SM.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Class_SM.java new file mode 100644 index 00000000000..89e23795aa9 --- /dev/null +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Class_SM.java @@ -0,0 +1,338 @@ +package org.openj9.test.java.lang; + +/******************************************************************************* + * Copyright (c) 2022, 2022 IBM Corp. and others + * + * This program and the accompanying materials are made available under + * the terms of the Eclipse Public License 2.0 which accompanies this + * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ + * or the Apache License, Version 2.0 which accompanies this distribution and + * is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * This Source Code may also be made available under the following + * Secondary Licenses when the conditions for such availability set + * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU + * General Public License, version 2 with the GNU Classpath + * Exception [1] and GNU General Public License, version 2 with the + * OpenJDK Assembly Exception [2]. + * + * [1] https://www.gnu.org/software/classpath/license.html + * [2] http://openjdk.java.net/legal/assembly-exception.html + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception + *******************************************************************************/ + +import org.testng.annotations.Test; +import org.testng.log4testng.Logger; +import org.testng.Assert; +import org.testng.AssertJUnit; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.ClassLoader; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.security.*; + +import org.openj9.test.support.resource.Support_Resources; + +/** + * + * @requiredClass org.openj9.test.support.resource.Support_Resources + * @requiredResource org/openj9/resources/openj9tr_compressD.txt + * @requiredResource org/openj9/resources/openj9tr_general.jar + * @requiredResource org/openj9/resources/openj9tr_Foo.c + */ +@Test(groups = { "level.sanity" }) +public class Test_Class_SM { + private static final Logger logger = Logger.getLogger(Test_Class_SM.class); + + @Test + public void test_getMethods_subtest2() { + PrivilegedAction action = new PrivilegedAction() { + @Override + public Object run() { + try { + File resources = Support_Resources.createTempFolder(); + String[] expected_E = new String[] { + "org.openj9.resources.classinheritance.E.method_N(java.lang.String)", + "org.openj9.resources.classinheritance.E.method_M(java.lang.String)", + "org.openj9.resources.classinheritance.A.method_K(java.lang.String)", + "org.openj9.resources.classinheritance.E.method_L(java.lang.String)", + "org.openj9.resources.classinheritance.E.method_O(java.lang.String)", + "org.openj9.resources.classinheritance.B.method_K(java.lang.String)"}; + + Support_Resources.copyFile(resources, null, "openj9tr_general.jar"); + File file = new File(resources.toString() + "/openj9tr_general.jar"); + URL url = new URL("file:" + file.getPath()); + ClassLoader loader = new URLClassLoader(new URL[] { url }, null); + + Class cls_E = Class.forName("org.openj9.resources.classinheritance.E", false, loader); + Method[] methodNames_E = cls_E.getMethods(); + AssertJUnit.assertEquals("Returned incorrect number of methods for cls_E", expected_E.length + Object.class.getMethods().length, methodNames_E.length); + for (int i = 0; i < expected_E.length; i++) { + boolean match = false; + for (int j = 0; j < methodNames_E.length; j++) { + if (methodNames_E[j].toString().indexOf(expected_E[i]) != -1) { + match = true; + } + } + AssertJUnit.assertTrue("Expected method " + expected_E[i] + " not found.", match); + } + } catch (MalformedURLException e) { + logger.error("Unexpected exception: " + e); + } catch (ClassNotFoundException e) { + logger.error("Unexpected exception: " + e); + } + + return null; + } + }; + AccessController.doPrivileged(action); + } + + /** + * @tests java.lang.Class#getClasses() + */ + @Test + public void test_getClasses2() { + final Permission privCheckPermission = new BasicPermission("Privilege check") { + }; + class MyCombiner implements DomainCombiner { + boolean combine; + public ProtectionDomain[] combine(ProtectionDomain[] executionDomains, ProtectionDomain[] parentDomains) { + combine = true; + return new ProtectionDomain[0]; + } + public boolean isPriviledged() { + combine = false; + try { + AccessController.checkPermission(privCheckPermission); + } catch (SecurityException e) { + } + return !combine; + } + }; + final MyCombiner combiner = new MyCombiner(); + class SecurityManagerCheck extends SecurityManager { + String reason; + Class checkClass; + int checkType; + int checkPermission = 0; + int checkMemberAccess = 0; + int checkPackageAccess = 0; + + public void setExpected(String reason, Class cls, int type) { + this.reason = reason; + checkClass = cls; + checkType = type; + checkPermission = 0; + checkMemberAccess = 0; + checkPackageAccess = 0; + } + public void checkPermission(Permission perm) { + if (combiner.isPriviledged()) + return; + checkPermission++; + } + public void checkPackageAccess(String packageName) { + if (packageName.startsWith("java.") || packageName.startsWith("org.openj9.test.java.lang")) { + return; + } + if (combiner.isPriviledged()) + return; + checkPackageAccess++; + String name = checkClass.getName(); + int index = name.lastIndexOf('.'); + String checkPackage = name.substring(0, index); + AssertJUnit.assertTrue(reason + " unexpected package: " + packageName, packageName.equals(checkPackage)); + } + public void assertProperCalls() { + int declared = checkType == Member.DECLARED ? 1 : 0; + AssertJUnit.assertTrue(reason + " unexpected checkPermission count: " + checkPermission, checkPermission == declared); + AssertJUnit.assertTrue(reason + " unexpected checkPackageAccess count: " + checkPackageAccess, checkPackageAccess == 1); + } + } + + final SecurityManagerCheck sm = new SecurityManagerCheck(); + + AccessControlContext acc = new AccessControlContext(new ProtectionDomain[0]); + AccessControlContext acc2 = new AccessControlContext(acc, combiner); + + PrivilegedAction action = new PrivilegedAction() { + public Object run() { + File resources = Support_Resources.createTempFolder(); + try { + Support_Resources.copyFile(resources, null, "openj9tr_general.jar"); + File file = new File(resources.toString() + "/openj9tr_general.jar"); + URL url = new URL("file:" + file.getPath()); + ClassLoader loader = new URLClassLoader(new URL[]{url}, null); + Class cls = Class.forName("org.openj9.resources.security.SecurityTestSub", false, loader); + // must preload junit.framework.Assert before installing SecurityManager + // otherwise loading it inside checkPackageAccess() is recursive + AssertJUnit.assertTrue("preload assertions", true); + System.setSecurityManager(sm); + try { + sm.setExpected("getClasses", cls, java.lang.reflect.Member.PUBLIC); + cls.getClasses(); + sm.assertProperCalls(); + + sm.setExpected("getDeclaredClasses", cls, java.lang.reflect.Member.DECLARED); + cls.getDeclaredClasses(); + sm.assertProperCalls(); + + sm.setExpected("getConstructor", cls, java.lang.reflect.Member.PUBLIC); + cls.getConstructor(new Class[0]); + sm.assertProperCalls(); + + sm.setExpected("getConstructors", cls, java.lang.reflect.Member.PUBLIC); + cls.getConstructors(); + sm.assertProperCalls(); + + sm.setExpected("getDeclaredConstructor", cls, java.lang.reflect.Member.DECLARED); + cls.getDeclaredConstructor(new Class[0]); + sm.assertProperCalls(); + + sm.setExpected("getDeclaredConstructors", cls, java.lang.reflect.Member.DECLARED); + cls.getDeclaredConstructors(); + sm.assertProperCalls(); + + sm.setExpected("getField", cls, java.lang.reflect.Member.PUBLIC); + cls.getField("publicField"); + sm.assertProperCalls(); + + sm.setExpected("getFields", cls, java.lang.reflect.Member.PUBLIC); + cls.getFields(); + sm.assertProperCalls(); + + sm.setExpected("getDeclaredField", cls, java.lang.reflect.Member.DECLARED); + cls.getDeclaredField("publicField"); + sm.assertProperCalls(); + + sm.setExpected("getDeclaredFields", cls, java.lang.reflect.Member.DECLARED); + cls.getDeclaredFields(); + sm.assertProperCalls(); + + sm.setExpected("getDeclaredMethod", cls, java.lang.reflect.Member.DECLARED); + cls.getDeclaredMethod("publicMethod", new Class[0]); + sm.assertProperCalls(); + + sm.setExpected("getDeclaredMethods", cls, java.lang.reflect.Member.DECLARED); + cls.getDeclaredMethods(); + sm.assertProperCalls(); + + sm.setExpected("getMethod", cls, java.lang.reflect.Member.PUBLIC); + cls.getMethod("publicMethod", new Class[0]); + sm.assertProperCalls(); + + sm.setExpected("getMethods", cls, java.lang.reflect.Member.PUBLIC); + cls.getMethods(); + sm.assertProperCalls(); + + sm.setExpected("newInstance", cls, java.lang.reflect.Member.PUBLIC); + cls.newInstance(); + sm.assertProperCalls(); + } finally { + System.setSecurityManager(null); + } + } catch (Exception e) { + if (e instanceof RuntimeException) + throw (RuntimeException)e; + Assert.fail("unexpected exception: " + e); + } + return null; + } + }; + AccessController.doPrivileged(action, acc2); + } + + /** + * @tests java.lang.Class#getResource(java.lang.String) + */ + @Test + public void test_getResource() { + // Test for method java.net.URL java.lang.Class.getResource(java.lang.String) + System.setSecurityManager(new SecurityManager()); + try { + URL res = Object.class.getResource("Object.class"); + AssertJUnit.assertTrue("Object.class should not be found", res == null); + } finally { + System.setSecurityManager(null); + } + + String name = "/org/openj9/resources/openj9tr_Foo.c"; + + // find resource from object + AssertJUnit.assertTrue("directory of this class can be found", + Test_Class_SM.class.getResource(name) != null); + + // find resource from array of objects + AssertJUnit.assertTrue("directory of array of this class can be found", + Test_Class_SM[].class.getResource(name) != null); + } + + /** + * @tests java.lang.Class#getResourceAsStream(java.lang.String) + */ + @Test + public void test_getResourceAsStream() { + // Test for method java.io.InputStream java.lang.Class.getResourceAsStream(java.lang.String) + String name = Support_Resources.RESOURCE_PACKAGE + "openj9tr_compressD.txt"; + Class clazz = null; + try { + clazz = Class.forName("org.openj9.test.java.lang.Test_Class_SM"); + } catch (ClassNotFoundException e) { + AssertJUnit.assertTrue("Should be able to find the class org.openj9.test.java.lang.Test_Class_SM", false); + } + AssertJUnit.assertTrue("the file " + name + " can not be found in this directory", + clazz.getResourceAsStream(name) != null); + + System.setSecurityManager(new SecurityManager()); + try { + InputStream res = Object.class.getResourceAsStream("Object.class"); + AssertJUnit.assertTrue("Object.class should not be found", res == null); + } finally { + System.setSecurityManager(null); + } + + name = "org/openj9/resources/openj9tr_Foo.c"; + AssertJUnit.assertTrue("the file " + name + " should not be found in this directory", + clazz.getResourceAsStream(name) == null); + AssertJUnit.assertTrue("the file " + name + " can be found in the root directory", + clazz.getResourceAsStream("/" + name) != null); + // find resource from array of objects + AssertJUnit.assertTrue("the file " + name + " can be found in the root directory where the class is an array", + Test_Class_SM[].class.getResourceAsStream("/" + name) != null); + + try { + clazz = Class.forName("java.lang.Object"); + } catch (ClassNotFoundException e) { + AssertJUnit.assertTrue("Should be able to find the class java.lang.Object", false); + } + InputStream str = clazz.getResourceAsStream("Class.class"); + AssertJUnit.assertTrue( + "java.lang.Object couldn't find its class with getResource...", + str != null); + try { + AssertJUnit.assertTrue("Cannot read single byte", str.read() != -1); + AssertJUnit.assertTrue("Cannot read multiple bytes", str.read(new byte[5]) == 5); + str.close(); + } catch (IOException e) { + AssertJUnit.assertTrue("Exception while closing resource stream 1.", false); + } + + InputStream str2 = getClass().getResourceAsStream(Support_Resources.RESOURCE_PACKAGE + "openj9tr_compressD.txt"); + AssertJUnit.assertTrue("Can't find resource", str2 != null); + try { + AssertJUnit.assertTrue("Cannot read single byte", str2.read() != -1); + AssertJUnit.assertTrue("Cannot read multiple bytes", str2.read(new byte[5]) == 5); + str2.close(); + } catch (IOException e) { + AssertJUnit.assertTrue("Exception while closing resource stream 2.", false); + } + } + +} diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternalsImpl.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternalsImpl.java index 383cc6aadde..9f5a5db3734 100644 --- a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternalsImpl.java +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternalsImpl.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2013, 2019 IBM Corp. and others + * Copyright (c) 2013, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -24,11 +24,6 @@ import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; -import java.security.AccessController; -import java.security.AllPermission; -import java.security.CodeSource; -import java.security.PermissionCollection; -import java.security.PrivilegedExceptionAction; import org.testng.Assert; import org.testng.annotations.Test; @@ -38,26 +33,12 @@ public class Test_J9VMInternalsImpl { private static final String ORG_TESTNG = "org.testng"; //$NON-NLS-1$ - private static final String TEST_RESTRICTED = "$TestRestricted"; //$NON-NLS-1$ static final Logger logger = Logger.getLogger(Test_J9VMInternalsImpl.class); public static class NCDFEHelper { /* intentionally empty */ } - public static class SuperclassRestricted extends sun.misc.test.RestrictedClass { - static { - logger.debug("FAILED: clinit of SuperclassRestricted called"); //$NON-NLS-1$ - } - - } - - public static class InterfaceRestricted implements sun.misc.test.RestrictedInterface { - static { - logger.debug("FAILED: clinit of InterfaceRestricted called"); //$NON-NLS-1$ - } - } - public static class TestNCDFE { private static int testCount = 1; @@ -104,182 +85,12 @@ public void runTest1() { } } - /* - * The test must be performed in a different ClassLoader, - * because the default application ClassLoader has a built in check for package access. - */ - public static class TestRestricted { - private static int testCount = 2; - - /* - * We need a local logger because referring to the logger refers to the outer class, - * which our special classloader cannot load. - */ - private static final Logger restrictedLogger = Logger.getLogger(TestRestricted.class); - - public static void startTest(String testing) { - restrictedLogger.debug("\nTest " + testCount++ + ": " + testing); //$NON-NLS-1$ //$NON-NLS-2$ - } - - public void runTest2(final String className) throws Exception { - /* stop security checks here */ - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - // must create the classloader in an environment with sufficient privilege, as it remembers its context - ClassLoader loader = new URLClassLoader( - new URL[] { getClass().getProtectionDomain().getCodeSource().getLocation() }, - getClass().getClassLoader()); - System.setSecurityManager(new SecurityManager()); - try { - - startTest("try instantiating from a restricted package 1st time"); //$NON-NLS-1$ - @SuppressWarnings("rawtypes") - Class cl = Class.forName(className + "$TestHelper1", true, loader); //$NON-NLS-1$ - Runnable testRunner = (Runnable)cl.newInstance(); - try { - testRunner.run(); - Assert.fail("FAILED: successfully created an instance of a restricted package"); //$NON-NLS-1$ - } catch (SecurityException e) { - /* intentionally empty */ - } - - startTest("try instantiating from a restricted package 2nd time"); //$NON-NLS-1$ - try { - testRunner.run(); - Assert.fail("FAILED: successfully created an instance of a restricted package 2nd time"); //$NON-NLS-1$ - } catch (SecurityException e) { - /* intentionally empty */ - } - - @SuppressWarnings("rawtypes") - Class cl2 = Class.forName(className + "$TestHelper2", true, loader); //$NON-NLS-1$ - Runnable testRunner2 = (Runnable)cl2.newInstance(); - testRunner2.run(); - - } finally { - System.setSecurityManager(null); - } - return null; - } - }); - } - } - - public static class TestHelper1 implements Runnable { - @Override - public void run() { - new sun.misc.test.RestrictedClass(); - } - } - - public static class TestHelper2 extends TestRestricted implements Runnable { - private static final String RESTRICTED_CLASS = "sun.misc.test.RestrictedClass"; //$NON-NLS-1$ - - @Override - public void run() { - startTest("try loading class from a restricted package using Class.forName()"); //$NON-NLS-1$ - try { - @SuppressWarnings({ "unused", "rawtypes" }) - Class cl2 = Class.forName(RESTRICTED_CLASS); - Assert.fail("FAILED: unexpected behavior: successfully loaded " //$NON-NLS-1$ - + RESTRICTED_CLASS + " using forName"); //$NON-NLS-1$ - } catch (SecurityException e) { - logger.debug("PASSED: forName of" //$NON-NLS-1$ - + RESTRICTED_CLASS + ": " + e); //$NON-NLS-1$ - } catch (ClassNotFoundException e) { - Assert.fail("FAILED: unexpected: " + e); //$NON-NLS-1$ - } - - startTest("try casting to a class in a restricted package"); //$NON-NLS-1$ - try { - Object o = new Object(); - @SuppressWarnings("unused") - sun.misc.test.RestrictedClass encoder = (sun.misc.test.RestrictedClass)o; - Assert.fail("FAILED: successfully cast to" + RESTRICTED_CLASS); //$NON-NLS-1$ - } catch (ClassCastException e) { - Assert.fail("FAILED: cast to" //$NON-NLS-1$ - + RESTRICTED_CLASS + ": " + e); //$NON-NLS-1$ - } catch (SecurityException e) { - logger.debug("PASSED: casting to" //$NON-NLS-1$ - + RESTRICTED_CLASS + ": " + e); //$NON-NLS-1$ - } - - startTest("try testing instanceof a restricted package"); //$NON-NLS-1$ - try { - Object o = new Object(); - if (o instanceof sun.misc.test.RestrictedClass) { - /* intentionally empty */ - } - Assert.fail("FAILED: successfully tested instanceof" //$NON-NLS-1$ - + RESTRICTED_CLASS); - } catch (SecurityException e) { - logger.debug("PASSED: instanceof" //$NON-NLS-1$ - + RESTRICTED_CLASS + ": " + e); //$NON-NLS-1$ - } - - startTest("try calling a static method in a restricted package"); //$NON-NLS-1$ - try { - sun.misc.test.RestrictedClass.myStaticMethod(); - Assert.fail("FAILED: called static method on " + RESTRICTED_CLASS); //$NON-NLS-1$ - } catch (SecurityException e) { - logger.debug("PASSED: calling static method on " //$NON-NLS-1$ - + RESTRICTED_CLASS + " : " + e); //$NON-NLS-1$ - } - - startTest("try accessing a static field in a restricted package"); //$NON-NLS-1$ - try { - @SuppressWarnings({ "unused" }) - Object result = com.ibm.oti.util.ReflectPermissions.permissionSuppressAccessChecks; - Assert.fail( - "FAILED: accessed static field in com.ibm.oti.util.ReflectPermissions"); //$NON-NLS-1$ - } catch (SecurityException e) { - logger.debug( - "PASSED: accessing static field on sun.misc.ASCIICaseInsensitiveComparator: " + e); //$NON-NLS-1$ - } - } - } - - public static class TestHelper3 extends TestRestricted implements Runnable { - @Override - public void run() { - /* intentionally empty */ - } - } - @Test public void test_checkPackageAccess() throws Throwable { final String className = getClass().getName(); - System.setSecurityManager(new SecurityManager()); - try { - /* - * these tests are not dependent on the ClassLoader behaviour - */ - try { - @SuppressWarnings("rawtypes") - Class cl = Class.forName(className + "$SuperclassRestricted"); //$NON-NLS-1$ - Assert.fail("FAILED: successfully loaded " //$NON-NLS-1$ - + cl + " with restricted superclass"); //$NON-NLS-1$ - } catch (SecurityException e) { - /* intentionally empty */ - } - - try { - @SuppressWarnings("rawtypes") - Class cl = Class.forName(className + "$InterfaceRestricted"); //$NON-NLS-1$ - Assert.fail("FAILED: successfully loaded " //$NON-NLS-1$ - + cl + " with restricted interface"); //$NON-NLS-1$ - } catch (SecurityException e) { - /* intentionally empty */ - } - - } finally { - System.setSecurityManager(null); - } - /* - * special ClassLoader that changes behavior every time the + * special ClassLoader that changes behavior every time the * $NCDFEHelper class load is attempted */ ClassLoader loader1 = new URLClassLoader( @@ -316,51 +127,6 @@ public Class findClass(String name) throws ClassNotFoundException { @SuppressWarnings("unchecked") Method testMethod1 = cl1.getMethod("runTest1"); //$NON-NLS-1$ testMethod1.invoke(testInstance1); - - /* - * Create a ClassLoader with AllPermission so classes loaded by this loader - * are not restricted by the default permissions of the application ClassLoader. - */ - ClassLoader privilegedLoader = new URLClassLoader( - new URL[] { getClass().getProtectionDomain().getCodeSource().getLocation() }, null) { - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Class findClass(String name) throws ClassNotFoundException { - Class result; - if (name.startsWith(ORG_TESTNG)) { - result = Class.forName(name, true, ClassLoader.getSystemClassLoader()); - } else { - if (!name.startsWith(className + TEST_RESTRICTED)) { - throw new ClassNotFoundException(name); - } - result = super.findClass(name); - } - return result; - } - - @Override - public PermissionCollection getPermissions(CodeSource csource) { - PermissionCollection permCollection = super.getPermissions(csource); - /* - * Allow AllPermission so we can use this classloader - * to define a custom SecurityManager. - */ - permCollection.add(new AllPermission()); - return permCollection; - } - }; - - /* - * These tests are dependent on the ClassLoader behaviour. - * The default application ClassLoader checks package access of the classes being loaded. - * Other ClassLoaders don't have this behaviour - * and depend on the VM to do the check. We wish to test the VM behavior. - */ - @SuppressWarnings("rawtypes") - Class cl2 = Class.forName(className + TEST_RESTRICTED, true, privilegedLoader); - Object testInstance2 = cl2.newInstance(); - @SuppressWarnings("unchecked") - Method testMethod2 = cl2.getMethod("runTest2", String.class); //$NON-NLS-1$ - testMethod2.invoke(testInstance2, className); } + } diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternalsImpl_SM.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternalsImpl_SM.java new file mode 100644 index 00000000000..b471473e71e --- /dev/null +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternalsImpl_SM.java @@ -0,0 +1,275 @@ +/******************************************************************************* + * Copyright (c) 2022, 2022 IBM Corp. and others + * + * This program and the accompanying materials are made available under + * the terms of the Eclipse Public License 2.0 which accompanies this + * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ + * or the Apache License, Version 2.0 which accompanies this distribution and + * is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * This Source Code may also be made available under the following + * Secondary Licenses when the conditions for such availability set + * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU + * General Public License, version 2 with the GNU Classpath + * Exception [1] and GNU General Public License, version 2 with the + * OpenJDK Assembly Exception [2]. + * + * [1] https://www.gnu.org/software/classpath/license.html + * [2] http://openjdk.java.net/legal/assembly-exception.html + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception + *******************************************************************************/ +package org.openj9.test.java.lang; + +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.security.AccessController; +import java.security.AllPermission; +import java.security.CodeSource; +import java.security.PermissionCollection; +import java.security.PrivilegedExceptionAction; + +import org.testng.Assert; +import org.testng.annotations.Test; +import org.testng.log4testng.Logger; + +@Test(groups = { "level.sanity" }) +public class Test_J9VMInternalsImpl_SM { + + private static final String ORG_TESTNG = "org.testng"; //$NON-NLS-1$ + private static final String TEST_RESTRICTED = "$TestRestricted"; //$NON-NLS-1$ + static final Logger logger = Logger.getLogger(Test_J9VMInternalsImpl_SM.class); + + public static class SuperclassRestricted extends sun.misc.test.RestrictedClass { + static { + logger.debug("FAILED: clinit of SuperclassRestricted called"); //$NON-NLS-1$ + } + } + + public static class InterfaceRestricted implements sun.misc.test.RestrictedInterface { + static { + logger.debug("FAILED: clinit of InterfaceRestricted called"); //$NON-NLS-1$ + } + } + + /* + * The test must be performed in a different ClassLoader, + * because the default application ClassLoader has a built in check for package access. + */ + public static class TestRestricted { + private static int testCount = 2; + + /* + * We need a local logger because referring to the logger refers to the outer class, + * which our special classloader cannot load. + */ + private static final Logger restrictedLogger = Logger.getLogger(TestRestricted.class); + + public static void startTest(String testing) { + restrictedLogger.debug("\nTest " + testCount++ + ": " + testing); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public void runTest2(final String className) throws Exception { + /* stop security checks here */ + AccessController.doPrivileged(new PrivilegedExceptionAction() { + @Override + public Object run() throws Exception { + // must create the classloader in an environment with sufficient privilege, as it remembers its context + ClassLoader loader = new URLClassLoader( + new URL[] { getClass().getProtectionDomain().getCodeSource().getLocation() }, + getClass().getClassLoader()); + System.setSecurityManager(new SecurityManager()); + try { + + startTest("try instantiating from a restricted package 1st time"); //$NON-NLS-1$ + @SuppressWarnings("rawtypes") + Class cl = Class.forName(className + "$TestHelper1", true, loader); //$NON-NLS-1$ + Runnable testRunner = (Runnable)cl.newInstance(); + try { + testRunner.run(); + Assert.fail("FAILED: successfully created an instance of a restricted package"); //$NON-NLS-1$ + } catch (SecurityException e) { + /* intentionally empty */ + } + + startTest("try instantiating from a restricted package 2nd time"); //$NON-NLS-1$ + try { + testRunner.run(); + Assert.fail("FAILED: successfully created an instance of a restricted package 2nd time"); //$NON-NLS-1$ + } catch (SecurityException e) { + /* intentionally empty */ + } + + @SuppressWarnings("rawtypes") + Class cl2 = Class.forName(className + "$TestHelper2", true, loader); //$NON-NLS-1$ + Runnable testRunner2 = (Runnable)cl2.newInstance(); + testRunner2.run(); + + } finally { + System.setSecurityManager(null); + } + return null; + } + }); + } + } + + public static class TestHelper1 implements Runnable { + @Override + public void run() { + new sun.misc.test.RestrictedClass(); + } + } + + public static class TestHelper2 extends TestRestricted implements Runnable { + private static final String RESTRICTED_CLASS = "sun.misc.test.RestrictedClass"; //$NON-NLS-1$ + + @Override + public void run() { + startTest("try loading class from a restricted package using Class.forName()"); //$NON-NLS-1$ + try { + @SuppressWarnings({ "unused", "rawtypes" }) + Class cl2 = Class.forName(RESTRICTED_CLASS); + Assert.fail("FAILED: unexpected behavior: successfully loaded " //$NON-NLS-1$ + + RESTRICTED_CLASS + " using forName"); //$NON-NLS-1$ + } catch (SecurityException e) { + logger.debug("PASSED: forName of " //$NON-NLS-1$ + + RESTRICTED_CLASS + ": " + e); //$NON-NLS-1$ + } catch (ClassNotFoundException e) { + Assert.fail("FAILED: unexpected: " + e); //$NON-NLS-1$ + } + + startTest("try casting to a class in a restricted package"); //$NON-NLS-1$ + try { + Object o = new Object(); + @SuppressWarnings("unused") + sun.misc.test.RestrictedClass encoder = (sun.misc.test.RestrictedClass)o; + Assert.fail("FAILED: successfully cast to " + RESTRICTED_CLASS); //$NON-NLS-1$ + } catch (ClassCastException e) { + Assert.fail("FAILED: cast to " //$NON-NLS-1$ + + RESTRICTED_CLASS + ": " + e); //$NON-NLS-1$ + } catch (SecurityException e) { + logger.debug("PASSED: casting to " //$NON-NLS-1$ + + RESTRICTED_CLASS + ": " + e); //$NON-NLS-1$ + } + + startTest("try testing instanceof a restricted package"); //$NON-NLS-1$ + try { + Object o = new Object(); + if (o instanceof sun.misc.test.RestrictedClass) { + /* intentionally empty */ + } + Assert.fail("FAILED: successfully tested instanceof " //$NON-NLS-1$ + + RESTRICTED_CLASS); + } catch (SecurityException e) { + logger.debug("PASSED: instanceof " //$NON-NLS-1$ + + RESTRICTED_CLASS + ": " + e); //$NON-NLS-1$ + } + + startTest("try calling a static method in a restricted package"); //$NON-NLS-1$ + try { + sun.misc.test.RestrictedClass.myStaticMethod(); + Assert.fail("FAILED: called static method on " + RESTRICTED_CLASS); //$NON-NLS-1$ + } catch (SecurityException e) { + logger.debug("PASSED: calling static method on " //$NON-NLS-1$ + + RESTRICTED_CLASS + " : " + e); //$NON-NLS-1$ + } + + startTest("try accessing a static field in a restricted package"); //$NON-NLS-1$ + try { + @SuppressWarnings({ "unused" }) + Object result = com.ibm.oti.util.ReflectPermissions.permissionSuppressAccessChecks; + Assert.fail("FAILED: accessed static field in com.ibm.oti.util.ReflectPermissions"); //$NON-NLS-1$ + } catch (SecurityException e) { + logger.debug("PASSED: accessing static field on sun.misc.ASCIICaseInsensitiveComparator: " + e); //$NON-NLS-1$ + } + } + } + + public static class TestHelper3 extends TestRestricted implements Runnable { + @Override + public void run() { + /* intentionally empty */ + } + } + + @Test + public void test_checkPackageAccess() throws Throwable { + final String className = getClass().getName(); + + System.setSecurityManager(new SecurityManager()); + try { + /* + * these tests are not dependent on the ClassLoader behaviour + */ + try { + @SuppressWarnings("rawtypes") + Class cl = Class.forName(className + "$SuperclassRestricted"); //$NON-NLS-1$ + Assert.fail("FAILED: successfully loaded " //$NON-NLS-1$ + + cl + " with restricted superclass"); //$NON-NLS-1$ + } catch (SecurityException e) { + /* intentionally empty */ + } + + try { + @SuppressWarnings("rawtypes") + Class cl = Class.forName(className + "$InterfaceRestricted"); //$NON-NLS-1$ + Assert.fail("FAILED: successfully loaded " //$NON-NLS-1$ + + cl + " with restricted interface"); //$NON-NLS-1$ + } catch (SecurityException e) { + /* intentionally empty */ + } + + } finally { + System.setSecurityManager(null); + } + + /* + * Create a ClassLoader with AllPermission so classes loaded by this loader + * are not restricted by the default permissions of the application ClassLoader. + */ + ClassLoader privilegedLoader = new URLClassLoader( + new URL[] { getClass().getProtectionDomain().getCodeSource().getLocation() }, null) { + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public Class findClass(String name) throws ClassNotFoundException { + Class result; + if (name.startsWith(ORG_TESTNG)) { + result = Class.forName(name, true, ClassLoader.getSystemClassLoader()); + } else { + if (!name.startsWith(className + TEST_RESTRICTED)) { + throw new ClassNotFoundException(name); + } + result = super.findClass(name); + } + return result; + } + + @Override + public PermissionCollection getPermissions(CodeSource csource) { + PermissionCollection permCollection = super.getPermissions(csource); + /* + * Allow AllPermission so we can use this classloader + * to define a custom SecurityManager. + */ + permCollection.add(new AllPermission()); + return permCollection; + } + }; + + /* + * These tests are dependent on the ClassLoader behaviour. + * The default application ClassLoader checks package access of the classes being loaded. + * Other ClassLoaders don't have this behaviour + * and depend on the VM to do the check. We wish to test the VM behavior. + */ + @SuppressWarnings("rawtypes") + Class cl2 = Class.forName(className + TEST_RESTRICTED, true, privilegedLoader); + Object testInstance2 = cl2.newInstance(); + @SuppressWarnings("unchecked") + Method testMethod2 = cl2.getMethod("runTest2", String.class); //$NON-NLS-1$ + testMethod2.invoke(testInstance2, className); + } + +} diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternals_SM.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternals_SM.java new file mode 100644 index 00000000000..0e8afe5eb3d --- /dev/null +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_J9VMInternals_SM.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (c) 2022, 2022 IBM Corp. and others + * + * This program and the accompanying materials are made available under + * the terms of the Eclipse Public License 2.0 which accompanies this + * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ + * or the Apache License, Version 2.0 which accompanies this distribution and + * is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * This Source Code may also be made available under the following + * Secondary Licenses when the conditions for such availability set + * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU + * General Public License, version 2 with the GNU Classpath + * Exception [1] and GNU General Public License, version 2 with the + * OpenJDK Assembly Exception [2]. + * + * [1] https://www.gnu.org/software/classpath/license.html + * [2] http://openjdk.java.net/legal/assembly-exception.html + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception + *******************************************************************************/ +package org.openj9.test.java.lang; + +import org.testng.annotations.Test; + +@Test(groups = { "level.sanity" }) +public class Test_J9VMInternals_SM { +/* + * TestNG parses the test file, which interferes with the classloading under test. + * Put the test implementation in a separate file to prevent this interference. + */ + + @Test + public void test_checkPackageAccess() throws Throwable { + Test_J9VMInternalsImpl_SM testObject = new Test_J9VMInternalsImpl_SM(); + testObject.test_checkPackageAccess(); + } + +} diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_System_SM.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_System_SM.java new file mode 100644 index 00000000000..82003308e28 --- /dev/null +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_System_SM.java @@ -0,0 +1,144 @@ +package org.openj9.test.java.lang; + +/******************************************************************************* + * Copyright (c) 2022, 2022 IBM Corp. and others + * + * This program and the accompanying materials are made available under + * the terms of the Eclipse Public License 2.0 which accompanies this + * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ + * or the Apache License, Version 2.0 which accompanies this distribution and + * is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * This Source Code may also be made available under the following + * Secondary Licenses when the conditions for such availability set + * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU + * General Public License, version 2 with the GNU Classpath + * Exception [1] and GNU General Public License, version 2 with the + * OpenJDK Assembly Exception [2]. + * + * [1] https://www.gnu.org/software/classpath/license.html + * [2] http://openjdk.java.net/legal/assembly-exception.html + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception + *******************************************************************************/ + +import org.testng.annotations.Test; +import org.testng.annotations.BeforeMethod; +import org.testng.Assert; +import org.testng.AssertJUnit; +import java.security.Permission; + +import org.openj9.test.support.Support_Exec; +import org.openj9.test.util.VersionCheck; + +@Test(groups = { "level.sanity" }) +public class Test_System_SM { + + /** + * @tests java.lang.System#getSecurityManager() + */ + @Test + public void test_getSecurityManager() { + AssertJUnit.assertTrue("Returned incorrect SecurityManager", System.getSecurityManager() == null); + } + + /** + * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) + */ + @Test + public void test_setSecurityManager() { + /* [PR 97686, 123113] Improve System.setSecurityManager() initialization */ + class MySecurityManager extends SecurityManager { + public void preloadClasses(Permission perm) { + if (!(perm instanceof RuntimePermission) + || !(perm.getName().toLowerCase().equals("setsecuritymanager")) + ) { + // do nothing, required classes are now loaded + } + } + + public void checkPermission(Permission perm) { + if (!(perm instanceof RuntimePermission) + || !(perm.getName().toLowerCase().equals("setsecuritymanager")) + ) { + super.checkPermission(perm); + } + } + } + + MySecurityManager newManager = new MySecurityManager(); + // preload the required classes without calling implies() + try { + newManager.preloadClasses(new RuntimePermission("anything")); + } catch (SecurityException e) { + } + try { + System.setSecurityManager(new SecurityManager()); + System.getProperty("someProperty"); + Assert.fail("should cause SecurityException"); + } catch (SecurityException e) { + // expected + } finally { + System.setSecurityManager(null); + } + } + + /** + * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) + */ + @Test + public void test_setSecurityManager2() { + try { + String helperName = "org.openj9.test.java.lang.Test_System_SM$TestSecurityManager"; + String output = Support_Exec.execJava(new String[] { + "-Djava.security.manager=" + helperName, helperName }, + null, true); + AssertJUnit.assertTrue("not correct SecurityManager: " + output, output.startsWith(helperName)); + } catch (Exception e) { + Assert.fail("Unexpected: " + e); + } + } + + /** + * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) + */ + public static class TestSecurityManager extends SecurityManager { + public static void main(String[] args) { + System.out + .println(System.getSecurityManager().getClass().getName()); + } + } + + /** + * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) + */ + @Test + public void test_setSecurityManager3() { + /* https://github.com/eclipse-openj9/openj9/issues/6661 */ + if (VersionCheck.major() >= 11) { + try { + String helperName = "org.openj9.test.java.lang.Test_System_SM$TestSecurityManagerNonPublicConstructor"; + String output = Support_Exec.execJava(new String[] { "-Djava.security.manager=" + helperName, helperName }, + null, true, + "java.lang.NoSuchMethodException: org.openj9.test.java.lang.Test_System_SM$TestSecurityManagerNonPublicConstructor.()"); + // if the expected error string was not found, Assert.fail() will be invoked + // within Support_Exec.execJava() above. + } catch (Exception e) { + Assert.fail("Unexpected: " + e); + } + } + } + + /** + * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) + */ + public static class TestSecurityManagerNonPublicConstructor extends SecurityManager { + TestSecurityManagerNonPublicConstructor() { + } + + public static void main(String[] args) { + System.out.println(System.getSecurityManager().getClass().getName()); + } + } + +} diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Thread.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Thread.java index 1a17e94ff9b..515d1ed1c09 100644 --- a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Thread.java +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Thread.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 1998, 2021 IBM Corp. and others + * Copyright (c) 1998, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -123,37 +123,10 @@ public BogusException(String s) { Thread st, ct, spinner; - static boolean calledMySecurityManager = false; - // used in test_defaultMemoryArea to pass status from thread started // back to thread running test case boolean pass = true; - /** - * @tests java.lang.Thread#Thread() - */ - @Test - public void test_Constructor() { - Thread t; - SecurityManager m = new SecurityManager() { - public ThreadGroup getThreadGroup() { - calledMySecurityManager = true; - return Thread.currentThread().getThreadGroup(); - } - }; - try { - System.setSecurityManager(m); // To see if it checks Thread creation - // with our SecurityManager - - t = new Thread(); - } finally { - System.setSecurityManager(null); // restore original, no - // side-effects - } - AssertJUnit.assertTrue("Did not call SecurityManager.getThreadGroup ()", calledMySecurityManager); - t.start(); - } - /** * @tests java.lang.Thread#Thread(java.lang.Runnable) */ @@ -262,93 +235,6 @@ public void test_activeCount() { } } - /** - * @tests java.lang.Thread#checkAccess() - */ - @Test - public void test_checkAccess() { - ThreadGroup tg = new ThreadGroup("Test Group3"); - try { - st = new Thread(tg, new SimpleThread(1), "SimpleThread5"); - st.checkAccess(); - AssertJUnit.assertTrue("CheckAccess passed", true); - } catch (SecurityException e) { - Assert.fail("CheckAccess failed", e); - } - st.start(); - try { - st.join(); - } catch (InterruptedException e) { - } - tg.destroy(); - } - - /** - * @tests java.lang.Thread#checkAccess_interrupt_self() - */ - @Test - public void test_checkAccess_interrupt_self() { - try { - System.setSecurityManager(new SecurityManager() { - public void checkAccess(Thread t) { - Assert.fail("CheckAccess() was invoked"); - } - }); - - Thread.currentThread().interrupt(); - AssertJUnit.assertTrue("Failed to interrupt current thread", Thread.interrupted()); - } finally { - System.setSecurityManager(null); - } - } - - /** - * @tests java.lang.Thread#checkAccess_interrupt_not_self() - */ - @Test - public void test_checkAccess_interrupt_not_self() { - try { - SimpleThread simple = new SimpleThread(5000); - - st = new Thread(simple); - - synchronized (simple) { - st.start(); - - try { - simple.wait(); - } catch (InterruptedException e) { - } - } - - class MySecurityManager extends SecurityManager { - public volatile boolean called = false; - - public void checkAccess(Thread t) { - called = true; - } - } - - MySecurityManager sm = new MySecurityManager(); - - System.setSecurityManager(sm); - - AssertJUnit.assertTrue("Thread should be alive", st.isAlive()); - - st.interrupt(); - - AssertJUnit.assertTrue("checkAccess() was not called", sm.called); - - try { - st.join(10000); - } catch (InterruptedException e) { - Assert.fail("Join failed ", e); - } - } finally { - System.setSecurityManager(null); - } - } - /** * @tests java.lang.Thread#countStackFrames() */ @@ -493,72 +379,6 @@ public synchronized void run() { mytg.destroy(); } - /** - * @tests java.lang.Thread#getContextClassLoader() - */ - @Test - public void test_getContextClassLoader() { - Thread t = new Thread(); - AssertJUnit.assertTrue("Incorrect class loader returned", - t.getContextClassLoader() == Thread.currentThread().getContextClassLoader()); - t.start(); - - /* [PR CMVC 90230] behavior change in 1.5 */ - // behavior change in 1.5, Thread constructors should call - // parentThread.getContextClassLoader() - // instead of accessing field - final ClassLoader loader = new ClassLoader() { - }; - class ContextThread extends Thread { - private ClassLoader contextClassLoader; - - public ClassLoader getContextClassLoader() { - return contextClassLoader; - } - - public void setContextClassLoader(ClassLoader loader) { - contextClassLoader = loader; - } - - public void run() { - Thread thread = new Thread(); - ClassLoader contextLoader = thread.getContextClassLoader(); - AssertJUnit.assertTrue("incorrect context class loader", contextLoader == loader); - } - } - ; - Thread sub = new ContextThread(); - sub.setContextClassLoader(loader); - sub.start(); - /* [PR CMVC 90230] behavior change in 1.5 */ - // behavior change in 1.5, Thread constructors should check - // enableContextClassLoaderOverride - // if thread overrides getContextClassLoader() or - // setContextClassLoader() */ - class SubContextThread extends ContextThread { - } - ; - System.setSecurityManager(new SecurityManager()); - try { - // creating a new Thread, or subclass of Thread should not cause an - // exception - new Thread(); - new Thread() { - }; - boolean exception = false; - try { - new SubContextThread(); - } catch (SecurityException e) { - AssertJUnit.assertTrue("wrong exception: " + e, - e.getMessage().indexOf("enableContextClassLoaderOverride") != -1); - exception = true; - } - AssertJUnit.assertTrue("exception not thrown", exception); - } finally { - System.setSecurityManager(null); - } - } - /** * @tests java.lang.Thread#getName() */ @@ -1169,44 +989,6 @@ public void test_stop() { AssertJUnit.assertTrue("Failed to stopThread", !st.isAlive()); } - /** - * @tests java.lang.Thread#stop() - */ - @Test - public void test_stop2() { - /* [PR CMVC 94728] AccessControlException on dead Thread */ - Thread t = new Thread("t"); - class MySecurityManager extends SecurityManager { - public boolean intest = false; - - public void checkAccess(Thread t) { - if (intest) { - Assert.fail("checkAccess called"); - } - } - } - MySecurityManager sm = new MySecurityManager(); - System.setSecurityManager(sm); - try { - sm.intest = false; - t.start(); - try { - t.join(2000); - } catch (InterruptedException e) { - } - sm.intest = true; - try { - t.stop(); - // Ignore any SecurityExceptions, may not have stopThread - // permission - } catch (SecurityException e) { - } - sm.intest = false; - } finally { - System.setSecurityManager(null); - } - } - /** * @tests java.lang.Thread#stop(java.lang.Throwable) */ diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ThreadGroup.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ThreadGroup.java index eb1b713ef00..3b408c2ae65 100644 --- a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ThreadGroup.java +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ThreadGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 1998, 2019 IBM Corp. and others + * Copyright (c) 1998, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -214,31 +214,6 @@ public void run() { AssertJUnit.assertTrue("group not destroyed", tg.isDestroyed()); } - /** - * @tests java.lang.ThreadGroup#checkAccess() - */ - @Test - public void test_checkAccess() { - final ThreadGroup originalCurrent = getInitialThreadGroup(); - ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group"); - - SecurityManager currentManager = System.getSecurityManager(); - boolean passed = true; - - try { - if (currentManager != null) - testRoot.checkAccess(); - } catch (SecurityException se) { - passed = false; - } - ; - - AssertJUnit.assertTrue("CheckAccess is no-op with no Securitymanager", passed); - - testRoot.destroy(); - - } - /** * @tests java.lang.ThreadGroup#destroy() */ @@ -467,58 +442,6 @@ public void test_getName() { } - static ThreadGroup checkAccessGroup = null; - - /** - * @tests java.lang.ThreadGroup#getParent() - */ - @Test - public void test_getParent() { - final ThreadGroup originalCurrent = getInitialThreadGroup(); - ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group"); - - AssertJUnit.assertTrue("Parent is wrong", testRoot.getParent() == originalCurrent); - - // Create some groups, nested some levels. - final int TOTAL_DEPTH = 5; - ThreadGroup current = testRoot; - Vector groups = new Vector(); - // To maintain the invariant that a thread in the Vector is parent - // of the next one in the collection (and child of the previous one) - groups.addElement(testRoot); - - for (int i = 0; i < TOTAL_DEPTH; i++) { - current = new ThreadGroup(current, "level " + i); - groups.addElement(current); - } - - // Now we walk the levels down, checking if parent is ok - for (int i = 1; i < groups.size(); i++) { - current = (ThreadGroup)groups.elementAt(i); - ThreadGroup previous = (ThreadGroup)groups.elementAt(i - 1); - AssertJUnit.assertTrue("Parent is wrong", current.getParent() == previous); - } - - /* [PR 97314] ThreadGroup.getParent() should call parent.checkAccess() */ - SecurityManager m = new SecurityManager() { - public void checkAccess(ThreadGroup group) { - checkAccessGroup = group; - } - }; - ThreadGroup parent; - try { - System.setSecurityManager(m); // To see if it checks Thread creation - // with our SecurityManager - parent = testRoot.getParent(); - } finally { - System.setSecurityManager(null); // restore original, no - // side-effects - } - AssertJUnit.assertTrue("checkAccess with incorrect group", checkAccessGroup == parent); - - testRoot.destroy(); - } - /** * @tests java.lang.ThreadGroup#isDaemon() */ @@ -575,36 +498,6 @@ public void test_list() { } - /** - * @tests java.lang.ThreadGroup#parentOf(java.lang.ThreadGroup) - */ - @Test - public void test_parentOf() { - final ThreadGroup originalCurrent = getInitialThreadGroup(); - final ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group"); - final int DEPTH = 4; - buildRandomTreeUnder(testRoot, DEPTH); - - final ThreadGroup[] allChildren = allGroups(testRoot); - for (int i = 0; i < allChildren.length; i++) { - AssertJUnit.assertTrue("Have to be parentOf all children", testRoot.parentOf((ThreadGroup)allChildren[i])); - } - - AssertJUnit.assertTrue("Have to be parentOf itself", testRoot.parentOf(testRoot)); - - testRoot.destroy(); - AssertJUnit.assertTrue("Parent can't have test group as subgroup anymore", - !arrayIncludes(groups(testRoot.getParent()), testRoot)); - - /* [PR 97314] ThreadGroup.getParent() should call parent.checkAccess() */ - try { - System.setSecurityManager(new SecurityManager()); - AssertJUnit.assertTrue("Should not be parent", !testRoot.parentOf(originalCurrent)); - } finally { - System.setSecurityManager(null); - } - } - /** * @tests java.lang.ThreadGroup#resume() */ @@ -727,134 +620,6 @@ public void run() { AssertJUnit.assertTrue("daemon not destroyed", daemonGroup.isDestroyed()); } - /** - * @tests java.lang.ThreadGroup#setMaxPriority(int) - */ - @Test - public void test_setMaxPriority() { - final ThreadGroup originalCurrent = getInitialThreadGroup(); - ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group"); - - boolean passed; - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /* - * [PR 1FJ9S51] If new priority is greater than the current maximum, the - * maximum remains unchanged - */ - int currentMax = testRoot.getMaxPriority(); - testRoot.setMaxPriority(Thread.MAX_PRIORITY + 1); - passed = testRoot.getMaxPriority() == currentMax; - AssertJUnit.assertTrue("setMaxPriority: Any value higher than the current one is ignored. Before: " + currentMax - + " , after: " + testRoot.getMaxPriority(), passed); - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*[PR CMVC 177870] Java7:JCK:java_lang/ThreadGroup/setMaxPriority fails in all platform */ - currentMax = testRoot.getMaxPriority(); - testRoot.setMaxPriority(Thread.MIN_PRIORITY - 1); - passed = testRoot.getMaxPriority() == currentMax; - AssertJUnit.assertTrue("setMaxPriority: Any value smaller than MIN_PRIORITY is ignored. Before: " + currentMax - + " , after: " + testRoot.getMaxPriority(), passed); - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /* - * [PR 1FJ9S51] The test above now has side-effect, so we destroy and - * create a new one - */ - testRoot.destroy(); - testRoot = new ThreadGroup(originalCurrent, "Test group"); - - // Create some groups, nested some levels. Each level will have maxPrio - // 1 unit smaller - // than the parent's. However, there can't be a group with priority < - // Thread.MIN_PRIORITY - final int TOTAL_DEPTH = testRoot.getMaxPriority() - Thread.MIN_PRIORITY - 2; - ThreadGroup current = testRoot; - for (int i = 0; i < TOTAL_DEPTH; i++) { - current = new ThreadGroup(current, "level " + i); - } - - // Now we walk the levels down, changing the maxPrio and later verifying - // that the value - // is indeed 1 unit smaller than the parent's maxPrio. - int maxPrio, parentMaxPrio; - current = testRoot; - - // To maintain the invariant that when we are to modify a child, - // its maxPriority is always 1 unit smaller than its parent's. - // We have to set it for the root manually, and the loop does the rest - // for all - // the other sub-levels - current.setMaxPriority(current.getParent().getMaxPriority() - 1); - - for (int i = 0; i < TOTAL_DEPTH; i++) { - maxPrio = current.getMaxPriority(); - parentMaxPrio = current.getParent().getMaxPriority(); - - ThreadGroup[] children = groups(current); - AssertJUnit.assertTrue("Can only have 1 subgroup", children.length == 1); - current = children[0]; - AssertJUnit.assertTrue( - "Had to be 1 unit smaller than parent's priority in iteration=" + i + " checking->" + current, - maxPrio == parentMaxPrio - 1); - current.setMaxPriority(maxPrio - 1); - - // The next test is sort of redundant, since in next iteration it - // will be the - // parent tGroup, so the test will be done. - AssertJUnit.assertTrue("Had to be possible to change max priority", - current.getMaxPriority() == maxPrio - 1); - } - - AssertJUnit.assertTrue("Priority of leaf child group has to be much smaller than original root group", - current.getMaxPriority() == testRoot.getMaxPriority() - TOTAL_DEPTH); - - testRoot.destroy(); - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - passed = true; - testRoot = new ThreadGroup(originalCurrent, "Test group"); - try { - testRoot.setMaxPriority(Thread.MAX_PRIORITY); - } catch (IllegalArgumentException iae) { - passed = false; - } - AssertJUnit.assertTrue( - "Max Priority = Thread.MAX_PRIORITY should be possible if the test is run with default system ThreadGroup as root", - passed); - testRoot.destroy(); - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - passed = true; - testRoot = new ThreadGroup(originalCurrent, "Test group"); - System.setSecurityManager(new SecurityManager()); - try { - try { - testRoot.setMaxPriority(Thread.MIN_PRIORITY); - } catch (IllegalArgumentException iae) { - passed = false; - } - } finally { - System.setSecurityManager(null); - } - AssertJUnit.assertTrue("Min Priority = Thread.MIN_PRIORITY should be possible, always", passed); - testRoot.destroy(); - - /* [PR 97314] ThreadGroup.getParent() should call parent.checkAccess() */ - try { - System.setSecurityManager(new SecurityManager()); - /* [PR 97314] Should not cause a SecurityException */ - originalCurrent.setMaxPriority(Thread.MAX_PRIORITY); - } finally { - System.setSecurityManager(null); - } - } - /** * @tests java.lang.ThreadGroup#stop() */ diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ThreadGroup_SM.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ThreadGroup_SM.java new file mode 100644 index 00000000000..7ae4485107c --- /dev/null +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_ThreadGroup_SM.java @@ -0,0 +1,390 @@ +/******************************************************************************* + * Copyright (c) 2022, 2022 IBM Corp. and others + * + * This program and the accompanying materials are made available under + * the terms of the Eclipse Public License 2.0 which accompanies this + * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ + * or the Apache License, Version 2.0 which accompanies this distribution and + * is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * This Source Code may also be made available under the following + * Secondary Licenses when the conditions for such availability set + * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU + * General Public License, version 2 with the GNU Classpath + * Exception [1] and GNU General Public License, version 2 with the + * OpenJDK Assembly Exception [2]. + * + * [1] https://www.gnu.org/software/classpath/license.html + * [2] http://openjdk.java.net/legal/assembly-exception.html + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception + *******************************************************************************/ +package org.openj9.test.java.lang; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.Test; +import org.testng.log4testng.Logger; +import org.testng.annotations.BeforeMethod; +import org.testng.Assert; +import org.testng.AssertJUnit; +import java.util.Vector; + +@Test(groups = { "level.sanity" }) +public class Test_ThreadGroup_SM { + + private ThreadGroup rootThreadGroup = null; + private ThreadGroup initialThreadGroup = null; + + private ThreadGroup getInitialThreadGroup() { + return initialThreadGroup; + } + + /** + * @tests java.lang.ThreadGroup#checkAccess() + */ + @Test + public void test_checkAccess() { + final ThreadGroup originalCurrent = getInitialThreadGroup(); + ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group"); + + SecurityManager currentManager = System.getSecurityManager(); + boolean passed = true; + + try { + if (currentManager != null) + testRoot.checkAccess(); + } catch (SecurityException se) { + passed = false; + } + + AssertJUnit.assertTrue("CheckAccess is no-op with no Securitymanager", passed); + + testRoot.destroy(); + } + + static ThreadGroup checkAccessGroup = null; + + /** + * @tests java.lang.ThreadGroup#getParent() + */ + @Test + public void test_getParent() { + final ThreadGroup originalCurrent = getInitialThreadGroup(); + ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group"); + + AssertJUnit.assertTrue("Parent is wrong", testRoot.getParent() == originalCurrent); + + // Create some groups, nested some levels. + final int TOTAL_DEPTH = 5; + ThreadGroup current = testRoot; + Vector groups = new Vector(); + // To maintain the invariant that a thread in the Vector is parent + // of the next one in the collection (and child of the previous one) + groups.addElement(testRoot); + + for (int i = 0; i < TOTAL_DEPTH; i++) { + current = new ThreadGroup(current, "level " + i); + groups.addElement(current); + } + + // Now we walk the levels down, checking if parent is ok + for (int i = 1; i < groups.size(); i++) { + current = (ThreadGroup)groups.elementAt(i); + ThreadGroup previous = (ThreadGroup)groups.elementAt(i - 1); + AssertJUnit.assertTrue("Parent is wrong", current.getParent() == previous); + } + + /* [PR 97314] ThreadGroup.getParent() should call parent.checkAccess() */ + SecurityManager m = new SecurityManager() { + public void checkAccess(ThreadGroup group) { + checkAccessGroup = group; + } + }; + ThreadGroup parent; + try { + System.setSecurityManager(m); // To see if it checks Thread creation + // with our SecurityManager + parent = testRoot.getParent(); + } finally { + System.setSecurityManager(null); // restore original, no + // side-effects + } + AssertJUnit.assertTrue("checkAccess with incorrect group", checkAccessGroup == parent); + + testRoot.destroy(); + } + + /** + * @tests java.lang.ThreadGroup#parentOf(java.lang.ThreadGroup) + */ + @Test + public void test_parentOf() { + final ThreadGroup originalCurrent = getInitialThreadGroup(); + final ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group"); + final int DEPTH = 4; + buildRandomTreeUnder(testRoot, DEPTH); + + final ThreadGroup[] allChildren = allGroups(testRoot); + for (int i = 0; i < allChildren.length; i++) { + AssertJUnit.assertTrue("Have to be parentOf all children", testRoot.parentOf((ThreadGroup)allChildren[i])); + } + + AssertJUnit.assertTrue("Have to be parentOf itself", testRoot.parentOf(testRoot)); + + testRoot.destroy(); + AssertJUnit.assertTrue("Parent can't have test group as subgroup anymore", + !arrayIncludes(groups(testRoot.getParent()), testRoot)); + + /* [PR 97314] ThreadGroup.getParent() should call parent.checkAccess() */ + try { + System.setSecurityManager(new SecurityManager()); + AssertJUnit.assertTrue("Should not be parent", !testRoot.parentOf(originalCurrent)); + } finally { + System.setSecurityManager(null); + } + } + + /** + * @tests java.lang.ThreadGroup#setMaxPriority(int) + */ + @Test + public void test_setMaxPriority() { + final ThreadGroup originalCurrent = getInitialThreadGroup(); + ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group"); + + boolean passed; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /* + * [PR 1FJ9S51] If new priority is greater than the current maximum, the + * maximum remains unchanged + */ + int currentMax = testRoot.getMaxPriority(); + testRoot.setMaxPriority(Thread.MAX_PRIORITY + 1); + passed = testRoot.getMaxPriority() == currentMax; + AssertJUnit.assertTrue("setMaxPriority: Any value higher than the current one is ignored. Before: " + currentMax + + " , after: " + testRoot.getMaxPriority(), passed); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /*[PR CMVC 177870] Java7:JCK:java_lang/ThreadGroup/setMaxPriority fails in all platform */ + currentMax = testRoot.getMaxPriority(); + testRoot.setMaxPriority(Thread.MIN_PRIORITY - 1); + passed = testRoot.getMaxPriority() == currentMax; + AssertJUnit.assertTrue("setMaxPriority: Any value smaller than MIN_PRIORITY is ignored. Before: " + currentMax + + " , after: " + testRoot.getMaxPriority(), passed); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /* + * [PR 1FJ9S51] The test above now has side-effect, so we destroy and + * create a new one + */ + testRoot.destroy(); + testRoot = new ThreadGroup(originalCurrent, "Test group"); + + // Create some groups, nested some levels. Each level will have maxPrio + // 1 unit smaller + // than the parent's. However, there can't be a group with priority < + // Thread.MIN_PRIORITY + final int TOTAL_DEPTH = testRoot.getMaxPriority() - Thread.MIN_PRIORITY - 2; + ThreadGroup current = testRoot; + for (int i = 0; i < TOTAL_DEPTH; i++) { + current = new ThreadGroup(current, "level " + i); + } + + // Now we walk the levels down, changing the maxPrio and later verifying + // that the value + // is indeed 1 unit smaller than the parent's maxPrio. + int maxPrio, parentMaxPrio; + current = testRoot; + + // To maintain the invariant that when we are to modify a child, + // its maxPriority is always 1 unit smaller than its parent's. + // We have to set it for the root manually, and the loop does the rest + // for all + // the other sub-levels + current.setMaxPriority(current.getParent().getMaxPriority() - 1); + + for (int i = 0; i < TOTAL_DEPTH; i++) { + maxPrio = current.getMaxPriority(); + parentMaxPrio = current.getParent().getMaxPriority(); + + ThreadGroup[] children = groups(current); + AssertJUnit.assertTrue("Can only have 1 subgroup", children.length == 1); + current = children[0]; + AssertJUnit.assertTrue( + "Had to be 1 unit smaller than parent's priority in iteration=" + i + " checking->" + current, + maxPrio == parentMaxPrio - 1); + current.setMaxPriority(maxPrio - 1); + + // The next test is sort of redundant, since in next iteration it + // will be the + // parent tGroup, so the test will be done. + AssertJUnit.assertTrue("Had to be possible to change max priority", + current.getMaxPriority() == maxPrio - 1); + } + + AssertJUnit.assertTrue("Priority of leaf child group has to be much smaller than original root group", + current.getMaxPriority() == testRoot.getMaxPriority() - TOTAL_DEPTH); + + testRoot.destroy(); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + passed = true; + testRoot = new ThreadGroup(originalCurrent, "Test group"); + try { + testRoot.setMaxPriority(Thread.MAX_PRIORITY); + } catch (IllegalArgumentException iae) { + passed = false; + } + AssertJUnit.assertTrue( + "Max Priority = Thread.MAX_PRIORITY should be possible if the test is run with default system ThreadGroup as root", + passed); + testRoot.destroy(); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + passed = true; + testRoot = new ThreadGroup(originalCurrent, "Test group"); + System.setSecurityManager(new SecurityManager()); + try { + try { + testRoot.setMaxPriority(Thread.MIN_PRIORITY); + } catch (IllegalArgumentException iae) { + passed = false; + } + } finally { + System.setSecurityManager(null); + } + AssertJUnit.assertTrue("Min Priority = Thread.MIN_PRIORITY should be possible, always", passed); + testRoot.destroy(); + + /* [PR 97314] ThreadGroup.getParent() should call parent.checkAccess() */ + try { + System.setSecurityManager(new SecurityManager()); + /* [PR 97314] Should not cause a SecurityException */ + originalCurrent.setMaxPriority(Thread.MAX_PRIORITY); + } finally { + System.setSecurityManager(null); + } + } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + @BeforeMethod + protected void setUp() { + initialThreadGroup = Thread.currentThread().getThreadGroup(); + rootThreadGroup = initialThreadGroup; + while (rootThreadGroup.getParent() != null) + rootThreadGroup = rootThreadGroup.getParent(); + } + + /** + * Tears down the fixture, for example, close a network connection. This + * method is called after a test is executed. + */ + @AfterMethod + protected void tearDown() { + try { + // Give the threads a chance to die. + Thread.sleep(50); + } catch (InterruptedException e) { + } + } + + private ThreadGroup[] allGroups(ThreadGroup parent) { + int count = parent.activeGroupCount(); + ThreadGroup[] all = new ThreadGroup[count]; + parent.enumerate(all, true); + return all; + } + + private ThreadGroup[] groups(ThreadGroup parent) { + int count = parent.activeGroupCount(); // No API to get the count of + // immediate children only ? + ThreadGroup[] all = new ThreadGroup[count]; + parent.enumerate(all, false); + // Now we may have nulls in the array, we must find the actual size + int actualSize = 0; + for (; actualSize < all.length; actualSize++) { + if (all[actualSize] == null) + break; + } + ThreadGroup[] result; + if (actualSize == all.length) + result = all; + else { + result = new ThreadGroup[actualSize]; + System.arraycopy(all, 0, result, 0, actualSize); + } + return result; + } + + private void asyncBuildRandomTreeUnder(final ThreadGroup aGroup, final int depth, final Vector allCreated) { + if (depth <= 0) + return; + + final int maxImmediateSubgroups = random(3); + for (int i = 0; i < maxImmediateSubgroups; i++) { + final int iClone = i; + final String name = " Depth = " + depth + ",N = " + iClone + ",Vector size at creation: " + + allCreated.size(); + // Use concurrency to maximize chance of exposing concurrency bugs + // in ThreadGroups + Thread t = new Thread(aGroup, name) { + public void run() { + ThreadGroup newGroup = new ThreadGroup(aGroup, name); + allCreated.addElement(newGroup); + asyncBuildRandomTreeUnder(newGroup, depth - 1, allCreated); + } + }; + t.start(); + } + } + + private Vector asyncBuildRandomTreeUnder(final ThreadGroup aGroup, final int depth) { + Vector result = new Vector(); + asyncBuildRandomTreeUnder(aGroup, depth, result); + return result; + } + + private int random(int max) { + return 1 + ((new Object()).hashCode() % max); + } + + private Vector buildRandomTreeUnder(ThreadGroup aGroup, int depth) { + Vector result = asyncBuildRandomTreeUnder(aGroup, depth); + while (true) { + int sizeBefore = result.size(); + try { + Thread.sleep(1000); + int sizeAfter = result.size(); + // If no activity for a while, we assume async building may be + // done + if (sizeBefore == sizeAfter) + // It can only be done if no more threads. Unfortunately we + // are relying on this + // API to work as well. If it does not, we may loop forever. + if (aGroup.activeCount() == 0) { + break; + } + } catch (InterruptedException e) { + } + } + return result; + } + + private boolean arrayIncludes(Object[] array, Object toTest) { + for (int i = 0; i < array.length; i++) { + if (array[i] == toTest) + return true; + } + return false; + } + +} diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Thread_SM.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Thread_SM.java new file mode 100644 index 00000000000..47c462f54a8 --- /dev/null +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/Test_Thread_SM.java @@ -0,0 +1,273 @@ +/******************************************************************************* + * Copyright (c) 2022, 2022 IBM Corp. and others + * + * This program and the accompanying materials are made available under + * the terms of the Eclipse Public License 2.0 which accompanies this + * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ + * or the Apache License, Version 2.0 which accompanies this distribution and + * is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * This Source Code may also be made available under the following + * Secondary Licenses when the conditions for such availability set + * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU + * General Public License, version 2 with the GNU Classpath + * Exception [1] and GNU General Public License, version 2 with the + * OpenJDK Assembly Exception [2]. + * + * [1] https://www.gnu.org/software/classpath/license.html + * [2] http://openjdk.java.net/legal/assembly-exception.html + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception + *******************************************************************************/ +package org.openj9.test.java.lang; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.Test; +import org.testng.Assert; +import org.testng.AssertJUnit; + +@Test(groups = { "level.sanity" }) +public class Test_Thread_SM { + + static class SimpleThread implements Runnable { + int delay; + + public void run() { + try { + synchronized (this) { + this.notify(); + this.wait(delay); + } + } catch (InterruptedException e) { + return; + } + + } + + public SimpleThread(int d) { + if (d >= 0) + delay = d; + } + } + + Thread st; + + static boolean calledMySecurityManager = false; + + /** + * @tests java.lang.Thread#Thread() + */ + @Test + public void test_Constructor() { + Thread t; + SecurityManager m = new SecurityManager() { + public ThreadGroup getThreadGroup() { + calledMySecurityManager = true; + return Thread.currentThread().getThreadGroup(); + } + }; + try { + System.setSecurityManager(m); // To see if it checks Thread creation + // with our SecurityManager + + t = new Thread(); + } finally { + System.setSecurityManager(null); // restore original, no + // side-effects + } + AssertJUnit.assertTrue("Did not call SecurityManager.getThreadGroup ()", calledMySecurityManager); + t.start(); + } + + /** + * @tests java.lang.Thread#checkAccess() + */ + @Test + public void test_checkAccess() { + ThreadGroup tg = new ThreadGroup("Test Group3"); + try { + st = new Thread(tg, new SimpleThread(1), "SimpleThread5"); + st.checkAccess(); + AssertJUnit.assertTrue("CheckAccess passed", true); + } catch (SecurityException e) { + Assert.fail("CheckAccess failed", e); + } + st.start(); + try { + st.join(); + } catch (InterruptedException e) { + } + tg.destroy(); + } + + /** + * @tests java.lang.Thread#checkAccess_interrupt_self() + */ + @Test + public void test_checkAccess_interrupt_self() { + try { + System.setSecurityManager(new SecurityManager() { + public void checkAccess(Thread t) { + Assert.fail("CheckAccess() was invoked"); + } + }); + + Thread.currentThread().interrupt(); + AssertJUnit.assertTrue("Failed to interrupt current thread", Thread.interrupted()); + } finally { + System.setSecurityManager(null); + } + } + + /** + * @tests java.lang.Thread#checkAccess_interrupt_not_self() + */ + @Test + public void test_checkAccess_interrupt_not_self() { + try { + SimpleThread simple = new SimpleThread(5000); + + st = new Thread(simple); + + synchronized (simple) { + st.start(); + + try { + simple.wait(); + } catch (InterruptedException e) { + } + } + + class MySecurityManager extends SecurityManager { + public volatile boolean called = false; + + public void checkAccess(Thread t) { + called = true; + } + } + + MySecurityManager sm = new MySecurityManager(); + + System.setSecurityManager(sm); + + AssertJUnit.assertTrue("Thread should be alive", st.isAlive()); + + st.interrupt(); + + AssertJUnit.assertTrue("checkAccess() was not called", sm.called); + + try { + st.join(10000); + } catch (InterruptedException e) { + Assert.fail("Join failed ", e); + } + } finally { + System.setSecurityManager(null); + } + } + + /** + * @tests java.lang.Thread#getContextClassLoader() + */ + @Test + public void test_getContextClassLoader() { + Thread t = new Thread(); + AssertJUnit.assertTrue("Incorrect class loader returned", + t.getContextClassLoader() == Thread.currentThread().getContextClassLoader()); + t.start(); + + /* [PR CMVC 90230] behavior change in 1.5 */ + // behavior change in 1.5, Thread constructors should call + // parentThread.getContextClassLoader() + // instead of accessing field + final ClassLoader loader = new ClassLoader() { + }; + class ContextThread extends Thread { + private ClassLoader contextClassLoader; + + public ClassLoader getContextClassLoader() { + return contextClassLoader; + } + + public void setContextClassLoader(ClassLoader loader) { + contextClassLoader = loader; + } + + public void run() { + Thread thread = new Thread(); + ClassLoader contextLoader = thread.getContextClassLoader(); + AssertJUnit.assertTrue("incorrect context class loader", contextLoader == loader); + } + } + ; + Thread sub = new ContextThread(); + sub.setContextClassLoader(loader); + sub.start(); + /* [PR CMVC 90230] behavior change in 1.5 */ + // behavior change in 1.5, Thread constructors should check + // enableContextClassLoaderOverride + // if thread overrides getContextClassLoader() or + // setContextClassLoader() */ + class SubContextThread extends ContextThread { + } + ; + System.setSecurityManager(new SecurityManager()); + try { + // creating a new Thread, or subclass of Thread should not cause an + // exception + new Thread(); + new Thread() { + }; + boolean exception = false; + try { + new SubContextThread(); + } catch (SecurityException e) { + AssertJUnit.assertTrue("wrong exception: " + e, + e.getMessage().indexOf("enableContextClassLoaderOverride") != -1); + exception = true; + } + AssertJUnit.assertTrue("exception not thrown", exception); + } finally { + System.setSecurityManager(null); + } + } + + /** + * @tests java.lang.Thread#stop() + */ + @Test + public void test_stop2() { + /* [PR CMVC 94728] AccessControlException on dead Thread */ + Thread t = new Thread("t"); + class MySecurityManager extends SecurityManager { + public boolean intest = false; + + public void checkAccess(Thread t) { + if (intest) { + Assert.fail("checkAccess called"); + } + } + } + MySecurityManager sm = new MySecurityManager(); + System.setSecurityManager(sm); + try { + sm.intest = false; + t.start(); + try { + t.join(2000); + } catch (InterruptedException e) { + } + sm.intest = true; + try { + t.stop(); + // Ignore any SecurityExceptions, may not have stopThread + // permission + } catch (SecurityException e) { + } + sm.intest = false; + } finally { + System.setSecurityManager(null); + } + } + +} diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/invoke/Test_MethodHandleInfo.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/invoke/Test_MethodHandleInfo.java index 200c96bc329..2708c2112cd 100644 --- a/test/functional/Java8andUp/src/org/openj9/test/java/lang/invoke/Test_MethodHandleInfo.java +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/invoke/Test_MethodHandleInfo.java @@ -1,7 +1,7 @@ package org.openj9.test.java.lang.invoke; /******************************************************************************* - * Copyright (c) 1998, 2020 IBM Corp. and others + * Copyright (c) 1998, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -25,15 +25,9 @@ import org.testng.annotations.Test; import org.testng.Assert; import org.testng.AssertJUnit; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; import java.lang.invoke.*; -import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.*; -import java.security.AccessControlException; import org.openj9.test.java.lang.invoke.helpers.*; -import org.openj9.test.util.VersionCheck; import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; @@ -679,111 +673,6 @@ public void test_RevealDirect_TargetVarargsHandle() throws Throwable { lookup().revealDirect(mh); } - /** - * Check that a SecurityException is thrown when ... - * - * @throws Throwable - */ - @Test(groups = { "level.sanity" }) - public void test_RevealDirect_Security() throws Throwable { - if (VersionCheck.major() >= 15) { - /* This test doesn't apply to JDK15+ after removing package check for MethodHandles.Lookup() constructors exception three APIs */ - return; - } - - final String lookup = "org.openj9.test.java.lang.invoke.Helper_MethodHandleInfo"; - final String methodHandle = "org.openj9.test.java.lang.invoke.helpers.Helper_MethodHandleInfoOtherPackagePublic"; - - // Get lookup object from class loader L1 - ClassLoader l1 = new ClassLoader(Test_MethodHandleInfo.class.getClassLoader()) { - - @Override - public Class loadClass(String className) throws ClassNotFoundException { - if (className.equals(lookup)) { - return getClass( className ); - } - if (className.equals(methodHandle)) { - return getClass(className); - } - return super.loadClass(className); - } - - private Class getClass( String className )throws ClassNotFoundException { - String classFile = className.replace('.', '/') + ".class"; - try { - InputStream classStream = getClass().getClassLoader().getResourceAsStream( classFile ); - if ( classStream == null ) { - throw new ClassNotFoundException( "Error loading class : " + classFile ); - } - int size = classStream.available(); - byte classRep[] = new byte[size]; - DataInputStream in = new DataInputStream( classStream ); - in.readFully( classRep ); - in.close(); - Class clazz = defineClass( className, classRep, 0, classRep.length ); - return clazz; - } catch ( IOException e ) { - throw new ClassNotFoundException( e.getMessage() ); - } - } - - }; - Class classL1 = l1.loadClass(lookup); - Method mL1 = classL1.getDeclaredMethod("lookup"); - Lookup lookup1 = (Lookup)mL1.invoke(null); - - // Get MethodHandle from class loader L2 - ClassLoader l2 = new ClassLoader(Test_MethodHandleInfo.class.getClassLoader()) { - - @Override - public Class loadClass(String className) throws ClassNotFoundException { - if ( className.equals(methodHandle) ) { - return getClass( className ); - } - return super.loadClass( className ); - } - - private Class getClass( String className )throws ClassNotFoundException { - String classFile = className.replace('.', '/') + ".class"; - try { - InputStream classStream = getClass().getClassLoader().getResourceAsStream( classFile ); - if ( classStream == null ) { - throw new ClassNotFoundException( "Error loading class : " + classFile ); - } - int size = classStream.available(); - byte classRep[] = new byte[size]; - DataInputStream in = new DataInputStream( classStream ); - in.readFully( classRep ); - in.close(); - Class clazz = defineClass( className, classRep, 0, classRep.length ); - return clazz; - } catch ( IOException e ) { - throw new ClassNotFoundException( e.getMessage() ); - } - } - - }; - Class classL2 = l2.loadClass(methodHandle); - Method mL2 = classL2.getDeclaredMethod("publicClassMethodHandle"); - MethodHandle mh = (MethodHandle)mL2.invoke(null); - Method m2L2 = classL2.getDeclaredMethod("lookup"); - Lookup lookup2 = (Lookup)m2L2.invoke(null); - - helper_turnOwnSecurityManagerOn(); - - boolean ACEThrown = false; - try { - MethodHandleInfo mhi1 = lookup1.revealDirect(mh); - } catch (AccessControlException e) { - ACEThrown = true; - } catch (IllegalArgumentException e) { - Assert.fail("IllegalArgumentException thrown, expected AccessControlException."); - } finally { - helper_resetSecurityManager(); - } - AssertJUnit.assertTrue(ACEThrown); - } - /** * Caller-sensitive MH can only be cracked by the lookup object used to create it. Test with other lookup object. */ @@ -801,58 +690,5 @@ public void test_RevealDirect_CrackCallerSensitive() throws Throwable { AssertJUnit.assertTrue(IAEThrown); } - @Test(groups = { "level.sanity" }) - public void test_MHsReflectAs_WithSecMgr() throws Throwable { - helper_turnSecurityManagerOn(); - boolean ACEThrown = false; - MethodHandle target = lookup().findGetter(this.getClass(), "publicField", String.class); - try { - reflectAs(Field.class, target); - } catch (SecurityException e) { - ACEThrown = true; - } finally { - helper_resetSecurityManager(); - } - AssertJUnit.assertTrue(ACEThrown); - } - - @Test(groups = { "level.sanity" }) - public void test_MHsReflectAs_WithoutSecMgr() throws Throwable { - helper_turnSecurityManagerOff(); - MethodHandle target = lookup().findGetter(this.getClass(), "publicField", String.class); - Field f = reflectAs(Field.class, target); - String s = (String)f.get(new Test_MethodHandleInfo()); - helper_resetSecurityManager(); - AssertJUnit.assertEquals("publicField", s); - } - - private SecurityManager secmgr; - private void helper_turnSecurityManagerOn() { - secmgr = System.getSecurityManager(); - System.setSecurityManager(new SecurityManager()); - } - - private void helper_turnOwnSecurityManagerOn() { - secmgr = System.getSecurityManager(); - System.setSecurityManager(new SecurityManager() { - @Override - public void checkPackageAccess(String arg0) { - super.checkPackageAccess(arg0); - if (arg0.equals("org.openj9.test.java.lang.invoke.helpers")) { - throw new AccessControlException(""); - } - } - }); - } - - private void helper_turnSecurityManagerOff() { - secmgr = System.getSecurityManager(); - System.setSecurityManager(null); - } - - private void helper_resetSecurityManager() { - System.setSecurityManager(secmgr); - } - enum EnumTest {TEST1, TEST2} } diff --git a/test/functional/Java8andUp/src/org/openj9/test/java/lang/invoke/Test_MethodHandleInfo_SM.java b/test/functional/Java8andUp/src/org/openj9/test/java/lang/invoke/Test_MethodHandleInfo_SM.java new file mode 100644 index 00000000000..31a516d57c5 --- /dev/null +++ b/test/functional/Java8andUp/src/org/openj9/test/java/lang/invoke/Test_MethodHandleInfo_SM.java @@ -0,0 +1,199 @@ +package org.openj9.test.java.lang.invoke; + +/******************************************************************************* + * Copyright (c) 2022, 2022 IBM Corp. and others + * + * This program and the accompanying materials are made available under + * the terms of the Eclipse Public License 2.0 which accompanies this + * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ + * or the Apache License, Version 2.0 which accompanies this distribution and + * is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * This Source Code may also be made available under the following + * Secondary Licenses when the conditions for such availability set + * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU + * General Public License, version 2 with the GNU Classpath + * Exception [1] and GNU General Public License, version 2 with the + * OpenJDK Assembly Exception [2]. + * + * [1] https://www.gnu.org/software/classpath/license.html + * [2] http://openjdk.java.net/legal/assembly-exception.html + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception + *******************************************************************************/ + +import org.testng.annotations.Test; +import org.testng.Assert; +import org.testng.AssertJUnit; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.invoke.*; +import java.lang.reflect.*; +import java.security.AccessControlException; +import org.openj9.test.java.lang.invoke.helpers.*; +import org.openj9.test.util.VersionCheck; +import static java.lang.invoke.MethodHandles.*; + +public class Test_MethodHandleInfo_SM { + public String publicField = "publicField"; + + /** + * Check that a SecurityException is thrown when ... + * + * @throws Throwable + */ + @Test(groups = { "level.sanity" }) + public void test_RevealDirect_Security() throws Throwable { + if (VersionCheck.major() >= 15) { + /* This test doesn't apply to JDK15+ after removing package check for MethodHandles.Lookup() constructors exception three APIs */ + return; + } + + final String lookup = "org.openj9.test.java.lang.invoke.Helper_MethodHandleInfo"; + final String methodHandle = "org.openj9.test.java.lang.invoke.helpers.Helper_MethodHandleInfoOtherPackagePublic"; + + // Get lookup object from class loader L1 + ClassLoader l1 = new ClassLoader(Test_MethodHandleInfo_SM.class.getClassLoader()) { + + @Override + public Class loadClass(String className) throws ClassNotFoundException { + if (className.equals(lookup)) { + return getClass(className); + } + if (className.equals(methodHandle)) { + return getClass(className); + } + return super.loadClass(className); + } + + private Class getClass(String className)throws ClassNotFoundException { + String classFile = className.replace('.', '/') + ".class"; + try { + InputStream classStream = getClass().getClassLoader().getResourceAsStream(classFile); + if (classStream == null) { + throw new ClassNotFoundException("Error loading class : " + classFile); + } + int size = classStream.available(); + byte classRep[] = new byte[size]; + DataInputStream in = new DataInputStream(classStream); + in.readFully(classRep); + in.close(); + Class clazz = defineClass(className, classRep, 0, classRep.length); + return clazz; + } catch (IOException e) { + throw new ClassNotFoundException(e.getMessage()); + } + } + + }; + Class classL1 = l1.loadClass(lookup); + Method mL1 = classL1.getDeclaredMethod("lookup"); + Lookup lookup1 = (Lookup)mL1.invoke(null); + + // Get MethodHandle from class loader L2 + ClassLoader l2 = new ClassLoader(Test_MethodHandleInfo_SM.class.getClassLoader()) { + + @Override + public Class loadClass(String className) throws ClassNotFoundException { + if (className.equals(methodHandle)) { + return getClass(className); + } + return super.loadClass(className); + } + + private Class getClass(String className)throws ClassNotFoundException { + String classFile = className.replace('.', '/') + ".class"; + try { + InputStream classStream = getClass().getClassLoader().getResourceAsStream(classFile); + if (classStream == null) { + throw new ClassNotFoundException("Error loading class : " + classFile); + } + int size = classStream.available(); + byte classRep[] = new byte[size]; + DataInputStream in = new DataInputStream(classStream); + in.readFully(classRep); + in.close(); + Class clazz = defineClass(className, classRep, 0, classRep.length); + return clazz; + } catch (IOException e) { + throw new ClassNotFoundException(e.getMessage()); + } + } + + }; + Class classL2 = l2.loadClass(methodHandle); + Method mL2 = classL2.getDeclaredMethod("publicClassMethodHandle"); + MethodHandle mh = (MethodHandle)mL2.invoke(null); + Method m2L2 = classL2.getDeclaredMethod("lookup"); + Lookup lookup2 = (Lookup)m2L2.invoke(null); + + helper_turnOwnSecurityManagerOn(); + + boolean ACEThrown = false; + try { + MethodHandleInfo mhi1 = lookup1.revealDirect(mh); + } catch (AccessControlException e) { + ACEThrown = true; + } catch (IllegalArgumentException e) { + Assert.fail("IllegalArgumentException thrown, expected AccessControlException."); + } finally { + helper_resetSecurityManager(); + } + AssertJUnit.assertTrue(ACEThrown); + } + + @Test(groups = { "level.sanity" }) + public void test_MHsReflectAs_WithSecMgr() throws Throwable { + helper_turnSecurityManagerOn(); + boolean ACEThrown = false; + MethodHandle target = lookup().findGetter(this.getClass(), "publicField", String.class); + try { + reflectAs(Field.class, target); + } catch (SecurityException e) { + ACEThrown = true; + } finally { + helper_resetSecurityManager(); + } + AssertJUnit.assertTrue(ACEThrown); + } + + @Test(groups = { "level.sanity" }) + public void test_MHsReflectAs_WithoutSecMgr() throws Throwable { + helper_turnSecurityManagerOff(); + MethodHandle target = lookup().findGetter(this.getClass(), "publicField", String.class); + Field f = reflectAs(Field.class, target); + String s = (String)f.get(new Test_MethodHandleInfo_SM()); + helper_resetSecurityManager(); + AssertJUnit.assertEquals("publicField", s); + } + + private SecurityManager secmgr; + private void helper_turnSecurityManagerOn() { + secmgr = System.getSecurityManager(); + System.setSecurityManager(new SecurityManager()); + } + + private void helper_turnOwnSecurityManagerOn() { + secmgr = System.getSecurityManager(); + System.setSecurityManager(new SecurityManager() { + @Override + public void checkPackageAccess(String arg0) { + super.checkPackageAccess(arg0); + if (arg0.equals("org.openj9.test.java.lang.invoke.helpers")) { + throw new AccessControlException(""); + } + } + }); + } + + private void helper_turnSecurityManagerOff() { + secmgr = System.getSecurityManager(); + System.setSecurityManager(null); + } + + private void helper_resetSecurityManager() { + System.setSecurityManager(secmgr); + } + +} diff --git a/test/functional/Java8andUp/src/org/openj9/test/support/Support_ExtendedTestEnvironment.java b/test/functional/Java8andUp/src/org/openj9/test/support/Support_ExtendedTestEnvironment.java index dae785a2e0f..1eca1abac41 100644 --- a/test/functional/Java8andUp/src/org/openj9/test/support/Support_ExtendedTestEnvironment.java +++ b/test/functional/Java8andUp/src/org/openj9/test/support/Support_ExtendedTestEnvironment.java @@ -1,10 +1,7 @@ package org.openj9.test.support; -import org.openj9.test.java.lang.Test_Class; -import org.testng.log4testng.Logger; - /******************************************************************************* - * Copyright (c) 2010, 2018 IBM Corp. and others + * Copyright (c) 2010, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -26,8 +23,6 @@ *******************************************************************************/ public class Support_ExtendedTestEnvironment { - private static final Logger logger = Logger.getLogger(Support_ExtendedTestEnvironment.class); - private static Support_ExtendedTestEnvironment environment; public void execute(Runnable toRun) { @@ -52,22 +47,4 @@ public static Support_ExtendedTestEnvironment getInstance() { } return environment; } - - public SecurityManager setSecurityManager(final Class clazz) { - final SecurityManager[] sm = new SecurityManager[1]; - - try { - if (clazz != null) { - sm[0] = (SecurityManager) clazz.newInstance(); - } else { - sm[0] = null; - } - System.setSecurityManager(sm[0]); - } catch (IllegalAccessException e) { - logger.error("Unexpected exception: " + e); - } catch (InstantiationException e) { - logger.error("Unexpected exception: " + e); - } - return sm[0]; - } } diff --git a/test/functional/Java8andUp/src/org/openj9/test/vmArguments/VmArgumentTests.java b/test/functional/Java8andUp/src/org/openj9/test/vmArguments/VmArgumentTests.java index 3eba2ebbae8..da1692bcaad 100644 --- a/test/functional/Java8andUp/src/org/openj9/test/vmArguments/VmArgumentTests.java +++ b/test/functional/Java8andUp/src/org/openj9/test/vmArguments/VmArgumentTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2001, 2021 IBM Corp. and others + * Copyright (c) 2001, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -1313,7 +1313,7 @@ public void testWAS80Cmdline() { ":/opt/IBM/WebSphere/AppServer80/lib/urlprotocols.jar:/opt/IBM/WebSphere/AppServer80/deploytool/itp/batchboot.jar:/opt/IBM/WebSphere/AppServer80/deploytool/itp/batch2.jar" + ":/opt/IBM/WebSphere/AppServer80/java/lib/tools.jar"+":"+CLASSPATH; - String[] initalCmdLineArgs = {"-Declipse.security", + String[] initialCmdLineArgs = {"-Declipse.security", "-Dosgi.install.area=/opt/IBM/WebSphere/AppServer80", "-Dosgi.configuration.area=/opt/IBM/WebSphere/AppServer80/profiles/AppSrv01/servers/server1/configuration", "-Djava.awt.headless=true", @@ -1339,10 +1339,9 @@ public void testWAS80Cmdline() { "-Dcom.ibm.security.jgss.debug=off", "-Dcom.ibm.security.krb5.Krb5Debug=off", "-Djava.library.path=/opt/IBM/WebSphere/AppServer80/lib/native/linux/x86_64/:/opt/IBM/WebSphere/AppServer80/java/jre/lib/amd64/default:/opt/IBM/WebSphere/AppServer80/java/jre/lib/amd64:/opt/IBM/WebSphere/AppServer80/lib/native/linux/x86_64/:/opt/IBM/WebSphere/AppServer80/bin:.:/usr/lib:", - "-Djava.security.auth.login.config=/opt/IBM/WebSphere/AppServer80/profiles/AppSrv01/properties/wsjaas.conf", - "-Djava.security.policy=/opt/IBM/WebSphere/AppServer80/profiles/AppSrv01/properties/server.policy"}; + "-Djava.security.auth.login.config=/opt/IBM/WebSphere/AppServer80/profiles/AppSrv01/properties/wsjaas.conf"}; - String[] initalExpectedArgs = {"-Declipse.security", + String[] initialExpectedArgs = {"-Declipse.security", "-Dosgi.install.area=/opt/IBM/WebSphere/AppServer80", "-Dosgi.configuration.area=/opt/IBM/WebSphere/AppServer80/profiles/AppSrv01/servers/server1/configuration", "-Djava.awt.headless=true", @@ -1367,27 +1366,41 @@ public void testWAS80Cmdline() { "-Dcom.ibm.security.jgss.debug=off", "-Dcom.ibm.security.krb5.Krb5Debug=off", "-Djava.library.path=/opt/IBM/WebSphere/AppServer80/lib/native/linux/x86_64/:/opt/IBM/WebSphere/AppServer80/java/jre/lib/amd64/default:/opt/IBM/WebSphere/AppServer80/java/jre/lib/amd64:/opt/IBM/WebSphere/AppServer80/lib/native/linux/x86_64/:/opt/IBM/WebSphere/AppServer80/bin:.:/usr/lib:", - "-Djava.security.auth.login.config=/opt/IBM/WebSphere/AppServer80/profiles/AppSrv01/properties/wsjaas.conf", - "-Djava.security.policy=/opt/IBM/WebSphere/AppServer80/profiles/AppSrv01/properties/server.policy"}; + "-Djava.security.auth.login.config=/opt/IBM/WebSphere/AppServer80/profiles/AppSrv01/properties/wsjaas.conf"}; - - /* - * This test should only run for Java 1.8.0. For Java - * 1.9.0 and above, we do not support java.ext.dirs property. - */ String[] cmdLineArgs; String[] expectedArgs; - if (isJava8) { - cmdLineArgs = new String[initalCmdLineArgs.length + 1]; - System.arraycopy(initalCmdLineArgs, 0, cmdLineArgs, 0, initalCmdLineArgs.length); - cmdLineArgs[initalCmdLineArgs.length] = "-Djava.ext.dirs=/opt/IBM/WebSphere/AppServer80/tivoli/tam:/opt/IBM/WebSphere/AppServer80/java/jre/lib/ext"; - - expectedArgs = new String[initalExpectedArgs.length + 1]; - System.arraycopy(initalExpectedArgs, 0, expectedArgs, 0, initalExpectedArgs.length); - expectedArgs[initalExpectedArgs.length] = "-Djava.ext.dirs=/opt/IBM/WebSphere/AppServer80/tivoli/tam:/opt/IBM/WebSphere/AppServer80/java/jre/lib/ext"; + if (VersionCheck.major() < 19) { + final String policy = "-Djava.security.policy=/opt/IBM/WebSphere/AppServer80/profiles/AppSrv01/properties/server.policy"; + if (isJava8) { + /* + * This test should only run for Java 1.8.0. For Java + * 1.9.0 and above, we do not support java.ext.dirs property. + */ + final String dirs = "-Djava.ext.dirs=/opt/IBM/WebSphere/AppServer80/tivoli/tam:/opt/IBM/WebSphere/AppServer80/java/jre/lib/ext"; + + cmdLineArgs = new String[initialCmdLineArgs.length + 2]; + System.arraycopy(initialCmdLineArgs, 0, cmdLineArgs, 0, initialCmdLineArgs.length); + cmdLineArgs[initialCmdLineArgs.length] = policy; + cmdLineArgs[initialCmdLineArgs.length + 1] = dirs; + + expectedArgs = new String[initialExpectedArgs.length + 2]; + System.arraycopy(initialExpectedArgs, 0, expectedArgs, 0, initialExpectedArgs.length); + expectedArgs[initialExpectedArgs.length] = policy; + expectedArgs[initialExpectedArgs.length + 1] = dirs; + } else { + cmdLineArgs = new String[initialCmdLineArgs.length + 1]; + System.arraycopy(initialCmdLineArgs, 0, cmdLineArgs, 0, initialCmdLineArgs.length); + cmdLineArgs[initialCmdLineArgs.length] = policy; + + expectedArgs = new String[initialExpectedArgs.length + 1]; + System.arraycopy(initialExpectedArgs, 0, expectedArgs, 0, initialExpectedArgs.length); + expectedArgs[initialExpectedArgs.length] = policy; + } } else { - cmdLineArgs = initalCmdLineArgs.clone(); - expectedArgs = initalExpectedArgs.clone(); + /* SecurityManager and related classes have been removed. */ + cmdLineArgs = initialCmdLineArgs.clone(); + expectedArgs = initialExpectedArgs.clone(); } try { diff --git a/test/functional/Java8andUp/src_110_up/org/openj9/test/java/lang/Test_Class.java b/test/functional/Java8andUp/src_110_up/org/openj9/test/java/lang/Test_Class.java index 1b4789954c7..75aa3cd23e7 100644 --- a/test/functional/Java8andUp/src_110_up/org/openj9/test/java/lang/Test_Class.java +++ b/test/functional/Java8andUp/src_110_up/org/openj9/test/java/lang/Test_Class.java @@ -312,49 +312,6 @@ public void test_getMethods_subtest1() { AssertJUnit.assertTrue("Expected method " + expected_CF[i] + " not found.", match); } } -@Test -public void test_getMethods_subtest2() { - - java.security.PrivilegedAction action = new java.security.PrivilegedAction() { - public Object run() { - try { - File resources = Support_Resources.createTempFolder(); - String[] expected_E = new String[] { - "org.openj9.resources.classinheritance.E.method_N(java.lang.String)", - "org.openj9.resources.classinheritance.E.method_M(java.lang.String)", - "org.openj9.resources.classinheritance.A.method_K(java.lang.String)", - "org.openj9.resources.classinheritance.E.method_L(java.lang.String)", - "org.openj9.resources.classinheritance.E.method_O(java.lang.String)", - "org.openj9.resources.classinheritance.B.method_K(java.lang.String)"}; - - Support_Resources.copyFile(resources, null, "openj9tr_general.jar"); - File file = new File(resources.toString() + "/openj9tr_general.jar"); - java.net.URL url = new java.net.URL("file:" + file.getPath()); - ClassLoader loader = new java.net.URLClassLoader(new java.net.URL[]{url}, null); - - Class cls_E = Class.forName("org.openj9.resources.classinheritance.E", false, loader); - Method[] methodNames_E = cls_E.getMethods(); - AssertJUnit.assertEquals("Returned incorrect number of methods for cls_E", expected_E.length + Object.class.getMethods().length, methodNames_E.length); - for (int i = 0; i < expected_E.length; i++) { - boolean match = false; - for (int j = 0; j < methodNames_E.length; j++) { - if (methodNames_E[j].toString().indexOf(expected_E[i]) != -1) { - match = true; - } - } - AssertJUnit.assertTrue("Expected method " + expected_E[i] + " not found.", match); - } - } catch (MalformedURLException e) { - logger.error("Unexpected exception: " + e); - } catch (ClassNotFoundException e) { - logger.error("Unexpected exception: " + e); - } - - return null; - } - }; - java.security.AccessController.doPrivileged(action); -} static class ParentClass { public static void methodPublicStatic() {} @@ -641,161 +598,6 @@ public void test_getClasses() { } } -/** - * @tests java.lang.Class#getClasses() - */ -@Test -public void test_getClasses2() { - final java.security.Permission privCheckPermission = new java.security.BasicPermission("Privilege check") { - }; - class MyCombiner implements java.security.DomainCombiner { - boolean combine; - public java.security.ProtectionDomain[] combine(java.security.ProtectionDomain[] executionDomains, java.security.ProtectionDomain[] parentDomains) { - combine = true; - return new java.security.ProtectionDomain[0]; - } - public boolean isPriviledged() { - combine = false; - try { - java.security.AccessController.checkPermission(privCheckPermission); - } catch (SecurityException e) { - } - return !combine; - } - }; - final MyCombiner combiner = new MyCombiner(); - class SecurityManagerCheck extends SecurityManager { - String reason; - Class checkClass; - int checkType; - int checkPermission = 0; - int checkMemberAccess = 0; - int checkPackageAccess = 0; - - public void setExpected(String reason, Class cls, int type) { - this.reason = reason; - checkClass = cls; - checkType = type; - checkPermission = 0; - checkMemberAccess = 0; - checkPackageAccess = 0; - } - public void checkPermission(java.security.Permission perm) { - if (combiner.isPriviledged()) - return; - checkPermission++; - } - public void checkPackageAccess(String packageName) { - if (packageName.startsWith("java.") || packageName.startsWith("org.openj9.test.java.lang")) { - return; - } - if (combiner.isPriviledged()) - return; - checkPackageAccess++; - String name = checkClass.getName(); - int index = name.lastIndexOf('.'); - String checkPackage = name.substring(0, index); - AssertJUnit.assertTrue(reason + " unexpected package: " + packageName, packageName.equals(checkPackage)); - } - public void assertProperCalls() { - int declared = checkType == Member.DECLARED ? 1 : 0; - AssertJUnit.assertTrue(reason + " unexpected checkPermission count: " + checkPermission, checkPermission == declared); - AssertJUnit.assertTrue(reason + " unexpected checkPackageAccess count: " + checkPackageAccess, checkPackageAccess == 1); - } - } - - final SecurityManagerCheck sm = new SecurityManagerCheck(); - System.setSecurityManager(sm); - - java.security.AccessControlContext acc = new java.security.AccessControlContext(new java.security.ProtectionDomain[0]); - java.security.AccessControlContext acc2 = new java.security.AccessControlContext(acc, combiner); - - java.security.PrivilegedAction action = new java.security.PrivilegedAction() { - public Object run() { - File resources = Support_Resources.createTempFolder(); - try { - Support_Resources.copyFile(resources, null, "openj9tr_general.jar"); - File file = new File(resources.toString() + "/openj9tr_general.jar"); - java.net.URL url = new java.net.URL("file:" + file.getPath()); - ClassLoader loader = new java.net.URLClassLoader(new java.net.URL[]{url}, null); - Class cls = Class.forName("org.openj9.resources.security.SecurityTestSub", false, loader); - // must preload junit.framework.Assert before installing SecurityManager - // otherwise loading it inside checkPackageAccess() is recursive - AssertJUnit.assertTrue("preload assertions", true); - try { - sm.setExpected("getClasses", cls, java.lang.reflect.Member.PUBLIC); - cls.getClasses(); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredClasses", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredClasses(); - sm.assertProperCalls(); - - sm.setExpected("getConstructor", cls, java.lang.reflect.Member.PUBLIC); - cls.getConstructor(new Class[0]); - sm.assertProperCalls(); - - sm.setExpected("getConstructors", cls, java.lang.reflect.Member.PUBLIC); - cls.getConstructors(); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredConstructor", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredConstructor(new Class[0]); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredConstructors", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredConstructors(); - sm.assertProperCalls(); - - sm.setExpected("getField", cls, java.lang.reflect.Member.PUBLIC); - cls.getField("publicField"); - sm.assertProperCalls(); - - sm.setExpected("getFields", cls, java.lang.reflect.Member.PUBLIC); - cls.getFields(); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredField", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredField("publicField"); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredFields", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredFields(); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredMethod", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredMethod("publicMethod", new Class[0]); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredMethods", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredMethods(); - sm.assertProperCalls(); - - sm.setExpected("getMethod", cls, java.lang.reflect.Member.PUBLIC); - cls.getMethod("publicMethod", new Class[0]); - sm.assertProperCalls(); - - sm.setExpected("getMethods", cls, java.lang.reflect.Member.PUBLIC); - cls.getMethods(); - sm.assertProperCalls(); - - sm.setExpected("newInstance", cls, java.lang.reflect.Member.PUBLIC); - cls.newInstance(); - sm.assertProperCalls(); - } finally { - System.setSecurityManager(null); - } - } catch (Exception e) { - if (e instanceof RuntimeException) - throw (RuntimeException)e; - Assert.fail("unexpected exception: " + e); - } - return null; - } - }; - java.security.AccessController.doPrivileged(action, acc2); -} - /** * @tests java.lang.Class#getComponentType() */ @@ -1269,93 +1071,6 @@ public void test_getName() { className.equals("[Ljava.lang.Object;")); } -/** - * @tests java.lang.Class#getResource(java.lang.String) - */ -@Test -public void test_getResource() { - // Test for method java.net.URL java.lang.Class.getResource(java.lang.String) - System.setSecurityManager(new SecurityManager()); - try { - java.net.URL res = Object.class.getResource("Object.class"); - AssertJUnit.assertTrue("Object.class should not be found", res == null); - } finally { - System.setSecurityManager(null); - } - - String name = "/org/openj9/resources/openj9tr_Foo.c"; - - // find resource from object - AssertJUnit.assertTrue("directory of this class can be found", - Test_Class.class.getResource(name) != null); - - // find resource from array of objects - AssertJUnit.assertTrue("directory of array of this class can be found", - Test_Class[].class.getResource(name) != null); -} - -/** - * @tests java.lang.Class#getResourceAsStream(java.lang.String) - */ -@Test -public void test_getResourceAsStream() { - // Test for method java.io.InputStream java.lang.Class.getResourceAsStream(java.lang.String) - String name = Support_Resources.RESOURCE_PACKAGE + "openj9tr_compressD.txt"; - Class clazz = null; - try { - clazz = Class.forName("org.openj9.test.java.lang.Test_Class"); - } catch (ClassNotFoundException e) { - AssertJUnit.assertTrue("Should be able to find the class org.openj9.test.java.lang.Test_Class", false); - } - AssertJUnit.assertTrue("the file " + name + " can not be found in this directory", - clazz.getResourceAsStream(name) != null); - - System.setSecurityManager(new SecurityManager()); - try { - InputStream res = Object.class.getResourceAsStream("Object.class"); - AssertJUnit.assertTrue("Object.class should not be found", res == null); - } finally { - System.setSecurityManager(null); - } - - name = "org/openj9/resources/openj9tr_Foo.c"; - AssertJUnit.assertTrue("the file " + name + " should not be found in this directory", - clazz.getResourceAsStream(name) == null); - AssertJUnit.assertTrue("the file " + name + " can be found in the root directory", - clazz.getResourceAsStream("/" + name) != null); - // find resource from array of objects - AssertJUnit.assertTrue("the file " + name + " can be found in the root directory where the class is an array", - Test_Class[].class.getResourceAsStream("/" + name) != null); - - try { - clazz = Class.forName("java.lang.Object"); - } catch (ClassNotFoundException e) { - AssertJUnit.assertTrue("Should be able to find the class java.lang.Object", false); - } - InputStream str = clazz.getResourceAsStream("Class.class"); - AssertJUnit.assertTrue( - "java.lang.Object couldn't find its class with getResource...", - str != null); - try { - AssertJUnit.assertTrue("Cannot read single byte", str.read() != -1); - AssertJUnit.assertTrue("Cannot read multiple bytes", str.read(new byte[5]) == 5); - str.close(); - } catch (IOException e) { - AssertJUnit.assertTrue("Exception while closing resource stream 1.", false); - } - - InputStream str2 = getClass().getResourceAsStream(Support_Resources.RESOURCE_PACKAGE + "openj9tr_compressD.txt"); - AssertJUnit.assertTrue("Can't find resource", str2 != null); - try { - AssertJUnit.assertTrue("Cannot read single byte", str2.read() != -1); - AssertJUnit.assertTrue("Cannot read multiple bytes", str2.read(new byte[5]) == 5); - str2.close(); - } catch (IOException e) { - AssertJUnit.assertTrue("Exception while closing resource stream 2.", false); - } - -} - /** * @tests java.lang.Class#getSuperclass() */ @@ -1617,7 +1332,7 @@ public void test_toGenericString() { AssertJUnit.assertEquals("static class org.openj9.test.java.lang.Test_Class$StaticMember$Class", classes[1].toGenericString()); AssertJUnit.assertEquals("class org.openj9.test.java.lang.Test_Class$Member$Class", classes[2].toGenericString()); AssertJUnit.assertEquals("class org.openj9.test.java.lang.Test_Class$1Local$Class", classes[3].toGenericString()); - AssertJUnit.assertEquals("class org.openj9.test.java.lang.Test_Class$6", classes[4].toGenericString()); + AssertJUnit.assertEquals("class org.openj9.test.java.lang.Test_Class$3", classes[4].toGenericString()); AssertJUnit.assertEquals("int", classes[5].toGenericString()); AssertJUnit.assertEquals("class org.openj9.test.java.lang.Test_Class$1Local$Class$Member6$E", classes[6].toGenericString()); AssertJUnit.assertEquals("class org.openj9.test.java.lang.Test_Class$StaticMember$Class$Member2$A", classes[7].toGenericString()); @@ -1658,7 +1373,7 @@ public void test_getTypeName() { AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$StaticMember$Class", classes[1].getTypeName()); AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$Member$Class", classes[2].getTypeName()); AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$1Local$Class", classes[3].getTypeName()); - AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$6", classes[4].getTypeName()); + AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$3", classes[4].getTypeName()); AssertJUnit.assertEquals("int", classes[5].getTypeName()); AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$1Local$Class$Member6$E", classes[6].getTypeName()); AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$StaticMember$Class$Member2$A", classes[7].getTypeName()); diff --git a/test/functional/Java8andUp/src_110_up/org/openj9/test/java/lang/Test_System.java b/test/functional/Java8andUp/src_110_up/org/openj9/test/java/lang/Test_System.java index 74fd8744bac..a104e335ccf 100644 --- a/test/functional/Java8andUp/src_110_up/org/openj9/test/java/lang/Test_System.java +++ b/test/functional/Java8andUp/src_110_up/org/openj9/test/java/lang/Test_System.java @@ -1,7 +1,7 @@ package org.openj9.test.java.lang; /******************************************************************************* - * Copyright (c) 1998, 2021 IBM Corp. and others + * Copyright (c) 1998, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -232,15 +232,6 @@ public void test_setProperty3() { } } - /** - * @tests java.lang.System#getSecurityManager() - */ - @Test - public void test_getSecurityManager() { - AssertJUnit.assertTrue("Returned incorrect SecurityManager", System - .getSecurityManager() == null); - } - /** * @tests java.lang.System#identityHashCode(java.lang.Object) */ @@ -306,104 +297,6 @@ public void test_lineSeparator() { } } - /** - * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) - */ - @Test - public void test_setSecurityManager() { - /* [PR 97686, 123113] Improve System.setSecurityManager() initialization */ - class MySecurityManager extends SecurityManager { - public void preloadClasses(Permission perm) { - if (!(perm instanceof RuntimePermission) - || !perm.getName().toLowerCase().equals( - "setsecuritymanager")) { - // do nothing, required classes are now loaded - } - } - - public void checkPermission(Permission perm) { - if (!(perm instanceof RuntimePermission) - || !perm.getName().toLowerCase().equals( - "setsecuritymanager")) { - super.checkPermission(perm); - } - } - } - - MySecurityManager newManager = new MySecurityManager(); - // preload the required classes without calling implies() - try { - newManager.preloadClasses(new RuntimePermission("anything")); - } catch (SecurityException e) { - } - try { - System.setSecurityManager(new SecurityManager()); - System.getProperty("someProperty"); - Assert.fail("should cause SecurityException"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(null); - } - } - - /** - * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) - */ - @Test - public void test_setSecurityManager2() { - try { - String helperName = "org.openj9.test.java.lang.Test_System$TestSecurityManager"; - String output = Support_Exec.execJava(new String[] { - "-Djava.security.manager=" + helperName, helperName }, - null, true); - AssertJUnit.assertTrue("not correct SecurityManager: " + output, output - .startsWith(helperName)); - } catch (Exception e) { - Assert.fail("Unexpected: " + e); - } - } - - /** - * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) - */ - public static class TestSecurityManager extends SecurityManager { - public static void main(String[] args) { - System.out - .println(System.getSecurityManager().getClass().getName()); - } - } - - /** - * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) - */ - @Test - public void test_setSecurityManager3() { - /* https://github.com/eclipse-openj9/openj9/issues/6661 */ - try { - String helperName = "org.openj9.test.java.lang.Test_System$TestSecurityManagerNonPublicConstructor"; - String output = Support_Exec.execJava(new String[] { "-Djava.security.manager=" + helperName, helperName }, - null, true, - "java.lang.NoSuchMethodException: org.openj9.test.java.lang.Test_System$TestSecurityManagerNonPublicConstructor.()"); - // if the expected error string was not found, Assert.fail() will be invoked - // within Support_Exec.execJava() above. - } catch (Exception e) { - Assert.fail("Unexpected: " + e); - } - } - - /** - * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) - */ - public static class TestSecurityManagerNonPublicConstructor extends SecurityManager { - TestSecurityManagerNonPublicConstructor() { - } - - public static void main(String[] args) { - System.out.println(System.getSecurityManager().getClass().getName()); - } - } - /** * Sets up the fixture, for example, open a network connection. This method * is called before a test is executed. diff --git a/test/functional/Java8andUp/src_80/org/openj9/test/java/lang/Test_Class.java b/test/functional/Java8andUp/src_80/org/openj9/test/java/lang/Test_Class.java index d28e22630a7..7894c334d40 100644 --- a/test/functional/Java8andUp/src_80/org/openj9/test/java/lang/Test_Class.java +++ b/test/functional/Java8andUp/src_80/org/openj9/test/java/lang/Test_Class.java @@ -1,7 +1,7 @@ package org.openj9.test.java.lang; /******************************************************************************* - * Copyright (c) 1998, 2021 IBM Corp. and others + * Copyright (c) 1998, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -29,7 +29,6 @@ import org.testng.AssertJUnit; import org.testng.log4testng.Logger; import java.io.File; -import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.annotation.Inherited; @@ -43,10 +42,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; -import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; -import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; @@ -67,7 +64,6 @@ import org.openj9.test.java.lang.specimens.InterfaceTestClasses; import org.openj9.test.java.lang.specimens.SuperA; import org.openj9.test.java.lang.specimens.SuperDuper; -import org.openj9.test.support.resource.Support_Resources; import sun.misc.SharedSecrets; @@ -332,51 +328,6 @@ public void test_getMethods_subtest1() { } } - @Test - public void test_getMethods_subtest2() { - - java.security.PrivilegedAction action = new java.security.PrivilegedAction() { - public Object run() { - try { - File resources = Support_Resources.createTempFolder(); - String[] expected_E = new String[] { - "org.openj9.resources.classinheritance.E.method_N(java.lang.String)", - "org.openj9.resources.classinheritance.E.method_M(java.lang.String)", - "org.openj9.resources.classinheritance.A.method_K(java.lang.String)", - "org.openj9.resources.classinheritance.E.method_L(java.lang.String)", - "org.openj9.resources.classinheritance.E.method_O(java.lang.String)", - "org.openj9.resources.classinheritance.B.method_K(java.lang.String)" }; - - Support_Resources.copyFile(resources, null, "openj9tr_general.jar"); - File file = new File(resources.toString() + "/openj9tr_general.jar"); - java.net.URL url = new java.net.URL("file:" + file.getPath()); - ClassLoader loader = new java.net.URLClassLoader(new java.net.URL[] { url }, null); - - Class cls_E = Class.forName("org.openj9.resources.classinheritance.E", false, loader); - Method[] methodNames_E = cls_E.getMethods(); - AssertJUnit.assertEquals("Returned incorrect number of methods for cls_E", - expected_E.length + Object.class.getMethods().length, methodNames_E.length); - for (int i = 0; i < expected_E.length; i++) { - boolean match = false; - for (int j = 0; j < methodNames_E.length; j++) { - if (methodNames_E[j].toString().indexOf(expected_E[i]) != -1) { - match = true; - } - } - AssertJUnit.assertTrue("Expected method " + expected_E[i] + " not found.", match); - } - } catch (MalformedURLException e) { - logger.error("Unexpected exception: " + e); - } catch (ClassNotFoundException e) { - logger.error("Unexpected exception: " + e); - } - - return null; - } - }; - java.security.AccessController.doPrivileged(action); - } - static class ParentClass { public static void methodPublicStatic() {} public void methodPublicInstance() {} @@ -715,172 +666,6 @@ public void test_getClasses() { } } - /** - * @tests java.lang.Class#getClasses() - */ - @Test - public void test_getClasses2() { - final java.security.Permission privCheckPermission = new java.security.BasicPermission("Privilege check") { - }; - class MyCombiner implements java.security.DomainCombiner { - boolean combine; - - public java.security.ProtectionDomain[] combine(java.security.ProtectionDomain[] executionDomains, - java.security.ProtectionDomain[] parentDomains) { - combine = true; - return new java.security.ProtectionDomain[0]; - } - - public boolean isPriviledged() { - combine = false; - try { - java.security.AccessController.checkPermission(privCheckPermission); - } catch (SecurityException e) { - } - return !combine; - } - } - ; - final MyCombiner combiner = new MyCombiner(); - class SecurityManagerCheck extends SecurityManager { - String reason; - Class checkClass; - int checkType; - int checkPermission = 0; - int checkMemberAccess = 0; - int checkPackageAccess = 0; - - public void setExpected(String reason, Class cls, int type) { - this.reason = reason; - checkClass = cls; - checkType = type; - checkPermission = 0; - checkMemberAccess = 0; - checkPackageAccess = 0; - } - - public void checkPermission(java.security.Permission perm) { - if (combiner.isPriviledged()) - return; - checkPermission++; - } - - public void checkPackageAccess(String packageName) { - if (packageName.startsWith("java.") || packageName.startsWith("org.openj9.test.java.lang")) { - return; - } - if (combiner.isPriviledged()) - return; - checkPackageAccess++; - String name = checkClass.getName(); - int index = name.lastIndexOf('.'); - String checkPackage = name.substring(0, index); - AssertJUnit.assertTrue(reason + " unexpected package: " + packageName, - packageName.equals(checkPackage)); - } - - public void assertProperCalls() { - int declared = checkType == Member.DECLARED ? 1 : 0; - AssertJUnit.assertTrue(reason + " unexpected checkPermission count: " + checkPermission, - checkPermission == declared); - AssertJUnit.assertTrue(reason + " unexpected checkPackageAccess count: " + checkPackageAccess, - checkPackageAccess == 1); - } - } - - final SecurityManagerCheck sm = new SecurityManagerCheck(); - System.setSecurityManager(sm); - - java.security.AccessControlContext acc = new java.security.AccessControlContext( - new java.security.ProtectionDomain[0]); - java.security.AccessControlContext acc2 = new java.security.AccessControlContext(acc, combiner); - - java.security.PrivilegedAction action = new java.security.PrivilegedAction() { - public Object run() { - File resources = Support_Resources.createTempFolder(); - try { - Support_Resources.copyFile(resources, null, "openj9tr_general.jar"); - File file = new File(resources.toString() + "/openj9tr_general.jar"); - java.net.URL url = new java.net.URL("file:" + file.getPath()); - ClassLoader loader = new java.net.URLClassLoader(new java.net.URL[] { url }, null); - Class cls = Class.forName("org.openj9.resources.security.SecurityTestSub", false, loader); - // must preload junit.framework.Assert before installing SecurityManager - // otherwise loading it inside checkPackageAccess() is recursive - AssertJUnit.assertTrue("preload assertions", true); - try { - sm.setExpected("getClasses", cls, java.lang.reflect.Member.PUBLIC); - cls.getClasses(); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredClasses", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredClasses(); - sm.assertProperCalls(); - - sm.setExpected("getConstructor", cls, java.lang.reflect.Member.PUBLIC); - cls.getConstructor(new Class[0]); - sm.assertProperCalls(); - - sm.setExpected("getConstructors", cls, java.lang.reflect.Member.PUBLIC); - cls.getConstructors(); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredConstructor", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredConstructor(new Class[0]); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredConstructors", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredConstructors(); - sm.assertProperCalls(); - - sm.setExpected("getField", cls, java.lang.reflect.Member.PUBLIC); - cls.getField("publicField"); - sm.assertProperCalls(); - - sm.setExpected("getFields", cls, java.lang.reflect.Member.PUBLIC); - cls.getFields(); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredField", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredField("publicField"); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredFields", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredFields(); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredMethod", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredMethod("publicMethod", new Class[0]); - sm.assertProperCalls(); - - sm.setExpected("getDeclaredMethods", cls, java.lang.reflect.Member.DECLARED); - cls.getDeclaredMethods(); - sm.assertProperCalls(); - - sm.setExpected("getMethod", cls, java.lang.reflect.Member.PUBLIC); - cls.getMethod("publicMethod", new Class[0]); - sm.assertProperCalls(); - - sm.setExpected("getMethods", cls, java.lang.reflect.Member.PUBLIC); - cls.getMethods(); - sm.assertProperCalls(); - - sm.setExpected("newInstance", cls, java.lang.reflect.Member.PUBLIC); - cls.newInstance(); - sm.assertProperCalls(); - } finally { - System.setSecurityManager(null); - } - } catch (Exception e) { - if (e instanceof RuntimeException) - throw (RuntimeException)e; - Assert.fail("unexpected exception: " + e); - } - return null; - } - }; - java.security.AccessController.doPrivileged(action, acc2); - } - /** * @tests java.lang.Class#getComponentType() */ @@ -1355,91 +1140,6 @@ public void test_getName() { className.equals("[Ljava.lang.Object;")); } - /** - * @tests java.lang.Class#getResource(java.lang.String) - */ - @Test - public void test_getResource() { - // Test for method java.net.URL java.lang.Class.getResource(java.lang.String) - System.setSecurityManager(new SecurityManager()); - try { - java.net.URL res = Object.class.getResource("Object.class"); - AssertJUnit.assertTrue("Object.class should not be found", res == null); - } finally { - System.setSecurityManager(null); - } - - String name = "/org/openj9/resources/openj9tr_Foo.c"; - - // find resource from object - AssertJUnit.assertTrue("directory of this class can be found", - Test_Class.class.getResource(name) != null); - - // find resource from array of objects - AssertJUnit.assertTrue("directory of array of this class can be found", - Test_Class[].class.getResource(name) != null); - } - - /** - * @tests java.lang.Class#getResourceAsStream(java.lang.String) - */ - @Test - public void test_getResourceAsStream() { - // Test for method java.io.InputStream java.lang.Class.getResourceAsStream(java.lang.String) - String name = Support_Resources.RESOURCE_PACKAGE + "openj9tr_compressD.txt"; - Class clazz = null; - try { - clazz = Class.forName("org.openj9.test.java.lang.Test_Class"); - } catch (ClassNotFoundException e) { - AssertJUnit.assertTrue("Should be able to find the class org.openj9.test.java.lang.Test_Class", false); - } - AssertJUnit.assertTrue("the file " + name + " can not be found in this directory", - clazz.getResourceAsStream(name) != null); - - System.setSecurityManager(new SecurityManager()); - try { - InputStream res = Object.class.getResourceAsStream("Object.class"); - AssertJUnit.assertTrue("Object.class should not be found", res == null); - } finally { - System.setSecurityManager(null); - } - - name = "org/openj9/resources/openj9tr_Foo.c"; - AssertJUnit.assertTrue("the file " + name + " should not be found in this directory", - clazz.getResourceAsStream(name) == null); - AssertJUnit.assertTrue("the file " + name + " can be found in the root directory", - clazz.getResourceAsStream("/" + name) != null); - // find resource from array of objects - AssertJUnit.assertTrue("the file " + name + " can be found in the root directory where the class is an array", - Test_Class[].class.getResourceAsStream("/" + name) != null); - - try { - clazz = Class.forName("java.lang.Object"); - } catch (ClassNotFoundException e) { - AssertJUnit.assertTrue("Should be able to find the class java.lang.Object", false); - } - InputStream str = clazz.getResourceAsStream("Class.class"); - AssertJUnit.assertTrue("java.lang.Object couldn't find its class with getResource...", str != null); - try { - AssertJUnit.assertTrue("Cannot read single byte", str.read() != -1); - AssertJUnit.assertTrue("Cannot read multiple bytes", str.read(new byte[5]) == 5); - str.close(); - } catch (IOException e) { - AssertJUnit.assertTrue("Exception while closing resource stream 1.", false); - } - - InputStream str2 = getClass().getResourceAsStream(Support_Resources.RESOURCE_PACKAGE + "openj9tr_compressD.txt"); - AssertJUnit.assertTrue("Can't find resource", str2 != null); - try { - AssertJUnit.assertTrue("Cannot read single byte", str2.read() != -1); - AssertJUnit.assertTrue("Cannot read multiple bytes", str2.read(new byte[5]) == 5); - str2.close(); - } catch (IOException e) { - AssertJUnit.assertTrue("Exception while closing resource stream 2.", false); - } - - } - /** * @tests java.lang.Class#getSuperclass() */ @@ -1701,7 +1401,7 @@ public void test_toGenericString() { classes[2].toGenericString()); AssertJUnit.assertEquals("class org.openj9.test.java.lang.Test_Class$1Local$Class", classes[3].toGenericString()); - AssertJUnit.assertEquals("class org.openj9.test.java.lang.Test_Class$6", classes[4].toGenericString()); + AssertJUnit.assertEquals("class org.openj9.test.java.lang.Test_Class$3", classes[4].toGenericString()); AssertJUnit.assertEquals("int", classes[5].toGenericString()); AssertJUnit.assertEquals("class org.openj9.test.java.lang.Test_Class$1Local$Class$Member6$E", classes[6].toGenericString()); @@ -1751,7 +1451,7 @@ public void test_getTypeName() { AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$StaticMember$Class", classes[1].getTypeName()); AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$Member$Class", classes[2].getTypeName()); AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$1Local$Class", classes[3].getTypeName()); - AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$6", classes[4].getTypeName()); + AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$3", classes[4].getTypeName()); AssertJUnit.assertEquals("int", classes[5].getTypeName()); AssertJUnit.assertEquals("org.openj9.test.java.lang.Test_Class$1Local$Class$Member6$E", classes[6].getTypeName()); diff --git a/test/functional/Java8andUp/src_80/org/openj9/test/java/lang/Test_System.java b/test/functional/Java8andUp/src_80/org/openj9/test/java/lang/Test_System.java index 3b6283287aa..97146affa36 100644 --- a/test/functional/Java8andUp/src_80/org/openj9/test/java/lang/Test_System.java +++ b/test/functional/Java8andUp/src_80/org/openj9/test/java/lang/Test_System.java @@ -1,7 +1,7 @@ package org.openj9.test.java.lang; /******************************************************************************* - * Copyright (c) 1998, 2020 IBM Corp. and others + * Copyright (c) 1998, 2022 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this @@ -24,20 +24,13 @@ import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; -import org.openj9.test.support.Support_Exec; import org.testng.Assert; import org.testng.AssertJUnit; -import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileWriter; -import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; -import java.io.Writer; -import java.security.Permission; -import java.util.Enumeration; import java.util.Properties; @Test(groups = { "level.sanity" }) @@ -250,15 +243,6 @@ public void test_setProperty3() { } } - /** - * @tests java.lang.System#getSecurityManager() - */ - @Test - public void test_getSecurityManager() { - AssertJUnit.assertTrue("Returned incorrect SecurityManager", System - .getSecurityManager() == null); - } - /** * @tests java.lang.System#identityHashCode(java.lang.Object) */ @@ -337,75 +321,6 @@ public void test_lineSeparator() { } } - /** - * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) - */ - @Test - public void test_setSecurityManager() { - /* [PR 97686, 123113] Improve System.setSecurityManager() initialization */ - class MySecurityManager extends SecurityManager { - public void preloadClasses(Permission perm) { - if (!(perm instanceof RuntimePermission) - || !perm.getName().toLowerCase().equals( - "setsecuritymanager")) { - // do nothing, required classes are now loaded - } - } - - public void checkPermission(Permission perm) { - if (!(perm instanceof RuntimePermission) - || !perm.getName().toLowerCase().equals( - "setsecuritymanager")) { - super.checkPermission(perm); - } - } - } - - MySecurityManager newManager = new MySecurityManager(); - // preload the required classes without calling implies() - try { - newManager.preloadClasses(new RuntimePermission("anything")); - } catch (SecurityException e) { - } - try { - System.setSecurityManager(new SecurityManager()); - System.getProperty("someProperty"); - Assert.fail("should cause SecurityException"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(null); - } - } - - /** - * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) - */ - @Test - public void test_setSecurityManager2() { - /* [PR 125194] Allow java.security.manager from system ClassLoader */ - try { - String helperName = "org.openj9.test.java.lang.Test_System$TestSecurityManager"; - String output = Support_Exec.execJava(new String[] { - "-Djava.security.manager=" + helperName, helperName }, - null, true); - AssertJUnit.assertTrue("not correct SecurityManager: " + output, output - .startsWith(helperName)); - } catch (Exception e) { - Assert.fail("Unexpected: " + e); - } - } - - /** - * @tests java.lang.System#setSecurityManager(java.lang.SecurityManager) - */ - public static class TestSecurityManager extends SecurityManager { - public static void main(String[] args) { - System.out - .println(System.getSecurityManager().getClass().getName()); - } - } - /** * Sets up the fixture, for example, open a network connection. This method * is called before a test is executed. diff --git a/test/functional/Java8andUp/testng.xml b/test/functional/Java8andUp/testng.xml index 3f5e77ca721..3fe4fcf5ef6 100644 --- a/test/functional/Java8andUp/testng.xml +++ b/test/functional/Java8andUp/testng.xml @@ -1,7 +1,7 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +