Created
October 19, 2021 17:22
-
-
Save python273/42d28b5c4332a5e0aa94cb0d89f79f0a to your computer and use it in GitHub Desktop.
Stop a process and dump memory segments. Based on https://shafiqvinales.wordpress.com/2017/09/14/dump-a-linux-processs-memory-to-file/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pathlib import Path | |
import os | |
import ctypes, re, sys | |
from pprint import pprint | |
import traceback | |
c_ptrace = ctypes.CDLL("libc.so.6").ptrace | |
c_pid_t = ctypes.c_int32 | |
c_ptrace.argtypes = [ctypes.c_int, c_pid_t, ctypes.c_void_p, ctypes.c_void_p] | |
def ptrace(attach, pid): | |
op = ctypes.c_int(16 if attach else 17) | |
c_pid = c_pid_t(pid) | |
null = ctypes.c_void_p() | |
err = c_ptrace(op, c_pid, null, null) | |
if err != 0: | |
raise Exception('ptrace', err) | |
def maps_line_range(line): | |
m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r])', line) | |
return [int(m.group(1), 16), int(m.group(2), 16), m.group(3), line.strip()] | |
def cat_proc_mem(pid): | |
pid = int(pid) | |
segments_dir = Path(f'segments_{pid}/') | |
os.makedirs(segments_dir, exist_ok=True) | |
ptrace(True, pid) | |
print('waitpid', os.waitpid(pid, 0)) | |
with open(f"/proc/{pid}/maps", 'r') as maps_file: | |
maps_lines = maps_file.readlines() | |
for i in maps_lines: | |
print(i, end='') | |
ranges = [maps_line_range(i) for i in maps_lines] | |
print('sum ', sum(i[1] - i[0] for i in ranges)) | |
with open(segments_dir / 'info.txt', 'w') as f: | |
for i in maps_lines: | |
f.write(i) | |
mem_file = open(f"/proc/{pid}/mem", 'rb', 0) | |
for start_addr, end_addr, readable, l in ranges: | |
if readable != 'r': | |
print('skipping', l) | |
continue | |
print('reading', l) | |
mem_file.seek(start_addr) | |
try: | |
chunk = mem_file.read(end_addr - start_addr) | |
except OSError as e: | |
print('ERR reading') | |
traceback.print_exc() | |
with open(segments_dir / f'{"_".join(l.split(" ", 2)[:2])}.bin', 'wb') as f: | |
f.write(chunk) | |
mem_file.close() | |
ptrace(False, pid) | |
if __name__ == "__main__": | |
for pid in sys.argv[1:]: | |
cat_proc_mem(pid) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment