File: Binder.java

package info (click to toggle)
openjdk-11 11.0.16%2B8-1~deb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 784,576 kB
  • sloc: java: 5,128,021; xml: 1,192,224; cpp: 1,124,021; ansic: 422,433; javascript: 155,577; sh: 17,084; objc: 13,327; python: 4,522; asm: 3,570; makefile: 2,858; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (1273 lines) | stat: -rw-r--r-- 49,058 bytes parent folder | download | duplicates (10)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
/*
 * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package nsk.share.jdi;

import nsk.share.*;
import nsk.share.jpda.*;

import com.sun.jdi.*;
import com.sun.jdi.connect.*;

import com.sun.jdi.connect.Connector.Argument;
import java.io.*;
import java.net.*;
import java.util.*;

/**
 * This class provides debugger with connection to debugee VM
 * using JDI connectors.
 *<p>
 * This class provides abilities to launch and bind to debugee VM
 * as described for base <code>DebugeeBinder</code> class,
 * using JDI connectors and <code>com.sun.VirtualMachine</code> mirror.
 * <p>
 * When <code>Binder</code> is asked to bind to debugee by invoking
 * <code>bindToBebugee()</code> method it uses
 * <code>com.sun.jdi.Connector</code> object corresponding to
 * value of command line options <code>-connector</code> and
 * <code>-transport</code> to launch and connect to debugee VM.
 * After debugee is launched and connection is established
 * <code>Binder</code> uses <code>com.sun.jdi.VirtualMachine</code>
 * object to construct <code>Debugee</code> object, that
 * provides abilities to interact with debugee VM.
 *
 * @see Debugee
 * @see DebugeeBinder
 */
public class Binder extends DebugeeBinder {

    /**
     * Default message prefix for <code>Binder</code> object.
     */
    public static final String LOG_PREFIX = "binder> ";

    /**
     * Get version string.
     */
    public static String getVersion () {
        return "@(#)Binder.java 1.14 03/10/08";
    }

    // -------------------------------------------------- //

    /**
     * Handler of command line arguments.
     */
    private ArgumentHandler argumentHandler = null;

    /**
     * Return <code>argumentHandler</code> of this binder.
     */
    public ArgumentHandler getArgumentHandler() {
        return argumentHandler;
    }

    // -------------------------------------------------- //

    /**
     * Make <code>Binder</code> object and pass raw command line arguments.
     *
     * @deprecated  Use newer
     *              <code>Binder(ArgumentHandler,Log)</code>
     *              constructor.
     */
    public Binder (String args[]) {
        this(args, new Log(System.err));
    }

    /**
     * Make <code>Binder</code> object for raw command line arguments
     * and specified <code>log</code> object.
     *
     * @deprecated  Use newer
     *              <code>Binder(ArgumentHandler,Log)</code>
     *              constructor.
     */
    public Binder (String args[], Log log) {
        this(new ArgumentHandler(args), log);
    }

    /**
     * Make <code>Binder</code> object for specified command line arguments
     * and <code>log</code> object.
     */
    public Binder (ArgumentHandler argumentHandler, Log log) {
        super(argumentHandler, log);
        this.argumentHandler = argumentHandler;
    }

    // -------------------------------------------------- //

    /**
     * Make initial <code>Debugee</code> object for local debuggee process
     * started with launching connector.
     */
    public Debugee makeLocalDebugee(Process process) {
        LocalLaunchedDebugee debugee = new LocalLaunchedDebugee(process, this);

        Finalizer finalizer = new Finalizer(debugee);
        finalizer.activate();

        return debugee;
    }

    /**
     * Launch local debuggee process with specified command line
     * and make initial <code>Debugee</code> object.
     */
    public Debugee startLocalDebugee(String cmd) {
        Process process = null;

        try {
            process = launchProcess(cmd);
        } catch (IOException e) {
            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while launching local debuggee VM process:\n\t"
                            + e);
        }

