8281001: Class::forName(String) defaults to system class loader if the caller is null

Reviewed-by: mchung
This commit is contained in:
Tim Prinzing 2022-06-08 16:21:55 +00:00 committed by Mandy Chung
parent c68419f2f7
commit b92ce2699b
4 changed files with 12 additions and 7 deletions

View file

@ -357,6 +357,11 @@ public final class Class<T> implements java.io.Serializable,
* A call to {@code forName("X")} causes the class named
* {@code X} to be initialized.
*
* <p>
* In cases where this method is called from a context where there is no
* caller frame on the stack (e.g. when called directly from a JNI
* attached thread), the system class loader is used.
*
* @param className the fully qualified name of the desired class.
* @return the {@code Class} object for the class with the
* specified name.
@ -380,7 +385,9 @@ public final class Class<T> implements java.io.Serializable,
@CallerSensitiveAdapter
private static Class<?> forName(String className, Class<?> caller)
throws ClassNotFoundException {
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
ClassLoader loader = (caller == null) ? ClassLoader.getSystemClassLoader()
: ClassLoader.getClassLoader(caller);
return forName0(className, true, loader, caller);
}
/**

View file

@ -24,12 +24,12 @@
#define __CallHelper_hpp__
#include <stdlib.h>
#include <stdio.h>
#include <jni.h>
#undef NDEBUG
#include <assert.h>
#include <string>
#include <algorithm>
#include <iostream>
/*
* basis of classes to provide a bunch of checking in native calls to java
@ -48,7 +48,7 @@ protected:
void emitErrorMessage(const std::string& msg) {
std::string nm = classname;
std::replace(nm.begin(), nm.end(), '/', '.');
::printf("ERROR: %s::%s, %s\n", nm.c_str(), method.c_str(), msg.c_str());
std::cerr << "ERROR: " << nm << "::" << method << ", " << msg << std::endl;
}
// check the given object which is expected to be null
@ -202,7 +202,7 @@ public:
};
void emitErrorMessageAndExit(const std::string& msg) {
::printf("ERROR: %s\n", msg.c_str());
std::cerr << "ERROR: " << msg << std::endl;
::exit(-1);
}

View file

@ -24,7 +24,7 @@
/**
* @test
* @bug 8280902 8281000 8281003 8281006
* @bug 8280902 8281000 8281003 8281006 8281001
* @summary Test uses custom launcher that starts VM using JNI that verifies
* various API called with a null caller class function properly.
* @library /test/lib

View file

@ -83,12 +83,10 @@ void registerAsParallelCapable(JNIEnv* env) {
* Class exp = Class.forName("open.OpenResources");
*/
void forName(JNIEnv* env) {
/* coming soon
StaticCall m_Class_forName { env,
"java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;" };
m_Class_forName.callReturnNotNull(env->NewStringUTF("open.OpenResources"));
*/
}
/*