tinycodinglm / lang /lang-0021.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
4.33 kB
opencode trace
System You are an expert Java agent developer specializing in bytecode instrumentation, runtime agents, and the Java Instrumentation API.

You are an expert Java agent developer specializing in bytecode instrumentation, runtime agents, and the Java Instrumentation API.

User

How do I create an agent that attaches to a running JVM at runtime using agentmain()? Explain the VirtualMachine.attach() mechanism and provide complete code examples.

Assistant

Runtime Attachment with agentmain()

Runtime attachment lets you inject an agent into an already-running JVM without restarting it.

1. The Agent with agentmain()

java
import java.lang.instrument.Instrumentation;

public class RuntimeAgent {
    private static Instrumentation instrumentation;

    public static void agentmain(String agentArgs, Instrumentation inst) {
        instrumentation = inst;
        System.out.println("RuntimeAgent: agentmain called on PID " +
            ProcessHandle.current().pid());

        inst.addTransformer(new RuntimeTransformer(), true);

        // Optionally retransform already loaded classes
        for (Class<?> cls : inst.getAllLoadedClasses()) {
            if (cls.getName().startsWith("com.example.")) {
                try {
                    inst.retransformClasses(cls);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Instrumentation getInstrumentation() {
        return instrumentation;
    }
}

2. The Manifest.MF

markdown
Manifest-Version: 1.0
Agent-Class: com.example.RuntimeAgent
Can-Redefine-Classes: true
Can-Retransform-Classes: true

Note: Agent-Class (not Premain-Class) for runtime attachment.

3. The Attach Client

java
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import java.util.List;

public class AttachClient {
    public static void main(String[] args) throws Exception {
        // List all JVMs
        List<VirtualMachineDescriptor> vms = VirtualMachine.list();
        for (VirtualMachineDescriptor vmid : vms) {
            System.out.println("PID: " + vmid.id() +
                " | Main class: " + vmid.mainClass().orElse("N/A"));
        }

        // Attach to a specific PID
        String pid = args[0];
        VirtualMachine vm = VirtualMachine.attach(pid);
        try {
            String agentPath = "path/to/runtime-agent.jar";
            vm.loadAgent(agentPath, "option1=value1");
            System.out.println("Agent loaded successfully");
        } finally {
            vm.detach();
        }
    }
}

4. Java 9+ Dynamic Attach

java
import com.sun.tools.attach.VirtualMachine;
import java.lang.management.ManagementFactory;

public class DynamicAttacher {
    public static void attachAgent(String pid, String agentJar) {
        try {
            VirtualMachine vm = VirtualMachine.attach(pid);
            vm.loadAgent(agentJar, "arg");
            vm.detach();
        } catch (Exception e) {
            throw new RuntimeException("Attach failed", e);
        }
    }

    public static String getCurrentPid() {
        String name = ManagementFactory.getRuntimeMXBean().getName();
        return name.split("@")[0];
    }
}

5. Self-Attach for Testing

java
import java.lang.management.ManagementFactory;
import com.sun.tools.attach.VirtualMachine;

public class SelfAttach {
    public static void main(String[] args) throws Exception {
        String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
        VirtualMachine vm = VirtualMachine.attach(pid);
        try {
            vm.loadAgent("my-agent.jar", "self-attach=true");
            System.out.println("Self-attach successful");
        } finally {
            vm.detach();
        }
    }
}

Key points: Use Agent-Class for runtime agents, you need tools.jar on the classpath (or jdk.attach module in Java 9+), and VirtualMachine.loadAgent() calls agentmain() in the target JVM.