proc_windows.go 14.9 KB
Newer Older
L
Luke Hoban 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
package proc

import (
	"debug/gosym"
	"debug/pe"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"sync"
	"syscall"
	"unsafe"

	sys "golang.org/x/sys/windows"

	"github.com/derekparker/delve/dwarf/frame"
	"github.com/derekparker/delve/dwarf/line"
19
	"golang.org/x/debug/dwarf"
L
Luke Hoban 已提交
20 21 22 23
)

// OSProcessDetails holds Windows specific information.
type OSProcessDetails struct {
24
	hProcess    syscall.Handle
L
Luke Hoban 已提交
25 26 27 28 29 30 31 32 33
	breakThread int
}

// Launch creates and begins debugging a new process.
func Launch(cmd []string) (*Process, error) {
	argv0Go, err := filepath.Abs(cmd[0])
	if err != nil {
		return nil, err
	}
34 35

	// Make sure the binary exists and is an executable file
L
Luke Hoban 已提交
36 37 38 39 40
	if filepath.Base(cmd[0]) == cmd[0] {
		if _, err := exec.LookPath(cmd[0]); err != nil {
			return nil, err
		}
	}
41 42 43 44

	peFile, err := openExecutablePath(argv0Go)
	if err != nil {
		return nil, NotExecutableErr
L
Luke Hoban 已提交
45
	}
46 47
	peFile.Close()

L
Luke Hoban 已提交
48 49 50 51 52 53 54 55 56 57 58 59
	// Duplicate the stdin/stdout/stderr handles
	files := []uintptr{uintptr(syscall.Stdin), uintptr(syscall.Stdout), uintptr(syscall.Stderr)}
	p, _ := syscall.GetCurrentProcess()
	fd := make([]syscall.Handle, len(files))
	for i := range files {
		err := syscall.DuplicateHandle(p, syscall.Handle(files[i]), p, &fd[i], 0, true, syscall.DUPLICATE_SAME_ACCESS)
		if err != nil {
			return nil, err
		}
		defer syscall.CloseHandle(syscall.Handle(fd[i]))
	}

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
	argv0, err := syscall.UTF16PtrFromString(argv0Go)
	if err != nil {
		return nil, err
	}

	// create suitable command line for CreateProcess
	// see https://github.com/golang/go/blob/master/src/syscall/exec_windows.go#L326
	// adapted from standard library makeCmdLine
	// see https://github.com/golang/go/blob/master/src/syscall/exec_windows.go#L86
	var cmdLineGo string
	if len(cmd) >= 1 {
		for _, v := range cmd {
			if cmdLineGo != "" {
				cmdLineGo += " "
			}
			cmdLineGo += syscall.EscapeArg(v)
		}
	}

	var cmdLine *uint16
	if cmdLineGo != "" {
		if cmdLine, err = syscall.UTF16PtrFromString(cmdLineGo); err != nil {
			return nil, err
		}
	}

L
Luke Hoban 已提交
86 87 88 89 90 91 92 93
	// Initialize the startup info and create process
	si := new(sys.StartupInfo)
	si.Cb = uint32(unsafe.Sizeof(*si))
	si.Flags = syscall.STARTF_USESTDHANDLES
	si.StdInput = sys.Handle(fd[0])
	si.StdOutput = sys.Handle(fd[1])
	si.StdErr = sys.Handle(fd[2])
	pi := new(sys.ProcessInformation)
94
	err = sys.CreateProcess(argv0, cmdLine, nil, nil, true, _DEBUG_ONLY_THIS_PROCESS, nil, nil, si, pi)
L
Luke Hoban 已提交
95 96 97 98 99 100
	if err != nil {
		return nil, err
	}
	sys.CloseHandle(sys.Handle(pi.Process))
	sys.CloseHandle(sys.Handle(pi.Thread))

101 102
	return newDebugProcess(int(pi.ProcessId), argv0Go)
}
L
Luke Hoban 已提交
103

