Perplex
Perplex

Reputation: 13

Java Agent wont load into JVM

Im trying to load a Java Agent into a running JVM. I have the JVMs PID but whenever I try to load the agent into the JVM I get the error com.sun.tools.attach.AgentLoadException: Agent JAR not found or no Agent-Class attribute. Both files are in the same directory. I compile the class and package the class into a JAR archive using javac JavaAgent.java and jar cmf manifest.txt JavaAgent.jar *.class. Any help would be appreciated, thanks in advance.

AgentInstaller

package com.company;
import com.sun.tools.attach.*;

import java.io.IOException;

public class AgentLoader {

    public static void loadAgent() {
        String agentPath = "JavaAgent.jar";

        System.out.println("Dynamically loading java agent");
        String pid = "9484";

        try {
            VirtualMachine vm = VirtualMachine.attach(pid);
            vm.loadAgent(agentPath);
            vm.detach();
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

JavaAgent

package com.company;
import java.lang.instrument.Instrumentation;

class JavaAgent {
    private static Instrumentation instrumentation;

    public static void agentmain (String args, Instrumentation inst){
        System.out.println("Java Agent inserted");
    }

}

Manifest.txt

Main-Class: com.company.MyMainClass
Agent-Class: com.company.AgentLoader
Can-Redefine-Classes: true
Can-Retransform-Classes: true

UPDATE

Thanks to apangin I am now able to load the agent but it fails to initialize com.sun.tools.attach.AgentInitializationException: Agent JAR loaded but agent failed to initialize. I am running a Oracle JDK.

Upvotes: 1

Views: 4077

Answers (2)

Dimitar II
Dimitar II

Reputation: 2519

This error (Agent JAR loaded but agent failed to initialize) does not provide enough information to see where your agent throws exception. The full stacktrace appears on the other side - the JVM you are trying to attach to.

Attach the agent to some JVM which will display the agent output. Easy option is kotlinc (Kotlin compiler - its console waits in interactive mode). Then attach the agent and the stacktrace will appear in the kotlinc console. Close the target JVM before doing another attempt with modified agent. Otherwise the changes will not be applied.

Upvotes: 1

apangin
apangin

Reputation: 98324

Specify the full absolute path in agentPath.

Manifest should be named MANIFEST.MF

Agent-Class should be the fully qualified class name of the agent: com.company.JavaAgent.

Upvotes: 2

Related Questions