-
Notifications
You must be signed in to change notification settings - Fork 16
/
debug.go
1227 lines (1072 loc) · 36.2 KB
/
debug.go
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
package main
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/cyrus-and/gdb"
"github.com/ianlancetaylor/demangle"
"github.com/xyproto/mode"
"github.com/xyproto/vt100"
)
const (
smallRegisterWindow = iota
largeRegisterWindow
noRegisterWindow
)
var (
originalDirectory string
gdbLogFile = filepath.Join(userCacheDir, "o", "gdb.log")
gdbConsole strings.Builder
watchMap = make(map[string]string)
lastSeenWatchVariable string
showInstructionPane bool
gdbOutput bytes.Buffer
lastGDBOutputLength int
errProgramStopped = errors.New("program stopped") // must contain "program stopped"
programRunning bool
prevFlags []string
longInstructionPaneWidth int // should the instruction pane be extra wide, if so, how wide?
gdbPathRust *string
gdbPathRegular *string
)
// DebugActivateBreakpoint sends break-insert to gdb together with the breakpoint in e.breakpoint, if available
func (e *Editor) DebugActivateBreakpoint(sourceBaseFilename string) (string, error) {
if e.breakpoint != nil {
if retvalMap, err := e.gdb.CheckedSend("break-insert", fmt.Sprintf("%s:%d", sourceBaseFilename, e.breakpoint.LineNumber())); err != nil {
return fmt.Sprintf("%v", retvalMap), err
}
return "", nil
}
return "", errors.New("e.breakpoint is not set")
}
// DebugStart will start a new debug session, using gdb.
// Will end the existing session first if e.gdb != nil.
func (e *Editor) DebugStart(sourceDir, sourceBaseFilename, executableBaseFilename string, doneFunc func()) (string, error) {
flogf(gdbLogFile, "[gdb] dir %s, src %s, exe %s\n", sourceDir, sourceBaseFilename, executableBaseFilename)
// End any existing sessions
e.DebugEnd()
// Change directory to the sourcefile, temporarily
var err error
originalDirectory, err = os.Getwd()
if err == nil { // cd success
err = os.Chdir(sourceDir)
if err != nil {
return "", errors.New("could not change directory to " + sourceDir)
}
}
// Find the path to either "rust-gdb" or "gdb", depending on the mode
gdbPath := e.findGDB()
//flogf(gdbLogFile, "[gdb] starting %s: ", gdbExecutable)
// Start a new gdb session
e.gdb, err = gdb.NewCustom([]string{gdbPath}, func(notification map[string]interface{}) {
// Handle messages from gdb, including frames that contains line numbers
if payload, ok := notification["payload"]; ok {
switch notification["type"] {
case "exec":
if payloadMap, ok := payload.(map[string]interface{}); ok {
if frame, ok := payloadMap["frame"]; ok {
if frameMap, ok := frame.(map[string]interface{}); ok {
flogf(gdbLogFile, "[gdb] frame: %v\n", frameMap)
if lineNumberString, ok := frameMap["line"].(string); ok {
if lineNumber, err := strconv.Atoi(lineNumberString); err == nil { // success
// TODO: Fetch a different line number?
// Got a line number, send the editor there, without any status messages
e.GoToLineNumber(LineNumber(lineNumber), nil, nil, true)
}
}
}
}
}
case "console":
// output on stdout
if s, ok := payload.(string); ok {
gdbConsole.WriteString(s)
}
case "notify":
// notifications about events that are happening
if notification["class"] == "thread-group-exited" {
// gdb is done running
programRunning = false
doneFunc()
}
default:
//logf("[gdb] unrecognized notification: %v\n", notification)
}
//} else {
// logf("[gdb] callback without payload: %v\n", notification)
}
})
if err != nil {
e.gdb = nil
//flogf(gdbLogFile, "%s\n", "fail")
return "", err
}
if e.gdb == nil {
//flogf(gdbLogFile, "%s\n", "fail")
return "", errors.New("gdb.New returned no error, but e.gdb is nil")
}
//flogf(gdbLogFile, "%s\n", "ok")
// Handle output to stdout (and stderr?) from programs that are being debugged
go io.Copy(&gdbOutput, e.gdb)
// Load the executable file
if retvalMap, err := e.gdb.CheckedSend("file-exec-and-symbols", executableBaseFilename); err != nil {
return fmt.Sprintf("%v", retvalMap), err
}
// Pass in arguments
//e.gdb.Send("exec-arguments", "--version")
// Pass the breakpoint, if it has been set with ctrl-b
if e.breakpoint != nil {
if retvalMap, err := e.gdb.CheckedSend("break-insert", fmt.Sprintf("%s:%d", sourceBaseFilename, e.breakpoint.LineNumber())); err != nil {
return fmt.Sprintf("%v", retvalMap), err
}
}
// Assembly specific
if e.mode == mode.Assembly {
e.gdb.Send("break-insert", "-t", "1")
}
// Set the disassembly style
e.gdb.Send("gdb-set", "disassembly-flavor", "intel")
// Start from the top
if _, err := e.gdb.CheckedSend("exec-run", "--start"); err != nil {
output := gdbOutput.String()
gdbOutput.Reset()
return output, err
}
// Add any existing watches
for varName := range watchMap {
e.AddWatch(varName)
}
programRunning = true
return "started gdb", nil
}
// DebugContinue will continue the execution to the next breakpoint or to the end.
// e.gdb must not be nil.
func (e *Editor) DebugContinue() error {
if !programRunning {
return errProgramStopped
}
_, err := e.gdb.CheckedSend("exec-continue")
return err
}
// DebugRun will run the current program.
// e.gdb must not be nil.
func (e *Editor) DebugRun() error {
_, err := e.gdb.CheckedSend("exec-run")
return err
}
// DebugNext will continue the execution by stepping to the next line.
// e.gdb must not be nil.
func (e *Editor) DebugNext() error {
if !programRunning {
return errProgramStopped
}
gdbMI := "exec-next"
if e.debugStepInto {
gdbMI = "exec-step"
}
if _, err := e.gdb.CheckedSend(gdbMI); err != nil {
return err
}
consoleString := strings.TrimSpace(gdbConsole.String())
gdbConsole.Reset()
// Interpret consoleString and extract the new variable names and values,
// for variables there are watchpoints for.
if consoleString != "" {
var varName string
var varValue string
for _, line := range strings.Split(consoleString, "\n") {
if strings.Contains(line, "watchpoint") && strings.Contains(line, ":") {
fields := strings.SplitN(line, ":", 2)
varName = strings.TrimSpace(fields[1])
} else if varName != "" && strings.HasPrefix(line, "New value =") {
fields := strings.SplitN(line, "=", 2)
varValue = strings.TrimSpace(fields[1])
watchMap[varName] = varValue
lastSeenWatchVariable = varName
varName = ""
varValue = ""
}
}
}
if !programRunning {
return errProgramStopped
}
return nil
}
// DebugNextInstruction will continue the execution by stepping to the next instruction.
// e.gdb must not be nil.
func (e *Editor) DebugNextInstruction() error {
if !programRunning {
return errProgramStopped
}
showInstructionPane = true
gdbMI := "exec-next-instruction"
if e.debugStepInto {
gdbMI = "exec-step-instruction"
}
_, err := e.gdb.CheckedSend(gdbMI)
if err != nil {
return err
}
consoleString := strings.TrimSpace(gdbConsole.String())
gdbConsole.Reset()
// Interpret consoleString and extract the new variable names and values,
// for variables there are watchpoints for.
if consoleString != "" {
var varName string
var varValue string
for _, line := range strings.Split(consoleString, "\n") {
if strings.Contains(line, "watchpoint") && strings.Contains(line, ":") {
fields := strings.SplitN(line, ":", 2)
varName = strings.TrimSpace(fields[1])
} else if varName != "" && strings.HasPrefix(line, "New value =") {
fields := strings.SplitN(line, "=", 2)
varValue = strings.TrimSpace(fields[1])
watchMap[varName] = varValue
lastSeenWatchVariable = varName
varName = ""
varValue = ""
}
}
}
if !programRunning {
return errProgramStopped
}
return nil
}
// DebugStep will continue the execution by stepping.
// e.gdb must not be nil.
func (e *Editor) DebugStep() error {
if !programRunning {
return errProgramStopped
}
if _, err := e.gdb.CheckedSend("exec-step"); err != nil {
return err
}
consoleString := strings.TrimSpace(gdbConsole.String())
gdbConsole.Reset()
// Interpret consoleString and extract the new variable names and values,
// for variables there are watchpoints for.
if consoleString != "" {
var varName, varValue string
for _, line := range strings.Split(consoleString, "\n") {
if strings.Contains(line, "watchpoint") && strings.Contains(line, ":") {
fields := strings.SplitN(line, ":", 2)
varName = strings.TrimSpace(fields[1])
} else if varName != "" && strings.HasPrefix(line, "New value =") {
fields := strings.SplitN(line, "=", 2)
varValue = strings.TrimSpace(fields[1])
watchMap[varName] = varValue
lastSeenWatchVariable = varName
varName = ""
varValue = ""
}
}
}
if !programRunning {
return errProgramStopped
}
return nil
}
// DebugFinish will "step out".
// e.gdb must not be nil. Returns whatever was outputted to gdb stdout.
func (e *Editor) DebugFinish() error {
_, err := e.gdb.CheckedSend("exec-finish")
if err != nil {
return err
}
consoleString := strings.TrimSpace(gdbConsole.String())
gdbConsole.Reset()
// Interpret consoleString and extract the new variable names and values,
// for variables there are watchpoints for.
if consoleString != "" {
var varName, varValue string
for _, line := range strings.Split(consoleString, "\n") {
if strings.Contains(line, "watchpoint") && strings.Contains(line, ":") {
fields := strings.SplitN(line, ":", 2)
varName = strings.TrimSpace(fields[1])
} else if varName != "" && strings.HasPrefix(line, "New value =") {
fields := strings.SplitN(line, "=", 2)
varValue = strings.TrimSpace(fields[1])
watchMap[varName] = varValue
lastSeenWatchVariable = varName
varName = ""
varValue = ""
}
}
}
if !programRunning {
return errProgramStopped
}
return nil
}
// DebugRegisterNames will return all register names
func (e *Editor) DebugRegisterNames() ([]string, error) {
if e.gdb == nil {
return []string{}, errors.New("gdb must be running")
}
notification, err := e.gdb.CheckedSend("data-list-register-names")
if err != nil {
//flogf(gdbLogFile, "[gdb] data-list-register-names error: %s\n", err.Error())
return []string{}, err
}
if payload, ok := notification["payload"]; ok && notification["class"] == "done" {
if payloadMap, ok := payload.(map[string]interface{}); ok {
if registerNames, ok := payloadMap["register-names"]; ok {
if registerSlice, ok := registerNames.([]interface{}); ok {
registerStringSlice := make([]string, len(registerSlice))
for i, interfaceValue := range registerSlice {
if s, ok := interfaceValue.(string); ok {
registerStringSlice[i] = s
}
}
//flogf(gdbLogFile, "[gdb] data-list-register-names: %s\n", strings.Join(registerStringSlice, ","))
return registerStringSlice, nil
}
}
}
}
return []string{}, errors.New("could not find the register names in the payload returned from gdb")
}
// DebugChangedRegisters will return a list of all changed register numbers
func (e *Editor) DebugChangedRegisters() ([]int, error) {
// Then get the register values
notification, err := e.gdb.CheckedSend("data-list-changed-registers")
if err != nil {
//flogf(gdbLogFile, "[gdb] data-list-changed-registers error: %s\n", err.Error())
return []int{}, err
}
if payload, ok := notification["payload"]; ok && notification["class"] == "done" {
if payloadMap, ok := payload.(map[string]interface{}); ok {
//flogf(gdbLogFile, "[gdb] changed reg payload: %v\n", payloadMap)
if registerInterfaces, ok := payloadMap["changed-registers"].([]interface{}); ok {
changedRegisters := make([]int, len(registerInterfaces))
for _, registerNumberString := range registerInterfaces {
registerNumber, err := strconv.Atoi(registerNumberString.(string))
if err != nil {
return []int{}, err
}
changedRegisters = append(changedRegisters, registerNumber)
//flogf(gdbLogFile, "[gdb] regnum %v %T\n", registerNumber, registerNumber)
}
return changedRegisters, nil
}
}
}
//flogf(gdbLogFile, "[gdb] data-list-register-values %v\n", registers)
return []int{}, errors.New("could not find the register values in the payload returned from gdb")
}
// DebugDisassemble will return the next N assembly instructions
func (e *Editor) DebugDisassemble(n int) ([]string, error) {
// Then get the register values
notification, err := e.gdb.CheckedSend("data-disassemble -s $pc -e \"$pc + 20\" -- 0")
if err != nil {
//flogf(gdbLogFile, "[gdb] data-disassemble error: %s\n", err.Error())
return []string{}, err
}
result := []string{}
if payload, ok := notification["payload"]; ok && notification["class"] == "done" {
if payloadMap, ok := payload.(map[string]interface{}); ok {
//flogf(gdbLogFile, "[gdb] disasm payload: %v\n", payloadMap)
if asmDisSlice, ok := payloadMap["asm_insns"].([]interface{}); ok {
for i, asmDis := range asmDisSlice {
//flogf(gdbLogFile, "[gdb] disasm asm %d: %v %T\n", i, asmDis, asmDis)
if asmMap, ok := asmDis.(map[string]interface{}); ok {
instruction := asmMap["inst"]
result = append(result, instruction.(string))
}
// Only collect n asm statements
if i >= n {
//flogf(gdbLogFile, "[gdb] result %v\n", result)
break
}
}
return result, nil
}
}
}
//flogf(gdbLogFile, "[gdb] disasm result: %v\n", result)
return []string{}, errors.New("could not get disasm from gdb")
}
// DebugChangedRegisterMap returns a map of all registers that were changed the last step, and their values
func (e *Editor) DebugChangedRegisterMap() (map[string]string, error) {
// First get the names of the registers
names, err := e.DebugRegisterNames()
if err != nil {
return nil, err
}
// Then get the changed register IDs
changedRegisters, err := e.DebugChangedRegisters()
if err != nil {
return nil, err
}
// Then get the register IDs, then use them to get the register names and values
notification, err := e.gdb.CheckedSend("data-list-register-values", "--skip-unavailable", "x")
if err != nil {
//flogf(gdbLogFile, "[gdb] data-list-register-values error: %s\n", err.Error())
return nil, err
}
if payload, ok := notification["payload"]; ok && notification["class"] == "done" {
if payloadMap, ok := payload.(map[string]interface{}); ok {
if registerValues, ok := payloadMap["register-values"]; ok {
if registerSlice, ok := registerValues.([]interface{}); ok {
registers := make(map[string]string, len(names))
for _, singleRegisterMap := range registerSlice {
if registerMap, ok := singleRegisterMap.(map[string]interface{}); ok {
numberString, ok := registerMap["number"].(string)
if !ok {
return nil, errors.New("could not convert \"number\" interface to string")
}
registerNumber, err := strconv.Atoi(numberString)
if err != nil {
return nil, err
}
thisRegisterWasChanged := false
for _, changedRegisterNumber := range changedRegisters {
if changedRegisterNumber == registerNumber {
thisRegisterWasChanged = true
break
}
}
if !thisRegisterWasChanged {
// Continue to the next one in the list of all available registers
continue
}
value, ok := registerMap["value"].(string)
if !ok {
return nil, errors.New("could not convert \"value\" interface to string")
}
registerName := names[registerNumber]
registers[registerName] = value
//flogf(gdbLogFile, "[gdb] data-list-register-values: %s %s\n", registerName, value)
}
}
reg8byte := []string{"rax", "rcx", "rdx", "rbx", "rsi", "rdi", "rsp", "rbp", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"}
reg4byte := []string{"eax", "ecx", "edx", "ebx", "esi", "edi", "esp", "ebp", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d"}
reg2byte := []string{"ax", "cx", "dx", "bx", "si", "di", "sp", "bp", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w"}
reg1byteL := []string{"al", "cl", "dl", "bl", "sil", "dil", "spl", "bpl", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b"}
reg1byteH := []string{"ah", "ch", "dh", "bh", "sil", "dil", "spl", "bpl", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b"}
// If only the right half of ie. rax has changed, delete rax from the list
// If only the right half of ie. eax has changed, delete eax from the list
// If only the right half of ie. ax has changed, delete ax from the list
// But always keep al and ah
// TODO: Think this throught a bit better!
filterRegisters := e.debugShowRegisters != largeRegisterWindow
if filterRegisters {
for _, regSlice := range [][]string{reg8byte, reg4byte, reg2byte} {
for _, regName := range regSlice {
if !hasKey(registers, regName) {
continue
}
// Removing sub-registers goes here
// If ie. "rax" is present, filter out "eax", "ax", "ah" and "al"
for i, r8b := range reg8byte {
if hasKey(registers, r8b) {
delete(registers, reg4byte[i])
delete(registers, reg2byte[i])
delete(registers, reg1byteL[i])
delete(registers, reg1byteH[i])
}
}
// If ie. "eax" is present, filter out "ax", "ah" and "al"
for i, r4b := range reg4byte {
if hasKey(registers, r4b) {
delete(registers, reg2byte[i])
delete(registers, reg1byteL[i])
delete(registers, reg1byteH[i])
}
}
// If ie. "ax" is present, filter out "ah" and "al"
for i, r2b := range reg2byte {
if hasKey(registers, r2b) {
delete(registers, reg1byteL[i])
delete(registers, reg1byteH[i])
}
}
}
}
}
// Filter out "eflags" since it's covered by the status in the lower right corner
delete(registers, "eflags")
return registers, nil
}
}
}
}
//flogf(gdbLogFile, "[gdb] data-list-register-values %v\n", registers)
return nil, errors.New("could not find the register values in the payload returned from gdb")
}
// DebugRegisterMap will return a map of all register names and values
func (e *Editor) DebugRegisterMap() (map[string]string, error) {
// First get the names of the registers
names, err := e.DebugRegisterNames()
if err != nil {
return nil, err
}
// Then get the register IDs, then use them to get the register names and values
notification, err := e.gdb.CheckedSend("data-list-register-values", "--skip-unavailable", "x")
if err != nil {
//flogf(gdbLogFile, "[gdb] data-list-register-values error: %s\n", err.Error())
return nil, err
}
if payload, ok := notification["payload"]; ok && notification["class"] == "done" {
if payloadMap, ok := payload.(map[string]interface{}); ok {
if registerValues, ok := payloadMap["register-values"]; ok {
if registerSlice, ok := registerValues.([]interface{}); ok {
registers := make(map[string]string, len(names))
for _, singleRegisterMap := range registerSlice {
if registerMap, ok := singleRegisterMap.(map[string]interface{}); ok {
numberString, ok := registerMap["number"].(string)
if !ok {
return nil, errors.New("could not convert \"number\" interface to string")
}
registerNumber, err := strconv.Atoi(numberString)
if err != nil {
return nil, err
}
value, ok := registerMap["value"].(string)
if !ok {
return nil, errors.New("could not convert \"value\" interface to string")
}
registerName := names[registerNumber]
registers[registerName] = value
//flogf(gdbLogFile, "[gdb] data-list-register-values: %s %s\n", registerName, value)
}
}
return registers, nil
}
}
}
}
//flogf(gdbLogFile, "[gdb] data-list-register-values %v\n", registers)
return nil, errors.New("could not find the register values in the payload returned from gdb")
}
// DebugEnd will end the current gdb session, but not set debugMode to false
func (e *Editor) DebugEnd() {
if e.gdb != nil {
e.gdb.Exit()
}
e.gdb = nil
// Clear any existing output
gdbOutput.Reset()
gdbConsole.Reset()
// Clear the last seen variable
lastSeenWatchVariable = ""
// Clear the previous GDB stdout buffer length
lastGDBOutputLength = 0
// Also change to the original directory
if originalDirectory != "" {
os.Chdir(originalDirectory)
}
programRunning = false
longInstructionPaneWidth = 0
//flogf(gdbLogFile, "[gdb] %s\n", "stopped")
}
// AddWatch will add a watchpoint / watch expression to gdb
func (e *Editor) AddWatch(expression string) (string, error) {
var output string
if e.gdb != nil {
//flogf(gdbLogFile, "[gdb] adding watch: %s\n", expression)
_, err := e.gdb.CheckedSend("break-watch", "-a", expression)
if err != nil {
return "", err
}
output = gdbOutput.String()
gdbOutput.Reset()
//flogf(gdbLogFile, "[gdb] output after adding watch: %s\n", output)
}
watchMap[expression] = "?"
// Don't set this, the variable watch has not been seen yet
// lastSeenWatchVariable = expression
return output, nil
}
// DrawWatches will draw a box with the current watch expressions and values in the upper right
func (e *Editor) DrawWatches(c *vt100.Canvas, repositionCursor bool) {
// First create a box the size of the entire canvas
canvasBox := NewCanvasBox(c)
minWidth := 32
// Window is the background box that will be drawn in the upper right
upperRightBox := NewBox()
upperRightBox.UpperRightPlacement(canvasBox, minWidth)
w := int(c.Width())
h := int(c.Height())
// Then create a list box
listBox := NewBox()
marginY := 2
if h < 35 {
marginY = 1
}
listBox.FillWithMargins(upperRightBox, 2, marginY)
// Get the current theme for the watch box
bt := e.NewBoxTheme()
title := "Running"
bt.Background = &e.DebugRunningBackground
if !programRunning {
title = "Stopped"
bt.Background = &e.DebugStoppedBackground
}
// Draw the background box
e.DrawBox(bt, c, upperRightBox)
// Find the available space to draw help text in the upperRightBox
availableHeight := (listBox.H - marginY) - 1
if availableHeight < 2 {
// Draw at least two rows of help text, no matter what
availableHeight = 2
}
if len(watchMap) == 0 {
// Draw the help text, if the screen is wide enough
if w > 120 {
helpSlice := []string{
"ctrl-space : step",
"ctrl-n : next instruction",
"ctrl-f : finish (step out)",
"ctrl-r : run to end",
"ctrl-w : add a watch",
"ctrl-p : reg. pane layout",
"ctrl-i : toggle step into",
}
if e.debugStepInto {
helpSlice[0] = "ctrl-space : step into"
helpSlice[1] = "ctrl-n : next instruction (step into)"
}
if h < 32 {
helpSlice = helpSlice[:availableHeight]
}
e.DrawList(bt, c, listBox, helpSlice, -1)
} else if w > 80 {
narrowHelpSlice := []string{
"ctrl-space: step",
"ctrl-n: next inst.",
"ctrl-f: step out",
"ctrl-r: run to end",
"ctrl-w: add watch",
"ctrl-p: reg. pane",
"ctrl-i: toggle into",
}
if e.debugStepInto {
narrowHelpSlice[0] = "ctrl-space: step into"
narrowHelpSlice[1] = "ctrl-n: into n. inst."
}
if h < 32 {
narrowHelpSlice = narrowHelpSlice[:availableHeight]
}
e.DrawList(bt, c, listBox, narrowHelpSlice, -1)
}
} else {
overview := []string{}
foundLastSeen := false
// First add the last seen variable, at the top of the list
for k, v := range watchMap {
if k == lastSeenWatchVariable {
overview = append(overview, k+": "+v)
foundLastSeen = true
break
}
}
// Then add the rest
for k, v := range watchMap {
if k == lastSeenWatchVariable {
// Already added
continue
}
overview = append(overview, k+": "+v)
}
// Highlight the top item if a debug session is active, and it was changed during this session
if foundLastSeen && e.gdb != nil {
// Draw the list of watches, where the last changed one is highlighted (and at the top)
e.DrawList(bt, c, listBox, overview, 0)
} else {
// Draw the list of watches, with no highlights
e.DrawList(bt, c, listBox, overview, -1)
}
}
// Draw the title
e.DrawTitle(bt, c, upperRightBox, title)
// Blit
c.Draw()
// Reposition the cursor
if repositionCursor {
x := e.pos.ScreenX()
y := e.pos.ScreenY()
vt100.SetXY(uint(x), uint(y))
}
}
// DrawFlags will draw the currently set flags (like zero, carry etc) at the bottom right
func (e *Editor) DrawFlags(c *vt100.Canvas, repositionCursor bool) {
if e.gdb == nil {
return
}
defer func() {
// Reposition the cursor
if repositionCursor {
x := e.pos.ScreenX()
y := e.pos.ScreenY()
vt100.SetXY(uint(x), uint(y))
}
}()
changedFlags := []string{}
// Fetch the value of the machine flags (zero flag, carry etc)
// data-evalutate-expression is the same as print, output and call in gdb
if notification, err := e.gdb.CheckedSend("data-evaluate-expression", "$eflags"); err == nil {
if payload, ok := notification["payload"]; ok && notification["class"] == "done" {
if payloadMap, ok := payload.(map[string]interface{}); ok {
if flagNames, ok := payloadMap["value"]; ok {
if flagNamesString, ok := flagNames.(string); ok {
flagNamesString = strings.TrimPrefix(flagNamesString, "[ ")
flagNamesString = strings.TrimSuffix(flagNamesString, " ]")
flags := strings.Split(flagNamesString, " ")
// Find which flags changed since last step
for _, flag := range flags {
if !hasS(prevFlags, flag) {
changedFlags = append(changedFlags, flag)
}
}
prevFlags = flags
}
}
}
}
}
if len(changedFlags) == 0 {
return
}
const title = "Changed flags:"
lastWidthIndex := int(c.W() - 1)
lastHeightIndex := int(c.H() - 1)
// Length of all flags, joined with a "|" in between
textLength := len(title + " " + strings.Join(changedFlags, "|"))
// The left side margin, if the text is adjusted to the right
x := uint(lastWidthIndex - textLength)
// The bottom line
y := uint(lastHeightIndex)
// Title colors
fg := e.StatusForeground
bg := e.DebugOutputBackground
// Draw the title
c.Write(x, y, fg, bg, title+" ")
x += uint(len(title)) + 1
// Flag colors
fg = e.StatusErrorForeground
bg = e.StatusErrorBackground
for i, flag := range changedFlags {
if i > 0 {
c.Write(x, y, e.DebugInstructionsForeground, bg, "|")
x++
}
c.Write(x, y, fg, bg, flag)
x += uint(len(flag))
}
// Blit
c.Draw()
}
// DrawRegisters will draw a box with the current register values in the lower right
func (e *Editor) DrawRegisters(c *vt100.Canvas, repositionCursor bool) error {
if e.debugShowRegisters == noRegisterWindow || e.gdb == nil {
// Don't draw anything
return nil
}
filterWeirdRegisters := e.debugShowRegisters != largeRegisterWindow
// First create a box the size of the entire canvas
canvasBox := NewCanvasBox(c)
// Window is the background box that will be drawn in the upper right
lowerRightBox := NewBox()
minWidth := 32
var title string
if filterWeirdRegisters {
title = "Changed registers"
// narrow box
lowerRightBox.LowerRightPlacement(canvasBox, minWidth)
if showInstructionPane {
lowerRightBox.H = int(float64(lowerRightBox.H) * 0.9)
}
e.redraw = true
} else {
title = "All changed registers"
// wide box
lowerRightBox.LowerPlacement(canvasBox, 100)
e.redraw = true
}
// Then create a list box
listBox := NewBox()
listBox.FillWithMargins(lowerRightBox, 2, 2)
// Get the current theme for the register box
bt := e.NewBoxTheme()
bt.Background = &e.DebugRegistersBackground
// Draw the background box and title
e.DrawBox(bt, c, lowerRightBox)
e.DrawTitle(bt, c, lowerRightBox, title)
if e.gdb != nil {
allChangedRegisters, err := e.DebugChangedRegisterMap()
if err != nil {
return err
}
var regSlice []string
if filterWeirdRegisters {
for reg, value := range allChangedRegisters {
registryNameWithDigit := false
for _, digit := range []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"} {
if strings.Contains(reg, digit) {
registryNameWithDigit = true
}
}
spaceInValue := strings.Contains(value, " ")
// Skip registers with numbers in their names, like "ymm12", for now
if !registryNameWithDigit && !spaceInValue {
regSlice = append(regSlice, reg+": "+value)
}
}
} else {
for reg, value := range allChangedRegisters {
regSlice = append(regSlice, reg+": "+value)
}
}
sort.Strings(regSlice)
// Cutoff the slice by how high it is, if it's too long
if len(regSlice) > listBox.H {
if listBox.H > 0 {
regSlice = regSlice[:listBox.H]
}
}
// Draw the registers without numbers
e.DrawList(bt, c, listBox, regSlice, -1)
}
// Blit
c.Draw()
return nil
}
// DrawInstructions will draw a box with the current instructions
func (e *Editor) DrawInstructions(c *vt100.Canvas, repositionCursor bool) error {
defer func() {
// Reposition the cursor
if repositionCursor {
x := e.pos.ScreenX()
y := e.pos.ScreenY()
vt100.SetXY(uint(x), uint(y))
}
}()
if showInstructionPane && e.gdb != nil {
// First create a box the size of the entire canvas
canvasBox := NewCanvasBox(c)
// Window is the background box that will be drawn in the upper right
centerBox := NewBox()
minWidth := 32
centerBox.EvenLowerRightPlacement(canvasBox, minWidth)
e.redraw = true
// Then create a list box
listBox := NewBox()
listBox.FillWithMargins(centerBox, 1, 1)
// Get the current theme for the register box
bt := e.NewBoxTheme()
//bt.Text = &e.DebugInstructionsForeground
bt.Background = &e.DebugInstructionsBackground
title := "Next instructions"
if e.gdb != nil {
numberOfInstructionsToFetch := 5
instructions, err := e.DebugDisassemble(numberOfInstructionsToFetch)
if err != nil { // We end up here if the program is done running, when stepping
if err.Error() == "No registers." {
programRunning = false
}
return err
}
// Cutoff the slice by how high it is, if it's too long
if len(instructions) > listBox.H {
if listBox.H > 0 {
instructions = instructions[:listBox.H]
}
}