Path: blob/master/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java
67699 views
/*1* Copyright (c) 2005, 2021, 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()) {78// Keep canonical version of File, to delete, in case target process ends and /proc link has gone:79File f = createAttachFile(pid, ns_pid).getCanonicalFile();80try {81sendQuitTo(pid);8283// give the target VM time to start the attach mechanism84final int delay_step = 100;85final long timeout = attachTimeout();86long time_spend = 0;87long delay = 0;88do {89// Increase timeout on each attempt to reduce polling90delay += delay_step;91try {92Thread.sleep(delay);93} catch (InterruptedException x) { }9495time_spend += delay;96if (time_spend > timeout/2 && !socket_file.exists()) {97// Send QUIT again to give target VM the last chance to react98sendQuitTo(pid);99}100} while (time_spend <= timeout && !socket_file.exists());101if (!socket_file.exists()) {102throw new AttachNotSupportedException(103String.format("Unable to open socket file %s: " +104"target process %d doesn't respond within %dms " +105"or HotSpot VM not loaded", socket_path, pid,106time_spend));107}108} finally {109f.delete();110}111}112113// Check that the file owner/permission to avoid attaching to114// bogus process115checkPermissions(socket_path);116117// Check that we can connect to the process118// - this ensures we throw the permission denied error now rather than119// later when we attempt to enqueue a command.120int s = socket();121try {122connect(s, socket_path);123} finally {124close(s);125}126}127128/**129* Detach from the target VM130*/131public void detach() throws IOException {132synchronized (this) {133if (socket_path != null) {134socket_path = null;135}136}137}138139// protocol version140private final static String PROTOCOL_VERSION = "1";141142// known errors143private final static int ATTACH_ERROR_BADVERSION = 101;144145/**146* Execute the given command in the target VM.147*/148InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {149assert args.length <= 3; // includes null150151// did we detach?152synchronized (this) {153if (socket_path == null) {154throw new IOException("Detached from target VM");155}156}157158// create UNIX socket159int s = socket();160161// connect to target VM162try {163connect(s, socket_path);164} catch (IOException x) {165close(s);166throw x;167}168169IOException ioe = null;170171// connected - write request172// <ver> <cmd> <args...>173try {174writeString(s, PROTOCOL_VERSION);175writeString(s, cmd);176177for (int i = 0; i < 3; i++) {178if (i < args.length && args[i] != null) {179writeString(s, (String)args[i]);180} else {181writeString(s, "");182}183}184} catch (IOException x) {185ioe = x;186}187188189// Create an input stream to read reply190SocketInputStream sis = new SocketInputStream(s);191192// Read the command completion status193int completionStatus;194try {195completionStatus = readInt(sis);196} catch (IOException x) {197sis.close();198if (ioe != null) {199throw ioe;200} else {201throw x;202}203}204205if (completionStatus != 0) {206// read from the stream and use that as the error message207String message = readErrorMessage(sis);208sis.close();209210// In the event of a protocol mismatch then the target VM211// returns a known error so that we can throw a reasonable212// error.213if (completionStatus == ATTACH_ERROR_BADVERSION) {214throw new IOException("Protocol mismatch with target VM");215}216217// Special-case the "load" command so that the right exception is218// thrown.219if (cmd.equals("load")) {220String msg = "Failed to load agent library";221if (!message.isEmpty())222msg += ": " + message;223throw new AgentLoadException(msg);224} else {225if (message.isEmpty())226message = "Command failed in target VM";227throw new AttachOperationFailedException(message);228}229}230231// Return the input stream so that the command output can be read232return sis;233}234235/*236* InputStream for the socket connection to get target VM237*/238private class SocketInputStream extends InputStream {239int s = -1;240241public SocketInputStream(int s) {242this.s = s;243}244245public synchronized int read() throws IOException {246byte b[] = new byte[1];247int n = this.read(b, 0, 1);248if (n == 1) {249return b[0] & 0xff;250} else {251return -1;252}253}254255public synchronized int read(byte[] bs, int off, int len) throws IOException {256if ((off < 0) || (off > bs.length) || (len < 0) ||257((off + len) > bs.length) || ((off + len) < 0)) {258throw new IndexOutOfBoundsException();259} else if (len == 0) {260return 0;261}262263return VirtualMachineImpl.read(s, bs, off, len);264}265266public synchronized void close() throws IOException {267if (s != -1) {268int toClose = s;269s = -1;270VirtualMachineImpl.close(toClose);271}272}273}274275// Return the socket file for the given process.276private File findSocketFile(int pid, int ns_pid) {277// A process may not exist in the same mount namespace as the caller.278// Instead, attach relative to the target root filesystem as exposed by279// procfs regardless of namespaces.280String root = "/proc/" + pid + "/root/" + tmpdir;281return new File(root, ".java_pid" + ns_pid);282}283284// On Linux a simple handshake is used to start the attach mechanism285// if not already started. The client creates a .attach_pid<pid> file in the286// target VM's working directory (or temp directory), and the SIGQUIT handler287// checks for the file.288private File createAttachFile(int pid, int ns_pid) throws IOException {289String fn = ".attach_pid" + ns_pid;290String path = "/proc/" + pid + "/cwd/" + fn;291File f = new File(path);292try {293// Do not canonicalize the file path, or we will fail to attach to a VM in a container.294f.createNewFile();295} catch (IOException x) {296String root;297if (pid != ns_pid) {298// A process may not exist in the same mount namespace as the caller.299// Instead, attach relative to the target root filesystem as exposed by300// procfs regardless of namespaces.301root = "/proc/" + pid + "/root/" + tmpdir;302} else {303root = tmpdir;304}305f = new File(root, fn);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