Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/solaris/classes/sun/tools/attach/BsdVirtualMachine.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* Bsd implementation of HotSpotVirtualMachine37*/38public class BsdVirtualMachine extends HotSpotVirtualMachine {39// "tmpdir" 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// This is intentionally not the same as java.io.tmpdir, since44// the latter can be changed by the user.45// Any changes to this needs to be synchronized with HotSpot.46private static final String tmpdir;4748// The patch to the socket file created by the target VM49String path;5051/**52* Attaches to the target VM53*/54BsdVirtualMachine(AttachProvider provider, String vmid)55throws AttachNotSupportedException, IOException56{57super(provider, vmid);5859// This provider only understands pids60int pid;61try {62pid = Integer.parseInt(vmid);63} catch (NumberFormatException x) {64throw new AttachNotSupportedException("Invalid process identifier");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.70path = findSocketFile(pid);71if (path == null) {72File f = new File(tmpdir, ".attach_pid" + pid);73createAttachFile(f.getPath());74try {75sendQuitTo(pid);7677// give the target VM time to start the attach mechanism78int i = 0;79long delay = 200;80int retries = (int)(attachTimeout() / delay);81do {82try {83Thread.sleep(delay);84} catch (InterruptedException x) { }85path = findSocketFile(pid);86i++;87} while (i <= retries && path == null);88if (path == null) {89throw new AttachNotSupportedException(90"Unable to open socket file: target process not responding " +91"or HotSpot VM not loaded");92}93} finally {94f.delete();95}96}9798// Check that the file owner/permission to avoid attaching to99// bogus process100checkPermissions(path);101102// Check that we can connect to the process103// - this ensures we throw the permission denied error now rather than104// later when we attempt to enqueue a command.105int s = socket();106try {107connect(s, path);108} finally {109close(s);110}111}112113/**114* Detach from the target VM115*/116public void detach() throws IOException {117synchronized (this) {118if (this.path != null) {119this.path = null;120}121}122}123124// protocol version125private final static String PROTOCOL_VERSION = "1";126127// known errors128private final static int ATTACH_ERROR_BADVERSION = 101;129130/**131* Execute the given command in the target VM.132*/133InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {134assert args.length <= 3; // includes null135136// did we detach?137String p;138synchronized (this) {139if (this.path == null) {140throw new IOException("Detached from target VM");141}142p = this.path;143}144145// create UNIX socket146int s = socket();147148// connect to target VM149try {150connect(s, p);151} catch (IOException x) {152close(s);153throw x;154}155156IOException ioe = null;157158// connected - write request159// <ver> <cmd> <args...>160try {161writeString(s, PROTOCOL_VERSION);162writeString(s, cmd);163164for (int i=0; i<3; i++) {165if (i < args.length && args[i] != null) {166writeString(s, (String)args[i]);167} else {168writeString(s, "");169}170}171} catch (IOException x) {172ioe = x;173}174175176// Create an input stream to read reply177SocketInputStream sis = new SocketInputStream(s);178179// Read the command completion status180int completionStatus;181try {182completionStatus = readInt(sis);183} catch (IOException x) {184sis.close();185if (ioe != null) {186throw ioe;187} else {188throw x;189}190}191192if (completionStatus != 0) {193// read from the stream and use that as the error message194String message = readErrorMessage(sis);195sis.close();196197// In the event of a protocol mismatch then the target VM198// returns a known error so that we can throw a reasonable199// error.200if (completionStatus == ATTACH_ERROR_BADVERSION) {201throw new IOException("Protocol mismatch with target VM");202}203204// Special-case the "load" command so that the right exception is205// thrown.206if (cmd.equals("load")) {207throw new AgentLoadException("Failed to load agent library");208} else {209if (message == null) {210throw new AttachOperationFailedException("Command failed in target VM");211} else {212throw new AttachOperationFailedException(message);213}214}215}216217// Return the input stream so that the command output can be read218return sis;219}220221/*222* InputStream for the socket connection to get target VM223*/224private class SocketInputStream extends InputStream {225int s;226227public SocketInputStream(int s) {228this.s = s;229}230231public synchronized int read() throws IOException {232byte b[] = new byte[1];233int n = this.read(b, 0, 1);234if (n == 1) {235return b[0] & 0xff;236} else {237return -1;238}239}240241public synchronized int read(byte[] bs, int off, int len) throws IOException {242if ((off < 0) || (off > bs.length) || (len < 0) ||243((off + len) > bs.length) || ((off + len) < 0)) {244throw new IndexOutOfBoundsException();245} else if (len == 0) {246return 0;247}248249return BsdVirtualMachine.read(s, bs, off, len);250}251252public void close() throws IOException {253BsdVirtualMachine.close(s);254}255}256257// Return the socket file for the given process.258// Checks temp directory for .java_pid<pid>.259private String findSocketFile(int pid) {260String fn = ".java_pid" + pid;261File f = new File(tmpdir, fn);262return f.exists() ? f.getPath() : null;263}264265/*266* Write/sends the given to the target VM. String is transmitted in267* UTF-8 encoding.268*/269private void writeString(int fd, String s) throws IOException {270if (s.length() > 0) {271byte b[];272try {273b = s.getBytes("UTF-8");274} catch (java.io.UnsupportedEncodingException x) {275throw new InternalError();276}277BsdVirtualMachine.write(fd, b, 0, b.length);278}279byte b[] = new byte[1];280b[0] = 0;281write(fd, b, 0, 1);282}283284285//-- native methods286287static native void sendQuitTo(int pid) throws IOException;288289static native void checkPermissions(String path) throws IOException;290291static native int socket() throws IOException;292293static native void connect(int fd, String path) throws IOException;294295static native void close(int fd) throws IOException;296297static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;298299static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;300301static native void createAttachFile(String path);302303static native String getTempDir();304305static {306System.loadLibrary("attach");307tmpdir = getTempDir();308}309}310311312