Skip to content

Instantly share code, notes, and snippets.

@KubaO
Last active December 27, 2024 20:50
Show Gist options
  • Save KubaO/5691b8bd34fcb25119021acd1d7a3ee7 to your computer and use it in GitHub Desktop.
Save KubaO/5691b8bd34fcb25119021acd1d7a3ee7 to your computer and use it in GitHub Desktop.
import ctypes as c
buffer = c.create_string_buffer(32)
size = c.sizeof(buffer)
addr = c.addressof(buffer)
print(f"Buffer size is {size}d/{size:x}h bytes")
print(f"Buffer address is {addr:08x}h")
def dump(addr, size):
output = "Hexadecimal dump:\n"
for i in range(size):
byte = c.cast(addr+i, c.POINTER(c.c_uint8)).contents.value
if i%8==0:
if i: output += "\n"
output += f"{(addr+i):14}: "
output += f"{byte:02x} "
return output
# Write a couple of 4-byte integers to the buffer
integer = c.cast(addr+0, c.POINTER(c.c_uint32)).contents
integer.value = 0x12345678
integer = c.cast(addr+4, c.POINTER(c.c_uint32)).contents
integer.value = 0xdeadbeef
integer = c.cast(addr+16, c.POINTER(c.c_uint32)).contents
integer.value = 0xcafebabe
# Write a couple of bytes to the buffer
byte = c.cast(addr+8, c.POINTER(c.c_uint8)).contents
byte.value = 0x01
byte = c.cast(addr+9, c.POINTER(c.c_uint8)).contents
byte.value = 0x02
byte = c.cast(addr+size-1, c.POINTER(c.c_uint8)).contents
byte.value = 0xFF
# The dump will show the integers we wrote. Note that Intel
# is a small-endian CPU, so the lowest weight bytes come first.
# So the byte order for an integer is reversed vs. how you write
# that integer in hex.
print(dump(addr, size))
# Get rid of the buffer
del buffer
# Now the dump will show junk
print(dump(addr, size))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment