Path: blob/master/src/jdk.attach/aix/classes/sun/tools/attach/VirtualMachineImpl.java
40983 views
/*1* Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved.2* Copyright (c) 2015, 2019 SAP SE. All rights reserved.3* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.4*5* This code is free software; you can redistribute it and/or modify it6* under the terms of the GNU General Public License version 2 only, as7* published by the Free Software Foundation. Oracle designates this8* particular file as subject to the "Classpath" exception as provided9* by Oracle in the LICENSE file that accompanied this code.10*11* This code is distributed in the hope that it will be useful, but WITHOUT12* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or13* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License14* version 2 for more details (a copy is included in the LICENSE file that15* accompanied this code).16*17* You should have received a copy of the GNU General Public License version18* 2 along with this work; if not, write to the Free Software Foundation,19* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.20*21* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA22* or visit www.oracle.com if you need additional information or have any23* questions.24*/25package sun.tools.attach;2627import com.sun.tools.attach.AttachOperationFailedException;28import com.sun.tools.attach.AgentLoadException;29import com.sun.tools.attach.AttachNotSupportedException;30import com.sun.tools.attach.spi.AttachProvider;3132import java.io.InputStream;33import java.io.IOException;34import java.io.File;3536/*37* Aix implementation of HotSpotVirtualMachine38*/39public class VirtualMachineImpl extends HotSpotVirtualMachine {40// "/tmp" is used as a global well-known location for the files41// .java_pid<pid>. and .attach_pid<pid>. It is important that this42// location is the same for all processes, otherwise the tools43// will not be able to find all Hotspot processes.44// Any changes to this needs to be synchronized with HotSpot.45private static final String tmpdir = "/tmp";46String socket_path;4748/**49* Attaches to the target VM50*/51VirtualMachineImpl(AttachProvider provider, String vmid)52throws AttachNotSupportedException, IOException53{54super(provider, vmid);5556// This provider only understands pids57int pid;58try {59pid = Integer.parseInt(vmid);60if (pid < 1) {61throw new NumberFormatException();62}63} catch (NumberFormatException x) {64throw new AttachNotSupportedException("Invalid process identifier: " + vmid);65}6667// Find the socket file. If not found then we attempt to start the68// attach mechanism in the target VM by sending it a QUIT signal.69// Then we attempt to find the socket file again.70File socket_file = new File(tmpdir, ".java_pid" + pid);71socket_path = socket_file.getPath();72if (!socket_file.exists()) {73File f = createAttachFile(pid);74try {75sendQuitTo(pid);7677// give the target VM time to start the attach mechanism78final int delay_step = 100;79final long timeout = attachTimeout();80long time_spend = 0;81long delay = 0;82do {83// Increase timeout on each attempt to reduce polling84delay += delay_step;85try {86Thread.sleep(delay);87} catch (InterruptedException x) { }8889time_spend += delay;90if (time_spend > timeout/2 && !socket_file.exists()) {91// Send QUIT again to give target VM the last chance to react92sendQuitTo(pid);93}94} while (time_spend <= timeout && !socket_file.exists());95if (!socket_file.exists()) {96throw new AttachNotSupportedException(97String.format("Unable to open socket file %s: " +98"target process %d doesn't respond within %dms " +99"or HotSpot VM not loaded", socket_path, pid,100time_spend));101}102} finally {103f.delete();104}105}106107// Check that the file owner/permission to avoid attaching to108// bogus process109checkPermissions(socket_path);110111// Check that we can connect to the process112// - this ensures we throw the permission denied error now rather than113// later when we attempt to enqueue a command.114int s = socket();115try {116connect(s, socket_path);117} finally {118close(s);119}120}121122/**123* Detach from the target VM124*/125public void detach() throws IOException {126synchronized (this) {127if (socket_path != null) {128socket_path = null;129}130}131}132133// protocol version134private final static String PROTOCOL_VERSION = "1";135136// known errors137private final static int ATTACH_ERROR_BADVERSION = 101;138139/**140* Execute the given command in the target VM.141*/142InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {143assert args.length <= 3; // includes null144145// did we detach?146synchronized (this) {147if (socket_path == null) {148throw new IOException("Detached from target VM");149}150}151152// create UNIX socket153int s = socket();154155// connect to target VM156try {157connect(s, socket_path);158} catch (IOException x) {159close(s);160throw x;161}162163IOException ioe = null;164165// connected - write request166// <ver> <cmd> <args...>167try {168writeString(s, PROTOCOL_VERSION);169writeString(s, cmd);170171for (int i = 0; i < 3; i++) {172if (i < args.length && args[i] != null) {173writeString(s, (String)args[i]);174} else {175writeString(s, "");176}177}178} catch (IOException x) {179ioe = x;180}181182183// Create an input stream to read reply184SocketInputStream sis = new SocketInputStream(s);185186// Read the command completion status187int completionStatus;188try {189completionStatus = readInt(sis);190} catch (IOException x) {191sis.close();192if (ioe != null) {193throw ioe;194} else {195throw x;196}197}198199if (completionStatus != 0) {200// read from the stream and use that as the error message201String message = readErrorMessage(sis);202sis.close();203204// In the event of a protocol mismatch then the target VM205// returns a known error so that we can throw a reasonable206// error.207if (completionStatus == ATTACH_ERROR_BADVERSION) {208throw new IOException("Protocol mismatch with target VM");209}210211// Special-case the "load" command so that the right exception is212// thrown.213if (cmd.equals("load")) {214String msg = "Failed to load agent library";215if (!message.isEmpty())216msg += ": " + message;217throw new AgentLoadException(msg);218} else {219if (message.isEmpty())220message = "Command failed in target VM";221throw new AttachOperationFailedException(message);222}223}224225// Return the input stream so that the command output can be read226return sis;227}228229/*230* InputStream for the socket connection to get target VM231*/232private class SocketInputStream extends InputStream {233int s;234235public SocketInputStream(int s) {236this.s = s;237}238239public synchronized int read() throws IOException {240byte b[] = new byte[1];241int n = this.read(b, 0, 1);242if (n == 1) {243return b[0] & 0xff;244} else {245return -1;246}247}248249public synchronized int read(byte[] bs, int off, int len) throws IOException {250if ((off < 0) || (off > bs.length) || (len < 0) ||251((off + len) > bs.length) || ((off + len) < 0)) {252throw new IndexOutOfBoundsException();253} else if (len == 0)254return 0;255256return VirtualMachineImpl.read(s, bs, off, len);257}258259public synchronized void close() throws IOException {260if (s != -1) {261int toClose = s;262s = -1;263VirtualMachineImpl.close(toClose);264}265}266}267268// On Aix a simple handshake is used to start the attach mechanism269// if not already started. The client creates a .attach_pid<pid> file in the270// target VM's working directory (or temp directory), and the SIGQUIT handler271// checks for the file.272private File createAttachFile(int pid) throws IOException {273String fn = ".attach_pid" + pid;274String path = "/proc/" + pid + "/cwd/" + fn;275File f = new File(path);276try {277f = f.getCanonicalFile();278f.createNewFile();279} catch (IOException x) {280f = new File(tmpdir, fn);281f.createNewFile();282}283return f;284}285286/*287* Write/sends the given to the target VM. String is transmitted in288* UTF-8 encoding.289*/290private void writeString(int fd, String s) throws IOException {291if (s.length() > 0) {292byte b[];293try {294b = s.getBytes("UTF-8");295} catch (java.io.UnsupportedEncodingException x) {296throw new InternalError(x);297}298VirtualMachineImpl.write(fd, b, 0, b.length);299}300byte b[] = new byte[1];301b[0] = 0;302write(fd, b, 0, 1);303}304305306//-- native methods307308static native void sendQuitTo(int pid) throws IOException;309310static native void checkPermissions(String path) throws IOException;311312static native int socket() throws IOException;313314static native void connect(int fd, String path) throws IOException;315316static native void close(int fd) throws IOException;317318static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;319320static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;321322static {323System.loadLibrary("attach");324}325}326327328