Wednesday, October 14, 2015

Look before you leap

There are countless reasons to do unsafe memory access.  Here's some help:

import ctypes
import os

if hasattr(ctypes.cdll, "msvcrt"):  #windows branch
    _BUF = ctypes.create_string_buffer('a')


    def _check(address):
        try:
            ctypes.cdll.msvcrt.memcpy(_BUF, address, 1)
            return True
        except WindowsError:
            return False


else:
    libc = ctypes.CDLL('libc.so.6')
    libc.write.argtypes = ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t

    _BUF = open('/tmp/_buf', 'w')
    _FD = _BUF.fileno()
    os.unlink(_BUF)

    def _check(address):
        rc = libc.write(_FD, address, 1)
        _BUF.seek(0)
        return rc == 1


def is_valid_ptr(address):
    'determines if the passed address (integer) is a valid pointer'
    return _check(address)

No comments:

Post a Comment