byte-buddy icon indicating copy to clipboard operation
byte-buddy copied to clipboard

intercept System.currentTimeMillis()

Open lss9981 opened this issue 8 months ago • 4 comments

I want to intercept and modify the return value of System.currentTimeMillis() (a native method), and I also need to ensure thread isolation. I'm using Java 21, so JIT optimizations may be involved. My ByteBuddy version is 1.14.9. Is there any sample code or reference available?

The following code did not take effect.And I have already configured the following options at startup: -XX:+UnlockDiagnosticVMOptions -XX:DisableIntrinsic=_currentTimeMillis

return new AgentBuilder.Default()
                .enableNativeMethodPrefix(NATIVE_METHOD_PREFIX)
                .with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
                .with(AgentBuilder.InitializationStrategy.NoOp.INSTANCE)
                .ignore(not(ElementMatchers.is(System.class)))
                .type(ElementMatchers.is(System.class))
                .transform((builder, typeDescription, classLoader, module, protectionDomain) -> builder.method(ElementMatchers.named(Time_METHOD)).intercept(Advice.to(SystemTimeAdvice.class)))
                .installOn(instrumentation);

lss9981 avatar May 09 '25 10:05 lss9981

Interception of native methods is not very well supported, and I do not think it is possible with a Java agent for currentTimeMillis. This as the rebased method name is not permitted as System is loaded before the agent can be loaded.

raphw avatar May 11 '25 19:05 raphw

https://github.com/raphw/byte-buddy/issues/1195 Referring to this case, it seems that someone has successfully intercepted java.lang.System#currentTimeMillis before.

lss9981 avatar May 13 '25 01:05 lss9981

They use MemberSubstitution. The ticket states explicitly that the instrumentation did not effectuate.

raphw avatar May 13 '25 12:05 raphw

Therefore, given the current situation, it is not possible to intercept and tamper with System.currentTimeMillis().

lss9981 avatar May 14 '25 02:05 lss9981