Skip to content

Instantly share code, notes, and snippets.

@mgeeky
Created June 27, 2017 22:18
Show Gist options
  • Save mgeeky/6a8fa7814efb6c8ad783c3c76c791c4c to your computer and use it in GitHub Desktop.
Save mgeeky/6a8fa7814efb6c8ad783c3c76c791c4c to your computer and use it in GitHub Desktop.
Example of dumping memory from within Python's code, using `ctypes.c_byte.from_address`
#!/usr/bin/python
def hex_dump_memory(ptr, num):
import ctypes
s = ''
n = 0
lines = []
data = list((num * ctypes.c_byte).from_address(ptr))
if len(data) == 0:
return '<empty>'
for i in range(0, num, 16):
line = ''
line += '%04x | ' % (i)
n += 16
for j in range(n-16, n):
if j >= len(data): break
line += '%02x ' % abs(data[j])
line += ' ' * (3 * 16 + 7 - len(line)) + ' | '
for j in range(n-16, n):
if j >= len(data): break
c = data[j] if not (data[j] < 0x20 or data[j] > 0x7e) else '.'
line += '%c' % c
lines.append(line)
return '\n'.join(lines)
addr = int('0x' + open('/proc/self/maps', 'r').readlines()[0].split('-')[0], 16)
print 'Hex dump from 0x%016x' % addr
print hex_dump_memory(addr, 256)
@mgeeky
Copy link
Author

mgeeky commented Jan 12, 2022

@modz2014 hi! I've never tried repurposing that primitive into fully-fledged process dumper, neither do I believe that would be easy to do so. In order to obtain nice minidump you would need to adhere to underlying file format & required structures that formulate it.
Implemented primitive is capable of merely acquiring raw bytes view, which is not enough to end up with a tidy minidump.

Hopefully that makes things more clear.

Regards,
Mariusz

@modz2014
Copy link

modz2014 commented Jan 13, 2022

I just want to be able to dump memory of a program that’s all so I don’t have to use procdump all the time

it’s only dump at a certain string won’t even need a full
Dump of the program

@jfongattw
Copy link

Hasn't it been better to use ctypes.c_ubyte on line 9?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment