proctl.go 13.0 KB
Newer Older
1 2 3 4 5
// Package proctl provides functions for attaching to and manipulating
// a process during the debug session.
package proctl

import (
D
Derek Parker 已提交
6
	"debug/dwarf"
7
	"debug/gosym"
8
	"encoding/binary"
9 10 11
	"fmt"
	"os"
	"os/exec"
12 13 14
	"path/filepath"
	"strconv"
	"strings"
D
Derek Parker 已提交
15
	"sync"
16 17
	"syscall"

18 19
	sys "golang.org/x/sys/unix"

20
	"github.com/derekparker/delve/dwarf/frame"
D
Derek Parker 已提交
21
	"github.com/derekparker/delve/dwarf/line"
22
	"github.com/derekparker/delve/dwarf/reader"
D
Derek Parker 已提交
23
	"github.com/derekparker/delve/source"
24 25
)

D
Derek Parker 已提交
26 27 28
// Struct representing a debugged process. Holds onto pid, register values,
// process struct and process state.
type DebuggedProcess struct {
29 30
	Pid                 int
	Process             *os.Process
D
Derek Parker 已提交
31
	HWBreakPoints       [4]*BreakPoint
32 33
	BreakPoints         map[uint64]*BreakPoint
	Threads             map[int]*ThreadContext
34
	CurrentBreakpoint   *BreakPoint
35
	CurrentThread       *ThreadContext
36 37 38 39
	dwarf               *dwarf.Data
	goSymTable          *gosym.Table
	frameEntries        frame.FrameDescriptionEntries
	lineInfo            *line.DebugLineInfo
D
Derek Parker 已提交
40
	os                  *OSProcessDetails
D
Derek Parker 已提交
41
	ast                 *source.Searcher
42 43 44
	breakpointIDCounter int
	running             bool
	halt                bool
45
	exited              bool
D
Derek Parker 已提交
46 47
}

D
Derek Parker 已提交
48 49
// A ManualStopError happens when the user triggers a
// manual stop via SIGERM.
D
Derek Parker 已提交
50 51 52 53 54 55
type ManualStopError struct{}

func (mse ManualStopError) Error() string {
	return "Manual stop requested"
}

56 57 58 59 60 61 62 63 64 65 66
// 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)
}

D
Derek Parker 已提交
67
// Attach to an existing process with the given PID.
68 69 70 71 72 73 74 75
func Attach(pid int) (*DebuggedProcess, error) {
	dbp, err := newDebugProcess(pid, true)
	if err != nil {
		return nil, err
	}
	return dbp, nil
}

D
Derek Parker 已提交
76 77 78
// Create and begin debugging a new process. First entry in
// `cmd` is the program to run, and then rest are the arguments
// to be supplied to that process.
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
func Launch(cmd []string) (*DebuggedProcess, error) {
	proc := exec.Command(cmd[0])
	proc.Args = cmd
	proc.Stdout = os.Stdout
	proc.Stderr = os.Stderr
	proc.SysProcAttr = &syscall.SysProcAttr{Ptrace: true}

	if err := proc.Start(); err != nil {
		return nil, err
	}

	_, _, err := wait(proc.Process.Pid, 0)
	if err != nil {
		return nil, fmt.Errorf("waiting for target execve failed: %s", err)
	}

	return newDebugProcess(proc.Process.Pid, false)
}

98 99 100 101 102 103
// Returns whether or not Delve thinks the debugged
// process has exited.
func (dbp *DebuggedProcess) Exited() bool {
	return dbp.exited
}

D
Derek Parker 已提交
104 105
// Returns whether or not Delve thinks the debugged
// process is currently executing.
D
Derek Parker 已提交
106 107 108 109
func (dbp *DebuggedProcess) Running() bool {
	return dbp.running
}

D
Derek Parker 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
// 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() error {
	var wg sync.WaitGroup

	exe, err := dbp.findExecutable()
	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
}

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
// 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
		}

148
		pc, _, err := dbp.goSymTable.LineToPC(fileName, line)
149 150 151 152
		if err != nil {
			return 0, err
		}
		return pc, nil
D
Derek Parker 已提交
153
	}
154

D
Derek Parker 已提交
155
	// Try to lookup by function name
156
	fn := dbp.goSymTable.LookupFunc(str)
