One minute
Easily locate a memory address in Linux
- You are doing some fancy, low-level, unorthodox memory operation in your C program.
- You segfault.
- The most advanced debugging tool that you know (i.e. spamming
printf
around) is printing a memory address. - You are so dumb that you cannot figure it out where this address is located.
- You don’t want to manually look to
/proc/PID/maps
to find the memory segment.
Here is a Python script for you:
#!/usr/bin/python3
# (C) 2022 Massimo Girondi - CC BY-NC-SA 4.0
import re
import sys
import psutil
# From psutil examples
def pidof(pgname):
pids = []
for proc in psutil.process_iter(['name', 'cmdline']):
# search for matches in the process name and cmdline
if proc.info['name'] == pgname or \
proc.info['cmdline'] and proc.info['cmdline'][0] == pgname:
pids.append(str(proc.pid))
return pids
if len(sys.argv) < 3:
printf("Usage: locate_address.py process_name address"
exit(1)
name =sys.argv[1]
pid = int(pidof(name)[0])
address = int(sys.argv[2], 16)
pattern = re.compile("([0-9a-fx]+)-([0-9a-fx]+)(.* )+(.+)$")
with open(f"/proc/{pid}/maps") as f:
for line in f:
s = pattern.search(line)
start = int(f"0x{s.group(1)}",16)
stop = int(f"0x{s.group(2)}",16)
n = len(s.groups())
name = s.group(n)
#print(start, stop, name)
if start <= address <= stop:
print(line)