Java Reverse Fundamentals First Understanding javaagent

First of all, what is javaagent?

javaagent is a way to modify bytecode without affecting normal compilation.

In reverse, javaagent can complete the interception and enhancement of classes.

see an example

Create a new project with the following MyAgent structure in Eclipse

QQ screenshot 20180423085023.png

MyAgent.java file content

package com.vvvtimes.demo.agent;

import java.lang.instrument.Instrumentation;

public class MyAgent {

    public static void premain(String agentOps, Instrumentation inst) {
        System.out.println("========The number of premain parameters is 2 Method execution ========, My agentOps = [" + agentOps + "].");
        System.out.println(agentOps);
    }

    public static void premain(String agentOps) {
        System.out.println("========The number of premain parameters is 1 method execution========, My agentOps = [" + agentOps + "].");
        System.out.println(agentOps);
    }
}

MANIFEST.MF file content

Manifest-Version: 1.0
Premain-Class: com.vvvtimes.demo.agent.MyAgent
Can-Redefine-Classes: true

Note: Premain-Class here must point to the class where the premain method is located

You need to manually specify this file when Eclipse exports the jar

QQ screenshot 20180423085313.png

We will name the exported jar MyAgent.jar

Create another project named MyProgram

code show as below

package com.vvvtimes.demo;

public class MyProgram {
	public static void main(String[] args) {
		System.out.println("========Main method execution========");
	}

}

Export the runnable jar and name it MyProgram.jar

Put these two jars in the same directory (I put them on the desktop)

cd to this directory and execute

java -javaagent:MyAgent.jar=helloworld -jar MyProgram.jar

The running result is as follows

C:\Users\admin\Desktop>java -javaagent:MyAgent.jar=helloworld -jar MyProgram.jar
========The number of premain parameters is 2 Method execution ========, My agentOps = [helloworld].
helloworld
========Main method execution========

You can see that the two output statements in the premain method are executed before the main method is executed.

javaagent parameter options

java -javaagent:location of agentjar file [= parameters passed to premain] -jar jar file to run


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324660703&siteId=291194637