Debian Codegraph @

ptrace/debugger/debugger.py

raw
1 from logging import info, warning, error
2 from ptrace import PtraceError
3 from os import waitpid, WNOHANG
4 from signal import SIGTRAP, SIGSTOP
5 from errno import ECHILD
6 from ptrace.debugger import PtraceProcess, ProcessSignal
7 from ptrace.binding import HAS_PTRACE_EVENTS
8 from time import sleep
9 if HAS_PTRACE_EVENTS:
10 from ptrace.binding.func import (
11 PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK,
12 PTRACE_O_TRACEEXEC, PTRACE_O_TRACESYSGOOD,
13 PTRACE_O_TRACECLONE, THREAD_TRACE_FLAGS)
14
15
16 class DebuggerError(PtraceError):
17 pass
18
19
20 class PtraceDebugger(object):
21 """
22 Debugger managing one or multiple processes at the same time.
23
24 Methods
25 =======
26
27 * Process list:
28 - addProcess(): add a new process
29 - deleteProcess(): remove a process from the debugger
30
31 * Wait for an event:
32 - waitProcessEvent(): wait for a process event
33 - waitSignals(): wait for a signal
34 - waitSyscall(): wait for the next syscall event
35
36 * Options:
37 - traceFork(): enable fork() tracing
38 - traceExec(): enable exec() tracing
39 - traceClone(): enable clone() tracing
40 - enableSysgood(): enable sysgood option
41
42 * Other:
43 - quit(): quit the debugger, terminate all processes
44
45 Operations
46 ==========
47
48 - iterate on all processes: "for process in debugger: ..."
49 - get a process by its identifier: "process = debugger[pid]"
50 - get the number of processes: len(debugger)
51
52 Attributes
53 ==========
54
55 - dict: processes dictionary (pid -> PtraceProcess)
56 - list: processes list
57 - options: ptrace options
58 - trace_fork (bool): fork() tracing is enabled?
59 - trace_exec (bool): exec() tracing is enabled?
60 - trace_clone (bool): clone() tracing is enabled?
61 - use_sysgood (bool): sysgood option is enabled?
62 """
63
64 def __init__(self):
65 self.dict = {} # pid -> PtraceProcess object
66 self.list = []
67 self.options = 0
68 self.trace_fork = False
69 self.trace_exec = False
70 self.trace_clone = False
71 self.use_sysgood = False
72 self.enableSysgood()
73
74 def addProcess(self, pid, is_attached, parent=None, is_thread=False):
75 """
76 Add a new process using its identifier. Use is_attached=False to
77 attach an existing (running) process, and is_attached=True to trace
78 a new (stopped) process.
79 """
80 if pid in self.dict:
81 raise KeyError("The process %s is already registered!" % pid)
82 process = PtraceProcess(self, pid, is_attached,
83 parent=parent, is_thread=is_thread)
84 info("Attach %s to debugger" % process)
85 self.dict[pid] = process
86 self.list.append(process)
87 try:
88 process.waitSignals(SIGTRAP, SIGSTOP)
89 except KeyboardInterrupt:
90 error(
91 "User interrupt! Force the process %s attach "
92 "(don't wait for signals)."
93 % pid)
94 except ProcessSignal as event:
95 event.display()
96 except: # noqa: E722
97 process.is_attached = False
98 process.detach()
99 raise
100 if HAS_PTRACE_EVENTS and self.options:
101 process.setoptions(self.options)
102 return process
103
104 def quit(self):
105 """
106 Quit the debugger: terminate all processes in reverse order.
107 """
108 info("Quit debugger")
109 # Terminate processes in reverse order
110 # to kill children before parents
111 processes = list(self.list)
112 for process in reversed(processes):
113 process.terminate()
114 process.detach()
115
116 def _waitpid(self, wanted_pid, blocking=True):
117 """
118 Wait for a process event from a specific process (if wanted_pid is
119 set) or any process (wanted_pid=None). The call is blocking is
120 blocking option is True. Return the tuple (pid, status).
121
122 See os.waitpid() documentation for explanations about the result.
123 """
124 flags = 0
125 if not blocking:
126 flags |= WNOHANG
127 if wanted_pid:
128 if wanted_pid not in self.dict:
129 raise DebuggerError("Unknown PID: %r" %
130 wanted_pid, pid=wanted_pid)
131
132 process = self.dict[wanted_pid]
133 if process.is_thread:
134 flags |= THREAD_TRACE_FLAGS
135
136 pid, status = waitpid(wanted_pid, flags)
137 else:
138 pid, status = waitpid(-1, flags)
139 if (blocking or pid) and wanted_pid and (pid != wanted_pid):
140 raise DebuggerError("Unwanted PID: %r (instead of %s)"
141 % (pid, wanted_pid), pid=pid)
142 return pid, status
143
144 def _wait_event_pid(self, wanted_pid, blocking=True):
145 """
146 Wait for a process event from the specified process identifier. If
147 blocking=False, return None if there is no new event, otherwise return
148 an object based on ProcessEvent.
149 """
150 process = None
151 while not process:
152 try:
153 pid, status = self._waitpid(wanted_pid, blocking)
154 except OSError as err:
155 if err.errno == ECHILD:
156 process = self.dict[wanted_pid]
157 return process.processTerminated()
158 else:
159 raise err
160 if not blocking and not pid:
161 return None
162 try:
163 process = self.dict[pid]
164 except KeyError:
165 warning("waitpid() warning: Unknown PID %r" % pid)
166 return process.processStatus(status)
167
168 def _wait_event(self, wanted_pid, blocking=True):
169 if wanted_pid is not None:
170 return self._wait_event_pid(wanted_pid, blocking)
171
172 pause = 0.001
173 while True:
174 pids = tuple(self.dict)
175 if len(pids) > 1:
176 for pid in pids:
177 process = self._wait_event_pid(pid, False)
178 if process is not None:
179 return process
180 if not blocking:
181 return None
182 pause = min(pause * 2, 0.5)
183 sleep(pause)
184 else:
185 return self._wait_event_pid(pids[0], blocking)
186
187 def waitProcessEvent(self, pid=None, blocking=True):
188 """
189 Wait for a process event from a specific process (if pid option is
190 set) or any process (default). If blocking=False, return None if there
191 is no new event, otherwise return an object based on ProcessEvent.
192 """
193 return self._wait_event(pid, blocking)
194
195 def waitSignals(self, *signals, **kw):
196 """
197 Wait for any signal or some specific signals (if specified) from a
198 specific process (if pid keyword is set) or any process (default).
199 Return a ProcessSignal object or raise an unexpected ProcessEvent.
200 """
201 pid = kw.get('pid', None)
202 while True:
203 event = self._wait_event(pid)
204 if event.__class__ != ProcessSignal:
205 raise event
206 signum = event.signum
207 if signum in signals or not signals:
208 return event
209 raise event
210
211 def waitSyscall(self, process=None):
212 """
213 Wait for the next syscall event (enter or exit) for a specific process
214 (if specified) or any process (default). Return a ProcessSignal object
215 or raise an unexpected ProcessEvent.
216 """
217 signum = SIGTRAP
218 if self.use_sysgood:
219 signum |= 0x80
220 if process:
221 return self.waitSignals(signum, pid=process.pid)
222 else:
223 return self.waitSignals(signum)
224
225 def deleteProcess(self, process=None, pid=None):
226 """
227 Delete a process from the process list.
228 """
229 if not process:
230 try:
231 process = self.dict[pid]
232 except KeyError:
233 return
234 try:
235 del self.dict[process.pid]
236 except KeyError:
237 pass
238 try:
239 self.list.remove(process)
240 except ValueError:
241 pass
242
243 def traceFork(self):
244 """
245 Enable fork() tracing. Do nothing if it's not supported.
246 """
247 if not HAS_PTRACE_EVENTS:
248 raise DebuggerError(
249 "Tracing fork events is not supported on this architecture or operating system")
250 self.options |= PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK
251 self.trace_fork = True
252 info("Debugger trace forks (options=%s)" % self.options)
253
254 def traceExec(self):
255 """
256 Enable exec() tracing. Do nothing if it's not supported.
257 """
258 if not HAS_PTRACE_EVENTS:
259 # no effect on OS without ptrace events
260 return
261 self.trace_exec = True
262 self.options |= PTRACE_O_TRACEEXEC
263
264 def traceClone(self):
265 """
266 Enable clone() tracing. Do nothing if it's not supported.
267 """
268 if not HAS_PTRACE_EVENTS:
269 # no effect on OS without ptrace events
270 return
271 self.trace_clone = True
272 self.options |= PTRACE_O_TRACECLONE
273
274 def enableSysgood(self):
275 """
276 Enable sysgood option: ask the kernel to set bit #7 of the signal
277 number if the signal comes from the kernel space. If the signal comes
278 from the user space, the bit is unset.
279 """
280 if not HAS_PTRACE_EVENTS:
281 # no effect on OS without ptrace events
282 return
283 self.use_sysgood = True
284 self.options |= PTRACE_O_TRACESYSGOOD
285
286 def __getitem__(self, pid):
287 return self.dict[pid]
288
289 def __iter__(self):
290 return iter(self.list)
291
292 def __len__(self):
293 return len(self.list)