raphw / byte-buddy

Runtime code generation for the Java virtual machine.
https://bytebuddy.net
Apache License 2.0
6.11k stars 783 forks source link

JDK class enhancements #1656

Open zhuweimazp opened 1 month ago

zhuweimazp commented 1 month ago

Hello, I would like to ask, I want to make an enhancement to the string class, inform me that the class I wrote is executing the relevant logic, what should I do, is there a relevant example, please answer my question

zhuweimazp commented 1 month ago

I've defined the following interface to load using the boot classloader

public interface SpyDispatcher {

    public abstract void dispatcher(Object self,Object[] parameter,Object returnObj);

}

The interface is implemented in the agent

public class StainTrackingSpyDispatcherImpl implements SpyDispatcher {
    @Override
    public void dispatcher(Object self, Object[] parameter, Object returnObj) {
        System.out.println(returnObj.hashCode());
    }
}

An error is reported when the operation is run

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
    at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)
Caused by: java.lang.LinkageError: loader constraint violation: when resolving method "org.zhuwei.spy.Spy.setDispatcher(Lorg/zhuwei/spy/SpyDispatcher;)V" the class loader (instance of sun/misc/Launcher$AppClassLoader) of the current class, org/zhuwei/core/AgentCore, and the class loader (instance of <bootloader>) for the method's defining class, org/zhuwei/spy/Spy, have different Class objects for the type org/zhuwei/spy/SpyDispatcher used in the signature
    at org.zhuwei.core.AgentCore.startAugmenting(AgentCore.java:60)
    at org.zhuwei.agent.AgentLauncher.premain(AgentLauncher.java:11)
    ... 6 more
raphw commented 1 month ago

You need to seperate the class out of your agent. You likely load it on the agent before you inject it to the boot loader.

You need to assure the dispatcher is never loaded before it's injected into the boot loader.

15911075183ma commented 1 month ago

I changed the construction method and created the class through reflection, and it was normal.