intercept System.currentTimeMillis()
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);
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.
https://github.com/raphw/byte-buddy/issues/1195 Referring to this case, it seems that someone has successfully intercepted java.lang.System#currentTimeMillis before.
They use MemberSubstitution. The ticket states explicitly that the instrumentation did not effectuate.
Therefore, given the current situation, it is not possible to intercept and tamper with System.currentTimeMillis().