Instrument Java system class with byteBuddy
Asked Answered
T

0

0

I am new to bytebuddy. I tried to follow the link here to instrument a java system class, java.lang.String without success. Below is the code,

       AgentBuilder agentBuilder = new AgentBuilder.Default()
                .ignore(ElementMatchers.nameStartsWith("net.bytebuddy."))
                .enableBootstrapInjection(instrumentation, temp);
        agentBuilder
                .type(ElementMatchers.nameEndsWith(".String"))
                .transform(new AgentBuilder.Transformer() {
                    @Override
                    public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule) {
                        return builder.method(ElementMatchers.nameContains("toString")).intercept(MethodDelegation.to(MyInterceptor.class));
                    }
                }).installOn(instrumentation);


public static class MyInterceptor {

    public static String intercept(@SuperCall Callable<String> zuper) throws Exception {
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!  Hacking!!!!!!!!!!!!!!!!!!!!!!!!!");
        return zuper.call();
    }
}

from the ByteBuddy log, it seems the class has been transformed.

[Byte Buddy] DISCOVERY java.lang.String [null, null, loaded=true]
[Byte Buddy] TRANSFORM java.lang.String [null, null, loaded=true]
[Byte Buddy] COMPLETE java.lang.String [null, null, loaded=true]

After the instrumentation, when I invoke toString, for example,

system.out.println ("testString".toString());

I expect to see,

"!!!!!!!!!!!!!!!!!!!!!!!!!! Hacking!!!!!!!!!!!!!!!!!!!!!!!!!"
"testString" 

However, I only saw

  "testString"

Please let me know what the issue is. Thanks ahead.

Tattle answered 2/11, 2018 at 20:46 Comment(5)
use byte-buddy in version 1.9.3Tattle
You should be more specific on “But when run the test (what test), I did not see the expected (what did you expect) result (what actual result did you get).”…Lothians
@Holger, After the instrumentation, when I invoke toString, for example, system.out.println ("testString".toString()); I expect to see, "!!!!!!!!!!!!!!!!!!!!!!!!!! Hacking!!!!!!!!!!!!!!!!!!!!!!!!!", then "testString"Tattle
the code above, only prints, "testString" in my testTattle
You don’t get quotation marks in the output, do you? But anyway, perhaps String.toString() gets handled specially by the JVM, eliminating the call which is supposed to have no effect, without looking at the actual byte code.Lothians

© 2022 - 2024 — McMap. All rights reserved.