-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathJavaDebugServer.java
More file actions
824 lines (749 loc) · 29.6 KB
/
JavaDebugServer.java
File metadata and controls
824 lines (749 loc) · 29.6 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
package org.javacs.debug;
import com.sun.jdi.*;
import com.sun.jdi.connect.AttachingConnector;
import com.sun.jdi.connect.IllegalConnectorArgumentsException;
import com.sun.jdi.event.*;
import com.sun.jdi.request.BreakpointRequest;
import com.sun.jdi.request.EventRequest;
import com.sun.jdi.request.StepRequest;
import java.io.IOException;
import java.net.ConnectException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.logging.*;
import org.javacs.LogFormat;
import org.javacs.debug.proto.*;
public class JavaDebugServer implements DebugServer {
public static void main(String[] args) { // TODO don't show references for main method
// createLogFile();
LOG.info(String.join(" ", args));
new DebugAdapter(JavaDebugServer::new, System.in, System.out).run();
System.exit(0);
}
private static void createLogFile() {
try {
// TODO make location configurable
var logFile =
new FileHandler("/Users/georgefraser/Documents/java-language-server/java-debug-server.log", false);
logFile.setFormatter(new LogFormat());
Logger.getLogger("").addHandler(logFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private final DebugClient client;
private List<Path> sourceRoots = List.of();
private VirtualMachine vm;
private final List<Breakpoint> pendingBreakpoints = new ArrayList<>();
private static int breakPointCounter = 0;
class ReceiveVmEvents implements Runnable {
@Override
public void run() {
var events = vm.eventQueue();
while (true) {
try {
var nextSet = events.remove();
for (var event : nextSet) {
process(event);
}
} catch (VMDisconnectedException __) {
LOG.info("VM disconnected");
return;
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage(), e);
return;
}
}
}
private void process(com.sun.jdi.event.Event event) {
LOG.info("Received " + event.toString() + " from VM");
if (event instanceof ClassPrepareEvent) {
var prepare = (ClassPrepareEvent) event;
var type = prepare.referenceType();
LOG.info("ClassPrepareRequest for class " + type.name() + " in source " + relativePath(type));
enablePendingBreakpointsIn(type);
vm.resume();
} else if (event instanceof com.sun.jdi.event.BreakpointEvent) {
var b = (com.sun.jdi.event.BreakpointEvent) event;
var evt = new StoppedEventBody();
evt.reason = "breakpoint";
evt.threadId = b.thread().uniqueID();
evt.allThreadsStopped = b.request().suspendPolicy() == EventRequest.SUSPEND_ALL;
client.stopped(evt);
} else if (event instanceof StepEvent) {
var b = (StepEvent) event;
var evt = new StoppedEventBody();
evt.reason = "step";
evt.threadId = b.thread().uniqueID();
evt.allThreadsStopped = b.request().suspendPolicy() == EventRequest.SUSPEND_ALL;
client.stopped(evt);
// Disable event so we can create new step events
event.request().disable();
} else if (event instanceof VMDeathEvent) {
client.exited(new ExitedEventBody());
} else if (event instanceof VMDisconnectEvent) {
client.terminated(new TerminatedEventBody());
}
}
}
public JavaDebugServer(DebugClient client) {
this.client = client;
class LogToConsole extends Handler {
private final LogFormat format = new LogFormat();
@Override
public void publish(LogRecord r) {
var evt = new OutputEventBody();
evt.category = "console";
evt.output = format.format(r);
client.output(evt);
}
@Override
public void flush() {}
@Override
public void close() {}
}
Logger.getLogger("debug").addHandler(new LogToConsole());
}
@Override
public Capabilities initialize(InitializeRequestArguments req) {
var resp = new Capabilities();
resp.supportsConfigurationDoneRequest = true;
return resp;
}
@Override
public SetBreakpointsResponseBody setBreakpoints(SetBreakpointsArguments req) {
LOG.info("Received " + req.breakpoints.length + " breakpoints in " + req.source.path);
disableBreakpoints(req.source);
// Add these breakpoints to the pending set
var resp = new SetBreakpointsResponseBody();
resp.breakpoints = new Breakpoint[req.breakpoints.length];
for (var i = 0; i < req.breakpoints.length; i++) {
resp.breakpoints[i] = enableBreakpoint(req.source, req.breakpoints[i]);
}
return resp;
}
private void disableBreakpoints(Source source) {
for (var b : vm.eventRequestManager().breakpointRequests()) {
if (matchesFile(b, source)) {
LOG.info(String.format("Disable breakpoint %s:%d", source.path, b.location().lineNumber()));
b.disable();
}
}
}
private Breakpoint enableBreakpoint(Source source, SourceBreakpoint b) {
// Check for breakpoint in disabled breakpoints
for (var req : vm.eventRequestManager().breakpointRequests()) {
if (matchesFile(req, source) && matchesLine(req, b.line)) {
return enableDisabledBreakpoint(source, req);
}
}
// Check for breakpoint in loaded classes
for (var type : loadedTypesMatching(source.path)) {
return enableBreakpointImmediately(source, b, type);
}
// If class hasn't been loaded, add breakpoint to pending list
return enableBreakpointLater(source, b);
}
private boolean matchesFile(BreakpointRequest b, Source source) {
try {
var relativePath = b.location().sourcePath(vm.getDefaultStratum());
return source.path.endsWith(relativePath);
} catch (AbsentInformationException __) {
LOG.warning("No source information for " + b.location());
return false;
}
}
private boolean matchesLine(BreakpointRequest b, int line) {
return line == b.location().lineNumber(vm.getDefaultStratum());
}
private List<ReferenceType> loadedTypesMatching(String absolutePath) {
var matches = new ArrayList<ReferenceType>();
for (var type : vm.allClasses()) {
var path = relativePath(type);
if (!path.isEmpty() && absolutePath.endsWith(path)) {
matches.add(type);
}
}
return matches;
}
private Breakpoint enableDisabledBreakpoint(Source source, BreakpointRequest b) {
LOG.info(String.format("Enable disabled breakpoint %s:%d", source.path, b.location().lineNumber()));
b.enable();
var ok = new Breakpoint();
ok.verified = true;
ok.source = source;
ok.line = b.location().lineNumber(vm.getDefaultStratum());
return ok;
}
private Breakpoint enableBreakpointImmediately(Source source, SourceBreakpoint b, ReferenceType type) {
if (!tryEnableBreakpointImmediately(source, b, type)) {
var failed = new Breakpoint();
failed.verified = false;
failed.message = source.name + ":" + b.line + " could not be found or had no code on it";
return failed;
}
var ok = new Breakpoint();
ok.verified = true;
ok.source = source;
ok.line = b.line;
return ok;
}
private boolean tryEnableBreakpointImmediately(Source source, SourceBreakpoint b, ReferenceType type) {
List<Location> locations;
try {
locations = type.locationsOfLine(b.line);
} catch (AbsentInformationException __) {
LOG.info(String.format("No locations in %s for breakpoint %s:%d", type.name(), source.path, b.line));
return false;
}
for (var l : locations) {
LOG.info(String.format("Create breakpoint %s:%d", source.path, l.lineNumber()));
var req = vm.eventRequestManager().createBreakpointRequest(l);
req.setSuspendPolicy(EventRequest.SUSPEND_ALL);
req.enable();
}
return true;
}
private Breakpoint enableBreakpointLater(Source source, SourceBreakpoint b) {
LOG.info(String.format("Enable %s:%d later", source.path, b.line));
var pending = new Breakpoint();
pending.id = breakPointCounter++;
pending.source = new Source();
pending.source.path = source.path;
pending.line = b.line;
pending.column = b.column;
pending.verified = false;
pending.message = source.name + " is not yet loaded";
pendingBreakpoints.add(pending);
return pending;
}
@Override
public SetFunctionBreakpointsResponseBody setFunctionBreakpoints(SetFunctionBreakpointsArguments req) {
LOG.warning("Not yet implemented");
return new SetFunctionBreakpointsResponseBody();
}
@Override
public void setExceptionBreakpoints(SetExceptionBreakpointsArguments req) {
LOG.warning("Not yet implemented");
}
@Override
public void configurationDone() {
listenForClassPrepareEvents();
enablePendingBreakpointsInLoadedClasses();
vm.resume();
}
/* Request to be notified when files with pending breakpoints are loaded */
private void listenForClassPrepareEvents() {
Objects.requireNonNull(vm, "vm has not been initialized");
// Get all file names
var distinctSourceNames = new HashSet<String>();
for (var b : pendingBreakpoints) {
var path = Paths.get(b.source.path);
var name = path.getFileName();
distinctSourceNames.add(name.toString());
}
// Listen for classes with those names
for (var name : distinctSourceNames) {
LOG.info("Listen for ClassPrepareRequest in " + name);
var requestClassEvent = vm.eventRequestManager().createClassPrepareRequest();
requestClassEvent.addSourceNameFilter("*" + name);
requestClassEvent.setSuspendPolicy(EventRequest.SUSPEND_ALL);
requestClassEvent.enable();
}
}
@Override
public void launch(LaunchRequestArguments req) {
throw new UnsupportedOperationException();
}
private static AttachingConnector connector(String transport) {
var found = new ArrayList<String>();
for (var conn : Bootstrap.virtualMachineManager().attachingConnectors()) {
if (conn.transport().name().equals(transport)) {
return conn;
}
found.add(conn.transport().name());
}
throw new RuntimeException("Couldn't find connector for transport " + transport + " in " + found);
}
@Override
public void attach(AttachRequestArguments req) {
// Remember available source roots
sourceRoots = new ArrayList<Path>();
for (var string : req.sourceRoots) {
var path = Paths.get(string);
if (!Files.exists(path)) {
LOG.warning(string + " does not exist");
continue;
} else if (!Files.isDirectory(path)) {
LOG.warning(string + " is not a directory");
continue;
} else {
LOG.info(path + " is a source root");
sourceRoots.add(path);
}
}
// Attach to the running VM
if (!tryToConnect(req.port)) {
throw new RuntimeException("Failed to connect after 15 attempts");
}
// Create a thread that reads events from the VM
var reader = new java.lang.Thread(new ReceiveVmEvents(), "receive-vm");
reader.setDaemon(true);
reader.start();
// Tell the client we are ready to receive breakpoints
client.initialized();
}
private boolean tryToConnect(int port) {
var conn = connector("dt_socket");
var args = conn.defaultArguments();
var intervalMs = 500;
var tryForS = 15;
var attempts = tryForS * 1000 / intervalMs;
args.get("port").setValue(Integer.toString(port));
for (var attempt = 0; attempt < attempts; attempt++) {
try {
vm = conn.attach(args);
return true;
} catch (ConnectException e) {
LOG.warning(e.getMessage());
try {
java.lang.Thread.sleep(intervalMs);
} catch (InterruptedException __) {
// Nothing to do
}
} catch (IOException | IllegalConnectorArgumentsException e) {
throw new RuntimeException(e);
}
}
return false;
}
/* Set breakpoints for already-loaded classes */
private void enablePendingBreakpointsInLoadedClasses() {
Objects.requireNonNull(vm, "vm has not been initialized");
for (var type : vm.allClasses()) {
enablePendingBreakpointsIn(type);
}
}
private void enablePendingBreakpointsIn(ReferenceType type) {
// Check that class has source information
var path = relativePath(type);
if (path.isEmpty()) return;
// Look for pending breakpoints that can be enabled
var enabled = new ArrayList<Breakpoint>();
for (var b : pendingBreakpoints) {
if (b.source.path.endsWith(path)) {
enablePendingBreakpoint(b, type);
enabled.add(b);
}
}
pendingBreakpoints.removeAll(enabled);
}
private void enablePendingBreakpoint(Breakpoint b, ReferenceType type) {
try {
var locations = type.locationsOfLine(b.line);
for (var line : locations) {
var req = vm.eventRequestManager().createBreakpointRequest(line);
req.setSuspendPolicy(EventRequest.SUSPEND_ALL);
req.enable();
}
if (locations.isEmpty()) {
LOG.info("No locations at " + b.source.path + ":" + b.line);
var failed = new BreakpointEventBody();
failed.reason = "changed";
failed.breakpoint = b;
b.verified = false;
b.message = b.source.name + ":" + b.line + " could not be found or had no code on it";
client.breakpoint(failed);
return;
}
LOG.info("Enable breakpoint at " + b.source.path + ":" + b.line);
var ok = new BreakpointEventBody();
ok.reason = "changed";
ok.breakpoint = b;
b.verified = true;
b.message = null;
client.breakpoint(ok);
} catch (AbsentInformationException __) {
LOG.info("Absent information at " + b.source.path + ":" + b.line);
var failed = new BreakpointEventBody();
failed.reason = "changed";
failed.breakpoint = b;
b.verified = false;
b.message = b.source.name + ":" + b.line + " could not be found or had no code on it";
client.breakpoint(failed);
}
}
private String relativePath(ReferenceType type) {
try {
for (var path : type.sourcePaths(vm.getDefaultStratum())) {
return path;
}
return "";
} catch (AbsentInformationException __) {
return "";
}
}
@Override
public void disconnect(DisconnectArguments req) {
try {
vm.dispose();
} catch (VMDisconnectedException __) {
LOG.warning("VM has already terminated");
}
vm = null;
}
@Override
public void terminate(TerminateArguments req) {
vm.exit(1);
}
@Override
public void continue_(ContinueArguments req) {
valueIdTracker.clear();
vm.resume();
}
@Override
public void next(NextArguments req) {
var thread = findThread(req.threadId);
if (thread == null) {
LOG.warning("No thread with id " + req.threadId);
return;
}
LOG.info("Send StepRequest(STEP_LINE, STEP_OVER) to VM and resume");
var step = vm.eventRequestManager().createStepRequest(thread, StepRequest.STEP_LINE, StepRequest.STEP_OVER);
step.addCountFilter(1);
step.enable();
valueIdTracker.clear();
vm.resume();
}
@Override
public void stepIn(StepInArguments req) {
var thread = findThread(req.threadId);
if (thread == null) {
LOG.warning("No thread with id " + req.threadId);
return;
}
LOG.info("Send StepRequest(STEP_LINE, STEP_INTO) to VM and resume");
var step = vm.eventRequestManager().createStepRequest(thread, StepRequest.STEP_LINE, StepRequest.STEP_INTO);
step.addCountFilter(1);
step.enable();
valueIdTracker.clear();
vm.resume();
}
@Override
public void stepOut(StepOutArguments req) {
var thread = findThread(req.threadId);
if (thread == null) {
LOG.warning("No thread with id " + req.threadId);
return;
}
LOG.info("Send StepRequest(STEP_LINE, STEP_OUT) to VM and resume");
var step = vm.eventRequestManager().createStepRequest(thread, StepRequest.STEP_LINE, StepRequest.STEP_OUT);
step.addCountFilter(1);
step.enable();
valueIdTracker.clear();
vm.resume();
}
@Override
public ThreadsResponseBody threads() {
var threads = new ThreadsResponseBody();
threads.threads = asThreads(vm.allThreads());
return threads;
}
private org.javacs.debug.proto.Thread[] asThreads(List<ThreadReference> ts) {
var result = new org.javacs.debug.proto.Thread[ts.size()];
for (var i = 0; i < ts.size(); i++) {
result[i] = asThread(ts.get(i));
}
return result;
}
private org.javacs.debug.proto.Thread asThread(ThreadReference t) {
var thread = new org.javacs.debug.proto.Thread();
thread.id = t.uniqueID();
thread.name = t.name();
return thread;
}
private ThreadReference findThread(long threadId) {
for (var thread : vm.allThreads()) {
if (thread.uniqueID() == threadId) {
return thread;
}
}
return null;
}
@Override
public StackTraceResponseBody stackTrace(StackTraceArguments req) {
try {
for (var t : vm.allThreads()) {
if (t.uniqueID() == req.threadId) {
var length = t.frameCount() - req.startFrame;
if (req.levels != null && req.levels < length) {
length = req.levels;
}
var resp = new StackTraceResponseBody();
resp.stackFrames = asStackFrames(t.frames(req.startFrame, length));
resp.totalFrames = t.frameCount();
return resp;
}
}
throw new RuntimeException("Couldn't find thread " + req.threadId);
} catch (IncompatibleThreadStateException e) {
throw new RuntimeException(e);
}
}
private org.javacs.debug.proto.StackFrame[] asStackFrames(List<com.sun.jdi.StackFrame> fs) {
var result = new org.javacs.debug.proto.StackFrame[fs.size()];
for (var i = 0; i < fs.size(); i++) {
result[i] = asStackFrame(fs.get(i));
}
return result;
}
private org.javacs.debug.proto.StackFrame asStackFrame(com.sun.jdi.StackFrame f) {
var frame = new org.javacs.debug.proto.StackFrame();
frame.id = uniqueFrameId(f);
frame.name = f.location().method().name();
frame.source = asSource(f.location());
frame.line = f.location().lineNumber();
return frame;
}
private Source asSource(Location l) {
try {
var path = findSource(l);
var src = new Source();
src.name = l.sourceName();
src.path = Objects.toString(path, null);
return src;
} catch (AbsentInformationException __) {
var src = new Source();
src.path = relativePath(l.declaringType());
src.name = l.declaringType().name();
src.presentationHint = "deemphasize";
return src;
}
}
private static final Set<String> warnedCouldNotFind = new HashSet<>();
private Path findSource(Location l) throws AbsentInformationException {
var relative = l.sourcePath();
for (var root : sourceRoots) {
var absolute = root.resolve(relative);
if (Files.exists(absolute)) {
return absolute;
}
}
if (!warnedCouldNotFind.contains(relative)) {
LOG.warning("Could not find " + relative);
warnedCouldNotFind.add(relative);
}
return null;
}
/** Debug adapter protocol doesn't seem to like frame 0 */
private static final int FRAME_OFFSET = 100;
private long uniqueFrameId(com.sun.jdi.StackFrame f) {
try {
long count = FRAME_OFFSET;
for (var thread : f.virtualMachine().allThreads()) {
if (thread.equals(f.thread())) {
for (var frame : thread.frames()) {
if (frame.equals(f)) {
return count;
} else {
count++;
}
}
} else {
count += thread.frameCount();
}
}
return count;
} catch (IncompatibleThreadStateException e) {
throw new RuntimeException(e);
}
}
private com.sun.jdi.StackFrame findFrame(long id) {
try {
long count = FRAME_OFFSET;
for (var thread : vm.allThreads()) {
if (id < count + thread.frameCount()) {
var offset = (int) (id - count);
return thread.frame(offset);
} else {
count += thread.frameCount();
}
}
throw new RuntimeException("Couldn't find frame " + id);
} catch (IncompatibleThreadStateException e) {
throw new RuntimeException(e);
}
}
@Override
public ScopesResponseBody scopes(ScopesArguments req) {
var resp = new ScopesResponseBody();
var fields = new Scope();
fields.name = "Fields";
fields.presentationHint = "locals";
fields.expensive = true; // do not expand by default
fields.variablesReference = req.frameId * 2;
var locals = new Scope();
locals.name = "Locals";
locals.presentationHint = "locals";
locals.variablesReference = req.frameId * 2 + 1;
resp.scopes = new Scope[] {fields, locals};
return resp;
}
private static final long VALUE_ID_START = 1000000000;
private static class ValueIdTracker {
private final HashMap<Long, Value> values = new HashMap<>();
private long nextId = VALUE_ID_START;
public void clear() {
values.clear();
// Keep nextId to avoid accidentally accessing wrong Values.
}
public Value get(long id) {
return values.get(id);
}
public long put(Value value) {
long id = nextId++;
values.put(id, value);
return id;
}
}
private final ValueIdTracker valueIdTracker = new ValueIdTracker();
private static boolean hasInterestingChildren(Value value) {
return value instanceof ObjectReference && !(value instanceof StringReference);
}
@Override
public VariablesResponseBody variables(VariablesArguments req) {
if (req.variablesReference < VALUE_ID_START) {
var frameId = req.variablesReference / 2;
var scopeId = (int)(req.variablesReference % 2);
return frameVariables(frameId, scopeId);
}
Value value = valueIdTracker.get(req.variablesReference);
return valueChildren(value);
}
private VariablesResponseBody frameVariables(long frameId, int scopeId) {
var frame = findFrame(frameId);
var thread = frame.thread();
var variables = new ArrayList<Variable>();
if (scopeId == 0) {
var thisValue = frame.thisObject();
if (thisValue != null) {
variables.addAll(objectFieldsAsVariables(thisValue, thread));
}
} else {
variables.addAll(frameLocalsAsVariables(frame, thread));
}
var resp = new VariablesResponseBody();
resp.variables = variables.toArray(Variable[]::new);
return resp;
}
private VariablesResponseBody valueChildren(Value parentValue) {
// TODO: Use an actual owner thread.
ThreadReference mainThread = vm.allThreads().get(0);
var variables = new ArrayList<Variable>();
if (parentValue instanceof ArrayReference array) {
variables.addAll(arrayElementsAsVariables(array, mainThread));
} else if (parentValue instanceof ObjectReference object) {
variables.addAll(objectFieldsAsVariables(object, mainThread));
}
var resp = new VariablesResponseBody();
resp.variables = variables.toArray(Variable[]::new);
return resp;
}
private List<Variable> frameLocalsAsVariables(com.sun.jdi.StackFrame frame, ThreadReference thread) {
List<LocalVariable> visible;
try {
visible = frame.visibleVariables();
} catch (AbsentInformationException __) {
LOG.warning(String.format("No visible variable information in %s", frame.location()));
return List.of();
}
var variables = new ArrayList<Variable>();
var values = frame.getValues(visible);
for (var v : visible) {
var value = values.get(v);
var w = new Variable();
w.name = v.name();
w.value = print(value, thread);
w.type = v.typeName();
if (hasInterestingChildren(value)) {
w.variablesReference = valueIdTracker.put(value);
}
if (value instanceof ArrayReference array) {
w.indexedVariables = array.length();
}
// TODO set variablePresentationHint
variables.add(w);
}
return variables;
}
private List<Variable> arrayElementsAsVariables(ArrayReference array, ThreadReference thread) {
var variables = new ArrayList<Variable>();
var arrayType = (ArrayType) array.type();
var values = array.getValues();
var length = values.size();
for (int i = 0; i < length; i++) {
var value = values.get(i);
var w = new Variable();
w.name = Integer.toString(i, 10);
w.value = print(value, thread);
w.type = arrayType.componentTypeName();
if (hasInterestingChildren(value)) {
w.variablesReference = valueIdTracker.put(value);
}
variables.add(w);
}
return variables;
}
private List<Variable> objectFieldsAsVariables(ObjectReference object, ThreadReference thread) {
var variables = new ArrayList<Variable>();
var classType = (ClassType) object.type();
var values = object.getValues(classType.allFields());
for (var field : values.keySet()) {
var value = values.get(field);
var w = new Variable();
w.name = field.name();
w.value = print(value, thread);
w.type = field.typeName();
if (hasInterestingChildren(value)) {
w.variablesReference = valueIdTracker.put(value);
}
variables.add(w);
}
return variables;
}
private String print(Value value, ThreadReference t) {
if (value == null) {
return "null";
} else if (value instanceof ObjectReference) {
return printObject((ObjectReference) value, t);
} else {
return value.toString();
}
}
private String printObject(ObjectReference object, ThreadReference t) {
var type = object.referenceType();
for (var method : type.methodsByName("toString", "()Ljava/lang/String;")) {
try {
var string = (StringReference) object.invokeMethod(t, method, List.of(), 0);
return string.value();
} catch (InvocationException e) {
return String.format("toString() threw %s", e.exception().type().name());
} catch (InvalidTypeException | ClassNotLoadedException | IncompatibleThreadStateException e) {
throw new RuntimeException(e);
}
}
return object.toString();
}
@Override
public EvaluateResponseBody evaluate(EvaluateArguments req) {
throw new UnsupportedOperationException();
}
private static final Logger LOG = Logger.getLogger("debug");
}