D
Derek Parker 已提交
157 158 159 160 161 162 163 164 165
	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)
	}
166

D
Derek Parker 已提交
167 168 169 170
	// Use as breakpoint id
	for _, bp := range dbp.HWBreakPoints {
		if bp == nil {
			continue
171
		}
D
Derek Parker 已提交
172 173
		if uint64(bp.ID) == id {
			return bp.Addr, nil
174 175
		}
	}
D
Derek Parker 已提交
176 177 178 179 180 181 182 183
	for _, bp := range dbp.BreakPoints {
		if uint64(bp.ID) == id {
			return bp.Addr, nil
		}
	}

	// Last resort, use as raw address
	return id, nil
184 185
}

D
Derek Parker 已提交
186 187
// Sends out a request that the debugged process halt
// execution. Sends SIGSTOP to all threads.
D
Derek Parker 已提交
188 189 190
func (dbp *DebuggedProcess) RequestManualStop() {
	dbp.halt = true
	for _, th := range dbp.Threads {
D
Derek Parker 已提交
191
		th.Halt()
D
Derek Parker 已提交
192 193 194 195
	}
	dbp.running = false
}

D
Derek Parker 已提交
196 197 198 199 200 201 202 203 204
// 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.
205
func (dbp *DebuggedProcess) Break(addr uint64) (*BreakPoint, error) {
D
Derek Parker 已提交
206
	return dbp.setBreakpoint(dbp.CurrentThread.Id, addr)
207 208 209 210 211 212 213 214
}

// 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
	}
D
Derek Parker 已提交
215
	return dbp.Break(addr)
216 217 218
}

// Clears a breakpoint in the current thread.
219
func (dbp *DebuggedProcess) Clear(addr uint64) (*BreakPoint, error) {
D
Derek Parker 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
	tid := dbp.CurrentThread.Id
	// Check for hardware breakpoint
	for i, bp := range dbp.HWBreakPoints {
		if bp == nil {
			continue
		}
		if bp.Addr == addr {
			dbp.HWBreakPoints[i] = nil
			if err := clearHardwareBreakpoint(i, tid); err != nil {
				return nil, err
			}
			return bp, nil
		}
	}
	// Check for software breakpoint
	if bp, ok := dbp.BreakPoints[addr]; ok {
		thread := dbp.Threads[tid]
		if _, err := writeMemory(thread, uintptr(bp.Addr), bp.OriginalData); err != nil {
			return nil, fmt.Errorf("could not clear breakpoint %s", err)
		}
		delete(dbp.BreakPoints, addr)
		return bp, nil
	}
	return nil, fmt.Errorf("no breakpoint at %#v", addr)
244 245 246 247 248 249 250 251
}

// 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
	}
D
Derek Parker 已提交
252
	return dbp.Clear(addr)
253 254 255
}

// Returns the status of the current main thread context.
P
Paul Sbarra 已提交
256
func (dbp *DebuggedProcess) Status() *sys.WaitStatus {
257 258 259 260 261
	return dbp.CurrentThread.Status
}

// Step over function calls.
func (dbp *DebuggedProcess) Next() error {
D
Derek Parker 已提交
262 263
	return dbp.run(dbp.next)
}
264

D
Derek Parker 已提交
265 266 267 268 269 270 271 272 273 274
func (dbp *DebuggedProcess) next() error {
	curg, err := dbp.CurrentThread.curG()
	if err != nil {
		return err
	}
	defer dbp.clearTempBreakpoints()
	for _, th := range dbp.Threads {
		if th.blocked() { // Continue threads that aren't running go code.
			if err := th.Continue(); err != nil {
				return err
275
			}
D
Derek Parker 已提交
276 277 278 279 280 281
			continue
		}
		if err := th.Next(); err != nil {
			return err
		}
	}
282

D
Derek Parker 已提交
283
	for {
284
		thread, err := trapWait(dbp, -1)
D
Derek Parker 已提交
285 286
		if err != nil {
			return err
D
Derek Parker 已提交
287
		}
288
		// Check if we've hit a breakpoint.
289 290
		if dbp.CurrentBreakpoint != nil {
			if err = thread.clearTempBreakpoint(dbp.CurrentBreakpoint.Addr); err != nil {
291 292
				return err
			}
D
Derek Parker 已提交
293 294
		}
		// Grab the current goroutine for this thread.
295
		tg, err := thread.curG()
D
Derek Parker 已提交
296 297 298 299 300
		if err != nil {
			return err
		}
		// Make sure we're on the same goroutine.
		// TODO(dp) take into account goroutine exit.
301
		if tg.Id == curg.Id {
302 303
			if dbp.CurrentThread != thread {
				dbp.SwitchThread(thread.Id)
D
Derek Parker 已提交
304
			}
D
Derek Parker 已提交
305
			break
306 307
		}
	}
D
Derek Parker 已提交
308
	return dbp.Halt()
309 310 311 312 313 314 315 316 317 318
}

// Resume process.
func (dbp *DebuggedProcess) Continue() error {
	for _, thread := range dbp.Threads {
		err := thread.Continue()
		if err != nil {
			return err
		}
	}
319 320
	return dbp.run(dbp.resume)
}
321

322
func (dbp *DebuggedProcess) resume() error {
323
	thread, err := trapWait(dbp, -1)
324 325 326 327 328 329 330 331 332 333
	if err != nil {
		return err
	}
	if dbp.CurrentThread != thread {
		dbp.SwitchThread(thread.Id)
	}
	pc, err := thread.CurrentPC()
	if err != nil {
		return err
	}
334 335
	if dbp.CurrentBreakpoint != nil {
		if !dbp.CurrentBreakpoint.Temp {
336
			return dbp.Halt()
D
Derek Parker 已提交
337
		}
338 339
	}
	// Check to see if we hit a runtime.breakpoint
340
	fn := dbp.goSymTable.PCToFunc(pc)
341 342 343 344 345
	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
D
Derek Parker 已提交
346 347
			}
		}
348
		return dbp.Halt()
349
	}
350 351

	return fmt.Errorf("unrecognized breakpoint %#v", pc)
352 353
}

D
Derek Parker 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
// Steps through process.
func (dbp *DebuggedProcess) Step() (err error) {
	fn := func() error {
		for _, th := range dbp.Threads {
			if th.blocked() {
				continue
			}
			err := th.Step()
			if err != nil {
				return err
			}
		}
		return nil
	}

	return dbp.run(fn)
}

372 373 374 375
// Change from current thread to the thread specified by `tid`.
func (dbp *DebuggedProcess) SwitchThread(tid int) error {
	if th, ok := dbp.Threads[tid]; ok {
		dbp.CurrentThread = th
D
Derek Parker 已提交
376
		fmt.Printf("thread context changed from %d to %d\n", dbp.CurrentThread.Id, tid)
377 378 379 380 381
		return nil
	}
	return fmt.Errorf("thread %d does not exist", tid)
}

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
func (dbp *DebuggedProcess) GoroutinesInfo() ([]*G, error) {
	var (
		allg   []*G
		reader = dbp.dwarf.Reader()
	)

	allglen, err := allglenval(dbp, reader)
	if err != nil {
		return nil, err
	}
	reader.Seek(0)
	allgentryaddr, err := addressFor(dbp, "runtime.allg", reader)
	if err != nil {
		return nil, err
	}
	faddr, err := dbp.CurrentThread.readMemory(uintptr(allgentryaddr), ptrsize)
	allgptr := binary.LittleEndian.Uint64(faddr)

	for i := uint64(0); i < allglen; i++ {
		g, err := parseG(dbp, allgptr+(i*uint64(ptrsize)), reader)
		if err != nil {
			return nil, err
		}
		allg = append(allg, g)
	}
	return allg, nil
}

410 411
// Obtains register values from what Delve considers to be the current
// thread of the traced process.
412
func (dbp *DebuggedProcess) Registers() (Registers, error) {
413 414 415
	return dbp.CurrentThread.Registers()
}

416
// Returns the PC of the current thread.
417 418 419 420 421 422 423 424 425
func (dbp *DebuggedProcess) CurrentPC() (uint64, error) {
	return dbp.CurrentThread.CurrentPC()
}

// Returns the value of the named symbol.
func (dbp *DebuggedProcess) EvalSymbol(name string) (*Variable, error) {
	return dbp.CurrentThread.EvalSymbol(name)
}

D
Derek Parker 已提交
426 427 428 429
func (dbp *DebuggedProcess) CallFn(name string, fn func(*ThreadContext) error) error {
	return dbp.CurrentThread.CallFn(name, fn)
}

430 431
// Returns a reader for the dwarf data
func (dbp *DebuggedProcess) DwarfReader() *reader.Reader {
432 433 434 435 436 437 438 439 440 441 442 443 444
	return reader.New(dbp.dwarf)
}

func (dbp *DebuggedProcess) Sources() map[string]*gosym.Obj {
	return dbp.goSymTable.Files
}

func (dbp *DebuggedProcess) Funcs() []gosym.Func {
	return dbp.goSymTable.Funcs
}

func (dbp *DebuggedProcess) PCToLine(pc uint64) (string, int, *gosym.Func) {
	return dbp.goSymTable.PCToLine(pc)
445 446
}

D
Derek Parker 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459
// Finds the breakpoint for the given pc.
func (dbp *DebuggedProcess) FindBreakpoint(pc uint64) (*BreakPoint, bool) {
	for _, bp := range dbp.HWBreakPoints {
		if bp != nil && bp.Addr == pc {
			return bp, true
		}
	}
	if bp, ok := dbp.BreakPoints[pc]; ok {
		return bp, true
	}
	return nil, false
}

D
Derek Parker 已提交
460 461 462 463 464 465 466
// Returns a new DebuggedProcess struct.
func newDebugProcess(pid int, attach bool) (*DebuggedProcess, error) {
	dbp := DebuggedProcess{
		Pid:         pid,
		Threads:     make(map[int]*ThreadContext),
		BreakPoints: make(map[uint64]*BreakPoint),
		os:          new(OSProcessDetails),
D
Derek Parker 已提交
467
		ast:         source.New(),
D
Derek Parker 已提交
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
	}

	if attach {
		err := sys.PtraceAttach(pid)
		if err != nil {
			return nil, err
		}
		_, _, err = wait(pid, 0)
		if err != nil {
			return nil, err
		}
	}

	proc, err := os.FindProcess(pid)
	if err != nil {
		return nil, err
	}

	dbp.Process = proc
	err = dbp.LoadInformation()
	if err != nil {
		return nil, err
	}

	if err := dbp.updateThreadList(); err != nil {
		return nil, err
	}

	return &dbp, nil
}
D
Derek Parker 已提交
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
func (dbp *DebuggedProcess) clearTempBreakpoints() error {
	for _, bp := range dbp.HWBreakPoints {
		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
}
516
func (dbp *DebuggedProcess) handleBreakpointOnThread(id int) (*ThreadContext, error) {
D
Derek Parker 已提交
517 518
	thread, ok := dbp.Threads[id]
	if !ok {
519
		return nil, fmt.Errorf("could not find thread for %d", id)
D
Derek Parker 已提交
520 521 522
	}
	pc, err := thread.CurrentPC()
	if err != nil {
523
		return nil, err
D
Derek Parker 已提交
524 525 526 527
	}
	// Check for hardware breakpoint
	for _, bp := range dbp.HWBreakPoints {
		if bp != nil && bp.Addr == pc {
528 529
			dbp.CurrentBreakpoint = bp
			return thread, nil
D
Derek Parker 已提交
530 531 532 533
		}
	}
	// Check to see if we have hit a software breakpoint.
	if bp, ok := dbp.BreakPoints[pc-1]; ok {
534 535
		dbp.CurrentBreakpoint = bp
		return thread, nil
D
Derek Parker 已提交
536
	}
537
	return thread, nil
D
Derek Parker 已提交
538
}
D
Derek Parker 已提交
539

D
Derek Parker 已提交
540
func (dbp *DebuggedProcess) run(fn func() error) error {
541 542 543
	if dbp.exited {
		return fmt.Errorf("process has already exited")
	}
D
Derek Parker 已提交
544 545
	dbp.running = true
	dbp.halt = false
546
	dbp.CurrentBreakpoint = nil
D
Derek Parker 已提交
547 548 549 550 551 552 553 554
	defer func() { dbp.running = false }()
	if err := fn(); err != nil {
		if _, ok := err.(ManualStopError); !ok {
			return err
		}
	}
	return nil
}