        return makeLocalDebugee(process);
    }

    /**
     * Make debuggee wrapper for already launched debuggee VM.
     * After enwraping debugee's output is redirected to Binder's log,
     * VMStartEvent is received and debuggee is initialized.
     */
    public Debugee enwrapDebugee(VirtualMachine vm, Process proc) {
        Debugee debugee = makeLocalDebugee(proc);

        display("Redirecting VM output");
        debugee.redirectOutput(log);
        debugee.setupVM(vm);

        long timeout = argumentHandler.getWaitTime() * 60 * 1000; // milliseconds

        display("Waiting for VM initialized");
        debugee.waitForVMInit(timeout);

        return debugee;
    }

    /**
     * Launch debugee VM and establish connection to it without waiting for VMStartEvent.
     * After launching debugee's output is redirected to Binder's log,
     * but VMStartEvent is not received and so debuggee is not fully initialized.
     *
     * @see #bindToDebugee(String)
     */
    public Debugee bindToDebugeeNoWait(String classToExecute) {

        VirtualMachineManager vmm = Bootstrap.virtualMachineManager();
        display("VirtualMachineManager: version "
                + vmm.majorInterfaceVersion() + "."
                + vmm.minorInterfaceVersion());

        Debugee debugee = null;

        String classPath = null;
//        classPath = System.getProperty("java.class.path");

        prepareForPipeConnection(argumentHandler);

        if (argumentHandler.isLaunchedLocally()) {

            if (argumentHandler.isDefaultConnector()) {
                debugee = localDefaultLaunchDebugee(vmm, classToExecute, classPath);
            } else if (argumentHandler.isRawLaunchingConnector()) {
                debugee = localRawLaunchDebugee(vmm, classToExecute, classPath);
            } else if (argumentHandler.isLaunchingConnector()) {
                debugee = localLaunchDebugee(vmm, classToExecute, classPath);
            } else if (argumentHandler.isAttachingConnector()) {
                debugee = localLaunchAndAttachDebugee(vmm, classToExecute, classPath);
            } else if (argumentHandler.isLaunchingConnector()) {
                debugee = localLaunchDebugee(vmm, classToExecute, classPath);
            } else if (argumentHandler.isListeningConnector()) {
                debugee = localLaunchAndListenDebugee(vmm, classToExecute, classPath);
            } else {
                throw new TestBug("Unexpected connector type for local debugee launch mode"
                                  + argumentHandler.getConnectorType());
            }

        } else if (argumentHandler.isLaunchedRemotely()) {

            connectToBindServer(classToExecute);

            if (argumentHandler.isAttachingConnector()) {
                debugee = remoteLaunchAndAttachDebugee(vmm, classToExecute, classPath);
            } else if (argumentHandler.isListeningConnector()) {
                debugee = remoteLaunchAndListenDebugee(vmm, classToExecute, classPath);
            } else {
                throw new TestBug("Unexpected connector type for remote debugee launch mode"
                                  + argumentHandler.getConnectorType());
            }

        } else if (argumentHandler.isLaunchedManually()) {

            if (argumentHandler.isAttachingConnector()) {
                debugee = manualLaunchAndAttachDebugee(vmm, classToExecute, classPath);
            } else if (argumentHandler.isListeningConnector()) {
                debugee = manualLaunchAndListenDebugee(vmm, classToExecute, classPath);
            } else {
                throw new TestBug("Unexpected connector type for manual debugee launch mode"
                                  + argumentHandler.getConnectorType());
            }

        } else {
            throw new Failure("Unexpected debugee launching mode: " + argumentHandler.getLaunchMode());
        }

        return debugee;
    }

    /**
     * Launch debugee VM and establish JDI connection.
     * After launching debugee's output is redirected to Binder's log,
     * VMStart event is received and debuggee is initialized.
     *
     * @see #bindToDebugeeNoWait(String)
     */
    public Debugee bindToDebugee(String classToExecute) {
        Debugee debugee = bindToDebugeeNoWait(classToExecute);

        if(argumentHandler.getOptions().getProperty("traceAll") != null)
            debugee.VM().setDebugTraceMode(VirtualMachine.TRACE_ALL);

        long timeout = argumentHandler.getWaitTime() * 60 * 1000; // milliseconds

        display("Waiting for VM initialized");
        debugee.waitForVMInit(timeout);

        return debugee;
    }

    // -------------------------------------------------- //

    /**
     * Launch debugee locally via the default LaunchingConnector.
     */
    private Debugee localDefaultLaunchDebugee (VirtualMachineManager vmm,
                                                String classToExecute,
                                                String classPath) {
        display("Finding connector: " + "default" );
        LaunchingConnector connector = vmm.defaultConnector();
        Map<String,? extends Argument> arguments = setupLaunchingConnector(connector, classToExecute, classPath);

        VirtualMachine vm;
        try {
            display("Launching debugee");
            vm = connector.launch(arguments);
        } catch (IllegalConnectorArgumentsException e) {
            e.printStackTrace(log.getOutStream());
            throw new TestBug("Wrong connector arguments used to launch debuggee VM:\n\t" + e);
        } catch (VMStartException e) {
            e.printStackTrace(log.getOutStream());
            String msg = readVMStartExceptionOutput(e, log.getOutStream());
            throw new Failure("Caught exception while starting debugee VM:\n\t" + e + "\n" + msg);
        } catch (IOException e) {
            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while launching debugee VM:\n\t" + e);
        };

        Process process = vm.process();
        Debugee debugee = makeLocalDebugee(process);
        debugee.redirectOutput(log);
        debugee.setupVM(vm);

        return debugee;
    }


    /**
     * Launch debugee locally via the default LaunchingConnector.
     */
    private Debugee localLaunchDebugee (VirtualMachineManager vmm,
                                            String classToExecute,
                                            String classPath) {

        display("Finding connector: " + argumentHandler.getConnectorName() );
        LaunchingConnector connector =
            (LaunchingConnector) findConnector(argumentHandler.getConnectorName(),
                                                vmm.launchingConnectors());
        Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = setupLaunchingConnector(connector, classToExecute, classPath);

        VirtualMachine vm;
        try {
            display("Launching debugee");
            vm = connector.launch(arguments);
        } catch (IllegalConnectorArgumentsException e) {
            e.printStackTrace(log.getOutStream());
            throw new TestBug("Wrong connector arguments used to launch debuggee VM:\n\t" + e);
        } catch (VMStartException e) {
            e.printStackTrace(log.getOutStream());
            String msg = readVMStartExceptionOutput(e, log.getOutStream());
            throw new Failure("Caught exception while starting debugee VM:\n\t" + e + "\nProcess output:\n\t" + msg);
        } catch (IOException e) {
            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while launching debugee VM:\n\t" + e);
        };

        Process process = vm.process();
        Debugee debugee = makeLocalDebugee(process);
        debugee.redirectOutput(log);
        debugee.setupVM(vm);

        return debugee;
    }

    /**
     * Launch debugee locally via the RawLaunchingConnector.
     */
    private Debugee localRawLaunchDebugee (VirtualMachineManager vmm,
                                            String classToExecute,
                                            String classPath) {
        display("Finding connector: " + argumentHandler.getConnectorName() );
        LaunchingConnector connector =
            (LaunchingConnector) findConnector(argumentHandler.getConnectorName(),
                                                vmm.launchingConnectors());
        Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = setupRawLaunchingConnector(connector, classToExecute, classPath);

        VirtualMachine vm;
        try {
            display("Launching debugee");
            vm = connector.launch(arguments);
        } catch (IllegalConnectorArgumentsException e) {
            e.printStackTrace(log.getOutStream());
            throw new TestBug("Wrong connector arguments used to launch debuggee VM:\n\t" + e);
        } catch (VMStartException e) {
            e.printStackTrace(log.getOutStream());
            String msg = readVMStartExceptionOutput(e, log.getOutStream());
            throw new Failure("Caught exception while starting debugee VM:\n\t" + e + "\nProcess output:\n\t" + msg);
        } catch (IOException e) {
            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while launching debugee VM:\n\t" + e);
        };

        Process process = vm.process();
        Debugee debugee = makeLocalDebugee(process);
        debugee.redirectOutput(log);
        debugee.setupVM(vm);

        return debugee;
    }

    /**
     * Launch debugee VM locally as a local process and connect to it using
     * <code>AttachingConnector</code>.
     */
    private Debugee localLaunchAndAttachDebugee (VirtualMachineManager vmm,
                                                    String classToExecute,
                                                    String classPath) {
        display("FindingConnector: " + argumentHandler.getConnectorName() );
        AttachingConnector connector =
            (AttachingConnector) findConnector(argumentHandler.getConnectorName(),
                                                vmm.attachingConnectors());
        Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = setupAttachingConnector(connector, classToExecute, classPath);

        String address = makeTransportAddress();
        String[] cmdLineArgs = makeCommandLineArgs(classToExecute, address);
        String javaCmdLine = makeCommandLineString(classToExecute, address, "\"");

        display("Starting java process:\n\t" + javaCmdLine);
        Debugee debugee = startLocalDebugee(cmdLineArgs);
        debugee.redirectOutput(log);

        display("Attaching to debugee");
        VirtualMachine vm = null;
        IOException ioe = null;
        for (int i = 0; i < CONNECT_TRIES; i++) {
            try {
                vm = connector.attach(arguments);
                display("Debugee attached");
                debugee.setupVM(vm);
                return debugee;
            } catch (IOException e) {
                display("Attempt #" + i + " to connect to debugee VM failed:\n\t" + e);
                ioe = e;
                if (debugee.terminated()) {
                    throw new Failure("Unable to connect to debuggee VM: VM process is terminated");
                }
                try {
                    Thread.currentThread().sleep(CONNECT_TRY_DELAY);
                } catch (InterruptedException ie) {
                    ie.printStackTrace(log.getOutStream());
                    throw new Failure("Thread interrupted while pausing connection attempts:\n\t"
                                    + ie);
                }
            } catch (IllegalConnectorArgumentsException e) {
                e.printStackTrace(log.getOutStream());
                throw new TestBug("Wrong connector arguments used to attach to debuggee VM:\n\t" + e);
            }
        }
        throw new Failure("Unable to connect to debugee VM after " + CONNECT_TRIES
                        + " tries:\n\t" + ioe);
    }

    /**
     * Launch debugee VM locally as a local process and connect to it using
     * <code>ListeningConnector</code>.
     */
    private Debugee localLaunchAndListenDebugee (VirtualMachineManager vmm,
                                                    String classToExecute,
                                                    String classPath) {
        display("Finding connector: " + argumentHandler.getConnectorName() );
        ListeningConnector connector =
            (ListeningConnector) findConnector(argumentHandler.getConnectorName(),
                                                vmm.listeningConnectors());
        Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = setupListeningConnector(connector, classToExecute, classPath);

        String address = null;
        try {
            display("Listening for connection from debugee");
            address = connector.startListening(arguments);
        } catch (IllegalConnectorArgumentsException e) {
            e.printStackTrace(log.getOutStream());
            throw new TestBug("Wrong connector arguments used to listen debuggee VM:\n\t" + e);
        } catch (IOException e) {
            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while starting listening debugee VM:\n\t" + e);
        };

        String[] cmdLineArgs = makeCommandLineArgs(classToExecute, address);
        String javaCmdLine = makeCommandLineString(classToExecute, address, "\"");

        display("Starting java process:\n\t" + javaCmdLine);
        Debugee debugee = startLocalDebugee(cmdLineArgs);
        debugee.redirectOutput(log);

        display("Waiting for connection from debugee");
        VirtualMachine vm = null;
        IOException ioe = null;
        for (int i = 0; i < CONNECT_TRIES; i++) {
            try {
                vm = connector.accept(arguments);
                connector.stopListening(arguments);
                display("Debugee attached");
                debugee.setupVM(vm);
                return debugee;
            } catch (IOException e) {
                display("Attempt #" + i + " to listen debugee VM failed:\n\t" + e);
                ioe = e;
                if (debugee.terminated()) {
                    throw new Failure("Unable to connect to debuggee VM: VM process is terminated");
                }
                try {
                    Thread.currentThread().sleep(CONNECT_TRY_DELAY);
                } catch (InterruptedException ie) {
                    ie.printStackTrace(log.getOutStream());
                    throw new Failure("Thread interrupted while pausing connection attempts:\n\t"
                                    + ie);
                }
            } catch (IllegalConnectorArgumentsException e) {
                e.printStackTrace(log.getOutStream());
                throw new TestBug("Wrong connector arguments used to listen debuggee VM:\n\t" + e);
            }
        }
        throw new Failure("Unable to connect to debugee VM after " + CONNECT_TRIES
                        + " tries:\n\t" + ioe);
    }

    // -------------------------------------------------- //

    /**
     * Launch debugee VM remotely via <code>BindServer</code> and connect to it using
     * <code>AttachingConnector</code>.
     */
    private Debugee remoteLaunchAndAttachDebugee (VirtualMachineManager vmm,
                                                    String classToExecute,
                                                    String classPath) {
        display("Finding connector: " + argumentHandler.getConnectorName() );
        AttachingConnector connector =
            (AttachingConnector) findConnector(argumentHandler.getConnectorName(),
                                                vmm.attachingConnectors());

        Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = setupAttachingConnector(connector, classToExecute, classPath);

        String address = makeTransportAddress();
        String[] cmdLineArgs = makeCommandLineArgs(classToExecute, address);
        String javaCmdLine = makeCommandLineString(classToExecute, address, "\"");

        display("Starting remote java process:\n\t" + javaCmdLine);
        Debugee debugee = startRemoteDebugee(cmdLineArgs);

        display("Attaching to debugee");
        VirtualMachine vm;
        IOException ioe = null;
        for (int i = 0; i < CONNECT_TRIES; i++) {
            try {
                vm = connector.attach(arguments);
                display("Debugee attached");
                debugee.setupVM(vm);
                return debugee;
            } catch (IOException e) {
                display("Attempt #" + i + " to connect to debugee VM failed:\n\t" + e);
                ioe = e;
                if (debugee.terminated()) {
                    throw new Failure("Unable to connect to debuggee VM: VM process is terminated");
                }
                try {
                    Thread.currentThread().sleep(CONNECT_TRY_DELAY);
                } catch (InterruptedException ie) {
                    ie.printStackTrace(log.getOutStream());
                    throw new Failure("Thread interrupted while pausing connection attempts:\n\t"
                                    + ie);
                }
            } catch (IllegalConnectorArgumentsException e) {
                e.printStackTrace(log.getOutStream());
                throw new TestBug("Wrong connector arguments used to attach to debuggee VM:\n\t" + e);
            }
        }
        throw new Failure("Unable to connect to debugee VM after " + CONNECT_TRIES
                        + " tries:\n\t" + ioe);
    }

    /**
     * Launch debugee VM remotely via <code>BindServer</code> and connect to it using
     * <code>ListeningConnector</code>.
     */
    private Debugee remoteLaunchAndListenDebugee (VirtualMachineManager vmm,
                                                    String classToExecute,
                                                    String classPath) {
        display("Finding connector: " + argumentHandler.getConnectorName() );
        ListeningConnector connector =
            (ListeningConnector) findConnector(argumentHandler.getConnectorName(),
                                                vmm.listeningConnectors());
        Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = setupListeningConnector(connector, classToExecute, classPath);

        String address = null;
        try {
            display("Listening for connection from debugee");
            address = connector.startListening(arguments);
        } catch (IllegalConnectorArgumentsException e) {
            e.printStackTrace(log.getOutStream());
            throw new TestBug("Wrong connector arguments used to listen debuggee VM:\n\t" + e);
        } catch (IOException e) {
            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while starting listening debugee VM:\n\t" + e);
        };

        String[] cmdLineArgs = makeCommandLineArgs(classToExecute, address);
        String javaCmdLine = makeCommandLineString(classToExecute, address, "\"");

        display("Starting remote java process:\n\t" + javaCmdLine);
        Debugee debugee = startRemoteDebugee(cmdLineArgs);

        display("Waiting for connection from debugee");
        VirtualMachine vm;
        IOException ioe = null;
        for (int i = 0; i < CONNECT_TRIES; i++) {
            try {
                vm = connector.accept(arguments);
                connector.stopListening(arguments);
                display("Debugee attached");
                debugee.setupVM(vm);
                return debugee;
            } catch (IOException e) {
                display("Attempt #" + i + " to listen debugee VM failed:\n\t" + e);
                ioe = e;
                if (debugee.terminated()) {
                    throw new Failure("Unable to connect to debuggee VM: VM process is terminated");
                }
                try {
                    Thread.currentThread().sleep(CONNECT_TRY_DELAY);
                } catch (InterruptedException ie) {
                    ie.printStackTrace(log.getOutStream());
                    throw new Failure("Thread interrupted while pausing connection attempts:\n\t"
                                    + ie);
                }
            } catch (IllegalConnectorArgumentsException e) {
                e.printStackTrace(log.getOutStream());
                throw new TestBug("Wrong connector arguments used to listen debuggee VM:\n\t" + e);
            }
        }
        throw new Failure("Unable to connect to debugee VM after " + CONNECT_TRIES
                        + " tries:\n\t" + ioe);
    }

    // -------------------------------------------------- //

    /**
     * Prompt to manually launch debugee VM and connect to it using
     * <code>AttachingConnector</code>.
     */
    private Debugee manualLaunchAndAttachDebugee (VirtualMachineManager vmm,
                                                    String classToExecute,
                                                    String classPath) {
        display("Finding connector: " + argumentHandler.getConnectorName() );
        AttachingConnector connector =
            (AttachingConnector) findConnector(argumentHandler.getConnectorName(),
                                                vmm.attachingConnectors());
        Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = setupAttachingConnector(connector, classToExecute, classPath);

        String address = makeTransportAddress();
        String javaCmdLine = makeCommandLineString(classToExecute, address, "\"");

        display("Starting manual java process:\n\t" + javaCmdLine);
        ManualLaunchedDebugee debugee = startManualDebugee(javaCmdLine);

        VirtualMachine vm;
        try {
            display("Attaching to debugee");
            vm = connector.attach(arguments);
        } catch (IllegalConnectorArgumentsException e) {
            e.printStackTrace(log.getOutStream());
            throw new TestBug("Wrong connector arguments used to attach to debuggee VM:\n\t" + e);
        } catch (IOException e) {
            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while attaching to debugee VM:\n\t" + e);
        };
        display("Debugee attached");

        debugee.setupVM(vm);
        return debugee;
    }

    /**
     * Prompt to manually launch debugee VM and connect to it using
     * <code>ListeningConnector</code>.
     */
    private Debugee manualLaunchAndListenDebugee (VirtualMachineManager vmm,
                                                    String classToExecute,
                                                    String classPath) {
        display("Finding connector: " + argumentHandler.getConnectorName() );
        ListeningConnector connector =
            (ListeningConnector) findConnector(argumentHandler.getConnectorName(),
                                                vmm.listeningConnectors());
        Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = setupListeningConnector(connector, classToExecute, classPath);

        VirtualMachine vm;
        try {
            display("Listening for connection from debugee");
            String address = connector.startListening(arguments);
            String javaCmdLine = makeCommandLineString(classToExecute, address, "\"");
            display("Starting manual java process:\n\t" + javaCmdLine);
            ManualLaunchedDebugee debugee = startManualDebugee(javaCmdLine);
            display("Waiting for connection from debugee");
            vm = connector.accept(arguments);
            display("Debugee attached");
            connector.stopListening(arguments);
            debugee.setupVM(vm);
            return debugee;
        } catch (IllegalConnectorArgumentsException e) {
            e.printStackTrace(log.getOutStream());
            throw new TestBug("Wrong connector arguments used to listen debuggee VM:\n\t" + e);
        } catch (IOException e) {
            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while listening to debugee VM:\n\t" + e);
        }
    }

    // -------------------------------------------------- //

    /**
     * Make proper arguments for LaunchingConnector.
     */
    private Map<String,? extends Argument> setupLaunchingConnector(LaunchingConnector connector,
                                                String classToExecute,
                                                String classPath) {
        display("LaunchingConnector:");
        display("    name: " + connector.name());
        display("    description: " + connector.description());
        display("    transport: " + connector.transport());

        Hashtable<String,? extends Argument> arguments = new Hashtable<String,Argument>(connector.defaultArguments());

        Connector.Argument arg;

        arg = (Connector.StringArgument) arguments.get("quote");
        String quote = arg.value();

        String cmdline = classToExecute + " " +
                ArgumentHandler.joinArguments(argumentHandler.getRawArguments(), quote);

        arg = (Connector.StringArgument) arguments.get("main");
        arg.setValue(cmdline);

        if (! argumentHandler.willDebugeeSuspended()) {
            Connector.BooleanArgument barg = (Connector.BooleanArgument) arguments.get("suspend");
            barg.setValue(true);
        }

/*
        if (! argumentHandler.isJVMDIStrictMode()) {
            arg = (Connector.StringArgument) arguments.get("options");
            arg.setValue("strict=y");
        }
 */

        if (! argumentHandler.isDefaultDebugeeJavaHome()) {
            arg = (Connector.StringArgument) arguments.get("home");
            arg.setValue(argumentHandler.getDebugeeJavaHome());
        }

        if (! argumentHandler.isDefaultLaunchExecName()) {
            arg = (Connector.StringArgument) arguments.get("vmexec");
            arg.setValue(argumentHandler.getLaunchExecName());
        }

        String vmArgs = "";

        String vmUserArgs = argumentHandler.getLaunchOptions();

        if (vmUserArgs != null) {
            vmArgs = vmUserArgs;
        }

/*
        if (classPath != null) {
            vmArgs += " -classpath " + quote + classPath + quote;
        }
 */

        if (vmArgs.length() > 0) {
            arg = (Connector.StringArgument) arguments.get("options");
            arg.setValue(vmArgs);
        }

        display("Connector arguments:");
        Iterator iterator = arguments.values().iterator();
        while (iterator.hasNext()) {
            display("    " + iterator.next());
        }
        return arguments;
    }

    /**
     * Make proper arguments for RawLaunchingConnector.
     */
    private Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> setupRawLaunchingConnector(LaunchingConnector connector,
                                                String classToExecute,
                                                String classPath) {
        display("RawLaunchingConnector:");
        display("    name: " + connector.name());
        display("    description: " + connector.description());
        display("    transport: " + connector.transport());

        Hashtable<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = new Hashtable<java.lang.String, com.sun.jdi.connect.Connector.Argument>(connector.defaultArguments());

        String connectorAddress;
        String vmAddress;

        if (argumentHandler.isSocketTransport()) {
            connectorAddress = argumentHandler.getTransportPort();
            vmAddress = argumentHandler.getDebugeeHost()
                        + ":" + argumentHandler.getTransportPort();
        } else if (argumentHandler.isShmemTransport() ) {
            connectorAddress = argumentHandler.getTransportSharedName();
            vmAddress=connectorAddress;
        } else {
            throw new TestBug("Undefined transport type for AttachingConnector");
        }

        Connector.Argument arg;

        arg = (Connector.StringArgument) arguments.get("quote");
        String quote = arg.value();

        String javaCmdLine = makeCommandLineString(classToExecute, quote);

        arg = (Connector.StringArgument) arguments.get("command");
        arg.setValue(javaCmdLine);

        arg = (Connector.StringArgument) arguments.get("address");
        arg.setValue(connectorAddress);

        display("Connector arguments:");
        Iterator iterator = arguments.values().iterator();
        while (iterator.hasNext()) {
            display("    " + iterator.next());
        }
        return arguments;
    }

    /**
     * Make proper arguments for AttachingConnector.
     */
    private Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> setupAttachingConnector(AttachingConnector connector,
                                                String classToExecute,
                                                String classPath) {
        display("AttachingConnector:");
        display("    name: " + connector.name());
        display("    description: " + connector.description());
        display("    transport: " + connector.transport());

        Hashtable<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = new Hashtable<java.lang.String,com.sun.jdi.connect.Connector.Argument>(connector.defaultArguments());

        Connector.Argument arg;
        if (argumentHandler.isSocketTransport()) {
            arg = (Connector.StringArgument) arguments.get("hostname");
            arg.setValue(argumentHandler.getDebugeeHost());
            Connector.IntegerArgument iarg = (Connector.IntegerArgument) arguments.get("port");
            iarg.setValue(argumentHandler.getTransportPortNumber());
        } else {
            arg = (Connector.StringArgument) arguments.get("name");
            arg.setValue(argumentHandler.getTransportSharedName());
        }

        display("Connector arguments:");
        Iterator iterator = arguments.values().iterator();
        while (iterator.hasNext()) {
            display("    " + iterator.next());
        }
        return arguments;
    }

    /**
     * Make proper arguments for ListeningConnector.
     */
    private Map<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> setupListeningConnector(ListeningConnector connector,
                                                String classToExecute,
                                                String classPath) {
        display("ListeningConnector:");
        display("    name: " + connector.name());
        display("    description: " + connector.description());
        display("    transport: " + connector.transport());

        Hashtable<java.lang.String,? extends com.sun.jdi.connect.Connector.Argument> arguments = new Hashtable<java.lang.String,com.sun.jdi.connect.Connector.Argument>(connector.defaultArguments());

        Connector.Argument arg;
        if (argumentHandler.isSocketTransport()) {
            if (!argumentHandler.isTransportAddressDynamic()) {
                int port = argumentHandler.getTransportPortNumber();
                Connector.IntegerArgument iarg = (Connector.IntegerArgument) arguments.get("port");
                iarg.setValue(port);
            }
        } else {
            String sharedName = argumentHandler.getTransportSharedName();
            arg = (Connector.StringArgument) arguments.get("name");
            arg.setValue(sharedName);
        }

        display("Connector arguments:");
        Iterator iterator = arguments.values().iterator();
        while (iterator.hasNext()) {
            display("    " + iterator.next());
        }
        return arguments;
    }

    // -------------------------------------------------- //

    /**
     * Find connector by name from given connectors list.
     */
    private Connector findConnector(String connectorName, List connectors) {
        Iterator iter = connectors.iterator();

        while (iter.hasNext()) {
            Connector connector = (Connector) iter.next();
            if (connector.name().equals(connectorName)) {
                return connector;
            }
        }
        throw new Failure("JDI connector not found: " + connectorName);
    }

    // -------------------------------------------------- //

    /**
     * Launch local debuggee process with specified command line arguments
     * and make initial <code>Debugee</code> mirror.
     */
    protected Debugee startLocalDebugee(String[] cmdArgs) {
        Process process = null;

        try {
            process = launchProcess(cmdArgs);
        } catch (IOException e) {
            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while launching local debuggee VM process:\n\t"
                            + e);
        }

        return makeLocalDebugee(process);
    }

    /**
     * Launch remote debuggee process with specified command line arguments
     * and make initial <code>Debugee</code> mirror.
     */
    protected RemoteLaunchedDebugee startRemoteDebugee(String[] cmdArgs) {
        try {
            launchRemoteProcess(cmdArgs);
        } catch (IOException e) {
            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while launching remote debuggee VM process:\n\t"
                            + e);
        }

        RemoteLaunchedDebugee debugee = new RemoteLaunchedDebugee(this);

        Finalizer finalizer = new Finalizer(debugee);
        finalizer.activate();

        return debugee;
    }

    /**
     * Launch manual debuggee process with specified command line arguments
     * and make initial <code>Debugee</code> mirror.
     */
    protected ManualLaunchedDebugee startManualDebugee(String cmd) {
        ManualLaunchedDebugee debugee = new ManualLaunchedDebugee(this);
        debugee.launchDebugee(cmd);

        Finalizer finalizer = new Finalizer(debugee);
        finalizer.activate();

        return debugee;
    }

    public static String readVMStartExceptionOutput(VMStartException e, PrintStream log) {
        StringBuffer msg = new StringBuffer();
        try (InputStream is = e.process().getInputStream()) {
            msg.append("\tstdout: ").append(new String(readAllBytes(is))).append('\n');
        } catch (IOException e1) {
            log.println("Could not read normal output from launched process:" + e1);
        }
        try (InputStream is = e.process().getErrorStream()) {
            msg.append("\tstderr: ").append(new String(readAllBytes(is)));
        } catch (IOException e1) {
            log.println("Could not read error output from launched process:" + e1);
        }
        return msg.toString();
    }

    /**
     * Copied from the JDK 9 implementation in InputStream.java
     */
    private static byte[] readAllBytes(InputStream is) throws IOException {
        final int DEFAULT_BUFFER_SIZE = 8192;
        final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;

        byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
        int capacity = buf.length;
        int nread = 0;
        int n;
        for (;;) {
            // read to EOF which may read more or less than initial buffer size
            while ((n = is.read(buf, nread, capacity - nread)) > 0)
                nread += n;

            // if the last call to read returned -1, then we're done
            if (n < 0)
                break;

            // need to allocate a larger buffer
            if (capacity <= MAX_BUFFER_SIZE - capacity) {
                capacity = capacity << 1;
            } else {
                if (capacity == MAX_BUFFER_SIZE)
                    throw new OutOfMemoryError("Required array size too large");
                capacity = MAX_BUFFER_SIZE;
            }
            buf = Arrays.copyOf(buf, capacity);
        }
        return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
    }

}


