| 1 |
import re |
| 2 |
|
| 3 |
# Match a register name: $eax, $gp0, $orig_eax |
| 4 |
REGISTER_REGEX = re.compile(r"([a-z]+[a-z0-9_]+)") |
| 5 |
|
| 6 |
# Hexadecimal number (e.g. 0xa) |
| 7 |
HEXADECIMAL_REGEX = re.compile(r"0x[0-9a-f]+") |
| 8 |
|
| 9 |
# Make sure that the expression does not contain invalid characters |
| 10 |
# Examples: |
| 11 |
# (1-2)<<5 |
| 12 |
# 340&91 |
| 13 |
EXPR_REGEX = re.compile(r"^[()<>+*/&0-9-]+$") |
| 14 |
|
| 15 |
|
| 16 |
def replaceHexadecimal(regs): |
| 17 |
""" |
| 18 |
Convert an hexadecimal number to decimal number (as string). |
| 19 |
Callback used by parseExpression(). |
| 20 |
""" |
| 21 |
text = regs.group(0) |
| 22 |
if text.startswith("0x"): |
| 23 |
text = text[2:] |
| 24 |
elif not re.search("[a-f]", text): |
| 25 |
return text |
| 26 |
value = int(text, 16) |
| 27 |
return str(value) |
| 28 |
|
| 29 |
|
| 30 |
def parseExpression(process, text): |
| 31 |
""" |
| 32 |
Parse an expression. Syntax: |
| 33 |
- "10": decimal number |
| 34 |
- "0x10": hexadecimal number |
| 35 |
- "eax": register value |
| 36 |
- "a+b", "a-b", "a*b", "a/b", "a**b", "a<<b", "a>>b": operators |
| 37 |
|
| 38 |
>>> from ptrace.mockup import FakeProcess |
| 39 |
>>> process = FakeProcess() |
| 40 |
>>> parseExpression(process, "1+1") |
| 41 |
2 |
| 42 |
>>> process.setreg("eax", 3) |
| 43 |
>>> parseExpression(process, "eax*0x10") |
| 44 |
48 |
| 45 |
""" |
| 46 |
# Remove spaces and convert to lower case |
| 47 |
text = text.strip() |
| 48 |
orig_text = text |
| 49 |
if " " in text: |
| 50 |
raise ValueError("Space are forbidden: %r" % text) |
| 51 |
text = text.lower() |
| 52 |
|
| 53 |
def readRegister(regs): |
| 54 |
name = regs.group(1) |
| 55 |
value = process.getreg(name) |
| 56 |
return str(value) |
| 57 |
|
| 58 |
# Replace hexadecimal by decimal |
| 59 |
text = HEXADECIMAL_REGEX.sub(replaceHexadecimal, text) |
| 60 |
|
| 61 |
# Replace registers by their value |
| 62 |
text = REGISTER_REGEX.sub(readRegister, text) |
| 63 |
|
| 64 |
# Reject invalid characters |
| 65 |
if not EXPR_REGEX.match(text): |
| 66 |
raise ValueError("Invalid expression: %r" % orig_text) |
| 67 |
|
| 68 |
# Use integer division (a//b) instead of float division (a/b) |
| 69 |
text = text.replace("/", "//") |
| 70 |
|
| 71 |
# Finally, evaluate the expression |
| 72 |
try: |
| 73 |
value = eval(text) |
| 74 |
except SyntaxError: |
| 75 |
raise ValueError("Invalid expression: %r" % orig_text) |
| 76 |
return value |