-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInteractiveDebugger.kt
More file actions
811 lines (739 loc) · 31.9 KB
/
InteractiveDebugger.kt
File metadata and controls
811 lines (739 loc) · 31.9 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
package be.ugent.topl.mio.ui
import WasmBinary
import be.ugent.topl.mio.DebuggerConfig
import be.ugent.topl.mio.connections.Connection
import be.ugent.topl.mio.debugger.ConstraintParser
import be.ugent.topl.mio.debugger.Debugger
import be.ugent.topl.mio.debugger.MultiverseDebugger
import be.ugent.topl.mio.debugger.PrimitiveNode
import be.ugent.topl.mio.sourcemap.SourceMap
import be.ugent.topl.mio.woodstate.Checkpoint
import be.ugent.topl.mio.woodstate.WOODDumpResponse
import com.formdev.flatlaf.FlatClientProperties
import com.formdev.flatlaf.FlatLaf
import com.formdev.flatlaf.extras.FlatSVGIcon
import com.formdev.flatlaf.util.SystemInfo
import getBinaryInfo
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea
import org.fife.ui.rsyntaxtextarea.SyntaxConstants
import org.fife.ui.rsyntaxtextarea.Theme
import org.fife.ui.rtextarea.IconRowHeader
import org.fife.ui.rtextarea.RTextScrollPane
import java.awt.*
import java.awt.event.MouseEvent
import java.awt.event.MouseListener
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.io.File
import java.io.IOException
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.table.DefaultTableModel
import kotlin.concurrent.thread
class InteractiveDebugger(
connection: Connection,
symbolicWdcliPath: String,
private val sourceMapping: SourceMap? = null,
private val wasmFile: String = "/home/maarten/Documents/School/Thesis/thesis-git/wardbg/simple-sym-test.wasm",
private val config: DebuggerConfig
) : JFrame("WARDuino Debugger") {
private val binaryInfo = getBinaryInfo(symbolicWdcliPath, File(wasmFile).absolutePath)
private val debugger = MultiverseDebugger(
connection,
WasmBinary(File(wasmFile), binaryInfo),
symbolicWdcliPath,
false,
this::onGraphUpdate,
this::onMockingUpdate,
this::onHitBreakpoint
)
private val pauseButton = JButton().apply {
toolTipText = "Pause/Continue"
}
private val stepBackButton = JButton().apply {
toolTipText = "Step back one instruction"
}
private val stepOverButton = JButton().apply {
toolTipText = "Step over one instruction"
}
private val stepIntoButton = JButton().apply {
toolTipText = "Step a single instruction"
}
private val stepBackLineButton = JButton().apply {
toolTipText = "Step to the previous line"
}
private val stepLineButton = JButton().apply {
toolTipText = "Step to the next line"
}
private val stepOverLineButton = JButton().apply {
toolTipText = "Step over line"
}
private val flashButton = JButton().apply {
toolTipText = "Upload module to microcontroller"
}
private val progressBar = JProgressBar().apply {
isVisible = false
}
private val allButtons = listOf(pauseButton, stepBackButton, stepOverButton, stepIntoButton, stepLineButton, stepBackLineButton, stepOverLineButton, flashButton)
private val pausedOnlyButtons = listOf(stepBackButton, stepOverButton, stepIntoButton, stepLineButton, stepBackLineButton, stepOverLineButton)
private var paused = false
init {
allButtons.forEach { btn ->
btn.addActionListener {
multiversePanel.clearSelection()
}
}
}
private val textArea = RSyntaxTextArea()
private val scrollPane = RTextScrollPane(textArea, true)
private val multiversePanel = MultiversePanel(debugger, config) { checkpoint, progress ->
if (checkpoint != null) {
updateStepBackButton()
updatePcLabel()
}
allButtons.forEach { it.isEnabled = progress >= 1.0 }
progressBar.isVisible = progress < 1.0
progressBar.value = (progress * 100.0).toInt()
progressBar.maximum
}
private val watchWindow = WatchWindow()
private val debugBlue = if (!FlatLaf.isLafDark()) Color(0, 122, 204) else Color(117, 190, 255)
private val debugGreen = if (!FlatLaf.isLafDark()) Color(89, 158, 94) else Color(136, 207, 131)
private val continueIcon = FlatSVGIcon(javaClass.getResource("/debug-continue.svg"))
init {
continueIcon.colorFilter = FlatSVGIcon.ColorFilter()
continueIcon.colorFilter.add( Color.black, debugGreen, debugGreen)
}
private val pauseIcon = FlatSVGIcon(javaClass.getResource("/debug-pause.svg"))
private val breakpointIcon = FlatSVGIcon(javaClass.getResource("/debug-breakpoint-small.svg"))
init {
breakpointIcon.colorFilter = FlatSVGIcon.ColorFilter()
breakpointIcon.colorFilter.add( Color.black, Color(229, 20, 1), Color(229, 20, 1))
}
private var currentFileName = sourceMapping?.getSourceFile(0)
init {
FlatSVGIcon.ColorFilter.getInstance()
.add( Color.black, debugBlue, debugBlue)
updateEnabledButtons()
pauseButton.icon = pauseIcon
pauseButton.addActionListener {
if (paused) {
debugger.run()
pauseButton.icon = pauseIcon
} else {
debugger.pause()
pauseButton.icon = FlatSVGIcon(continueIcon)
}
paused = !paused
updateEnabledButtons()
updatePcLabel()
}
stepBackButton.icon = FlatSVGIcon(javaClass.getResource("/debug-step-back.svg"))
stepBackButton.addActionListener {
println("Step back")
//debugger.stepBack()
debugger.stepBack(1, binaryInfo) {}
updateStepBackButton()
updatePcLabel()
}
stepOverButton.icon = FlatSVGIcon(javaClass.getResource("/debug-step-over.svg"))
stepOverButton.addActionListener {
println("Step over")
debugger.stepOver()
updateStepBackButton()
updatePcLabel()
}
stepIntoButton.icon = FlatSVGIcon(javaClass.getResource("/debug-step-into.svg"))
stepIntoButton.addActionListener {
println("Step into")
debugger.stepInto()
updateStepBackButton()
updatePcLabel()
}
stepLineButton.icon = FlatSVGIcon(javaClass.getResource("/debug-step-into.svg"))
stepLineButton.addActionListener {
if (sourceMapping == null) {
stepLineButton.isEnabled = false
return@addActionListener
}
println("Step line")
var startLine = -1
try {
startLine = sourceMapping.getLineForPc(debugger.checkpoints.last()!!.snapshot.pc!!)
} catch(re: RuntimeException) {
System.err.println("WARNING: " + re.message)
}
debugger.stepUntil {
try {
sourceMapping.getLineForPc(it.pc!!) != startLine
} catch(re: RuntimeException) {
System.err.println("WARNING: " + re.message)
false
}
}
updateStepBackButton()
updatePcLabel()
}
stepBackLineButton.icon = FlatSVGIcon(javaClass.getResource("/debug-step-out.svg"))
stepBackLineButton.addActionListener {
if (sourceMapping == null) {
stepBackLineButton.isEnabled = false
return@addActionListener
}
println("Step back line")
var startLine = -1
try {
startLine = sourceMapping.getLineForPc(debugger.checkpoints.last()!!.snapshot.pc!!)
} catch(re: RuntimeException) {
System.err.println("WARNING: " + re.message)
}
debugger.stepBackUntil(binaryInfo) {
try {
sourceMapping.getLineForPc(it.pc!!) != startLine
} catch(re: RuntimeException) {
System.err.println("WARNING: " + re.message)
false
}
}
updateStepBackButton()
updatePcLabel()
}
stepOverLineButton.icon = FlatSVGIcon(javaClass.getResource("/debug-step-over.svg"))
stepOverLineButton.addActionListener {
if (sourceMapping == null) {
stepBackLineButton.isEnabled = false
return@addActionListener
}
println("Step over line")
var startLine = -1
try {
startLine = sourceMapping.getLineForPc(debugger.checkpoints.last()!!.snapshot.pc!!)
} catch(re: RuntimeException) {
System.err.println("WARNING: " + re.message)
}
debugger.stepOverUntil {
try {
sourceMapping.getLineForPc(it.pc!!) != startLine
} catch(re: RuntimeException) {
System.err.println("WARNING: " + re.message)
false
}
}
updateStepBackButton()
updatePcLabel()
}
flashButton.icon = FlatSVGIcon(javaClass.getResource("/debug-update-module.svg"))
flashButton.addActionListener {
/*val dialog = JFileChooser()
if (dialog.showDialog(this, "Upload") == JFileChooser.APPROVE_OPTION) {
debugger.updateModule(dialog.selectedFile.absolutePath)
}*/
debugger.updateModule(wasmFile)
}
val toolBar = JToolBar()
toolBar.isFloatable = true
if (config.macIntegratedToolbar && SystemInfo.isMacFullWindowContentSupported) {
toolBar.isFloatable = false
rootPane.putClientProperty("apple.awt.transparentTitleBar", true)
rootPane.putClientProperty("apple.awt.fullWindowContent", true)
rootPane.putClientProperty("apple.awt.windowTitleVisible", false)
rootPane.putClientProperty(
FlatClientProperties.MACOS_WINDOW_BUTTONS_SPACING,
FlatClientProperties.MACOS_WINDOW_BUTTONS_SPACING_MEDIUM
)
val placeholder = JPanel()
placeholder.putClientProperty(FlatClientProperties.FULL_WINDOW_CONTENT_BUTTONS_PLACEHOLDER, "mac")
val toolBarPanel = JPanel(BorderLayout())
toolBarPanel.add(placeholder, BorderLayout.WEST)
toolBarPanel.add(toolBar, BorderLayout.CENTER)
contentPane.add(toolBarPanel, BorderLayout.NORTH)
}
toolBar.add(pauseButton)
toolBar.add(stepBackButton)
toolBar.add(stepOverButton)
toolBar.add(stepIntoButton)
toolBar.addSeparator()
toolBar.add(stepBackLineButton)
toolBar.add(stepLineButton)
toolBar.add(stepOverLineButton)
toolBar.addSeparator()
toolBar.add(flashButton)
toolBar.addSeparator()
if (config.checkpointHistory) {
toolBar.add(JButton(FlatSVGIcon(javaClass.getResource("/history.svg"))).apply {
toolTipText = "Checkpoint history"
addActionListener {
val frame = CheckpointVisualiser(debugger.checkpoints, binaryInfo, debugger)
frame.isVisible = true
}
})
}
val consoleWindow = ConsoleWindow(debugger)
val consoleToggle = JToggleButton(FlatSVGIcon(javaClass.getResource("/console.svg"))).apply {
addActionListener {
consoleWindow.isVisible = model.isSelected
}
}
consoleWindow.addWindowListener(object : WindowAdapter() {
override fun windowClosing(e: WindowEvent?) {
if (consoleToggle.model.isSelected) {
consoleToggle.model.isSelected = false
}
}
})
toolBar.add(consoleToggle)
toolBar.add(progressBar)
val theme =
if (!FlatLaf.isLafDark()) Theme.load(javaClass.getResourceAsStream("/light.xml"))
else Theme.load(javaClass.getResourceAsStream("/dark.xml"))
theme.apply(textArea)
// Increase font size:
//textArea.font = textArea.font.deriveFont(textArea.font.size + 1.0f + 10)
textArea.isEditable = false
textArea.text = sourceMapping?.getSourceFile(0) ?: "Source mapping unavailable"
textArea.syntaxEditingStyle = sourceMapping?.getStyle() ?: SyntaxConstants.SYNTAX_STYLE_ASSEMBLER_X86
textArea.popupMenu.add(JMenuItem("Disassemble").apply {
addActionListener {
try {
DisassemblyWindow(debugger, wasmFile)
} catch(e: IOException) {
JOptionPane.showMessageDialog(null, e.message, "Error", JOptionPane.ERROR_MESSAGE)
}
}
})
scrollPane.isIconRowHeaderEnabled = true
scrollPane.gutter.iconRowHeaderInheritsGutterBackground = true
if (sourceMapping != null) {
scrollPane.gutter.isBookmarkingEnabled = true
scrollPane.gutter.bookmarkIcon = breakpointIcon
for (component in scrollPane.gutter.components) {
if (component is IconRowHeader) {
component.addMouseListener(object : MouseListener {
override fun mouseClicked(me: MouseEvent) {}
override fun mousePressed(me: MouseEvent) {
val line = textArea.getLineOfOffset(textArea.viewToModel2D(me.point))
try {
val addr = sourceMapping.getPcForLine(line + 1, currentFileName!!)
if (component.getTrackingIcons(line).isNotEmpty()) {
debugger.addBreakpoint(addr)
} else {
debugger.removeBreakpoint(addr)
}
} catch (e: Exception) {
component.toggleBookmark(line)
}
}
override fun mouseReleased(p0: MouseEvent?) {}
override fun mouseEntered(p0: MouseEvent?) {}
override fun mouseExited(p0: MouseEvent?) {}
})
}
}
}
/*for (choicepoint in binaryInfo.choicepoints) {
debugger.addBreakpoint(choicepoint)
}*/
val verticalPanel = JPanel()
verticalPanel.layout = BorderLayout()
if (!SystemInfo.isMacFullWindowContentSupported || !config.macIntegratedToolbar) {
verticalPanel.add(toolBar, BorderLayout.NORTH)
}
val horizontalSplitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollPane, multiversePanel)
horizontalSplitPane.resizeWeight = 0.6
val splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, horizontalSplitPane, JScrollPane(watchWindow))
splitPane.resizeWeight = 0.8
verticalPanel.add(splitPane, BorderLayout.CENTER)
//verticalPanel.add(scrollPane, BorderLayout.CENTER)
add(verticalPanel)
minimumSize = Dimension(250, 250)
preferredSize = Dimension(700, 500)
pack()
addWindowListener(object : WindowAdapter() {
override fun windowClosing(p0: WindowEvent?) {
debugger.close()
}
})
defaultCloseOperation = EXIT_ON_CLOSE
isVisible = true
}
init {
debugger.startReading()
debugger.setSnapshotPolicy(Debugger.SnapshotPolicy.Checkpointing())
pause()
}
private fun pause() {
debugger.pause()
pauseButton.icon = FlatSVGIcon(continueIcon)
paused = !paused
updateEnabledButtons()
updatePcLabel()
}
private fun updateEnabledButtons() {
pausedOnlyButtons.forEach { it.isEnabled = paused }
multiversePanel.isEnabled = paused
if (paused) {
updateStepBackButton()
}
}
private fun updateStepBackButton() {
stepBackButton.isEnabled = debugger.checkpoints.size > 1
stepBackLineButton.isEnabled = debugger.checkpoints.size > 1
}
private fun updatePcLabel() {
if (!paused) {
textArea.removeAllLineHighlights()
watchWindow.clear()
return
}
//val snapshot = debugger.currentSnapshot!!
val snapshot = debugger.checkpoints.last()!!.snapshot
//val snapshot = debugger.snapshotFull().second
watchWindow.update(snapshot)
if (sourceMapping == null)
return
updateBreakPoints(snapshot)
val pc = snapshot.pc!!
try {
val lineNumber = sourceMapping.getLineForPc(pc)
if (sourceMapping.getSourceFile(pc) != textArea.text)
textArea.text = sourceMapping.getSourceFile(pc)
currentFileName = sourceMapping.getSourceFileName(pc)
if (textArea.syntaxEditingStyle != sourceMapping.getStyle()) {
textArea.syntaxEditingStyle = sourceMapping.getStyle()
}
textArea.removeAllLineHighlights()
textArea.addLineHighlight(lineNumber - 1, if (!FlatLaf.isLafDark()) Color(255, 255, 186, 255) else Color(207, 207, 131, 75))
val lineY = textArea.yForLine(lineNumber - 1)
if (lineY < scrollPane.verticalScrollBar.value || lineY + 20 > scrollPane.verticalScrollBar.value + scrollPane.height) {
try {
scrollPane.verticalScrollBar.value = textArea.yForLine((lineNumber - 11).coerceAtLeast(0))
}
catch (_: Exception) {}
}
} catch(iae : RuntimeException) {
/*
* Mostly happens on end and else instructions because there is no line number returned for these
* instructions when using wat2wasm.
*/
System.err.println("WARNING: " + iae.message)
}
}
private fun updateBreakPoints(snapshot: WOODDumpResponse) {
if (sourceMapping == null)
return;
val breakpoints = snapshot.breakpoints!!
scrollPane.gutter.removeAllTrackingIcons()
for (breakPointPc in breakpoints) {
scrollPane.gutter.addLineTrackingIcon(sourceMapping.getLineForPc(breakPointPc) - 1, breakpointIcon, "Breakpoint")
}
}
private fun onHitBreakpoint(pc: Int) {
println("onPause pc = ${pc.toString(16)}")
paused = true
pauseButton.icon = continueIcon
updateEnabledButtons()
updatePcLabel()
}
private fun onGraphUpdate() {
multiversePanel.graphChanged()
}
private fun onMockingUpdate() {
multiversePanel.onMockingChanged()
}
}
interface MultiverseAction {
fun doAction()
}
class OverrideAction(val debugger: Debugger, val node: PrimitiveNode, val index: Int) : MultiverseAction {
override fun doAction() {
debugger.addPrimitiveOverride(node.primitive, node.arg, node.values[index])
}
}
class ContinueForAction(val debugger: Debugger, var n: Int) : MultiverseAction {
override fun doAction() {
debugger.continueFor(n)
}
}
class MultiversePanel(private val multiverseDebugger: MultiverseDebugger, config: DebuggerConfig, stateChanged: (c: Checkpoint?, b: Double) -> Unit) : JPanel() {
private val graphPanel = GraphPanel(multiverseDebugger.graph)
private val mockPanel = OverridesPanel()
private val concolicButton = JButton("Suggest interesting paths")
private var maxInstructions = 50
private val concolicOptionsButton = JButton().apply {
val gearIcon = FlatSVGIcon(MultiverseDebugger::javaClass.javaClass.getResource("/settings-gear.svg"))
gearIcon.colorFilter = FlatSVGIcon.ColorFilter()
gearIcon.colorFilter.add(Color.black, UIManager.getDefaults().getColor("Button.foreground"), UIManager.getDefaults().getColor("Button.foreground"))
icon = gearIcon
addActionListener {
JOptionPane.showInputDialog("Instruction limit", maxInstructions)?.let {
maxInstructions = it.toInt()
}
}
}
private val customButton = JButton("Mock").apply {
isEnabled = false
}
private val followButton = JButton(if (config.concolic) "Slide" else "Jump").apply {
isEnabled = false
}
init {
layout = BorderLayout()
//add(JScrollPane(graphPanel))
val scrollpane = JScrollPane(graphPanel)
graphPanel.associatedScrollPane = scrollpane
add(JSplitPane(JSplitPane.VERTICAL_SPLIT, scrollpane, mockPanel).apply {
resizeWeight = 0.7
})
//add(OverridesPanel(), BorderLayout.EAST)
add(JPanel(FlowLayout(FlowLayout.RIGHT)).apply {
if (config.concolic) {
add(concolicOptionsButton)
add(concolicButton)
}
add(customButton)
add(followButton)
}, BorderLayout.SOUTH)
concolicButton.addActionListener {
val w = BlockingWindow(null, "Analysing program")
w.location = Point(this.location.x + this.width/2 - w.width/2, this.location.y + this.height/2 - w.height/2)
w.run({ multiverseDebugger.predictFuture(maxInstructions) }) { graphChanged ->
if (!graphChanged) {
JOptionPane.showMessageDialog(this, "No future branching paths could be found")
}
}
}
graphPanel.addSelectionListener {
followButton.isEnabled = graphPanel.selectedValue != null
}
followButton.addActionListener {
graphPanel.allowSelection = false
stateChanged(null, 0.0)
followButton.isEnabled = false
customButton.isEnabled = false
thread {
// Disable breakpoints
val breakpointsStart = multiverseDebugger.checkpoints.last()!!.snapshot.breakpoints!!
for (breakpoint in breakpointsStart) {
multiverseDebugger.removeBreakpoint(breakpoint)
}
multiverseDebugger.printCheckpoints(multiverseDebugger.wasmBinary.metadata)
val backwardsLength = graphPanel.selectedPath!!.first.size
val forwardsLength = graphPanel.selectedPath!!.second.size
val totalLength = backwardsLength + forwardsLength
val backwardPath = graphPanel.selectedPath!!.first.toMutableList()
var finishedSteps = 0
multiverseDebugger.stepBack(backwardPath.size, multiverseDebugger.wasmBinary.metadata) {
graphPanel.completedPath.add(backwardPath.removeFirst())
graphPanel.repaint()
val remaining = forwardsLength + backwardPath.size
finishedSteps = totalLength - remaining
stateChanged(multiverseDebugger.checkpoints.last(), finishedSteps / totalLength.toDouble())
}
val forwardPath = graphPanel.selectedPath!!.second.toMutableList()
val actionPath = mutableListOf<MultiverseAction>()
for (i in 1..<forwardPath.size) {
val a = forwardPath[i - 1]
val b = forwardPath[i]
val index = a.children.indexOf(b)
if (a is PrimitiveNode) {
actionPath.add(OverrideAction(multiverseDebugger, a, index))
}
if (actionPath.isEmpty() || actionPath.last() is OverrideAction) {
actionPath.add(ContinueForAction(multiverseDebugger, 0))
}
val lastAction = actionPath.last() as ContinueForAction
lastAction.n++
}
for (action in actionPath) {
action.doAction()
if (action is ContinueForAction) {
finishedSteps += action.n
stateChanged(multiverseDebugger.checkpoints.last(), finishedSteps / totalLength.toDouble())
repeat(action.n) {
graphPanel.completedPath.add(forwardPath.removeFirst())
}
graphPanel.repaint()
}
}
graphPanel.repaint()
// Re-enable breakpoints
for (breakpoint in breakpointsStart) {
multiverseDebugger.addBreakpoint(breakpoint)
}
stateChanged(multiverseDebugger.checkpoints.last(), 1.0)
//debugger.continueFor(forwardPath.size - 1)
graphPanel.completedPath.add(forwardPath.last())
graphPanel.repaint()
//multiverseDebugger.graph.currentNode = forwardPath.last()
graphPanel.completedPath.clear()
graphPanel.selectedNodes.clear()
graphPanel.repaint()
multiverseDebugger.printCheckpoints(multiverseDebugger.wasmBinary.metadata)
graphPanel.clearSelection()
customButton.isEnabled = true
graphPanel.allowSelection = true
}
}
customButton.addActionListener {
val currentNode = multiverseDebugger.graph.currentNode
val mainPanel = JPanel()
val primitiveNameTextField = JComboBox<String>()
multiverseDebugger.wasmBinary.metadata.primitive_fidx_mapping.forEach {
primitiveNameTextField.addItem(it)
}
mainPanel.add(primitiveNameTextField)
mainPanel.add(JLabel("("))
val argTextField = JTextField()
mainPanel.add(argTextField)
mainPanel.add(JLabel(") = "))
val returnValueTextField = JTextField()
mainPanel.add(returnValueTextField)
if (currentNode is PrimitiveNode) {
argTextField.isEnabled = false
argTextField.text = currentNode.arg.toString()
primitiveNameTextField.isEnabled = false
primitiveNameTextField.selectedItem = currentNode.primitive
}
val relations = if (File(DebuggerConfig.configDir + "/program.constraints").exists()) ConstraintParser.parseFile("test.constraints") else listOf()
fun handleRelations() {
returnValueTextField.isEnabled = true
for (relation in relations) {
if (primitiveNameTextField.selectedItem == relation.override.primName &&
argTextField.text == relation.override.arg.toString()
) {
val state = multiverseDebugger.getCurrentState()
val realValue = state.io!!.find { it.key == relation.io.key }?.value
if (realValue != null && relation.comp(realValue, relation.io.value)) {
returnValueTextField.text = relation.override.returnValue.toString()
returnValueTextField.isEnabled = false
}
}
}
}
// Re-check relations when changing primitive or argument.
primitiveNameTextField.addActionListener {
handleRelations()
}
argTextField.document.addDocumentListener(object : DocumentListener {
override fun insertUpdate(e: DocumentEvent?) {
handleRelations()
}
override fun removeUpdate(e: DocumentEvent?) {
handleRelations()
}
override fun changedUpdate(e: DocumentEvent?) {
handleRelations()
}
})
val pauseIcon = ImageIcon(javaClass.getResource("/logo-small.png"))
val allOptions = arrayOf("Create range", "Mock", "Cancel")
val optionPane = JOptionPane(mainPanel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION).apply {
//options = options1.toTypedArray()
val rangeButton = JButton(allOptions[0])
val mockButton = JButton(allOptions[1])
val cancelButton = JButton(allOptions[2])
options = arrayOf(rangeButton, mockButton, cancelButton)
rangeButton.isEnabled = currentNode is PrimitiveNode
rangeButton.addActionListener {
this.value = rangeButton.text
}
mockButton.addActionListener {
this.value = mockButton.text
}
cancelButton.addActionListener {
this.value = cancelButton.text
}
}
val dialog = optionPane.createDialog(null, "Mock primitive call")
dialog.setIconImage(pauseIcon.image)
dialog.isVisible = true
val x = optionPane.value
if (x == allOptions[1]) {
val primitiveName = primitiveNameTextField.selectedItem as String
val arg = argTextField.text.toInt()
val returnValue = (returnValueTextField.text as String).toInt()
multiverseDebugger.addPrimitiveOverride(primitiveName, arg, returnValue)
} else if (x == allOptions[0]) {
showPathRangeWindow()
}
}
}
private fun showPathRangeWindow() {
val myPanel = JPanel()
myPanel.add(JLabel("min:"))
val minTextField = JTextField()
myPanel.add(minTextField)
myPanel.add(Box.createHorizontalStrut(15))
myPanel.add(JLabel("max:"))
val maxTextField = JTextField()
myPanel.add(maxTextField)
myPanel.add(JLabel("step:"))
val stepTextField = JTextField()
myPanel.add(stepTextField)
if (JOptionPane.showConfirmDialog(
null, myPanel,
"Choose path range", JOptionPane.OK_CANCEL_OPTION
) == JOptionPane.OK_OPTION
) {
val min = minTextField.text.toInt()
val max = maxTextField.text.toInt()
val step = stepTextField.text.toInt()
for (x in min..max step step) {
multiverseDebugger.createNewPath(x, false)
}
}
}
fun graphChanged() {
graphPanel.repaint()
graphPanel.revalidate()
//customButton.isEnabled = multiverseDebugger.graph.currentNode is PrimitiveNode
}
fun clearSelection() {
graphPanel.clearSelection()
graphPanel.repaint()
}
fun onMockingChanged() {
mockPanel.clear()
for (primMocks in multiverseDebugger.overrides) {
for (argResultPair in primMocks.value) {
mockPanel.addItem(primMocks.key, listOf(argResultPair.key), argResultPair.value) {
multiverseDebugger.removePrimitiveOverride(primMocks.key, argResultPair.key)
}
}
}
}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
concolicOptionsButton.isEnabled = enabled
concolicButton.isEnabled = enabled
//customButton.isEnabled = enabled && multiverseDebugger.graph.currentNode is PrimitiveNode
customButton.isEnabled = enabled
followButton.isEnabled = enabled
}
}
class WatchWindow : JTable() {
private val tableModel = DefaultTableModel()
init {
model = tableModel
tableModel.setColumnIdentifiers(arrayOf("Name", "Type", "Value"))
setDefaultEditor(Any::class.java, null)
}
fun update(snapshot: WOODDumpResponse) {
tableModel.rowCount = 0
tableModel.addRow(arrayOf("pc", "i32", String.format("0x%x", snapshot.pc)))
for (global in snapshot.globals!!) {
tableModel.addRow(arrayOf("global ${global.idx}", global.type, global.value))
}
if (snapshot.callstack!!.isNotEmpty()) {
tableModel.addRow(arrayOf("fp", "i32", snapshot.callstack.last().fp))
}
val stack = snapshot.stack!!
for (stackElement in stack) {
tableModel.addRow(arrayOf("stack[${stackElement.idx}]", stackElement.type, stackElement.value))
}
}
fun clear() {
tableModel.rowCount = 0
}
}