Skip to content

Latest commit

 

History

History
64 lines (45 loc) · 2.88 KB

File metadata and controls

64 lines (45 loc) · 2.88 KB

Overview

  1. How Java/JVM agents work
  2. See also asm/byte buddy doc

Key points

  1. Agents can make arbitrary mutations to class files (even those already loaded)
  2. Agents can generate new class files
  3. Agents are deployed as jar files (so you must build them first)
  4. JVM allows multiple agents, executed in order specified on command line
    1. TODO: how to do multiple when packaged (approach 3)
  5. You specify Agent class in src/main/resources/META-INF/MANIFEST.MF
    1. attributes depend on approach, see below
  6. There are 3 ways to load agent
    1. Approach-1: Command line
    2. Approach-2: Attach to running JVM
    3. Approach-3: Bundled/Packaged with the application (into same Jar)

Approach-1: Command line

java -javaagent:/path/to/jar ...

java -javaagent:/path/to/jar=option1 ...   <-- TODO: better example
  1. MANIFEST.MF must contain Premain-Class attribute
  2. Premain-Class attribute must point to a class with public static void premain(String agentArgs, Instrumentation inst) { method
    1. Intellij will enforce
  3. Any code which is legal for public static void main(...) is legal for public static void premain(...)

Approach-2: Attach to running JVM

  1. TODO

Approach-3: Bundled/Packaged with the application

  1. MANIFEST.MF must contain Launcher-Agent-Class attribute
  2. Launcher-Agent-Class attribute must point to a class with public static void agentmain(String agentArgs, Instrumentation inst) { method
    1. Intellij will enforce
  3. JVM invokes agentmain(...) method before main(...) method
  1. BootstrapClassLoader
    1. has no parent
  2. PlatformClassLoader
    1. Loads JDK
  3. System Class loader == AppClassLoader
    1. Loads your application classes

Errors/Exceptions

Gotchas

  • Debugging premain doesn't work

Other Resources

  1. https://docs.oracle.com/en/java/javase/20/docs/api/java.instrument/java/lang/instrument/package-summary.html