Java Code Examples for com.sun.tools.attach.VirtualMachine#loadAgent()

The following examples show how to use com.sun.tools.attach.VirtualMachine#loadAgent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefineClass.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void loadInstrumentationAgent(String myName, byte[] buf) throws Exception {
    // Create agent jar file on the fly
    Manifest m = new Manifest();
    m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    m.getMainAttributes().put(new Attributes.Name("Agent-Class"), myName);
    m.getMainAttributes().put(new Attributes.Name("Can-Redefine-Classes"), "true");
    File jarFile = File.createTempFile("agent", ".jar");
    jarFile.deleteOnExit();
    JarOutputStream jar = new JarOutputStream(new FileOutputStream(jarFile), m);
    jar.putNextEntry(new JarEntry(myName.replace('.', '/') + ".class"));
    jar.write(buf);
    jar.close();
    String pid = Long.toString(ProcessTools.getProcessId());
    System.out.println("Our pid is = " + pid);
    VirtualMachine vm = VirtualMachine.attach(pid);
    vm.loadAgent(jarFile.getAbsolutePath());
}
 
Example 2
Source File: CoreLauncher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void attachAgent(final String targetJvmPid,
                         final String agentJarPath,
                         final String cfg) throws Exception {

    VirtualMachine vmObj = null;
    try {

        vmObj = VirtualMachine.attach(targetJvmPid);
        if (vmObj != null) {
            vmObj.loadAgent(agentJarPath, cfg);
        }

    } finally {
        if (null != vmObj) {
            vmObj.detach();
        }
    }

}
 
Example 3
Source File: AttachUtils.java    From JByteMod-Beta with GNU General Public License v2.0 6 votes vote down vote up
public void loadAgent(String agentJar, int pid, String options) {
  VirtualMachine vm = getVirtualMachine(pid);
  if (vm == null) {
    throw new RuntimeException("Can\'t attach to this jvm. Add -javaagent:" + agentJar + " to the commandline");
  } else {
    try {
      try {
        vm.loadAgent(agentJar, options);
      } finally {
        vm.detach();
      }

    } catch (Exception var9) {
      throw new RuntimeException("Can\'t attach to this jvm. Add -javaagent:" + agentJar + " to the commandline", var9);
    }
  }
}
 
Example 4
Source File: HotSwapUtil.java    From jforgame with Apache License 2.0 6 votes vote down vote up
public static String reloadClass(String path) {
        try {
            // 拿到当前jvm的进程id
            String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
            VirtualMachine vm = VirtualMachine.attach(pid);
            path = "hotswap" + File.separator + path;
            log = "empty";
            exception = null;
            List<File> files = listFiles(path);
            logger.error("热更目录[{}],总共有{}个文件", path, files.size());
            for (File file : files) {
                String classPath = path + File.separator + file.getName();
                logger.error("reload path ==" + classPath);
                // path参数即agentmain()方法的第一个参数
                vm.loadAgent("agent/hotswap-agent.jar", classPath);
                logger.error("热更日志{}", log);
                logger.error("热更异常{}", exception);
            }
//            return "热更的文件有 " + String.join(",", succFiles);
            return log;
        } catch (Throwable e) {
            logger.error("", e);
            return "热更失败";
        }
    }
 
Example 5
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Loads a java agent into the VM and checks that java.instrument is loaded.
 */
static void startJavaAgent(VirtualMachine vm, Path agent) throws Exception {
    System.out.println("Load java agent ...");
    vm.loadAgent(agent.toString());

    // the Agent class should be visible
    Class.forName("Agent");

    // types in java.instrument should be visible
    Class.forName("java.lang.instrument.Instrumentation");
}
 
Example 6
Source File: DremioAttach.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static void main(String vmid, String[] args) throws Exception {
  VirtualMachine vm = null;
  try {
    vm = VirtualMachine.attach(vmid);
    vm.loadAgent(DremioAgent.class.getProtectionDomain().getCodeSource().getLocation().getPath(), String.join("\t", args));
  } finally {
    if (vm != null) {
      vm.detach();
    }
  }
}
 
