-
-
Notifications
You must be signed in to change notification settings - Fork 778
/
VirtualMachine.java
2777 lines (2513 loc) · 124 KB
/
VirtualMachine.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2014 - Present Rafael Winterhalter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bytebuddy.agent;
import com.sun.jna.*;
import com.sun.jna.platform.win32.*;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIOptions;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.bytebuddy.agent.utility.nullability.MaybeNull;
import net.bytebuddy.agent.utility.nullability.UnknownNull;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.FileLock;
import java.security.PrivilegedAction;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* <p>
* An implementation for attachment on a virtual machine. This interface mimics the tooling API's virtual
* machine interface to allow for similar usage by {@link ByteBuddyAgent} where all calls are made via
* reflection such that this structural typing suffices for interoperability.
* </p>
* <p>
* <b>Note</b>: Implementations are required to declare a static method {@code attach(String)} returning an
* instance of a class that declares the methods defined by {@link VirtualMachine}.
* </p>
*/
public interface VirtualMachine {
/**
* Loads the target VMs system properties.
*
* @return The target VM properties.
* @throws IOException If an I/O exception occurs.
*/
Properties getSystemProperties() throws IOException;
/**
* Loads the target VMs agent properties.
*
* @return The target VM properties.
* @throws IOException If an I/O exception occurs.
*/
Properties getAgentProperties() throws IOException;
/**
* Loads an agent into the represented virtual machine.
*
* @param jarFile The jar file to attach.
* @throws IOException If an I/O exception occurs.
*/
void loadAgent(String jarFile) throws IOException;
/**
* Loads an agent into the represented virtual machine.
*
* @param jarFile The jar file to attach.
* @param argument The argument to provide or {@code null} if no argument should be provided.
* @throws IOException If an I/O exception occurs.
*/
void loadAgent(String jarFile, @MaybeNull String argument) throws IOException;
/**
* Loads a native agent into the represented virtual machine.
*
* @param path The agent path.
* @throws IOException If an I/O exception occurs.
*/
void loadAgentPath(String path) throws IOException;
/**
* Loads a native agent into the represented virtual machine.
*
* @param path The agent path.
* @param argument The argument to provide or {@code null} if no argument should be provided.
* @throws IOException If an I/O exception occurs.
*/
void loadAgentPath(String path, @MaybeNull String argument) throws IOException;
/**
* Loads a native agent library into the represented virtual machine.
*
* @param library The agent library.
* @throws IOException If an I/O exception occurs.
*/
void loadAgentLibrary(String library) throws IOException;
/**
* Loads a native agent library into the represented virtual machine.
*
* @param library The agent library.
* @param argument The argument to provide or {@code null} if no argument should be provided.
* @throws IOException If an I/O exception occurs.
*/
void loadAgentLibrary(String library, @MaybeNull String argument) throws IOException;
/**
* Starts a JMX management agent.
*
* @param properties The properties to transfer to the JMX agent.
* @throws IOException If an I/O error occurs.
*/
void startManagementAgent(Properties properties) throws IOException;
/**
* Starts a local management agent.
*
* @return The local connector address.
* @throws IOException If an I/O error occurs.
*/
String startLocalManagementAgent() throws IOException;
/**
* Detaches this virtual machine representation.
*
* @throws IOException If an I/O exception occurs.
*/
void detach() throws IOException;
/**
* A resolver for the current VM's virtual machine attachment emulation.
*/
enum Resolver implements PrivilegedAction<Class<? extends VirtualMachine>> {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Class<? extends VirtualMachine> run() {
try {
Class.forName("com.sun.jna.Platform");
} catch (ClassNotFoundException exception) {
throw new IllegalStateException("Optional JNA dependency is not available", exception);
}
return System.getProperty("java.vm.name", "").toUpperCase(Locale.US).contains("J9")
? ForOpenJ9.class
: ForHotSpot.class;
}
}
/**
* An abstract base implementation for a virtual machine.
*/
abstract class AbstractBase implements VirtualMachine {
/**
* {@inheritDoc}
*/
public void loadAgent(String jarFile) throws IOException {
loadAgent(jarFile, null);
}
/**
* {@inheritDoc}
*/
public void loadAgentPath(String path) throws IOException {
loadAgentPath(path, null);
}
/**
* {@inheritDoc}
*/
public void loadAgentLibrary(String library) throws IOException {
loadAgentLibrary(library, null);
}
}
/**
* A virtual machine attachment implementation for a HotSpot VM or any compatible JVM.
*/
class ForHotSpot extends AbstractBase {
/**
* The protocol version to use for communication.
*/
private static final String PROTOCOL_VERSION = "1";
/**
* The {@code load} command.
*/
private static final String LOAD_COMMAND = "load";
/**
* The {@code instrument} command.
*/
private static final String INSTRUMENT_COMMAND = "instrument";
/**
* A delimiter to be used for attachment.
*/
private static final String ARGUMENT_DELIMITER = "=";
/**
* The virtual machine connection.
*/
private final Connection connection;
/**
* Creates a new virtual machine connection for HotSpot.
*
* @param connection The virtual machine connection.
*/
protected ForHotSpot(Connection connection) {
this.connection = connection;
}
/**
* Attaches to the supplied process id using the default JNA implementation.
*
* @param processId The process id.
* @return A suitable virtual machine implementation.
* @throws IOException If an IO exception occurs during establishing the connection.
*/
public static VirtualMachine attach(String processId) throws IOException {
if (Platform.isWindows()) {
return attach(processId, new Connection.ForJnaWindowsNamedPipe.Factory());
} else if (Platform.isSolaris()) {
return attach(processId, new Connection.ForJnaSolarisDoor.Factory(15, 100, TimeUnit.MILLISECONDS));
} else {
return attach(processId, Connection.ForJnaPosixSocket.Factory.withDefaultTemporaryFolder(15, 100, TimeUnit.MILLISECONDS));
}
}
/**
* Attaches to the supplied process id using the supplied connection factory.
*
* @param processId The process id.
* @param connectionFactory The connection factory to use.
* @return A suitable virtual machine implementation.
* @throws IOException If an IO exception occurs during establishing the connection.
*/
public static VirtualMachine attach(String processId, Connection.Factory connectionFactory) throws IOException {
return new ForHotSpot(connectionFactory.connect(processId));
}
/**
* Checks the header of a response.
*
* @param response The response to check the header for.
* @throws IOException If an I/O exception occurs.
*/
private static void checkHeader(Connection.Response response) throws IOException {
byte[] buffer = new byte[1];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int length;
while ((length = response.read(buffer)) != -1) {
if (length > 0) {
if (buffer[0] == '\n') {
break;
}
outputStream.write(buffer[0]);
}
}
switch (Integer.parseInt(outputStream.toString("UTF-8"))) {
case 0:
return;
case 101:
throw new IOException("Protocol mismatch with target VM");
default:
buffer = new byte[1024];
outputStream = new ByteArrayOutputStream();
while ((length = response.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
throw new IllegalStateException(outputStream.toString("UTF-8"));
}
}
/**
* {@inheritDoc}
*/
public Properties getSystemProperties() throws IOException {
return getProperties("properties");
}
/**
* {@inheritDoc}
*/
public Properties getAgentProperties() throws IOException {
return getProperties("agentProperties");
}
/**
* Loads properties of the target VM.
*
* @param command The command for fetching properties.
* @return The read properties.
* @throws IOException If an I/O exception occurs.
*/
private Properties getProperties(String command) throws IOException {
Connection.Response response = connection.execute(PROTOCOL_VERSION, command, null, null, null);
try {
checkHeader(response);
byte[] buffer = new byte[1024];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int length;
while ((length = response.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
Properties properties = new Properties();
properties.load(new ByteArrayInputStream(outputStream.toByteArray()));
return properties;
} finally {
response.close();
}
}
/**
* {@inheritDoc}
*/
public void loadAgent(String jarFile, @MaybeNull String argument) throws IOException {
load(jarFile, false, argument);
}
/**
* {@inheritDoc}
*/
public void loadAgentPath(String path, @MaybeNull String argument) throws IOException {
load(path, true, argument);
}
/**
* {@inheritDoc}
*/
public void loadAgentLibrary(String library, @MaybeNull String argument) throws IOException {
load(library, false, argument);
}
/**
* Loads an agent by the given command.
*
* @param file The Java agent or library to be loaded.
* @param absolute {@code true} if the agent location is absolute.
* @param argument The argument to the agent or {@code null} if no argument is given.
* @throws IOException If an I/O exception occurs.
*/
protected void load(String file, boolean absolute, @MaybeNull String argument) throws IOException {
Connection.Response response = connection.execute(PROTOCOL_VERSION, LOAD_COMMAND, INSTRUMENT_COMMAND, Boolean.toString(absolute), (argument == null
? file
: file + ARGUMENT_DELIMITER + argument));
try {
checkHeader(response);
} finally {
response.close();
}
}
/**
* {@inheritDoc}
*/
public void startManagementAgent(Properties properties) throws IOException {
StringBuilder stringBuilder = new StringBuilder("ManagementAgent.start ");
boolean first = true;
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
if (!(entry.getKey() instanceof String) || !((String) entry.getKey()).startsWith("com.sun.management.")) {
throw new IllegalArgumentException("Illegal property name: " + entry.getKey());
} else if (first) {
first = false;
} else {
stringBuilder.append(' ');
}
stringBuilder.append(((String) entry.getKey()).substring("com.sun.management.".length())).append('=');
String value = entry.getValue().toString();
if (value.contains(" ")) {
stringBuilder.append('\'').append(value).append('\'');
} else {
stringBuilder.append(value);
}
}
Connection.Response response = connection.execute(PROTOCOL_VERSION, "jcmd", stringBuilder.toString(), null, null);
try {
checkHeader(response);
} finally {
response.close();
}
}
/**
* {@inheritDoc}
*/
public String startLocalManagementAgent() throws IOException {
Connection.Response response = connection.execute(PROTOCOL_VERSION, "jcmd", "ManagementAgent.start_local", null, null);
try {
checkHeader(response);
return getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
} finally {
response.close();
}
}
/**
* {@inheritDoc}
*/
public void detach() throws IOException {
connection.close();
}
/**
* Represents a connection to a virtual machine.
*/
public interface Connection extends Closeable {
/**
* Executes a command on the current connection.
*
* @param protocol The target VMs protocol version for the attach API.
* @param argument The arguments to send to the target VM.
* @return The response of the target JVM.
* @throws IOException If an I/O error occurred.
*/
Response execute(String protocol, String... argument) throws IOException;
/**
* A response to an execution command to a VM.
*/
interface Response extends Closeable {
/**
* Reads a buffer from the target VM.
*
* @param buffer The buffer to read to.
* @return The bytes read or {@code -1} if no more bytes could be read.
* @throws IOException If an I/O exception occurred.
*/
int read(byte[] buffer) throws IOException;
}
/**
* A factory for creating connections to virtual machines.
*/
interface Factory {
/**
* Connects to the supplied process.
*
* @param processId The process id.
* @return The connection to the virtual machine with the supplied process id.
* @throws IOException If an I/O exception occurs during connecting to the targeted VM.
*/
Connection connect(String processId) throws IOException;
/**
* A factory for attaching via a socket file.
*/
abstract class ForSocketFile implements Factory {
/**
* The name prefix for a socket.
*/
private static final String SOCKET_FILE_PREFIX = ".java_pid";
/**
* The name prefix for an attachment file indicator.
*/
private static final String ATTACH_FILE_PREFIX = ".attach_pid";
/**
* The temporary directory to use.
*/
private final String temporaryDirectory;
/**
* The maximum amount of attempts for checking the establishment of a socket connection.
*/
private final int attempts;
/**
* The pause between two checks for an established socket connection.
*/
private final long pause;
/**
* The time unit of the pause time.
*/
private final TimeUnit timeUnit;
/**
* Creates a connection factory for creating a socket connection via a file.
*
* @param temporaryDirectory The temporary directory to use.
* @param attempts The maximum amount of attempts for checking the establishment of a socket connection.
* @param pause The pause between two checks for an established socket connection.
* @param timeUnit The time unit of the pause time.
*/
protected ForSocketFile(String temporaryDirectory, int attempts, long pause, TimeUnit timeUnit) {
this.temporaryDirectory = temporaryDirectory;
this.attempts = attempts;
this.pause = pause;
this.timeUnit = timeUnit;
}
/**
* {@inheritDoc}
*/
@SuppressFBWarnings(value = "DMI_HARDCODED_ABSOLUTE_FILENAME", justification = "File name convention is specified.")
public Connection connect(String processId) throws IOException {
File socket = new File(temporaryDirectory, SOCKET_FILE_PREFIX + processId);
if (!socket.exists()) {
String target = ATTACH_FILE_PREFIX + processId, path = "/proc/" + processId + "/cwd/" + target;
File attachFile = new File(path);
try {
if (!attachFile.createNewFile() && !attachFile.isFile()) {
throw new IllegalStateException("Could not create attach file: " + attachFile);
}
} catch (IOException ignored) {
attachFile = new File(temporaryDirectory, target);
if (!attachFile.createNewFile() && !attachFile.isFile()) {
throw new IllegalStateException("Could not create attach file: " + attachFile);
}
}
try {
kill(processId, 3);
int attempts = this.attempts;
while (!socket.exists() && attempts-- > 0) {
timeUnit.sleep(pause);
}
if (!socket.exists()) {
throw new IllegalStateException("Target VM did not respond: " + processId);
}
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new IllegalStateException(exception);
} finally {
if (!attachFile.delete()) {
attachFile.deleteOnExit();
}
}
}
return doConnect(socket);
}
/**
* Sends a kill signal to the target process.
*
* @param processId The process id.
* @param signal The signal to send.
*/
protected abstract void kill(String processId, int signal);
/**
* Connects to the supplied POSIX socket.
*
* @param socket The socket to connect to.
* @return An active connection to the supplied socket.
* @throws IOException If an error occurs during connection.
*/
protected abstract Connection doConnect(File socket) throws IOException;
}
}
/**
* A connection that is represented by a byte channel that is persistent during communication.
*
* @param <T> The connection representation.
*/
abstract class OnPersistentByteChannel<T> implements Connection {
/**
* A blank line argument.
*/
private static final byte[] BLANK = new byte[]{0};
/**
* {@inheritDoc}
*/
public Connection.Response execute(String protocol, String... argument) throws IOException {
T connection = connect();
try {
write(connection, protocol.getBytes("UTF-8"));
write(connection, BLANK);
for (String anArgument : argument) {
if (anArgument != null) {
write(connection, anArgument.getBytes("UTF-8"));
}
write(connection, BLANK);
}
return new Response(connection);
} catch (Throwable throwable) {
close(connection);
if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
} else if (throwable instanceof IOException) {
throw (IOException) throwable;
} else {
throw new IllegalStateException(throwable);
}
}
}
/**
* A response of a persistent byte channel.
*/
private class Response implements Connection.Response {
/**
* The connection representing this response.
*/
private final T connection;
/**
* Creates a new response for a persistent byte channel.
*
* @param connection The connection representing this response.
*/
private Response(T connection) {
this.connection = connection;
}
/**
* {@inheritDoc}
*/
public int read(byte[] buffer) throws IOException {
return OnPersistentByteChannel.this.read(connection, buffer);
}
/**
* {@inheritDoc}
*/
public void close() throws IOException {
OnPersistentByteChannel.this.close(connection);
}
}
/**
* Creates a new connection to the target VM.
*
* @return Returns a new connection to the target VM.
* @throws IOException If an I/O exception occurs.
*/
protected abstract T connect() throws IOException;
/**
* Closes the connection to the target VM.
*
* @param connection The connection to close.
* @throws IOException If an I/O exception occurs.
*/
protected abstract void close(T connection) throws IOException;
/**
* Writes to the target VM.
*
* @param connection The connection to write to.
* @param buffer The buffer to write to.
* @throws IOException If an I/O exception occurs during writing.
*/
protected abstract void write(T connection, byte[] buffer) throws IOException;
/**
* Reads from the target VM.
*
* @param connection The connection to read from.
* @param buffer The buffer to store the result in.
* @return The number of byte that were read.
* @throws IOException If an I/O exception occurs.
*/
protected abstract int read(T connection, byte[] buffer) throws IOException;
}
/**
* Implements a connection for a Posix socket in JNA.
*/
class ForJnaPosixSocket extends OnPersistentByteChannel<Integer> {
/**
* The JNA library to use.
*/
private final PosixLibrary library;
/**
* The POSIX socket.
*/
private final File socket;
/**
* Creates a connection for a virtual posix socket implemented in JNA.
*
* @param library The JNA library to use.
* @param socket The POSIX socket.
*/
protected ForJnaPosixSocket(PosixLibrary library, File socket) {
this.library = library;
this.socket = socket;
}
@Override
protected Integer connect() {
int handle = library.socket(1, 1, 0);
try {
PosixLibrary.SocketAddress address = new PosixLibrary.SocketAddress();
try {
address.setPath(socket.getAbsolutePath());
library.connect(handle, address, address.size());
return handle;
} finally {
address = null;
}
} catch (RuntimeException exception) {
library.close(handle);
throw exception;
}
}
@Override
protected int read(Integer handle, byte[] buffer) {
int read = library.read(handle, ByteBuffer.wrap(buffer), buffer.length);
return read == 0 ? -1 : read;
}
@Override
protected void write(Integer handle, byte[] buffer) {
library.write(handle, ByteBuffer.wrap(buffer), buffer.length);
}
@Override
protected void close(Integer handle) {
library.close(handle);
}
/**
* {@inheritDoc}
*/
public void close() {
/* do nothing */
}
/**
* A JNA library binding for Posix sockets.
*/
protected interface PosixLibrary extends Library {
/**
* Sends a kill command.
*
* @param processId The process id to kill.
* @param signal The signal to send.
* @return The return code.
* @throws LastErrorException If an error occurs.
*/
int kill(int processId, int signal) throws LastErrorException;
/**
* Creates a POSIX socket connection.
*
* @param domain The socket's domain.
* @param type The socket's type.
* @param protocol The protocol version.
* @return A handle to the socket that was created or {@code 0} if no socket could be created.
* @throws LastErrorException If an error occurs.
*/
int socket(int domain, int type, int protocol) throws LastErrorException;
/**
* Connects a socket connection.
*
* @param handle The socket's handle.
* @param address The address of the POSIX socket.
* @param length The length of the socket value.
* @return The return code.
* @throws LastErrorException If an error occurs.
*/
int connect(int handle, SocketAddress address, int length) throws LastErrorException;
/**
* Reads from a POSIX socket.
*
* @param handle The socket's handle.
* @param buffer The buffer to read from.
* @param count The bytes being read.
* @return The amount of bytes that could be read.
* @throws LastErrorException If an error occurs.
*/
int read(int handle, ByteBuffer buffer, int count) throws LastErrorException;
/**
* Writes to a POSIX socket.
*
* @param handle The socket's handle.
* @param buffer The buffer to write to.
* @param count The bytes being written.
* @return The return code.
* @throws LastErrorException If an error occurs.
*/
int write(int handle, ByteBuffer buffer, int count) throws LastErrorException;
/**
* Closes the socket connection.
*
* @param handle The handle of the connection.
* @return The return code.
* @throws LastErrorException If an error occurs.
*/
int close(int handle) throws LastErrorException;
/**
* Represents an address for a POSIX socket.
*/
class SocketAddress extends Structure {
/**
* The socket family.
*/
@SuppressWarnings("unused")
@SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD", justification = "Field required by native implementation.")
public short family = 1;
/**
* The socket path.
*/
public byte[] path = new byte[100];
/**
* Sets the socket path.
*
* @param path The socket path.
*/
protected void setPath(String path) {
try {
System.arraycopy(path.getBytes("UTF-8"), 0, this.path, 0, path.length());
System.arraycopy(new byte[]{0}, 0, this.path, path.length(), 1);
} catch (UnsupportedEncodingException exception) {
throw new IllegalStateException(exception);
}
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("family", "path");
}
}
}
/**
* A factory for a POSIX socket connection to a JVM using JNA.
*/
public static class Factory extends Connection.Factory.ForSocketFile {
/**
* The socket library API.
*/
private final PosixLibrary library;
/**
* Creates a connection factory for a POSIX socket using JNA.
*
* @param temporaryDirectory The temporary directory to use.
* @param attempts The maximum amount of attempts for checking the establishment of a socket connection.
* @param pause The pause between two checks for an established socket connection.
* @param timeUnit The time unit of the pause time.
*/
@SuppressWarnings("deprecation")
public Factory(String temporaryDirectory, int attempts, long pause, TimeUnit timeUnit) {
super(temporaryDirectory, attempts, pause, timeUnit);
library = Native.loadLibrary("c", PosixLibrary.class);
}
/**
* Creates a connection factory for a POSIX socket using JNA while locating the default temporary directory used on the
* current platform.
*
* @param attempts The maximum amount of attempts for checking the establishment of a socket connection.
* @param pause The pause between two checks for an established socket connection.
* @param timeUnit The time unit of the pause time.
* @return An appropriate connection factory.
*/
@SuppressWarnings("deprecation")
public static Connection.Factory withDefaultTemporaryFolder(int attempts, long pause, TimeUnit timeUnit) {
String temporaryDirectory;
if (Platform.isMac()) {
MacLibrary library = Native.loadLibrary("c", MacLibrary.class);
Memory memory = new Memory(4096);
try {
long length = library.confstr(MacLibrary.CS_DARWIN_USER_TEMP_DIR, memory, memory.size());
if (length == 0 || length > 4096) {
temporaryDirectory = "/tmp";
} else {
temporaryDirectory = memory.getString(0);
}
} finally {
memory = null;
}
} else {
temporaryDirectory = "/tmp";
}
return new Factory(temporaryDirectory, attempts, pause, timeUnit);
}
@Override
protected void kill(String processId, int signal) {
library.kill(Integer.parseInt(processId), signal);
}
@Override
public Connection doConnect(File socket) {
return new Connection.ForJnaPosixSocket(library, socket);
}
/**
* A library for reading a Mac user's temporary directory.
*/
public interface MacLibrary extends Library {
/**
* The temporary directory.
*/
int CS_DARWIN_USER_TEMP_DIR = 65537;
/**
* Reads a configuration dependant variable into a memory segment.
*
* @param name The name of the variable.
* @param buffer The buffer to read the variable into.
* @param length The length of the buffer.
* @return The amount of bytes written to the buffer.
*/
long confstr(int name, Pointer buffer, long length);
}
}
}
/**
* Implements a connection for a Windows named pipe in JNA.
*/
class ForJnaWindowsNamedPipe implements Connection {
/**
* Indicates a memory release.
*/
private static final int MEM_RELEASE = 0x8000;
/**
* The library to use for communicating with Windows native functions.
*/
private final WindowsLibrary library;
/**
* The library to use for communicating with Windows attachment extension that is included as a DLL.
*/
private final WindowsAttachLibrary attachLibrary;
/**
* The handle of the target VM's process.
*/
private final WinNT.HANDLE process;
/**
* A pointer to the code that was injected into the target process.
*/
private final WinDef.LPVOID code;
/**
* A source of random values being used for generating pipe names.
*/
private final SecureRandom random;
/**
* Creates a new connection via a named pipe.
*
* @param library The library to use for communicating with Windows native functions.
* @param attachLibrary The library to use for communicating with Windows attachment extension that is included as a DLL.
* @param process The handle of the target VM's process.
* @param code A pointer to the code that was injected into the target process.
*/
protected ForJnaWindowsNamedPipe(WindowsLibrary library,
WindowsAttachLibrary attachLibrary,
WinNT.HANDLE process,
WinDef.LPVOID code) {
this.library = library;
this.attachLibrary = attachLibrary;
this.process = process;
this.code = code;
random = new SecureRandom();
}
/**