Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java
40948 views
1
/*
2
* Copyright (c) 2005, 2019, 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
import java.nio.charset.StandardCharsets;
36
import java.nio.file.Path;
37
import java.nio.file.Paths;
38
import java.nio.file.Files;
39
40
/*
41
* Linux implementation of HotSpotVirtualMachine
42
*/
43
public class VirtualMachineImpl extends HotSpotVirtualMachine {
44
// "/tmp" is used as a global well-known location for the files
45
// .java_pid<pid>. and .attach_pid<pid>. It is important that this
46
// location is the same for all processes, otherwise the tools
47
// will not be able to find all Hotspot processes.
48
// Any changes to this needs to be synchronized with HotSpot.
49
private static final String tmpdir = "/tmp";
50
String socket_path;
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
if (pid < 1) {
64
throw new NumberFormatException();
65
}
66
} catch (NumberFormatException x) {
67
throw new AttachNotSupportedException("Invalid process identifier: " + vmid);
68
}
69
70
// Try to resolve to the "inner most" pid namespace
71
int ns_pid = getNamespacePid(pid);
72
73
// Find the socket file. If not found then we attempt to start the
74
// attach mechanism in the target VM by sending it a QUIT signal.
75
// Then we attempt to find the socket file again.
76
File socket_file = findSocketFile(pid, ns_pid);
77
socket_path = socket_file.getPath();
78
if (!socket_file.exists()) {
79
File f = createAttachFile(pid, ns_pid);
80
try {
81
sendQuitTo(pid);
82
83
// give the target VM time to start the attach mechanism
84
final int delay_step = 100;
85
final long timeout = attachTimeout();
86
long time_spend = 0;
87
long delay = 0;
88
do {
89
// Increase timeout on each attempt to reduce polling
90
delay += delay_step;
91
try {
92
Thread.sleep(delay);
93
} catch (InterruptedException x) { }
94
95
time_spend += delay;
96
if (time_spend > timeout/2 && !socket_file.exists()) {
97
// Send QUIT again to give target VM the last chance to react
98
sendQuitTo(pid);
99
}
100
} while (time_spend <= timeout && !socket_file.exists());
101
if (!socket_file.exists()) {
102
throw new AttachNotSupportedException(
103
String.format("Unable to open socket file %s: " +
104
"target process %d doesn't respond within %dms " +
105
"or HotSpot VM not loaded", socket_path, pid,
106
time_spend));
107
}
108
} finally {
109
f.delete();
110
}
111
}
112
113
// Check that the file owner/permission to avoid attaching to
114
// bogus process
115
checkPermissions(socket_path);
116
117
// Check that we can connect to the process
118
// - this ensures we throw the permission denied error now rather than
119
// later when we attempt to enqueue a command.
120
int s = socket();
121
try {
122
connect(s, socket_path);
123
} finally {
124
close(s);
125
}
126
}
127
128
/**
129
* Detach from the target VM
130
*/
131
public void detach() throws IOException {
132
synchronized (this) {
133
if (socket_path != null) {
134
socket_path = null;
135
}
136
}
137
}
138
139
// protocol version
140
private final static String PROTOCOL_VERSION = "1";
141
142
// known errors
143
private final static int ATTACH_ERROR_BADVERSION = 101;
144
145
/**
146
* Execute the given command in the target VM.
147
*/
148
InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {
149
assert args.length <= 3; // includes null
150
151
// did we detach?
152
synchronized (this) {
153
if (socket_path == null) {
154
throw new IOException("Detached from target VM");
155
}
156
}
157
158
// create UNIX socket
159
int s = socket();
160
161
// connect to target VM
162
try {
163
connect(s, socket_path);
164
} catch (IOException x) {
165
close(s);
166
throw x;
167
}
168
169
IOException ioe = null;
170
171
// connected - write request
172
// <ver> <cmd> <args...>
173
try {
174
writeString(s, PROTOCOL_VERSION);
175
writeString(s, cmd);
176
177
for (int i = 0; i < 3; i++) {
178
if (i < args.length && args[i] != null) {
179
writeString(s, (String)args[i]);
180
} else {
181
writeString(s, "");
182
}
183
}
184
} catch (IOException x) {
185
ioe = x;
186
}
187
188
189
// Create an input stream to read reply
190
SocketInputStream sis = new SocketInputStream(s);
191
192
// Read the command completion status
193
int completionStatus;
194
try {
195
completionStatus = readInt(sis);
196
} catch (IOException x) {
197
sis.close();
198
if (ioe != null) {
199
throw ioe;
200
} else {
201
throw x;
202
}
203
}
204
205
if (completionStatus != 0) {
206
// read from the stream and use that as the error message
207
String message = readErrorMessage(sis);
208
sis.close();
209
210
// In the event of a protocol mismatch then the target VM
211
// returns a known error so that we can throw a reasonable
212
// error.
213
if (completionStatus == ATTACH_ERROR_BADVERSION) {
214
throw new IOException("Protocol mismatch with target VM");
215
}
216
217
// Special-case the "load" command so that the right exception is
218
// thrown.
219
if (cmd.equals("load")) {
220
String msg = "Failed to load agent library";
221
if (!message.isEmpty())
222
msg += ": " + message;
223
throw new AgentLoadException(msg);
224
} else {
225
if (message.isEmpty())
226
message = "Command failed in target VM";
227
throw new AttachOperationFailedException(message);
228
}
229
}
230
231
// Return the input stream so that the command output can be read
232
return sis;
233
}
234
235
/*
236
* InputStream for the socket connection to get target VM
237
*/
238
private class SocketInputStream extends InputStream {
239
int s = -1;
240
241
public SocketInputStream(int s) {
242
this.s = s;
243
}
244
245
public synchronized int read() throws IOException {
246
byte b[] = new byte[1];
247
int n = this.read(b, 0, 1);
248
if (n == 1) {
249
return b[0] & 0xff;
250
} else {
251
return -1;
252
}
253
}
254
255
public synchronized int read(byte[] bs, int off, int len) throws IOException {
256
if ((off < 0) || (off > bs.length) || (len < 0) ||
257
((off + len) > bs.length) || ((off + len) < 0)) {
258
throw new IndexOutOfBoundsException();
259
} else if (len == 0) {
260
return 0;
261
}
262
263
return VirtualMachineImpl.read(s, bs, off, len);
264
}
265
266
public synchronized void close() throws IOException {
267
if (s != -1) {
268
int toClose = s;
269
s = -1;
270
VirtualMachineImpl.close(toClose);
271
}
272
}
273
}
274
275
// Return the socket file for the given process.
276
private File findSocketFile(int pid, int ns_pid) {
277
// A process may not exist in the same mount namespace as the caller.
278
// Instead, attach relative to the target root filesystem as exposed by
279
// procfs regardless of namespaces.
280
String root = "/proc/" + pid + "/root/" + tmpdir;
281
return new File(root, ".java_pid" + ns_pid);
282
}
283
284
// On Linux a simple handshake is used to start the attach mechanism
285
// if not already started. The client creates a .attach_pid<pid> file in the
286
// target VM's working directory (or temp directory), and the SIGQUIT handler
287
// checks for the file.
288
private File createAttachFile(int pid, int ns_pid) throws IOException {
289
String fn = ".attach_pid" + ns_pid;
290
String path = "/proc/" + pid + "/cwd/" + fn;
291
File f = new File(path);
292
try {
293
f = f.getCanonicalFile();
294
f.createNewFile();
295
} catch (IOException x) {
296
String root;
297
if (pid != ns_pid) {
298
// A process may not exist in the same mount namespace as the caller.
299
// Instead, attach relative to the target root filesystem as exposed by
300
// procfs regardless of namespaces.
301
root = "/proc/" + pid + "/root/" + tmpdir;
302
} else {
303
root = tmpdir;
304
}
305
f = new File(root, fn);
306
f = f.getCanonicalFile();
307
f.createNewFile();
308
}
309
return f;
310
}
311
312
/*
313
* Write/sends the given to the target VM. String is transmitted in
314
* UTF-8 encoding.
315
*/
316
private void writeString(int fd, String s) throws IOException {
317
if (s.length() > 0) {
318
byte b[];
319
try {
320
b = s.getBytes("UTF-8");
321
} catch (java.io.UnsupportedEncodingException x) {
322
throw new InternalError(x);
323
}
324
VirtualMachineImpl.write(fd, b, 0, b.length);
325
}
326
byte b[] = new byte[1];
327
b[0] = 0;
328
write(fd, b, 0, 1);
329
}
330
331
332
// Return the inner most namespaced PID if there is one,
333
// otherwise return the original PID.
334
private int getNamespacePid(int pid) throws AttachNotSupportedException, IOException {
335
// Assuming a real procfs sits beneath, reading this doesn't block
336
// nor will it consume a lot of memory.
337
String statusFile = "/proc/" + pid + "/status";
338
File f = new File(statusFile);
339
if (!f.exists()) {
340
return pid; // Likely a bad pid, but this is properly handled later.
341
}
342
343
Path statusPath = Paths.get(statusFile);
344
345
try {
346
for (String line : Files.readAllLines(statusPath, StandardCharsets.UTF_8)) {
347
String[] parts = line.split(":");
348
if (parts.length == 2 && parts[0].trim().equals("NSpid")) {
349
parts = parts[1].trim().split("\\s+");
350
// The last entry represents the PID the JVM "thinks" it is.
351
// Even in non-namespaced pids these entries should be
352
// valid. You could refer to it as the inner most pid.
353
int ns_pid = Integer.parseInt(parts[parts.length - 1]);
354
return ns_pid;
355
}
356
}
357
// Old kernels may not have NSpid field (i.e. 3.10).
358
// Fallback to original pid in the event we cannot deduce.
359
return pid;
360
} catch (NumberFormatException | IOException x) {
361
throw new AttachNotSupportedException("Unable to parse namespace");
362
}
363
}
364
365
366
//-- native methods
367
368
static native void sendQuitTo(int pid) throws IOException;
369
370
static native void checkPermissions(String path) throws IOException;
371
372
static native int socket() throws IOException;
373
374
static native void connect(int fd, String path) throws IOException;
375
376
static native void close(int fd) throws IOException;
377
378
static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;
379
380
static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;
381
382
static {
383
System.loadLibrary("attach");
384
}
385
}
386
387