proc_linux.go 7.3 KB
Newer Older
D
Derek Parker 已提交
1
package proc
D
Derek Parker 已提交
2 3 4 5 6 7

import (
	"debug/elf"
	"debug/gosym"
	"fmt"
	"os"
8
	"os/exec"
D
Derek Parker 已提交
9 10
	"path/filepath"
	"strconv"
D
Derek Parker 已提交
11 12 13 14 15 16
	"sync"
	"syscall"

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

	"github.com/derekparker/delve/dwarf/frame"
D
Derek Parker 已提交
17
	"github.com/derekparker/delve/dwarf/line"
D
Derek Parker 已提交
18 19 20 21 22 23 24 25 26 27 28
)

const (
	STATUS_SLEEPING   = 'S'
	STATUS_RUNNING    = 'R'
	STATUS_TRACE_STOP = 't'
)

// Not actually needed for Linux.
type OSProcessDetails interface{}

29 30 31 32
// 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.
func Launch(cmd []string) (*DebuggedProcess, error) {
33 34 35 36 37 38 39 40 41 42 43 44 45 46
	var (
		proc *exec.Cmd
		err  error
	)
	dbp := New(0)
	dbp.execPtraceFunc(func() {
		proc = exec.Command(cmd[0])
		proc.Args = cmd
		proc.Stdout = os.Stdout
		proc.Stderr = os.Stderr
		proc.SysProcAttr = &syscall.SysProcAttr{Ptrace: true}
		err = proc.Start()
	})
	if err != nil {
47 48
		return nil, err
	}
49 50
	dbp.Pid = proc.Process.Pid
	_, _, err = wait(proc.Process.Pid, 0)
51 52 53 54 55 56
	if err != nil {
		return nil, fmt.Errorf("waiting for target execve failed: %s", err)
	}
	return initializeDebugProcess(dbp, proc.Path, false)
}

D
Derek Parker 已提交
57 58
func (dbp *DebuggedProcess) requestManualStop() (err error) {
	return sys.Kill(dbp.Pid, sys.SIGSTOP)
D
Derek Parker 已提交
59 60 61 62
}

// Attach to a newly created thread, and store that thread in our list of
// known threads.
D
Derek Parker 已提交
63
func (dbp *DebuggedProcess) addThread(tid int, attach bool) (*Thread, error) {
D
Derek Parker 已提交
64 65 66 67
	if thread, ok := dbp.Threads[tid]; ok {
		return thread, nil
	}

68
	var err error
D
Derek Parker 已提交
69
	if attach {
70
		dbp.execPtraceFunc(func() { err = sys.PtraceAttach(tid) })
D
Derek Parker 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
		if err != nil && err != sys.EPERM {
			// 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)
		}
	}

89
	dbp.execPtraceFunc(func() { err = syscall.PtraceSetOptions(tid, syscall.PTRACE_O_TRACECLONE) })
D
Derek Parker 已提交
90 91 92 93 94 95
	if err == syscall.ESRCH {
		_, _, err = wait(tid, 0)
		if err != nil {
			return nil, fmt.Errorf("error while waiting after adding thread: %d %s", tid, err)
		}

96
		dbp.execPtraceFunc(func() { err = syscall.PtraceSetOptions(tid, syscall.PTRACE_O_TRACECLONE) })
D
Derek Parker 已提交
97 98 99 100 101
		if err != nil {
			return nil, fmt.Errorf("could not set options for new traced thread %d %s", tid, err)
		}
	}

D
Derek Parker 已提交
102
	dbp.Threads[tid] = &Thread{
103 104 105
		Id:  tid,
		dbp: dbp,
		os:  new(OSSpecificDetails),
D
Derek Parker 已提交
106 107
	}

D
Derek Parker 已提交
108 109 110 111
	if dbp.CurrentThread == nil {
		dbp.CurrentThread = dbp.Threads[tid]
	}

D
Derek Parker 已提交
112 113 114
	return dbp.Threads[tid], nil
}

D
Derek Parker 已提交
115
func (dbp *DebuggedProcess) updateThreadList() error {
D
Derek Parker 已提交
116
	var attach bool
D
Derek Parker 已提交
117 118 119 120 121 122
	tids, _ := filepath.Glob(fmt.Sprintf("/proc/%d/task/*", dbp.Pid))
	for _, tidpath := range tids {
		tidstr := filepath.Base(tidpath)
		tid, err := strconv.Atoi(tidstr)
		if err != nil {
			return err
D
Derek Parker 已提交
123
		}
D
Derek Parker 已提交
124 125 126 127
		if tid != dbp.Pid {
			attach = true
		}
		if _, err := dbp.addThread(tid, attach); err != nil {
D
Derek Parker 已提交
128 129 130
			return err
		}
	}
D
Derek Parker 已提交
131
	return nil
D
Derek Parker 已提交
132 133
}

134 135 136 137 138
func (dbp *DebuggedProcess) findExecutable(path string) (*elf.File, error) {
	if path == "" {
		path = fmt.Sprintf("/proc/%d/exe", dbp.Pid)
	}
	f, err := os.OpenFile(path, 0, os.ModePerm)
D
Derek Parker 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151
	if err != nil {
		return nil, err
	}

	elffile, err := elf.NewFile(f)
	if err != nil {
		return nil, err
	}

	data, err := elffile.DWARF()
	if err != nil {
		return nil, err
	}
152
	dbp.dwarf = data
D
Derek Parker 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165

	return elffile, nil
}

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

	if sec := exe.Section(".debug_frame"); sec != nil {
		debugFrame, err := exe.Section(".debug_frame").Data()
		if err != nil {
			fmt.Println("could not get .debug_frame section", err)
			os.Exit(1)
		}
166
		dbp.frameEntries = frame.Parse(debugFrame)
D
Derek Parker 已提交
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
	} else {
		fmt.Println("could not find .debug_frame section in binary")
		os.Exit(1)
	}
}

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

	var (
		symdat  []byte
		pclndat []byte
		err     error
	)

	if sec := exe.Section(".gosymtab"); sec != nil {
		symdat, err = sec.Data()
		if err != nil {
			fmt.Println("could not get .gosymtab section", err)
			os.Exit(1)
		}
	}

	if sec := exe.Section(".gopclntab"); sec != nil {
		pclndat, err = sec.Data()
		if err != nil {
			fmt.Println("could not get .gopclntab section", err)
			os.Exit(1)
		}
	}

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

205
	dbp.goSymTable = tab
D
Derek Parker 已提交
206 207
}

D
Derek Parker 已提交
208 209 210 211 212 213 214 215 216
func (dbp *DebuggedProcess) parseDebugLineInfo(exe *elf.File, wg *sync.WaitGroup) {
	defer wg.Done()

	if sec := exe.Section(".debug_line"); sec != nil {
		debugLine, err := exe.Section(".debug_line").Data()
		if err != nil {
			fmt.Println("could not get .debug_line section", err)
			os.Exit(1)
		}
217
		dbp.lineInfo = line.Parse(debugLine)
D
Derek Parker 已提交
218 219 220 221 222 223
	} else {
		fmt.Println("could not find .debug_line section in binary")
		os.Exit(1)
	}
}

D
Derek Parker 已提交
224
func (dbp *DebuggedProcess) trapWait(pid int) (*Thread, error) {
D
Derek Parker 已提交
225 226 227
	for {
		wpid, status, err := wait(pid, 0)
		if err != nil {
228
			return nil, fmt.Errorf("wait err %s %d", err, pid)
D
Derek Parker 已提交
229 230 231 232
		}
		if wpid == 0 {
			continue
		}
233 234
		th, ok := dbp.Threads[wpid]
		if ok {
D
Derek Parker 已提交
235 236
			th.Status = status
		}
237 238 239 240 241 242
		if status.Exited() {
			if wpid == dbp.Pid {
				dbp.exited = true
				return nil, ProcessExitedError{Pid: wpid, Status: status.ExitStatus()}
			}
			continue
D
Derek Parker 已提交
243 244 245 246
		}
		if status.StopSignal() == sys.SIGTRAP && status.TrapCause() == sys.PTRACE_EVENT_CLONE {
			// A traced thread has cloned a new thread, grab the pid and
			// add it to our list of traced threads.
247 248
			var cloned uint
			dbp.execPtraceFunc(func() { cloned, err = sys.PtraceGetEventMsg(wpid) })
D
Derek Parker 已提交
249
			if err != nil {
250
				return nil, fmt.Errorf("could not get event message: %s", err)
D
Derek Parker 已提交
251
			}
252
			th, err = dbp.addThread(int(cloned), false)
D
Derek Parker 已提交
253
			if err != nil {
254
				return nil, err
D
Derek Parker 已提交
255
			}
256 257 258
			// Set all hardware breakpoints on the new thread.
			for _, bp := range dbp.Breakpoints {
				if !bp.hardware {
259 260
					continue
				}
261
				if err = dbp.setHardwareBreakpoint(bp.reg, th.Id, bp.Addr); err != nil {
262 263 264
					return nil, err
				}
			}
265
			if err = th.Continue(); err != nil {
266
				return nil, fmt.Errorf("could not continue new thread %d %s", cloned, err)
D
Derek Parker 已提交
267
			}
268 269
			if err = dbp.Threads[int(wpid)].Continue(); err != nil {
				return nil, fmt.Errorf("could not continue existing thread %d %s", cloned, err)
D
Derek Parker 已提交
270
			}
D
Derek Parker 已提交
271 272 273
			continue
		}
		if status.StopSignal() == sys.SIGTRAP {
D
Derek Parker 已提交
274
			return dbp.handleBreakpointOnThread(wpid)
D
Derek Parker 已提交
275
		}
276 277 278
		if status.StopSignal() == sys.SIGTRAP && dbp.halt {
			return th, nil
		}
D
Derek Parker 已提交
279
		if status.StopSignal() == sys.SIGSTOP && dbp.halt {
280
			return nil, ManualStopError{}
D
Derek Parker 已提交
281
		}
282
		if th != nil {
283
			// TODO(dp) alert user about unexpected signals here.
284 285 286 287
			if err := th.Continue(); err != nil {
				return nil, err
			}
		}
D
Derek Parker 已提交
288 289 290
	}
}

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
func stopped(pid int) bool {
	f, err := os.Open(fmt.Sprintf("/proc/%d/stat", pid))
	if err != nil {
		return false
	}
	defer f.Close()

	var (
		p     int
		comm  string
		state rune
	)
	fmt.Fscanf(f, "%d %s %c", &p, &comm, &state)
	if state == STATUS_TRACE_STOP {
		return true
	}
	return false
}

D
Derek Parker 已提交
310 311 312 313 314
func wait(pid, options int) (int, *sys.WaitStatus, error) {
	var status sys.WaitStatus
	wpid, err := sys.Wait4(pid, &status, sys.WALL|options, nil)
	return wpid, &status, err
}