-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlixDebugAdapter.java
More file actions
1399 lines (1281 loc) · 58.5 KB
/
Copy pathFlixDebugAdapter.java
File metadata and controls
1399 lines (1281 loc) · 58.5 KB
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
import com.sun.jdi.*;
import com.sun.jdi.connect.AttachingConnector;
import com.sun.jdi.connect.Connector;
import com.sun.jdi.event.*;
import com.sun.jdi.request.BreakpointRequest;
import com.sun.jdi.request.ClassPrepareRequest;
import com.sun.jdi.request.EventRequest;
import com.sun.jdi.request.EventRequestManager;
import com.sun.jdi.request.StepRequest;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A minimal Debug Adapter Protocol (DAP) server that debugs a running Flix
* program by attaching to its JVM over JDWP and resolving breakpoints
* against .flix source lines via the "Flix" stratum that a fork of Flix
* (github.com/wstein/flix-fork, --Xdebug) embeds as a JSR-45
* SourceDebugExtension.
*
* This intentionally supports only the handful of requests needed to set a
* line breakpoint, hit it, and inspect the call stack/locals -- it is not a
* general-purpose Java debugger.
*/
public class FlixDebugAdapter {
/**
* VS Code (and the standalone {@code dap_client_test.py}) launch this adapter as a child
* process and speak DAP directly over its stdin/stdout, so that stays the default with no
* arguments. IntelliJ's LSP4IJ, by contrast, has no stdio DAP transport at all -- its
* DebugAdapterDescriptor/ServerReadyConfig machinery only ever connects to a DAP server over
* a TCP socket (confirmed by reading LSP4IJ's own source, not just its docs) -- so "--port
* <n>" opens a one-shot server socket on that exact port instead and speaks DAP there once a
* single client connects. Both modes share every line of protocol/JDI handling below.
*/
public static void main(String[] args) throws Exception {
Integer port = null;
for (int i = 0; i < args.length; i++) {
if ("--port".equals(args[i]) && i + 1 < args.length) {
port = Integer.parseInt(args[++i]);
}
}
if (port != null) {
runOverSocket(port);
} else {
new FlixDebugAdapter(System.in, System.out).run();
}
}
private static void runOverSocket(int port) throws Exception {
try (ServerSocket server = new ServerSocket(port)) {
// LSP4IJ's DebugAdapterDescriptor picks this exact port itself (via its "${port}"
// command-line substitution) before launching us, so it already knows where to
// connect; this line is only a human-visible/log-matchable readiness signal, not
// something the port number is parsed out of.
System.out.println("Listening for DAP client on port " + port);
System.out.flush();
Socket client = server.accept();
new FlixDebugAdapter(client.getInputStream(), client.getOutputStream()).run();
}
}
// ------------------------------------------------------------------
// DAP transport
// ------------------------------------------------------------------
private final InputStream in;
private final PrintStream out;
private final AtomicInteger seq = new AtomicInteger(1);
FlixDebugAdapter(InputStream in, OutputStream out) throws UnsupportedEncodingException {
this.in = in;
this.out = new PrintStream(out, true, "UTF-8");
}
private void run() throws IOException {
while (true) {
Map<String, Object> msg = readMessage();
if (msg == null) return;
String type = (String) msg.get("type");
if ("request".equals(type)) {
handleRequest(msg);
}
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> readMessage() throws IOException {
int contentLength = -1;
while (true) {
String line = readHeaderLine();
if (line == null) return null;
if (line.isEmpty()) break;
int colon = line.indexOf(':');
if (colon > 0) {
String name = line.substring(0, colon).trim();
String value = line.substring(colon + 1).trim();
if (name.equalsIgnoreCase("Content-Length")) {
contentLength = Integer.parseInt(value);
}
}
}
if (contentLength < 0) return null;
byte[] body = new byte[contentLength];
int read = 0;
while (read < contentLength) {
int n = in.read(body, read, contentLength - read);
if (n < 0) return null;
read += n;
}
String json = new String(body, StandardCharsets.UTF_8);
Object parsed = Json.parse(json);
return (Map<String, Object>) parsed;
}
private String readHeaderLine() throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int prev = -1;
int c;
while ((c = in.read()) != -1) {
if (prev == '\r' && c == '\n') {
byte[] bytes = buf.toByteArray();
return new String(bytes, 0, bytes.length - 1, StandardCharsets.UTF_8);
}
buf.write(c);
prev = c;
}
return buf.size() == 0 ? null : buf.toString(StandardCharsets.UTF_8);
}
private synchronized void send(Map<String, Object> msg) {
msg.put("seq", seq.getAndIncrement());
String json = Json.write(msg);
byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
out.print("Content-Length: " + bytes.length + "\r\n\r\n");
out.write(bytes, 0, bytes.length);
out.flush();
}
private void sendResponse(Map<String, Object> request, boolean success, Object body) {
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("type", "response");
resp.put("request_seq", request.get("seq"));
resp.put("success", success);
resp.put("command", request.get("command"));
if (body != null) resp.put("body", body);
send(resp);
}
private void sendErrorResponse(Map<String, Object> request, String message) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("error", Map.of("id", 1, "format", message));
sendResponse(request, false, body);
}
private void sendEvent(String event, Object body) {
Map<String, Object> msg = new LinkedHashMap<>();
msg.put("type", "event");
msg.put("event", event);
if (body != null) msg.put("body", body);
send(msg);
}
// ------------------------------------------------------------------
// Request dispatch
// ------------------------------------------------------------------
private VirtualMachine vm;
private Thread eventThread;
/** Namespaces with no user code in this project -- excluded both from class-prepare watching
* (onAttach) and from stepping (onStep), so e.g. java.lang.invoke.LambdaForm$DMH synthetic
* frames (generated for invokedynamic call sites, which Flix's compiled lambdas use heavily)
* are stepped over instead of surfacing as a source-less frame VS Code can't display. */
private static final String[] EXCLUDED_PACKAGES = {
"java.*", "javax.*", "jdk.*", "sun.*", "com.sun.*", "scala.*",
"dev.flix.runtime.*", "ca.uwaterloo.*", "com.*", "org.*", "net.*"};
@SuppressWarnings("unchecked")
private void handleRequest(Map<String, Object> req) {
String command = (String) req.get("command");
Map<String, Object> args = (Map<String, Object>) req.getOrDefault("arguments", Map.of());
try {
switch (command) {
case "initialize" -> onInitialize(req);
case "attach" -> onAttach(req, args);
// A DAP client's choice of "launch" vs. "attach" doesn't reliably reflect what it
// wants us to do: LSP4IJ's DAPClient always sends "launch", regardless of whether
// its own run configuration is configured as Attach or Launch, because *it* always
// spawns this adapter as a process either way (see DAPRunConfigurationOptions).
// So "launch" requests are disambiguated by argument shape instead of by command
// name: a "program" argument means spawn `flix run --Xdebug` ourselves (real
// launch semantics); its absence means these are attach-shaped arguments
// (hostName/port) that merely arrived over the "launch" verb.
case "launch" -> onLaunchOrAttach(req, args);
case "setBreakpoints" -> onSetBreakpoints(req, args);
case "configurationDone" -> onConfigurationDone(req);
case "threads" -> onThreads(req);
case "stackTrace" -> onStackTrace(req, args);
case "scopes" -> onScopes(req, args);
case "variables" -> onVariables(req, args);
case "evaluate" -> onEvaluate(req, args);
case "continue" -> onContinue(req);
case "next" -> onStep(req, args, StepRequest.STEP_OVER);
case "stepIn" -> onStep(req, args, StepRequest.STEP_INTO);
case "stepOut" -> onStep(req, args, StepRequest.STEP_OUT);
case "pause" -> onPause(req);
case "disconnect" -> onDisconnect(req);
default -> sendResponse(req, true, null);
}
} catch (Exception e) {
sendErrorResponse(req, command + " failed: " + e);
}
}
private void onInitialize(Map<String, Object> req) {
Map<String, Object> caps = new LinkedHashMap<>();
caps.put("supportsConfigurationDoneRequest", true);
sendResponse(req, true, caps);
sendEvent("initialized", null);
}
// ------------------------------------------------------------------
// Attach
// ------------------------------------------------------------------
private void onAttach(Map<String, Object> req, Map<String, Object> args) throws Exception {
doAttach(args);
sendResponse(req, true, null);
}
private void onLaunchOrAttach(Map<String, Object> req, Map<String, Object> args) throws Exception {
if (args.containsKey("program")) {
onLaunch(req, args);
} else {
onAttach(req, args);
}
}
/** Attaches to an already-running --Xdebug JVM's JDWP port; shared by both a real "attach"
* request and a "launch" request that spawned that JVM itself (see onLaunch). Sends no
* response of its own since onLaunch's retry loop needs to catch and retry a failed attempt
* before the JVM's JDWP listener comes up. */
private void doAttach(Map<String, Object> args) throws Exception {
String host = String.valueOf(args.getOrDefault("hostName", "localhost"));
int port = ((Number) args.getOrDefault("port", 5005)).intValue();
AttachingConnector connector = null;
for (Connector c : Bootstrap.virtualMachineManager().attachingConnectors()) {
if (c.transport() != null && "dt_socket".equals(c.transport().name())) {
connector = (AttachingConnector) c;
break;
}
}
if (connector == null) throw new IllegalStateException("no dt_socket attaching connector available");
Map<String, Connector.Argument> cargs = connector.defaultArguments();
cargs.get("hostname").setValue(host);
cargs.get("port").setValue(String.valueOf(port));
vm = connector.attach(cargs);
// Root and one-segment Flix namespaces generate implementation classes in dev.flix.gen;
// deeper namespaces generate them beside their facades (for example Acme.Api$Def$foo).
// The exclusions below leave generated user code visible while filtering JVM and compiler
// classes that would make class-prepare watching slow under SUSPEND_ALL.
// Without this, watching every class the whole JVM loads (including Flix's own Scala
// compiler/runtime) makes startup extremely slow under SUSPEND_ALL.
EventRequestManager erm = vm.eventRequestManager();
ClassPrepareRequest cpr = erm.createClassPrepareRequest();
for (String pattern : EXCLUDED_PACKAGES) {
cpr.addClassExclusionFilter(pattern);
}
cpr.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
cpr.enable();
eventThread = new Thread(this::eventLoop, "flix-debug-jdi-events");
eventThread.setDaemon(true);
eventThread.start();
}
// ------------------------------------------------------------------
// Launch
// ------------------------------------------------------------------
/** Non-null only for a "launch" session, i.e. one where this adapter spawned the target JVM
* itself rather than attaching to one someone else started -- used by onDisconnect to decide
* whether stopping the debug session should also kill the target process. */
private Process launchedProcess;
/**
* Spawns `flix run --Xdebug` (or a caller-supplied command) itself with a JDWP agent
* listening on a freshly-picked free port, then attaches to it the same way onAttach would --
* closing the "attach-only" gap where a target JVM had to already be running, suspended,
* before this adapter could do anything.
*
* Required argument: "program", a path to the .flix file or project directory to run (used
* to locate the project root, by walking up for the nearest flix.toml). Optional arguments:
* "entryPoint" (Flix --entrypoint, if not the default main()), "cwd" (overrides the located
* project root), "flixCommand" (the command used to invoke flix, as a list of strings;
* defaults to the FLIX_DEBUG_COMMAND environment variable if set, then ["flix"] -- e.g.
* flix-lab's launch.json points this at scripts/flix-fork explicitly, since a plain `flix` on
* PATH wouldn't have --Xdebug support, but DAP clients with no way to set a per-request
* argument (LSP4IJ's generic run configuration UI has no field for this) can still override
* the default via that environment variable instead), and "args" (extra arguments passed
* through to the running program).
*/
private void onLaunch(Map<String, Object> req, Map<String, Object> args) throws Exception {
String program = String.valueOf(args.get("program"));
File programFile = new File(program);
File startDir = programFile.isDirectory() ? programFile : programFile.getParentFile();
if (startDir == null) startDir = new File(".");
File cwd = args.get("cwd") != null ? new File(String.valueOf(args.get("cwd"))) : findProjectRoot(startDir);
List<String> command = new ArrayList<>();
if (args.get("flixCommand") instanceof List<?> flixCommand && !flixCommand.isEmpty()) {
for (Object o : flixCommand) command.add(String.valueOf(o));
} else {
String envCommand = System.getenv("FLIX_DEBUG_COMMAND");
command.add(envCommand != null && !envCommand.isBlank() ? envCommand : "flix");
}
command.add("run");
command.add("--Xdebug");
command.add("--yes");
Object entryPoint = args.get("entryPoint");
if (entryPoint != null && !String.valueOf(entryPoint).isBlank()) {
command.add("--entrypoint");
command.add(String.valueOf(entryPoint));
}
if (args.get("args") instanceof List<?> programArgs) {
for (Object o : programArgs) command.add(String.valueOf(o));
}
int port = findFreePort();
ProcessBuilder pb = new ProcessBuilder(command);
pb.directory(cwd);
pb.redirectErrorStream(true);
String existingOpts = System.getenv().getOrDefault("JAVA_TOOL_OPTIONS", "");
pb.environment().put("JAVA_TOOL_OPTIONS",
(existingOpts.isBlank() ? "" : existingOpts + " ")
+ "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:" + port);
debug("launching: " + String.join(" ", command) + " (cwd=" + cwd + ", JDWP port=" + port + ")");
try {
launchedProcess = pb.start();
} catch (IOException e) {
sendErrorResponse(req, "failed to start '" + String.join(" ", command) + "' in " + cwd + ": " + e.getMessage());
return;
}
Thread pump = new Thread(() -> pumpOutput(launchedProcess), "flix-debug-launch-output");
pump.setDaemon(true);
pump.start();
Map<String, Object> attachArgs = new LinkedHashMap<>();
attachArgs.put("hostName", "localhost");
attachArgs.put("port", port);
// The target JVM's JDWP listener takes a moment to come up after the process starts, so
// retry the attach instead of racing it with a single attempt. A refused connection here
// never reaches the JVM's JDWP server at all, so unlike probing the port with a bare
// socket first, this can't accidentally consume the one-shot accept a suspend=y listener
// grants its real debugger connection.
long deadline = System.currentTimeMillis() + 30_000;
Exception lastError = null;
while (System.currentTimeMillis() < deadline) {
if (!launchedProcess.isAlive()) {
sendErrorResponse(req, "flix process exited before a debugger could attach (exit code "
+ launchedProcess.exitValue() + "); see the Debug Console for its output");
return;
}
try {
doAttach(attachArgs);
lastError = null;
break;
} catch (Exception e) {
lastError = e;
Thread.sleep(200);
}
}
if (lastError != null) {
sendErrorResponse(req, "failed to attach to the launched flix process: " + lastError);
return;
}
sendResponse(req, true, null);
}
private void pumpOutput(Process process) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("category", "console");
body.put("output", line + "\n");
sendEvent("output", body);
}
} catch (IOException ignored) {
}
}
private static int findFreePort() throws IOException {
try (ServerSocket probe = new ServerSocket(0)) {
return probe.getLocalPort();
}
}
private static File findProjectRoot(File start) {
for (File dir = start; dir != null; dir = dir.getParentFile()) {
if (new File(dir, "flix.toml").isFile()) return dir;
}
return start;
}
private void onConfigurationDone(Map<String, Object> req) {
sendResponse(req, true, null);
// The target JVM is suspended at startup (JDWP suspend=y) so that
// breakpoints set here bind before any user code runs. Resume it
// now that configuration (breakpoints, etc.) is done.
if (vm != null) vm.resume();
}
// ------------------------------------------------------------------
// Breakpoints
// ------------------------------------------------------------------
/** A breakpoint requested for a source file, not yet necessarily resolved to a JDI location. */
private static final class PendingBreakpoint {
final int id;
final int line;
boolean verified;
PendingBreakpoint(int id, int line) { this.id = id; this.line = line; }
}
/** file path (as given by the client) -> requested lines, replaced wholesale on each setBreakpoints call. */
private final Map<String, List<PendingBreakpoint>> pendingByPath = new LinkedHashMap<>();
/** file path -> the BreakpointRequests we created for it, so a later setBreakpoints call can clear them. */
private final Map<String, List<BreakpointRequest>> requestsByPath = new LinkedHashMap<>();
private int nextBreakpointId = 1;
@SuppressWarnings("unchecked")
private void onSetBreakpoints(Map<String, Object> req, Map<String, Object> args) {
Map<String, Object> source = (Map<String, Object>) args.get("source");
String path = String.valueOf(source.get("path"));
List<Map<String, Object>> breakpoints = (List<Map<String, Object>>) args.getOrDefault("breakpoints", List.of());
EventRequestManager erm = vm.eventRequestManager();
for (BreakpointRequest r : requestsByPath.getOrDefault(path, List.of())) {
erm.deleteEventRequest(r);
}
requestsByPath.put(path, new ArrayList<>());
List<PendingBreakpoint> pending = new ArrayList<>();
List<Object> resultBreakpoints = new ArrayList<>();
for (Map<String, Object> bp : breakpoints) {
int line = ((Number) bp.get("line")).intValue();
pending.add(new PendingBreakpoint(nextBreakpointId++, line));
}
pendingByPath.put(path, pending);
boolean[] resolved = new boolean[pending.size()];
if (vm != null) {
for (ReferenceType rt : vm.allClasses()) {
resolveBreakpointsIn(rt, path, pending, resolved, false);
}
}
for (int i = 0; i < pending.size(); i++) {
pending.get(i).verified = resolved[i];
Map<String, Object> b = new LinkedHashMap<>();
b.put("id", pending.get(i).id);
b.put("verified", resolved[i]);
b.put("line", pending.get(i).line);
resultBreakpoints.add(b);
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("breakpoints", resultBreakpoints);
sendResponse(req, true, body);
}
/**
* Tries to resolve as many of `pending`'s not-yet-resolved lines as possible against `rt`,
* emitting a "breakpoint" (reason: "changed") event for any that newly verify -- e.g. when
* called from a class-prepare handler after the initial setBreakpoints response already
* reported them as unverified.
*/
private void resolveBreakpointsIn(ReferenceType rt, String path, List<PendingBreakpoint> pending, boolean[] resolved, boolean emitEvents) {
String baseName = basename(path);
List<String> strata;
try {
strata = rt.availableStrata();
} catch (Exception e) {
return;
}
List<String> tryStrata = new ArrayList<>();
if (strata.contains("Flix")) tryStrata.add("Flix");
tryStrata.add(rt.defaultStratum());
for (String stratum : tryStrata) {
List<String> sourceNames;
try {
sourceNames = rt.sourceNames(stratum);
} catch (AbsentInformationException e) {
continue;
}
boolean matches = false;
for (String name : sourceNames) {
if (name.equals(baseName) || path.endsWith(name)) { matches = true; break; }
}
if (!matches) continue;
for (int i = 0; i < pending.size(); i++) {
if (resolved[i]) continue;
int line = pending.get(i).line;
List<Location> locs;
try {
locs = rt.locationsOfLine(stratum, baseName, line);
} catch (AbsentInformationException e) {
continue;
}
if (locs.isEmpty()) continue;
EventRequestManager erm = vm.eventRequestManager();
for (Location loc : locs) {
BreakpointRequest br = erm.createBreakpointRequest(loc);
br.setSuspendPolicy(EventRequest.SUSPEND_ALL);
br.enable();
requestsByPath.computeIfAbsent(path, k -> new ArrayList<>()).add(br);
debug("breakpoint set at " + loc);
}
resolved[i] = true;
if (emitEvents) {
PendingBreakpoint pb = pending.get(i);
pb.verified = true;
Map<String, Object> b = new LinkedHashMap<>();
b.put("id", pb.id);
b.put("verified", true);
b.put("line", pb.line);
Map<String, Object> body = new LinkedHashMap<>();
body.put("reason", "changed");
body.put("breakpoint", b);
sendEvent("breakpoint", body);
}
}
return;
}
}
private static String basename(String path) {
int idx = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
return idx < 0 ? path : path.substring(idx + 1);
}
// ------------------------------------------------------------------
// Threads / stack / scopes / variables
// ------------------------------------------------------------------
private void onThreads(Map<String, Object> req) {
List<Object> threads = new ArrayList<>();
if (vm != null) {
for (ThreadReference t : vm.allThreads()) {
Map<String, Object> jt = new LinkedHashMap<>();
jt.put("id", (int) t.uniqueID());
jt.put("name", t.name());
threads.add(jt);
}
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("threads", threads);
sendResponse(req, true, body);
}
/** synthetic frameId -> (threadId, frame index), since JDI StackFrame objects go stale across resumes. */
private final Map<Integer, int[]> frameById = new LinkedHashMap<>();
/** synthetic variablesReference -> the JDI ObjectReference/ArrayReference it should expand to. */
private final Map<Integer, ObjectReference> objectRefById = new LinkedHashMap<>();
/** frameById, objectRefById and StackFrame/ObjectReference identities all go stale once the VM resumes, so
* frame ids and object ids share one counter/generation and are cleared together. */
private int nextRefId = 1;
private ThreadReference threadById(long id) {
for (ThreadReference t : vm.allThreads()) {
if (t.uniqueID() == id) return t;
}
return null;
}
private void onStackTrace(Map<String, Object> req, Map<String, Object> args) throws IncompatibleThreadStateException {
long threadId = ((Number) args.get("threadId")).longValue();
ThreadReference thread = threadById(threadId);
List<Object> frames = new ArrayList<>();
if (thread != null) {
List<StackFrame> stack = thread.frames();
for (int i = 0; i < stack.size(); i++) {
StackFrame sf = stack.get(i);
Location loc = sf.location();
int frameId = nextRefId++;
frameById.put(frameId, new int[]{(int) threadId, i});
String stratum = loc.declaringType().availableStrata().contains("Flix") ? "Flix" : loc.declaringType().defaultStratum();
String sourcePath;
int line;
try {
sourcePath = loc.sourcePath(stratum);
line = loc.lineNumber(stratum);
} catch (AbsentInformationException e) {
sourcePath = loc.declaringType().name();
line = loc.lineNumber();
}
Map<String, Object> frame = new LinkedHashMap<>();
frame.put("id", frameId);
frame.put("name", loc.method().name());
Map<String, Object> source = new LinkedHashMap<>();
source.put("name", basename(sourcePath));
source.put("path", sourcePath);
frame.put("source", source);
frame.put("line", line);
frame.put("column", 1);
frames.add(frame);
}
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("stackFrames", frames);
body.put("totalFrames", frames.size());
sendResponse(req, true, body);
}
private void onScopes(Map<String, Object> req, Map<String, Object> args) {
int frameId = ((Number) args.get("frameId")).intValue();
Map<String, Object> scope = new LinkedHashMap<>();
scope.put("name", "Locals");
scope.put("variablesReference", frameId);
scope.put("expensive", false);
Map<String, Object> body = new LinkedHashMap<>();
body.put("scopes", List.of(scope));
sendResponse(req, true, body);
}
private void onVariables(Map<String, Object> req, Map<String, Object> args) throws IncompatibleThreadStateException {
int variablesReference = ((Number) args.get("variablesReference")).intValue();
List<Object> vars = new ArrayList<>();
int[] loc = frameById.get(variablesReference);
if (loc != null) {
ThreadReference thread = threadById(loc[0]);
if (thread != null && loc[1] < thread.frameCount()) {
StackFrame sf = thread.frame(loc[1]);
try {
for (LocalVariable lv : sf.visibleVariables()) {
vars.add(toVariable(lv.name(), sf.getValue(lv), lv.typeName()));
}
} catch (AbsentInformationException e) {
// no local variable table for this frame; nothing to show.
}
}
} else {
ObjectReference or = objectRefById.get(variablesReference);
if (or instanceof ArrayReference ar) {
vars.addAll(arrayElementVariables(ar));
} else if (or != null) {
vars.addAll(fieldVariables(or));
}
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("variables", vars);
sendResponse(req, true, body);
}
/** Supports a small expression subset against the given frame's locals: dotted field access,
* method calls with literal int/string/bool/null arguments, and integer array indexing --
* e.g. "classes.v0", "tree.forEach(1)", "items[0].value". Not a real expression language: no
* operators, and call arguments must be literals, not sub-expressions -- a full evaluator
* would mean compiling arbitrary Flix source against the running program, which is a
* different-scale problem (effectively embedding a Flix compiler in the adapter) than this is
* trying to solve. Requires a frameId; this adapter has no notion of a global/REPL scope. */
private void onEvaluate(Map<String, Object> req, Map<String, Object> args) throws IncompatibleThreadStateException {
Object frameIdObj = args.get("frameId");
if (frameIdObj == null) {
sendErrorResponse(req, "evaluate requires a frameId; no global scope is supported");
return;
}
int[] loc = frameById.get(((Number) frameIdObj).intValue());
if (loc == null) {
sendErrorResponse(req, "unknown frameId");
return;
}
ThreadReference thread = threadById(loc[0]);
if (thread == null || loc[1] >= thread.frameCount()) {
sendErrorResponse(req, "stack frame no longer available");
return;
}
StackFrame sf = thread.frame(loc[1]);
String expression = String.valueOf(args.get("expression")).trim();
String rootName;
List<Step> steps;
try {
Map.Entry<String, List<Step>> parsed = PathParser.parse(expression);
rootName = parsed.getKey();
steps = parsed.getValue();
} catch (IllegalArgumentException e) {
sendErrorResponse(req, "cannot parse expression: " + e.getMessage());
return;
}
Value current;
try {
LocalVariable lv = null;
for (LocalVariable candidate : sf.visibleVariables()) {
if (candidate.name().equals(rootName)) {
lv = candidate;
break;
}
}
if (lv == null) {
sendErrorResponse(req, "no such variable: " + rootName);
return;
}
current = sf.getValue(lv);
} catch (AbsentInformationException e) {
sendErrorResponse(req, "no local variable information for this frame");
return;
}
for (Step step : steps) {
try {
current = switch (step.kind) {
case FIELD -> applyField(current, step.name);
case CALL -> applyCall(current, step.name, step.args, thread);
case INDEX -> applyIndex(current, step.index);
};
} catch (EvaluateException e) {
sendErrorResponse(req, e.getMessage());
return;
}
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("result", formatValue(current));
body.put("type", current == null ? "null" : current.type().name());
body.put("variablesReference", registerRef(current));
sendResponse(req, true, body);
}
/** A step's error message is already phrased to show the user directly, unlike the raw JDI
* exceptions it wraps. */
private static final class EvaluateException extends Exception {
EvaluateException(String message) {
super(message);
}
}
private static Value applyField(Value current, String name) throws EvaluateException {
if (!(current instanceof ObjectReference or)) {
throw new EvaluateException("cannot access field '" + name + "' on a non-object value");
}
Field f = or.referenceType().fieldByName(name);
if (f == null) {
throw new EvaluateException("no such field: " + name);
}
return or.getValue(f);
}
private static Value applyIndex(Value current, int index) throws EvaluateException {
if (!(current instanceof ArrayReference ar)) {
throw new EvaluateException("cannot index a non-array value with []");
}
if (index < 0 || index >= ar.length()) {
throw new EvaluateException("index " + index + " out of bounds for array of length " + ar.length());
}
return ar.getValue(index);
}
private Value applyCall(Value current, String methodName, List<Object> literalArgs, ThreadReference thread)
throws EvaluateException {
if (!(current instanceof ObjectReference or)) {
throw new EvaluateException("cannot call '" + methodName + "' on a non-object value");
}
List<Method> candidates = or.referenceType().methodsByName(methodName);
Method method = candidates.stream()
.filter(m -> m.argumentTypeNames().size() == literalArgs.size())
.findFirst()
.orElse(null);
if (method == null) {
throw new EvaluateException(candidates.isEmpty()
? "no such method: " + methodName
: "no overload of '" + methodName + "' takes " + literalArgs.size() + " argument(s)");
}
List<Value> jdiArgs = new ArrayList<>();
for (Object literal : literalArgs) {
jdiArgs.add(mirrorLiteral(literal));
}
try {
// INVOKE_SINGLE_THREADED: only the invoking thread runs during the call, matching how
// most Java debuggers evaluate expressions -- otherwise arbitrary other threads could
// run (and hit breakpoints, mutate shared state, etc.) as a side effect of a watch.
return or.invokeMethod(thread, method, jdiArgs, ObjectReference.INVOKE_SINGLE_THREADED);
} catch (InvocationException e) {
throw new EvaluateException("'" + methodName + "' threw: " + formatValue(e.exception()));
} catch (Exception e) {
throw new EvaluateException("failed to invoke '" + methodName + "': " + e);
}
}
private Value mirrorLiteral(Object literal) {
if (literal == null) return null;
if (literal instanceof Integer n) return vm.mirrorOf(n);
if (literal instanceof String s) return vm.mirrorOf(s);
if (literal instanceof Boolean b) return vm.mirrorOf(b);
throw new IllegalStateException("unexpected literal type: " + literal.getClass());
}
private enum StepKind {FIELD, CALL, INDEX}
private static final class Step {
final StepKind kind;
final String name;
final List<Object> args;
final int index;
private Step(StepKind kind, String name, List<Object> args, int index) {
this.kind = kind;
this.name = name;
this.args = args;
this.index = index;
}
static Step field(String name) {
return new Step(StepKind.FIELD, name, null, 0);
}
static Step call(String name, List<Object> args) {
return new Step(StepKind.CALL, name, args, 0);
}
static Step index(int index) {
return new Step(StepKind.INDEX, null, null, index);
}
}
/** Hand-rolled parser for onEvaluate's expression subset: {@code root(.field|.call(args)|[int])*}
* where args are comma-separated int/string/true/false/null literals. Throws
* IllegalArgumentException with a position-annotated, user-facing message on anything else. */
private static final class PathParser {
private final String s;
private int i = 0;
private PathParser(String s) {
this.s = s;
}
static Map.Entry<String, List<Step>> parse(String expression) {
PathParser p = new PathParser(expression);
String root = p.identifier();
List<Step> steps = new ArrayList<>();
while (p.i < p.s.length()) {
char c = p.s.charAt(p.i);
if (c == '.') {
p.i++;
String name = p.identifier();
if (p.peek() == '(') {
p.i++;
List<Object> callArgs = p.args();
p.expect(')');
steps.add(Step.call(name, callArgs));
} else {
steps.add(Step.field(name));
}
} else if (c == '[') {
p.i++;
int idx = p.integer();
p.expect(']');
steps.add(Step.index(idx));
} else {
throw new IllegalArgumentException("unexpected '" + c + "' at position " + p.i);
}
}
return Map.entry(root, steps);
}
private char peek() {
return i < s.length() ? s.charAt(i) : '\0';
}
private void expect(char c) {
if (peek() != c) throw new IllegalArgumentException("expected '" + c + "' at position " + i);
i++;
}
private String identifier() {
int start = i;
while (i < s.length() && (Character.isLetterOrDigit(s.charAt(i)) || s.charAt(i) == '_' || s.charAt(i) == '$')) {
i++;
}
if (i == start) throw new IllegalArgumentException("expected identifier at position " + i);
return s.substring(start, i);
}
private int integer() {
int start = i;
if (peek() == '-') i++;
while (i < s.length() && Character.isDigit(s.charAt(i))) i++;
if (i == start || (i == start + 1 && s.charAt(start) == '-')) {
throw new IllegalArgumentException("expected integer at position " + i);
}
return Integer.parseInt(s.substring(start, i));
}
private String stringLiteral() {
expect('"');
StringBuilder sb = new StringBuilder();
while (peek() != '"') {
if (i >= s.length()) throw new IllegalArgumentException("unterminated string literal");
char c = s.charAt(i++);
if (c == '\\' && i < s.length()) {
char e = s.charAt(i++);
sb.append(switch (e) {
case 'n' -> '\n';
case 't' -> '\t';
case '"' -> '"';
case '\\' -> '\\';
default -> e;
});
} else {
sb.append(c);
}
}
i++; // closing quote
return sb.toString();
}
private List<Object> args() {
List<Object> result = new ArrayList<>();
skipWs();
if (peek() == ')') return result;
while (true) {
result.add(literal());
skipWs();
if (peek() == ',') {
i++;
skipWs();
continue;
}
break;
}
return result;
}
private void skipWs() {
while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
}
private Object literal() {
skipWs();
char c = peek();
if (c == '"') return stringLiteral();
if (c == '-' || Character.isDigit(c)) return integer();
if (s.startsWith("true", i)) {
i += 4;
return Boolean.TRUE;
}
if (s.startsWith("false", i)) {
i += 5;
return Boolean.FALSE;
}
if (s.startsWith("null", i)) {
i += 4;
return null;
}
throw new IllegalArgumentException("expected a literal (int/string/true/false/null) at position " + i);
}
}
/** Every field (including inherited) of an arbitrary object, resolved generically via JDI reflection
* so that Flix's compiled representations (Tag/Obj wrappers, records, ...) drill down without any
* Flix-specific knowledge here. */
private List<Object> fieldVariables(ObjectReference or) {
List<Object> vars = new ArrayList<>();
for (Field f : or.referenceType().allFields()) {
if (f.isStatic()) continue;
Value v;
try {
v = or.getValue(f);
} catch (Exception e) {
continue;
}
vars.add(toVariable(f.name(), v, f.typeName()));
}
return vars;
}
private List<Object> arrayElementVariables(ArrayReference ar) {
List<Object> vars = new ArrayList<>();
List<Value> values = ar.getValues();
for (int i = 0; i < values.size(); i++) {
vars.add(toVariable("[" + i + "]", values.get(i), ""));
}
return vars;
}