/**
 * Mirror of locally launched debugee.
 */
final class LocalLaunchedDebugee extends Debugee {

    /** Enwrap the locally started VM process. */
    public LocalLaunchedDebugee (Process process, Binder binder) {
        super(binder);
        this.process = process;
        checkTermination = true;
    }

    // ---------------------------------------------- //

    /** Return exit status of the debugee VM. */
    public int getStatus () {
        return process.exitValue();
    }

    /** Check whether the debugee VM has been terminated. */
    public boolean terminated () {
        if (process == null)
            return true;

        try {
            int value = process.exitValue();
            return true;
        } catch (IllegalThreadStateException e) {
            return false;
        }
    }

    // ---------------------------------------------- //

    /** Kill the debugee VM. */
    protected void killDebugee () {
        super.killDebugee();
        if (!terminated()) {
            log.display("Killing debugee VM process");
            process.destroy();
        }
    }

    /** Wait until the debugee VM shutdown or crash. */
    protected int waitForDebugee () throws InterruptedException {
        int code = process.waitFor();
        return code;
    }

    /** Get a pipe to write to the debugee's stdin stream. */
    protected OutputStream getInPipe () {
        return process.getOutputStream();
    }

    /** Get a pipe to read the debugee's stdout stream. */
    protected InputStream getOutPipe () {
        return process.getInputStream();
    }

