Realization of obtaining relevant data in method interception
If you don't understand my last article, please step back and run it as you go, and in the process of running you will deepen the
Understanding of the program.
This article mainly uses ASM to obtain the relevant data when the method is called when intercepting the method, such as the parameter list, the local variable list, the method
Important data such as the call stack and operation status code, and the method execution time. System Information combined with current system memory status, CPU utilization, etc.
You can provide the most reliable analysis basis for the business logic when an exception occurs. This article requires a certain understanding of bytecode, even if you have some original
Because I have to copy the implementation here, I also hope that you can use the implementation of these examples prior to understand it. Able to read and use the content correctly
These implementations, you would have been able to understand it.
A bit more around the place, let's compare the dynamic generation of class with ASM and the use of proxy agents to inject code differently:
When using proxies to inject code, we are actually using reflection to invoke a method object. So inject the code directly into the
Before and after the Invoke:
Before (); Invoke (Obj,m,args); After ();
This kind of implementation is very well understood, it is plain that if you want to execute method m, then please give me to help you execute, so I can
Man shows off: I'm going to execute method M (before), I've executed method M (after).
When ASM dynamically generates class, the Onmethodenter and Onmethodeixt methods of Myadviceadaptor are wrapping a method
Called when a method is run instead of running one. If we call in the Onmethodenter method
System.out.println ("Hello,world");
This is the invocation of a System.out.println ("Hello") that is unrelated to the new method to be generated when Visitmethod.
The generated method is not injected with any instructions, so the System.out.println ("Hello") is not invoked at execution time;
The correct approach is to invoke the ASM operation in Onmethodenter to insert the directive into the method to be wrapped:
VISITFIELDINSN (getstatic, "Java/lang/system", "Out", "ljava/io/printstream;"); VISITLDCINSN ("Hello world!"); VISITMETHODINSN (invokevirtual, "Java/io/printstream", "println", "(ljava/lang/string;) V");
Such a talent would be System.out.println ("Hello,world") and inserted into the forefront of the newly generated method.
For example, the original method is
void test{New Thread (). Start ();}
So, using ASM to generate this method should be
VISITTYPEINSN (NEW, "Java/lang/thread"); VISITINSN (DUP); VISITMETHODINSN (invokespecial, "Java/lang/thread", "<init>", "() V"); VISITMETHODINSN (invokevirtual, "Java/lang/thread", "Start", "() V"); VISITINSN (RETURN);
And now because Myadviceadaptor's Onmethodenterr method has the code to insert the instruction, the code will be in Methoevisitor
First insert before starting the generation of the original method, that is, the instruction that generates the new method becomes:
VISITFIELDINSN (getstatic, "Java/lang/system", "Out", "ljava/io/printstream;"); VISITLDCINSN ("Hello world!"); VISITMETHODINSN (invokevirtual, "Java/io/printstream", "println", "(ljava/lang/string;) V");//here if the stack has no balance it should be added to the pop. The code that enables you to insert is restored to its original state before the original method code begins after execution is complete. VISITTYPEINSN (NEW, "Java/lang/thread"); VISITINSN (DUP); Remember last year I wrote about why the object new operation will certainly be DUP. Http://blog.csdn.net/axman/archive/2008/05/05/2393621.aspx visitmethodinsn (invokespecial, "Java/lang/thread", " <init> "," () V "); VISITMETHODINSN (invokevirtual, "Java/lang/thread", "Start", "() V"); VISITINSN (RETURN);
This way the original method is regenerated to:
void test{System.out.println ("Hello,world"); new Thread (). Start ();
Similarly, the ASM Insert directive must be used in Onmethodeixt to inject code into the resulting method.
Well, make sense of the theory above. We are here to get the relevant data.
First, in a method invocation, we are able to get the parameter list of the method and the local variable list using ASM. And the method last operation status code
The time difference between the code injected before and after the original method can be used to calculate the execution times of the original method code.
Because the code that is inserted in the Onmethodenter method is inserted before all operations of the original method include an argument pass, the parameter table is obtained,
Local variable table, operation status code is obtained in the Onmethodeixt method:
Get a list of local variables:
void onmethodexit (int opcode) {int localvarcnt = 0; if (nextlocal > firstlocal) localvarcnt = nextlocal-firstlocal;// These two variables are implemented by the Adviceadapter superclass, because a methodvisitor can parse the local variable table from a method in the original//class in Visitmethod. Note that I said that the local variable table refers to a static table. The local variable list is a list of actual variables in the method stack that is said//in the actual memory of the method call. Loadvararray (LOCALVARCNT); } private void Loadvararray (int varcnt) {Type object_type = Type.getobjecttype ("Java/lang/object"); push (VARCNT); NewArray (object_type); for (int i = 0; i < varcnt; i++) {int index = super.firstlocal + i; DUP (); push (i); loadlocal (index); box (Getlocaltype (index)); Arraystore (object_type); }///At this point the local variables have all been placed in a object[], this is the local variable list, how to come out, the following. }
To get a list of method parameters:
void onmethodexit (int opcode) {loadargarray ();//This method is also adviceadapter superclass has been implemented. In fact, and the local variable list to get almost, its specific implementation://push (Argumenttypes.length); NewArray (object_type); for (int i = 0; i < argumenttypes.length; i++) {//DUP ();//push (i);//Loadarg (i);//box (Argumenttypes[i]);//AR Raystore (object_type); }//The above loadvararray is actually referring to this code, and then calculates the actual index of the local variable to achieve. }
Well, if we're going to get a few messages right now:
The intercepted method is in the class, the method name, the local variable list (array), the parameter list (array), the operation status code. So:
void onmethodexit (int opcode) {visitldcinsn (className); visitldcinsn (methodName);//Previous article we only used the method of Sortname, The real implementation should use FullName, because//methods have overloaded, only by Sortname can not be limited to a certain method. VISITLDCINSN (string.valueof (opcode)); int localvarcnt = 0; if (Nextlocal > firstlocal) {localvarcnt = nextlocal-firstlocal; Loadvararray (localvarcnt);} else{VISITINSN (aconst_null);//In order to occupy a stack position. } int argscnt = 0; argcnt = xxx; The number of parameters can be analyzed from the method signature. if (argscnt > 0) {loadargarray ();} else{visitinsn (aconst_null);//In order to occupy a stack position. } }
OK, now that the top five operands of the stack are args,vars,opcode,mthodname,classname, we can of course use ASM instructions
The generated code passes the five operands in the stack to the specified destination, but the operation is too complex to call a method with five arguments and then
This method uses ordinary Java code to freely transmit to the destination, rather than using ASM code in the intercepted method to deliver to the destination.
So we just need to define the good one method externally:
Class org.axman.test.sender{public static void Send (String classname,string method,string opcode,object[] LocalVar, Object[] args) {//printing or saving to a file/database or to other service processing. }} then in onmethodexit: void onmethodexit (int opcode) {visitldcinsn (className); visitldcinsn (methodName);// In the previous article we only used the method of sortname, the real implementation should be used FullName, because//method has overloaded, only by Sortname can not be limited to a certain method. VISITLDCINSN (string.valueof (opcode)); int localvarcnt = 0; if (Nextlocal > firstlocal) {localvarcnt = nextlocal-firstlocal; Loadvararray (localvarcnt);} else{VISITINSN (aconst_null);//In order to occupy a stack position. } int argscnt = 0; argcnt = xxx; The number of parameters can be analyzed from the method signature. if (argscnt > 0) {loadargarray ();} else{visitinsn (aconst_null);//In order to occupy a stack position. } visitmethodinsn (Opcodes.invokestatic, "Org.axman.test.Sender", "Send", "(ljava/lang/string; ljava/lang/string; ljava/lang/string; [Ljava/lang/object; [Ljava/lang/object;) V "); }
It is possible to pass information such as the argument list, local variable list, and operation status code of the intercepted method to the outside.
Get Call stack
Using Sun.reflect.Reflection.getCallerClass (x); we can only get the class where the caller resides, if it's a different method in the same class
The call between the test fails to explicitly view the method call chain.
The full method call stack can be obtained by using Throwable's Getstacktrace (). As long as we construct a Throwable object, we can pass
It is to get all callers calling this method:
public static String Getinvokestack () {throwable t = new throwable (); Stacktraceelement ste[] = T.getstacktrace (); StringBuilder sb = new StringBuilder (); for (int i = 1; i < ste.length; i++) {Sb.append (ste[i].tostring ()). Append (";");} return sb.tostring (); }
This is just the ToString () method that calls Stacktraceelement, and you can get more information about it as needed.
Since Set[0] is the method in which the T object resides, we do not need this caller information. Therefore the circulation begins directly from 1.
If this method is called in the Test.main () method, then the first caller is directly test.main ();
Originally we need to use the ASM directive in the Onmethodeixt method to let the intercepted method call this method, and the method return value stack as a parameter
Passed to the Send method. But because the intercepted method is bound to call the Send method, so we call Getinvokestack () directly in send, then the intercepted
The method is the second caller. So we just have to start the loop from 2, and then call Getinvokestack () in the Send method, and we can get the intercepted method.
Chain of all calls.
In fact, we will also pass the classname,methodname using a similar method in the Onmethidenter method. It also passes in when you enter the method you want to intercept.
A random string to the Myadviceadaptor constructor, and in the Onmethidenter and Onmethideixt methods, the ASM command is also invoked to pass this random string to the shape
Sender.send () so that the send data for the method entry and exit can be paired. And you can use the time difference of two paired send to perform a
The code that calculates the execution time of the original method code is injected into the original method.
Other details of the problem. I'll make a confession later. (The entire test project compressed documents need to contact to obtain, previously in the blog to provide MMS project compression file, a lot of brothers actually directly take my mobile phone number in the project for development testing, I received a lot of test MMS)