Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java Agent

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to use Java Agent". In daily operation, I believe many people have doubts about how to use Java Agent. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use Java Agent". Next, please follow the editor to study!

Brief introduction of Java Agent Technology

Java Agent is literally translated as Java agent and is often referred to as Java probe technology.

Java Agent, introduced in JDK1.5, is a technology that can dynamically modify Java bytecode. After the classes in Java are compiled, the bytecode is executed by JVM, and the bytecode information is obtained before the JVM executes the bytecode, and the bytecode is modified by the bytecode converter to complete some additional functions.

Java Agent is a jar package that cannot be run independently. It works through the JVM process attached to the target program. When starting, you only need to add the-javaagent parameter to the startup parameters of the target program and add the ClassFileTransformer bytecode converter, which is equivalent to adding an interceptor in front of the main method.

Introduction to Java Agent function

Java Agent has the following main functions:

Java Agent can intercept and modify the bytecode before loading Java bytecode

Java Agent can modify loaded bytecode while Jvm is running

Application scenarios of Java Agent:

Debugging features of IDE, such as Eclipse, IntelliJ IDEA

Hot deployment features, such as JRebel, XRebel, spring-loaded

Various online diagnostic tools, such as Btrace, Greys, and Ali's Arthas

Various performance analysis tools, such as Visual VM, JConsole, etc.

Full-link performance testing tools, such as Skywalking, Pinpoint, etc.

Principle of Java Agent implementation

Before we understand the implementation principle of Java Agent, we need to have a clear understanding of the Java class loading mechanism. One is to execute the man method through premain before it is executed, and the other is to modify the program during operation, which needs to be realized by Attach in JVM. The implementation principle of Attach is based on JVMTI.

Mainly intercept and modify the bytecode before the class is loaded

Let's introduce these key terms separately:

JVMTI is JVM Tool Interface, which is a collection of interfaces exposed by JVM to users for extension. JVMTI is based on event-driven. Every time JVM executes certain logic, it triggers callback interfaces for some events. Through these callback interfaces, users can extend themselves.

JVMTI is the unified basis for implementing Debugger, Profiler, Monitor, Thread Analyser and other tools, and it is implemented in mainstream Java virtual machines.

JVMTIAgent is a dynamic library that uses some of the interfaces exposed by JVMTI to do things that we want to do but cannot normally do, but in order to distinguish it from ordinary dynamic libraries, it generally implements one or more of the following functions:

The Agent_OnLoad function, if agent is loaded at startup, is set by the JVM parameter

Agent_OnAttach function. If agent is not loaded at startup, but if we first attach to the target process, and then send the load command to the corresponding target process to load, the Agent_OnAttach function will be called during the loading process.

Agent_OnUnload function, called when agent is unloaded

Javaagent relies on instrument's JVMTIAgent (the corresponding dynamic library under Linux is libinstrument.so), and there are also individuals called JPLISAgent (Java Programming Language Instrumentation Services Agent), which provide support for piling services written in Java language.

Instrument implements both Agent_OnLoad and Agent_OnAttach methods, that is, when in use, agent can be loaded either at startup or dynamically at runtime. Startup loading can also load instrument agent indirectly through a way similar to-javaagent:jar package path. Runtime dynamic loading depends on JVM's attach mechanism, and agent is loaded by sending load commands.

JVM Attach refers to a function of inter-process communication provided by JVM, which allows one process to pass commands to another process and perform some internal operations, such as thread dump, then it is necessary to execute jstack, and then pass parameters such as pid to the thread that needs dump to execute.

Java Agent case

Let's take the execution time of the printing method as an example, which is realized through Java Agent.

First, we need to build a simplified Maven project in which we build two Maven subprojects, one for plug-in Agent and one for the test target program.

We import two project publicly dependent packages in the parent application

Org.javassist javassist 3.28.0-GA

First of all, let's build the target program of the test.

