| 1 |
from ptrace.ctypes_tools import formatAddress |
| 2 |
from ptrace import PtraceError |
| 3 |
from logging import info |
| 4 |
from weakref import ref |
| 5 |
from ptrace.cpu_info import CPU_POWERPC, CPU_WORD_SIZE |
| 6 |
from ptrace.ctypes_tools import word2bytes |
| 7 |
|
| 8 |
|
| 9 |
class Breakpoint(object): |
| 10 |
""" |
| 11 |
Software breakpoint. |
| 12 |
|
| 13 |
Use desinstall() method to remove the breakpoint from the process. |
| 14 |
""" |
| 15 |
|
| 16 |
def __init__(self, process, address, size=None): |
| 17 |
self._installed = False |
| 18 |
self.process = ref(process) |
| 19 |
self.address = address |
| 20 |
if CPU_POWERPC: |
| 21 |
size = CPU_WORD_SIZE |
| 22 |
elif size is None: |
| 23 |
size = 1 |
| 24 |
self.size = size |
| 25 |
|
| 26 |
# Store instruction bytes |
| 27 |
info("Install %s" % self) |
| 28 |
self.old_bytes = process.readBytes(address, size) |
| 29 |
|
| 30 |
if CPU_POWERPC: |
| 31 |
# Replace instruction with "TRAP" |
| 32 |
new_bytes = word2bytes(0x0cc00000) |
| 33 |
else: |
| 34 |
# Replace instruction with "INT 3" |
| 35 |
new_bytes = b"\xCC" * size |
| 36 |
process.writeBytes(address, new_bytes) |
| 37 |
self._installed = True |
| 38 |
|
| 39 |
def desinstall(self, set_ip=False): |
| 40 |
""" |
| 41 |
Remove the breakpoint from the associated process. If set_ip is True, |
| 42 |
restore the instruction pointer to the address of the breakpoint. |
| 43 |
""" |
| 44 |
if not self._installed: |
| 45 |
return |
| 46 |
self._installed = False |
| 47 |
info("Desinstall %s" % self) |
| 48 |
process = self.process() |
| 49 |
if not process: |
| 50 |
return |
| 51 |
if process.running: |
| 52 |
process.writeBytes(self.address, self.old_bytes) |
| 53 |
if set_ip: |
| 54 |
process.setInstrPointer(self.address) |
| 55 |
process.removeBreakpoint(self) |
| 56 |
|
| 57 |
def __str__(self): |
| 58 |
return "<Breakpoint %s..%s>" % ( |
| 59 |
formatAddress(self.address), |
| 60 |
formatAddress(self.address + self.size - 1)) |
| 61 |
|
| 62 |
def __del__(self): |
| 63 |
try: |
| 64 |
self.desinstall(False) |
| 65 |
except PtraceError: |
| 66 |
pass |