forked from processing/processing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDebugger.java
More file actions
1392 lines (1179 loc) · 40.8 KB
/
Debugger.java
File metadata and controls
1392 lines (1179 loc) · 40.8 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
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-15 The Processing Foundation
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program 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 for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package processing.mode.java;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import com.sun.jdi.request.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTree; // needed for javadocs
import javax.swing.tree.DefaultMutableTreeNode;
import processing.app.Sketch;
import processing.app.SketchCode;
import processing.mode.java.debug.*;
import processing.mode.java.pdex.VMEventListener;
import processing.mode.java.pdex.VMEventReader;
import processing.mode.java.runner.Runner;
public class Debugger implements VMEventListener {
/// editor window, acting as main view
protected JavaEditor editor;
/// the runtime, contains debuggee VM
protected Runner runtime;
/// debuggee vm has started, VMStartEvent received, main class loaded
protected boolean started = false;
/// currently paused at breakpoint or step
protected boolean paused = false;
/// thread the last breakpoint or step occured in
protected ThreadReference currentThread;
/// name of the main class that's currently being debugged
protected String mainClassName;
/// the debuggee's main class
protected ReferenceType mainClass;
/// holds all loaded classes in the debuggee VM
protected Set<ReferenceType> classes = new HashSet<ReferenceType>();
/// listeners for class load events
protected List<ClassLoadListener> classLoadListeners =
new ArrayList<ClassLoadListener>();
/// path to the src folder of the current build
protected String srcPath;
/// list of current breakpoints
protected List<LineBreakpoint> breakpoints =
new ArrayList<LineBreakpoint>();
/// the step request we are currently in, or null if not in a step
protected StepRequest requestedStep;
/// maps line number changes at runtime (orig -> changed)
protected Map<LineID, LineID> runtimeLineChanges =
new HashMap<LineID, LineID>();
/// tab filenames which already have been tracked for runtime changes
protected Set<String> runtimeTabsTracked = new HashSet<String>();
public Debugger(JavaEditor editor) {
this.editor = editor;
}
public VirtualMachine vm() {
if (runtime != null) {
return runtime.vm();
}
return null;
}
public JavaEditor getEditor() {
return editor;
}
/**
* Retrieve the main class of the debuggee VM.
* @return the main classes {@link ReferenceType}
* or null if the debugger is not started.
*/
public ReferenceType getMainClass() {
if (isStarted()) {
return mainClass;
}
return null;
}
/**
* Get the {@link ReferenceType} for a class name.
* @param name the class name
* @return the {@link ReferenceType} or null if not found
* (e.g. not yet loaded)
*/
public ReferenceType getClass(String name) {
if (name == null) {
return null;
}
if (name.equals(mainClassName)) {
return mainClass;
}
for (ReferenceType rt : classes) {
if (rt.name().equals(name)) {
return rt;
}
}
return null;
}
/**
* Add a class load listener. Will be notified when a class is loaded in the
* debuggee VM.
* @param listener the {@link ClassLoadListener}
*/
public void addClassLoadListener(ClassLoadListener listener) {
classLoadListeners.add(listener);
}
/**
* Remove a class load listener. Cease to be notified when classes are
* loaded in the debuggee VM.
* @param listener {@link ClassLoadListener}
*/
public void removeClassLoadListener(ClassLoadListener listener) {
classLoadListeners.remove(listener);
}
/**
* Start a debugging session. Builds the sketch and launches a VM to run it.
* VM starts suspended. Should produce a VMStartEvent.
*/
public synchronized void startDebug() {
//stopDebug(); // stop any running sessions
if (isStarted()) {
return; // do nothing
}
// we are busy now
editor.statusBusy();
// clear console
editor.clearConsole();
// clear variable inspector (also resets expanded states)
editor.variableInspector().reset();
// load edits into sketch obj, etc...
editor.prepareRun();
// after prepareRun, since this removes highlights
editor.activateDebug();
try {
Sketch sketch = editor.getSketch();
JavaBuild build = new JavaBuild(sketch);
log(Level.INFO, "building sketch: {0}", sketch.getName());
//LineMapping.addLineNumbers(sketch); // annotate
mainClassName = build.build(false);
//LineMapping.removeLineNumbers(sketch); // annotate
log(Level.INFO, "class: {0}", mainClassName);
// folder with assembled/preprocessed src
srcPath = build.getSrcFolder().getPath();
log(Level.INFO, "build src: {0}", srcPath);
// folder with compiled code (.class files)
log(Level.INFO, "build bin: {0}", build.getBinFolder().getPath());
if (mainClassName != null) {
// generate the source line mapping
//lineMap = LineMapping.generateMapping(srcPath + File.separator + mainClassName + ".java");
log(Level.INFO, "launching debuggee runtime");
runtime = new Runner(build, editor);
VirtualMachine vm = runtime.launchDebug(); // non-blocking
if (vm == null) {
log(Level.SEVERE, "error 37: launch failed");
}
// start receiving vm events
VMEventReader eventThread = new VMEventReader(vm.eventQueue(), this);
eventThread.start();
startTrackingLineChanges();
editor.statusBusy();
}
} catch (Exception e) {
editor.statusError(e);
}
}
/**
* End debugging session. Stops and disconnects VM. Should produce
* VMDisconnectEvent.
*/
public synchronized void stopDebug() {
editor.variableInspector().lock();
if (runtime != null) {
log(Level.INFO, "closing runtime");
runtime.close();
runtime = null;
//build = null;
classes.clear();
// need to clear highlight here because, VMDisconnectedEvent seems to be unreliable. TODO: likely synchronization problem
editor.clearCurrentLine();
}
stopTrackingLineChanges();
started = false;
editor.deactivateDebug();
editor.deactivateContinue();
editor.deactivateStep();
editor.statusEmpty();
}
/** Resume paused debugging session. Resumes VM. */
public synchronized void continueDebug() {
editor.activateContinue();
editor.variableInspector().lock();
//editor.clearSelection();
//clearHighlight();
editor.clearCurrentLine();
if (!isStarted()) {
startDebug();
} else if (isPaused()) {
runtime.vm().resume();
paused = false;
editor.statusBusy();
}
}
/**
* Step through source code lines.
* @param stepDepth the step depth ({@link StepRequest#STEP_OVER},
* {@link StepRequest#STEP_INTO} or {@link StepRequest#STEP_OUT})
*/
protected void step(int stepDepth) {
if (!isStarted()) {
startDebug();
} else if (isPaused()) {
editor.variableInspector().lock();
editor.activateStep();
// use global to mark that there is a step request pending
requestedStep = runtime.vm().eventRequestManager().createStepRequest(currentThread, StepRequest.STEP_LINE, stepDepth);
requestedStep.addCountFilter(1); // valid for one step only
requestedStep.enable();
paused = false;
runtime.vm().resume();
editor.statusBusy();
}
}
/** Step over current statement. */
public synchronized void stepOver() {
step(StepRequest.STEP_OVER);
}
/** Step into current statement. */
public synchronized void stepInto() {
step(StepRequest.STEP_INTO);
}
/** Step out of current statement. */
public synchronized void stepOut() {
step(StepRequest.STEP_OUT);
}
/** Print the current stack trace. */
public synchronized void printStackTrace() {
if (isStarted()) {
printStackTrace(currentThread);
}
}
/**
* Print local variables. Outputs type, name and value of each variable.
*/
public synchronized void printLocals() {
if (isStarted()) {
printLocalVariables(currentThread);
}
}
/**
* Print fields of current {@code this}-object.
* Outputs type, name and value of each field.
*/
public synchronized void printThis() {
if (isStarted()) {
printThis(currentThread);
}
}
/**
* Print a source code snippet of the current location.
*/
public synchronized void printSource() {
if (isStarted()) {
printSourceLocation(currentThread);
}
}
/**
* Set a breakpoint on the current line.
*/
public synchronized void setBreakpoint() {
setBreakpoint(editor.getCurrentLineID());
}
/**
* Set a breakpoint on a line in the current tab.
* @param lineIdx the line index (0-based) of the current tab to set the
* breakpoint on
*/
public synchronized void setBreakpoint(int lineIdx) {
setBreakpoint(editor.getLineIDInCurrentTab(lineIdx));
}
public synchronized void setBreakpoint(LineID line) {
// do nothing if we are kinda busy
if (isStarted() && !isPaused()) {
return;
}
// do nothing if there already is a breakpoint on this line
if (hasBreakpoint(line)) {
return;
}
breakpoints.add(new LineBreakpoint(line, this));
log(Level.INFO, "set breakpoint on line {0}", line);
}
/**
* Remove a breakpoint from the current line (if set).
*/
public synchronized void removeBreakpoint() {
removeBreakpoint(editor.getCurrentLineID().lineIdx());
}
/**
* Remove a breakpoint from a line in the current tab.
*
* @param lineIdx the line index (0-based) in the current tab to remove the
* breakpoint from
*/
protected void removeBreakpoint(int lineIdx) {
// do nothing if we are kinda busy
if (isBusy()) {
return;
}
LineBreakpoint bp = breakpointOnLine(editor.getLineIDInCurrentTab(lineIdx));
if (bp != null) {
bp.remove();
breakpoints.remove(bp);
log(Level.INFO, "removed breakpoint {0}", bp);
}
}
/** Remove all breakpoints. */
public synchronized void clearBreakpoints() {
//TODO: handle busy-ness correctly
if (isBusy()) {
log(Level.WARNING, "busy");
return;
}
for (LineBreakpoint bp : breakpoints) {
bp.remove();
}
breakpoints.clear();
}
/**
* Clear breakpoints in a specific tab.
* @param tabFilename the tab's file name
*/
public synchronized void clearBreakpoints(String tabFilename) {
//TODO: handle busy-ness correctly
if (isBusy()) {
log(Level.WARNING, "busy");
return;
}
Iterator<LineBreakpoint> i = breakpoints.iterator();
while (i.hasNext()) {
LineBreakpoint bp = i.next();
if (bp.lineID().fileName().equals(tabFilename)) {
bp.remove();
i.remove();
}
}
}
/**
* Get the breakpoint on a certain line, if set.
* @param line the line to get the breakpoint from
* @return the breakpoint, or null if no breakpoint is set on the specified
* line.
*/
protected LineBreakpoint breakpointOnLine(LineID line) {
for (LineBreakpoint bp : breakpoints) {
if (bp.isOnLine(line)) {
return bp;
}
}
return null;
}
/** Toggle a breakpoint on the current line. */
public synchronized void toggleBreakpoint() {
toggleBreakpoint(editor.getCurrentLineID().lineIdx());
}
/**
* Toggle a breakpoint on a line in the current tab.
* @param lineIdx the line index (0-based) in the current tab
*/
public synchronized void toggleBreakpoint(int lineIdx) {
LineID line = editor.getLineIDInCurrentTab(lineIdx);
if (!hasBreakpoint(line)) {
setBreakpoint(line.lineIdx());
} else {
removeBreakpoint(line.lineIdx());
}
}
/**
* Check if there's a breakpoint on a particular line.
* @param line the line id
* @return true if a breakpoint is set on the given line, otherwise false
*/
protected boolean hasBreakpoint(LineID line) {
LineBreakpoint bp = breakpointOnLine(line);
return bp != null;
}
/** Print a list of currently set breakpoints. */
public synchronized void listBreakpoints() {
if (breakpoints.isEmpty()) {
System.out.println("no breakpoints");
} else {
System.out.println("line breakpoints:");
for (LineBreakpoint bp : breakpoints) {
System.out.println(bp);
}
}
}
/**
* Retrieve a list of breakpoint in a particular tab.
* @param tabFilename the tab's file name
* @return the list of breakpoints in the given tab
*/
public synchronized List<LineBreakpoint> getBreakpoints(String tabFilename) {
List<LineBreakpoint> list = new ArrayList<LineBreakpoint>();
for (LineBreakpoint bp : breakpoints) {
if (bp.lineID().fileName().equals(tabFilename)) {
list.add(bp);
}
}
return list;
}
/**
* Callback for VM events. Will be called from another thread.
* ({@link VMEventReader})
* @param es Incoming set of events from VM
*/
@Override
public synchronized void vmEvent(EventSet es) {
for (Event e : es) {
log(Level.INFO, "*** VM Event: {0}", e.toString());
if (e instanceof VMStartEvent) {
vmStartEvent();
} else if (e instanceof ClassPrepareEvent) {
vmClassPrepareEvent((ClassPrepareEvent) e);
} else if (e instanceof BreakpointEvent) {
vmBreakPointEvent((BreakpointEvent) e);
} else if (e instanceof StepEvent) {
vmStepEvent((StepEvent) e);
} else if (e instanceof VMDisconnectEvent) {
stopDebug();
} else if (e instanceof VMDeathEvent) {
started = false;
editor.statusEmpty();
}
}
}
private void vmStartEvent() {
// break on main class load
log(Level.INFO, "requesting event on main class load: {0}", mainClassName);
ClassPrepareRequest mainClassPrepare = runtime.vm().eventRequestManager().createClassPrepareRequest();
mainClassPrepare.addClassFilter(mainClassName);
mainClassPrepare.enable();
// break on loading custom classes
for (SketchCode tab : editor.getSketch().getCode()) {
if (tab.isExtension("java")) {
log(Level.INFO, "requesting event on class load: {0}", tab.getPrettyName());
ClassPrepareRequest customClassPrepare = runtime.vm().eventRequestManager().createClassPrepareRequest();
customClassPrepare.addClassFilter(tab.getPrettyName());
customClassPrepare.enable();
}
}
runtime.vm().resume();
}
private void vmClassPrepareEvent(ClassPrepareEvent ce) {
ReferenceType rt = ce.referenceType();
currentThread = ce.thread();
paused = true; // for now we're paused
if (rt.name().equals(mainClassName)) {
//printType(rt);
mainClass = rt;
log(Level.INFO, "main class load: {0}", rt.name());
started = true; // now that main class is loaded, we're started
} else {
classes.add(rt); // save loaded classes
log(Level.INFO, "class load: {0}", rt.name());
}
// notify listeners
for (ClassLoadListener listener : classLoadListeners) {
if (listener != null) {
listener.classLoaded(rt);
}
}
paused = false; // resuming now
runtime.vm().resume();
}
private void vmBreakPointEvent(BreakpointEvent be) {
currentThread = be.thread(); // save this thread
updateVariableInspector(currentThread); // this is already on the EDT
final LineID newCurrentLine = locationToLineID(be.location());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
editor.setCurrentLine(newCurrentLine);
editor.deactivateStep();
editor.deactivateContinue();
}
});
// hit a breakpoint during a step, need to cancel the step.
if (requestedStep != null) {
runtime.vm().eventRequestManager().deleteEventRequest(requestedStep);
requestedStep = null;
}
// fix canvas update issue
// TODO: is this a good solution?
resumeOtherThreads(currentThread);
paused = true;
editor.statusHalted();
}
private void vmStepEvent(StepEvent se) {
currentThread = se.thread();
//printSourceLocation(currentThread);
updateVariableInspector(currentThread); // this is already on the EDT
final LineID newCurrentLine = locationToLineID(se.location());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
editor.setCurrentLine(newCurrentLine);
editor.deactivateStep();
editor.deactivateContinue();
}
});
// delete the steprequest that triggered this step so new ones can be placed (only one per thread)
EventRequestManager mgr = runtime.vm().eventRequestManager();
mgr.deleteEventRequest(se.request());
requestedStep = null; // mark that there is no step request pending
paused = true;
editor.statusHalted();
// disallow stepping into invisible lines
if (!locationIsVisible(se.location())) {
// TODO: this leads to stepping, should it run on the EDT?
stepOutIntoViewOrContinue();
}
}
/**
* Check whether a location corresponds to a code line in the editor.
* @param l the location
* @return true if the location corresponds to a line in the editor
*/
protected boolean locationIsVisible(Location l) {
return locationToLineID(l) != null;
}
/**
* Step out if this results in a visible location, otherwise continue.
*/
protected void stepOutIntoViewOrContinue() {
try {
List<StackFrame> frames = currentThread.frames();
if (frames.size() > 1) {
if (locationIsVisible(frames.get(1).location())) {
//System.out.println("stepping out to: " + locationToString(frames.get(1).location()));
stepOut();
return;
}
}
continueDebug();
} catch (IncompatibleThreadStateException ex) {
log(Level.SEVERE, null, ex);
}
}
/**
* Check whether a debugging session is running. i.e. the debugger is
* connected to a debuggee VM, VMStartEvent has been received and main
* class is loaded.
* @return true if the debugger is started.
*/
public synchronized boolean isStarted() {
return started && runtime != null && runtime.vm() != null;
}
/**
* Check whether the debugger is paused. i.e. it is currently suspended
* at a breakpoint or step.
*
* @return true if the debugger is paused, false otherwise or if not started
* ({@link #isStarted()})
*/
public synchronized boolean isPaused() {
return isStarted() && paused && currentThread != null && currentThread.isSuspended();
}
/**
* Check whether the debugger is currently busy. i.e. running (not
* suspended).
* @return true if the debugger is currently running and not suspended.
*/
public synchronized boolean isBusy() {
return isStarted() && !isPaused();
}
/**
* Print call stack trace of a thread. Only works on suspended threads.
* @param t suspended thread to print stack trace of
*/
protected void printStackTrace(ThreadReference t) {
if (!t.isSuspended()) {
return;
}
try {
System.out.println("stack trace for thread " + t.name() + ":");
int i = 0;
for (StackFrame f : t.frames()) {
// Location l = f.location();
System.out.println(i++ + ": " + f.toString());
}
} catch (IncompatibleThreadStateException ex) {
log(Level.SEVERE, null, ex);
}
}
/**
* Resume all other threads except the one given as parameter. Useful
* e.g. to just keep the thread suspended a breakpoint occurred in.
* @param t the thread not to resume
*/
protected void resumeOtherThreads(ThreadReference t) {
if (!isStarted()) {
return;
}
for (ThreadReference other : vm().allThreads()) {
if (!other.equals(t) && other.isSuspended()) {
other.resume();
}
}
}
/**
* Print info about all current threads. Includes name, status,
* isSuspended, isAtBreakpoint.
*/
public synchronized void printThreads() {
if (!isPaused()) {
return;
}
System.out.println("threads:");
for (ThreadReference t : vm().allThreads()) {
printThread(t);
}
}
/**
* Print info about a thread. Includes name, status, isSuspended,
* isAtBreakpoint.
* @param t the thread to print info about
*/
protected void printThread(ThreadReference t) {
System.out.println(t.name());
System.out.println(" is suspended: " + t.isSuspended());
System.out.println(" is at breakpoint: " + t.isAtBreakpoint());
System.out.println(" status: " + threadStatusToString(t.status()));
}
/**
* Convert a status code returned by {@link ThreadReference#status() }
* to a human readable form.
* @param status {@link ThreadReference#THREAD_STATUS_MONITOR},
* {@link ThreadReference#THREAD_STATUS_NOT_STARTED},
* {@link ThreadReference#THREAD_STATUS_RUNNING},
* {@link ThreadReference#THREAD_STATUS_SLEEPING},
* {@link ThreadReference#THREAD_STATUS_UNKNOWN},
* {@link ThreadReference#THREAD_STATUS_WAIT} or
* {@link ThreadReference#THREAD_STATUS_ZOMBIE}
* @return String containing readable status code.
*/
protected String threadStatusToString(int status) {
switch (status) {
case ThreadReference.THREAD_STATUS_MONITOR:
return "THREAD_STATUS_MONITOR";
case ThreadReference.THREAD_STATUS_NOT_STARTED:
return "THREAD_STATUS_NOT_STARTED";
case ThreadReference.THREAD_STATUS_RUNNING:
return "THREAD_STATUS_RUNNING";
case ThreadReference.THREAD_STATUS_SLEEPING:
return "THREAD_STATUS_SLEEPING";
case ThreadReference.THREAD_STATUS_UNKNOWN:
return "THREAD_STATUS_UNKNOWN";
case ThreadReference.THREAD_STATUS_WAIT:
return "THREAD_STATUS_WAIT";
case ThreadReference.THREAD_STATUS_ZOMBIE:
return "THREAD_STATUS_ZOMBIE";
default:
return "";
}
}
/**
* Print local variables on a suspended thread. Takes the topmost stack
* frame and lists all local variables and their values.
*
* @param t suspended thread
*/
protected void printLocalVariables(ThreadReference t) {
if (!t.isSuspended()) {
return;
}
try {
if (t.frameCount() == 0) {
System.out.println("call stack empty");
} else {
StackFrame sf = t.frame(0);
List<LocalVariable> locals = sf.visibleVariables();
if (locals.isEmpty()) {
System.out.println("no local variables");
return;
}
for (LocalVariable lv : locals) {
System.out.println(lv.typeName() + " " + lv.name() + " = " + sf.getValue(lv));
}
}
} catch (IncompatibleThreadStateException ex) {
log(Level.SEVERE, null, ex);
} catch (AbsentInformationException ex) {
System.out.println("local variable information not available");
}
}
/**
* Update variable inspector window. Displays local variables and this
* fields.
* @param t suspended thread to retrieve locals and this
*/
protected void updateVariableInspector(ThreadReference t) {
if (!t.isSuspended()) {
return;
}
try {
if (t.frameCount() == 0) {
// TODO: needs to be handled in a better way:
log(Level.WARNING, "call stack empty");
} else {
final DebugTray vi = editor.variableInspector();
// first get data
final List<DefaultMutableTreeNode> stackTrace = getStackTrace(t);
final List<VariableNode> locals = getLocals(t, 0);
final String currentLocation = currentLocation(t);
final List<VariableNode> thisFields = getThisFields(t, 0, true);
final List<VariableNode> declaredThisFields = getThisFields(t, 0, false);
final String thisName = thisName(t);
// now update asynchronously
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//System.out.println("updating vi. from EDT: " + javax.swing.SwingUtilities.isEventDispatchThread());
vi.updateCallStack(stackTrace, "Call Stack");
vi.updateLocals(locals, "Locals at " + currentLocation);
vi.updateThisFields(thisFields, "Class " + thisName);
vi.updateDeclaredThisFields(declaredThisFields, "Class " + thisName);
vi.unlock(); // need to do this before rebuilding, otherwise we get these ... dots in the labels
vi.rebuild();
}
});
}
} catch (IncompatibleThreadStateException ex) {
log(Level.SEVERE, null, ex);
}
}
/**
* Get the class name of the current this object in a suspended thread.
* @param t a suspended thread
* @return the class name of this
*/
protected String thisName(ThreadReference t) {
try {
if (!t.isSuspended() || t.frameCount() == 0) {
return "";
}
return t.frame(0).thisObject().referenceType().name();
} catch (IncompatibleThreadStateException ex) {
log(Level.SEVERE, null, ex);
return "";
}
}
/**
* Get a description of the current location in a suspended thread.
* Format: class.method:translated_line_number
* @param t a suspended thread
* @return descriptive string for the given location
*/
protected String currentLocation(ThreadReference t) {
try {
if (!t.isSuspended() || t.frameCount() == 0) {
return "";
}
return locationToString(t.frame(0).location());
} catch (IncompatibleThreadStateException ex) {
log(Level.SEVERE, null, ex);
return "";
}
}
/**
* Get a string describing a location.
* Format: class.method:translated_line_number
* @param loc a location
* @return descriptive string for the given location
*/
protected String locationToString(Location loc) {
LineID line = locationToLineID(loc);
int lineNumber = (line != null) ? (line.lineIdx() + 1) : loc.lineNumber();
return loc.declaringType().name() + "." + loc.method().name() + ":" + lineNumber;
}
/**
* Compile a list of current locals usable for insertion into a
* {@link JTree}. Recursively resolves object references.
* @param t the suspended thread to get locals for
* @param depth how deep to resolve nested object references. 0 will not
* resolve nested objects.
* @return the list of current locals
*/
protected List<VariableNode> getLocals(ThreadReference t, int depth) {
//System.out.println("getting locals");
List<VariableNode> vars = new ArrayList<VariableNode>();
try {
if (t.frameCount() > 0) {
StackFrame sf = t.frame(0);
for (LocalVariable lv : sf.visibleVariables()) {
//System.out.println("local var: " + lv.name());
Value val = sf.getValue(lv);
VariableNode var = new LocalVariableNode(lv.name(), lv.typeName(), val, lv, sf);
if (depth > 0) {
var.addChildren(getFields(val, depth - 1, true));
}
vars.add(var);
}
}
} catch (IncompatibleThreadStateException ex) {
log(Level.SEVERE, null, ex);
} catch (AbsentInformationException ex) {
log(Level.WARNING, "local variable information not available", ex);
}
return vars;
}
/**
* Compile a list of fields in the current this object usable for insertion
* into a {@link JTree}. Recursively resolves object references.
* @param t the suspended thread to get locals for
* @param depth how deep to resolve nested object references. 0 will not
* resolve nested objects.
* @return the list of fields in the current this object
*/
protected List<VariableNode> getThisFields(ThreadReference t, int depth,