diff options
Diffstat (limited to 'kamon-autoweave/src/main')
14 files changed, 2742 insertions, 0 deletions
diff --git a/kamon-autoweave/src/main/java/com/sun/tools/attach/AgentInitializationException.java b/kamon-autoweave/src/main/java/com/sun/tools/attach/AgentInitializationException.java new file mode 100644 index 00000000..c31ab371 --- /dev/null +++ b/kamon-autoweave/src/main/java/com/sun/tools/attach/AgentInitializationException.java @@ -0,0 +1,90 @@ +/* + * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package com.sun.tools.attach; + +/** + * The exception thrown when an agent fails to initialize in the target Java virtual machine. + * <p/> + * <p> This exception is thrown by {@link + * VirtualMachine#loadAgent VirtualMachine.loadAgent}, + * {@link VirtualMachine#loadAgentLibrary + * VirtualMachine.loadAgentLibrary}, {@link + * VirtualMachine#loadAgentPath VirtualMachine.loadAgentPath} + * methods if an agent, or agent library, cannot be initialized. + * When thrown by <tt>VirtualMachine.loadAgentLibrary</tt>, or + * <tt>VirtualMachine.loadAgentPath</tt> then the exception encapsulates + * the error returned by the agent's <code>Agent_OnAttach</code> function. + * This error code can be obtained by invoking the {@link #returnValue() returnValue} method. + */ +public final class AgentInitializationException extends Exception +{ + private static final long serialVersionUID = -1508756333332806353L; + + private final int returnValue; + + /** + * Constructs an <code>AgentInitializationException</code> with + * no detail message. + */ + public AgentInitializationException() + { + returnValue = 0; + } + + /** + * Constructs an <code>AgentInitializationException</code> with the specified detail message. + * + * @param s the detail message. + */ + public AgentInitializationException(String s) + { + super(s); + returnValue = 0; + } + + /** + * Constructs an <code>AgentInitializationException</code> with + * the specified detail message and the return value from the + * execution of the agent's <code>Agent_OnAttach</code> function. + * + * @param s the detail message. + * @param returnValue the return value + */ + public AgentInitializationException(String s, int returnValue) + { + super(s); + this.returnValue = returnValue; + } + + /** + * If the exception was created with the return value from the agent + * <code>Agent_OnAttach</code> function then this returns that value, + * otherwise returns <code>0</code>. </p> + */ + public int returnValue() + { + return returnValue; + } +} diff --git a/kamon-autoweave/src/main/java/com/sun/tools/attach/AgentLoadException.java b/kamon-autoweave/src/main/java/com/sun/tools/attach/AgentLoadException.java new file mode 100644 index 00000000..816255a5 --- /dev/null +++ b/kamon-autoweave/src/main/java/com/sun/tools/attach/AgentLoadException.java @@ -0,0 +1,55 @@ +/* + * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package com.sun.tools.attach; + +/** + * The exception thrown when an agent cannot be loaded into the target Java virtual machine. + * <p/> + * <p> This exception is thrown by {@link + * VirtualMachine#loadAgent VirtualMachine.loadAgent} or + * {@link VirtualMachine#loadAgentLibrary + * VirtualMachine.loadAgentLibrary}, {@link VirtualMachine#loadAgentPath loadAgentPath} methods + * if the agent, or agent library, cannot be loaded. + */ +public final class AgentLoadException extends Exception +{ + private static final long serialVersionUID = 688047862952114238L; + + /** + * Constructs an <code>AgentLoadException</code> with + * no detail message. + */ + public AgentLoadException() + { + } + + /** + * Constructs an <code>AgentLoadException</code> with the specified detail message. + */ + public AgentLoadException(String s) + { + super(s); + } +} diff --git a/kamon-autoweave/src/main/java/com/sun/tools/attach/AttachNotSupportedException.java b/kamon-autoweave/src/main/java/com/sun/tools/attach/AttachNotSupportedException.java new file mode 100644 index 00000000..7b59e6e2 --- /dev/null +++ b/kamon-autoweave/src/main/java/com/sun/tools/attach/AttachNotSupportedException.java @@ -0,0 +1,56 @@ +/* + * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package com.sun.tools.attach; + +/** + * Thrown by {@link VirtualMachine#attach VirtalMachine.attach} when attempting to attach to a Java + * virtual machine for which a compatible {@link com.sun.tools.attach.spi.AttachProvider + * AttachProvider} does not exist. It is also thrown by {@link + * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine + * AttachProvider.attachVirtualMachine} if the provider attempts to + * attach to a Java virtual machine with which it not compatible. + */ +public final class AttachNotSupportedException extends Exception +{ + private static final long serialVersionUID = 3391824968260177264L; + + /** + * Constructs an <code>AttachNotSupportedException</code> with no detail message. + */ + public AttachNotSupportedException() + { + } + + /** + * Constructs an <code>AttachNotSupportedException</code> with + * the specified detail message. + * + * @param s the detail message. + */ + public AttachNotSupportedException(String s) + { + super(s); + } +} diff --git a/kamon-autoweave/src/main/java/com/sun/tools/attach/VirtualMachine.java b/kamon-autoweave/src/main/java/com/sun/tools/attach/VirtualMachine.java new file mode 100644 index 00000000..e1f010f8 --- /dev/null +++ b/kamon-autoweave/src/main/java/com/sun/tools/attach/VirtualMachine.java @@ -0,0 +1,527 @@ +/* + * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package com.sun.tools.attach; + +import com.sun.tools.attach.spi.AttachProvider; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +/** + * A Java virtual machine. + * <p/> + * <p> A <code>VirtualMachine</code> represents a Java virtual machine to which this + * Java virtual machine has attached. The Java virtual machine to which it is + * attached is sometimes called the <i>target virtual machine</i>, or <i>target VM</i>. + * An application (typically a tool such as a managemet console or profiler) uses a + * VirtualMachine to load an agent into the target VM. For example, a profiler tool + * written in the Java Language might attach to a running application and load its + * profiler agent to profile the running application. </p> + * <p/> + * <p> A VirtualMachine is obtained by invoking the {@link #attach(String) attach} method + * with an identifier that identifies the target virtual machine. The identifier is + * implementation-dependent but is typically the process identifier (or pid) in + * environments where each Java virtual machine runs in its own operating system process. + * Alternatively, a <code>VirtualMachine</code> instance is obtained by invoking the + * {@link #attach(VirtualMachineDescriptor) attach} method with a {@link + * com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor} obtained + * from the list of virtual machine descriptors returned by the {@link #list list} method. + * Once a reference to a virtual machine is obtained, the {@link #loadAgent loadAgent}, + * {@link #loadAgentLibrary loadAgentLibrary}, and {@link #loadAgentPath loadAgentPath} + * methods are used to load agents into target virtual machine. The {@link + * #loadAgent loadAgent} method is used to load agents that are written in the Java + * Language and deployed in a {@link java.util.jar.JarFile JAR file}. (See + * {@link java.lang.instrument} for a detailed description on how these agents + * are loaded and started). The {@link #loadAgentLibrary loadAgentLibrary} and + * {@link #loadAgentPath loadAgentPath} methods are used to load agents that + * are deployed in a dynamic library and make use of the <a + * href="../../../../../../../../technotes/guides/jvmti/index.html">JVM Tools + * Interface</a>. </p> + * <p/> + * <p> In addition to loading agents a VirtualMachine provides read access to the + * {@link java.lang.System#getProperties() system properties} in the target VM. + * This can be useful in some environments where properties such as + * <code>java.home</code>, <code>os.name</code>, or <code>os.arch</code> are + * used to construct the path to agent that will be loaded into the target VM. + * <p/> + * <p> The following example demonstrates how VirtualMachine may be used:</p> + * <p/> + * <pre> + * <p/> + * // attach to target VM + * VirtualMachine vm = VirtualMachine.attach("2177"); + * <p/> + * // get system properties in target VM + * Properties props = vm.getSystemProperties(); + * <p/> + * // construct path to management agent + * String home = props.getProperty("java.home"); + * String agent = home + File.separator + "lib" + File.separator + * + "management-agent.jar"; + * <p/> + * // load agent into target VM + * vm.loadAgent(agent, "com.sun.management.jmxremote.port=5000"); + * <p/> + * // detach + * vm.detach(); + * <p/> + * </pre> + * <p/> + * <p> In this example we attach to a Java virtual machine that is identified by + * the process identifier <code>2177</code>. The system properties from the target + * VM are then used to construct the path to a <i>management agent</i> which is then + * loaded into the target VM. Once loaded the client detaches from the target VM. </p> + * <p/> + * <p> A VirtualMachine is safe for use by multiple concurrent threads. </p> + * + * @since 1.6 + */ +public abstract class VirtualMachine +{ + private final AttachProvider provider; + private final String id; + private volatile int hash; // 0 => not computed + + /** + * Initializes a new instance of this class. + * + * @param provider The attach provider creating this class. + * @param id The abstract identifier that identifies the Java virtual machine. + */ + protected VirtualMachine(AttachProvider provider, String id) + { + this.provider = provider; + this.id = id; + } + + /** + * Return a list of Java virtual machines. + * <p/> + * This method returns a list of Java {@link com.sun.tools.attach.VirtualMachineDescriptor} + * elements. The list is an aggregation of the virtual machine descriptor lists obtained by + * invoking the {@link com.sun.tools.attach.spi.AttachProvider#listVirtualMachines + * listVirtualMachines} method of all installed {@link com.sun.tools.attach.spi.AttachProvider + * attach providers}. If there are no Java virtual machines known to any provider then an empty + * list is returned. + * + * @return The list of virtual machine descriptors. + */ + public static List<VirtualMachineDescriptor> list() + { + List<VirtualMachineDescriptor> l = new ArrayList<VirtualMachineDescriptor>(); + List<AttachProvider> providers = AttachProvider.providers(); + + for (AttachProvider provider : providers) { + l.addAll(provider.listVirtualMachines()); + } + + return l; + } + + /** + * Attaches to a Java virtual machine. + * <p/> + * This method obtains the list of attach providers by invoking the + * {@link com.sun.tools.attach.spi.AttachProvider#providers() AttachProvider.providers()} method. + * It then iterates overs the list and invokes each provider's {@link + * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(java.lang.String) + * attachVirtualMachine} method in turn. If a provider successfully + * attaches then the iteration terminates, and the VirtualMachine created + * by the provider that successfully attached is returned by this method. + * If the <code>attachVirtualMachine</code> method of all providers throws + * {@link com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException} + * then this method also throws <code>AttachNotSupportedException</code>. + * This means that <code>AttachNotSupportedException</code> is thrown when + * the identifier provided to this method is invalid, or the identifier + * corresponds to a Java virtual machine that does not exist, or none + * of the providers can attach to it. This exception is also thrown if + * {@link com.sun.tools.attach.spi.AttachProvider#providers() + * AttachProvider.providers()} returns an empty list. </p> + * + * @param id The abstract identifier that identifies the Java virtual machine. + * @return A VirtualMachine representing the target VM. + * @throws SecurityException If a security manager has been installed and it denies + * {@link com.sun.tools.attach.AttachPermission AttachPermission} + * <tt>("attachVirtualMachine")</tt>, or another permission + * required by the implementation. + * @throws IOException If an I/O error occurs + */ + public static VirtualMachine attach(String id) throws AttachNotSupportedException, IOException + { + List<AttachProvider> providers = AttachProvider.providers(); + AttachNotSupportedException lastExc = null; + + for (AttachProvider provider : providers) { + try { + return provider.attachVirtualMachine(id); + } + catch (AttachNotSupportedException x) { + lastExc = x; + } + } + + throw lastExc; + } + + /** + * Attaches to a Java virtual machine. + * <p/> + * This method first invokes the {@link com.sun.tools.attach.VirtualMachineDescriptor#provider() + * provider()} method of the given virtual machine descriptor to obtain the attach provider. + * It then invokes the attach provider's {@link + * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(VirtualMachineDescriptor) + * attachVirtualMachine} to attach to the target VM. + * + * @param vmd The virtual machine descriptor. + * + * @return A VirtualMachine representing the target VM. + * + * @throws SecurityException + * If a security manager has been installed and it denies + * {@link com.sun.tools.attach.AttachPermission AttachPermission} + * <tt>("attachVirtualMachine")</tt>, or another permission + * required by the implementation. + * + * @throws AttachNotSupportedException + * If the attach provider's <code>attachVirtualmachine</code> + * throws <code>AttachNotSupportedException</code>. + * + * @throws IOException If an I/O error occurs + * + * @throws NullPointerException If <code>vmd</code> is <code>null</code>. + */ + public static VirtualMachine attach(VirtualMachineDescriptor vmd) + throws AttachNotSupportedException, IOException + { + return vmd.provider().attachVirtualMachine(vmd); + } + + /** + * Detach from the virtual machine. + * <p/> + * After detaching from the virtual machine, any further attempt to invoke + * operations on that virtual machine will cause an {@link java.io.IOException + * IOException} to be thrown. If an operation (such as {@link #loadAgent + * loadAgent} for example) is in progress when this method is invoked then + * the behaviour is implementation dependent. In other words, it is + * implementation specific if the operation completes or throws <tt>IOException</tt>. + * <p/> + * If already detached from the virtual machine then invoking this method has no effect. + * + * @throws IOException If an I/O error occurs + */ + public abstract void detach() throws IOException; + + /** + * Returns the provider that created this virtual machine. + */ + public final AttachProvider provider() + { + return provider; + } + + /** + * Returns the identifier for this Java virtual machine. + */ + public final String id() + { + return id; + } + + /** + * Loads an agent library. + * <p/> + * A <a href="../../../../../../../../technotes/guides/jvmti/index.html">JVM + * TI</a> client is called an <i>agent</i>. It is developed in a native language. + * A JVM TI agent is deployed in a platform specific manner but it is typically the + * platform equivalent of a dynamic library. This method causes the given agent + * library to be loaded into the target VM (if not already loaded). + * It then causes the target VM to invoke the <code>Agent_OnAttach</code> function + * as specified in the + * <a href="../../../../../../../../technotes/guides/jvmti/index.html"> JVM Tools + * Interface</a> specification. Note that the <code>Agent_OnAttach</code> + * function is invoked even if the agent library was loaded prior to invoking + * this method. + * <p/> + * The agent library provided is the name of the agent library. It is interpreted + * in the target virtual machine in an implementation-dependent manner. Typically an + * implementation will expand the library name into an operating system specific file + * name. For example, on UNIX systems, the name <tt>foo</tt> might be expanded to + * <tt>libfoo.so</tt>, and located using the search path specified by the + * <tt>LD_LIBRARY_PATH</tt> environment variable. + * <p/> + * If the <code>Agent_OnAttach</code> function in the agent library returns + * an error then an {@link com.sun.tools.attach.AgentInitializationException} is + * thrown. The return value from the <code>Agent_OnAttach</code> can then be + * obtained by invoking the {@link + * com.sun.tools.attach.AgentInitializationException#returnValue() returnValue} + * method on the exception. + * + * @param agentLibrary The name of the agent library. + * @param options The options to provide to the <code>Agent_OnAttach</code> + * function (can be <code>null</code>). + * @throws AgentLoadException If the agent library does not exist, or cannot be loaded for + * another reason. + * @throws AgentInitializationException If the <code>Agent_OnAttach</code> function returns an error + * @throws IOException If an I/O error occurs + * @throws NullPointerException If <code>agentLibrary</code> is <code>null</code>. + * @see com.sun.tools.attach.AgentInitializationException#returnValue() + */ + public abstract void loadAgentLibrary(String agentLibrary, String options) + throws AgentLoadException, AgentInitializationException, IOException; + + /** + * Loads an agent library. + * <p/> + * This convenience method works as if by invoking: + * <p/> + * <blockquote><tt> + * {@link #loadAgentLibrary(String, String) loadAgentLibrary}(agentLibrary, null); + * </tt></blockquote> + * + * @param agentLibrary The name of the agent library. + * @throws AgentLoadException If the agent library does not exist, or cannot be loaded for + * another reason. + * @throws AgentInitializationException If the <code>Agent_OnAttach</code> function returns an error + * @throws IOException If an I/O error occurs + * @throws NullPointerException If <code>agentLibrary</code> is <code>null</code>. + */ + public void loadAgentLibrary(String agentLibrary) + throws AgentLoadException, AgentInitializationException, IOException + { + loadAgentLibrary(agentLibrary, null); + } + + /** + * Load a native agent library by full pathname. + * <p/> + * A <a href="../../../../../../../../technotes/guides/jvmti/index.html">JVM TI</a> client is + * called an <i>agent</i>. It is developed in a native language. + * A JVM TI agent is deployed in a platform specific manner but it is typically the + * platform equivalent of a dynamic library. This method causes the given agent + * library to be loaded into the target VM (if not already loaded). + * It then causes the target VM to invoke the <code>Agent_OnAttach</code> function + * as specified in the + * <a href="../../../../../../../../technotes/guides/jvmti/index.html"> JVM Tools + * Interface</a> specification. Note that the <code>Agent_OnAttach</code> + * function is invoked even if the agent library was loaded prior to invoking + * this method. + * <p/> + * The agent library provided is the absolute path from which to load the + * agent library. Unlike {@link #loadAgentLibrary loadAgentLibrary}, the library name + * is not expanded in the target virtual machine. + * <p/> + * If the <code>Agent_OnAttach</code> function in the agent library returns + * an error then an {@link com.sun.tools.attach.AgentInitializationException} is + * thrown. The return value from the <code>Agent_OnAttach</code> can then be + * obtained by invoking the {@link + * com.sun.tools.attach.AgentInitializationException#returnValue() returnValue} + * method on the exception. + * + * @param agentPath The full path of the agent library. + * @param options The options to provide to the <code>Agent_OnAttach</code> + * function (can be <code>null</code>). + * @throws AgentLoadException If the agent library does not exist, or cannot be loaded for + * another reason. + * @throws AgentInitializationException If the <code>Agent_OnAttach</code> function returns an error + * @throws IOException If an I/O error occurs + * @throws NullPointerException If <code>agentPath</code> is <code>null</code>. + * @see com.sun.tools.attach.AgentInitializationException#returnValue() + */ + public abstract void loadAgentPath(String agentPath, String options) + throws AgentLoadException, AgentInitializationException, IOException; + + /** + * Load a native agent library by full pathname. + * <p/> + * This convenience method works as if by invoking: + * <p/> + * <blockquote><tt> + * {@link #loadAgentPath(String, String) loadAgentPath}(agentLibrary, null); + * </tt></blockquote> + * + * @param agentPath The full path to the agent library. + * @throws AgentLoadException If the agent library does not exist, or cannot be loaded for + * another reason. + * @throws AgentInitializationException If the <code>Agent_OnAttach</code> function returns an error + * @throws IOException If an I/O error occurs + * @throws NullPointerException If <code>agentPath</code> is <code>null</code>. + */ + public void loadAgentPath(String agentPath) + throws AgentLoadException, AgentInitializationException, IOException + { + loadAgentPath(agentPath, null); + } + + + /** + * Loads an agent. + * <p/> + * <p> The agent provided to this method is a path name to a JAR file on the file + * system of the target virtual machine. This path is passed to the target virtual + * machine where it is interpreted. The target virtual machine attempts to start + * the agent as specified by the {@link java.lang.instrument} specification. + * That is, the specified JAR file is added to the system class path (of the target + * virtual machine), and the <code>agentmain</code> method of the agent class, specified + * by the <code>Agent-Class</code> attribute in the JAR manifest, is invoked. This + * method completes when the <code>agentmain</code> method completes. + * + * @param agent Path to the JAR file containing the agent. + * @param options The options to provide to the agent's <code>agentmain</code> + * method (can be <code>null</code>). + * @throws AgentLoadException If the agent does not exist, or cannot be started in the manner + * specified in the {@link java.lang.instrument} specification. + * @throws AgentInitializationException If the <code>agentmain</code> throws an exception + * @throws IOException If an I/O error occurs + * @throws NullPointerException If <code>agent</code> is <code>null</code>. + */ + public abstract void loadAgent(String agent, String options) + throws AgentLoadException, AgentInitializationException, IOException; + + /** + * Loads an agent. + * <p/> + * This convenience method works as if by invoking: + * <p/> + * <blockquote><tt> + * {@link #loadAgent(String, String) loadAgent}(agent, null); + * </tt></blockquote> + * + * @param agent Path to the JAR file containing the agent. + * @throws AgentLoadException If the agent does not exist, or cannot be started in the manner + * specified in the {@link java.lang.instrument} specification. + * @throws AgentInitializationException If the <code>agentmain</code> throws an exception + * @throws IOException If an I/O error occurs + * @throws NullPointerException If <code>agent</code> is <code>null</code>. + */ + public void loadAgent(String agent) + throws AgentLoadException, AgentInitializationException, IOException + { + loadAgent(agent, null); + } + + /** + * Returns the current system properties in the target virtual machine. + * <p/> + * This method returns the system properties in the target virtual + * machine. Properties whose key or value is not a <tt>String</tt> are + * omitted. The method is approximately equivalent to the invocation of the + * method {@link java.lang.System#getProperties System.getProperties} + * in the target virtual machine except that properties with a key or + * value that is not a <tt>String</tt> are not included. + * <p/> + * This method is typically used to decide which agent to load into + * the target virtual machine with {@link #loadAgent loadAgent}, or + * {@link #loadAgentLibrary loadAgentLibrary}. For example, the + * <code>java.home</code> or <code>user.dir</code> properties might be + * use to create the path to the agent library or JAR file. + * + * @return The system properties + * @throws IOException If an I/O error occurs + * @see java.lang.System#getProperties + * @see #loadAgentLibrary + * @see #loadAgent + */ + public abstract Properties getSystemProperties() throws IOException; + + /** + * Returns the current <i>agent properties</i> in the target virtual + * machine. + * <p/> + * The target virtual machine can maintain a list of properties on + * behalf of agents. The manner in which this is done, the names of the + * properties, and the types of values that are allowed, is implementation + * specific. Agent properties are typically used to store communication + * end-points and other agent configuration details. For example, a debugger + * agent might create an agent property for its transport address. + * <p/> + * This method returns the agent properties whose key and value is a + * <tt>String</tt>. Properties whose key or value is not a <tt>String</tt> + * are omitted. If there are no agent properties maintained in the target + * virtual machine then an empty property list is returned. + * + * @return The agent properties + * @throws IOException If an I/O error occurs + */ + public abstract Properties getAgentProperties() throws IOException; + + /** + * Returns a hash-code value for this VirtualMachine. The hash + * code is based upon the VirtualMachine's components, and satisfies + * the general contract of the Object.hashCode method. + * + * @return A hash-code value for this virtual machine + */ + public int hashCode() + { + if (hash != 0) { + return hash; + } + + hash = provider.hashCode() * 127 + id.hashCode(); + return hash; + } + + /** + * Tests this VirtualMachine for equality with another object. + * <p/> + * <p> If the given object is not a VirtualMachine then this + * method returns <tt>false</tt>. For two VirtualMachines to + * be considered equal requires that they both reference the same + * provider, and their {@link VirtualMachineDescriptor#id() identifiers} are equal. </p> + * <p/> + * <p> This method satisfies the general contract of the {@link + * java.lang.Object#equals(Object) Object.equals} method. </p> + * + * @param ob The object to which this object is to be compared + * @return <tt>true</tt> if, and only if, the given object is + * a VirtualMachine that is equal to this + * VirtualMachine. + */ + public boolean equals(Object ob) + { + if (ob == this) { + return true; + } + + if (!(ob instanceof VirtualMachine)) { + return false; + } + + VirtualMachine other = (VirtualMachine) ob; + + return other.provider() == provider() && other.id().equals(id()); + } + + /** + * Returns the string representation of the <code>VirtualMachine</code>. + */ + public String toString() + { + return provider.toString() + ": " + id; + } +} diff --git a/kamon-autoweave/src/main/java/com/sun/tools/attach/VirtualMachineDescriptor.java b/kamon-autoweave/src/main/java/com/sun/tools/attach/VirtualMachineDescriptor.java new file mode 100644 index 00000000..6459e806 --- /dev/null +++ b/kamon-autoweave/src/main/java/com/sun/tools/attach/VirtualMachineDescriptor.java @@ -0,0 +1,208 @@ +/* + * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package com.sun.tools.attach; + +import com.sun.tools.attach.spi.AttachProvider; + +/** + * Describes a Java virtual machine. + * <p/> + * <p> A <code>VirtualMachineDescriptor</code> is a container class used to + * describe a Java virtual machine. It encapsulates an identifier that identifies + * a target virtual machine, and a reference to the {@link + * com.sun.tools.attach.spi.AttachProvider AttachProvider} that should be used + * when attempting to attach to the virtual machine. The identifier is + * implementation-dependent but is typically the process identifier (or pid) + * environments where each Java virtual machine runs in its own operating system + * process. </p> + * <p/> + * <p> A <code>VirtualMachineDescriptor</code> also has a {@link #displayName() displayName}. + * The display name is typically a human readable string that a tool might + * display to a user. For example, a tool that shows a list of Java + * virtual machines running on a system might use the display name rather + * than the identifier. A <code>VirtualMachineDescriptor</code> may be + * created without a <i>display name</i>. In that case the identifier is + * used as the <i>display name</i>. + * <p/> + * <p> <code>VirtualMachineDescriptor</code> instances are typically created by + * invoking the {@link VirtualMachine#list VirtualMachine.list()} + * method. This returns the complete list of descriptors to describe the + * Java virtual machines known to all installed {@link + * com.sun.tools.attach.spi.AttachProvider attach providers}. + * + * @since 1.6 + */ +public final class VirtualMachineDescriptor +{ + private AttachProvider provider; + private String id; + private String displayName; + + private volatile int hash; // 0 => not computed + + /** + * Creates a virtual machine descriptor from the given components. + * + * @param provider The AttachProvider to attach to the Java virtual machine. + * @param id The virtual machine identifier. + * @param displayName The display name. + * @throws NullPointerException If any of the arguments are <code>null</code> + */ + public VirtualMachineDescriptor(AttachProvider provider, String id, String displayName) + { + if (provider == null) { + throw new NullPointerException("provider cannot be null"); + } + + if (id == null) { + throw new NullPointerException("identifier cannot be null"); + } + + if (displayName == null) { + throw new NullPointerException("display name cannot be null"); + } + + this.provider = provider; + this.id = id; + this.displayName = displayName; + } + + /** + * Creates a virtual machine descriptor from the given components. + * <p/> + * <p> This convenience constructor works as if by invoking the + * three-argument constructor as follows: + * <p/> + * <blockquote><tt> + * new {@link #VirtualMachineDescriptor(com.sun.tools.attach.spi.AttachProvider, String, String) + * VirtualMachineDescriptor}(provider, id, id); + * </tt></blockquote> + * <p/> + * <p> That is, it creates a virtual machine descriptor such that + * the <i>display name</i> is the same as the virtual machine + * identifier. + * + * @param provider The AttachProvider to attach to the Java virtual machine. + * @param id The virtual machine identifier. + * @throws NullPointerException If <tt>provider</tt> or <tt>id</tt> is <tt>null</tt>. + */ + public VirtualMachineDescriptor(AttachProvider provider, String id) + { + this(provider, id, id); + } + + /** + * Return the <code>AttachProvider</code> that this descriptor references. + * + * @return The <code>AttachProvider</code> that this descriptor references. + */ + public AttachProvider provider() + { + return provider; + } + + /** + * Return the identifier component of this descriptor. + * + * @return The identifier component of this descriptor. + */ + public String id() + { + return id; + } + + /** + * Return the <i>display name</i> component of this descriptor. + * + * @return The display name component of this descriptor. + */ + public String displayName() + { + return displayName; + } + + /** + * Returns a hash-code value for this VirtualMachineDescriptor. The hash + * code is based upon the descriptor's components, and satisfies + * the general contract of the Object.hashCode method. + * + * @return A hash-code value for this descriptor. + */ + public int hashCode() + { + if (hash != 0) { + return hash; + } + + hash = provider.hashCode() * 127 + id.hashCode(); + return hash; + } + + /** + * Tests this VirtualMachineDescriptor for equality with another object. + * <p/> + * <p> If the given object is not a VirtualMachineDescriptor then this + * method returns <tt>false</tt>. For two VirtualMachineDescriptors to + * be considered equal requires that they both reference the same + * provider, and their {@link #id() identifiers} are equal. </p> + * <p/> + * <p> This method satisfies the general contract of the {@link + * Object#equals(Object) Object.equals} method. </p> + * + * @param ob The object to which this object is to be compared + * @return <tt>true</tt> if, and only if, the given object is + * a VirtualMachineDescriptor that is equal to this + * VirtualMachineDescriptor. + */ + public boolean equals(Object ob) + { + if (ob == this) + return true; + if (!(ob instanceof VirtualMachineDescriptor)) + return false; + VirtualMachineDescriptor other = (VirtualMachineDescriptor) ob; + if (other.provider() != this.provider()) { + return false; + } + if (!other.id().equals(this.id())) { + return false; + } + return true; + } + + /** + * Returns the string representation of the <code>VirtualMachineDescriptor</code>. + */ + public String toString() + { + String s = provider.toString() + ": " + id; + + if (displayName != id) { + s += " " + displayName; + } + + return s; + } +} diff --git a/kamon-autoweave/src/main/java/com/sun/tools/attach/spi/AttachProvider.java b/kamon-autoweave/src/main/java/com/sun/tools/attach/spi/AttachProvider.java new file mode 100644 index 00000000..98e8084d --- /dev/null +++ b/kamon-autoweave/src/main/java/com/sun/tools/attach/spi/AttachProvider.java @@ -0,0 +1,240 @@ +/*
+ * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+package com.sun.tools.attach.spi;
+
+import com.sun.tools.attach.AttachNotSupportedException;
+import com.sun.tools.attach.VirtualMachine;
+import com.sun.tools.attach.VirtualMachineDescriptor;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.ServiceLoader;
+
+/**
+ * Attach provider class for attaching to a Java virtual machine.
+ * <p/>
+ * <p> An attach provider is a concrete subclass of this class that has a
+ * zero-argument constructor and implements the abstract methods specified
+ * below. </p>
+ * <p/>
+ * <p> An attach provider implementation is typically tied to a Java virtual
+ * machine implementation, version, or even mode of operation. That is, a specific
+ * provider implementation will typically only be capable of attaching to
+ * a specific Java virtual machine implementation or version. For example, Sun's
+ * JDK implementation ships with provider implementations that can only attach to
+ * Sun's <i>HotSpot</i> virtual machine. In general, if an environment
+ * consists of Java virtual machines of different versions and from different
+ * vendors then there will be an attach provider implementation for each
+ * <i>family</i> of implementations or versions. </p>
+ * <p/>
+ * <p> An attach provider is identified by its {@link #name <i>name</i>} and
+ * {@link #type <i>type</i>}. The <i>name</i> is typically, but not required to
+ * be, a name that corresponds to the VM vendor. The Sun JDK implementation,
+ * for example, ships with attach providers that use the name <i>"sun"</i>. The
+ * <i>type</i> typically corresponds to the attach mechanism. For example, an
+ * implementation that uses the Doors inter-process communication mechanism
+ * might use the type <i>"doors"</i>. The purpose of the name and type is to
+ * identify providers in environments where there are multiple providers
+ * installed. </p>
+ * <p/>
+ * <p> AttachProvider implementations are loaded and instantiated at the first
+ * invocation of the {@link #providers() providers} method. This method
+ * attempts to load all provider implementations that are installed on the
+ * platform. </p>
+ * <p/>
+ * <p> All of the methods in this class are safe for use by multiple
+ * concurrent threads. </p>
+ *
+ * @since 1.6
+ */
+public abstract class AttachProvider
+{
+ private static final Object lock = new Object();
+ private static List<AttachProvider> providers;
+
+ /**
+ * Initializes a new instance of this class.
+ */
+ protected AttachProvider() {}
+
+ /**
+ * Return this provider's name.
+ *
+ * @return The name of this provider
+ */
+ public abstract String name();
+
+ /**
+ * Return this provider's type.
+ *
+ * @return The type of this provider
+ */
+ public abstract String type();
+
+ /**
+ * Attaches to a Java virtual machine.
+ * <p/>
+ * <p> A Java virtual machine is identified by an abstract identifier. The
+ * nature of this identifier is platform dependent but in many cases it will be the
+ * string representation of the process identifier (or pid). </p>
+ * <p/>
+ * <p> This method parses the identifier and maps the identifier to a Java
+ * virtual machine (in an implementation dependent manner). If the identifier
+ * cannot be parsed by the provider then an {@link
+ * com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException}
+ * is thrown. Once parsed this method attempts to attach to the Java virtual machine.
+ * If the provider detects that the identifier corresponds to a Java virtual machine
+ * that does not exist, or it corresponds to a Java virtual machine that does not support
+ * the attach mechanism implemented by this provider, or it detects that the
+ * Java virtual machine is a version to which this provider cannot attach, then
+ * an <code>AttachNotSupportedException</code> is thrown. </p>
+ *
+ * @param id The abstract identifier that identifies the Java virtual machine.
+ * @return VirtualMachine representing the target virtual machine.
+ * @throws SecurityException If a security manager has been installed and it denies
+ * {@link com.sun.tools.attach.AttachPermission AttachPermission}
+ * <tt>("attachVirtualMachine")</tt>, or other permission
+ * required by the implementation.
+ * @throws AttachNotSupportedException If the identifier cannot be parsed, or it corresponds to
+ * to a Java virtual machine that does not exist, or it
+ * corresponds to a Java virtual machine which this
+ * provider cannot attach.
+ * @throws IOException If some other I/O error occurs
+ * @throws NullPointerException If <code>id</code> is <code>null</code>
+ */
+ public abstract VirtualMachine attachVirtualMachine(String id)
+ throws AttachNotSupportedException, IOException;
+
+ /**
+ * Attaches to a Java virtual machine.
+ * <p/>
+ * A Java virtual machine can be described using a {@link
+ * com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor}.
+ * This method invokes the descriptor's {@link
+ * com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method
+ * to check that it is equal to this provider. It then attempts to attach to the
+ * Java virtual machine.
+ *
+ * @param vmd The virtual machine descriptor
+ * @return VirtualMachine representing the target virtual machine.
+ * @throws SecurityException If a security manager has been installed and it denies
+ * {@link com.sun.tools.attach.AttachPermission AttachPermission}
+ * <tt>("attachVirtualMachine")</tt>, or other permission
+ * required by the implementation.
+ * @throws AttachNotSupportedException If the descriptor's {@link
+ * com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method
+ * returns a provider that is not this provider, or it does not correspond
+ * to a Java virtual machine to which this provider can attach.
+ * @throws IOException If some other I/O error occurs
+ * @throws NullPointerException If <code>vmd</code> is <code>null</code>
+ */
+ public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
+ throws AttachNotSupportedException, IOException
+ {
+ if (vmd.provider() != this) {
+ throw new AttachNotSupportedException("provider mismatch");
+ }
+
+ return attachVirtualMachine(vmd.id());
+ }
+
+ /**
+ * Lists the Java virtual machines known to this provider.
+ * <p/>
+ * This method returns a list of {@link com.sun.tools.attach.VirtualMachineDescriptor} elements.
+ * Each <code>VirtualMachineDescriptor</code> describes a Java virtual machine
+ * to which this provider can <i>potentially</i> attach. There isn't any
+ * guarantee that invoking {@link #attachVirtualMachine(VirtualMachineDescriptor)
+ * attachVirtualMachine} on each descriptor in the list will succeed.
+ *
+ * @return The list of virtual machine descriptors which describe the
+ * Java virtual machines known to this provider (may be empty).
+ */
+ public abstract List<VirtualMachineDescriptor> listVirtualMachines();
+
+ /**
+ * Returns a list of the installed attach providers.
+ * <p/>
+ * <p> An AttachProvider is installed on the platform if:
+ * <p/>
+ * <ul>
+ * <li><p>It is installed in a JAR file that is visible to the defining
+ * class loader of the AttachProvider type (usually, but not required
+ * to be, the {@link java.lang.ClassLoader#getSystemClassLoader system
+ * class loader}).</p></li>
+ * <p/>
+ * <li><p>The JAR file contains a provider configuration named
+ * <tt>com.sun.tools.attach.spi.AttachProvider</tt> in the resource directory
+ * <tt>META-INF/services</tt>. </p></li>
+ * <p/>
+ * <li><p>The provider configuration file lists the full-qualified class
+ * name of the AttachProvider implementation. </p></li>
+ * </ul>
+ * <p/>
+ * <p> The format of the provider configuration file is one fully-qualified
+ * class name per line. Space and tab characters surrounding each class name,
+ * as well as blank lines are ignored. The comment character is
+ * <tt>'#'</tt> (<tt>0x23</tt>), and on each line all characters following
+ * the first comment character are ignored. The file must be encoded in
+ * UTF-8. </p>
+ * <p/>
+ * <p> AttachProvider implementations are loaded and instantiated
+ * (using the zero-arg constructor) at the first invocation of this method.
+ * The list returned by the first invocation of this method is the list
+ * of providers. Subsequent invocations of this method return a list of the same
+ * providers. The list is unmodifable.</p>
+ *
+ * @return A list of the installed attach providers.
+ */
+ @SuppressWarnings({"Since15"})
+ public static List<AttachProvider> providers()
+ {
+ synchronized (lock) {
+ if (providers == null) {
+ providers = new ArrayList<AttachProvider>();
+
+ ServiceLoader<AttachProvider> providerLoader =
+ ServiceLoader.load(AttachProvider.class, AttachProvider.class.getClassLoader());
+
+ for (AttachProvider aProviderLoader : providerLoader) {
+ try {
+ providers.add(aProviderLoader);
+ }
+ catch (ThreadDeath td) {
+ throw td;
+ }
+ catch (Throwable t) {
+ // Ignore errors and exceptions.
+ System.err.println(t);
+ }
+ }
+ }
+
+ return Collections.unmodifiableList(providers);
+ }
+ }
+}
diff --git a/kamon-autoweave/src/main/java/sun/tools/attach/BsdVirtualMachine.java b/kamon-autoweave/src/main/java/sun/tools/attach/BsdVirtualMachine.java new file mode 100644 index 00000000..1f134de6 --- /dev/null +++ b/kamon-autoweave/src/main/java/sun/tools/attach/BsdVirtualMachine.java @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package sun.tools.attach; + +import com.sun.tools.attach.VirtualMachine; +import com.sun.tools.attach.AgentLoadException; +import com.sun.tools.attach.AttachNotSupportedException; +import com.sun.tools.attach.spi.AttachProvider; +import java.io.InputStream; +import java.io.IOException; +import java.io.File; +import java.util.Properties; + +/* + * Bsd implementation of HotSpotVirtualMachine + */ +public class BsdVirtualMachine extends HotSpotVirtualMachine { + // "tmpdir" is used as a global well-known location for the files + // .java_pid<pid>. and .attach_pid<pid>. It is important that this + // location is the same for all processes, otherwise the tools + // will not be able to find all Hotspot processes. + // This is intentionally not the same as java.io.tmpdir, since + // the latter can be changed by the user. + // Any changes to this needs to be synchronized with HotSpot. + private static final String tmpdir; + + // The patch to the socket file created by the target VM + String path; + + /** + * Attaches to the target VM + */ + public BsdVirtualMachine(AttachProvider provider, String vmid) + throws AttachNotSupportedException, IOException + { + super(provider, vmid); + + // This provider only understands pids + int pid; + try { + pid = Integer.parseInt(vmid); + } catch (NumberFormatException x) { + throw new AttachNotSupportedException("Invalid process identifier"); + } + + // Find the socket file. If not found then we attempt to start the + // attach mechanism in the target VM by sending it a QUIT signal. + // Then we attempt to find the socket file again. + path = findSocketFile(pid); + if (path == null) { + File f = new File(tmpdir, ".attach_pid" + pid); + createAttachFile(f.getPath()); + try { + sendQuitTo(pid); + + // give the target VM time to start the attach mechanism + int i = 0; + long delay = 200; + int retries = (int)(attachTimeout() / delay); + do { + try { + Thread.sleep(delay); + } catch (InterruptedException x) { } + path = findSocketFile(pid); + i++; + } while (i <= retries && path == null); + if (path == null) { + throw new AttachNotSupportedException( + "Unable to open socket file: target process not responding " + + "or HotSpot VM not loaded"); + } + } finally { + f.delete(); + } + } + + // Check that the file owner/permission to avoid attaching to + // bogus process + checkPermissions(path); + + // Check that we can connect to the process + // - this ensures we throw the permission denied error now rather than + // later when we attempt to enqueue a command. + int s = socket(); + try { + connect(s, path); + } finally { + close(s); + } + } + + /** + * Detach from the target VM + */ + public void detach() throws IOException { + synchronized (this) { + if (this.path != null) { + this.path = null; + } + } + } + + // protocol version + private final static String PROTOCOL_VERSION = "1"; + + // known errors + private final static int ATTACH_ERROR_BADVERSION = 101; + + /** + * Execute the given command in the target VM. + */ + InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException { + assert args.length <= 3; // includes null + + // did we detach? + String p; + synchronized (this) { + if (this.path == null) { + throw new IOException("Detached from target VM"); + } + p = this.path; + } + + // create UNIX socket + int s = socket(); + + // connect to target VM + try { + connect(s, p); + } catch (IOException x) { + close(s); + throw x; + } + + IOException ioe = null; + + // connected - write request + // <ver> <cmd> <args...> + try { + writeString(s, PROTOCOL_VERSION); + writeString(s, cmd); + + for (int i=0; i<3; i++) { + if (i < args.length && args[i] != null) { + writeString(s, (String)args[i]); + } else { + writeString(s, ""); + } + } + } catch (IOException x) { + ioe = x; + } + + + // Create an input stream to read reply + SocketInputStream sis = new SocketInputStream(s); + + // Read the command completion status + int completionStatus; + try { + completionStatus = readInt(sis); + } catch (IOException x) { + sis.close(); + if (ioe != null) { + throw ioe; + } else { + throw x; + } + } + + if (completionStatus != 0) { + sis.close(); + + // In the event of a protocol mismatch then the target VM + // returns a known error so that we can throw a reasonable + // error. + if (completionStatus == ATTACH_ERROR_BADVERSION) { + throw new IOException("Protocol mismatch with target VM"); + } + + // Special-case the "load" command so that the right exception is + // thrown. + if (cmd.equals("load")) { + throw new AgentLoadException("Failed to load agent library"); + } else { + throw new IOException("Command failed in target VM"); + } + } + + // Return the input stream so that the command output can be read + return sis; + } + + /* + * InputStream for the socket connection to get target VM + */ + private class SocketInputStream extends InputStream { + int s; + + public SocketInputStream(int s) { + this.s = s; + } + + public synchronized int read() throws IOException { + byte b[] = new byte[1]; + int n = this.read(b, 0, 1); + if (n == 1) { + return b[0] & 0xff; + } else { + return -1; + } + } + + public synchronized int read(byte[] bs, int off, int len) throws IOException { + if ((off < 0) || (off > bs.length) || (len < 0) || + ((off + len) > bs.length) || ((off + len) < 0)) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) + return 0; + + return BsdVirtualMachine.read(s, bs, off, len); + } + + public void close() throws IOException { + BsdVirtualMachine.close(s); + } + } + + // Return the socket file for the given process. + // Checks temp directory for .java_pid<pid>. + private String findSocketFile(int pid) { + String fn = ".java_pid" + pid; + File f = new File(tmpdir, fn); + return f.exists() ? f.getPath() : null; + } + + /* + * Write/sends the given to the target VM. String is transmitted in + * UTF-8 encoding. + */ + private void writeString(int fd, String s) throws IOException { + if (s.length() > 0) { + byte b[]; + try { + b = s.getBytes("UTF-8"); + } catch (java.io.UnsupportedEncodingException x) { + throw new InternalError(); + } + BsdVirtualMachine.write(fd, b, 0, b.length); + } + byte b[] = new byte[1]; + b[0] = 0; + write(fd, b, 0, 1); + } + + + //-- native methods + + static native void sendQuitTo(int pid) throws IOException; + + static native void checkPermissions(String path) throws IOException; + + static native int socket() throws IOException; + + static native void connect(int fd, String path) throws IOException; + + static native void close(int fd) throws IOException; + + static native int read(int fd, byte buf[], int off, int bufLen) throws IOException; + + static native void write(int fd, byte buf[], int off, int bufLen) throws IOException; + + static native void createAttachFile(String path); + + static native String getTempDir(); + + static { + System.loadLibrary("attach"); + tmpdir = getTempDir(); + } +} diff --git a/kamon-autoweave/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java b/kamon-autoweave/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java new file mode 100644 index 00000000..0bc04b04 --- /dev/null +++ b/kamon-autoweave/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.tools.attach; + +import com.sun.tools.attach.VirtualMachine; +import com.sun.tools.attach.AgentLoadException; +import com.sun.tools.attach.AgentInitializationException; +import com.sun.tools.attach.spi.AttachProvider; + +import java.io.InputStream; +import java.io.IOException; +import java.util.Properties; +import java.util.Map; + +/* + * The HotSpot implementation of com.sun.tools.attach.VirtualMachine. + */ + +public abstract class HotSpotVirtualMachine extends VirtualMachine { + + HotSpotVirtualMachine(AttachProvider provider, String id) { + super(provider, id); + } + + /* + * Load agent library + * If isAbsolute is true then the agent library is the absolute path + * to the library and thus will not be expanded in the target VM. + * if isAbsolute is false then the agent library is just a library + * name and it will be expended in the target VM. + */ + private void loadAgentLibrary(String agentLibrary, boolean isAbsolute, String options) + throws AgentLoadException, AgentInitializationException, IOException + { + InputStream in = execute("load", + agentLibrary, + isAbsolute ? "true" : "false", + options); + try { + int result = readInt(in); + if (result != 0) { + throw new AgentInitializationException("Agent_OnAttach failed", result); + } + } finally { + in.close(); + + } + } + + /* + * Load agent library - library name will be expanded in target VM + */ + public void loadAgentLibrary(String agentLibrary, String options) + throws AgentLoadException, AgentInitializationException, IOException + { + loadAgentLibrary(agentLibrary, false, options); + } + + /* + * Load agent - absolute path of library provided to target VM + */ + public void loadAgentPath(String agentLibrary, String options) + throws AgentLoadException, AgentInitializationException, IOException + { + loadAgentLibrary(agentLibrary, true, options); + } + + /* + * Load JPLIS agent which will load the agent JAR file and invoke + * the agentmain method. + */ + public void loadAgent(String agent, String options) + throws AgentLoadException, AgentInitializationException, IOException + { + String args = agent; + if (options != null) { + args = args + "=" + options; + } + try { + loadAgentLibrary("instrument", args); + } catch (AgentLoadException x) { + throw new InternalError("instrument library is missing in target VM"); + } catch (AgentInitializationException x) { + /* + * Translate interesting errors into the right exception and + * message (FIXME: create a better interface to the instrument + * implementation so this isn't necessary) + */ + int rc = x.returnValue(); + switch (rc) { + case JNI_ENOMEM: + throw new AgentLoadException("Insuffient memory"); + case ATTACH_ERROR_BADJAR: + throw new AgentLoadException("Agent JAR not found or no Agent-Class attribute"); + case ATTACH_ERROR_NOTONCP: + throw new AgentLoadException("Unable to add JAR file to system class path"); + case ATTACH_ERROR_STARTFAIL: + throw new AgentInitializationException("Agent JAR loaded but agent failed to initialize"); + default : + throw new AgentLoadException("Failed to load agent - unknown reason: " + rc); + } + } + } + + /* + * The possible errors returned by JPLIS's agentmain + */ + private static final int JNI_ENOMEM = -4; + private static final int ATTACH_ERROR_BADJAR = 100; + private static final int ATTACH_ERROR_NOTONCP = 101; + private static final int ATTACH_ERROR_STARTFAIL = 102; + + + /* + * Send "properties" command to target VM + */ + public Properties getSystemProperties() throws IOException { + InputStream in = null; + Properties props = new Properties(); + try { + in = executeCommand("properties"); + props.load(in); + } finally { + if (in != null) in.close(); + } + return props; + } + + public Properties getAgentProperties() throws IOException { + InputStream in = null; + Properties props = new Properties(); + try { + in = executeCommand("agentProperties"); + props.load(in); + } finally { + if (in != null) in.close(); + } + return props; + } + + // --- HotSpot specific methods --- + + // same as SIGQUIT + public void localDataDump() throws IOException { + executeCommand("datadump").close(); + } + + // Remote ctrl-break. The output of the ctrl-break actions can + // be read from the input stream. + public InputStream remoteDataDump(Object ... args) throws IOException { + return executeCommand("threaddump", args); + } + + // Remote heap dump. The output (error message) can be read from the + // returned input stream. + public InputStream dumpHeap(Object ... args) throws IOException { + return executeCommand("dumpheap", args); + } + + // Heap histogram (heap inspection in HotSpot) + public InputStream heapHisto(Object ... args) throws IOException { + return executeCommand("inspectheap", args); + } + + // set JVM command line flag + public InputStream setFlag(String name, String value) throws IOException { + return executeCommand("setflag", name, value); + } + + // print command line flag + public InputStream printFlag(String name) throws IOException { + return executeCommand("printflag", name); + } + + public InputStream executeJCmd(String command) throws IOException { + return executeCommand("jcmd", command); + } + + // -- Supporting methods + + + /* + * Execute the given command in the target VM - specific platform + * implementation must implement this. + */ + abstract InputStream execute(String cmd, Object ... args) + throws AgentLoadException, IOException; + + /* + * Convenience method for simple commands + */ + private InputStream executeCommand(String cmd, Object ... args) throws IOException { + try { + return execute(cmd, args); + } catch (AgentLoadException x) { + throw new InternalError("Should not get here"); + } + } + + + /* + * Utility method to read an 'int' from the input stream. Ideally + * we should be using java.util.Scanner here but this implementation + * guarantees not to read ahead. + */ + int readInt(InputStream in) throws IOException { + StringBuilder sb = new StringBuilder(); + + // read to \n or EOF + int n; + byte buf[] = new byte[1]; + do { + n = in.read(buf, 0, 1); + if (n > 0) { + char c = (char)buf[0]; + if (c == '\n') { + break; // EOL found + } else { + sb.append(c); + } + } + } while (n > 0); + + if (sb.length() == 0) { + throw new IOException("Premature EOF"); + } + + int value; + try { + value = Integer.parseInt(sb.toString()); + } catch (NumberFormatException x) { + throw new IOException("Non-numeric value found - int expected"); + } + return value; + } + + // -- attach timeout support + + private static long defaultAttachTimeout = 5000; + private volatile long attachTimeout; + + /* + * Return attach timeout based on the value of the sun.tools.attach.attachTimeout + * property, or the default timeout if the property is not set to a positive + * value. + */ + long attachTimeout() { + if (attachTimeout == 0) { + synchronized(this) { + if (attachTimeout == 0) { + try { + String s = + System.getProperty("sun.tools.attach.attachTimeout"); + attachTimeout = Long.parseLong(s); + } catch (SecurityException se) { + } catch (NumberFormatException ne) { + } + if (attachTimeout <= 0) { + attachTimeout = defaultAttachTimeout; + } + } + } + } + return attachTimeout; + } +} diff --git a/kamon-autoweave/src/main/java/sun/tools/attach/LinuxVirtualMachine.java b/kamon-autoweave/src/main/java/sun/tools/attach/LinuxVirtualMachine.java new file mode 100644 index 00000000..97298ee1 --- /dev/null +++ b/kamon-autoweave/src/main/java/sun/tools/attach/LinuxVirtualMachine.java @@ -0,0 +1,339 @@ +/* + * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package sun.tools.attach; + +import com.sun.tools.attach.VirtualMachine; +import com.sun.tools.attach.AgentLoadException; +import com.sun.tools.attach.AttachNotSupportedException; +import com.sun.tools.attach.spi.AttachProvider; +import java.io.InputStream; +import java.io.IOException; +import java.io.File; +import java.util.Properties; + +/* + * Linux implementation of HotSpotVirtualMachine + */ +public class LinuxVirtualMachine extends HotSpotVirtualMachine { + // "/tmp" is used as a global well-known location for the files + // .java_pid<pid>. and .attach_pid<pid>. It is important that this + // location is the same for all processes, otherwise the tools + // will not be able to find all Hotspot processes. + // Any changes to this needs to be synchronized with HotSpot. + private static final String tmpdir = "/tmp"; + + // Indicates if this machine uses the old LinuxThreads + static boolean isLinuxThreads; + + // The patch to the socket file created by the target VM + String path; + + /** + * Attaches to the target VM + */ + public LinuxVirtualMachine(AttachProvider provider, String vmid) + throws AttachNotSupportedException, IOException + { + super(provider, vmid); + + // This provider only understands pids + int pid; + try { + pid = Integer.parseInt(vmid); + } catch (NumberFormatException x) { + throw new AttachNotSupportedException("Invalid process identifier"); + } + + // Find the socket file. If not found then we attempt to start the + // attach mechanism in the target VM by sending it a QUIT signal. + // Then we attempt to find the socket file again. + path = findSocketFile(pid); + if (path == null) { + File f = createAttachFile(pid); + try { + // On LinuxThreads each thread is a process and we don't have the + // pid of the VMThread which has SIGQUIT unblocked. To workaround + // this we get the pid of the "manager thread" that is created + // by the first call to pthread_create. This is parent of all + // threads (except the initial thread). + if (isLinuxThreads) { + int mpid; + try { + mpid = getLinuxThreadsManager(pid); + } catch (IOException x) { + throw new AttachNotSupportedException(x.getMessage()); + } + assert(mpid >= 1); + sendQuitToChildrenOf(mpid); + } else { + sendQuitTo(pid); + } + + // give the target VM time to start the attach mechanism + int i = 0; + long delay = 200; + int retries = (int)(attachTimeout() / delay); + do { + try { + Thread.sleep(delay); + } catch (InterruptedException x) { } + path = findSocketFile(pid); + i++; + } while (i <= retries && path == null); + if (path == null) { + throw new AttachNotSupportedException( + "Unable to open socket file: target process not responding " + + "or HotSpot VM not loaded"); + } + } finally { + f.delete(); + } + } + + // Check that the file owner/permission to avoid attaching to + // bogus process + checkPermissions(path); + + // Check that we can connect to the process + // - this ensures we throw the permission denied error now rather than + // later when we attempt to enqueue a command. + int s = socket(); + try { + connect(s, path); + } finally { + close(s); + } + } + + /** + * Detach from the target VM + */ + public void detach() throws IOException { + synchronized (this) { + if (this.path != null) { + this.path = null; + } + } + } + + // protocol version + private final static String PROTOCOL_VERSION = "1"; + + // known errors + private final static int ATTACH_ERROR_BADVERSION = 101; + + /** + * Execute the given command in the target VM. + */ + InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException { + assert args.length <= 3; // includes null + + // did we detach? + String p; + synchronized (this) { + if (this.path == null) { + throw new IOException("Detached from target VM"); + } + p = this.path; + } + + // create UNIX socket + int s = socket(); + + // connect to target VM + try { + connect(s, p); + } catch (IOException x) { + close(s); + throw x; + } + + IOException ioe = null; + + // connected - write request + // <ver> <cmd> <args...> + try { + writeString(s, PROTOCOL_VERSION); + writeString(s, cmd); + + for (int i=0; i<3; i++) { + if (i < args.length && args[i] != null) { + writeString(s, (String)args[i]); + } else { + writeString(s, ""); + } + } + } catch (IOException x) { + ioe = x; + } + + + // Create an input stream to read reply + SocketInputStream sis = new SocketInputStream(s); + + // Read the command completion status + int completionStatus; + try { + completionStatus = readInt(sis); + } catch (IOException x) { + sis.close(); + if (ioe != null) { + throw ioe; + } else { + throw x; + } + } + + if (completionStatus != 0) { + sis.close(); + + // In the event of a protocol mismatch then the target VM + // returns a known error so that we can throw a reasonable + // error. + if (completionStatus == ATTACH_ERROR_BADVERSION) { + throw new IOException("Protocol mismatch with target VM"); + } + + // Special-case the "load" command so that the right exception is + // thrown. + if (cmd.equals("load")) { + throw new AgentLoadException("Failed to load agent library"); + } else { + throw new IOException("Command failed in target VM"); + } + } + + // Return the input stream so that the command output can be read + return sis; + } + + /* + * InputStream for the socket connection to get target VM + */ + private class SocketInputStream extends InputStream { + int s; + + public SocketInputStream(int s) { + this.s = s; + } + + public synchronized int read() throws IOException { + byte b[] = new byte[1]; + int n = this.read(b, 0, 1); + if (n == 1) { + return b[0] & 0xff; + } else { + return -1; + } + } + + public synchronized int read(byte[] bs, int off, int len) throws IOException { + if ((off < 0) || (off > bs.length) || (len < 0) || + ((off + len) > bs.length) || ((off + len) < 0)) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) + return 0; + + return LinuxVirtualMachine.read(s, bs, off, len); + } + + public void close() throws IOException { + LinuxVirtualMachine.close(s); + } + } + + // Return the socket file for the given process. + private String findSocketFile(int pid) { + File f = new File(tmpdir, ".java_pid" + pid); + if (!f.exists()) { + return null; + } + return f.getPath(); + } + + // On Solaris/Linux a simple handshake is used to start the attach mechanism + // if not already started. The client creates a .attach_pid<pid> file in the + // target VM's working directory (or temp directory), and the SIGQUIT handler + // checks for the file. + private File createAttachFile(int pid) throws IOException { + String fn = ".attach_pid" + pid; + String path = "/proc/" + pid + "/cwd/" + fn; + File f = new File(path); + try { + f.createNewFile(); + } catch (IOException x) { + f = new File(tmpdir, fn); + f.createNewFile(); + } + return f; + } + + /* + * Write/sends the given to the target VM. String is transmitted in + * UTF-8 encoding. + */ + private void writeString(int fd, String s) throws IOException { + if (s.length() > 0) { + byte b[]; + try { + b = s.getBytes("UTF-8"); + } catch (java.io.UnsupportedEncodingException x) { + throw new InternalError(); + } + LinuxVirtualMachine.write(fd, b, 0, b.length); + } + byte b[] = new byte[1]; + b[0] = 0; + write(fd, b, 0, 1); + } + + + //-- native methods + + static native boolean isLinuxThreads(); + + static native int getLinuxThreadsManager(int pid) throws IOException; + + static native void sendQuitToChildrenOf(int pid) throws IOException; + + static native void sendQuitTo(int pid) throws IOException; + + static native void checkPermissions(String path) throws IOException; + + static native int socket() throws IOException; + + static native void connect(int fd, String path) throws IOException; + + static native void close(int fd) throws IOException; + + static native int read(int fd, byte buf[], int off, int bufLen) throws IOException; + + static native void write(int fd, byte buf[], int off, int bufLen) throws IOException; + + static { + System.loadLibrary("attach"); + isLinuxThreads = isLinuxThreads(); + } +} diff --git a/kamon-autoweave/src/main/java/sun/tools/attach/SolarisVirtualMachine.java b/kamon-autoweave/src/main/java/sun/tools/attach/SolarisVirtualMachine.java new file mode 100644 index 00000000..388c89c4 --- /dev/null +++ b/kamon-autoweave/src/main/java/sun/tools/attach/SolarisVirtualMachine.java @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package sun.tools.attach; + +import com.sun.tools.attach.VirtualMachine; +import com.sun.tools.attach.AgentLoadException; +import com.sun.tools.attach.AttachNotSupportedException; +import com.sun.tools.attach.spi.AttachProvider; +import java.io.InputStream; +import java.io.IOException; +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Properties; + +/* + * Solaris implementation of HotSpotVirtualMachine. + */ +public class SolarisVirtualMachine extends HotSpotVirtualMachine { + // "/tmp" is used as a global well-known location for the files + // .java_pid<pid>. and .attach_pid<pid>. It is important that this + // location is the same for all processes, otherwise the tools + // will not be able to find all Hotspot processes. + // Any changes to this needs to be synchronized with HotSpot. + private static final String tmpdir = "/tmp"; + + // door descriptor; + private int fd = -1; + + /** + * Attaches to the target VM + */ + public SolarisVirtualMachine(AttachProvider provider, String vmid) + throws AttachNotSupportedException, IOException + { + super(provider, vmid); + // This provider only understands process-ids (pids). + int pid; + try { + pid = Integer.parseInt(vmid); + } catch (NumberFormatException x) { + throw new AttachNotSupportedException("invalid process identifier"); + } + + // Opens the door file to the target VM. If the file is not + // found it might mean that the attach mechanism isn't started in the + // target VM so we attempt to start it and retry. + try { + fd = openDoor(pid); + } catch (FileNotFoundException fnf1) { + File f = createAttachFile(pid); + try { + // kill -QUIT will tickle target VM to check for the + // attach file. + sigquit(pid); + + // give the target VM time to start the attach mechanism + int i = 0; + long delay = 200; + int retries = (int)(attachTimeout() / delay); + do { + try { + Thread.sleep(delay); + } catch (InterruptedException x) { } + try { + fd = openDoor(pid); + } catch (FileNotFoundException fnf2) { } + i++; + } while (i <= retries && fd == -1); + if (fd == -1) { + throw new AttachNotSupportedException( + "Unable to open door: target process not responding or " + + "HotSpot VM not loaded"); + } + } finally { + f.delete(); + } + } + assert fd >= 0; + } + + /** + * Detach from the target VM + */ + public void detach() throws IOException { + synchronized (this) { + if (fd != -1) { + close(fd); + fd = -1; + } + } + } + + /** + * Execute the given command in the target VM. + */ + InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException { + assert args.length <= 3; // includes null + + // first check that we are still attached + int door; + synchronized (this) { + if (fd == -1) { + throw new IOException("Detached from target VM"); + } + door = fd; + } + + // enqueue the command via a door call + int s = enqueue(door, cmd, args); + assert s >= 0; // valid file descriptor + + // The door call returns a file descriptor (one end of a socket pair). + // Create an input stream around it. + SocketInputStream sis = new SocketInputStream(s); + + // Read the command completion status + int completionStatus; + try { + completionStatus = readInt(sis); + } catch (IOException ioe) { + sis.close(); + throw ioe; + } + + // If non-0 it means an error but we need to special-case the + // "load" command to ensure that the right exception is thrown. + if (completionStatus != 0) { + sis.close(); + if (cmd.equals("load")) { + throw new AgentLoadException("Failed to load agent library"); + } else { + throw new IOException("Command failed in target VM"); + } + } + + // Return the input stream so that the command output can be read + return sis; + } + + // InputStream over a socket + private class SocketInputStream extends InputStream { + int s; + + public SocketInputStream(int s) { + this.s = s; + } + + public synchronized int read() throws IOException { + byte b[] = new byte[1]; + int n = this.read(b, 0, 1); + if (n == 1) { + return b[0] & 0xff; + } else { + return -1; + } + } + + public synchronized int read(byte[] bs, int off, int len) throws IOException { + if ((off < 0) || (off > bs.length) || (len < 0) || + ((off + len) > bs.length) || ((off + len) < 0)) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) + return 0; + + return SolarisVirtualMachine.read(s, bs, off, len); + } + + public void close() throws IOException { + SolarisVirtualMachine.close(s); + } + } + + // The door is attached to .java_pid<pid> in the temporary directory. + private int openDoor(int pid) throws IOException { + String path = tmpdir + "/.java_pid" + pid;; + fd = open(path); + + // Check that the file owner/permission to avoid attaching to + // bogus process + try { + checkPermissions(path); + } catch (IOException ioe) { + close(fd); + throw ioe; + } + return fd; + } + + // On Solaris/Linux a simple handshake is used to start the attach mechanism + // if not already started. The client creates a .attach_pid<pid> file in the + // target VM's working directory (or temporary directory), and the SIGQUIT + // handler checks for the file. + private File createAttachFile(int pid) throws IOException { + String fn = ".attach_pid" + pid; + String path = "/proc/" + pid + "/cwd/" + fn; + File f = new File(path); + try { + f.createNewFile(); + } catch (IOException x) { + f = new File(tmpdir, fn); + f.createNewFile(); + } + return f; + } + + //-- native methods + + static native int open(String path) throws IOException; + + static native void close(int fd) throws IOException; + + static native int read(int fd, byte buf[], int off, int buflen) throws IOException; + + static native void checkPermissions(String path) throws IOException; + + static native void sigquit(int pid) throws IOException; + + // enqueue a command (and arguments) to the given door + static native int enqueue(int fd, String cmd, Object ... args) + throws IOException; + + static { + System.loadLibrary("attach"); + } +} diff --git a/kamon-autoweave/src/main/java/sun/tools/attach/WindowsVirtualMachine.java b/kamon-autoweave/src/main/java/sun/tools/attach/WindowsVirtualMachine.java new file mode 100644 index 00000000..260d02b7 --- /dev/null +++ b/kamon-autoweave/src/main/java/sun/tools/attach/WindowsVirtualMachine.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package sun.tools.attach; + +import com.sun.tools.attach.VirtualMachine; +import com.sun.tools.attach.AgentLoadException; +import com.sun.tools.attach.AttachNotSupportedException; +import com.sun.tools.attach.spi.AttachProvider; +import sun.tools.attach.HotSpotVirtualMachine; +import java.io.IOException; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +import java.util.Random; + +public class WindowsVirtualMachine extends HotSpotVirtualMachine { + + // the enqueue code stub (copied into each target VM) + private static byte[] stub; + + private volatile long hProcess; // handle to the process + + public WindowsVirtualMachine(AttachProvider provider, String id) + throws AttachNotSupportedException, IOException + { + super(provider, id); + + int pid; + try { + pid = Integer.parseInt(id); + } catch (NumberFormatException x) { + throw new AttachNotSupportedException("Invalid process identifier"); + } + hProcess = openProcess(pid); + + // The target VM might be a pre-6.0 VM so we enqueue a "null" command + // which minimally tests that the enqueue function exists in the target + // VM. + try { + enqueue(hProcess, stub, null, null); + } catch (IOException x) { + throw new AttachNotSupportedException(x.getMessage()); + } + } + + public void detach() throws IOException { + synchronized (this) { + if (hProcess != -1) { + closeProcess(hProcess); + hProcess = -1; + } + } + } + + InputStream execute(String cmd, Object ... args) + throws AgentLoadException, IOException + { + assert args.length <= 3; // includes null + + // create a pipe using a random name + int r = (new Random()).nextInt(); + String pipename = "\\\\.\\pipe\\javatool" + r; + long hPipe = createPipe(pipename); + + // check if we are detached - in theory it's possible that detach is invoked + // after this check but before we enqueue the command. + if (hProcess == -1) { + closePipe(hPipe); + throw new IOException("Detached from target VM"); + } + + try { + // enqueue the command to the process + enqueue(hProcess, stub, cmd, pipename, args); + + // wait for command to complete - process will connect with the + // completion status + connectPipe(hPipe); + + // create an input stream for the pipe + PipedInputStream is = new PipedInputStream(hPipe); + + // read completion status + int status = readInt(is); + if (status != 0) { + // special case the load command so that the right exception is thrown + if (cmd.equals("load")) { + throw new AgentLoadException("Failed to load agent library"); + } else { + throw new IOException("Command failed in target VM"); + } + } + + // return the input stream + return is; + + } catch (IOException ioe) { + closePipe(hPipe); + throw ioe; + } + } + + // An InputStream based on a pipe to the target VM + private class PipedInputStream extends InputStream { + + private long hPipe; + + public PipedInputStream(long hPipe) { + this.hPipe = hPipe; + } + + public synchronized int read() throws IOException { + byte b[] = new byte[1]; + int n = this.read(b, 0, 1); + if (n == 1) { + return b[0] & 0xff; + } else { + return -1; + } + } + + public synchronized int read(byte[] bs, int off, int len) throws IOException { + if ((off < 0) || (off > bs.length) || (len < 0) || + ((off + len) > bs.length) || ((off + len) < 0)) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) + return 0; + + return WindowsVirtualMachine.readPipe(hPipe, bs, off, len); + } + + public void close() throws IOException { + if (hPipe != -1) { + WindowsVirtualMachine.closePipe(hPipe); + hPipe = -1; + } + } + } + + + //-- native methods + + static native void init(); + + static native byte[] generateStub(); + + static native long openProcess(int pid) throws IOException; + + static native void closeProcess(long hProcess) throws IOException; + + static native long createPipe(String name) throws IOException; + + static native void closePipe(long hPipe) throws IOException; + + static native void connectPipe(long hPipe) throws IOException; + + static native int readPipe(long hPipe, byte buf[], int off, int buflen) throws IOException; + + static native void enqueue(long hProcess, byte[] stub, + String cmd, String pipename, Object ... args) throws IOException; + + static { + System.loadLibrary("attach"); + init(); // native initialization + stub = generateStub(); // generate stub to copy into target process + } +} diff --git a/kamon-autoweave/src/main/resources/reference.conf b/kamon-autoweave/src/main/resources/reference.conf new file mode 100644 index 00000000..c47b1a5d --- /dev/null +++ b/kamon-autoweave/src/main/resources/reference.conf @@ -0,0 +1,12 @@ +# ====================================== # +# Kamon-Autowave Reference Configuration # +# ====================================== # + +kamon { + autowave { + options { + verbose = false + showWeaveInfo = false + } + } +}
\ No newline at end of file diff --git a/kamon-autoweave/src/main/scala/kamon/autoweave/Autoweave.scala b/kamon-autoweave/src/main/scala/kamon/autoweave/Autoweave.scala new file mode 100644 index 00000000..29c4254a --- /dev/null +++ b/kamon-autoweave/src/main/scala/kamon/autoweave/Autoweave.scala @@ -0,0 +1,32 @@ +/* ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + * ========================================================================================= + */ + +package kamon.autoweave + +import kamon.Kamon +import kamon.autoweave.loader.AgentLoader +import org.aspectj.weaver.loadtime.Agent + + +object Autoweave { + val config = Kamon.config.getConfig("kamon.autowave.options") + val verbose = config.getBoolean("verbose") + val showWeaveInfo = config.getBoolean("showWeaveInfo") + + System.setProperty("aj.weaving.verbose", verbose.toString) + System.setProperty("org.aspectj.weaver.showWeaveInfo", showWeaveInfo.toString) + + AgentLoader.attachAgentToJVM(classOf[Agent]) + } diff --git a/kamon-autoweave/src/main/scala/kamon/autoweave/loader/AgentLoader.scala b/kamon-autoweave/src/main/scala/kamon/autoweave/loader/AgentLoader.scala new file mode 100644 index 00000000..d4efdb85 --- /dev/null +++ b/kamon-autoweave/src/main/scala/kamon/autoweave/loader/AgentLoader.scala @@ -0,0 +1,155 @@ +/* ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + * ========================================================================================= + */ + +package kamon.autoweave.loader + +import java.io.{File, FileOutputStream, InputStream} +import java.lang.management.ManagementFactory +import java.util +import java.util.jar.Attributes.Name +import java.util.jar.{JarEntry, JarOutputStream, Manifest} + +import com.sun.tools.attach.spi.AttachProvider +import com.sun.tools.attach.{VirtualMachine, VirtualMachineDescriptor} +import sun.tools.attach._ + +import scala.util.control.NoStackTrace +import scala.util.{Failure, Success, Try} + +object AgentLoader { + + /** + * Gets the current JVM PID + * + * @return Returns the PID + */ + + private def getPidFromRuntimeMBean: String = { + val jvm = ManagementFactory.getRuntimeMXBean.getName + val pid = jvm.substring(0, jvm.indexOf('@')) + pid + } + + /** + * Loads an agent into a JVM. + * + * @param agent The main agent class. + * @param resources Array of classes to be included with agent. + */ + def attachAgentToJVM(agent: Class[_], resources: Seq[Class[_]] = Seq.empty): Unit = { + val vm = attachToRunningJVM() + vm.loadAgent(generateAgentJar(agent, resources).getAbsolutePath) + vm.detach() + } + + /** + * Java variant + * + * @param agent + */ + def attachAgentToJVM(agent: Class[_]): Unit = attachAgentToJVM(agent, Seq.empty) + + /** + * Generates a temporary agent file to be loaded. + * + * @param agent The main agent class. + * @param resources Array of classes to be included with agent. + * @return Returns a temporary jar file with the specified classes included. + */ + private def generateAgentJar(agent: Class[_], resources: Seq[Class[_]]): File = { + val jarFile = File.createTempFile("agent", ".jar") + jarFile.deleteOnExit() + + val manifest = new Manifest() + val mainAttributes = manifest.getMainAttributes + // Create manifest stating that agent is allowed to transform classes + mainAttributes.put(Name.MANIFEST_VERSION, "1.0") + mainAttributes.put(new Name("Agent-Class"), agent.getName) + mainAttributes.put(new Name("Can-Retransform-Classes"), "true") + mainAttributes.put(new Name("Can-Redefine-Classes"), "true") + + val jos = new JarOutputStream(new FileOutputStream(jarFile), manifest) + + jos.putNextEntry(new JarEntry(agent.getName.replace('.', '/') + ".class")) + + jos.write(getBytesFromStream(agent.getClassLoader.getResourceAsStream(unqualify(agent)))) + jos.closeEntry() + + for (clazz ← resources) { + val name = unqualify(clazz) + jos.putNextEntry(new JarEntry(name)) + jos.write(getBytesFromStream(clazz.getClassLoader.getResourceAsStream(name))) + jos.closeEntry() + } + + jos.close() + jarFile + } + + /** + * Gets bytes from InputStream. + * + * @param stream + * The InputStream. + * @return + * Returns a byte[] representation of given stream. + */ + private def getBytesFromStream(stream: InputStream): Array[Byte] = { + Stream.continually(stream.read).takeWhile(_ != -1).map(_.toByte).toArray + } + + private def unqualify(clazz: Class[_]): String = clazz.getName.replace('.', '/') + ".class" + + /** + * Gets the current HotSpotVirtualMachine implementation otherwise a failure. + * + * @return + * Returns the HotSpotVirtualMachine implementation of the running JVM. + */ + private def findVirtualMachineImplementation(): Try[Class[_ <: HotSpotVirtualMachine]] = System.getProperty("os.name") match { + case os if os.startsWith("Windows") => Success(classOf[WindowsVirtualMachine]) + case os if os.startsWith("Mac OS X") => Success(classOf[BsdVirtualMachine]) + case os if os.startsWith("Solaris") => Success(classOf[SolarisVirtualMachine]) + case os if os.startsWith("Linux") || os.startsWith("LINUX") => Success(classOf[LinuxVirtualMachine]) + case other => Failure(new RuntimeException(s"Cannot use Attach API on unknown OS: $other") with NoStackTrace) + } + + /** + * Attach to the running JVM. + * + * @return + * Returns the attached VirtualMachine + */ + private def attachToRunningJVM(): VirtualMachine = { + val AttachProvider = new AttachProvider() { + override def name(): String = null + override def `type`(): String = null + override def attachVirtualMachine(id: String): VirtualMachine = null + override def listVirtualMachines(): util.List[VirtualMachineDescriptor] = null + } + + findVirtualMachineImplementation() match { + case Success(vmClass) => + val pid = getPidFromRuntimeMBean + // This is only done with Reflection to avoid the JVM pre-loading all the XyzVirtualMachine classes. + val vmConstructor = vmClass.getConstructor(classOf[AttachProvider], classOf[String]) + val newVM = vmConstructor.newInstance(AttachProvider, pid) + newVM.asInstanceOf[VirtualMachine] + case Failure(reason) => throw reason + } + } +} + + |