104 105 106 107
// newDebugProcess prepares process pid for debugging.
func newDebugProcess(pid int, exepath string) (*Process, error) {
	dbp := New(pid)
	// It should not actually be possible for the
L
Luke Hoban 已提交
108
	// call to waitForDebugEvent to fail, since Windows
109 110 111 112
	// will always fire a CREATE_PROCESS_DEBUG_EVENT event
	// immediately after launching under DEBUG_ONLY_THIS_PROCESS.
	// Attaching with DebugActiveProcess has similar effect.
	var err error
L
Luke Hoban 已提交
113 114 115 116 117 118 119 120 121 122 123
	var tid, exitCode int
	dbp.execPtraceFunc(func() {
		tid, exitCode, err = dbp.waitForDebugEvent()
	})
	if err != nil {
		return nil, err
	}
	if tid == 0 {
		dbp.postExit()
		return nil, ProcessExitedError{Pid: dbp.Pid, Status: exitCode}
	}
124 125
	return initializeDebugProcess(dbp, exepath, false)
}
L
Luke Hoban 已提交
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
// findExePath searches for process pid, and returns its executable path.
func findExePath(pid int) (string, error) {
	// Original code suggested different approach (see below).
	// Maybe it could be useful in the future.
	//
	// Find executable path from PID/handle on Windows:
	// https://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx

	p, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))
	if err != nil {
		return "", err
	}
	defer syscall.CloseHandle(p)

	n := uint32(128)
	for {
		buf := make([]uint16, int(n))
		err = _QueryFullProcessImageName(p, 0, &buf[0], &n)
		switch err {
		case syscall.ERROR_INSUFFICIENT_BUFFER:
			// try bigger buffer
			n *= 2
			// but stop if it gets too big
			if n > 10000 {
				return "", err
			}
		case nil:
			return syscall.UTF16ToString(buf[:n]), nil
		default:
			return "", err
		}
	}
L
Luke Hoban 已提交
159 160 161 162
}

// Attach to an existing process with the given PID.
func Attach(pid int) (*Process, error) {
163 164 165 166 167 168 169 170 171 172
	// TODO: Probably should have SeDebugPrivilege before starting here.
	err := _DebugActiveProcess(uint32(pid))
	if err != nil {
		return nil, err
	}
	exepath, err := findExePath(pid)
	if err != nil {
		return nil, err
	}
	return newDebugProcess(pid, exepath)
L
Luke Hoban 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185
}

// Kill kills the process.
func (dbp *Process) Kill() error {
	if dbp.exited {
		return nil
	}
	if !dbp.Threads[dbp.Pid].Stopped() {
		return errors.New("process must be stopped in order to kill it")
	}
	// TODO: Should not have to ignore failures here,
	// but some tests appear to Kill twice causing
	// this to fail on second attempt.
186
	_ = syscall.TerminateProcess(dbp.os.hProcess, 1)
L
Luke Hoban 已提交
187 188 189 190 191
	dbp.exited = true
	return nil
}

func (dbp *Process) requestManualStop() error {
192
	return _DebugBreakProcess(dbp.os.hProcess)
L
Luke Hoban 已提交
193 194 195 196 197 198 199 200
}

func (dbp *Process) updateThreadList() error {
	// We ignore this request since threads are being
	// tracked as they are created/killed in waitForDebugEvent.
	return nil
}

201
func (dbp *Process) addThread(hThread syscall.Handle, threadID int, attach bool) (*Thread, error) {
L
Luke Hoban 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
	if thread, ok := dbp.Threads[threadID]; ok {
		return thread, nil
	}
	thread := &Thread{
		ID:  threadID,
		dbp: dbp,
		os:  new(OSSpecificDetails),
	}
	thread.os.hThread = hThread
	dbp.Threads[threadID] = thread
	if dbp.CurrentThread == nil {
		dbp.SwitchThread(thread.ID)
	}
	return thread, nil
}

func (dbp *Process) parseDebugFrame(exe *pe.File, wg *sync.WaitGroup) {
	defer wg.Done()

221 222 223 224 225 226
	debugFrameSec := exe.Section(".debug_frame")
	debugInfoSec := exe.Section(".debug_info")

	if debugFrameSec != nil && debugInfoSec != nil {
		debugFrame, err := debugFrameSec.Data()
		if err != nil && uint32(len(debugFrame)) < debugFrameSec.Size {
L
Luke Hoban 已提交
227 228 229
			fmt.Println("could not get .debug_frame section", err)
			os.Exit(1)
		}
230 231 232 233 234 235 236
		if 0 < debugFrameSec.VirtualSize && debugFrameSec.VirtualSize < debugFrameSec.Size {
			debugFrame = debugFrame[:debugFrameSec.VirtualSize]
		}
		dat, err := debugInfoSec.Data()
		if err != nil {
			fmt.Println("could not get .debug_info section", err)
			os.Exit(1)
L
Luke Hoban 已提交
237
		}
238
		dbp.frameEntries = frame.Parse(debugFrame, frame.DwarfEndian(dat))
L
Luke Hoban 已提交
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
	} else {
		fmt.Println("could not find .debug_frame section in binary")
		os.Exit(1)
	}
}

