File size: 4,333 Bytes
b27bfb3 | 1 2 3 4 5 | {"type": "session", "harness": "opencode", "id": "lang-0021", "name": "agentmain() and Runtime Attachment"}
{"type": "message", "message": {"role": "system", "content": "You are an expert Java agent developer specializing in bytecode instrumentation, runtime agents, and the Java Instrumentation API."}}
{"type": "message", "message": {"role": "user", "content": "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."}}
{"type": "message", "message": {"role": "assistant", "content": "## Runtime Attachment with agentmain()\n\nRuntime attachment lets you inject an agent into an already-running JVM without restarting it.\n\n### 1. The Agent with agentmain()\n\n```java\nimport java.lang.instrument.Instrumentation;\n\npublic class RuntimeAgent {\n private static Instrumentation instrumentation;\n\n public static void agentmain(String agentArgs, Instrumentation inst) {\n instrumentation = inst;\n System.out.println(\"RuntimeAgent: agentmain called on PID \" +\n ProcessHandle.current().pid());\n\n inst.addTransformer(new RuntimeTransformer(), true);\n\n // Optionally retransform already loaded classes\n for (Class<?> cls : inst.getAllLoadedClasses()) {\n if (cls.getName().startsWith(\"com.example.\")) {\n try {\n inst.retransformClasses(cls);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n }\n\n public static Instrumentation getInstrumentation() {\n return instrumentation;\n }\n}\n```\n\n### 2. The Manifest.MF\n\n```\nManifest-Version: 1.0\nAgent-Class: com.example.RuntimeAgent\nCan-Redefine-Classes: true\nCan-Retransform-Classes: true\n```\n\nNote: Agent-Class (not Premain-Class) for runtime attachment.\n\n### 3. The Attach Client\n\n```java\nimport com.sun.tools.attach.VirtualMachine;\nimport com.sun.tools.attach.VirtualMachineDescriptor;\nimport java.util.List;\n\npublic class AttachClient {\n public static void main(String[] args) throws Exception {\n // List all JVMs\n List<VirtualMachineDescriptor> vms = VirtualMachine.list();\n for (VirtualMachineDescriptor vmid : vms) {\n System.out.println(\"PID: \" + vmid.id() +\n \" | Main class: \" + vmid.mainClass().orElse(\"N/A\"));\n }\n\n // Attach to a specific PID\n String pid = args[0];\n VirtualMachine vm = VirtualMachine.attach(pid);\n try {\n String agentPath = \"path/to/runtime-agent.jar\";\n vm.loadAgent(agentPath, \"option1=value1\");\n System.out.println(\"Agent loaded successfully\");\n } finally {\n vm.detach();\n }\n }\n}\n```\n\n### 4. Java 9+ Dynamic Attach\n\n```java\nimport com.sun.tools.attach.VirtualMachine;\nimport java.lang.management.ManagementFactory;\n\npublic class DynamicAttacher {\n public static void attachAgent(String pid, String agentJar) {\n try {\n VirtualMachine vm = VirtualMachine.attach(pid);\n vm.loadAgent(agentJar, \"arg\");\n vm.detach();\n } catch (Exception e) {\n throw new RuntimeException(\"Attach failed\", e);\n }\n }\n\n public static String getCurrentPid() {\n String name = ManagementFactory.getRuntimeMXBean().getName();\n return name.split(\"@\")[0];\n }\n}\n```\n\n### 5. Self-Attach for Testing\n\n```java\nimport java.lang.management.ManagementFactory;\nimport com.sun.tools.attach.VirtualMachine;\n\npublic class SelfAttach {\n public static void main(String[] args) throws Exception {\n String pid = ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0];\n VirtualMachine vm = VirtualMachine.attach(pid);\n try {\n vm.loadAgent(\"my-agent.jar\", \"self-attach=true\");\n System.out.println(\"Self-attach successful\");\n } finally {\n vm.detach();\n }\n }\n}\n```\n\nKey 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."}}
|