问题
I made a java agent with bytebuddy. It works well untill target application load classes form uRLConnection.getInputStream. The target app works well without attachment the agent, but shows exception [java.lang.ClassNotFoundException] when the agent attached. this is app's classloading line.
return this.getClass().getClassLoader().loadClass(string) //string points the name of a byte array.
In the application, the classes is provided in the form of byte array from the uRLConnection.getInputStream at runtime and the application loads those at runtime. The eclipst stacktrace:
[Byte Buddy] COMPLETE client [app.m@7dc3712, null, loaded=false]
Exception in thread "main" java.lang.NoClassDefFoundError: kh
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at app.m.loadClass(m.java:22)
at java.lang.ClassLoader.loadClass(Unknown Source)
at app.appletviewer.b(appletviewer.java:1176)
at app.appletviewer.a(appletviewer.java:454)
at Launcher.main(Launcher.java:43)
Caused by: java.lang.ClassNotFoundException: kh
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at app.u.loadClass(u.java:79)
at java.lang.ClassLoader.findSystemClass(Unknown Source)
at app.m.loadClass(m.java:30)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 7 more
My agent is:
try {
new AgentBuilder.Default()
.with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
.with(AgentBuilder.Listener.StreamWriting.toSystemError())
.type((ElementMatchers.any()))
.transform((builder, typeDescription, classLoader, module) -> builder
.method(ElementMatchers.any())
.intercept(Advice.to(MyAdviser.class))
).installOn(instrumentation);
} catch (Exception e) {
return;
}
I also tried
.transform(new AgentBuilder.Transformer.ForAdvice()
.include(MyAdviser.class.getClassLoader())
.advice(ElementMatchers.any(), MyAdviser.class.getName()))
But it doesn't seem to be attached.
回答1:
I think your problem might be something else here. Try the second form of advice which avoids class loading where a class loading of a system class in an too ealry stage is probably is your problem in the application of loaded advice. Set an .ignore(none())
matcher for the instrumentation to make the second approach work as boot strap classes like URLConnection are not by instrumented by Byte Buddy in the default configuration.
来源:https://stackoverflow.com/questions/53644246/how-to-attach-bytebuddy-agent-when-target-application-load-classes-from-urlconne