-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdumper.py
executable file
·70 lines (54 loc) · 1.66 KB
/
dumper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python3
import sys
import os
import re
from textwrap import wrap
hexline_pattern = re.compile(r"([0-9a-f]{4}):\s+((?:[0-9a-f]{4} )+)")
whitespace_pattern = re.compile(r"\s+")
def main():
if not check_args():
usage()
return
inf = sys.stdin
with get_outfile(sys.argv[1]) as outf:
lines = inf.read().splitlines()
image = extract_image(lines)
outf.write(image)
def extract_image(lines):
mem_map = dict(filter(lambda x: x[0] != None, map(decode_line, lines)))
last_addr = 0
image = []
for addr, line_bytes in mem_map.items():
if is_gap(addr, last_addr):
fill_gap(image, addr, last_addr)
image.extend(line_bytes)
last_addr = addr
return bytearray(image)
def is_gap(addr, last_addr):
return addr > last_addr + 16
def fill_gap(image_bytes, addr, last_addr):
for i in range(0, (addr-last_addr)-16):
image_bytes.append(0)
def decode_line(line):
match = hexline_pattern.search(line)
if match is None:
return (None, None)
addr = int(match.group(1), 16)
line_bytes = extract_line_bytes(match.group(2))
return (addr, line_bytes)
def extract_line_bytes(byte_str):
clean_byte_str = re.sub(whitespace_pattern, "", byte_str)
return list(map(lambda x: int(x, 16), wrap(clean_byte_str, 2)))
def check_args():
if len(sys.argv) != 2:
return False
return True
def usage():
print(f"Usage: {sys.argv[0]} <output path>")
print()
print("Input is read from stdin.")
def get_outfile(path):
if path == "-":
return os.fdopen(sys.stdout.fileno(), "wb", closefd=False)
return open(path, "wb")
main()