    /** Get a pipe to read the debugee's stderr stream. */
    protected InputStream getErrPipe () {
        return process.getErrorStream();
    }
}


/**
 * Mirror of remotely launched debugee.
 */
final class RemoteLaunchedDebugee extends Debugee {

    /** Enwrap the remotely started VM process. */
    public RemoteLaunchedDebugee (Binder binder) {
        super(binder);
    }

    // ---------------------------------------------- //

    /** Return exit status of the debugee VM. */
    public int getStatus () {
        return binder.getRemoteProcessStatus();
    }

    /** Check whether the debugee VM has been terminated. */
    public boolean terminated () {
        return binder.isRemoteProcessTerminated();
    }

    // ---------------------------------------------- //

    /** Kill the debugee VM. */
    protected void killDebugee () {
        super.killDebugee();
        if (!terminated()) {
            binder.killRemoteProcess();
        }
    }

    /** Wait until the debugee VM shutdown or crash. */
    protected int waitForDebugee () {
        return binder.waitForRemoteProcess();
    }

    /** Get a pipe to write to the debugee's stdin stream. */
    protected OutputStream getInPipe () {
        return null;
    }

    /** Get a pipe to read the debugee's stdout stream. */
    protected InputStream getOutPipe () {
        return null;
    }

    /** Get a pipe to read the debugee's stderr stream. */
    protected InputStream getErrPipe () {
        return null;
    }

