VirtualMachineImpl.java revision 15492:f754ada66386
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 */ 25package sun.tools.attach; 26 27import com.sun.tools.attach.AttachOperationFailedException; 28import com.sun.tools.attach.AgentLoadException; 29import com.sun.tools.attach.AttachNotSupportedException; 30import com.sun.tools.attach.spi.AttachProvider; 31 32import java.io.InputStream; 33import java.io.IOException; 34import java.io.File; 35 36/* 37 * Linux implementation of HotSpotVirtualMachine 38 */ 39public 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 %s: " + 97 "target process %d doesn't respond within %dms " + 98 "or HotSpot VM not loaded", f.getPath(), pid, time_spend)); 99 } 100 } finally { 101 f.delete(); 102 } 103 } 104 105 // Check that the file owner/permission to avoid attaching to 106 // bogus process 107 checkPermissions(path); 108 109 // Check that we can connect to the process 110 // - this ensures we throw the permission denied error now rather than 111 // later when we attempt to enqueue a command. 112 int s = socket(); 113 try { 114 connect(s, path); 115 } finally { 116 close(s); 117 } 118 } 119 120 /** 121 * Detach from the target VM 122 */ 123 public void detach() throws IOException { 124 synchronized (this) { 125 if (this.path != null) { 126 this.path = null; 127 } 128 } 129 } 130 131 // protocol version 132 private final static String PROTOCOL_VERSION = "1"; 133 134 // known errors 135 private final static int ATTACH_ERROR_BADVERSION = 101; 136 137 /** 138 * Execute the given command in the target VM. 139 */ 140 InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException { 141 assert args.length <= 3; // includes null 142 143 // did we detach? 144 String p; 145 synchronized (this) { 146 if (this.path == null) { 147 throw new IOException("Detached from target VM"); 148 } 149 p = this.path; 150 } 151 152 // create UNIX socket 153 int s = socket(); 154 155 // connect to target VM 156 try { 157 connect(s, p); 158 } catch (IOException x) { 159 close(s); 160 throw x; 161 } 162 163 IOException ioe = null; 164 165 // connected - write request 166 // <ver> <cmd> <args...> 167 try { 168 writeString(s, PROTOCOL_VERSION); 169 writeString(s, cmd); 170 171 for (int i=0; i<3; i++) { 172 if (i < args.length && args[i] != null) { 173 writeString(s, (String)args[i]); 174 } else { 175 writeString(s, ""); 176 } 177 } 178 } catch (IOException x) { 179 ioe = x; 180 } 181 182 183 // Create an input stream to read reply 184 SocketInputStream sis = new SocketInputStream(s); 185 186 // Read the command completion status 187 int completionStatus; 188 try { 189 completionStatus = readInt(sis); 190 } catch (IOException x) { 191 sis.close(); 192 if (ioe != null) { 193 throw ioe; 194 } else { 195 throw x; 196 } 197 } 198 199 if (completionStatus != 0) { 200 // read from the stream and use that as the error message 201 String message = readErrorMessage(sis); 202 sis.close(); 203 204 // In the event of a protocol mismatch then the target VM 205 // returns a known error so that we can throw a reasonable 206 // error. 207 if (completionStatus == ATTACH_ERROR_BADVERSION) { 208 throw new IOException("Protocol mismatch with target VM"); 209 } 210 211 // Special-case the "load" command so that the right exception is 212 // thrown. 213 if (cmd.equals("load")) { 214 throw new AgentLoadException("Failed to load agent library"); 215 } else { 216 if (message == null) { 217 throw new AttachOperationFailedException("Command failed in target VM"); 218 } else { 219 throw new AttachOperationFailedException(message); 220 } 221 } 222 } 223 224 // Return the input stream so that the command output can be read 225 return sis; 226 } 227 228 /* 229 * InputStream for the socket connection to get target VM 230 */ 231 private class SocketInputStream extends InputStream { 232 int s; 233 234 public SocketInputStream(int s) { 235 this.s = s; 236 } 237 238 public synchronized int read() throws IOException { 239 byte b[] = new byte[1]; 240 int n = this.read(b, 0, 1); 241 if (n == 1) { 242 return b[0] & 0xff; 243 } else { 244 return -1; 245 } 246 } 247 248 public synchronized int read(byte[] bs, int off, int len) throws IOException { 249 if ((off < 0) || (off > bs.length) || (len < 0) || 250 ((off + len) > bs.length) || ((off + len) < 0)) { 251 throw new IndexOutOfBoundsException(); 252 } else if (len == 0) 253 return 0; 254 255 return VirtualMachineImpl.read(s, bs, off, len); 256 } 257 258 public void close() throws IOException { 259 VirtualMachineImpl.close(s); 260 } 261 } 262 263 // Return the socket file for the given process. 264 private String findSocketFile(int pid) { 265 File f = new File(tmpdir, ".java_pid" + pid); 266 if (!f.exists()) { 267 return null; 268 } 269 return f.getPath(); 270 } 271 272 // On Solaris/Linux a simple handshake is used to start the attach mechanism 273 // if not already started. The client creates a .attach_pid<pid> file in the 274 // target VM's working directory (or temp directory), and the SIGQUIT handler 275 // checks for the file. 276 private File createAttachFile(int pid) throws IOException { 277 String fn = ".attach_pid" + pid; 278 String path = "/proc/" + pid + "/cwd/" + fn; 279 File f = new File(path); 280 try { 281 f.createNewFile(); 282 } catch (IOException x) { 283 f = new File(tmpdir, fn); 284 f.createNewFile(); 285 } 286 return f; 287 } 288 289 /* 290 * Write/sends the given to the target VM. String is transmitted in 291 * UTF-8 encoding. 292 */ 293 private void writeString(int fd, String s) throws IOException { 294 if (s.length() > 0) { 295 byte b[]; 296 try { 297 b = s.getBytes("UTF-8"); 298 } catch (java.io.UnsupportedEncodingException x) { 299 throw new InternalError(x); 300 } 301 VirtualMachineImpl.write(fd, b, 0, b.length); 302 } 303 byte b[] = new byte[1]; 304 b[0] = 0; 305 write(fd, b, 0, 1); 306 } 307 308 309 //-- native methods 310 311 static native boolean isLinuxThreads(); 312 313 static native int getLinuxThreadsManager(int pid) throws IOException; 314 315 static native void sendQuitToChildrenOf(int pid) throws IOException; 316 317 static native void sendQuitTo(int pid) throws IOException; 318 319 static native void checkPermissions(String path) throws IOException; 320 321 static native int socket() throws IOException; 322 323 static native void connect(int fd, String path) throws IOException; 324 325 static native void close(int fd) throws IOException; 326 327 static native int read(int fd, byte buf[], int off, int bufLen) throws IOException; 328 329 static native void write(int fd, byte buf[], int off, int bufLen) throws IOException; 330 331 static { 332 System.loadLibrary("attach"); 333 } 334} 335