Redefine java.lang classes with ByteBuddy

萝らか妹 提交于 2019-12-10 11:26:22

问题


I'm trying to redefine classes on the java.lang package such as String.class or Integer.class using ByteBuddy but with no success. My question is if that's even possible?

This is the code I'm trying in my java agent:

public static void premain(String agentArgs, Instrumentation inst) {
    new AgentBuilder.Default()
            .type(named("java.lang.String"))
            .transform((builder, typeDescription, classLoader) ->
                    builder.method(named("toString"))
                            .intercept(FixedValue.value("toString() got hacked!")))
            .with(AgentBuilder.Listener.StreamWriting.toSystemOut())
            .with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
            .with(AgentBuilder.TypeStrategy.Default.REDEFINE)
            .installOn(inst);
}

When I check the output of the logs and what I see regarding the String class is:

[Byte Buddy] IGNORE [[Ljava.lang.String; [null, null]
[Byte Buddy] COMPLETE [[Ljava.lang.String; [null, null]

Does this means that ByteBuddy is not redefining the String class? Is that even possible?

Many thanks.


回答1:


Yes, Byte Buddy can redefine any class but by default, the bootstrap classes are ignored. You can override this default setting by defining a custom ignore matcher or just removing it alltogether:

AgentBuilder agentBuilder = new AgentBuilder.Default().ignore(none());

I would however strongly advice you against messing with the bootstrap classes and especially with the String class. A lot of code makes strong assumptions about the toString class.

Most JVMs do not allow you to alter the class file format when redefining classes which is why you should enable the .disableClassFormatChanges() option. Doing so, you cannot longer add methods or fields which is when you should look into using the Advice class instead of the standard interceptors.



来源:https://stackoverflow.com/questions/40433232/redefine-java-lang-classes-with-bytebuddy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!