    public void redirectStdout(OutputStream out) {
    }

    public void redirectStdout(Log log, String prefix) {
    }

    public void redirectStderr(OutputStream out) {
    }

    public void redirectStderr(Log log, String prefix) {
    }
}


/**
 * Mirror of manually launched debugee.
 */
final class ManualLaunchedDebugee extends Debugee {
    /** Enwrap the manually started VM process. */
    public ManualLaunchedDebugee (Binder binder) {
        super(binder);
        makeInputReader();
    }

    // ---------------------------------------------- //

    private int exitCode = 0;
    private boolean finished = false;
    private static BufferedReader bin = null;

    public void launchDebugee(String commandLine) {
        makeInputReader();

        putMessage("Launch target VM using such command line:\n"
                    + commandLine);
        String answer = askQuestion("Has the VM successfully started? (yes/no)", "yes");
        for ( ; ; ) {
            if (answer.equals("yes"))
                break;
            if (answer.equals("no"))
                throw new Failure ("Unable to manually launch debugee VM");
            answer = askQuestion("Wrong answer. Please type yes or no", "yes");
        }
    }

    private static void makeInputReader() {
        if (bin == null) {
            bin = new BufferedReader(new InputStreamReader(System.in));
        }
    }

    private static void destroyInputReader() {
        if (bin != null) {
            try {
                bin.close();
            } catch (IOException e) {
//                e.printStackTrace(log.getOutStream());
                throw new Failure("Caught exception while closing input stream:\n\t" + e);
            }
            bin = null;
        }
    }

