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