// Borrowed from https://golang.org/src/cmd/internal/objfile/pe.go
func findPESymbol(f *pe.File, name string) (*pe.Symbol, error) {
	for _, s := range f.Symbols {
		if s.Name != name {
			continue
		}
		if s.SectionNumber <= 0 {
			return nil, fmt.Errorf("symbol %s: invalid section number %d", name, s.SectionNumber)
		}
		if len(f.Sections) < int(s.SectionNumber) {
			return nil, fmt.Errorf("symbol %s: section number %d is larger than max %d", name, s.SectionNumber, len(f.Sections))
		}
		return s, nil
	}
	return nil, fmt.Errorf("no %s symbol found", name)
}

// Borrowed from https://golang.org/src/cmd/internal/objfile/pe.go
func loadPETable(f *pe.File, sname, ename string) ([]byte, error) {
	ssym, err := findPESymbol(f, sname)
	if err != nil {
		return nil, err
	}
	esym, err := findPESymbol(f, ename)
	if err != nil {
		return nil, err
	}
	if ssym.SectionNumber != esym.SectionNumber {
		return nil, fmt.Errorf("%s and %s symbols must be in the same section", sname, ename)
	}
	sect := f.Sections[ssym.SectionNumber-1]
	data, err := sect.Data()
	if err != nil {
		return nil, err
	}
	return data[ssym.Value:esym.Value], nil
}

// Borrowed from https://golang.org/src/cmd/internal/objfile/pe.go
func pcln(exe *pe.File) (textStart uint64, symtab, pclntab []byte, err error) {
	var imageBase uint64
	switch oh := exe.OptionalHeader.(type) {
	case *pe.OptionalHeader32:
		imageBase = uint64(oh.ImageBase)
	case *pe.OptionalHeader64:
		imageBase = oh.ImageBase
	default:
		return 0, nil, nil, fmt.Errorf("pe file format not recognized")
	}
	if sect := exe.Section(".text"); sect != nil {
		textStart = imageBase + uint64(sect.VirtualAddress)
	}
	if pclntab, err = loadPETable(exe, "runtime.pclntab", "runtime.epclntab"); err != nil {
		// We didn't find the symbols, so look for the names used in 1.3 and earlier.
		// TODO: Remove code looking for the old symbols when we no longer care about 1.3.
		var err2 error
		if pclntab, err2 = loadPETable(exe, "pclntab", "epclntab"); err2 != nil {
			return 0, nil, nil, err
		}
	}
	if symtab, err = loadPETable(exe, "runtime.symtab", "runtime.esymtab"); err != nil {
		// Same as above.
		var err2 error
		if symtab, err2 = loadPETable(exe, "symtab", "esymtab"); err2 != nil {
			return 0, nil, nil, err
		}
	}
	return textStart, symtab, pclntab, nil
}

func (dbp *Process) obtainGoSymbols(exe *pe.File, wg *sync.WaitGroup) {
	defer wg.Done()

	_, symdat, pclndat, err := pcln(exe)
	if err != nil {
		fmt.Println("could not get Go symbols", err)
		os.Exit(1)
	}

	pcln := gosym.NewLineTable(pclndat, uint64(exe.Section(".text").Offset))
	tab, err := gosym.NewTable(symdat, pcln)
	if err != nil {
		fmt.Println("could not get initialize line table", err)
		os.Exit(1)
	}

	dbp.goSymTable = tab
}

