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 // The patch to the socket file created by the target VM 48 String path; 49 50 /** 51 * Attaches to the target VM 52 */ 53 VirtualMachineImpl(AttachProvider provider, String vmid) 54 throws AttachNotSupportedException, IOException 55 { 56 super(provider, vmid); 57 58 // This provider only understands pids 59 int pid; 60 try { 61 pid = Integer.parseInt(vmid); 62 } catch (NumberFormatException x) { 63 throw new AttachNotSupportedException("Invalid process identifier"); 64 } 65 66 // Find the socket file. If not found then we attempt to start the 67 // attach mechanism in the target VM by sending it a QUIT signal. 68 // Then we attempt to find the socket file again. 69 path = findSocketFile(pid); 70 if (path == null) { 71 File f = createAttachFile(pid); 72 try { 73 sendQuitTo(pid); 74 75 // give the target VM time to start the attach mechanism 76 final int delay_step = 100; 77 final long timeout = attachTimeout(); 78 long time_spend = 0; 79 long delay = 0; 80 do { 81 // Increase timeout on each attempt to reduce polling 82 delay += delay_step; 83 try { 84 Thread.sleep(delay); 85 } catch (InterruptedException x) { } 86 path = findSocketFile(pid); 87 88 time_spend += delay; 89 if (time_spend > timeout/2 && path == null) { 90 // Send QUIT again to give target VM the last chance to react 91 sendQuitTo(pid); 92 } 93 } while (time_spend <= timeout && path == null); 94 if (path == null) { 95 throw new AttachNotSupportedException( 96 String.format("Unable to open socket file: target process %d not responding within %dms or HotSpot VM not loaded", pid, time_spend)); 97 } 98 } finally { 99 f.delete(); 100 } 101 } 102 103 // Check that the file owner/permission to avoid attaching to 104 // bogus process 105 checkPermissions(path); 106 107 // Check that we can connect to the process 108 // - this ensures we throw the permission denied error now rather than 109 // later when we attempt to enqueue a command. 110 int s = socket(); 111 try { 112 connect(s, path); 113 } finally { 114 close(s); 115 } 116 } 117 118 /** 119 * Detach from the target VM 120 */ 121 public void detach() throws IOException { 122 synchronized (this) { 123 if (this.path != null) { 124 this.path = null; 125 } 126 } 127 } 128 129 // protocol version 130 private final static String PROTOCOL_VERSION = "1"; 131 132 // known errors 133 private final static int ATTACH_ERROR_BADVERSION = 101; 134 135 /** 136 * Execute the given command in the target VM. 137 */ 138 InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException { 139 assert args.length <= 3; // includes null 140 141 // did we detach? 142 String p; 143 synchronized (this) { 144 if (this.path == null) { 145 throw new IOException("Detached from target VM"); 146 } 147 p = this.path; 148 } 149 150 // create UNIX socket 151 int s = socket(); 152 153 // connect to target VM 154 try { 155 connect(s, p); 156 } catch (IOException x) { 157 close(s); 158 throw x; 159 } 160 161 IOException ioe = null; 162 163 // connected - write request 164 // <ver> <cmd> <args...> 165 try { 166 writeString(s, PROTOCOL_VERSION); 167 writeString(s, cmd); 168 169 for (int i=0; i<3; i++) { 170 if (i < args.length && args[i] != null) { 171 writeString(s, (String)args[i]); 172 } else { 173 writeString(s, ""); 174 } 175 } 176 } catch (IOException x) { 177 ioe = x; 178 } 179 180 181 // Create an input stream to read reply 182 SocketInputStream sis = new SocketInputStream(s); 183 184 // Read the command completion status 185 int completionStatus; 186 try { 187 completionStatus = readInt(sis); 188 } catch (IOException x) { 189 sis.close(); 190 if (ioe != null) { 191 throw ioe; 192 } else { 193 throw x; 194 } 195 } 196 197 if (completionStatus != 0) { 198 // read from the stream and use that as the error message 199 String message = readErrorMessage(sis); 200 sis.close(); 201 202 // In the event of a protocol mismatch then the target VM 203 // returns a known error so that we can throw a reasonable 204 // error. 205 if (completionStatus == ATTACH_ERROR_BADVERSION) { 206 throw new IOException("Protocol mismatch with target VM"); 207 } 208 209 // Special-case the "load" command so that the right exception is 210 // thrown. 211 if (cmd.equals("load")) { 212 throw new AgentLoadException("Failed to load agent library"); 213 } else { 214 if (message == null) { 215 throw new AttachOperationFailedException("Command failed in target VM"); 216 } else { 217 throw new AttachOperationFailedException(message); 218 } 219 } 220 } 221 222 // Return the input stream so that the command output can be read 223 return sis; 224 } 225 226 /* 227 * InputStream for the socket connection to get target VM 228 */ 229 private class SocketInputStream extends InputStream { 230 int s; 231 232 public SocketInputStream(int s) { 233 this.s = s; 234 } 235 236 public synchronized int read() throws IOException { 237 byte b[] = new byte[1]; 238 int n = this.read(b, 0, 1); 239 if (n == 1) { 240 return b[0] & 0xff; 241 } else { 242 return -1; 243 } 244 } 245 246 public synchronized int read(byte[] bs, int off, int len) throws IOException { 247 if ((off < 0) || (off > bs.length) || (len < 0) || 248 ((off + len) > bs.length) || ((off + len) < 0)) { 249 throw new IndexOutOfBoundsException(); 250 } else if (len == 0) 251 return 0; 252 253 return VirtualMachineImpl.read(s, bs, off, len); 254 } 255 256 public void close() throws IOException { 257 VirtualMachineImpl.close(s); 258 } 259 } 260 261 // Return the socket file for the given process. 262 private String findSocketFile(int pid) { 263 File f = new File(tmpdir, ".java_pid" + pid); 264 if (!f.exists()) { 265 return null; 266 } 267 return f.getPath(); 268 } 269 270 // On Solaris/Linux a simple handshake is used to start the attach mechanism 271 // if not already started. The client creates a .attach_pid<pid> file in the 272 // target VM's working directory (or temp directory), and the SIGQUIT handler 273 // checks for the file. 274 private File createAttachFile(int pid) throws IOException { 275 String fn = ".attach_pid" + pid; 276 String path = "/proc/" + pid + "/cwd/" + fn; 277 File f = new File(path); 278 try { 279 f.createNewFile(); 280 } catch (IOException x) { 281 f = new File(tmpdir, fn); 282 f.createNewFile(); 283 } 284 return f; 285 } 286 287 /* 288 * Write/sends the given to the target VM. String is transmitted in 289 * UTF-8 encoding. 290 */ 291 private void writeString(int fd, String s) throws IOException { 292 if (s.length() > 0) { 293 byte b[]; 294 try { 295 b = s.getBytes("UTF-8"); 296 } catch (java.io.UnsupportedEncodingException x) { 297 throw new InternalError(x); 298 } 299 VirtualMachineImpl.write(fd, b, 0, b.length); 300 } 301 byte b[] = new byte[1]; 302 b[0] = 0; 303 write(fd, b, 0, 1); 304 } 305 306 307 //-- native methods 308 309 static native boolean isLinuxThreads(); 310 311 static native int getLinuxThreadsManager(int pid) throws IOException; 312 313 static native void sendQuitToChildrenOf(int pid) throws IOException; 314 315 static native void sendQuitTo(int pid) throws IOException; 316 317 static native void checkPermissions(String path) throws IOException; 318 319 static native int socket() throws IOException; 320 321 static native void connect(int fd, String path) throws IOException; 322 323 static native void close(int fd) throws IOException; 324 325 static native int read(int fd, byte buf[], int off, int bufLen) throws IOException; 326 327 static native void write(int fd, byte buf[], int off, int bufLen) throws IOException; 328 329 static { 330 System.loadLibrary("attach"); 331 } 332 }