aboutsummaryrefslogtreecommitdiff
path: root/kamon-autoweave/src/main/java/sun/tools
diff options
context:
space:
mode:
Diffstat (limited to 'kamon-autoweave/src/main/java/sun/tools')
-rw-r--r--kamon-autoweave/src/main/java/sun/tools/attach/BsdVirtualMachine.java303
-rw-r--r--kamon-autoweave/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java289
-rw-r--r--kamon-autoweave/src/main/java/sun/tools/attach/LinuxVirtualMachine.java339
-rw-r--r--kamon-autoweave/src/main/java/sun/tools/attach/SolarisVirtualMachine.java247
-rw-r--r--kamon-autoweave/src/main/java/sun/tools/attach/WindowsVirtualMachine.java189
5 files changed, 1367 insertions, 0 deletions
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
+ }
+}