Debian Codegraph @

interp/debugger.go

raw symbols SCIP
1 package interp
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "go/token"
8 "reflect"
9 "sort"
10 "sync"
11 )
12
13 var (
14 // ErrNotLive indicates that the specified ID does not refer to a (live) Go
15 // routine.
16 ErrNotLive = errors.New("not live")
17
18 // ErrRunning indicates that the specified Go routine is running.
19 ErrRunning = errors.New("running")
20
21 // ErrNotRunning indicates that the specified Go routine is running.
22 ErrNotRunning = errors.New("not running")
23 )
24
25 var rNodeType = reflect.TypeOf((*node)(nil)).Elem()
26
27 // A Debugger can be used to debug a Yaegi program.
28 type Debugger struct {
29 interp *Interpreter
30 events func(*DebugEvent)
31 context context.Context
32 cancel context.CancelFunc
33
34 gWait *sync.WaitGroup
35 gLock *sync.Mutex
36 gID int
37 gLive map[int]*debugRoutine
38
39 result reflect.Value
40 err error
41 }
42
43 // go routine debug state.
44 type debugRoutine struct {
45 id int
46
47 mode DebugEventReason
48 running bool
49 resume chan struct{}
50
51 fDepth int
52 fStep int
53 }
54
55 // node debug state.
56 type nodeDebugData struct {
57 program *Program
58 breakOnLine bool
59 breakOnCall bool
60 }
61
62 // frame debug state.
63 type frameDebugData struct {
64 g *debugRoutine
65 node *node
66 name string
67 kind frameKind
68 scope *scope
69 }
70
71 // frame kind.
72 type frameKind int
73
74 const (
75 // interpreter root frame.
76 frameRoot frameKind = iota + 1
77
78 // function call frame.
79 frameCall
80
81 // closure capture frame.
82 frameClosure
83 )
84
85 // DebugOptions are the debugger options.
86 type DebugOptions struct {
87 // If true, Go routine IDs start at 1 instead of 0.
88 GoRoutineStartAt1 bool
89 }
90
91 // A DebugEvent is an event generated by a debugger.
92 type DebugEvent struct {
93 debugger *Debugger
94 reason DebugEventReason
95 frame *frame
96 }
97
98 // DebugFrame provides access to stack frame information while debugging a
99 // program.
100 type DebugFrame struct {
101 event *DebugEvent
102 frames []*frame
103 }
104
105 // DebugFrameScope provides access to scoped variables while debugging a
106 // program.
107 type DebugFrameScope struct {
108 frame *frame
109 }
110
111 // DebugVariable is the name and value of a variable from a debug session.
112 type DebugVariable struct {
113 Name string
114 Value reflect.Value
115 }
116
117 // DebugGoRoutine provides access to information about a Go routine while
118 // debugging a program.
119 type DebugGoRoutine struct {
120 id int
121 }
122
123 // Breakpoint is the result of attempting to set a breakpoint.
124 type Breakpoint struct {
125 // Valid indicates whether the breakpoint was successfully set.
126 Valid bool
127
128 // Position indicates the source position of the breakpoint.
129 Position token.Position
130 }
131
132 // DebugEventReason is the reason a debug event occurred.
133 type DebugEventReason int
134
135 const (
136 // continue execution normally.
137 debugRun DebugEventReason = iota
138
139 // DebugPause is emitted when a pause request is completed. Can be used with
140 // Interrupt to request a pause.
141 DebugPause
142
143 // DebugBreak is emitted when a debug target hits a breakpoint.
144 DebugBreak
145
146 // DebugEntry is emitted when a debug target starts executing. Can be used
147 // with Step to produce a corresponding event when execution starts.
148 DebugEntry
149
150 // DebugStepInto is emitted when a stepInto request is completed. Can be
151 // used with Step or Interrupt to request a stepInto.
152 DebugStepInto
153
154 // DebugStepOver is emitted when a stepOver request is completed. Can be
155 // used with Step or Interrupt to request a stepOver.
156 DebugStepOver
157
158 // DebugStepOut is emitted when a stepOut request is completed. Can be used
159 // with Step or Interrupt to request a stepOut.
160 DebugStepOut
161
162 // DebugTerminate is emitted when a debug target terminates. Can be used
163 // with Interrupt to attempt to terminate the program.
164 DebugTerminate
165
166 // DebugEnterGoRoutine is emitted when a Go routine is entered.
167 DebugEnterGoRoutine
168
169 // DebugExitGoRoutine is emitted when a Go routine is exited.
170 DebugExitGoRoutine
171 )
172
173 // Debug initializes a debugger for the given program.
174 //
175 // The program will not start running until Step or Continue has been called. If
176 // Step is called with DebugEntry, an entry event will be generated before the
177 // first statement is executed. Otherwise, the debugger will behave as usual.
178 func (interp *Interpreter) Debug(ctx context.Context, prog *Program, events func(*DebugEvent), opts *DebugOptions) *Debugger {
179 dbg := new(Debugger)
180 dbg.interp = interp
181 dbg.events = events
182 dbg.context, dbg.cancel = context.WithCancel(ctx)
183 dbg.gWait = new(sync.WaitGroup)
184 dbg.gLock = new(sync.Mutex)
185 dbg.gLive = make(map[int]*debugRoutine, 1)
186
187 if opts == nil {
188 opts = new(DebugOptions)
189 }
190 if opts.GoRoutineStartAt1 {
191 dbg.gID = 1
192 }
193
194 mainG := dbg.enterGoRoutine()
195 mainG.mode = DebugEntry
196
197 interp.debugger = dbg
198 interp.frame.debug = &frameDebugData{kind: frameRoot, g: mainG}
199
200 prog.root.Walk(func(n *node) bool {
201 n.setProgram(prog)
202 return true
203 }, nil)
204
205 go func() {
206 defer func() { interp.debugger = nil }()
207 defer events(&DebugEvent{reason: DebugTerminate})
208 defer dbg.cancel()
209
210 <-mainG.resume
211 dbg.events(&DebugEvent{dbg, DebugEnterGoRoutine, interp.frame})
212 dbg.result, dbg.err = interp.ExecuteWithContext(ctx, prog)
213 dbg.exitGoRoutine(mainG)
214 dbg.events(&DebugEvent{dbg, DebugExitGoRoutine, interp.frame})
215 dbg.gWait.Wait()
216 }()
217
218 return dbg
219 }
220
221 // Wait blocks until all Go routines launched by the program have terminated.
222 // Wait returns the results of `(*Interpreter).Execute`.
223 func (dbg *Debugger) Wait() (reflect.Value, error) {
224 <-dbg.context.Done()
225 return dbg.result, dbg.err
226 }
227
228 // mark entry into a go routine.
229 func (dbg *Debugger) enterGoRoutine() *debugRoutine {
230 g := new(debugRoutine)
231 g.resume = make(chan struct{})
232
233 dbg.gWait.Add(1)
234
235 dbg.gLock.Lock()
236 g.id = dbg.gID
237 dbg.gID++
238 dbg.gLive[g.id] = g
239 dbg.gLock.Unlock()
240
241 return g
242 }
243
244 // mark exit from a go routine.
245 func (dbg *Debugger) exitGoRoutine(g *debugRoutine) {
246 dbg.gLock.Lock()
247 delete(dbg.gLive, g.id)
248 dbg.gLock.Unlock()
249
250 dbg.gWait.Done()
251 }
252
253 // get the state for a given go routine, if it's live.
254 func (dbg *Debugger) getGoRoutine(id int) (*debugRoutine, bool) {
255 dbg.gLock.Lock()
256 g, ok := dbg.gLive[id]
257 dbg.gLock.Unlock()
258 return g, ok
259 }
260
261 // mark entry into a function call.
262 func (dbg *Debugger) enterCall(nFunc, nCall *node, f *frame) {
263 if f.debug != nil {
264 f.debug.g.fDepth++
265 return
266 }
267
268 f.debug = new(frameDebugData)
269 f.debug.g = f.anc.debug.g
270 f.debug.scope = nFunc.scope
271
272 switch nFunc.kind {
273 case funcLit:
274 f.debug.kind = frameCall
275
276 case funcDecl:
277 f.debug.kind = frameCall
278 f.debug.name = nFunc.child[1].ident
279 }
280
281 if nCall != nil && nCall.anc.kind == goStmt {
282 f.debug.g = dbg.enterGoRoutine()
283 dbg.events(&DebugEvent{dbg, DebugEnterGoRoutine, f})
284 }
285
286 f.debug.g.fDepth++
287 }
288
289 // mark exit from a function call.
290 func (dbg *Debugger) exitCall(nFunc, nCall *node, f *frame) {
291 _ = nFunc // ignore unused, so exitCall can have the same signature as enterCall
292
293 f.debug.g.fDepth--
294
295 if nCall != nil && nCall.anc.kind == goStmt {
296 dbg.exitGoRoutine(f.debug.g)
297 dbg.events(&DebugEvent{dbg, DebugExitGoRoutine, f})
298 }
299 }
300
301 // called by the interpreter prior to executing the node.
302 func (dbg *Debugger) exec(n *node, f *frame) (stop bool) {
303 f.debug.node = n
304
305 if n != nil && n.pos == token.NoPos {
306 return false
307 }
308
309 g := f.debug.g
310 defer func() { g.running = true }()
311
312 e := &DebugEvent{dbg, g.mode, f}
313 switch {
314 case g.mode == DebugTerminate:
315 dbg.cancel()
316 return true
317
318 case n.shouldBreak():
319 e.reason = DebugBreak
320
321 case g.mode == debugRun:
322 return false
323
324 case g.mode == DebugStepOut:
325 if g.fDepth >= g.fStep {
326 return false
327 }
328
329 case g.mode == DebugStepOver:
330 if g.fDepth > g.fStep {
331 return false
332 }
333 }
334 dbg.events(e)
335
336 g.running = false
337 select {
338 case <-g.resume:
339 return false
340 case <-dbg.context.Done():
341 return true
342 }
343 }
344
345 // Continue continues execution of the specified Go routine. Continue returns
346 // ErrNotLive if there is no Go routine with the corresponding ID, or if it is not
347 // live.
348 func (dbg *Debugger) Continue(id int) error {
349 g, ok := dbg.getGoRoutine(id)
350 if !ok {
351 return ErrNotLive
352 }
353
354 g.mode = debugRun
355 g.resume <- struct{}{}
356 return nil
357 }
358
359 // update the exec mode of this routine.
360 func (g *debugRoutine) setMode(reason DebugEventReason) {
361 if g.mode == DebugTerminate {
362 return
363 }
364
365 if g.mode == DebugEntry && reason == DebugEntry {
366 return
367 }
368
369 switch reason {
370 case DebugStepInto, DebugStepOver, DebugStepOut:
371 g.mode, g.fStep = reason, g.fDepth
372 default:
373 g.mode = DebugPause
374 }
375 }
376
377 // Step issues a stepInto, stepOver, or stepOut request to a stopped Go routine.
378 // Step returns ErrRunning if the Go routine is running. Step returns ErrNotLive
379 // if there is no Go routine with the corresponding ID, or if it is not live.
380 func (dbg *Debugger) Step(id int, reason DebugEventReason) error {
381 g, ok := dbg.getGoRoutine(id)
382 if !ok {
383 return ErrNotLive
384 }
385
386 if g.running {
387 return ErrRunning
388 }
389
390 g.setMode(reason)
391 g.resume <- struct{}{}
392 return nil
393 }
394
395 // Interrupt issues a stepInto, stepOver, or stepOut request to a running Go
396 // routine. Interrupt returns ErrRunning if the Go routine is running. Interrupt
397 // returns ErrNotLive if there is no Go routine with the corresponding ID, or if
398 // it is not live.
399 func (dbg *Debugger) Interrupt(id int, reason DebugEventReason) bool {
400 g, ok := dbg.getGoRoutine(id)
401 if !ok {
402 return false
403 }
404
405 g.setMode(reason)
406 return true
407 }
408
409 // Terminate attempts to terminate the program.
410 func (dbg *Debugger) Terminate() {
411 dbg.gLock.Lock()
412 g := dbg.gLive
413 dbg.gLive = nil
414 dbg.gLock.Unlock()
415
416 for _, g := range g {
417 g.mode = DebugTerminate
418 close(g.resume)
419 }
420 }
421
422 // BreakpointTarget is the target of a request to set breakpoints.
423 type BreakpointTarget func(*Debugger, func(*node))
424
425 // PathBreakpointTarget is used to set breapoints on compiled code by path. This
426 // can be used to set breakpoints on code compiled with EvalPath, or source
427 // packages loaded by Yaegi.
428 func PathBreakpointTarget(path string) BreakpointTarget {
429 return func(dbg *Debugger, cb func(*node)) {
430 for _, r := range dbg.interp.roots {
431 f := dbg.interp.fset.File(r.pos)
432 if f != nil && f.Name() == path {
433 cb(r)
434 return
435 }
436 }
437 }
438 }
439
440 // ProgramBreakpointTarget is used to set breakpoints on a Program.
441 func ProgramBreakpointTarget(prog *Program) BreakpointTarget {
442 return func(_ *Debugger, cb func(*node)) {
443 cb(prog.root)
444 }
445 }
446
447 // AllBreakpointTarget is used to set breakpoints on all compiled code. Do not
448 // use with LineBreakpoint.
449 func AllBreakpointTarget() BreakpointTarget {
450 return func(dbg *Debugger, cb func(*node)) {
451 for _, r := range dbg.interp.roots {
452 cb(r)
453 }
454 }
455 }
456
457 type breakpointSetup struct {
458 roots []*node
459 lines map[int]int
460 funcs map[string]int
461 }
462
463 // BreakpointRequest is a request to set a breakpoint.
464 type BreakpointRequest func(*breakpointSetup, int)
465
466 // LineBreakpoint requests a breakpoint on the given line.
467 func LineBreakpoint(line int) BreakpointRequest {
468 return func(b *breakpointSetup, i int) {
469 b.lines[line] = i
470 }
471 }
472
473 // FunctionBreakpoint requests a breakpoint on the named function.
474 func FunctionBreakpoint(name string) BreakpointRequest {
475 return func(b *breakpointSetup, i int) {
476 b.funcs[name] = i
477 }
478 }
479
480 // SetBreakpoints sets breakpoints for the given target. The returned array has
481 // an entry for every request, in order. If a given breakpoint request cannot be
482 // satisfied, the corresponding entry will be marked invalid. If the target
483 // cannot be found, all entries will be marked invalid.
484 func (dbg *Debugger) SetBreakpoints(target BreakpointTarget, requests ...BreakpointRequest) []Breakpoint {
485 // start with all breakpoints unverified
486 results := make([]Breakpoint, len(requests))
487
488 // prepare all the requests
489 setup := new(breakpointSetup)
490 target(dbg, func(root *node) {
491 setup.roots = append(setup.roots, root)
492 setup.lines = make(map[int]int, len(requests))
493 setup.funcs = make(map[string]int, len(requests))
494 for i, rq := range requests {
495 rq(setup, i)
496 }
497 })
498
499 // find breakpoints
500 for _, root := range setup.roots {
501 root.Walk(func(n *node) bool {
502 // function breakpoints
503 if len(setup.funcs) > 0 && n.kind == funcDecl {
504 // reset stale breakpoints
505 n.start.setBreakOnCall(false)
506
507 if i, ok := setup.funcs[n.child[1].ident]; ok && !results[i].Valid {
508 results[i].Valid = true
509 results[i].Position = dbg.interp.fset.Position(n.start.pos)
510 n.start.setBreakOnCall(true)
511 return true
512 }
513 }
514
515 // line breakpoints
516 if len(setup.lines) > 0 && n.pos.IsValid() && n.action != aNop && getExec(n) != nil {
517 // reset stale breakpoints
518 n.setBreakOnLine(false)
519
520 pos := dbg.interp.fset.Position(n.pos)
521 if i, ok := setup.lines[pos.Line]; ok && !results[i].Valid {
522 results[i].Valid = true
523 results[i].Position = pos
524 n.setBreakOnLine(true)
525 return true
526 }
527 }
528
529 return true
530 }, nil)
531 }
532
533 return results
534 }
535
536 // GoRoutines returns an array of live Go routines.
537 func (dbg *Debugger) GoRoutines() []*DebugGoRoutine {
538 dbg.gLock.Lock()
539 r := make([]*DebugGoRoutine, 0, len(dbg.gLive))
540 for id := range dbg.gLive {
541 r = append(r, &DebugGoRoutine{id})
542 }
543 dbg.gLock.Unlock()
544 sort.Slice(r, func(i, j int) bool { return r[i].id < r[j].id })
545 return r
546 }
547
548 // ID returns the ID of the Go routine.
549 func (r *DebugGoRoutine) ID() int { return r.id }
550
551 // Name returns "Goroutine {ID}".
552 func (r *DebugGoRoutine) Name() string { return fmt.Sprintf("Goroutine %d", r.id) }
553
554 // GoRoutine returns the ID of the Go routine that generated the event.
555 func (evt *DebugEvent) GoRoutine() int {
556 if evt.frame.debug == nil {
557 return 0
558 }
559 return evt.frame.debug.g.id
560 }
561
562 // Reason returns the reason for the event.
563 func (evt *DebugEvent) Reason() DebugEventReason {
564 return evt.reason
565 }
566
567 // Walk the stack trace frames. The root frame is included if and only if it is
568 // the only frame. Closure frames are rolled up into the following call frame.
569 func (evt *DebugEvent) walkFrames(fn func([]*frame) bool) {
570 if evt.frame == evt.frame.root {
571 fn([]*frame{evt.frame})
572 return
573 }
574
575 var g *debugRoutine
576 if evt.frame.debug != nil {
577 g = evt.frame.debug.g
578 }
579
580 var frames []*frame
581 for f := evt.frame; f != nil && f != f.root && (f.debug == nil || f.debug.g == g); f = f.anc {
582 if f.debug == nil || f.debug.kind != frameCall {
583 frames = append(frames, f)
584 continue
585 }
586
587 if len(frames) > 0 {
588 if !fn(frames) {
589 return
590 }
591 }
592
593 frames = frames[:0]
594 frames = append(frames, f)
595 }
596
597 if len(frames) > 0 {
598 fn(frames)
599 }
600 }
601
602 // FrameDepth returns the number of call frames in the stack trace.
603 func (evt *DebugEvent) FrameDepth() int {
604 if evt.frame == evt.frame.root {
605 return 1
606 }
607
608 var n int
609 evt.walkFrames(func([]*frame) bool { n++; return true })
610 return n
611 }
612
613 // Frames returns the call frames in the range [start, end).
614 func (evt *DebugEvent) Frames(start, end int) []*DebugFrame {
615 count := end - start
616 if count < 0 {
617 return nil
618 }
619
620 frames := []*DebugFrame{}
621 evt.walkFrames(func(f []*frame) bool {
622 df := &DebugFrame{evt, make([]*frame, len(f))}
623 copy(df.frames, f)
624 frames = append(frames, df)
625 return len(frames) < count
626 })
627 return frames
628 }
629
630 // Name returns the name of the stack frame. For function calls to named
631 // functions, this is the function name.
632 func (f *DebugFrame) Name() string {
633 d := f.frames[0].debug
634 if d == nil {
635 return "<unknown>"
636 }
637 switch d.kind {
638 case frameRoot:
639 return "<init>"
640 case frameClosure:
641 return "<closure>"
642 case frameCall:
643 if d.name == "" {
644 return "<anonymous>"
645 }
646 return d.name
647 default:
648 return "<unknown>"
649 }
650 }
651
652 // Position returns the current position of the frame. This is effectively the
653 // program counter/link register. May return `Position{}`.
654 func (f *DebugFrame) Position() token.Position {
655 d := f.frames[0].debug
656 if d == nil || d.node == nil {
657 return token.Position{}
658 }
659 return f.event.debugger.interp.fset.Position(d.node.pos)
660 }
661
662 // Program returns the program associated with the current position of the
663 // frame. May return nil.
664 func (f *DebugFrame) Program() *Program {
665 d := f.frames[0].debug
666 if d == nil || d.node == nil {
667 return nil
668 }
669
670 return d.node.debug.program
671 }
672
673 // Scopes returns the variable scopes of the frame.
674 func (f *DebugFrame) Scopes() []*DebugFrameScope {
675 s := make([]*DebugFrameScope, len(f.frames))
676 for i, f := range f.frames {
677 s[i] = &DebugFrameScope{f}
678 }
679 return s
680 }
681
682 // IsClosure returns true if this is the capture scope of a closure.
683 func (f *DebugFrameScope) IsClosure() bool {
684 return f.frame.debug != nil && f.frame.debug.kind == frameClosure
685 }
686
687 // Variables returns the names and values of the variables of the scope.
688 func (f *DebugFrameScope) Variables() []*DebugVariable {
689 d := f.frame.debug
690 if d == nil || d.scope == nil {
691 return nil
692 }
693
694 index := map[int]string{}
695 scanScope(d.scope, index)
696
697 m := make([]*DebugVariable, 0, len(f.frame.data))
698 for i, v := range f.frame.data {
699 if typ := v.Type(); typ.AssignableTo(rNodeType) || typ.Kind() == reflect.Ptr && typ.Elem().AssignableTo(rNodeType) {
700 continue
701 }
702 name, ok := index[i]
703 if !ok {
704 continue
705 }
706
707 m = append(m, &DebugVariable{name, v})
708 }
709 return m
710 }
711
712 func scanScope(sc *scope, index map[int]string) {
713 for name, sym := range sc.sym {
714 if _, ok := index[sym.index]; ok {
715 continue
716 }
717 index[sym.index] = name
718 }
719
720 for _, ch := range sc.child {
721 if ch.def != sc.def {
722 continue
723 }
724 scanScope(ch, index)
725 }
726 }