forked from go-delve/delve
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proc.go
686 lines (608 loc) · 16.1 KB
/
proc.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
package proc
import (
"debug/dwarf"
"debug/gosym"
"encoding/binary"
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
sys "golang.org/x/sys/unix"
"github.com/derekparker/delve/dwarf/frame"
"github.com/derekparker/delve/dwarf/line"
"github.com/derekparker/delve/dwarf/reader"
"github.com/derekparker/delve/source"
)
// DebuggedProcess represents all of the information the debugger
// is holding onto regarding the process we are debugging.
type DebuggedProcess struct {
Pid int // Process Pid
Process *os.Process // Pointer to process struct for the actual process we are debugging
// Software breakpoint table. Hardware breakpoints are stored in proc/arch.go, as they are architecture dependant.
Breakpoints map[uint64]*Breakpoint
// List of threads mapped as such: pid -> *Thread
Threads map[int]*Thread
// Active thread. This is the default thread used for setting breakpoints, evaluating variables, etc..
CurrentThread *Thread
dwarf *dwarf.Data
goSymTable *gosym.Table
frameEntries frame.FrameDescriptionEntries
lineInfo *line.DebugLineInfo
firstStart bool
singleStepping bool
os *OSProcessDetails
arch Arch
ast *source.Searcher
breakpointIDCounter int
tempBreakpointIDCounter int
running bool
halt bool
exited bool
ptraceChan chan func()
ptraceDoneChan chan interface{}
}
func New(pid int) *DebuggedProcess {
dbp := &DebuggedProcess{
Pid: pid,
Threads: make(map[int]*Thread),
Breakpoints: make(map[uint64]*Breakpoint),
firstStart: true,
os: new(OSProcessDetails),
ast: source.New(),
ptraceChan: make(chan func()),
ptraceDoneChan: make(chan interface{}),
}
go dbp.handlePtraceFuncs()
return dbp
}
// A ManualStopError happens when the user triggers a
// manual stop via SIGERM.
type ManualStopError struct{}
func (mse ManualStopError) Error() string {
return "Manual stop requested"
}
// ProcessExitedError indicates that the process has exited and contains both
// process id and exit status.
type ProcessExitedError struct {
Pid int
Status int
}
func (pe ProcessExitedError) Error() string {
return fmt.Sprintf("process %d has exited with status %d", pe.Pid, pe.Status)
}
// Attach to an existing process with the given PID.
func Attach(pid int) (*DebuggedProcess, error) {
dbp, err := initializeDebugProcess(New(pid), "", true)
if err != nil {
return nil, err
}
return dbp, nil
}
func (dbp *DebuggedProcess) Detach(kill bool) (err error) {
// Clean up any breakpoints we've set.
for _, bp := range dbp.arch.HardwareBreakpoints() {
if bp != nil {
dbp.Clear(bp.Addr)
}
}
for _, bp := range dbp.Breakpoints {
if bp != nil {
dbp.Clear(bp.Addr)
}
}
dbp.execPtraceFunc(func() {
var sig int
if kill {
sig = int(sys.SIGINT)
}
err = PtraceDetach(dbp.Pid, sig)
})
return
}
// Returns whether or not Delve thinks the debugged
// process has exited.
func (dbp *DebuggedProcess) Exited() bool {
return dbp.exited
}
// Returns whether or not Delve thinks the debugged
// process is currently executing.
func (dbp *DebuggedProcess) Running() bool {
return dbp.running
}
// Finds the executable and then uses it
// to parse the following information:
// * Dwarf .debug_frame section
// * Dwarf .debug_line section
// * Go symbol table.
func (dbp *DebuggedProcess) LoadInformation(path string) error {
var wg sync.WaitGroup
exe, err := dbp.findExecutable(path)
if err != nil {
return err
}
wg.Add(3)
go dbp.parseDebugFrame(exe, &wg)
go dbp.obtainGoSymbols(exe, &wg)
go dbp.parseDebugLineInfo(exe, &wg)
wg.Wait()
return nil
}
// Find a location by string (file+line, function, breakpoint id, addr)
func (dbp *DebuggedProcess) FindLocation(str string) (uint64, error) {
// File + Line
if strings.ContainsRune(str, ':') {
fl := strings.Split(str, ":")
fileName, err := filepath.Abs(fl[0])
if err != nil {
return 0, err
}
line, err := strconv.Atoi(fl[1])
if err != nil {
return 0, err
}
pc, _, err := dbp.goSymTable.LineToPC(fileName, line)
if err != nil {
return 0, err
}
return pc, nil
}
// Try to lookup by function name
fn := dbp.goSymTable.LookupFunc(str)
if fn != nil {
return fn.Entry, nil
}
// Attempt to parse as number for breakpoint id or raw address
id, err := strconv.ParseUint(str, 0, 64)
if err != nil {
return 0, fmt.Errorf("unable to find location for %s", str)
}
// Use as breakpoint id
for _, bp := range dbp.arch.HardwareBreakpoints() {
if bp == nil {
continue
}
if uint64(bp.ID) == id {
return bp.Addr, nil
}
}
for _, bp := range dbp.Breakpoints {
if uint64(bp.ID) == id {
return bp.Addr, nil
}
}
// Last resort, use as raw address
return id, nil
}
// Sends out a request that the debugged process halt
// execution. Sends SIGSTOP to all threads.
func (dbp *DebuggedProcess) RequestManualStop() error {
dbp.halt = true
err := dbp.requestManualStop()
if err != nil {
return err
}
err = dbp.Halt()
if err != nil {
return err
}
dbp.running = false
return nil
}
// Sets a breakpoint at addr, and stores it in the process wide
// break point table. Setting a break point must be thread specific due to
// ptrace actions needing the thread to be in a signal-delivery-stop.
//
// Depending on hardware support, Delve will choose to either
// set a hardware or software breakpoint. Essentially, if the
// hardware supports it, and there are free debug registers, Delve
// will set a hardware breakpoint. Otherwise we fall back to software
// breakpoints, which are a bit more work for us.
func (dbp *DebuggedProcess) Break(addr uint64) (*Breakpoint, error) {
return dbp.setBreakpoint(dbp.CurrentThread.Id, addr, false)
}
// Sets a temp breakpoint, for the 'next' command.
func (dbp *DebuggedProcess) TempBreak(addr uint64) (*Breakpoint, error) {
return dbp.setBreakpoint(dbp.CurrentThread.Id, addr, true)
}
// Sets a breakpoint by location string (function, file+line, address)
func (dbp *DebuggedProcess) BreakByLocation(loc string) (*Breakpoint, error) {
addr, err := dbp.FindLocation(loc)
if err != nil {
return nil, err
}
return dbp.Break(addr)
}
func (dbp *DebuggedProcess) HardwareBreakpoints() []*Breakpoint {
return dbp.arch.HardwareBreakpoints()
}
// Clears a breakpoint in the current thread.
func (dbp *DebuggedProcess) Clear(addr uint64) (*Breakpoint, error) {
return dbp.clearBreakpoint(dbp.CurrentThread.Id, addr)
}
// Clears a breakpoint by location (function, file+line, address, breakpoint id)
func (dbp *DebuggedProcess) ClearByLocation(loc string) (*Breakpoint, error) {
addr, err := dbp.FindLocation(loc)
if err != nil {
return nil, err
}
return dbp.Clear(addr)
}
// Returns the status of the current main thread context.
func (dbp *DebuggedProcess) Status() *sys.WaitStatus {
return dbp.CurrentThread.Status
}
// Step over function calls.
func (dbp *DebuggedProcess) Next() error {
return dbp.run(dbp.next)
}
func (dbp *DebuggedProcess) next() error {
// Make sure we clean up the temp breakpoints created by thread.Next
defer dbp.clearTempBreakpoints()
chanRecvCount, err := dbp.setChanRecvBreakpoints()
if err != nil {
return err
}
g, err := dbp.CurrentThread.getG()
if err != nil {
return err
}
if g.DeferPC != 0 {
_, err = dbp.TempBreak(g.DeferPC)
if err != nil {
return err
}
}
var goroutineExiting bool
var waitCount int
for _, th := range dbp.Threads {
if th.blocked() {
// Ignore threads that aren't running go code.
continue
}
waitCount++
if err = th.SetNextBreakpoints(); err != nil {
if err, ok := err.(GoroutineExitingError); ok {
waitCount = waitCount - 1 + chanRecvCount
if err.goid == g.Id {
goroutineExiting = true
}
continue
}
return err
}
}
for _, th := range dbp.Threads {
if err = th.Continue(); err != nil {
return err
}
}
for waitCount > 0 {
thread, err := dbp.trapWait(-1)
if err != nil {
return err
}
tg, err := thread.getG()
if err != nil {
return err
}
// Make sure we're on the same goroutine, unless it has exited.
if tg.Id == g.Id || goroutineExiting {
if dbp.CurrentThread != thread {
dbp.SwitchThread(thread.Id)
}
}
waitCount--
}
return dbp.Halt()
}
func (dbp *DebuggedProcess) setChanRecvBreakpoints() (int, error) {
var count int
allg, err := dbp.GoroutinesInfo()
if err != nil {
return 0, err
}
for _, g := range allg {
if g.ChanRecvBlocked() {
ret, err := g.chanRecvReturnAddr(dbp)
if err != nil {
if _, ok := err.(NullAddrError); ok {
continue
}
return 0, err
}
if _, err = dbp.TempBreak(ret); err != nil {
return 0, err
}
count++
}
}
return count, nil
}
// Resume process.
func (dbp *DebuggedProcess) Continue() error {
for _, thread := range dbp.Threads {
err := thread.Continue()
if err != nil {
return err
}
}
return dbp.run(dbp.resume)
}
func (dbp *DebuggedProcess) resume() error {
thread, err := dbp.trapWait(-1)
if err != nil {
return err
}
if dbp.CurrentThread != thread {
dbp.SwitchThread(thread.Id)
}
pc, err := thread.PC()
if err != nil {
return err
}
if dbp.CurrentBreakpoint != nil || dbp.halt {
return dbp.Halt()
}
// Check to see if we hit a runtime.breakpoint
fn := dbp.goSymTable.PCToFunc(pc)
if fn != nil && fn.Name == "runtime.breakpoint" {
// step twice to get back to user code
for i := 0; i < 2; i++ {
if err = thread.Step(); err != nil {
return err
}
}
return dbp.Halt()
}
return fmt.Errorf("unrecognized breakpoint %#v", pc)
}
// Single step, will execute a single instruction.
func (dbp *DebuggedProcess) Step() (err error) {
fn := func() error {
dbp.singleStepping = true
defer func() { dbp.singleStepping = false }()
for _, th := range dbp.Threads {
if th.blocked() {
continue
}
err := th.Step()
if err != nil {
return err
}
}
return nil
}
return dbp.run(fn)
}
// Change from current thread to the thread specified by `tid`.
func (dbp *DebuggedProcess) SwitchThread(tid int) error {
if th, ok := dbp.Threads[tid]; ok {
fmt.Printf("thread context changed from %d to %d\n", dbp.CurrentThread.Id, tid)
dbp.CurrentThread = th
return nil
}
return fmt.Errorf("thread %d does not exist", tid)
}
// Returns an array of G structures representing the information
// Delve cares about from the internal runtime G structure.
func (dbp *DebuggedProcess) GoroutinesInfo() ([]*G, error) {
var (
allg []*G
rdr = dbp.DwarfReader()
)
addr, err := rdr.AddrFor("runtime.allglen")
if err != nil {
return nil, err
}
allglenBytes, err := dbp.CurrentThread.readMemory(uintptr(addr), 8)
if err != nil {
return nil, err
}
allglen := binary.LittleEndian.Uint64(allglenBytes)
rdr.Seek(0)
allgentryaddr, err := rdr.AddrFor("runtime.allg")
if err != nil {
return nil, err
}
faddr, err := dbp.CurrentThread.readMemory(uintptr(allgentryaddr), dbp.arch.PtrSize())
allgptr := binary.LittleEndian.Uint64(faddr)
for i := uint64(0); i < allglen; i++ {
g, err := parseG(dbp.CurrentThread, allgptr+(i*uint64(dbp.arch.PtrSize())), true)
if err != nil {
return nil, err
}
allg = append(allg, g)
}
return allg, nil
}
// Stop all threads.
func (dbp *DebuggedProcess) Halt() (err error) {
for _, th := range dbp.Threads {
if err := th.Halt(); err != nil {
return err
}
}
return nil
}
// Obtains register values from what Delve considers to be the current
// thread of the traced process.
func (dbp *DebuggedProcess) Registers() (Registers, error) {
return dbp.CurrentThread.Registers()
}
// Returns the PC of the current thread.
func (dbp *DebuggedProcess) PC() (uint64, error) {
return dbp.CurrentThread.PC()
}
// Returns the PC of the current thread.
func (dbp *DebuggedProcess) CurrentBreakpoint() *Breakpoint {
return dbp.CurrentThread.CurrentBreakpoint
}
// Returns the value of the named symbol.
func (dbp *DebuggedProcess) EvalVariable(name string) (*Variable, error) {
return dbp.CurrentThread.EvalVariable(name)
}
// Returns a reader for the dwarf data
func (dbp *DebuggedProcess) DwarfReader() *reader.Reader {
return reader.New(dbp.dwarf)
}
// Returns list of source files that comprise the debugged binary.
func (dbp *DebuggedProcess) Sources() map[string]*gosym.Obj {
return dbp.goSymTable.Files
}
// Returns list of functions present in the debugged program.
func (dbp *DebuggedProcess) Funcs() []gosym.Func {
return dbp.goSymTable.Funcs
}
// Converts an instruction address to a file/line/function.
func (dbp *DebuggedProcess) PCToLine(pc uint64) (string, int, *gosym.Func) {
return dbp.goSymTable.PCToLine(pc)
}
// Finds the breakpoint for the given ID.
func (dbp *DebuggedProcess) FindBreakpointByID(id int) (*Breakpoint, bool) {
for _, bp := range dbp.arch.HardwareBreakpoints() {
if bp != nil && bp.ID == id {
return bp, true
}
}
for _, bp := range dbp.Breakpoints {
if bp.ID == id {
return bp, true
}
}
return nil, false
}
// Finds the breakpoint for the given pc.
func (dbp *DebuggedProcess) FindBreakpoint(pc uint64) (*Breakpoint, bool) {
for _, bp := range dbp.arch.HardwareBreakpoints() {
if bp != nil && bp.Addr == pc {
return bp, true
}
}
if bp, ok := dbp.Breakpoints[pc]; ok {
return bp, true
}
return nil, false
}
// Returns a new DebuggedProcess struct.
func initializeDebugProcess(dbp *DebuggedProcess, path string, attach bool) (*DebuggedProcess, error) {
if attach {
var err error
dbp.execPtraceFunc(func() { err = sys.PtraceAttach(dbp.Pid) })
if err != nil {
return nil, err
}
_, _, err = wait(dbp.Pid, 0)
if err != nil {
return nil, err
}
}
proc, err := os.FindProcess(dbp.Pid)
if err != nil {
return nil, err
}
dbp.Process = proc
err = dbp.LoadInformation(path)
if err != nil {
return nil, err
}
if err := dbp.updateThreadList(); err != nil {
return nil, err
}
switch runtime.GOARCH {
case "amd64":
dbp.arch = AMD64Arch()
}
return dbp, nil
}
func (dbp *DebuggedProcess) clearTempBreakpoints() error {
for _, bp := range dbp.arch.HardwareBreakpoints() {
if bp != nil && bp.Temp {
if _, err := dbp.Clear(bp.Addr); err != nil {
return err
}
}
}
for _, bp := range dbp.Breakpoints {
if !bp.Temp {
continue
}
if _, err := dbp.Clear(bp.Addr); err != nil {
return err
}
}
return nil
}
func (dbp *DebuggedProcess) handleBreakpointOnThread(id int) (*Thread, error) {
thread, ok := dbp.Threads[id]
if !ok {
return nil, fmt.Errorf("could not find thread for %d", id)
}
pc, err := thread.PC()
if err != nil {
return nil, err
}
// Check for hardware breakpoint
for _, bp := range dbp.arch.HardwareBreakpoints() {
if bp != nil && bp.Addr == pc {
thread.CurrentBreakpoint = bp
return thread, nil
}
}
// Check to see if we have hit a software breakpoint.
if bp, ok := dbp.Breakpoints[pc-1]; ok {
thread.CurrentBreakpoint = bp
if err = thread.SetPC(bp.Addr); err != nil {
return nil, err
}
return thread, nil
}
if dbp.halt {
return thread, nil
}
fn := dbp.goSymTable.PCToFunc(pc)
if fn != nil && fn.Name == "runtime.breakpoint" {
thread.singleStepping = true
defer func() { thread.singleStepping = false }()
for i := 0; i < 2; i++ {
if err := thread.Step(); err != nil {
return nil, err
}
}
return thread, nil
}
return nil, NoBreakpointError{addr: pc}
}
func (dbp *DebuggedProcess) run(fn func() error) error {
if dbp.exited {
return fmt.Errorf("process has already exited")
}
dbp.running = true
dbp.halt = false
for _, th := range dbp.Threads {
th.CurrentBreakpoint = nil
}
defer func() { dbp.running = false }()
if err := fn(); err != nil {
if _, ok := err.(ManualStopError); !ok {
return err
}
}
return nil
}
func (dbp *DebuggedProcess) handlePtraceFuncs() {
// We must ensure here that we are running on the same thread during
// the execution of dbg. This is due to the fact that ptrace(2) expects
// all commands after PTRACE_ATTACH to come from the same thread.
runtime.LockOSThread()
for fn := range dbp.ptraceChan {
fn()
dbp.ptraceDoneChan <- nil
}
}
func (dbp *DebuggedProcess) execPtraceFunc(fn func()) {
dbp.ptraceChan <- fn
<-dbp.ptraceDoneChan
}