Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor Object Creation using ASM in Java

I am using ASM to monitor Object creation in Java. Currently, I take the call to init as the indicator of the creation of a new object and instrument a program from

invoke XXX.init

to

dup;  
invoke XXX.init;  
call_my_method(Object)

My idea is to duplicate a copy of newObjectReference and, after the init of this object, I call my method to keep this object.

However, during runtime, there is an exception:

java.lang.VerifyError, Expecting to find unitialized object on stack.

When I used "-noverify" option, during runtime, if there is a thread instance, a second exception thrown:

Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at test.ThreadTest.test

For the second case, I am sure there is no call to start() of a thread except that in the original program.

Is there a better way to monitor the New Object Creation?

Thanks a lot.

like image 606
Life Thinker Avatar asked Oct 06 '22 06:10

Life Thinker


1 Answers

Try, converting invoke XXX.init to

invoke XXX.init;
dup;
call_my_method(Object)

Basically call the duplicate after the init method returns.

Explanation:: So given that you want to track new object creations, i am guessing you are looking at statements such as, new XXX(). Now, the way this translates to bytecode is as follows:-

NEW XXX
DUP
INVOKESPECIAL <init>

In other words, the NEW bytecode instruction is used to create the object itself. It is duplicated on top of the stack, so you have an additional copy of the object. At this point mind you, the 2 copies of the object are uninitialized. And then the init method is invoked on the first uninitialized object on top of the stack. By the time the constructor returns, the object is initialized, and thus the object sitting on top of the stack, is also initialized. (that is because the "object" sitting on top of the stack, is really an object reference pointing to the actual object which is sitting somewhere on the heap. I use the word object instead of object reference as it is simpler to explain things. sorry if this caused any confusion.)

like image 133
vijay Avatar answered Oct 10 '22 04:10

vijay