threads.go 8.6 KB
Newer Older
D
Derek Parker 已提交
1 2 3
package proctl

import (
4
	"debug/gosym"
D
Derek Parker 已提交
5
	"fmt"
6
	"path/filepath"
D
Derek Parker 已提交
7

8
	"github.com/derekparker/delve/dwarf/frame"
9
	"github.com/derekparker/delve/source"
P
Paul Sbarra 已提交
10
	sys "golang.org/x/sys/unix"
D
Derek Parker 已提交
11 12
)

D
Derek Parker 已提交
13 14 15 16 17
// ThreadContext represents a single thread in the traced process
// Id represents the thread id, Process holds a reference to the
// DebuggedProcess struct that contains info on the process as
// a whole, and Status represents the last result of a `wait` call
// on this thread.
D
Derek Parker 已提交
18
type ThreadContext struct {
19 20 21
	Id                int
	Status            *sys.WaitStatus
	CurrentBreakpoint *BreakPoint
22
	dbp               *DebuggedProcess
23
	singleStepping    bool
24 25
	running           bool
	os                *OSSpecificDetails
26 27
}

28 29 30 31 32 33 34
type Location struct {
	PC   uint64
	File string
	Line int
	Fn   *gosym.Func
}

D
Derek Parker 已提交
35 36 37 38
// Continue the execution of this thread. This method takes
// software breakpoints into consideration and ensures that
// we step over any breakpoints. It will restore the instruction,
// step, and then restore the breakpoint and continue.
D
Derek Parker 已提交
39
func (thread *ThreadContext) Continue() error {
D
Derek Parker 已提交
40
	pc, err := thread.PC()
D
Derek Parker 已提交
41
	if err != nil {
42
		return err
D
Derek Parker 已提交
43 44
	}

45 46
	// Check whether we are stopped at a breakpoint, and
	// if so, single step over it before continuing.
47
	if _, ok := thread.dbp.BreakPoints[pc]; ok {
D
Derek Parker 已提交
48 49
		if err := thread.Step(); err != nil {
			return err
D
Derek Parker 已提交
50 51
		}
	}
D
Cleanup  
Derek Parker 已提交
52
	return thread.resume()
D
Derek Parker 已提交
53 54 55 56 57
}

// Single steps this thread a single instruction, ensuring that
// we correctly handle the likely case that we are at a breakpoint.
func (thread *ThreadContext) Step() (err error) {
58 59
	thread.singleStepping = true
	defer func() { thread.singleStepping = false }()
D
Derek Parker 已提交
60
	pc, err := thread.PC()
D
Derek Parker 已提交
61 62 63 64
	if err != nil {
		return err
	}

65
	bp, ok := thread.dbp.BreakPoints[pc]
D
Derek Parker 已提交
66 67
	if ok {
		// Clear the breakpoint so that we can continue execution.
68
		_, err = thread.dbp.Clear(bp.Addr)
D
Derek Parker 已提交
69 70 71 72 73 74
		if err != nil {
			return err
		}

		// Restore breakpoint now that we have passed it.
		defer func() {
D
Derek Parker 已提交
75
			var nbp *BreakPoint
76
			nbp, err = thread.dbp.Break(bp.Addr)
D
Derek Parker 已提交
77
			nbp.Temp = bp.Temp
D
Derek Parker 已提交
78 79 80
		}()
	}

D
Derek Parker 已提交
81
	err = thread.singleStep()
D
Derek Parker 已提交
82 83 84
	if err != nil {
		return fmt.Errorf("step failed: %s", err.Error())
	}
D
Derek Parker 已提交
85
	return nil
D
Derek Parker 已提交
86 87
}

88 89
// Set breakpoint using this thread.
func (thread *ThreadContext) Break(addr uint64) (*BreakPoint, error) {
90
	return thread.dbp.setBreakpoint(thread.Id, addr, false)
91 92
}

93 94
// Set breakpoint using this thread.
func (thread *ThreadContext) TempBreak(addr uint64) (*BreakPoint, error) {
95
	return thread.dbp.setBreakpoint(thread.Id, addr, true)
96 97
}

98 99
// Clear breakpoint using this thread.
func (thread *ThreadContext) Clear(addr uint64) (*BreakPoint, error) {
100 101 102 103 104 105 106 107 108 109
	return thread.dbp.clearBreakpoint(thread.Id, addr)
}

func (thread *ThreadContext) Location() (*Location, error) {
	pc, err := thread.PC()
	if err != nil {
		return nil, err
	}
	f, l, fn := thread.dbp.PCToLine(pc)
	return &Location{PC: pc, File: f, Line: l, Fn: fn}, nil
D
Derek Parker 已提交
110
}
D
Derek Parker 已提交
111

D
Derek Parker 已提交
112 113 114 115 116 117 118 119
// Step to next source line.
//
// Next will step over functions, and will follow through to the
// return address of a function.
//
// This functionality is implemented by finding all possible next lines
// and setting a breakpoint at them. Once we've set a breakpoint at each
// potential line, we continue the thread.
120
func (thread *ThreadContext) SetNextBreakpoints() (err error) {
D
Derek Parker 已提交
121
	curpc, err := thread.PC()
D
Derek Parker 已提交
122 123 124 125
	if err != nil {
		return err
	}

D
Derek Parker 已提交
126 127
	// Grab info on our current stack frame. Used to determine
	// whether we may be stepping outside of the current function.
128
	fde, err := thread.dbp.frameEntries.FDEForPC(curpc)
D
Derek Parker 已提交
129 130
	if err != nil {
		return err
D
Derek Parker 已提交
131 132
	}

D
Derek Parker 已提交
133
	// Get current file/line.
134 135 136 137 138 139
	loc, err := thread.Location()
	if err != nil {
		return err
	}
	if filepath.Ext(loc.File) == ".go" {
		if err = thread.next(curpc, fde, loc.File, loc.Line); err != nil {
140 141 142
			return err
		}
	} else {
143
		if err = thread.cnext(curpc, fde); err != nil {
144
			return err
D
Derek Parker 已提交
145 146
		}
	}
147
	return nil
D
Derek Parker 已提交
148
}
D
Derek Parker 已提交
149

150 151 152 153 154 155 156 157 158 159 160 161
// Go routine is exiting.
type GoroutineExitingError struct {
	goid int
}

func (ge GoroutineExitingError) Error() string {
	return fmt.Sprintf("goroutine %d is exiting", ge.goid)
}

// This version of next uses the AST from the current source file to figure out all of the potential source lines
// we could end up at.
func (thread *ThreadContext) next(curpc uint64, fde *frame.FrameDescriptionEntry, file string, line int) error {
162
	lines, err := thread.dbp.ast.NextLines(file, line)
D
Derek Parker 已提交
163
	if err != nil {
164 165 166
		if _, ok := err.(source.NoNodeError); !ok {
			return err
		}
D
Derek Parker 已提交
167
	}
D
Derek Parker 已提交
168

169
	ret, err := thread.ReturnAddress()
D
Derek Parker 已提交
170
	if err != nil {
171
		return err
D
Derek Parker 已提交
172 173
	}

174 175
	pcs := make([]uint64, 0, len(lines))
	for i := range lines {
176
		pcs = append(pcs, thread.dbp.lineInfo.AllPCsForFileLine(file, lines[i])...)
177
	}
D
Derek Parker 已提交
178

179 180 181 182 183
	var covered bool
	for i := range pcs {
		if fde.Cover(pcs[i]) {
			covered = true
			break
D
Derek Parker 已提交
184
		}
185
	}
186 187

	if !covered {
188
		fn := thread.dbp.goSymTable.PCToFunc(ret)
189
		if fn != nil && fn.Name == "runtime.goexit" {
190
			g, err := thread.getG()
191 192 193 194
			if err != nil {
				return err
			}
			return GoroutineExitingError{goid: g.Id}
D
Derek Parker 已提交
195
		}
196
	}
197 198 199 200 201 202 203 204
	pcs = append(pcs, ret)
	return thread.setNextTempBreakpoints(curpc, pcs)
}

// Set a breakpoint at every reachable location, as well as the return address. Without
// the benefit of an AST we can't be sure we're not at a branching statement and thus
// cannot accurately predict where we may end up.
func (thread *ThreadContext) cnext(curpc uint64, fde *frame.FrameDescriptionEntry) error {
205
	pcs := thread.dbp.lineInfo.AllPCsBetween(fde.Begin(), fde.End())
206 207 208 209 210 211 212
	ret, err := thread.ReturnAddress()
	if err != nil {
		return err
	}
	pcs = append(pcs, ret)
	return thread.setNextTempBreakpoints(curpc, pcs)
}
213

214 215 216
func (thread *ThreadContext) setNextTempBreakpoints(curpc uint64, pcs []uint64) error {
	for i := range pcs {
		if pcs[i] == curpc || pcs[i] == curpc-1 {
217 218
			continue
		}
219
		if _, err := thread.dbp.TempBreak(pcs[i]); err != nil {
D
Derek Parker 已提交
220
			if _, ok := err.(BreakPointExistsError); !ok {
221 222 223
				return err
			}
		}
D
Derek Parker 已提交
224 225 226 227
	}
	return nil
}

D
Derek Parker 已提交
228
// Sets the PC for this thread.
229 230 231 232 233 234 235 236
func (thread *ThreadContext) SetPC(pc uint64) error {
	regs, err := thread.Registers()
	if err != nil {
		return err
	}
	return regs.SetPC(thread, pc)
}

237 238 239
// Returns information on the G (goroutine) that is executing on this thread.
//
// The G structure for a thread is stored in thread local memory. Execute instructions
D
Derek Parker 已提交
240
// that move the *G structure into a CPU register, and then grab
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
// the new registers and parse the G structure.
//
// We cannot simply use the allg linked list in order to find the M that represents
// the given OS thread and follow its G pointer because on Darwin mach ports are not
// universal, so our port for this thread would not map to the `id` attribute of the M
// structure. Also, when linked against libc, Go prefers the libc version of clone as
// opposed to the runtime version. This has the consequence of not setting M.id for
// any thread, regardless of OS.
//
// In order to get around all this craziness, we write the instructions to retrieve the G
// structure running on this thread (which is stored in thread local memory) into the
// current instruction stream. The instructions are obviously arch/os dependant, as they
// vary on how thread local storage is implemented, which MMU register is used and
// what the offset into thread local storage is.
func (thread *ThreadContext) getG() (g *G, err error) {
	var pcInt uint64
	pcInt, err = thread.PC()
	if err != nil {
		return
	}
	pc := uintptr(pcInt)
	// Read original instructions.
	originalInstructions := make([]byte, len(thread.dbp.arch.CurgInstructions()))
	if _, err = readMemory(thread, pc, originalInstructions); err != nil {
		return
	}
	// Write new instructions.
	if _, err = writeMemory(thread, pc, thread.dbp.arch.CurgInstructions()); err != nil {
		return
	}
	// We're going to be intentionally modifying the registers
	// once we execute the code we inject into the instruction stream,
	// so save them off here so we can restore them later.
	if _, err = thread.saveRegisters(); err != nil {
		return
	}
	// Ensure original instructions and PC are both restored.
	defer func() {
		// Do not shadow previous error, if there was one.
		originalErr := err
		// Restore the original instructions and register contents.
		if _, err = writeMemory(thread, pc, originalInstructions); err != nil {
			return
D
Derek Parker 已提交
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
		if err = thread.restoreRegisters(); err != nil {
			return
		}
		err = originalErr
		return
	}()
	// Execute new instructions.
	if err = thread.resume(); err != nil {
		return
	}
	// Set the halt flag so that trapWait will ignore the fact that
	// we hit a breakpoint that isn't captured in our list of
	// known breakpoints.
	thread.dbp.halt = true
	defer func(dbp *DebuggedProcess) { dbp.halt = false }(thread.dbp)
	if _, err = thread.dbp.trapWait(-1); err != nil {
		return
	}
	// Grab *G from RCX.
	regs, err := thread.Registers()
	if err != nil {
		return nil, err
	}
	g, err = parseG(thread, regs.CX(), false)
	return
D
Derek Parker 已提交
310
}