1 /*
   2  * Copyright (c) 2005, 2014, Oracle and/or its affiliates. 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 it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * 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 WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 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 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package sun.tools.attach;
  26 
  27 import com.sun.tools.attach.AttachOperationFailedException;
  28 import com.sun.tools.attach.AgentLoadException;
  29 import com.sun.tools.attach.AttachNotSupportedException;
  30 import com.sun.tools.attach.spi.AttachProvider;
  31 
  32 import java.io.InputStream;
  33 import java.io.IOException;
  34 import java.io.File;
  35 
  36 /*
  37  * Linux implementation of HotSpotVirtualMachine
  38  */
  39 public class VirtualMachineImpl extends HotSpotVirtualMachine {
  40     // "/tmp" is used as a global well-known location for the files
  41     // .java_pid<pid>. and .attach_pid<pid>. It is important that this
  42     // location is the same for all processes, otherwise the tools
  43     // will not be able to find all Hotspot processes.
  44     // Any changes to this needs to be synchronized with HotSpot.
  45     private static final String tmpdir = "/tmp";
  46 
  47     // Indicates if this machine uses the old LinuxThreads
  48     static boolean isLinuxThreads;
  49 
  50     // The patch to the socket file created by the target VM
  51     String path;
  52 
  53     /**
  54      * Attaches to the target VM
  55      */
  56     VirtualMachineImpl(AttachProvider provider, String vmid)
  57         throws AttachNotSupportedException, IOException
  58     {
  59         super(provider, vmid);
  60 
  61         // This provider only understands pids
  62         int pid;
  63         try {
  64             pid = Integer.parseInt(vmid);
  65         } catch (NumberFormatException x) {
  66             throw new AttachNotSupportedException("Invalid process identifier");
  67         }
  68 
  69         // Find the socket file. If not found then we attempt to start the
  70         // attach mechanism in the target VM by sending it a QUIT signal.
  71         // Then we attempt to find the socket file again.
  72         path = findSocketFile(pid);
  73         if (path == null) {
  74             File f = createAttachFile(pid);
  75             try {
  76                 // On LinuxThreads each thread is a process and we don't have the
  77                 // pid of the VMThread which has SIGQUIT unblocked. To workaround
  78                 // this we get the pid of the "manager thread" that is created
  79                 // by the first call to pthread_create. This is parent of all
  80                 // threads (except the initial thread).
  81                 if (isLinuxThreads) {
  82                     int mpid;
  83                     try {
  84                         mpid = getLinuxThreadsManager(pid);
  85                     } catch (IOException x) {
  86                         throw new AttachNotSupportedException(x.getMessage());
  87                     }
  88                     assert(mpid >= 1);
  89                     sendQuitToChildrenOf(mpid);
  90                 } else {
  91                     sendQuitTo(pid);
  92                 }
  93 
  94                 // give the target VM time to start the attach mechanism
  95                 int i = 0;
  96                 long delay = 200;
  97                 int retries = (int)(attachTimeout() / delay);
  98                 do {
  99                     try {
 100                         Thread.sleep(delay);
 101                     } catch (InterruptedException x) { }
 102                     path = findSocketFile(pid);
 103                     i++;
 104                 } while (i <= retries && path == null);
 105                 if (path == null) {
 106                     throw new AttachNotSupportedException(
 107                         "Unable to open socket file: target process not responding " +
 108                         "or HotSpot VM not loaded");
 109                 }
 110             } finally {
 111                 f.delete();
 112             }
 113         }
 114 
 115         // Check that the file owner/permission to avoid attaching to
 116         // bogus process
 117         checkPermissions(path);
 118 
 119         // Check that we can connect to the process
 120         // - this ensures we throw the permission denied error now rather than
 121         // later when we attempt to enqueue a command.
 122         int s = socket();
 123         try {
 124             connect(s, path);
 125         } finally {
 126             close(s);
 127         }
 128     }
 129 
 130     /**
 131      * Detach from the target VM
 132      */
 133     public void detach() throws IOException {
 134         synchronized (this) {
 135             if (this.path != null) {
 136                 this.path = null;
 137             }
 138         }
 139     }
 140 
 141     // protocol version
 142     private final static String PROTOCOL_VERSION = "1";
 143 
 144     // known errors
 145     private final static int ATTACH_ERROR_BADVERSION = 101;
 146 
 147     /**
 148      * Execute the given command in the target VM.
 149      */
 150     InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {
 151         assert args.length <= 3;                // includes null
 152 
 153         // did we detach?
 154         String p;
 155         synchronized (this) {
 156             if (this.path == null) {
 157                 throw new IOException("Detached from target VM");
 158             }
 159             p = this.path;
 160         }
 161 
 162         // create UNIX socket
 163         int s = socket();
 164 
 165         // connect to target VM
 166         try {
 167             connect(s, p);
 168         } catch (IOException x) {
 169             close(s);
 170             throw x;
 171         }
 172 
 173         IOException ioe = null;
 174 
 175         // connected - write request
 176         // <ver> <cmd> <args...>
 177         try {
 178             writeString(s, PROTOCOL_VERSION);
 179             writeString(s, cmd);
 180 
 181             for (int i=0; i<3; i++) {
 182                 if (i < args.length && args[i] != null) {
 183                     writeString(s, (String)args[i]);
 184                 } else {
 185                     writeString(s, "");
 186                 }
 187             }
 188         } catch (IOException x) {
 189             ioe = x;
 190         }
 191 
 192 
 193         // Create an input stream to read reply
 194         SocketInputStream sis = new SocketInputStream(s);
 195 
 196         // Read the command completion status
 197         int completionStatus;
 198         try {
 199             completionStatus = readInt(sis);
 200         } catch (IOException x) {
 201             sis.close();
 202             if (ioe != null) {
 203                 throw ioe;
 204             } else {
 205                 throw x;
 206             }
 207         }
 208 
 209         if (completionStatus != 0) {
 210             // read from the stream and use that as the error message
 211             String message = readErrorMessage(sis);
 212             sis.close();
 213 
 214             // In the event of a protocol mismatch then the target VM
 215             // returns a known error so that we can throw a reasonable
 216             // error.
 217             if (completionStatus == ATTACH_ERROR_BADVERSION) {
 218                 throw new IOException("Protocol mismatch with target VM");
 219             }
 220 
 221             // Special-case the "load" command so that the right exception is
 222             // thrown.
 223             if (cmd.equals("load")) {
 224                 throw new AgentLoadException("Failed to load agent library");
 225             } else {
 226                 if (message == null) {
 227                     throw new AttachOperationFailedException("Command failed in target VM");
 228                 } else {
 229                     throw new AttachOperationFailedException(message);
 230                 }
 231             }
 232         }
 233 
 234         // Return the input stream so that the command output can be read
 235         return sis;
 236     }
 237 
 238     /*
 239      * InputStream for the socket connection to get target VM
 240      */
 241     private class SocketInputStream extends InputStream {
 242         int s;
 243 
 244         public SocketInputStream(int s) {
 245             this.s = s;
 246         }
 247 
 248         public synchronized int read() throws IOException {
 249             byte b[] = new byte[1];
 250             int n = this.read(b, 0, 1);
 251             if (n == 1) {
 252                 return b[0] & 0xff;
 253             } else {
 254                 return -1;
 255             }
 256         }
 257 
 258         public synchronized int read(byte[] bs, int off, int len) throws IOException {
 259             if ((off < 0) || (off > bs.length) || (len < 0) ||
 260                 ((off + len) > bs.length) || ((off + len) < 0)) {
 261                 throw new IndexOutOfBoundsException();
 262             } else if (len == 0)
 263                 return 0;
 264 
 265             return VirtualMachineImpl.read(s, bs, off, len);
 266         }
 267 
 268         public void close() throws IOException {
 269             VirtualMachineImpl.close(s);
 270         }
 271     }
 272 
 273     // Return the socket file for the given process.
 274     private String findSocketFile(int pid) {
 275         File f = new File(tmpdir, ".java_pid" + pid);
 276         if (!f.exists()) {
 277             return null;
 278         }
 279         return f.getPath();
 280     }
 281 
 282     // On Solaris/Linux a simple handshake is used to start the attach mechanism
 283     // if not already started. The client creates a .attach_pid<pid> file in the
 284     // target VM's working directory (or temp directory), and the SIGQUIT handler
 285     // checks for the file.
 286     private File createAttachFile(int pid) throws IOException {
 287         String fn = ".attach_pid" + pid;
 288         String path = "/proc/" + pid + "/cwd/" + fn;
 289         File f = new File(path);
 290         try {
 291             f.createNewFile();
 292         } catch (IOException x) {
 293             f = new File(tmpdir, fn);
 294             f.createNewFile();
 295         }
 296         return f;
 297     }
 298 
 299     /*
 300      * Write/sends the given to the target VM. String is transmitted in
 301      * UTF-8 encoding.
 302      */
 303     private void writeString(int fd, String s) throws IOException {
 304         if (s.length() > 0) {
 305             byte b[];
 306             try {
 307                 b = s.getBytes("UTF-8");
 308             } catch (java.io.UnsupportedEncodingException x) {
 309                 throw new InternalError(x);
 310             }
 311             VirtualMachineImpl.write(fd, b, 0, b.length);
 312         }
 313         byte b[] = new byte[1];
 314         b[0] = 0;
 315         write(fd, b, 0, 1);
 316     }
 317 
 318 
 319     //-- native methods
 320 
 321     static native boolean isLinuxThreads();
 322 
 323     static native int getLinuxThreadsManager(int pid) throws IOException;
 324 
 325     static native void sendQuitToChildrenOf(int pid) throws IOException;
 326 
 327     static native void sendQuitTo(int pid) throws IOException;
 328 
 329     static native void checkPermissions(String path) throws IOException;
 330 
 331     static native int socket() throws IOException;
 332 
 333     static native void connect(int fd, String path) throws IOException;
 334 
 335     static native void close(int fd) throws IOException;
 336 
 337     static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;
 338 
 339     static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;
 340 
 341     static {
 342         System.loadLibrary("attach");
 343         isLinuxThreads = isLinuxThreads();
 344     }
 345 }