Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@mgeeky mgeeky commented Jun 27, 2017

$ ./python_memory_dump.py 
Hex dump from 0x000055b92c7c2000
0000 | 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00  | .ELF............
0010 | 03 00 3e 00 01 00 00 00 10 42 0d 00 00 00 00 00  | ..>......B......
0020 | 40 00 00 00 00 00 00 00 38 4c 39 00 00 00 00 00  | @.......8.9.....
0030 | 00 00 00 00 40 00 38 00 09 00 40 00 1e 00 1d 00  | ....@.8...@.....
0040 | 06 00 00 00 05 00 00 00 40 00 00 00 00 00 00 00  | ........@.......
0050 | 40 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00  | @.......@.......
0060 | 08 01 00 00 00 00 00 00 08 01 00 00 00 00 00 00  | ................
0070 | 08 00 00 00 00 00 00 00 03 00 00 00 04 00 00 00  | ................
0080 | 38 02 00 00 00 00 00 00 38 02 00 00 00 00 00 00  | 8.......8.......
0090 | 38 02 00 00 00 00 00 00 1c 00 00 00 00 00 00 00  | 8...............
00a0 | 1c 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00  | ................
00b0 | 01 00 00 00 05 00 00 00 00 00 00 00 00 00 00 00  | ................
00c0 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  | ................
00d0 | 0c 2d 32 00 00 00 00 00 0c 2d 32 00 00 00 00 00  | .-2......-2.....
00e0 | 00 00 20 00 00 00 00 00 01 00 00 00 06 00 00 00  | .. .............
00f0 | 38 39 32 00 00 00 00 00 38 39 52 00 00 00 00 00  | .92......9R.....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.