func (dbp *Process) parseDebugLineInfo(exe *pe.File, wg *sync.WaitGroup) {
	defer wg.Done()

	if sec := exe.Section(".debug_line"); sec != nil {
		debugLine, err := sec.Data()
		if err != nil && uint32(len(debugLine)) < sec.Size {
			fmt.Println("could not get .debug_line section", err)
			os.Exit(1)
		}
		if 0 < sec.VirtualSize && sec.VirtualSize < sec.Size {
			debugLine = debugLine[:sec.VirtualSize]
		}
		dbp.lineInfo = line.Parse(debugLine)
	} else {
		fmt.Println("could not find .debug_line section in binary")
		os.Exit(1)
	}
}

353 354
var UnsupportedArchErr = errors.New("unsupported architecture of windows/386 - only windows/amd64 is supported")

L
Luke Hoban 已提交
355
func (dbp *Process) findExecutable(path string) (*pe.File, error) {
356
	peFile, err := openExecutablePath(path)
L
Luke Hoban 已提交
357 358 359
	if err != nil {
		return nil, err
	}
360 361
	if peFile.Machine != pe.IMAGE_FILE_MACHINE_AMD64 {
		return nil, UnsupportedArchErr
L
Luke Hoban 已提交
362
	}
363
	dbp.dwarf, err = dwarfFromPE(peFile)
L
Luke Hoban 已提交
364 365 366 367 368 369
	if err != nil {
		return nil, err
	}
	return peFile, nil
}

370 371
func openExecutablePath(path string) (*pe.File, error) {
	f, err := os.OpenFile(path, 0, os.ModePerm)
372 373 374
	if err != nil {
		return nil, err
	}
375 376 377
	return pe.NewFile(f)
}

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
// Adapted from src/debug/pe/file.go: pe.(*File).DWARF()
func dwarfFromPE(f *pe.File) (*dwarf.Data, error) {
	// There are many other DWARF sections, but these
	// are the ones the debug/dwarf package uses.
	// Don't bother loading others.
	var names = [...]string{"abbrev", "info", "line", "str"}
	var dat [len(names)][]byte
	for i, name := range names {
		name = ".debug_" + name
		s := f.Section(name)
		if s == nil {
			continue
		}
		b, err := s.Data()
		if err != nil && uint32(len(b)) < s.Size {
			return nil, err
		}
		if 0 < s.VirtualSize && s.VirtualSize < s.Size {
			b = b[:s.VirtualSize]
		}
		dat[i] = b
	}

	abbrev, info, line, str := dat[0], dat[1], dat[2], dat[3]
	return dwarf.New(abbrev, nil, nil, info, line, nil, nil, str)
}

L
Luke Hoban 已提交
405
func (dbp *Process) waitForDebugEvent() (threadID, exitCode int, err error) {
406
	var debugEvent _DEBUG_EVENT
407
	shouldExit := false
L
Luke Hoban 已提交
408 409
	for {
		// Wait for a debug event...
410 411 412
		err := _WaitForDebugEvent(&debugEvent, syscall.INFINITE)
		if err != nil {
			return 0, 0, err
L
Luke Hoban 已提交
413 414 415
		}

		// ... handle each event kind ...
416 417 418 419 420 421 422 423 424
		unionPtr := unsafe.Pointer(&debugEvent.U[0])
		switch debugEvent.DebugEventCode {
		case _CREATE_PROCESS_DEBUG_EVENT:
			debugInfo := (*_CREATE_PROCESS_DEBUG_INFO)(unionPtr)
			hFile := debugInfo.File
			if hFile != 0 && hFile != syscall.InvalidHandle {
				err = syscall.CloseHandle(hFile)
				if err != nil {
					return 0, 0, err
L
Luke Hoban 已提交
425 426
				}
			}
427 428
			dbp.os.hProcess = debugInfo.Process
			_, err = dbp.addThread(debugInfo.Thread, int(debugEvent.ThreadId), false)
L
Luke Hoban 已提交
429 430 431 432
			if err != nil {
				return 0, 0, err
			}
			break
433 434 435
		case _CREATE_THREAD_DEBUG_EVENT:
			debugInfo := (*_CREATE_THREAD_DEBUG_INFO)(unionPtr)
			_, err = dbp.addThread(debugInfo.Thread, int(debugEvent.ThreadId), false)
L
Luke Hoban 已提交
436 437 438 439
			if err != nil {
				return 0, 0, err
			}
			break
440 441
		case _EXIT_THREAD_DEBUG_EVENT:
			delete(dbp.Threads, int(debugEvent.ThreadId))
L
Luke Hoban 已提交
442
			break
443
		case _OUTPUT_DEBUG_STRING_EVENT:
L
Luke Hoban 已提交
444 445
			//TODO: Handle debug output strings
			break
446 447 448 449 450 451 452
		case _LOAD_DLL_DEBUG_EVENT:
			debugInfo := (*_LOAD_DLL_DEBUG_INFO)(unionPtr)
			hFile := debugInfo.File
			if hFile != 0 && hFile != syscall.InvalidHandle {
				err = syscall.CloseHandle(hFile)
				if err != nil {
					return 0, 0, err
L
Luke Hoban 已提交
453 454 455
				}
			}
			break
456
		case _UNLOAD_DLL_DEBUG_EVENT:
L
Luke Hoban 已提交
457
			break
458
		case _RIP_EVENT:
L
Luke Hoban 已提交
459
			break
460 461
		case _EXCEPTION_DEBUG_EVENT:
			tid := int(debugEvent.ThreadId)
L
Luke Hoban 已提交
462 463
			dbp.os.breakThread = tid
			return tid, 0, nil
464 465 466
		case _EXIT_PROCESS_DEBUG_EVENT:
			debugInfo := (*_EXIT_PROCESS_DEBUG_INFO)(unionPtr)
			exitCode = int(debugInfo.ExitCode)
467
			shouldExit = true
L
Luke Hoban 已提交
468
		default:
469
			return 0, 0, fmt.Errorf("unknown debug event code: %d", debugEvent.DebugEventCode)
L
Luke Hoban 已提交
470 471 472
		}

		// .. and then continue unless we received an event that indicated we should break into debugger.
473 474 475
		err = _ContinueDebugEvent(debugEvent.ProcessId, debugEvent.ThreadId, _DBG_CONTINUE)
		if err != nil {
			return 0, 0, err
L
Luke Hoban 已提交
476
		}
477 478 479 480

		if shouldExit {
			return 0, exitCode, nil
		}
L
Luke Hoban 已提交
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
	}
}

func (dbp *Process) trapWait(pid int) (*Thread, error) {
	var err error
	var tid, exitCode int
	dbp.execPtraceFunc(func() {
		tid, exitCode, err = dbp.waitForDebugEvent()
	})
	if err != nil {
		return nil, err
	}
	if tid == 0 {
		dbp.postExit()
		return nil, ProcessExitedError{Pid: dbp.Pid, Status: exitCode}
	}
	th := dbp.Threads[tid]
	return th, nil
}

func (dbp *Process) loadProcessInformation(wg *sync.WaitGroup) {
	wg.Done()
}

func (dbp *Process) wait(pid, options int) (int, *sys.WaitStatus, error) {
	return 0, nil, fmt.Errorf("not implemented: wait")
}

func (dbp *Process) setCurrentBreakpoints(trapthread *Thread) error {
	// TODO: In theory, we should also be setting the breakpoints on other
	// threads that happen to have hit this BP. But doing so leads to periodic
	// failures in the TestBreakpointsCounts test with hit counts being too high,
D
Derek Parker 已提交
513
	// which can be traced back to occurrences of multiple threads hitting a BP
L
Luke Hoban 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
	// at the same time.

	// My guess is that Windows will correctly trigger multiple DEBUG_EVENT's
	// in this case, one for each thread, so we should only handle the BP hit
	// on the thread that the debugger was evented on.

	return trapthread.SetCurrentBreakpoint()
}

func (dbp *Process) exitGuard(err error) error {
	return err
}

func (dbp *Process) resume() error {
	// Only resume the thread that broke into the debugger
	thread := dbp.Threads[dbp.os.breakThread]
	// This relies on the same assumptions as dbp.setCurrentBreakpoints
	if thread.CurrentBreakpoint != nil {
532
		if err := thread.StepInstruction(); err != nil {
L
Luke Hoban 已提交
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
			return err
		}
		thread.CurrentBreakpoint = nil
	}
	// In case we are now on a different thread, make sure we resume
	// the thread that is broken.
	thread = dbp.Threads[dbp.os.breakThread]
	if err := thread.resume(); err != nil {
		return err
	}
	return nil
}

func killProcess(pid int) error {
	fmt.Println("killProcess")
	return fmt.Errorf("not implemented: killProcess")
}