    private static void putMessage(String msg) {
        System.out.println("\n>>> " + msg);
    }

    private static String askQuestion(String question, String defaultAnswer) {
        try {
            System.out.print("\n>>> " + question);
            System.out.print(" [" + defaultAnswer + "] ");
            System.out.flush();
            String answer = bin.readLine();
            if (answer.equals(""))
                return defaultAnswer;
            return answer;
        } catch (IOException e) {
//            e.printStackTrace(log.getOutStream());
            throw new Failure("Caught exception while reading answer:\n\t" + e);
        }
    }

    /** Return exit status of the debugee VM. */
    public int getStatus () {
        if (! finished) {
            throw new Failure("Unable to get status of debugee VM: process still alive");
        }
        return exitCode;
    }

    /** Check whether the debugee VM has been terminated. */
    public boolean terminated () {
        return finished;
    }

    // ---------------------------------------------- //

    /** Kill the debugee VM. */
    protected void killDebugee () {
        super.killDebugee();
        if (!terminated()) {
            putMessage("Kill launched VM");
            String answer = askQuestion("Has the VM successfully terminated? (yes/no)", "yes");
            for ( ; ; ) {
                if (answer.equals("yes")) {
                    finished = true;
                    break;
                }
                if (answer.equals("no"))
                    throw new Failure ("Unable to manually kill debugee VM");
                answer = askQuestion("Wrong answer. Please type yes or no", "yes");
            }
        }
    }

    /** Wait until the debugee VM shutdown or crash. */
    protected int waitForDebugee () {
        putMessage("Wait for launched VM to exit.");
        String answer = askQuestion("What is VM exit code?", "95");
        for ( ; ; ) {
            try {
                exitCode = Integer.parseInt(answer);
                break;
            } catch (NumberFormatException e) {
                answer = askQuestion("Wrong answer. Please type integer value", "95");
            }
        }
        finished = true;
        return exitCode;
    }

    /** Get a pipe to write to the debugee's stdin stream. */
    protected OutputStream getInPipe () {
        return null;
    }

    /** Get a pipe to read the debugee's stdout stream. */
    protected InputStream getOutPipe () {
        return null;
    }

    /** Get a pipe to read the debugee's stderr stream. */
    protected InputStream getErrPipe () {
        return null;
    }

    public void redirectStdout(OutputStream out) {
    }

    public void redirectStdout(Log log, String prefix) {
    }

    public void redirectStderr(OutputStream out) {
    }

    public void redirectStderr(Log log, String prefix) {
    }

    public void close() {
        destroyInputReader();
        super.close();
    }
}