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