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.

Sams2018
  • 1
  • 1
  • use byte-buddy in version 1.9.3 – Sams2018 Nov 02 '18 at 20:47
  • 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).”… – Holger Nov 05 '18 at 11:17
  • @Holger, After the instrumentation, when I invoke toString, for example, system.out.println ("testString".toString()); I expect to see, "!!!!!!!!!!!!!!!!!!!!!!!!!! Hacking!!!!!!!!!!!!!!!!!!!!!!!!!", then "testString" – Sams2018 Nov 05 '18 at 13:08
  • the code above, only prints, "testString" in my test – Sams2018 Nov 05 '18 at 13:18
  • 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. – Holger Nov 06 '18 at 07:40

0 Answers0