001/*
002 * Copyright 2012-2014 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.boot.loader.tools;
018
019import java.io.File;
020import java.lang.management.ManagementFactory;
021import java.lang.reflect.Method;
022import java.util.List;
023
024/**
025 * Utility class to attach an instrumentation agent to the running JVM.
026 *
027 * @author Dave Syer
028 */
029public abstract class AgentAttacher {
030
031        private static final String VIRTUAL_MACHINE_CLASS_NAME = "com.sun.tools.attach.VirtualMachine";
032
033        public static void attach(File agent) {
034                try {
035                        String name = ManagementFactory.getRuntimeMXBean().getName();
036                        String pid = name.substring(0, name.indexOf('@'));
037                        ClassLoader classLoader = JvmUtils.getToolsClassLoader();
038                        Class<?> vmClass = classLoader.loadClass(VIRTUAL_MACHINE_CLASS_NAME);
039                        Method attachMethod = vmClass.getDeclaredMethod("attach", String.class);
040                        Object vm = attachMethod.invoke(null, pid);
041                        Method loadAgentMethod = vmClass.getDeclaredMethod("loadAgent", String.class);
042                        loadAgentMethod.invoke(vm, agent.getAbsolutePath());
043                        vmClass.getDeclaredMethod("detach").invoke(vm);
044                }
045                catch (Exception ex) {
046                        throw new RuntimeException("Unable to attach agent to the JVM", ex);
047                }
048        }
049
050        public static List<String> commandLineArguments() {
051                return ManagementFactory.getRuntimeMXBean().getInputArguments();
052        }
053
054        public static boolean hasNoVerify() {
055                return commandLineArguments().contains("-Xverify:none");
056        }
057
058}