1/*
2 * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2015 SAP SE. 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 */
26package sun.tools.attach;
27
28import com.sun.tools.attach.AttachOperationFailedException;
29import com.sun.tools.attach.AgentLoadException;
30import com.sun.tools.attach.AttachNotSupportedException;
31import com.sun.tools.attach.spi.AttachProvider;
32
33import java.io.InputStream;
34import java.io.IOException;
35import java.io.File;
36
37// Based on linux/classes/sun/tools/attach/VirtualMachineImpl.java.
38
39/*
40 * Aix implementation of HotSpotVirtualMachine
41 */
42public class VirtualMachineImpl extends HotSpotVirtualMachine {
43    // "/tmp" is used as a global well-known location for the files
44    // .java_pid<pid>. and .attach_pid<pid>. It is important that this
45    // location is the same for all processes, otherwise the tools
46    // will not be able to find all Hotspot processes.
47    // Any changes to this needs to be synchronized with HotSpot.
48    private static final String tmpdir = "/tmp";
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                sendQuitTo(pid);
77
78                // give the target VM time to start the attach mechanism
79                final int delay_step = 100;
80                final long timeout = attachTimeout();
81                long time_spend = 0;
82                long delay = 0;
83                do {
84                    // Increase timeout on each attempt to reduce polling
85                    delay += delay_step;
86                    try {
87                        Thread.sleep(delay);
88                    } catch (InterruptedException x) { }
89                    path = findSocketFile(pid);
90
91                    time_spend += delay;
92                    if (time_spend > timeout/2 && path == null) {
93                        // Send QUIT again to give target VM the last chance to react
94                        sendQuitTo(pid);
95                    }
96                } while (time_spend <= timeout && path == null);
97                if (path == null) {
98                    throw new AttachNotSupportedException(
99                        String.format("Unable to open socket file %s: " +
100                          "target process %d doesn't respond within %dms " +
101                          "or HotSpot VM not loaded", f.getPath(), pid, time_spend));
102                }
103            } finally {
104                f.delete();
105            }
106        }
107
108        // Check that the file owner/permission to avoid attaching to
109        // bogus process
110        checkPermissions(path);
111
112        // Check that we can connect to the process
113        // - this ensures we throw the permission denied error now rather than
114        // later when we attempt to enqueue a command.
115        int s = socket();
116        try {
117            connect(s, path);
118        } finally {
119            close(s);
120        }
121    }
122
123    /**
124     * Detach from the target VM
125     */
126    public void detach() throws IOException {
127        synchronized (this) {
128            if (this.path != null) {
129                this.path = null;
130            }
131        }
132    }
133
134    // protocol version
135    private final static String PROTOCOL_VERSION = "1";
136
137    // known errors
138    private final static int ATTACH_ERROR_BADVERSION = 101;
139
140    /**
141     * Execute the given command in the target VM.
142     */
143    InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {
144        assert args.length <= 3;            // includes null
145
146        // did we detach?
147        String p;
148        synchronized (this) {
149            if (this.path == null) {
150                throw new IOException("Detached from target VM");
151            }
152            p = this.path;
153        }
154
155        // create UNIX socket
156        int s = socket();
157
158        // connect to target VM
159        try {
160            connect(s, p);
161        } catch (IOException x) {
162            close(s);
163            throw x;
164        }
165
166        IOException ioe = null;
167
168        // connected - write request
169        // <ver> <cmd> <args...>
170        try {
171            writeString(s, PROTOCOL_VERSION);
172            writeString(s, cmd);
173
174            for (int i=0; i<3; i++) {
175                if (i < args.length && args[i] != null) {
176                    writeString(s, (String)args[i]);
177                } else {
178                    writeString(s, "");
179                }
180            }
181        } catch (IOException x) {
182            ioe = x;
183        }
184
185
186        // Create an input stream to read reply
187        SocketInputStream sis = new SocketInputStream(s);
188
189        // Read the command completion status
190        int completionStatus;
191        try {
192            completionStatus = readInt(sis);
193        } catch (IOException x) {
194            sis.close();
195            if (ioe != null) {
196                throw ioe;
197            } else {
198                throw x;
199            }
200        }
201
202        if (completionStatus != 0) {
203            // read from the stream and use that as the error message
204            String message = readErrorMessage(sis);
205            sis.close();
206
207            // In the event of a protocol mismatch then the target VM
208            // returns a known error so that we can throw a reasonable
209            // error.
210            if (completionStatus == ATTACH_ERROR_BADVERSION) {
211                throw new IOException("Protocol mismatch with target VM");
212            }
213
214            // Special-case the "load" command so that the right exception is
215            // thrown.
216            if (cmd.equals("load")) {
217                String msg = "Failed to load agent library";
218                if (!message.isEmpty())
219                    msg += ": " + message;
220                throw new AgentLoadException(msg);
221            } else {
222                if (message.isEmpty())
223                    message = "Command failed in target VM";
224                throw new AttachOperationFailedException(message);
225            }
226        }
227
228        // Return the input stream so that the command output can be read
229        return sis;
230    }
231
232    /*
233     * InputStream for the socket connection to get target VM
234     */
235    private class SocketInputStream extends InputStream {
236        int s;
237
238        public SocketInputStream(int s) {
239            this.s = s;
240        }
241
242        public synchronized int read() throws IOException {
243            byte b[] = new byte[1];
244            int n = this.read(b, 0, 1);
245            if (n == 1) {
246                return b[0] & 0xff;
247            } else {
248                return -1;
249            }
250        }
251
252        public synchronized int read(byte[] bs, int off, int len) throws IOException {
253            if ((off < 0) || (off > bs.length) || (len < 0) ||
254                ((off + len) > bs.length) || ((off + len) < 0)) {
255                throw new IndexOutOfBoundsException();
256            } else if (len == 0)
257                return 0;
258
259            return VirtualMachineImpl.read(s, bs, off, len);
260        }
261
262        public void close() throws IOException {
263            VirtualMachineImpl.close(s);
264        }
265    }
266
267    // Return the socket file for the given process.
268    private String findSocketFile(int pid) {
269        File f = new File(tmpdir, ".java_pid" + pid);
270        if (!f.exists()) {
271            return null;
272        }
273        return f.getPath();
274    }
275
276    // On Solaris/Linux/Aix a simple handshake is used to start the attach mechanism
277    // if not already started. The client creates a .attach_pid<pid> file in the
278    // target VM's working directory (or temp directory), and the SIGQUIT handler
279    // checks for the file.
280    private File createAttachFile(int pid) throws IOException {
281        String fn = ".attach_pid" + pid;
282        String path = "/proc/" + pid + "/cwd/" + fn;
283        File f = new File(path);
284        try {
285            f.createNewFile();
286        } catch (IOException x) {
287            f = new File(tmpdir, fn);
288            f.createNewFile();
289        }
290        return f;
291    }
292
293    /*
294     * Write/sends the given to the target VM. String is transmitted in
295     * UTF-8 encoding.
296     */
297    private void writeString(int fd, String s) throws IOException {
298        if (s.length() > 0) {
299            byte b[];
300            try {
301                b = s.getBytes("UTF-8");
302            } catch (java.io.UnsupportedEncodingException x) {
303                throw new InternalError(x);
304            }
305            VirtualMachineImpl.write(fd, b, 0, b.length);
306        }
307        byte b[] = new byte[1];
308        b[0] = 0;
309        write(fd, b, 0, 1);
310    }
311
312
313    //-- native methods
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}
333