Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/solaris/classes/sun/tools/attach/LinuxVirtualMachine.java
32288 views
/*1* Copyright (c) 2005, 2014, 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;3435/*36* Linux implementation of HotSpotVirtualMachine37*/38public class LinuxVirtualMachine extends HotSpotVirtualMachine {39// "/tmp" is used as a global well-known location for the files40// .java_pid<pid>. and .attach_pid<pid>. It is important that this41// location is the same for all processes, otherwise the tools42// will not be able to find all Hotspot processes.43// Any changes to this needs to be synchronized with HotSpot.44private static final String tmpdir = "/tmp";4546// Indicates if this machine uses the old LinuxThreads47static boolean isLinuxThreads;4849// The patch to the socket file created by the target VM50String path;5152/**53* Attaches to the target VM54*/55LinuxVirtualMachine(AttachProvider provider, String vmid)56throws AttachNotSupportedException, IOException57{58super(provider, vmid);5960// This provider only understands pids61int pid;62try {63pid = Integer.parseInt(vmid);64} catch (NumberFormatException x) {65throw new AttachNotSupportedException("Invalid process identifier");66}6768// Find the socket file. If not found then we attempt to start the69// attach mechanism in the target VM by sending it a QUIT signal.70// Then we attempt to find the socket file again.71path = findSocketFile(pid);72if (path == null) {73File f = createAttachFile(pid);74try {75// On LinuxThreads each thread is a process and we don't have the76// pid of the VMThread which has SIGQUIT unblocked. To workaround77// this we get the pid of the "manager thread" that is created78// by the first call to pthread_create. This is parent of all79// threads (except the initial thread).80if (isLinuxThreads) {81int mpid;82try {83mpid = getLinuxThreadsManager(pid);84} catch (IOException x) {85throw new AttachNotSupportedException(x.getMessage());86}87assert(mpid >= 1);88sendQuitToChildrenOf(mpid);89} else {90sendQuitTo(pid);91}9293// give the target VM time to start the attach mechanism94int i = 0;95long delay = 200;96int retries = (int)(attachTimeout() / delay);97do {98try {99Thread.sleep(delay);100} catch (InterruptedException x) { }101path = findSocketFile(pid);102i++;103} while (i <= retries && path == null);104if (path == null) {105throw new AttachNotSupportedException(106"Unable to open socket file: target process not responding " +107"or HotSpot VM not loaded");108}109} finally {110f.delete();111}112}113114// Check that the file owner/permission to avoid attaching to115// bogus process116checkPermissions(path);117118// Check that we can connect to the process119// - this ensures we throw the permission denied error now rather than120// later when we attempt to enqueue a command.121int s = socket();122try {123connect(s, path);124} finally {125close(s);126}127}128129/**130* Detach from the target VM131*/132public void detach() throws IOException {133synchronized (this) {134if (this.path != null) {135this.path = null;136}137}138}139140// protocol version141private final static String PROTOCOL_VERSION = "1";142143// known errors144private final static int ATTACH_ERROR_BADVERSION = 101;145146/**147* Execute the given command in the target VM.148*/149InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {150assert args.length <= 3; // includes null151152// did we detach?153String p;154synchronized (this) {155if (this.path == null) {156throw new IOException("Detached from target VM");157}158p = this.path;159}160161// create UNIX socket162int s = socket();163164// connect to target VM165try {166connect(s, p);167} catch (IOException x) {168close(s);169throw x;170}171172IOException ioe = null;173174// connected - write request175// <ver> <cmd> <args...>176try {177writeString(s, PROTOCOL_VERSION);178writeString(s, cmd);179180for (int i=0; i<3; i++) {181if (i < args.length && args[i] != null) {182writeString(s, (String)args[i]);183} else {184writeString(s, "");185}186}187} catch (IOException x) {188ioe = x;189}190191192// Create an input stream to read reply193SocketInputStream sis = new SocketInputStream(s);194195// Read the command completion status196int completionStatus;197try {198completionStatus = readInt(sis);199} catch (IOException x) {200sis.close();201if (ioe != null) {202throw ioe;203} else {204throw x;205}206}207208if (completionStatus != 0) {209// read from the stream and use that as the error message210String message = readErrorMessage(sis);211sis.close();212213// In the event of a protocol mismatch then the target VM214// returns a known error so that we can throw a reasonable215// error.216if (completionStatus == ATTACH_ERROR_BADVERSION) {217throw new IOException("Protocol mismatch with target VM");218}219220// Special-case the "load" command so that the right exception is221// thrown.222if (cmd.equals("load")) {223throw new AgentLoadException("Failed to load agent library");224} else {225if (message == null) {226throw new AttachOperationFailedException("Command failed in target VM");227} else {228throw new AttachOperationFailedException(message);229}230}231}232233// Return the input stream so that the command output can be read234return sis;235}236237/*238* InputStream for the socket connection to get target VM239*/240private class SocketInputStream extends InputStream {241int s;242243public SocketInputStream(int s) {244this.s = s;245}246247public synchronized int read() throws IOException {248byte b[] = new byte[1];249int n = this.read(b, 0, 1);250if (n == 1) {251return b[0] & 0xff;252} else {253return -1;254}255}256257public synchronized int read(byte[] bs, int off, int len) throws IOException {258if ((off < 0) || (off > bs.length) || (len < 0) ||259((off + len) > bs.length) || ((off + len) < 0)) {260throw new IndexOutOfBoundsException();261} else if (len == 0)262return 0;263264return LinuxVirtualMachine.read(s, bs, off, len);265}266267public void close() throws IOException {268LinuxVirtualMachine.close(s);269}270}271272// Return the socket file for the given process.273private String findSocketFile(int pid) {274File f = new File(tmpdir, ".java_pid" + pid);275if (!f.exists()) {276return null;277}278return f.getPath();279}280281// On Solaris/Linux a simple handshake is used to start the attach mechanism282// if not already started. The client creates a .attach_pid<pid> file in the283// target VM's working directory (or temp directory), and the SIGQUIT handler284// checks for the file.285private File createAttachFile(int pid) throws IOException {286String fn = ".attach_pid" + pid;287String path = "/proc/" + pid + "/cwd/" + fn;288File f = new File(path);289try {290f.createNewFile();291} catch (IOException x) {292f = new File(tmpdir, fn);293f.createNewFile();294}295return f;296}297298/*299* Write/sends the given to the target VM. String is transmitted in300* UTF-8 encoding.301*/302private void writeString(int fd, String s) throws IOException {303if (s.length() > 0) {304byte b[];305try {306b = s.getBytes("UTF-8");307} catch (java.io.UnsupportedEncodingException x) {308throw new InternalError(x);309}310LinuxVirtualMachine.write(fd, b, 0, b.length);311}312byte b[] = new byte[1];313b[0] = 0;314write(fd, b, 0, 1);315}316317318//-- native methods319320static native boolean isLinuxThreads();321322static native int getLinuxThreadsManager(int pid) throws IOException;323324static native void sendQuitToChildrenOf(int pid) throws IOException;325326static native void sendQuitTo(int pid) throws IOException;327328static native void checkPermissions(String path) throws IOException;329330static native int socket() throws IOException;331332static native void connect(int fd, String path) throws IOException;333334static native void close(int fd) throws IOException;335336static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;337338static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;339340static {341System.loadLibrary("attach");342isLinuxThreads = isLinuxThreads();343}344}345346347