| 1 |
from ptrace.binding import ( |
| 2 |
HAS_PTRACE_SINGLESTEP, HAS_PTRACE_EVENTS, |
| 3 |
HAS_PTRACE_SIGINFO, HAS_PTRACE_IO, HAS_PTRACE_GETREGS, |
| 4 |
HAS_PTRACE_GETREGSET, |
| 5 |
ptrace_attach, ptrace_detach, |
| 6 |
ptrace_cont, ptrace_syscall, |
| 7 |
ptrace_setregs, |
| 8 |
ptrace_peektext, ptrace_poketext, |
| 9 |
REGISTER_NAMES) |
| 10 |
from ptrace.os_tools import HAS_PROC, RUNNING_BSD, RUNNING_PYTHON3 |
| 11 |
from ptrace.tools import dumpRegs |
| 12 |
from ptrace.cpu_info import CPU_WORD_SIZE |
| 13 |
from ptrace.ctypes_tools import bytes2word, word2bytes, bytes2type, bytes2array |
| 14 |
from signal import SIGTRAP, SIGSTOP, SIGKILL |
| 15 |
from ptrace.ctypes_tools import formatAddress, formatWordHex |
| 16 |
from ctypes import sizeof, c_char_p |
| 17 |
from logging import info, warning, error |
| 18 |
from ptrace.error import PtraceError |
| 19 |
from errno import ESRCH, EACCES |
| 20 |
from ptrace.debugger import (Breakpoint, |
| 21 |
ProcessExit, ProcessSignal, NewProcessEvent, ProcessExecution) |
| 22 |
from os import (kill, |
| 23 |
WIFSTOPPED, WSTOPSIG, |
| 24 |
WIFSIGNALED, WTERMSIG, |
| 25 |
WIFEXITED, WEXITSTATUS) |
| 26 |
from ptrace.disasm import HAS_DISASSEMBLER |
| 27 |
from ptrace.debugger.backtrace import getBacktrace |
| 28 |
from ptrace.debugger.process_error import ProcessError |
| 29 |
from ptrace.debugger.memory_mapping import readProcessMappings |
| 30 |
from ptrace.binding.cpu import CPU_INSTR_POINTER, CPU_STACK_POINTER, CPU_FRAME_POINTER, CPU_SUB_REGISTERS |
| 31 |
from ptrace.debugger.syscall_state import SyscallState |
| 32 |
|
| 33 |
if HAS_PTRACE_SINGLESTEP: |
| 34 |
from ptrace.binding import ptrace_singlestep |
| 35 |
if HAS_PTRACE_SIGINFO: |
| 36 |
from ptrace.binding import ptrace_getsiginfo |
| 37 |
if HAS_PTRACE_IO: |
| 38 |
from ctypes import create_string_buffer, addressof |
| 39 |
from ptrace.binding import ( |
| 40 |
ptrace_io, ptrace_io_desc, |
| 41 |
PIOD_READ_D, PIOD_WRITE_D) |
| 42 |
if HAS_PTRACE_EVENTS: |
| 43 |
from ptrace.binding import ( |
| 44 |
ptrace_setoptions, ptrace_geteventmsg, WPTRACEEVENT, |
| 45 |
PTRACE_EVENT_FORK, PTRACE_EVENT_VFORK, PTRACE_EVENT_CLONE, |
| 46 |
PTRACE_EVENT_EXEC) |
| 47 |
NEW_PROCESS_EVENT = ( |
| 48 |
PTRACE_EVENT_FORK, PTRACE_EVENT_VFORK, PTRACE_EVENT_CLONE) |
| 49 |
if HAS_PTRACE_GETREGS or HAS_PTRACE_GETREGSET: |
| 50 |
from ptrace.binding import ptrace_getregs |
| 51 |
else: |
| 52 |
from ptrace.binding import ptrace_peekuser, ptrace_registers_t |
| 53 |
if HAS_DISASSEMBLER: |
| 54 |
from ptrace.disasm import disassemble, disassembleOne, MAX_INSTR_SIZE |
| 55 |
if HAS_PROC: |
| 56 |
from ptrace.linux_proc import readProcessStat |
| 57 |
|
| 58 |
MIN_CODE_SIZE = 32 |
| 59 |
MAX_CODE_SIZE = 1024 |
| 60 |
DEFAULT_NB_INSTR = 10 |
| 61 |
DEFAULT_CODE_SIZE = 24 |
| 62 |
|
| 63 |
|
| 64 |
class PtraceProcess(object): |
| 65 |
""" |
| 66 |
Process traced by a PtraceDebugger. |
| 67 |
|
| 68 |
Methods |
| 69 |
======= |
| 70 |
|
| 71 |
* control execution: |
| 72 |
|
| 73 |
- singleStep(): execute one instruction |
| 74 |
- cont(): continue the execution |
| 75 |
- syscall(): break at next syscall |
| 76 |
- setInstrPointer(): change the instruction pointer |
| 77 |
- kill(): send a signal to the process |
| 78 |
- terminate(): kill the process |
| 79 |
|
| 80 |
* wait an event: |
| 81 |
|
| 82 |
- waitEvent(): wait next process event |
| 83 |
- waitSignals(): wait a signal |
| 84 |
|
| 85 |
* get status |
| 86 |
|
| 87 |
- getreg(): get a register |
| 88 |
- getInstrPointer(): get the instruction pointer |
| 89 |
- getStackPointer(): get the stack pointer |
| 90 |
- getFramePointer(): get the stack pointer |
| 91 |
- getregs(): get all registers, e.g. regs=getregs(); print regs.eax |
| 92 |
- disassemble(): assembler code of the next instructions |
| 93 |
- disassembleOne(): assembler code of the next instruction |
| 94 |
- findStack(): get stack memory mapping |
| 95 |
- getsiginfo(): get signal information |
| 96 |
- getBacktrace(): get the current backtrace |
| 97 |
|
| 98 |
* set status |
| 99 |
|
| 100 |
- setreg(): set a register |
| 101 |
- setregs(): set all registers |
| 102 |
|
| 103 |
* memory access: |
| 104 |
|
| 105 |
- readWord(): read a memory word |
| 106 |
- readBytes(): read some bytes |
| 107 |
- readStruct(): read a structure |
| 108 |
- readArray(): read an array |
| 109 |
- readCString(): read a C string |
| 110 |
- readMappings(): get all memory mappings |
| 111 |
- writeWord(): write a memory word |
| 112 |
- writeBytes(): write some bytes |
| 113 |
|
| 114 |
* display status: |
| 115 |
|
| 116 |
- dumpCode(): display the next instructions |
| 117 |
- dumpStack(): display some memory words around the stack pointer |
| 118 |
- dumpMaps(): display memory mappings |
| 119 |
- dumpRegs(): display all registers |
| 120 |
|
| 121 |
* breakpoint: |
| 122 |
|
| 123 |
- createBreakpoint(): set a breakpoint |
| 124 |
- findBreakpoint(): find a breakpoint |
| 125 |
- removeBreakpoint(): remove a breakpoint |
| 126 |
|
| 127 |
* other: |
| 128 |
|
| 129 |
- setoptions(): set ptrace options |
| 130 |
|
| 131 |
See each method to get better documentation. You are responsible |
| 132 |
to manage the process state: some methods may fail or crash your |
| 133 |
processus if they are called when the process is in the wrong |
| 134 |
state. |
| 135 |
|
| 136 |
Attributes |
| 137 |
========== |
| 138 |
|
| 139 |
* main attributes: |
| 140 |
- pid: identifier of the process |
| 141 |
- debugger: PtraceDebugger instance |
| 142 |
- breakpoints: dictionary of active breakpoints |
| 143 |
- parent: parent PtraceProcess (None if process has no parent) |
| 144 |
|
| 145 |
* state: |
| 146 |
- running: if True, the process is alive, otherwise the process |
| 147 |
doesn't exist anymore |
| 148 |
- exited: if True, the process has exited (attributed only used |
| 149 |
on BSD operation systems) |
| 150 |
- is_attached: if True, the process is attached by ptrace |
| 151 |
- was_attached: if True, the process will be detached at exit |
| 152 |
- is_stopped: if True, the process is stopped, otherwise it's |
| 153 |
running |
| 154 |
- syscall_state: control syscall tracing |
| 155 |
|
| 156 |
Sometimes, is_stopped value is wrong. You might use isTraced() to |
| 157 |
make sure that the process is stopped. |
| 158 |
""" |
| 159 |
|
| 160 |
def __init__(self, debugger, pid, is_attached, parent=None, is_thread=False): |
| 161 |
self.debugger = debugger |
| 162 |
self.breakpoints = {} |
| 163 |
self.pid = pid |
| 164 |
self.running = True |
| 165 |
self.exited = False |
| 166 |
self.parent = parent |
| 167 |
self.was_attached = is_attached |
| 168 |
self.is_attached = False |
| 169 |
self.is_stopped = True |
| 170 |
self.is_thread = is_thread |
| 171 |
if not is_attached: |
| 172 |
self.attach() |
| 173 |
else: |
| 174 |
self.is_attached = True |
| 175 |
if HAS_PROC: |
| 176 |
self.read_mem_file = None |
| 177 |
self.syscall_state = SyscallState(self) |
| 178 |
|
| 179 |
def isTraced(self): |
| 180 |
if not HAS_PROC: |
| 181 |
self.notImplementedError() |
| 182 |
stat = readProcessStat(self.pid) |
| 183 |
return (stat.state == 'T') |
| 184 |
|
| 185 |
def attach(self): |
| 186 |
if self.is_attached: |
| 187 |
return |
| 188 |
info("Attach process %s" % self.pid) |
| 189 |
ptrace_attach(self.pid) |
| 190 |
self.is_attached = True |
| 191 |
|
| 192 |
def dumpCode(self, start=None, stop=None, manage_bp=False, log=None): |
| 193 |
if not log: |
| 194 |
log = error |
| 195 |
try: |
| 196 |
ip = self.getInstrPointer() |
| 197 |
except PtraceError as err: |
| 198 |
if start is None: |
| 199 |
log("Unable to read instruction pointer: %s" % err) |
| 200 |
return |
| 201 |
ip = None |
| 202 |
if start is None: |
| 203 |
start = ip |
| 204 |
|
| 205 |
try: |
| 206 |
self._dumpCode(start, stop, ip, manage_bp, log) |
| 207 |
except PtraceError as err: |
| 208 |
log("Unable to dump code at %s: %s" % ( |
| 209 |
formatAddress(start), err)) |
| 210 |
|
| 211 |
def _dumpCode(self, start, stop, ip, manage_bp, log): |
| 212 |
if stop is not None: |
| 213 |
stop = max(start, stop) |
| 214 |
stop = min(stop, start + MAX_CODE_SIZE - 1) |
| 215 |
|
| 216 |
if not HAS_DISASSEMBLER: |
| 217 |
if stop is not None: |
| 218 |
size = stop - start + 1 |
| 219 |
else: |
| 220 |
size = MIN_CODE_SIZE |
| 221 |
code = self.readBytes(start, size) |
| 222 |
if RUNNING_PYTHON3: |
| 223 |
text = " ".join("%02x" % byte for byte in code) |
| 224 |
else: |
| 225 |
text = " ".join("%02x" % ord(byte) for byte in code) |
| 226 |
log("CODE: %s" % text) |
| 227 |
return |
| 228 |
|
| 229 |
log("CODE:") |
| 230 |
if manage_bp: |
| 231 |
address = start |
| 232 |
for line in range(10): |
| 233 |
bp = False |
| 234 |
if address in self.breakpoints: |
| 235 |
bytes = self.breakpoints[address].old_bytes |
| 236 |
instr = disassembleOne(bytes, address) |
| 237 |
bp = True |
| 238 |
else: |
| 239 |
instr = self.disassembleOne(address) |
| 240 |
text = "%s| %s (%s)" % (formatAddress( |
| 241 |
instr.address), instr.text, instr.hexa) |
| 242 |
if instr.address == ip: |
| 243 |
text += " <==" |
| 244 |
if bp: |
| 245 |
text += " * BREAKPOINT *" |
| 246 |
log(text) |
| 247 |
address = address + instr.size |
| 248 |
if stop is not None and stop <= address: |
| 249 |
break |
| 250 |
else: |
| 251 |
for instr in self.disassemble(start, stop): |
| 252 |
text = "%s| %s (%s)" % (formatAddress( |
| 253 |
instr.address), instr.text, instr.hexa) |
| 254 |
if instr.address == ip: |
| 255 |
text += " <==" |
| 256 |
log(text) |
| 257 |
|
| 258 |
def disassemble(self, start=None, stop=None, nb_instr=None): |
| 259 |
if not HAS_DISASSEMBLER: |
| 260 |
self.notImplementedError() |
| 261 |
if start is None: |
| 262 |
start = self.getInstrPointer() |
| 263 |
if stop is not None: |
| 264 |
stop = max(start, stop) |
| 265 |
size = stop - start + 1 |
| 266 |
else: |
| 267 |
if nb_instr is None: |
| 268 |
nb_instr = DEFAULT_NB_INSTR |
| 269 |
size = nb_instr * MAX_INSTR_SIZE |
| 270 |
|
| 271 |
code = self.readBytes(start, size) |
| 272 |
for index, instr in enumerate(disassemble(code, start)): |
| 273 |
yield instr |
| 274 |
if nb_instr and nb_instr <= (index + 1): |
| 275 |
break |
| 276 |
|
| 277 |
def disassembleOne(self, address=None): |
| 278 |
if not HAS_DISASSEMBLER: |
| 279 |
self.notImplementedError() |
| 280 |
if address is None: |
| 281 |
address = self.getInstrPointer() |
| 282 |
code = self.readBytes(address, MAX_INSTR_SIZE) |
| 283 |
return disassembleOne(code, address) |
| 284 |
|
| 285 |
def findStack(self): |
| 286 |
for map in self.readMappings(): |
| 287 |
if map.pathname == "[stack]": |
| 288 |
return map |
| 289 |
return None |
| 290 |
|
| 291 |
def detach(self): |
| 292 |
if not self.is_attached: |
| 293 |
return |
| 294 |
self.is_attached = False |
| 295 |
if self.running: |
| 296 |
info("Detach %s" % self) |
| 297 |
ptrace_detach(self.pid) |
| 298 |
self.debugger.deleteProcess(process=self) |
| 299 |
|
| 300 |
def _notRunning(self): |
| 301 |
self.running = False |
| 302 |
if HAS_PROC and self.read_mem_file: |
| 303 |
try: |
| 304 |
self.read_mem_file.close() |
| 305 |
except IOError: |
| 306 |
pass |
| 307 |
self.detach() |
| 308 |
|
| 309 |
def kill(self, signum): |
| 310 |
kill(self.pid, signum) |
| 311 |
|
| 312 |
def terminate(self, wait_exit=True): |
| 313 |
if not self.running or not self.was_attached: |
| 314 |
return True |
| 315 |
warning("Terminate %s" % self) |
| 316 |
done = False |
| 317 |
try: |
| 318 |
if self.is_stopped: |
| 319 |
self.cont(SIGKILL) |
| 320 |
else: |
| 321 |
self.kill(SIGKILL) |
| 322 |
except PtraceError as event: |
| 323 |
if event.errno == ESRCH: |
| 324 |
done = True |
| 325 |
else: |
| 326 |
raise event |
| 327 |
if not done: |
| 328 |
if not wait_exit: |
| 329 |
return False |
| 330 |
self.waitExit() |
| 331 |
self._notRunning() |
| 332 |
return True |
| 333 |
|
| 334 |
def waitExit(self): |
| 335 |
while True: |
| 336 |
# Wait for any process signal |
| 337 |
event = self.waitEvent() |
| 338 |
event_cls = event.__class__ |
| 339 |
|
| 340 |
# Process exited: we are done |
| 341 |
if event_cls == ProcessExit: |
| 342 |
return |
| 343 |
|
| 344 |
# Event different than a signal? Raise an exception |
| 345 |
if event_cls != ProcessSignal: |
| 346 |
raise event |
| 347 |
|
| 348 |
# Send the signal to the process |
| 349 |
signum = event.signum |
| 350 |
if signum not in (SIGTRAP, SIGSTOP): |
| 351 |
self.cont(signum) |
| 352 |
else: |
| 353 |
self.cont() |
| 354 |
|
| 355 |
def processStatus(self, status): |
| 356 |
# Process exited? |
| 357 |
if WIFEXITED(status): |
| 358 |
code = WEXITSTATUS(status) |
| 359 |
event = self.processExited(code) |
| 360 |
|
| 361 |
# Process killed by a signal? |
| 362 |
elif WIFSIGNALED(status): |
| 363 |
signum = WTERMSIG(status) |
| 364 |
event = self.processKilled(signum) |
| 365 |
|
| 366 |
# Invalid process status? |
| 367 |
elif not WIFSTOPPED(status): |
| 368 |
raise ProcessError(self, "Unknown process status: %r" % status) |
| 369 |
|
| 370 |
# Ptrace event? |
| 371 |
elif HAS_PTRACE_EVENTS and WPTRACEEVENT(status): |
| 372 |
event = WPTRACEEVENT(status) |
| 373 |
event = self.ptraceEvent(event) |
| 374 |
|
| 375 |
else: |
| 376 |
signum = WSTOPSIG(status) |
| 377 |
event = self.processSignal(signum) |
| 378 |
return event |
| 379 |
|
| 380 |
def processTerminated(self): |
| 381 |
self._notRunning() |
| 382 |
return ProcessExit(self) |
| 383 |
|
| 384 |
def processExited(self, code): |
| 385 |
if RUNNING_BSD and not self.exited: |
| 386 |
# on FreeBSD, we have to waitpid() twice |
| 387 |
# to avoid zombi process!? |
| 388 |
self.exited = True |
| 389 |
self.waitExit() |
| 390 |
self._notRunning() |
| 391 |
return ProcessExit(self, exitcode=code) |
| 392 |
|
| 393 |
def processKilled(self, signum): |
| 394 |
self._notRunning() |
| 395 |
return ProcessExit(self, signum=signum) |
| 396 |
|
| 397 |
def processSignal(self, signum): |
| 398 |
self.is_stopped = True |
| 399 |
return ProcessSignal(signum, self) |
| 400 |
|
| 401 |
def ptraceEvent(self, event): |
| 402 |
if not HAS_PTRACE_EVENTS: |
| 403 |
self.notImplementedError() |
| 404 |
if event in NEW_PROCESS_EVENT: |
| 405 |
new_pid = ptrace_geteventmsg(self.pid) |
| 406 |
is_thread = (event == PTRACE_EVENT_CLONE) |
| 407 |
new_process = self.debugger.addProcess( |
| 408 |
new_pid, is_attached=True, parent=self, is_thread=is_thread) |
| 409 |
return NewProcessEvent(new_process) |
| 410 |
elif event == PTRACE_EVENT_EXEC: |
| 411 |
return ProcessExecution(self) |
| 412 |
else: |
| 413 |
raise ProcessError(self, "Unknown ptrace event: %r" % event) |
| 414 |
|
| 415 |
def getregs(self): |
| 416 |
if HAS_PTRACE_GETREGS or HAS_PTRACE_GETREGSET: |
| 417 |
return ptrace_getregs(self.pid) |
| 418 |
else: |
| 419 |
# FIXME: Optimize getreg() when used with this function |
| 420 |
words = [] |
| 421 |
nb_words = sizeof(ptrace_registers_t) // CPU_WORD_SIZE |
| 422 |
for offset in range(nb_words): |
| 423 |
word = ptrace_peekuser(self.pid, offset * CPU_WORD_SIZE) |
| 424 |
bytes = word2bytes(word) |
| 425 |
words.append(bytes) |
| 426 |
bytes = ''.join(words) |
| 427 |
return bytes2type(bytes, ptrace_registers_t) |
| 428 |
|
| 429 |
def getreg(self, name): |
| 430 |
try: |
| 431 |
name, shift, mask = CPU_SUB_REGISTERS[name] |
| 432 |
except KeyError: |
| 433 |
shift = 0 |
| 434 |
mask = None |
| 435 |
if name not in REGISTER_NAMES: |
| 436 |
raise ProcessError(self, "Unknown register: %r" % name) |
| 437 |
regs = self.getregs() |
| 438 |
value = getattr(regs, name) |
| 439 |
value >>= shift |
| 440 |
if mask: |
| 441 |
value &= mask |
| 442 |
return value |
| 443 |
|
| 444 |
def setregs(self, regs): |
| 445 |
ptrace_setregs(self.pid, regs) |
| 446 |
|
| 447 |
def setreg(self, name, value): |
| 448 |
regs = self.getregs() |
| 449 |
if name in CPU_SUB_REGISTERS: |
| 450 |
full_name, shift, mask = CPU_SUB_REGISTERS[name] |
| 451 |
full_value = getattr(regs, full_name) |
| 452 |
full_value &= ~mask |
| 453 |
full_value |= ((value & mask) << shift) |
| 454 |
value = full_value |
| 455 |
name = full_name |
| 456 |
if name not in REGISTER_NAMES: |
| 457 |
raise ProcessError(self, "Unknown register: %r" % name) |
| 458 |
setattr(regs, name, value) |
| 459 |
self.setregs(regs) |
| 460 |
|
| 461 |
def singleStep(self): |
| 462 |
if not HAS_PTRACE_SINGLESTEP: |
| 463 |
self.notImplementedError() |
| 464 |
ptrace_singlestep(self.pid) |
| 465 |
|
| 466 |
def filterSignal(self, signum): |
| 467 |
if signum == SIGTRAP: |
| 468 |
# Never transfer SIGTRAP signal |
| 469 |
return 0 |
| 470 |
else: |
| 471 |
return signum |
| 472 |
|
| 473 |
def syscall(self, signum=0): |
| 474 |
signum = self.filterSignal(signum) |
| 475 |
ptrace_syscall(self.pid, signum) |
| 476 |
self.is_stopped = False |
| 477 |
|
| 478 |
def setInstrPointer(self, ip): |
| 479 |
if CPU_INSTR_POINTER: |
| 480 |
self.setreg(CPU_INSTR_POINTER, ip) |
| 481 |
else: |
| 482 |
raise ProcessError( |
| 483 |
self, "Instruction pointer register is not defined") |
| 484 |
|
| 485 |
def getInstrPointer(self): |
| 486 |
if CPU_INSTR_POINTER: |
| 487 |
return self.getreg(CPU_INSTR_POINTER) |
| 488 |
else: |
| 489 |
raise ProcessError( |
| 490 |
self, "Instruction pointer register is not defined") |
| 491 |
|
| 492 |
def getStackPointer(self): |
| 493 |
if CPU_STACK_POINTER: |
| 494 |
return self.getreg(CPU_STACK_POINTER) |
| 495 |
else: |
| 496 |
raise ProcessError(self, "Stack pointer register is not defined") |
| 497 |
|
| 498 |
def getFramePointer(self): |
| 499 |
if CPU_FRAME_POINTER: |
| 500 |
return self.getreg(CPU_FRAME_POINTER) |
| 501 |
else: |
| 502 |
raise ProcessError(self, "Stack pointer register is not defined") |
| 503 |
|
| 504 |
def _readBytes(self, address, size): |
| 505 |
offset = address % CPU_WORD_SIZE |
| 506 |
if offset: |
| 507 |
# Read word |
| 508 |
address -= offset |
| 509 |
word = self.readWord(address) |
| 510 |
bytes = word2bytes(word) |
| 511 |
|
| 512 |
# Read some bytes from the word |
| 513 |
subsize = min(CPU_WORD_SIZE - offset, size) |
| 514 |
data = bytes[offset:offset + subsize] # <-- FIXME: Big endian! |
| 515 |
|
| 516 |
# Move cursor |
| 517 |
size -= subsize |
| 518 |
address += CPU_WORD_SIZE |
| 519 |
else: |
| 520 |
data = b'' |
| 521 |
|
| 522 |
while size: |
| 523 |
# Read word |
| 524 |
word = self.readWord(address) |
| 525 |
bytes = word2bytes(word) |
| 526 |
|
| 527 |
# Read bytes from the word |
| 528 |
if size < CPU_WORD_SIZE: |
| 529 |
data += bytes[:size] # <-- FIXME: Big endian! |
| 530 |
break |
| 531 |
data += bytes |
| 532 |
|
| 533 |
# Move cursor |
| 534 |
size -= CPU_WORD_SIZE |
| 535 |
address += CPU_WORD_SIZE |
| 536 |
return data |
| 537 |
|
| 538 |
def readWord(self, address): |
| 539 |
"""Address have to be aligned!""" |
| 540 |
word = ptrace_peektext(self.pid, address) |
| 541 |
return word |
| 542 |
|
| 543 |
if HAS_PTRACE_IO: |
| 544 |
def readBytes(self, address, size): |
| 545 |
buffer = create_string_buffer(size) |
| 546 |
io_desc = ptrace_io_desc( |
| 547 |
piod_op=PIOD_READ_D, |
| 548 |
piod_offs=address, |
| 549 |
piod_addr=addressof(buffer), |
| 550 |
piod_len=size) |
| 551 |
ptrace_io(self.pid, io_desc) |
| 552 |
return buffer.raw |
| 553 |
elif HAS_PROC: |
| 554 |
def readBytes(self, address, size): |
| 555 |
if not self.read_mem_file: |
| 556 |
filename = '/proc/%u/mem' % self.pid |
| 557 |
try: |
| 558 |
self.read_mem_file = open(filename, 'rb', 0) |
| 559 |
except IOError as err: |
| 560 |
message = "Unable to open %s: fallback to ptrace implementation" % filename |
| 561 |
if err.errno != EACCES: |
| 562 |
error(message) |
| 563 |
else: |
| 564 |
info(message) |
| 565 |
self.readBytes = self._readBytes |
| 566 |
return self.readBytes(address, size) |
| 567 |
|
| 568 |
try: |
| 569 |
mem = self.read_mem_file |
| 570 |
mem.seek(address) |
| 571 |
data = mem.read(size) |
| 572 |
except (IOError, ValueError) as err: |
| 573 |
raise ProcessError(self, "readBytes(%s, %s) error: %s" % ( |
| 574 |
formatAddress(address), size, err)) |
| 575 |
if len(data) == 0 and size: |
| 576 |
# Issue #10: If the process was not created by the debugger |
| 577 |
# (ex: fork), the kernel may deny reading private mappings of |
| 578 |
# /proc/pid/mem to the debugger, depending on the kernel |
| 579 |
# version and kernel config (ex: SELinux enabled or not). |
| 580 |
# |
| 581 |
# Fallback to PTRACE_PEEKTEXT. It is slower but a debugger |
| 582 |
# tracing the process is always allowed to use it. |
| 583 |
self.readBytes = self._readBytes |
| 584 |
return self.readBytes(address, size) |
| 585 |
return data |
| 586 |
else: |
| 587 |
readBytes = _readBytes |
| 588 |
|
| 589 |
def getsiginfo(self): |
| 590 |
if not HAS_PTRACE_SIGINFO: |
| 591 |
self.notImplementedError() |
| 592 |
return ptrace_getsiginfo(self.pid) |
| 593 |
|
| 594 |
def writeBytes(self, address, bytes): |
| 595 |
if HAS_PTRACE_IO: |
| 596 |
size = len(bytes) |
| 597 |
bytes = create_string_buffer(bytes) |
| 598 |
io_desc = ptrace_io_desc( |
| 599 |
piod_op=PIOD_WRITE_D, |
| 600 |
piod_offs=address, |
| 601 |
piod_addr=addressof(bytes), |
| 602 |
piod_len=size) |
| 603 |
ptrace_io(self.pid, io_desc) |
| 604 |
else: |
| 605 |
offset = address % CPU_WORD_SIZE |
| 606 |
if offset: |
| 607 |
# Write partial word (end) |
| 608 |
address -= offset |
| 609 |
size = CPU_WORD_SIZE - offset |
| 610 |
word = self.readBytes(address, CPU_WORD_SIZE) |
| 611 |
if len(bytes) < size: |
| 612 |
size = len(bytes) |
| 613 |
word = word[:offset] + bytes[:size] + \ |
| 614 |
word[offset + size:] # <-- FIXME: Big endian! |
| 615 |
else: |
| 616 |
# <-- FIXME: Big endian! |
| 617 |
word = word[:offset] + bytes[:size] |
| 618 |
self.writeWord(address, bytes2word(word)) |
| 619 |
bytes = bytes[size:] |
| 620 |
address += CPU_WORD_SIZE |
| 621 |
|
| 622 |
# Write full words |
| 623 |
while CPU_WORD_SIZE <= len(bytes): |
| 624 |
# Read one word |
| 625 |
word = bytes[:CPU_WORD_SIZE] |
| 626 |
word = bytes2word(word) |
| 627 |
self.writeWord(address, word) |
| 628 |
|
| 629 |
# Move to next word |
| 630 |
bytes = bytes[CPU_WORD_SIZE:] |
| 631 |
address += CPU_WORD_SIZE |
| 632 |
if not bytes: |
| 633 |
return |
| 634 |
|
| 635 |
# Write partial word (begin) |
| 636 |
size = len(bytes) |
| 637 |
word = self.readBytes(address, CPU_WORD_SIZE) |
| 638 |
# FIXME: Write big endian version of the next line |
| 639 |
word = bytes + word[size:] |
| 640 |
self.writeWord(address, bytes2word(word)) |
| 641 |
|
| 642 |
def readStruct(self, address, struct): |
| 643 |
bytes = self.readBytes(address, sizeof(struct)) |
| 644 |
bytes = c_char_p(bytes) |
| 645 |
return bytes2type(bytes, struct) |
| 646 |
|
| 647 |
def readArray(self, address, basetype, count): |
| 648 |
bytes = self.readBytes(address, sizeof(basetype) * count) |
| 649 |
bytes = c_char_p(bytes) |
| 650 |
return bytes2array(bytes, basetype, count) |
| 651 |
|
| 652 |
def readCString(self, address, max_size, chunk_length=256): |
| 653 |
string = [] |
| 654 |
size = 0 |
| 655 |
truncated = False |
| 656 |
while True: |
| 657 |
done = False |
| 658 |
data = self.readBytes(address, chunk_length) |
| 659 |
pos = data.find(b'\0') |
| 660 |
if pos != -1: |
| 661 |
done = True |
| 662 |
data = data[:pos] |
| 663 |
if max_size <= size + chunk_length: |
| 664 |
data = data[:(max_size - size)] |
| 665 |
string.append(data) |
| 666 |
truncated = True |
| 667 |
break |
| 668 |
string.append(data) |
| 669 |
if done: |
| 670 |
break |
| 671 |
size += chunk_length |
| 672 |
address += chunk_length |
| 673 |
return b''.join(string), truncated |
| 674 |
|
| 675 |
def dumpStack(self, log=None): |
| 676 |
if not log: |
| 677 |
log = error |
| 678 |
stack = self.findStack() |
| 679 |
if stack: |
| 680 |
log("STACK: %s" % stack) |
| 681 |
self._dumpStack(log) |
| 682 |
|
| 683 |
def _dumpStack(self, log): |
| 684 |
sp = self.getStackPointer() |
| 685 |
displayed = 0 |
| 686 |
for index in range(-5, 5 + 1): |
| 687 |
delta = index * CPU_WORD_SIZE |
| 688 |
try: |
| 689 |
value = self.readWord(sp + delta) |
| 690 |
log("STACK%+ 3i: %s" % (delta, formatWordHex(value))) |
| 691 |
displayed += 1 |
| 692 |
except PtraceError: |
| 693 |
pass |
| 694 |
if not displayed: |
| 695 |
log("ERROR: unable to read the stack (SP=%s)" % formatAddress(sp)) |
| 696 |
|
| 697 |
def readMappings(self): |
| 698 |
return readProcessMappings(self) |
| 699 |
|
| 700 |
def dumpMaps(self, log=None): |
| 701 |
if not log: |
| 702 |
log = error |
| 703 |
for map in self.readMappings(): |
| 704 |
log("MAPS: %s" % map) |
| 705 |
|
| 706 |
def writeWord(self, address, word): |
| 707 |
""" |
| 708 |
Address have to be aligned! |
| 709 |
""" |
| 710 |
ptrace_poketext(self.pid, address, word) |
| 711 |
|
| 712 |
def dumpRegs(self, log=None): |
| 713 |
if not log: |
| 714 |
log = error |
| 715 |
try: |
| 716 |
regs = self.getregs() |
| 717 |
dumpRegs(log, regs) |
| 718 |
except PtraceError as err: |
| 719 |
log("Unable to read registers: %s" % err) |
| 720 |
|
| 721 |
def cont(self, signum=0): |
| 722 |
signum = self.filterSignal(signum) |
| 723 |
ptrace_cont(self.pid, signum) |
| 724 |
self.is_stopped = False |
| 725 |
|
| 726 |
def setoptions(self, options): |
| 727 |
if not HAS_PTRACE_EVENTS: |
| 728 |
self.notImplementedError() |
| 729 |
info("Set %s options to %s" % (self, options)) |
| 730 |
ptrace_setoptions(self.pid, options) |
| 731 |
|
| 732 |
def waitEvent(self): |
| 733 |
return self.debugger.waitProcessEvent(pid=self.pid) |
| 734 |
|
| 735 |
def waitSignals(self, *signals): |
| 736 |
return self.debugger.waitSignals(*signals, pid=self.pid) |
| 737 |
|
| 738 |
def waitSyscall(self): |
| 739 |
self.debugger.waitSyscall(self) |
| 740 |
|
| 741 |
def findBreakpoint(self, address): |
| 742 |
for bp in self.breakpoints.values(): |
| 743 |
if bp.address <= address < bp.address + bp.size: |
| 744 |
return bp |
| 745 |
return None |
| 746 |
|
| 747 |
def createBreakpoint(self, address, size=1): |
| 748 |
bp = self.findBreakpoint(address) |
| 749 |
if bp: |
| 750 |
raise ProcessError(self, "A breakpoint is already set: %s" % bp) |
| 751 |
bp = Breakpoint(self, address, size) |
| 752 |
self.breakpoints[address] = bp |
| 753 |
return bp |
| 754 |
|
| 755 |
def getBacktrace(self, max_args=6, max_depth=20): |
| 756 |
return getBacktrace(self, max_args=max_args, max_depth=max_depth) |
| 757 |
|
| 758 |
def removeBreakpoint(self, breakpoint): |
| 759 |
del self.breakpoints[breakpoint.address] |
| 760 |
|
| 761 |
def __del__(self): |
| 762 |
try: |
| 763 |
self.detach() |
| 764 |
except PtraceError: |
| 765 |
pass |
| 766 |
|
| 767 |
def __str__(self): |
| 768 |
return self.__repr__() |
| 769 |
|
| 770 |
def __repr__(self): |
| 771 |
return "<PtraceProcess #%s>" % self.pid |
| 772 |
|
| 773 |
def __hash__(self): |
| 774 |
return hash(self.pid) |
| 775 |
|
| 776 |
def notImplementedError(self): |
| 777 |
raise NotImplementedError() |