简体   繁体   中英

How to intercept object creation in Java lower than user class level

我正在寻找一些方法,通过使用Java代理或仪器类(最好是比用户类更低级别的东西)拦截JVM中的所有对象创建( new或任何替代方法来创建Object),有一个类似的问题 ,它没有'重点关注Java代理或低于检测用户类的东西

Java Objects can be created in several different ways.

  1. From Java code , when a Java method, either interpreted or compiled, executes one of the following bytecode instructions: new , newarray , anewarray , multianewarray .
  2. From native code , when native methods, including those in standard class library, call one of JNI functions: NewObject , NewObjectArray , NewStringUTF , NewDirectByteBuffer , etc.
  3. Directly from VM runtime , when a new object is created internally by JVM, for example, in response to Object.clone() , Throwable.getStackTrace() , Class.getInterfaces() , etc.

Unfortunately, there is no single point where you can collect objects from all these sources. However, there are means for intercepting all of them.

  1. Objects instantiated from Java can be caught by an Instrumentation agent. The agent needs to define a ClassFileTransformer that will scan the bytecode of all loaded classes for object-creating instructions and modify it.

    Note: there is no need to intercept all new instructions, you can instrument Object() constructor instead. But you still need to intercept array allocation instructions.

  2. JNI functions can be intercepted by JVMTI agent. You need to define your own native hooks for NewObjectArray , NewStringUTF etc. and then replace JNI function table. See JVMTI Reference for the details.

  3. Objects created by the VM can be caught by JVMTI Event Callback mechanism . The desired event is VMObjectAlloc .

    Note: JVM will not post VMObjectAlloc event for objects allocated from Java or by JNI functions.

All other ways of object instantiation (cloning, reflection, deserialization) fall into one of the above categories.


Get JDK 8 Demos and Samples from Oracle Java SE Downloads website.
There is a sample JVMTI agent for exactly this question.

Look under

  • jvmti/heapTracker
  • jvmti/hprof

You can take a look at this opensource java agent created by devexperts team https://github.com/Devexperts/aprof It provides nice reports to detect where memory is allocated. But, as i know, it doesn't intercept new objects created via JNI or sun.misc.Unsafe.allocateInstance in current version

It is pure java agent which manipulates bytecode with ASM. Before each object allocation aprof inserts method call which traks allocation size and location stack (where this allocation occurs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM