【发布时间】:2019-11-05 19:11:26
【问题描述】:
我有一个示例 jar,我正在从磁盘加载到类池中。从那里我可以很容易地访问这个类中的方法并使用它们来检测它们,正如你在 JsEval 方法中所做的那样。
但是,在 Helloworld 示例类中,我希望能够检测其他库函数调用。在这个例子中,我试图从 nashorn 脚本引擎中检测 eval 函数。但是,这不起作用。我能够很好地访问类(pool.get),并且能够修补 eval 的方法。但是,当我从 cl.run() 运行 SampleClass 时,方法的执行就像没有插入任何代码一样。我怀疑这与我用来执行 Sampleclass 的类加载器有关,但我被卡住了。关于我在这里做错了什么有什么想法吗?
public class maventest {
public static void main(String[] args)
throws NotFoundException, CannotCompileException, Throwable
{
ClassPool pool = ClassPool.getDefault();
Loader cl = new Loader(pool);
//pool.importPackage(Test.class.getPackage().getName());
//Get the Jar from disk. This works and the method is instrumented.
pool.insertClassPath(
"Z:\\HelloWorld\\target\\HelloWorld-1.0-SNAPSHOT-jar-with-dependencies.jar"
);
pool.importPackage("com.mycompany.helloworld");
//pool.appendClassPath();
CtClass helloworld = pool.get("com.mycompany.helloworld.SampleClass");
helloworld
.getDeclaredMethod("JsEval")
.insertBefore(
"System.out.println(\"Calling JsEval from within helloworld\\n\");"
);
//This does not work.
//Attempt to instrument the eval function that is called from inside of HelloWorld
String classToLoad = "jdk.nashorn.api.scripting.NashornScriptEngine";
String constuctor_name = "eval";
CtClass nash = pool.get(classToLoad);
//Multiple eval calls.. Just instrument them all.
CtMethod[] meths = nash.getDeclaredMethods("eval");
for (CtMethod m : meths) {
m.insertBefore(
"System.out.println(\"Nashorn Scripting Engined eval called.\");"
);
}
//Execute the hello world class with null args
cl.run("com.mycompany.helloworld.SampleClass", null);
}
}
这是调用我希望检测的 lib 函数的示例代码。
public class SampleClass {
public static void main(String[] args) throws IOException, NotFoundException {
JsEval("var greeting='hello world'; print(greeting) + greeting");
}
private static void JsEval(String js) {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
Object result = engine.eval(js);
}
catch (ScriptException ex) {
Logger.getLogger(SampleClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
【问题讨论】: