proctl.go 12.6 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 8 9 10
	"debug/gosym"
	"fmt"
	"os"
	"os/exec"
11 12 13
	"path/filepath"
	"strconv"
	"strings"
14
	"syscall"
15
	"time"
16

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

19
	"github.com/derekparker/delve/dwarf/frame"
20
	"github.com/derekparker/delve/dwarf/reader"
21 22
)

D
Derek Parker 已提交
23 24 25
// Struct representing a debugged process. Holds onto pid, register values,
// process struct and process state.
type DebuggedProcess struct {
26 27 28 29 30
	Pid                 int
	Process             *os.Process
	Dwarf               *dwarf.Data
	GoSymTable          *gosym.Table
	FrameEntries        *frame.FrameDescriptionEntries
D
Derek Parker 已提交
31
	HWBreakPoints       [4]*BreakPoint
32 33 34 35 36 37
	BreakPoints         map[uint64]*BreakPoint
	Threads             map[int]*ThreadContext
	CurrentThread       *ThreadContext
	breakpointIDCounter int
	running             bool
	halt                bool
D
Derek Parker 已提交
38 39
}

D
Derek Parker 已提交
40 41
// A ManualStopError happens when the user triggers a
// manual stop via SIGERM.
D
Derek Parker 已提交
42 43 44 45 46 47
type ManualStopError struct{}

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

D
Derek Parker 已提交
48
// Attach to an existing process with the given PID.
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
func Attach(pid int) (*DebuggedProcess, error) {
	dbp, err := newDebugProcess(pid, true)
	if err != nil {
		return nil, err
	}
	// Attach to all currently active threads.
	allm, err := dbp.CurrentThread.AllM()
	if err != nil {
		return nil, err
	}
	for _, m := range allm {
		if m.procid == 0 {
			continue
		}
		_, err := dbp.AttachThread(m.procid)
		if err != nil {
			return nil, err
		}
	}
	return dbp, nil
}

D
Derek Parker 已提交
71 72 73
// 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.
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
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)
}

// Returns a new DebuggedProcess struct with sensible defaults.
func newDebugProcess(pid int, attach bool) (*DebuggedProcess, error) {
	dbp := DebuggedProcess{
		Pid:         pid,
		Threads:     make(map[int]*ThreadContext),
		BreakPoints: make(map[uint64]*BreakPoint),
	}

	if attach {
		thread, err := dbp.AttachThread(pid)
		if err != nil {
			return nil, err
		}
		dbp.CurrentThread = thread
	} else {
		thread, err := dbp.addThread(pid)
		if err != nil {
			return nil, err
		}
		dbp.CurrentThread = thread
	}

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

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

	return &dbp, nil
}

D
Derek Parker 已提交
129 130
// Attach to a newly created thread, and store that thread in our list of
// known threads.
131 132 133 134 135
func (dbp *DebuggedProcess) AttachThread(tid int) (*ThreadContext, error) {
	if thread, ok := dbp.Threads[tid]; ok {
		return thread, nil
	}

P
Paul Sbarra 已提交
136 137
	err := sys.PtraceAttach(tid)
	if err != nil && err != sys.EPERM {
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
		// Do not return err if err == EPERM,
		// we may already be tracing this thread due to
		// PTRACE_O_TRACECLONE. We will surely blow up later
		// if we truly don't have permissions.
		return nil, fmt.Errorf("could not attach to new thread %d %s", tid, err)
	}

	pid, status, err := wait(tid, 0)
	if err != nil {
		return nil, err
	}

	if status.Exited() {
		return nil, fmt.Errorf("thread already exited %d", pid)
	}

	return dbp.addThread(tid)
}

D
Derek Parker 已提交
157 158
// Returns whether or not Delve thinks the debugged
// process is currently executing.
D
Derek Parker 已提交
159 160 161 162
func (dbp *DebuggedProcess) Running() bool {
	return dbp.running
}

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
// 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
	} else {
		// 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
198 199 200 201 202 203 204 205
		for _, bp := range dbp.HWBreakPoints {
			if bp == nil {
				continue
			}
			if uint64(bp.ID) == id {
				return bp.Addr, nil
			}
		}
206 207 208 209 210 211 212 213 214 215 216
		for _, bp := range dbp.BreakPoints {
			if uint64(bp.ID) == id {
				return bp.Addr, nil
			}
		}

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

D
Derek Parker 已提交
217 218
// Sends out a request that the debugged process halt
// execution. Sends SIGSTOP to all threads.
D
Derek Parker 已提交
219 220 221
func (dbp *DebuggedProcess) RequestManualStop() {
	dbp.halt = true
	for _, th := range dbp.Threads {
222
		if stopped(th.Id) {
D
Derek Parker 已提交
223 224
			continue
		}
P
Paul Sbarra 已提交
225
		sys.Tgkill(dbp.Pid, th.Id, sys.SIGSTOP)
D
Derek Parker 已提交
226 227 228 229
	}
	dbp.running = false
}

D
Derek Parker 已提交
230 231
// Sets a breakpoint, adding it to our list of known breakpoints. Uses
// the "current thread" when setting the breakpoint.
232 233 234 235 236 237 238 239 240 241
func (dbp *DebuggedProcess) Break(addr uint64) (*BreakPoint, error) {
	return dbp.CurrentThread.Break(addr)
}

// 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
	}
242 243 244 245
	return dbp.CurrentThread.Break(addr)
}

// Clears a breakpoint in the current thread.
246 247 248 249 250 251 252 253 254 255 256
func (dbp *DebuggedProcess) Clear(addr uint64) (*BreakPoint, error) {
	return dbp.CurrentThread.Clear(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.CurrentThread.Clear(addr)
257 258 259
}

// Returns the status of the current main thread context.
P
Paul Sbarra 已提交
260
func (dbp *DebuggedProcess) Status() *sys.WaitStatus {
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
	return dbp.CurrentThread.Status
}

// Loop through all threads, printing their information
// to the console.
func (dbp *DebuggedProcess) PrintThreadInfo() error {
	for _, th := range dbp.Threads {
		if err := th.PrintInfo(); err != nil {
			return err
		}
	}
	return nil
}

// Steps through process.
func (dbp *DebuggedProcess) Step() (err error) {
	var (
		th *ThreadContext
		ok bool
	)

	allm, err := dbp.CurrentThread.AllM()
	if err != nil {
		return err
	}

D
Derek Parker 已提交
287 288 289 290 291 292
	fn := func() error {
		for _, m := range allm {
			th, ok = dbp.Threads[m.procid]
			if !ok {
				th = dbp.Threads[dbp.Pid]
			}
293

D
Derek Parker 已提交
294 295 296 297 298
			if m.blocked == 0 {
				err := th.Step()
				if err != nil {
					return err
				}
299 300
			}

D
Derek Parker 已提交
301 302
		}
		return nil
303 304
	}

D
Derek Parker 已提交
305
	return dbp.run(fn)
306 307 308 309 310 311 312 313 314
}

// Step over function calls.
func (dbp *DebuggedProcess) Next() error {
	var (
		th *ThreadContext
		ok bool
	)

D
Derek Parker 已提交
315
	fn := func() error {
316 317 318 319 320
		allm, err := dbp.CurrentThread.AllM()
		if err != nil {
			return err
		}

D
Derek Parker 已提交
321 322 323 324 325
		for _, m := range allm {
			th, ok = dbp.Threads[m.procid]
			if !ok {
				th = dbp.Threads[dbp.Pid]
			}
326

D
Derek Parker 已提交
327 328 329 330 331 332 333 334 335
			if m.blocked == 1 {
				// Continue any blocked M so that the
				// scheduler can continue to do its'
				// job correctly.
				err := th.Continue()
				if err != nil {
					return err
				}
				continue
336 337
			}

D
Derek Parker 已提交
338
			err := th.Next()
P
Paul Sbarra 已提交
339
			if err != nil && err != sys.ESRCH {
D
Derek Parker 已提交
340 341
				return err
			}
342
		}
D
Derek Parker 已提交
343
		return stopTheWorld(dbp)
344
	}
D
Derek Parker 已提交
345
	return dbp.run(fn)
346 347 348 349 350 351 352 353 354 355 356
}

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

D
Derek Parker 已提交
357 358 359 360 361 362
	fn := func() error {
		wpid, _, err := trapWait(dbp, -1)
		if err != nil {
			return err
		}
		return handleBreakPoint(dbp, wpid)
363
	}
D
Derek Parker 已提交
364
	return dbp.run(fn)
365 366 367 368
}

// Obtains register values from what Delve considers to be the current
// thread of the traced process.
369
func (dbp *DebuggedProcess) Registers() (Registers, error) {
370 371 372 373 374 375 376 377 378 379 380 381
	return dbp.CurrentThread.Registers()
}

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)
}

382 383 384 385 386
// Returns a reader for the dwarf data
func (dbp *DebuggedProcess) DwarfReader() *reader.Reader {
	return reader.New(dbp.Dwarf)
}

D
Derek Parker 已提交
387 388 389 390 391 392 393 394 395 396 397 398
func (dbp *DebuggedProcess) run(fn func() error) error {
	dbp.running = true
	dbp.halt = false
	defer func() { dbp.running = false }()
	if err := fn(); err != nil {
		if _, ok := err.(ManualStopError); !ok {
			return err
		}
	}
	return nil
}

399 400 401 402 403 404 405 406
type ProcessExitedError struct {
	pid int
}

func (pe ProcessExitedError) Error() string {
	return fmt.Sprintf("process %d has exited", pe.pid)
}

P
Paul Sbarra 已提交
407
func trapWait(dbp *DebuggedProcess, pid int) (int, *sys.WaitStatus, error) {
408 409 410 411 412 413 414 415 416 417 418 419 420 421
	for {
		wpid, status, err := wait(pid, 0)
		if err != nil {
			return -1, nil, fmt.Errorf("wait err %s %d", err, pid)
		}
		if wpid == 0 {
			continue
		}
		if th, ok := dbp.Threads[wpid]; ok {
			th.Status = status
		}
		if status.Exited() && wpid == dbp.Pid {
			return -1, status, ProcessExitedError{wpid}
		}
P
Paul Sbarra 已提交
422
		if status.StopSignal() == sys.SIGTRAP && status.TrapCause() == sys.PTRACE_EVENT_CLONE {
423 424 425 426 427 428
			err = addNewThread(dbp, wpid)
			if err != nil {
				return -1, nil, err
			}
			continue
		}
P
Paul Sbarra 已提交
429
		if status.StopSignal() == sys.SIGTRAP {
430 431
			return wpid, status, nil
		}
P
Paul Sbarra 已提交
432
		if status.StopSignal() == sys.SIGSTOP && dbp.halt {
D
Derek Parker 已提交
433 434
			return -1, nil, ManualStopError{}
		}
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
	}
}

func handleBreakPoint(dbp *DebuggedProcess, pid int) error {
	thread := dbp.Threads[pid]
	if pid != dbp.CurrentThread.Id {
		fmt.Printf("thread context changed from %d to %d\n", dbp.CurrentThread.Id, pid)
		dbp.CurrentThread = thread
	}

	pc, err := thread.CurrentPC()
	if err != nil {
		return fmt.Errorf("could not get current pc %s", err)
	}

	// 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++ {
			err = thread.Step()
			if err != nil {
				return err
			}
		}
		stopTheWorld(dbp)
		return nil
	}

464 465 466 467 468 469 470 471 472 473
	// Check for hardware breakpoint
	for _, bp := range dbp.HWBreakPoints {
		if bp.Addr == pc {
			if !bp.temp {
				stopTheWorld(dbp)
			}
			return nil
		}
	}
	// Check to see if we have hit a software breakpoint.
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
	if bp, ok := dbp.BreakPoints[pc-1]; ok {
		if !bp.temp {
			stopTheWorld(dbp)
		}
		return nil
	}

	return fmt.Errorf("did not hit recognized breakpoint")
}

// Ensure execution of every traced thread is halted.
func stopTheWorld(dbp *DebuggedProcess) error {
	// Loop through all threads and ensure that we
	// stop the rest of them, so that by the time
	// we return control to the user, all threads
	// are inactive. We send SIGSTOP and ensure all
	// threads are in in signal-delivery-stop mode.
	for _, th := range dbp.Threads {
492
		if stopped(th.Id) {
493 494
			continue
		}
P
Paul Sbarra 已提交
495
		err := sys.Tgkill(dbp.Pid, th.Id, sys.SIGSTOP)
496 497 498
		if err != nil {
			return err
		}
P
Paul Sbarra 已提交
499
		pid, _, err := wait(th.Id, sys.WNOHANG)
500 501 502 503 504 505 506 507 508 509 510
		if err != nil {
			return fmt.Errorf("wait err %s %d", err, pid)
		}
	}

	return nil
}

func addNewThread(dbp *DebuggedProcess, pid int) error {
	// A traced thread has cloned a new thread, grab the pid and
	// add it to our list of traced threads.
P
Paul Sbarra 已提交
511
	msg, err := sys.PtraceGetEventMsg(pid)
512 513 514 515 516 517 518 519 520 521
	if err != nil {
		return fmt.Errorf("could not get event message: %s", err)
	}
	fmt.Println("new thread spawned", msg)

	_, err = dbp.addThread(int(msg))
	if err != nil {
		return err
	}

P
Paul Sbarra 已提交
522
	err = sys.PtraceCont(int(msg), 0)
523 524 525 526
	if err != nil {
		return fmt.Errorf("could not continue new thread %d %s", msg, err)
	}

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
	// Here we loop for a while to ensure that the once we continue
	// the newly created thread, we allow enough time for the runtime
	// to assign m->procid. This is important because we rely on
	// looping through runtime.allm in other parts of the code, so
	// we require that this is set before we do anything else.
	// TODO(dp): we might be able to eliminate this loop by telling
	// the CPU to emit a breakpoint exception on write to this location
	// in memory. That way we prevent having to loop, and can be
	// notified as soon as m->procid is set.
	th := dbp.Threads[pid]
	for {
		allm, _ := th.AllM()
		for _, m := range allm {
			if m.procid == int(msg) {
				// Continue the thread that cloned
				return sys.PtraceCont(pid, 0)
			}
		}
		time.Sleep(time.Millisecond)
546 547 548
	}
}

P
Paul Sbarra 已提交
549 550 551
func wait(pid, options int) (int, *sys.WaitStatus, error) {
	var status sys.WaitStatus
	wpid, err := sys.Wait4(pid, &status, sys.WALL|options, nil)
552 553
	return wpid, &status, err
}