/ / launch class public class APPMain {public static void main (String [] args) {System.out.println ("APP start!") ; AppInit.init ();}} / / public class AppInit {public static void init () {try {System.out.println ("initializing APP..."); Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();}

Then we started the program to test whether it could be executed properly, and after the program was executed properly, we began to build the probe program.

In the probe program, we need to write, change the Transformer of the original class, and complete the function of outputting the execution time of the method through the custom Transformer class.

First, check the entry of the Agent program

Public class RunTimeAgent {public static void premain (String arg, Instrumentation instrumentation) {System.out.println ("probe start!") ; System.out.println ("probe input parameters:" + arg); instrumentation.addTransformer (new RunTimeTransformer ());}}

Here every class will take this method when it is loaded. We can intercept the specified class through className, and then use javassist as a tool to deal with Class. The idea here is similar to reflection, but it is more powerful than reflection and can modify bytecode dynamically.

Javassist is an open source library for analyzing, editing, and creating Java bytecode.

Import javassist.ClassPool;import javassist.CtClass;import javassist.CtMethod;import java.lang.instrument.ClassFileTransformer;import java.lang.instrument.IllegalClassFormatException;import java.security.ProtectionDomain;public class RunTimeTransformer implements ClassFileTransformer {private static final String INJECTED_CLASS = "com.zhj.test.init.AppInit"; @ Override public byte [] transform (ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte [] classfileBuffer) throws IllegalClassFormatException {String realClassName = className.replace ("/", ".") If (realClassName.equals (INJECTED_CLASS)) {System.out.println ("intercepted class name:" + realClassName); CtClass ctClass; try {/ / use javassist to get the bytecode class ClassPool classPool = ClassPool.getDefault (); ctClass = classPool.get (realClassName) / / get all the method instances of this class, or select a method to enhance CtMethod [] declaredMethods = ctClass.getDeclaredMethods (); for (CtMethod method: declaredMethods) {System.out.println (method.getName () + "method is intercepted"); method.addLocalVariable ("time", CtClass.longType) Method.insertBefore ("System.out.println (\"-- start execution -\ "); method.insertBefore (" time = System.currentTimeMillis (); "); method.insertAfter (" System.out.println (\ "--end execution -\"); ") Method.insertAfter ("System.out.println (\" run time:\ "+ (System.currentTimeMillis ()-time));} return ctClass.toBytecode ();} catch (Throwable e) {/ / use Throwable instead of Exception System.out.println (e.getMessage ()); e.printStackTrace () }} return classfileBuffer;}}

We need to configure and compile the packaged plug-ins in Maven so that we can easily generate jar packages for Agent with Maven

Org.apache.maven.plugins maven-compiler-plugin 3.5.1 8 8 org.apache.maven.plugins maven-jar-plugin 3.2.0 true 1.0 com.zhj.agent. RunTimeAgent true true

Otherwise, we need to create a META-INF/MANIFEST.MF file under resources. The contents of the file are as follows. We can see that this is consistent with the configuration in Maven, and then package it into a jar package with the help of the compiler by configuring the compiler. You need to specify the file.

Manifest-Version: 1.0Premain-Class: com.zhj.agent.RunTimeAgentCan-Redefine-Classes: trueCan-Retransform-Classes: true

The MANIFEST.MF parameter description of the notice file:

Manifest-Version

File version

Premain-Class

The class that contains the premain method (the full path name of the class) the main method runs as a proxy

Agent-Class

The class containing the agentmain method (the full path name of the class) can be modified after the main starts

Boot-Class-Path

Sets the list of paths that the bootstrap class loader searches for. When the platform-specific mechanism for finding a class fails, the bootstrap class loader searches for these paths. Search for paths in the order listed. Paths in the list are separated by one or more spaces. (optional)

Can-Redefine-Classes true

Indicates that the required classes for this agent can be redefined, and the default value is false (optional)

Can-Retransform-Classes true

Indicates the classes required to reconvert this agent. The default value is false (optional)

Can-Set-Native-Method-Prefix true

Indicates that the native method prefix required by this agent can be set, and the default value is false (optional)

Finally, the jar package of Agent is generated through Maven, then the initiator of the test target program is modified and the JVM parameter is added.

Example parameters:-javaagent:F:\ code\ myCode\ agent-test\ runtime-agent\ target\ runtime-agent-1.0-SNAPSHOT.jar=hello

Final result:

At this point, the study on "how to use Java Agent" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report