Path: blob/master/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java
40948 views
/*1* Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package sun.tools.attach;2526import com.sun.tools.attach.AttachOperationFailedException;27import com.sun.tools.attach.AgentLoadException;28import com.sun.tools.attach.AttachNotSupportedException;29import com.sun.tools.attach.spi.AttachProvider;3031import java.io.InputStream;32import java.io.IOException;33import java.io.File;34import java.nio.charset.StandardCharsets;35import java.nio.file.Path;36import java.nio.file.Paths;37import java.nio.file.Files;3839/*40* Linux implementation of HotSpotVirtualMachine41*/42public class VirtualMachineImpl extends HotSpotVirtualMachine {43// "/tmp" is used as a global well-known location for the files44// .java_pid<pid>. and .attach_pid<pid>. It is important that this45// location is the same for all processes, otherwise the tools46// will not be able to find all Hotspot processes.47// Any changes to this needs to be synchronized with HotSpot.48private static final String tmpdir = "/tmp";49String socket_path;50/**51* Attaches to the target VM52*/53VirtualMachineImpl(AttachProvider provider, String vmid)54throws AttachNotSupportedException, IOException55{56super(provider, vmid);5758// This provider only understands pids59int pid;60try {61pid = Integer.parseInt(vmid);62if (pid < 1) {63throw new NumberFormatException();64}65} catch (NumberFormatException x) {66throw new AttachNotSupportedException("Invalid process identifier: " + vmid);67}6869// Try to resolve to the "inner most" pid namespace70int ns_pid = getNamespacePid(pid);7172// Find the socket file. If not found then we attempt to start the73// attach mechanism in the target VM by sending it a QUIT signal.74// Then we attempt to find the socket file again.75File socket_file = findSocketFile(pid, ns_pid);76socket_path = socket_file.getPath();77if (!socket_file.exists()) {78File f = createAttachFile(pid, ns_pid);79try {80sendQuitTo(pid);8182// give the target VM time to start the attach mechanism83final int delay_step = 100;84final long timeout = attachTimeout();85long time_spend = 0;86long delay = 0;87do {88// Increase timeout on each attempt to reduce polling89delay += delay_step;90try {91Thread.sleep(delay);92} catch (InterruptedException x) { }9394time_spend += delay;95if (time_spend > timeout/2 && !socket_file.exists()) {96// Send QUIT again to give target VM the last chance to react97sendQuitTo(pid);98}99} while (time_spend <= timeout && !socket_file.exists());100if (!socket_file.exists()) {101throw new AttachNotSupportedException(102String.format("Unable to open socket file %s: " +103"target process %d doesn't respond within %dms " +104"or HotSpot VM not loaded", socket_path, pid,105time_spend));106}107} finally {108f.delete();109}110}111112// Check that the file owner/permission to avoid attaching to113// bogus process114checkPermissions(socket_path);115116// Check that we can connect to the process117// - this ensures we throw the permission denied error now rather than118// later when we attempt to enqueue a command.119int s = socket();120try {121connect(s, socket_path);122} finally {123close(s);124}125}126127/**128* Detach from the target VM129*/130public void detach() throws IOException {131synchronized (this) {132if (socket_path != null) {133socket_path = null;134}135}136}137138// protocol version139private final static String PROTOCOL_VERSION = "1";140141// known errors142private final static int ATTACH_ERROR_BADVERSION = 101;143144/**145* Execute the given command in the target VM.146*/147InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {148assert args.length <= 3; // includes null149150// did we detach?151synchronized (this) {152if (socket_path == null) {153throw new IOException("Detached from target VM");154}155}156157// create UNIX socket158int s = socket();159160// connect to target VM161try {162connect(s, socket_path);163} catch (IOException x) {164close(s);165throw x;166}167168IOException ioe = null;169170// connected - write request171// <ver> <cmd> <args...>172try {173writeString(s, PROTOCOL_VERSION);174writeString(s, cmd);175176for (int i = 0; i < 3; i++) {177if (i < args.length && args[i] != null) {178writeString(s, (String)args[i]);179} else {180writeString(s, "");181}182}183} catch (IOException x) {184ioe = x;185}186187188// Create an input stream to read reply189SocketInputStream sis = new SocketInputStream(s);190191// Read the command completion status192int completionStatus;193try {194completionStatus = readInt(sis);195} catch (IOException x) {196sis.close();197if (ioe != null) {198throw ioe;199} else {200throw x;201}202}203204if (completionStatus != 0) {205// read from the stream and use that as the error message206String message = readErrorMessage(sis);207sis.close();208209// In the event of a protocol mismatch then the target VM210// returns a known error so that we can throw a reasonable211// error.212if (completionStatus == ATTACH_ERROR_BADVERSION) {213throw new IOException("Protocol mismatch with target VM");214}215216// Special-case the "load" command so that the right exception is217// thrown.218if (cmd.equals("load")) {219String msg = "Failed to load agent library";220if (!message.isEmpty())221msg += ": " + message;222throw new AgentLoadException(msg);223} else {224if (message.isEmpty())225message = "Command failed in target VM";226throw new AttachOperationFailedException(message);227}228}229230// Return the input stream so that the command output can be read231return sis;232}233234/*235* InputStream for the socket connection to get target VM236*/237private class SocketInputStream extends InputStream {238int s = -1;239240public SocketInputStream(int s) {241this.s = s;242}243244public synchronized int read() throws IOException {245byte b[] = new byte[1];246int n = this.read(b, 0, 1);247if (n == 1) {248return b[0] & 0xff;249} else {250return -1;251}252}253254public synchronized int read(byte[] bs, int off, int len) throws IOException {255if ((off < 0) || (off > bs.length) || (len < 0) ||256((off + len) > bs.length) || ((off + len) < 0)) {257throw new IndexOutOfBoundsException();258} else if (len == 0) {259return 0;260}261262return VirtualMachineImpl.read(s, bs, off, len);263}264265public synchronized void close() throws IOException {266if (s != -1) {267int toClose = s;268s = -1;269VirtualMachineImpl.close(toClose);270}271}272}273274// Return the socket file for the given process.275private File findSocketFile(int pid, int ns_pid) {276// A process may not exist in the same mount namespace as the caller.277// Instead, attach relative to the target root filesystem as exposed by278// procfs regardless of namespaces.279String root = "/proc/" + pid + "/root/" + tmpdir;280return new File(root, ".java_pid" + ns_pid);281}282283// On Linux a simple handshake is used to start the attach mechanism284// if not already started. The client creates a .attach_pid<pid> file in the285// target VM's working directory (or temp directory), and the SIGQUIT handler286// checks for the file.287private File createAttachFile(int pid, int ns_pid) throws IOException {288String fn = ".attach_pid" + ns_pid;289String path = "/proc/" + pid + "/cwd/" + fn;290File f = new File(path);291try {292f = f.getCanonicalFile();293f.createNewFile();294} catch (IOException x) {295String root;296if (pid != ns_pid) {297// A process may not exist in the same mount namespace as the caller.298// Instead, attach relative to the target root filesystem as exposed by299// procfs regardless of namespaces.300root = "/proc/" + pid + "/root/" + tmpdir;301} else {302root = tmpdir;303}304f = new File(root, fn);305f = f.getCanonicalFile();306f.createNewFile();307}308return f;309}310311/*312* Write/sends the given to the target VM. String is transmitted in313* UTF-8 encoding.314*/315private void writeString(int fd, String s) throws IOException {316if (s.length() > 0) {317byte b[];318try {319b = s.getBytes("UTF-8");320} catch (java.io.UnsupportedEncodingException x) {321throw new InternalError(x);322}323VirtualMachineImpl.write(fd, b, 0, b.length);324}325byte b[] = new byte[1];326b[0] = 0;327write(fd, b, 0, 1);328}329330331// Return the inner most namespaced PID if there is one,332// otherwise return the original PID.333private int getNamespacePid(int pid) throws AttachNotSupportedException, IOException {334// Assuming a real procfs sits beneath, reading this doesn't block335// nor will it consume a lot of memory.336String statusFile = "/proc/" + pid + "/status";337File f = new File(statusFile);338if (!f.exists()) {339return pid; // Likely a bad pid, but this is properly handled later.340}341342Path statusPath = Paths.get(statusFile);343344try {345for (String line : Files.readAllLines(statusPath, StandardCharsets.UTF_8)) {346String[] parts = line.split(":");347if (parts.length == 2 && parts[0].trim().equals("NSpid")) {348parts = parts[1].trim().split("\\s+");349// The last entry represents the PID the JVM "thinks" it is.350// Even in non-namespaced pids these entries should be351// valid. You could refer to it as the inner most pid.352int ns_pid = Integer.parseInt(parts[parts.length - 1]);353return ns_pid;354}355}356// Old kernels may not have NSpid field (i.e. 3.10).357// Fallback to original pid in the event we cannot deduce.358return pid;359} catch (NumberFormatException | IOException x) {360throw new AttachNotSupportedException("Unable to parse namespace");361}362}363364365//-- native methods366367static native void sendQuitTo(int pid) throws IOException;368369static native void checkPermissions(String path) throws IOException;370371static native int socket() throws IOException;372373static native void connect(int fd, String path) throws IOException;374375static native void close(int fd) throws IOException;376377static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;378379static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;380381static {382System.loadLibrary("attach");383}384}385386387