-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
commands.go
2476 lines (2156 loc) · 66.7 KB
/
commands.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
// Copyright 2016, Gdlv Authors
package main
import (
"bytes"
"errors"
"fmt"
"go/parser"
"go/scanner"
"io"
"net/rpc"
"os"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"text/tabwriter"
"time"
"unicode"
"golang.org/x/mobile/event/key"
"github.com/aarzilli/gdlv/internal/dlvclient/service/api"
"github.com/aarzilli/gdlv/internal/prettyprint"
"github.com/aarzilli/nucular"
"github.com/aarzilli/nucular/font"
"github.com/aarzilli/nucular/label"
"github.com/aarzilli/nucular/rect"
"github.com/aarzilli/nucular/richtext"
"github.com/aarzilli/nucular/style"
"github.com/aarzilli/nucular/style-editor"
)
const optimizedFunctionWarning = "Warning: debugging optimized function"
type cmdfunc func(out io.Writer, args string) error
type command struct {
aliases []string
group commandGroup
complete func()
helpMsg string
cmdFn cmdfunc
}
type commandGroup uint8
const (
otherCmds commandGroup = iota
breakCmds
runCmds
revCmds
dataCmds
winCmds
scriptCmds
)
var commandGroupDescriptions = []struct {
description string
group commandGroup
}{
{"Running the program", runCmds},
{"Reverse execution", revCmds},
{"Manipulating breakpoints", breakCmds},
{"Viewing program variables and memory", dataCmds},
{"Setting up the GUI", winCmds},
{"Starlark script commands", scriptCmds},
{"Other commands", otherCmds},
}
// Returns true if the command string matches one of the aliases for this command
func (c command) match(cmdstr string) bool {
for _, v := range c.aliases {
if v == cmdstr {
return true
}
}
return false
}
type Commands struct {
cmds []command
}
var (
LongLoadConfig = api.LoadConfig{true, 1, 128, 16, -1}
LongArrayLoadConfig = api.LoadConfig{true, 1, 128, 64, -1}
ShortLoadConfig = api.LoadConfig{false, 0, 64, 0, 3}
)
type ByFirstAlias []command
func (a ByFirstAlias) Len() int { return len(a) }
func (a ByFirstAlias) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByFirstAlias) Less(i, j int) bool { return a[i].aliases[0] < a[j].aliases[0] }
var cmdhistory = []string{""}
var historyShown int = 0
var historySearch bool
var historyNeedle string
var cmds *Commands
func DebugCommands() *Commands {
c := &Commands{}
c.cmds = []command{
{aliases: []string{"help", "h"}, cmdFn: c.help, helpMsg: `Prints the help message.
help [command]
Type "help" followed by the name of a command for more information about it.`},
{aliases: []string{"break", "b"}, group: breakCmds, cmdFn: breakpoint, complete: completeLocation, helpMsg: `Sets a breakpoint.
break [name] <linespec>
break
See $GOPATH/src/github.com/go-delve/delve/Documentation/cli/locspec.md for the syntax of linespec. To set breakpoints you can also right click on a source line and click "Set breakpoint". Breakpoint properties can be changed by right clicking on a breakpoint (either in the source panel or the breakpoints panel) and selecting "Edit breakpoint".
Without arguments displays all currently set breakponts.`},
{aliases: []string{"clear"}, group: breakCmds, cmdFn: clear, helpMsg: `Deletes breakpoint.
clear <breakpoint name or id>`},
{aliases: []string{"restart", "r"}, group: runCmds, cmdFn: restart, helpMsg: `Restart process.
For live processes any argument passed to restart will be used as argument for the program.
If no arguments are specified the program will be restarted with the same arguments as the last time it was started.
Use:
restart --
To clear the arguments passed to the program.
If the target is recorded:
restart [<checkpoint>]
Restarts the recording at the specified (optional) breakpoint.
restart -r
Re-records the program, any arguments specified after '-r' are passed to the target program. Pass '--' to clear the arguments passed to the program.
All forms of restart that support specifying a list of arguments to pass to the target program (i.e. 'restart' on a live process or 'restart -r' on a recording) also support specifying a list of redirects for the target process:
<input.txt redirects the standard input of the target process from input.txt
>output.txt redirects the standard output of the target process to output.txt
2>error.txt redirects the standard error of the target process to error.txt
`},
{aliases: []string{"continue", "c"}, group: runCmds, cmdFn: cont, helpMsg: "Run until breakpoint or program termination."},
{aliases: []string{"rewind", "rw"}, group: revCmds, cmdFn: rewind, helpMsg: "Run backwards until breakpoint or program termination."},
{aliases: []string{"rev"}, group: revCmds, cmdFn: c.reverse, helpMsg: `Executes program backwards.
rev next
rev step
rev stepout
rev step-instruction
`},
{aliases: []string{"checkpoint", "check"}, cmdFn: checkpoint, helpMsg: `Creates a checkpoint at the current position.
checkpoint [where]`},
{aliases: []string{"step", "s"}, group: runCmds, cmdFn: step, helpMsg: `Single step through program.
step [-list|-first|-last|name]
Specify a name to step into one specific function call. Use the -list option for all the function calls on the current line. To step into a specific function call you can also right click on a function call (on the current line) and select "Step into".
Option -first will step into the first function call of the line, -last will step into the last call of the line. When called without arguments step will use -first as default, but this can be changed using config.`},
{aliases: []string{"step-instruction", "si"}, group: runCmds, cmdFn: stepInstruction, helpMsg: "Single step a single cpu instruction."},
{aliases: []string{"next-instruction", "ni"}, group: runCmds,
cmdFn: nextInstruction, helpMsg: "Like step-instruction but does not step into CALL instructions."},
{aliases: []string{"next", "n"}, group: runCmds, cmdFn: next, helpMsg: "Step over to next source line."},
{aliases: []string{"stepout", "o"}, group: runCmds, cmdFn: stepout, helpMsg: "Step out of the current function."},
{aliases: []string{"cancelnext"}, group: runCmds, cmdFn: cancelnext, helpMsg: "Cancels the next operation currently in progress."},
{aliases: []string{"interrupt"}, group: runCmds, cmdFn: interrupt, helpMsg: "interrupts execution."},
{aliases: []string{"print", "p"}, group: dataCmds, complete: completeVariable, cmdFn: printVar, helpMsg: `Evaluate an expression.
print [@<scope-expr>] [format-expr] <expression>
print [@<scope-expr>] [format-expr] $ <starlar-expression>
See $GOPATH/src/github.com/go-delve/delve/Documentation/cli/expr.md for a description of supported expressions.
Type 'help scope-expr' for a description of <scope-expr>.
Type 'help format-expr' for a description of <format-expr>.`},
{aliases: []string{"list", "ls"}, complete: completeLocation, cmdFn: listCommand, helpMsg: `Show source code.
list <linespec>
See $GOPATH/src/github.com/go-delve/delve/Documentation/cli/expr.md for a description of supported expressions.`},
{aliases: []string{"set"}, group: dataCmds, cmdFn: setVar, complete: completeVariable, helpMsg: `Changes the value of a variable.
set <variable> = <value>
See $GOPATH/src/github.com/go-delve/delve/Documentation/cli/expr.md for a description of supported expressions. Only numerical variables and pointers can be changed.`},
{aliases: []string{"display", "disp", "dp"}, group: dataCmds, complete: completeVariable, cmdFn: displayVar, helpMsg: `Adds one expression to the Variables panel.
display [@<scope-expr>] [format-expr] <expression>
display [@<scope-expr>] [format-expr] $ <starlark-expression>
See $GOPATH/src/github.com/go-delve/delve/Documentation/cli/expr.md for a description of supported expressions.
Type 'help scope-expr' for a description of <scope-expr>.
Type 'help format-expr' for a description of <format-expr>.`},
{aliases: []string{"details", "det", "dt"}, group: dataCmds, complete: completeVariable, cmdFn: detailsVar, helpMsg: `Opens details window for the specified expression.
details <expr>
`},
{aliases: []string{"layout"}, group: winCmds, cmdFn: layoutCommand, helpMsg: `Manages window layout.
layout <name>
Loads the specified layout.
layout save <name> <descr>
Saves the current layout. Overwrite "default" to change the default layout.
layout list
Lists saved layouts.`},
{aliases: []string{"config"}, cmdFn: configCommand, helpMsg: `Configuration
config
config alias <command> <alias>
config zoom <factor>
Without arguments opens the configuration window.
With the 'alias' subcommand sets up a command alias.
With the 'zoom' subcommand changes the display scaling factor (makes fonts larger or smaller).
`},
{aliases: []string{"scroll"}, group: winCmds, cmdFn: scrollCommand, helpMsg: `Controls scrollback behavior.
scroll clear Clears scrollback
scroll silence Silences output from inferior
scroll noise Re-enables output from inferior.
`},
{aliases: []string{"exit", "quit", "q"}, cmdFn: exitCommand, helpMsg: "Exit the debugger."},
{aliases: []string{"window", "win"}, complete: completeWindow, cmdFn: windowCommand, helpMsg: `Opens a window.
window <kind>
Kind is one of listing, diassembly, goroutines, stacktrace, variables, globals, breakpoints, threads, registers, sources, functions, types and checkpoints.
Shortcuts:
Alt-1 Listing window
Alt-2 Variables window
Alt-3 Globals window
Alt-4 Registers window
Alt-5 Breakpoints window
Alt-6 Stacktrace window
Alt-7 Disassembly window
Alt-8 Goroutines window
Alt-9 Threads Window
`},
{aliases: []string{"source"}, cmdFn: sourceCommand, complete: completeFilesystem, helpMsg: `Executes a starlark script
source <path>
If path is a single '-' character an interactive starlark interpreter will start instead. Type 'exit' to exit.
See documentation in doc/starlark.md.`},
{aliases: []string{"stack"}, cmdFn: stackCommand, helpMsg: `Prints stacktrace
stack [depth]
Prints the current stack trace. If depth is omitted it defaults to 5, all other settings are copied from the stacktrace panel.`},
{aliases: []string{"goroutines"}, cmdFn: goroutinesCommand, helpMsg: `Prints the list of currently running goroutines.
All parameters are copied from the goroutines panel.`},
{aliases: []string{"dump"}, cmdFn: dump, helpMsg: `Creates a core dump from the current process state
dump <output file>
The core dump is always written in ELF, even on systems (windows, macOS) where this is not customary. For environments other than linux/amd64 threads and registers are dumped in a format that only Delve can read back.`},
{aliases: []string{"watch"}, group: breakCmds, cmdFn: watchpoint, helpMsg: `Set watchpoint.
watch [-r|-w|-rw] <expr>
-r stops when the memory location is read
-w stops when the memory location is written
-rw stops when the memory location is read or written
The memory location is specified with the same expression language used by 'print', for example:
watch v
will watch the address of variable 'v'.
See also: "help print".`},
{aliases: []string{"call"}, group: runCmds, cmdFn: call, helpMsg: `Resumes process, injecting a function call (EXPERIMENTAL!!!)
call [-unsafe] <function call expression>
Current limitations:
- only pointers to stack-allocated objects can be passed as argument.
- only some automatic type conversions are supported.
- functions can only be called on running goroutines that are not
executing the runtime.
- the current goroutine needs to have at least 256 bytes of free space on
the stack.
- functions can only be called when the goroutine is stopped at a safe
point.
- calling a function will resume execution of all goroutines.
- only supported on linux's native backend.
`},
{aliases: []string{"target"}, cmdFn: target, helpMsg: `Manages child process debugging.
target follow-exec [-on [regex]] [-off]
Enables or disables follow exec mode. When follow exec mode Delve will automatically attach to new child processes executed by the target process. An optional regular expression can be passed to 'target follow-exec', only child processes with a command line matching the regular expression will be followed.
target list
List currently attached processes.
target switch [pid]
Switches to the specified process.
`},
{aliases: []string{"libraries"}, cmdFn: libraries, helpMsg: `List loaded dynamic libraries`},
}
sort.Sort(ByFirstAlias(c.cmds))
return c
}
var noCmdError = errors.New("command not available")
func noCmdAvailable(out io.Writer, args string) error {
return noCmdError
}
func nullCommand(out io.Writer, args string) error {
return nil
}
func (c *Commands) help(out io.Writer, args string) error {
if args == "scope-expr" {
fmt.Fprintf(out, `A scope expression can be used as the first argument of the 'print' and 'display' commands to describe the scope in which an expression should be evaluated. For example in:
print @g2f8 a+1
The text "@g2f8" is a scope expression describing that the expression "a+1" should be executed in the 8th frame (f8) of goroutine 2 (g2).
A scope expression always starts with an '@' character and should contain either a goroutine specifier, a frame specifier or both.
A goroutine specifier is a positive integer following the character 'g'. The integer can be specified in decimal or in hexadecimal, following a '0x' prefix.
There are three kinds of frame specifiers:
1. The character 'f' followed by a positive integer specifies the frame number in which the expression should be evaluated. 'f0' specifies the topmost stack frame, 'f1' specifies the caller frame, etc.
2. The character 'f' followed by a negative integer specifies the frame offset for the frame in which the expression should be evaluated. Gdlv will look in the topmost 100 frames for a frame with the same offset as the one specified.
3. The character 'f' followed by a regular expression delimited by the character '/'. This specifies that the expression should be evaluated in the first frame that's executing a function whose name matches the regular expression.`)
return nil
}
if args == "format-expr" {
fmt.Fprintf(out, `A format expression can be used to change the way print and display format their output. The syntax is similar to the format directives of printf
print %02x
Changes the format of integer numbers to hexadecimal, padding with 0s for two characters
print %0.2f
Changes the format of floating point numbers to %0.2f.
print %200s x
Changes the number of characters retrieved for strings to 200.
print %#s x
Formats strings like 'hexdump -C'.
print %100a x
Changes the number of elements loaded for slices, arrays and maps to 100.
print %5v x
Changes the recursion depth for structs and pointers to 5.
print %+0.2g%o%1000s x
Multiple formatting directives can be used simultaneously, in this example integer numbers will be print in octal, floating point numbers will be formatted with %+0.2g and strings will be loaded up to 1000 characters.`)
return nil
}
if args != "" {
for _, cmd := range c.cmds {
for _, alias := range cmd.aliases {
if alias == args {
fmt.Fprintln(out, cmd.helpMsg)
return nil
}
}
}
switch args {
case "fonts":
fmt.Fprintf(out, `By default gdlv uses a built-in version of Droid Sans Mono.
If you don't like the font or if it doesn't cover a script that you need you
can change the font by setting the environment variables GDLV_NORMAL_FONT
and GDLV_BOLD_FONT to the path of two ttf files.
`)
return nil
}
return noCmdError
}
fmt.Fprintln(out, "The following commands are available:")
for _, cgd := range commandGroupDescriptions {
fmt.Fprintf(out, "\n%s:\n", cgd.description)
w := new(tabwriter.Writer)
w.Init(out, 0, 8, 0, ' ', 0)
for _, cmd := range c.cmds {
if cmd.group != cgd.group {
continue
}
h := cmd.helpMsg
if idx := strings.Index(h, "\n"); idx >= 0 {
h = h[:idx]
}
if len(cmd.aliases) > 1 {
fmt.Fprintf(w, " %s (alias: %s) \t %s\n", cmd.aliases[0], strings.Join(cmd.aliases[1:], " | "), h)
} else {
fmt.Fprintf(w, " %s \t %s\n", cmd.aliases[0], h)
}
}
if err := w.Flush(); err != nil {
return err
}
}
fmt.Fprintln(out, "Type help followed by a command for full documentation.")
fmt.Fprintln(out)
fmt.Fprintln(out, "Keybindings:")
{
w := new(tabwriter.Writer)
w.Init(out, 0, 8, 0, ' ', 0)
fmt.Fprintln(w, " Ctrl +/- \t Zoom in/out")
fmt.Fprintln(w, " Escape \t Focus command line")
fmt.Fprintln(w, " Shift-F5, Ctrl-delete \t Request manual stop")
fmt.Fprintln(w, " F5, Alt-enter \t Continue")
fmt.Fprintln(w, " F10, Alt-right \t Next")
fmt.Fprintln(w, " F11, Alt-down \t Step")
fmt.Fprintln(w, " Shift-F11, Alt-up \t Step Out")
fmt.Fprintln(w, " Shift-enter \t Add new expression to the variables window")
if err := w.Flush(); err != nil {
return err
}
}
fmt.Fprintln(out)
fmt.Fprintln(out, "Keybindings for the variables window:")
{
w := new(tabwriter.Writer)
w.Init(out, 0, 8, 0, ' ', 0)
fmt.Fprintln(w, " Shift-up \t move to previous expression")
fmt.Fprintln(w, " Shift-down \t move to next expression")
fmt.Fprintln(w, " Shift-delete \t removes current expression")
fmt.Fprintln(w, " Ctrl-o \t expands current expression")
if err := w.Flush(); err != nil {
return err
}
}
fmt.Fprintln(out, "\nFor help about changing fonts type \"help fonts\".")
return nil
}
func setBreakpoint(out io.Writer, tracepoint bool, argstr string) error {
if argstr == "" {
listBreakpoints()
return nil
}
if curThread < 0 {
cmd := "B"
if tracepoint {
cmd = "T"
}
ScheduledBreakpoints = append(ScheduledBreakpoints, fmt.Sprintf("%s%s", cmd, argstr))
fmt.Fprintf(out, "Breakpoint will be set on restart\n")
return nil
}
defer refreshState(refreshToSameFrame, clearBreakpoint, nil)
args := strings.SplitN(argstr, " ", 2)
requestedBp := &api.Breakpoint{}
locspec := ""
switch len(args) {
case 1:
locspec = argstr
case 2:
if api.ValidBreakpointName(args[0]) == nil {
requestedBp.Name = args[0]
locspec = args[1]
} else {
locspec = argstr
}
default:
return fmt.Errorf("address required")
}
requestedBp.Tracepoint = tracepoint
locs, substSpec, findLocErr := client.FindLocation(currentEvalScope(), locspec, true, nil)
if findLocErr != nil && requestedBp.Name != "" {
requestedBp.Name = ""
locspec = argstr
var err2 error
var substSpec2 string
locs, substSpec2, err2 = client.FindLocation(currentEvalScope(), locspec, true, nil)
if err2 == nil {
substSpec = substSpec2
findLocErr = nil
}
}
if findLocErr != nil && shouldAskToSuspendBreakpoint() {
wnd.PopupOpen("Set suspended breakpoint?", dynamicPopupFlags, rect.Rect{100, 100, 550, 400}, true, func(w *nucular.Window) {
w.Row(30).Static(0)
w.Label("Could not find breakpoint location, set suspended breakpoint?", "LC")
yes, no := yesno(w)
switch {
case yes:
bp, err := client.CreateBreakpointWithExpr(requestedBp, locspec, nil, true)
out := &editorWriter{false}
if err != nil {
fmt.Fprintf(out, "Could not set breakpoint: %v", err)
} else {
fmt.Fprintf(out, "%s set at %s\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp, false))
go refreshState(refreshToSameFrame, clearBreakpoint, nil)
}
w.Close()
case no:
w.Close()
}
})
}
if findLocErr != nil {
return findLocErr
}
if substSpec != "" {
locspec = substSpec
}
for _, loc := range locs {
requestedBp.Addr = loc.PC
requestedBp.Addrs = loc.PCs
requestedBp.AddrPid = loc.PCPids
setBreakpointEx(out, requestedBp, locspec)
}
return nil
}
func shouldAskToSuspendBreakpoint() bool {
fns, _ := client.ListFunctions(`^plugin\.Open$`, 0)
_, err := client.GetState()
return len(fns) > 0 || isErrProcessExited(err) || client.FollowExecEnabled()
}
func isErrProcessExited(err error) bool {
rpcError, ok := err.(rpc.ServerError)
return ok && strings.Contains(rpcError.Error(), "has exited with status")
}
func setBreakpointEx(out io.Writer, requestedBp *api.Breakpoint, locspec string) {
if curThread < 0 {
switch {
default:
fallthrough
case requestedBp.Addr != 0:
fmt.Fprintf(out, "error: process exited\n")
return
case requestedBp.FunctionName != "":
ScheduledBreakpoints = append(ScheduledBreakpoints, fmt.Sprintf("B%s", requestedBp.FunctionName))
case requestedBp.File != "":
ScheduledBreakpoints = append(ScheduledBreakpoints, fmt.Sprintf("T%s:%d", requestedBp.File, requestedBp.Line))
}
fmt.Fprintf(out, "Breakpoint will be set on restart\n")
return
}
bp, err := client.CreateBreakpointWithExpr(requestedBp, locspec, nil, true)
if err != nil {
fmt.Fprintf(out, "Could not create breakpoint: %v\n", err)
}
fmt.Fprintf(out, "%s set at %s\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp, false))
if len(bp.Addrs) > 1 {
fmt.Fprintf(out, "\tother addresses:")
for _, addr := range bp.Addrs {
fmt.Fprintf(out, " %#x", addr)
}
}
freezeBreakpoint(out, bp)
}
func listBreakpoints() {
wnd.Lock()
defer wnd.Unlock()
style := wnd.Style()
c := scrollbackEditor.Append(true)
defer c.End()
bps, err := client.ListBreakpoints(false)
if err != nil {
c.Text(fmt.Sprintf("Command failed: %v\n", err))
return
}
for _, bp := range bps {
c.Text(fmt.Sprintf("%s at %#x for ", formatBreakpointName(bp, true), bp.Addr))
if bp.FunctionName != "" {
c.Text(fmt.Sprintf("%s()\n ", bp.FunctionName))
} else {
c.Text("\n ")
}
writeLinkToLocation(c, style, bp.File, bp.Line, bp.Addr)
c.Text(fmt.Sprintf(" (%d)\n", bp.TotalHitCount))
if bp.Cond != "" {
c.Text(fmt.Sprintf("\tcond %s\n", bp.Cond))
}
}
}
func breakpoint(out io.Writer, args string) error {
return setBreakpoint(out, false, args)
}
func clear(out io.Writer, args string) error {
if len(args) == 0 {
return fmt.Errorf("not enough arguments")
}
id, err := strconv.Atoi(args)
var bp *api.Breakpoint
if err == nil {
bp, err = client.ClearBreakpoint(id)
} else {
bp, err = client.ClearBreakpointByName(args)
}
removeFrozenBreakpoint(bp)
if err != nil {
return err
}
fmt.Fprintf(out, "%s cleared at %s\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp, false))
return nil
}
func restart(out io.Writer, args string) error {
resetArgs := false
var newArgs []string
rerecord := false
args = strings.TrimSpace(args)
restartCheckpoint := ""
if args != "" {
argv := splitQuotedFields(args, '\'')
if len(argv) > 0 {
if client != nil && client.Recorded() && argv[0] == "-r" {
restartCheckpoint = ""
rerecord = true
argv = argv[1:]
}
}
if len(argv) > 0 {
if argv[0] == "--" {
argv = argv[1:]
}
resetArgs = true
newArgs = argv
}
}
if client != nil && client.Recorded() && !rerecord {
restartCheckpoint = args
newArgs = nil
resetArgs = false
}
if rerecord && !delveFeatures.hasRerecord {
return fmt.Errorf("rerecord unsupported by this version of delve")
}
if len(BackendServer.buildcmd) > 0 && (BackendServer.buildcmd[0] == "test") {
newArgs = addTestPrefix(newArgs)
}
if client == nil {
go pseudoCommandWrap(func(w io.Writer) error {
return doRebuild(w, resetArgs, newArgs)
})
return nil
}
if BackendServer.StaleExecutable() && (!client.Recorded() || rerecord) {
wnd.PopupOpen("Recompile?", dynamicPopupFlags, rect.Rect{100, 100, 550, 400}, true, func(w *nucular.Window) {
w.Row(30).Static(0)
w.Label("Executable is stale. Rebuild?", "LC")
yes, no := yesno(w)
switch {
case yes:
go pseudoCommandWrap(func(w io.Writer) error {
return doRebuild(w, resetArgs, newArgs)
})
w.Close()
case no:
go pseudoCommandWrap(func(w io.Writer) error {
return doRestart(w, restartCheckpoint, resetArgs, newArgs, rerecord)
})
w.Close()
}
})
return nil
}
return doRestart(out, restartCheckpoint, resetArgs, newArgs, rerecord)
}
func yesno(w *nucular.Window) (yes, no bool) {
for _, e := range w.Input().Keyboard.Keys {
switch {
case e.Code == key.CodeEscape:
no = true
case e.Code == key.CodeReturnEnter:
yes = true
}
}
w.Row(30).Static(0, 100, 100, 0)
w.Spacing(1)
if w.ButtonText("Yes") {
yes = true
}
if w.ButtonText("No") {
no = true
}
w.Spacing(1)
return yes, no
}
func splitQuotedFields(in string, quote rune) []string {
type stateEnum int
const (
inSpace stateEnum = iota
inField
inQuote
inQuoteEscaped
)
state := inSpace
r := []string{}
var buf bytes.Buffer
for _, ch := range in {
switch state {
case inSpace:
if ch == quote {
state = inQuote
} else if !unicode.IsSpace(ch) {
buf.WriteRune(ch)
state = inField
}
case inField:
if ch == quote {
state = inQuote
} else if unicode.IsSpace(ch) {
r = append(r, buf.String())
buf.Reset()
} else {
buf.WriteRune(ch)
}
case inQuote:
if ch == quote {
state = inField
} else if ch == '\\' {
state = inQuoteEscaped
} else {
buf.WriteRune(ch)
}
case inQuoteEscaped:
buf.WriteRune(ch)
state = inQuote
}
}
if buf.Len() != 0 {
r = append(r, buf.String())
}
return r
}
func pseudoCommandWrap(cmd func(io.Writer) error) {
wnd.Changed()
defer wnd.Changed()
out := editorWriter{true}
err := cmd(&out)
if err != nil {
fmt.Fprintf(&out, "Error executing command: %v\n", err)
}
}
func doRestart(out io.Writer, restartCheckpoint string, resetArgs bool, argsAndRedirects []string, rerecord bool) error {
args, redirects, err := parseRedirects(argsAndRedirects)
if err != nil {
return err
}
shouldFinishRestart := client == nil || !client.Recorded() || rerecord
_, err = client.RestartFrom(rerecord, restartCheckpoint, resetArgs, args, redirects, false)
if err != nil {
return err
}
if shouldFinishRestart {
finishRestart(out, true)
}
firstStop = true
refreshState(refreshToFrameZero, clearStop, nil)
return nil
}
func doRebuild(out io.Writer, resetArgs bool, argsAndRedirects []string) error {
args, redirects, err := parseRedirects(argsAndRedirects)
if err != nil {
return err
}
rerecord := client != nil && client.Recorded()
dorestart := BackendServer.serverProcess != nil
BackendServer.Rebuild()
if !dorestart || !BackendServer.buildok {
return nil
}
updateFrozenBreakpoints()
clearFrozenBreakpoints()
discarded, err := client.RestartFrom(rerecord, "", resetArgs, args, redirects, false)
if err != nil {
fmt.Fprintf(out, "error on restart\n")
return err
}
fmt.Fprintln(out, "Process restarted with PID", client.ProcessPid())
for i := range discarded {
fmt.Fprintf(out, "Discarded %s at %s: %v\n", formatBreakpointName(discarded[i].Breakpoint, false), formatBreakpointLocation(discarded[i].Breakpoint, false), discarded[i].Reason)
}
restoreFrozenBreakpoints(out)
finishRestart(out, true)
refreshState(refreshToFrameZero, clearStop, nil)
return nil
}
func parseRedirects(w []string) (args []string, redirects [3]string, err error) {
for len(w) > 0 {
var found bool
var err error
w, found, err = parseOneRedirect(w, &redirects)
if err != nil {
return nil, [3]string{}, err
}
if !found {
break
}
}
return w, redirects, nil
}
func parseOneRedirect(w []string, redirs *[3]string) ([]string, bool, error) {
prefixes := []string{"<", ">", "2>"}
names := []string{"stdin", "stdout", "stderr"}
if len(w) >= 2 {
for _, prefix := range prefixes {
if w[len(w)-2] == prefix {
w[len(w)-2] += w[len(w)-1]
w = w[:len(w)-1]
break
}
}
}
for i, prefix := range prefixes {
if strings.HasPrefix(w[len(w)-1], prefix) {
if redirs[i] != "" {
return nil, false, fmt.Errorf("redirect error: %s redirected twice", names[i])
}
redirs[i] = w[len(w)-1][len(prefix):]
return w[:len(w)-1], true, nil
}
}
return w, false, nil
}
func cont(out io.Writer, args string) error {
stateChan := client.Continue()
var state *api.DebuggerState
for state = range stateChan {
if state.Err != nil {
refreshState(refreshToFrameZero, clearStop, state)
return state.Err
}
printcontext(out, state)
}
refreshState(refreshToFrameZero, clearStop, state)
return nil
}
func call(out io.Writer, args string) error {
const unsafePrefix = "-unsafe "
unsafe := false
if strings.HasPrefix(args, unsafePrefix) {
unsafe = true
args = args[len(unsafePrefix):]
}
state, err := client.Call(curGid, args, unsafe)
if err != nil {
return err
}
printcontext(out, state)
refreshState(refreshToFrameZero, clearStop, state)
return nil
}
func rewind(out io.Writer, args string) error {
stateChan := client.Rewind()
var state *api.DebuggerState
for state = range stateChan {
if state.Err != nil {
refreshState(refreshToFrameZero, clearStop, state)
return state.Err
}
printcontext(out, state)
}
refreshState(refreshToFrameZero, clearStop, state)
return nil
}
func (c *Commands) reverse(out io.Writer, args string) error {
v := strings.SplitN(args, " ", 2)
if len(v) < 1 {
return fmt.Errorf("rev must be followed by next, step, step-instruction or stepout")
}
cmd := c.findCommand(v[0])
if cmd == nil {
return fmt.Errorf("unknown command %q", v[0])
}
args = ""
if len(v) > 1 {
args = v[1]
}
const revprefix = "-rev "
switch cmd.aliases[0] {
case "next":
return next(out, revprefix+args)
case "step":
return step(out, revprefix+args)
case "stepout":
return stepout(out, revprefix+args)
case "step-instruction":
return stepInstruction(out, revprefix+args)
default:
return fmt.Errorf("rev must be followed by next, step, step-instruction or stepout")
}
}
type continueAction uint8
const (
continueActionIgnoreThis continueAction = iota
continueActionIgnoreAll
continueActionStopAndCancel
continueActionStopWithoutCancel
)
func continueUntilCompleteNext(out io.Writer, state *api.DebuggerState, op string, bp *api.Breakpoint) error {
ignoreAll := false
if !state.NextInProgress {
goto continueCompleted
}
continueLoop:
for {
stateChan := client.DirectionCongruentContinue()
for state = range stateChan {
if state.Err != nil {