Example 7
Source File: Agent.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static public void main(String[] args) throws Exception {
    // Create speculative trap entries
    Test.m();

    String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
    int p = nameOfRunningVM.indexOf('@');
    String pid = nameOfRunningVM.substring(0, p);

    // Make the nmethod go away
    for (int i = 0; i < 10; i++) {
        System.gc();
    }

    // Redefine class
    try {
        VirtualMachine vm = VirtualMachine.attach(pid);
        vm.loadAgent(AGENT_JAR, "");
        vm.detach();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    Test.m();
    // GC will hit dead method pointer
    for (int i = 0; i < 10; i++) {
        System.gc();
    }
}
 
Example 8
Source File: Agent.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static public void main(String[] args) throws Exception {
    // Create speculative trap entries
    Test.m();

    String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
    int p = nameOfRunningVM.indexOf('@');
    String pid = nameOfRunningVM.substring(0, p);

    // Make the nmethod go away
    for (int i = 0; i < 10; i++) {
        System.gc();
    }

    // Redefine class
    try {
        VirtualMachine vm = VirtualMachine.attach(pid);
        vm.loadAgent(System.getProperty("test.classes",".") + "/agent.jar", "");
        vm.detach();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    Test.m();
    // GC will hit dead method pointer
    for (int i = 0; i < 10; i++) {
        System.gc();
    }
}
 
Example 9
Source File: TransformerUtils.java    From RuntimeTransformer with MIT License 5 votes vote down vote up
static void attachAgent(File agentFile, Class<?>[] transformers) {
    try {
        String pid = ManagementFactory.getRuntimeMXBean().getName();
        VirtualMachine vm = VirtualMachine.attach(pid.substring(0, pid.indexOf('@')));
        vm.loadAgent(agentFile.getAbsolutePath());
        vm.detach();

        Agent.getInstance().process(transformers);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 10
Source File: TestLoadedAgent.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... arg) throws Exception {
    long pid = ProcessTools.getProcessId();
    VirtualMachine vm = VirtualMachine.attach(Long.toString(pid));
    vm.loadAgent("EventEmitterAgent.jar");
    vm.detach();
    EventEmitterAgent.validateRecording();
}
 
Example 11
Source File: Agent.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static public void main(String[] args) throws Exception {
    // Create speculative trap entries
    Test.m();

    String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
    int p = nameOfRunningVM.indexOf('@');
    String pid = nameOfRunningVM.substring(0, p);

    // Make the nmethod go away
    for (int i = 0; i < 10; i++) {
        System.gc();
    }

    // Redefine class
    try {
        VirtualMachine vm = VirtualMachine.attach(pid);
        vm.loadAgent(System.getProperty("test.classes",".") + "/agent.jar", "");
        vm.detach();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    Test.m();
    // GC will hit dead method pointer
    for (int i = 0; i < 10; i++) {
        System.gc();
    }
}
 
Example 12
Source File: JVMAgent.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Try to start an agent. Wait for it to attach, or throw an exception */
public static JVMAgent get() throws AgentLoadException, AgentInitializationException, IOException, AttachNotSupportedException {
    // There may be only one
    if (instance != null) {
        return instance;
    }
    
    // Not guaranteed to be correct, but seems to work.
    String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];    
    VirtualMachine jvm = VirtualMachine.attach(pid);

    // Gets the current path
    String path = JVMAgent.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    String decodedPath = URLDecoder.decode(path, "UTF-8");
    jvm.loadAgent(decodedPath, null);
    
    // Wait for the instance, time out relatively quickly
    try {
        if (!waitForInstance.await(2000, TimeUnit.MILLISECONDS)) {
            System.err.println("Unable to create JVM agent: timed out waiting for JVM agent to attach");
            return null;
        }
    } catch (InterruptedException e) {
        System.err.println("Unable to create JVM agent: interrupted waiting for JVM agent to attach");
        return null;
    }
    
    if (instance == null) {
        System.err.println("Unable to create JVM agent");
    } else {
        System.out.println("Successfully attached JVM agent");
    }
    
    // Return the instance, which might be null
    synchronized(JVMAgent.class) {
        return instance;            
    }
}
 
Example 13
Source File: SpecialAgent.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
  if (args.length != 1) {
    System.err.println("Usage: <PID>");
    System.exit(1);
  }

  final VirtualMachine vm = VirtualMachine.attach(args[0]);
  final String agentPath = SpecialAgent.class.getProtectionDomain().getCodeSource().getLocation().getPath();
  final StringBuilder inputArguments = SpecialAgentUtil.getInputArguments();
  final int logFileProperty = inputArguments.indexOf("-Dsa.log.file=");
  if (logFileProperty > 0) {
    final int start = logFileProperty + 14;
    final int end = Math.max(inputArguments.indexOf(" ", start), inputArguments.length());
    final String filePath = inputArguments.substring(start, end);
    inputArguments.replace(start, end, new File(filePath).getAbsolutePath());
  }

  if (inputArguments.length() > 0)
    inputArguments.append(' ');

  inputArguments.append("-D").append(INIT_DEFER).append("=dynamic");
  try {
    vm.loadAgent(agentPath, inputArguments.toString());
  }
  finally {
    vm.detach();
  }
}
 
Example 14
Source File: RemoteConnectorImpl.java    From scenic-view with GNU General Public License v3.0 5 votes vote down vote up
private void loadAgent(final VirtualMachine machine, final File agentFile) {
    try {
        final long start = System.currentTimeMillis();
        final int port = getValidPort();
        Logger.print("Loading agent for:" + machine + " ID:" + machine.id() + " on port:" + port + " took:" + (System.currentTimeMillis() - start) + "ms using agent defined in " + agentFile.getAbsolutePath());
        vmInfo.put(port, machine.id());
        machine.loadAgent(agentFile.getAbsolutePath(), Integer.toString(port) + ":" + this.port + ":" + machine.id() + ":" + Logger.isEnabled());
        machine.detach();
    } catch (final Exception e) {
        ExceptionLogger.submitException(e);
    }
}
 
Example 15
Source File: Agent.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static public void main(String[] args) throws Exception {
    // Create speculative trap entries
    Test.m();

    String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
    int p = nameOfRunningVM.indexOf('@');
    String pid = nameOfRunningVM.substring(0, p);

    // Make the nmethod go away
    for (int i = 0; i < 10; i++) {
        System.gc();
    }

    // Redefine class
    try {
        VirtualMachine vm = VirtualMachine.attach(pid);
        vm.loadAgent(System.getProperty("test.classes",".") + "/agent.jar", "");
        vm.detach();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    Test.m();
    // GC will hit dead method pointer
    for (int i = 0; i < 10; i++) {
        System.gc();
    }
}
 
Example 16
Source File: AgentMainTest.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, AttachNotSupportedException,
        AgentLoadException, AgentInitializationException {
    String pid = getPid();
    VirtualMachine vm = VirtualMachine.attach(pid);
    vm.loadAgent("game-classreloadagent-1.0.jar");

    System.out.println(ClassReloadAgent.isRedefineClassesSupported());
    System.out.println(ClassReloadAgent.isModifiableClass(AgentMainTest.class));
}
 
Example 17
Source File: Arthas.java    From arthas with Apache License 2.0 4 votes vote down vote up
private void attachAgent(Configure configure) throws Exception {
    VirtualMachineDescriptor virtualMachineDescriptor = null;
    for (VirtualMachineDescriptor descriptor : VirtualMachine.list()) {
        String pid = descriptor.id();
        if (pid.equals(Long.toString(configure.getJavaPid()))) {
            virtualMachineDescriptor = descriptor;
            break;
        }
    }
    VirtualMachine virtualMachine = null;
    try {
        if (null == virtualMachineDescriptor) { // 使用 attach(String pid) 这种方式
            virtualMachine = VirtualMachine.attach("" + configure.getJavaPid());
        } else {
            virtualMachine = VirtualMachine.attach(virtualMachineDescriptor);
        }

        Properties targetSystemProperties = virtualMachine.getSystemProperties();
        String targetJavaVersion = JavaVersionUtils.javaVersionStr(targetSystemProperties);
        String currentJavaVersion = JavaVersionUtils.javaVersionStr();
        if (targetJavaVersion != null && currentJavaVersion != null) {
            if (!targetJavaVersion.equals(currentJavaVersion)) {
                AnsiLog.warn("Current VM java version: {} do not match target VM java version: {}, attach may fail.",
                                currentJavaVersion, targetJavaVersion);
                AnsiLog.warn("Target VM JAVA_HOME is {}, arthas-boot JAVA_HOME is {}, try to set the same JAVA_HOME.",
                                targetSystemProperties.getProperty("java.home"), System.getProperty("java.home"));
            }
        }

        String arthasAgentPath = configure.getArthasAgent();
        //convert jar path to unicode string
        configure.setArthasAgent(encodeArg(arthasAgentPath));
        configure.setArthasCore(encodeArg(configure.getArthasCore()));
        virtualMachine.loadAgent(arthasAgentPath,
                configure.getArthasCore() + ";" + configure.toString());
    } finally {
        if (null != virtualMachine) {
            virtualMachine.detach();
        }
    }
}
 
Example 18
Source File: Attacher.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	if (args.length < 2)
	{
		logOut("Not enough arguments given. This code requires, in this order:");
		logOut("1) The PID of JVM to attach to.");
		logOut("1) The absolute location of the agent jar to be attached.");
		logOut("3) (optional) Any arguments to be passed to the java agent.");
		System.exit(1);
	}
	String vmPidArg = args[0];
	Integer.parseInt(vmPidArg); //Just to make sure it's a number.
	logOut("Will attempt to attach to JVM with pid " + vmPidArg);

	String agentPathString = args[1];

	logOut("Attach will be done using agent jar file: " + agentPathString);
	
	// This may cause a compiler error in eclipse, as it is not a java.* class
	// It can be fixed by editing the access rules for the JRE system library
	// attach to target VM
	
	//First we wait for the target VM to become available
	boolean foundTarget = false;
	while (!foundTarget) {
		List<VirtualMachineDescriptor> allVMs = VirtualMachine.list();
		for (VirtualMachineDescriptor oneVM : allVMs) {
			if (oneVM.id().equals(vmPidArg)) {
				foundTarget = true;
			}
		}
		if (!foundTarget) {
			Thread.sleep(1000);
		}
	}
	
	//Then we attach to it.
	VirtualMachine vm = VirtualMachine.attach(vmPidArg);
	
	// load agent into target VM
	try {
		if (args.length > 2) {
			vm.loadAgent(agentPathString, args[2]);
		} else {
			vm.loadAgent(agentPathString);
		}
	} catch (java.io.IOException e) {
		//This exception is thrown if the test process terminates before the agent does. 
		//We don't mind if this happens.
	}
	
	// detach
	vm.detach();
}
 
Example 19
Source File: AgentHookUtil.java    From util4j with Apache License 2.0 4 votes vote down vote up
/**
 * 指定一个../xx.jar的临时文件路径用于agent的加载
 * @param agentTmpPath String path = File.createTempFile("agent_tmp", ".jar", new   File("").getAbsoluteFile()).getPath();
 * @param deleteOndetach
 * @return
 * @throws IOException
 * @throws AttachNotSupportedException
 * @throws AgentLoadException
 * @throws AgentInitializationException
 */
public synchronized static AgentHook getAgentHook(String agentTmpPath,boolean deleteOndetach) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
    if(agentHook!=null){
        return agentHook;
    }
    File tempFile=null;
    VirtualMachine virtualMachine=null;
    FileOutputStream fos;
    try {
        InputStream resourceAsStream = AgentHookUtil.class.getClassLoader().getResourceAsStream(agentName);
        byte[] agentData=InputStreamUtils.getBytes(resourceAsStream);
        if(agentTmpPath!=null){
           try {
               tempFile=new File(agentTmpPath);
               tempFile.createNewFile();
           }catch (Exception e){
               log.error(e.getMessage(),e);
           }
        }
        if(tempFile==null){
            tempFile = File.createTempFile("agent_tmp", ".jar");
        }
        fos=new FileOutputStream(tempFile);
        fos.write(agentData);
        fos.close();
        resourceAsStream.close();
        String path=tempFile.toString();
        System.out.println("loadAgentUsePath:"+path);
        log.info("loadAgentUsePath:"+path);
        virtualMachine = VmUtil.getVirtualMachine();
        String arg=AgentHookImpl.class.getName();
        virtualMachine.loadAgent(path,arg);
        agentHook=AgentHookImpl.getInstance();
        return agentHook;
    }finally {
        if(virtualMachine!=null){
            virtualMachine.detach();
            log.info("detach agent");
        }
        if(deleteOndetach){
            if(tempFile!=null){
                tempFile.delete();
                if(tempFile.exists()){
                    tempFile.deleteOnExit();
                }
            }
        }
    }
}
 
Example 20
Source File: Agent.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
static public void main(String[] args) throws Exception {

        // loader2 must be first on the list so loader 1 must be used first
        ClassLoader loader1 = newClassLoader();
        String packageName = Agent.class.getPackage().getName();
        Class dummy = loader1.loadClass(packageName + ".Test");

        ClassLoader loader2 = newClassLoader();

        Test_class = loader2.loadClass(packageName + ".Test");
        Method m3 = Test_class.getMethod("m3", ClassLoader.class);
        // Add speculative trap in m2() (loaded by loader1) that
        // references m4() (loaded by loader2).
        m3.invoke(Test_class.newInstance(), loader1);

        String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
        int p = nameOfRunningVM.indexOf('@');
        String pid = nameOfRunningVM.substring(0, p);

        // Make the nmethod go away
        for (int i = 0; i < 10; i++) {
            System.gc();
        }

        // Redefine class Test loaded by loader2
        for (int i = 0; i < 2; i++) {
            try {
                VirtualMachine vm = VirtualMachine.attach(pid);
                vm.loadAgent(AGENT_JAR, "");
                vm.detach();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        // Will process loader2 first, find m4() is redefined and
        // needs to be freed then process loader1, check the
        // speculative trap in m2() and try to access m4() which was
        // freed already.
        for (int i = 0; i < 10; i++) {
            System.gc();
        }
    }