Exemplo n.º 1
0
def compile_time_get_string_data(obj):
    """Get string data from a python string for use at compile-time to embed
    the string data into the LLVM module.
    """
    from ctypes import (
        CFUNCTYPE, c_void_p, c_int, c_uint, c_ssize_t, c_ubyte, py_object,
        POINTER, byref,
    )

    extract_unicode_fn = c_helpers['extract_unicode']
    proto = CFUNCTYPE(c_void_p, py_object, POINTER(c_ssize_t), POINTER(c_int),
                      POINTER(c_uint), POINTER(c_ssize_t))
    fn = proto(extract_unicode_fn)
    length = c_ssize_t()
    kind = c_int()
    is_ascii = c_uint()
    hashv = c_ssize_t()
    data = fn(obj, byref(length), byref(kind), byref(is_ascii), byref(hashv))
    if data is None:
        raise ValueError("cannot extract unicode data from the given string")
    length = length.value
    kind = kind.value
    is_ascii = is_ascii.value
    nbytes = (length + 1) * _kind_to_byte_width(kind)
    out = (c_ubyte * nbytes).from_address(data)
    return bytes(out), length, kind, is_ascii, hashv.value
Exemplo n.º 2
0
def compile_time_get_string_data(obj):
    """Get string data from a python string for use at compile-time to embed
    the string data into the LLVM module.
    """
    from ctypes import (
        CFUNCTYPE, c_void_p, c_int, c_uint, c_ssize_t, c_ubyte, py_object,
        POINTER, byref,
    )

    extract_unicode_fn = c_helpers['extract_unicode']
    proto = CFUNCTYPE(c_void_p, py_object, POINTER(c_ssize_t), POINTER(c_int),
                      POINTER(c_uint), POINTER(c_ssize_t))
    fn = proto(extract_unicode_fn)
    length = c_ssize_t()
    kind = c_int()
    is_ascii = c_uint()
    hashv = c_ssize_t()
    data = fn(obj, byref(length), byref(kind), byref(is_ascii), byref(hashv))
    if data is None:
        raise ValueError("cannot extract unicode data from the given string")
    length = length.value
    kind = kind.value
    is_ascii = is_ascii.value
    nbytes = (length + 1) * _kind_to_byte_width(kind)
    out = (c_ubyte * nbytes).from_address(data)
    return bytes(out), length, kind, is_ascii, hashv.value
Exemplo n.º 3
0
    def get(self):
        """Return solution statuses.

        Return number of iterations, stop criterion, initial residual, and
        final residual.

        """
        it = ctypes.c_ssize_t()
        st_cr = ctypes.c_ssize_t()
        r1 = ctypes.c_double()
        r2 = ctypes.c_double()
        status = API.nlsp_get(self._handle, it, st_cr, r1, r2)
        if status:
            raise IcsError(API.nlsp_get, status)
        return it.value, st_cr.value, r1.value, r2.value
Exemplo n.º 4
0
def BufferToAddress(buf):
  obj = ctypes.py_object(buf)
  address = ctypes.c_void_p()
  length = ctypes.c_ssize_t()
  ctypes.pythonapi.PyObject_AsReadBuffer(
      obj, ctypes.byref(address), ctypes.byref(length))
  return address.value
def sq_ass_item(obj, size, item):
    pyobj = PyObject.from_address(obj)
    old_refcnt = pyobj.ob_refcnt
    pyobj.ob_refcnt = 1
    ret =  libpython.PyTuple_SetItem(ctypes.c_void_p(obj), ctypes.c_ssize_t(size), ctypes.c_void_p(item))
    pyobj.ob_refcnt = old_refcnt
    return ret
Exemplo n.º 6
0
def address_of_buffer(buf):
    """Find the address of a buffer"""
    obj = ctypes.py_object(buf)
    address = ctypes.c_void_p()
    length = ctypes.c_ssize_t()
    ctypes.pythonapi.PyObject_AsReadBuffer(obj, ctypes.byref(address), ctypes.byref(length))
    return address.value
Exemplo n.º 7
0
def BufferToAddress(buf):
    obj = ctypes.py_object(buf)
    address = ctypes.c_void_p()
    length = ctypes.c_ssize_t()
    ctypes.pythonapi.PyObject_AsReadBuffer(obj, ctypes.byref(address),
                                           ctypes.byref(length))
    return address.value
Exemplo n.º 8
0
    def fetch(self):
        columns = self.check_columns()
        rows = []

        while True:
            for i in range(self.get_results_column_number()):
                column_name = columns[i]['name']
                column_type = columns[i]['type']
                column_size = columns[i]['size']
                rows.append({})
                rows[-1]['column_name'] = column_name
                column_buffer = ctypes.create_string_buffer(column_size)
                indicator = ctypes.c_ssize_t(column_size)
                self.SQLBindCol(self.cur_handle, i + 1, column_type,
                                ctypes.byref(column_buffer), column_size,
                                ctypes.byref(indicator))
                ctypes.memset(
                    ctypes.addressof(column_buffer) + indicator.value, 0, 1)
                rows[-1]['value'] = column_buffer
            rc = int(self.SQLFetch(self.cur_handle))
            if rc == SQL_SUCCESS or rc == SQL_SUCCESS_WITH_INFO:
                pass
            elif rc == NO_DATA:
                rows.pop(len(rows) - 1)
                break
            else:
                raise Exception("Query Failed {}".format(rc))
        for row in rows:
            print(row['column_name'], row['value'].raw.decode())
Exemplo n.º 9
0
def address_of_buffer(buf):
    """Find the address of a buffer"""
    obj = ctypes.py_object(buf)
    address = ctypes.c_void_p()
    length = ctypes.c_ssize_t()
    ctypes.pythonapi.PyObject_AsReadBuffer(obj, ctypes.byref(address),
                                           ctypes.byref(length))
    return address.value
Exemplo n.º 10
0
def read_c_ssize_t(hProcess, address):
    ReadBuffer = ctypes.c_ssize_t()
    lpBuffer = ctypes.byref(ReadBuffer)
    nSize = ctypes.sizeof(ReadBuffer)
    bytesRead = ctypes.c_ulong(0)

    ctypes.windll.kernel32.ReadProcessMemory(hProcess, address, lpBuffer,
                                             nSize, bytesRead)
    return ReadBuffer.value
Exemplo n.º 11
0
def buffer_info(buf, ptr_type = ctypes.c_void_p):
  """Given a python buffer, return its address and length"""

  assert isinstance(buf, buffer)
  address = ptr_type()
  length = ctypes.c_ssize_t()
  obj = ctypes.py_object(buf)
  ctypes.pythonapi.PyObject_AsReadBuffer(obj, ctypes.byref(address),
                                         ctypes.byref(length))
  return address, length.value
Exemplo n.º 12
0
def buffer_info(obj):
    '''
    A routine to get the memory address and size of the underlying buffer of
    for the type supporting the buffer interface.
    '''
    cobj = ctypes.py_object(obj)
    address = ctypes.c_void_p()
    length = ctypes.c_ssize_t()
    ctypes.pythonapi.PyObject_AsReadBuffer(cobj, ctypes.byref(address), ctypes.byref(length))
    return address.value, length.value
Exemplo n.º 13
0
def buffer_info(obj):
    '''
    A routine to get the memory address and size of the underlying buffer of
    for the type supporting the buffer interface.
    '''
    cobj = ctypes.py_object(obj)
    address = ctypes.c_void_p()
    length = ctypes.c_ssize_t()
    ctypes.pythonapi.PyObject_AsReadBuffer(cobj, ctypes.byref(address),
                                           ctypes.byref(length))
    return address.value, length.value
Exemplo n.º 14
0
    def update(self, data):
        # Passing a buffer/memoryview object via ctypes is inconvenient.  See
        # http://thread.gmane.org/gmane.comp.python.devel/134936/focus=134941
        buf = buffer(data)
        address = ctypes.c_void_p()
        length = ctypes.c_ssize_t()
        ctypes.pythonapi.PyObject_AsReadBuffer(
            ctypes.py_object(buf), ctypes.byref(address), ctypes.byref(length))
        assert length >= 0

        _libxxhash.XXH64_update(
            self._state, address, ctypes.c_size_t(length.value))
Exemplo n.º 15
0
    def update(self, data):
        # Passing a buffer/memoryview object via ctypes is inconvenient.  See
        # http://thread.gmane.org/gmane.comp.python.devel/134936/focus=134941
        buf = buffer(data)
        address = ctypes.c_void_p()
        length = ctypes.c_ssize_t()
        ctypes.pythonapi.PyObject_AsReadBuffer(ctypes.py_object(buf),
                                               ctypes.byref(address),
                                               ctypes.byref(length))
        assert length >= 0

        _libxxhash.XXH64_update(self._state, address,
                                ctypes.c_size_t(length.value))
Exemplo n.º 16
0
	def __init__(self):
		self.size_link = ctypes.sizeof(Link)
		self.size_context = ctypes.sizeof(Context)
		print("Size link {} context {} wchar {} float {}".format(self.size_link, self.size_context, ctypes.sizeof(ctypes.c_wchar), ctypes.sizeof(ctypes.c_float)))

		self.memfile = mmap.mmap(0, 5460, "MumbleLink", mmap.ACCESS_READ)
		self.memfile.seek(0)
		print("Memfile is closed? {}".format(self.memfile.closed))
		obj = ctypes.py_object(self.memfile)
		address = ctypes.c_void_p()
		length = ctypes.c_ssize_t()
		ctypes.pythonapi.PyObject_AsReadBuffer(obj, ctypes.byref(address), ctypes.byref(length))
		int_pointer = address.value
		print("Opened memfile at location {}".format(address))
Exemplo n.º 17
0
def test():
    import time
    import cv2
    print(
        ctypes.windll.user32.SetThreadDpiAwarenessContext(
            ctypes.c_ssize_t(-4)))
    hwnd = ctypes.windll.user32.FindWindowW(
        'com.android.settings',
        None)  # Documents UI window of Windows Subsystem for Android
    # hwnd = ctypes.windll.user32.FindWindowW('CabinetWClass', None)  # random explorer window
    title = f"screenshot for window {hwnd}"
    cv2.namedWindow(title)
    print(title)
    session = CaptureSession()
    state_box = [None, False, False]  # frame, changed, stop

    def frame_callback(session):
        frame = session.get_frame()
        if frame is None:
            return
        state_box[0] = frame
        state_box[1] = True

    def close_callback(session):
        state_box[2] = True

    session.frame_callback = frame_callback
    session.close_callback = close_callback
    session.start(hwnd, False)
    # time.sleep(2)
    # t0 = time.perf_counter()
    # frame = session.get_frame()
    # t1 = time.perf_counter()
    # print('captured image of shape', frame.shape, 'in', t1-t0, 's')
    # cv2.imshow(title, frame)
    while not state_box[2]:
        if state_box[1]:
            state_box[1] = False
            cv2.imshow(title, state_box[0].array)
        key = cv2.waitKey(16)
        try:
            if key == 27 or cv2.getWindowProperty(title,
                                                  cv2.WND_PROP_VISIBLE) != 1:
                break
        except:
            break
    session.stop()

    cv2.destroyAllWindows()
Exemplo n.º 18
0
    def update(self, data):
        # Passing a buffer/memoryview object via ctypes is inconvenient.  See
        # http://thread.gmane.org/gmane.comp.python.devel/134936/focus=134941
        if sys.version_info.major == 2:  # Python 2
            buf = buffer(data)  # pylint:disable=undefined-variable
        else:  # Python 3
            buf = memoryview(data)
        address = ctypes.c_void_p()
        length = ctypes.c_ssize_t()
        ctypes.pythonapi.PyObject_AsReadBuffer(ctypes.py_object(buf),
                                               ctypes.byref(address),
                                               ctypes.byref(length))
        assert length.value >= 0

        _libxxhash.XXH64_update(self._state, address,
                                ctypes.c_size_t(length.value))
Exemplo n.º 19
0
 def _bindcol(self, col_num):
     """Get col description and then bind the col"""
     col_name = ctypes.create_string_buffer(256)
     col_name_size = ctypes.c_short()
     col_type = ctypes.c_short()
     col_type_size = ctypes.c_ssize_t()
     col_dec_digits = ctypes.c_short()
     col_nullable = ctypes.c_short()
     rc = self.conn.api.SQLDescribeColW(
         self.handle, col_num, ctypes.byref(col_name),
         ctypes.sizeof(col_name), ctypes.byref(col_name_size),
         ctypes.byref(col_type), ctypes.byref(col_type_size),
         ctypes.byref(col_dec_digits), ctypes.byref(col_nullable))
     check_error(self, rc, 'request col {}'.format(col_num))
     col_name_decoded = col_name[:col_name_size.value*2].decode('utf_16_le')
     nullable = bool(1-col_nullable.value)
     # print('col #{} name: {}, type: {}, size: {} nullable: {}'.format(
     #     col_num, col_name_decoded, col_type.value, col_type_size.value,
     #     nullable))
     c_col_type = SQL_TYPE_MAP[col_type.value]
     charsize = None
     is_char_array = False
     is_fixed_width = False
     if col_type.value in ALL_SQL_CHAR:
         is_char_array = True
         c_col_type = ctypes.c_char
         charsize = col_type_size.value + 1
         if col_type.value in (SQL_CHAR, SQL_WCHAR):
             is_fixed_width = True
             col_type.value = SQL_CHAR
         elif col_type.value in (SQL_WCHAR, SQL_WVARCHAR, SQL_WLONGVARCHAR):
             # ODBC Unicode != utf-8; can't use the ctypes c_wchar
             charsize = col_type_size.value * 2 + 2
             col_type.value = SQL_WCHAR
         col_buff = ((c_col_type * charsize) * self.arraysize)()
     else:
         col_buff = (c_col_type * self.arraysize)()
     if col_type.value == SQL_BIGINT:
         col_type.value = -25  # SQL_C_BIGINT
     col_indicator = (ctypes.c_ssize_t * self.arraysize)()
     self.return_buffer.append((col_num, col_buff, col_indicator,
                                is_char_array, is_fixed_width, nullable))
     # Bind the column
     rc = self.conn.api.SQLBindCol(self.handle, col_num, col_type.value,
                                   ctypes.byref(col_buff), charsize,
                                   ctypes.byref(col_indicator))
     check_error(self, rc, 'bind col {}'.format(col_num))
Exemplo n.º 20
0
# License along with this library; If not, see <http://www.gnu.org/licenses/>.
#
# Author: Gris Ge <*****@*****.**>
#         Nir Soffer <*****@*****.**>

import json
import socket
import ctypes
import sys
import struct

_API_VERSION_MAJOR = 0

_IPC_ADDR = "\0/org/kernel/linux/storage/multipathd"

_IPC_LEN_SIZE = ctypes.sizeof(ctypes.c_ssize_t(0))

if sys.version_info[0] < 3:
    _CMD_HEAD = struct.Struct("q" if _IPC_LEN_SIZE == 8 else "i")
else:
    _CMD_HEAD = struct.Struct("n")


class DMMP_path(object):
    """
    DMMP_pathgroup is the abstraction of path in multipath-tools.
    """
    def __init__(self, path):
        """
        Internal function. For mpaths_get() only.
        """
Exemplo n.º 21
0
#
# Author: Gris Ge <*****@*****.**>
#         Nir Soffer <*****@*****.**>

import json
import socket
import ctypes
import sys
import struct


_API_VERSION_MAJOR = 0

_IPC_ADDR = "\0/org/kernel/linux/storage/multipathd"

_IPC_LEN_SIZE = ctypes.sizeof(ctypes.c_ssize_t(0))

if sys.version_info[0] < 3:
    _CMD_HEAD = struct.Struct("q" if _IPC_LEN_SIZE == 8 else "i")
else:
    _CMD_HEAD = struct.Struct("n")


class DMMP_path(object):
    """
    DMMP_pathgroup is the abstraction of path in multipath-tools.
    """
    def __init__(self, path):
        """
        Internal function. For mpaths_get() only.
        """
Exemplo n.º 22
0
def main():
    nGpus = ctypes.c_int()
    name = b' ' * 100
    cc_major = ctypes.c_int()
    cc_minor = ctypes.c_int()
    cores = ctypes.c_int()
    threads_per_core = ctypes.c_int()
    clockrate = ctypes.c_int()
    freeMem = ctypes.c_ssize_t()
    totalMem = ctypes.c_ssize_t()
    #freeMem = ctypes.c_size_t()
    #totalMem = ctypes.c_size_t()

    result = ctypes.c_int()
    device = ctypes.c_int()
    context = ctypes.c_void_p()
    error_str = ctypes.c_char_p()

    result = cuda.cuInit(0)
    if result != CUDA_SUCCESS:
        cuda.cuGetErrorString(result, ctypes.byref(error_str))
        print("cuInit failed with error code %d: %s" % (result, error_str.value.decode()))
        return 1
    result = cuda.cuDeviceGetCount(ctypes.byref(nGpus))
    if result != CUDA_SUCCESS:
        cuda.cuGetErrorString(result, ctypes.byref(error_str))
        print("cuDeviceGetCount failed with error code %d: %s" % (result, error_str.value.decode()))
        return 1
    print("Found %d device(s)." % nGpus.value)
    for i in range(nGpus.value):
        result = cuda.cuDeviceGet(ctypes.byref(device), i)
        if result != CUDA_SUCCESS:
            cuda.cuGetErrorString(result, ctypes.byref(error_str))
            print("cuDeviceGet failed with error code %d: %s" % (result, error_str.value.decode()))
            return 1
        print("Device: %d" % i)
        if cuda.cuDeviceGetName(ctypes.c_char_p(name), len(name), device) == CUDA_SUCCESS:
            print("  Name: %s" % (name.split(b'\0', 1)[0].decode()))
        if cuda.cuDeviceComputeCapability(ctypes.byref(cc_major), ctypes.byref(cc_minor), device) == CUDA_SUCCESS:
            print("  Compute Capability: %d.%d" % (cc_major.value, cc_minor.value))
        if cuda.cuDeviceGetAttribute(ctypes.byref(cores), CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, device) == CUDA_SUCCESS:
            print("  Multiprocessors: %d" % cores.value)
            print("  CUDA Cores: %d" % (cores.value * ConvertSMVer2Cores(cc_major.value, cc_minor.value)))
            if cuda.cuDeviceGetAttribute(ctypes.byref(threads_per_core), CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, device) == CUDA_SUCCESS:
                print("  Concurrent threads: %d" % (cores.value * threads_per_core.value))
        if cuda.cuDeviceGetAttribute(ctypes.byref(clockrate), CU_DEVICE_ATTRIBUTE_CLOCK_RATE, device) == CUDA_SUCCESS:
            print("  GPU clock: %g MHz" % (clockrate.value / 1000.))
        if cuda.cuDeviceGetAttribute(ctypes.byref(clockrate), CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, device) == CUDA_SUCCESS:
            print("  Memory clock: %g MHz" % (clockrate.value / 1000.))
        result = cuda.cuCtxCreate(ctypes.byref(context), 0, device)
        if result != CUDA_SUCCESS:
            cuda.cuGetErrorString(result, ctypes.byref(error_str))
            print("cuCtxCreate failed with error code %d: %s" % (result, error_str.value.decode()))
        else:
            result = cuda.cuMemGetInfo(ctypes.byref(freeMem), ctypes.byref(totalMem))
            if result == CUDA_SUCCESS:
                print("  Total Memory: %ld MiB" % (totalMem.value / 1024**2))
                print("  Free Memory: %ld MiB" % (freeMem.value / 1024**2))
            else:
                cuda.cuGetErrorString(result, ctypes.byref(error_str))
                print("cuMemGetInfo failed with error code %d: %s" % (result, error_str.value.decode()))
            cuda.cuCtxDetach(context)
    return 0
Exemplo n.º 23
0
    a['TextIOBaseType'] = io.TextIOBase()
    a['BufferedIOBaseType'] = io.BufferedIOBase()
    a['UnicodeIOType'] = TextIO() # the new StringIO
    a['LoggingAdapterType'] = logging.LoggingAdapter(_logger,_dict) # pickle ok
    if HAS_CTYPES:
        a['CBoolType'] = ctypes.c_bool(1)
        a['CLongDoubleType'] = ctypes.c_longdouble()
except ImportError:
    pass
try: # python 2.7
    import argparse
    # data types (CH 8)
    a['OrderedDictType'] = collections.OrderedDict(_dict)
    a['CounterType'] = collections.Counter(_dict)
    if HAS_CTYPES:
        a['CSSizeTType'] = ctypes.c_ssize_t()
    # generic operating system services (CH 15)
    a['NullHandlerType'] = logging.NullHandler() # pickle ok  # new 2.7
    a['ArgParseFileType'] = argparse.FileType() # pickle ok
#except AttributeError:
except ImportError:
    pass

# -- pickle fails on all below here -----------------------------------------
# types module (part of CH 8)
a['CodeType'] = compile('','','exec')
a['DictProxyType'] = type.__dict__
a['DictProxyType2'] = _newclass.__dict__
a['EllipsisType'] = Ellipsis
a['ClosedFileType'] = open(os.devnull, 'wb', buffering=0).close()
a['GetSetDescriptorType'] = array.array.typecode
Exemplo n.º 24
0
    a["BufferedIOBaseType"] = io.BufferedIOBase()
    a["UnicodeIOType"] = TextIO()  # the new StringIO
    a["LoggingAdapterType"] = logging.LoggingAdapter(_logger, _dict)  # pickle ok
    if HAS_CTYPES:
        a["CBoolType"] = ctypes.c_bool(1)
        a["CLongDoubleType"] = ctypes.c_longdouble()
except ImportError:
    pass
try:  # python 2.7
    import argparse

    # data types (CH 8)
    a["OrderedDictType"] = collections.OrderedDict(_dict)
    a["CounterType"] = collections.Counter(_dict)
    if HAS_CTYPES:
        a["CSSizeTType"] = ctypes.c_ssize_t()
    # generic operating system services (CH 15)
    a["NullHandlerType"] = logging.NullHandler()  # pickle ok  # new 2.7
    a["ArgParseFileType"] = argparse.FileType()  # pickle ok
# except AttributeError:
except ImportError:
    pass

# -- pickle fails on all below here -----------------------------------------
# types module (part of CH 8)
a["CodeType"] = compile("", "", "exec")
a["DictProxyType"] = type.__dict__
a["DictProxyType2"] = _newclass.__dict__
a["EllipsisType"] = Ellipsis
a["ClosedFileType"] = open(os.devnull, "wb", buffering=0).close()
a["GetSetDescriptorType"] = array.array.typecode
Exemplo n.º 25
0
def write_c_ssize_t(hProcess, address, value):
    ctypes.windll.kernel32.WriteProcessMemory(
        hProcess, address, ctypes.byref(ctypes.c_ssize_t(value)),
        ctypes.sizeof(ctypes.c_ssize_t(value)), ctypes.c_ulong(0))
Exemplo n.º 26
0
 def get_column_size(self, i):
     col_size = ctypes.c_ssize_t(0)
     self.SQLColAttribute(self.cur_handle, i + 1, 1003,
                          ctypes.byref(ctypes.create_string_buffer(10)), 10,
                          ctypes.c_short(), ctypes.byref(col_size))
     return col_size.value
Exemplo n.º 27
0
from immutables._testutils import HashKey

none_hash = map_hash(None)
assert (none_hash != 1)
assert (none_hash.bit_length() <= 32)

none_hash_u = ctypes.c_size_t(none_hash).value
not_collision = 0xffffffff & (~none_hash_u)

mask = 0x7ffffffff
none_collisions = [
    none_hash_u & (mask >> shift) for shift in reversed(range(0, 32, 5))
]
assert (len(none_collisions) == 7)
none_collisions = [
    ctypes.c_ssize_t(h | (not_collision & (mask << shift))).value
    for shift, h in zip(range(5, 37, 5), none_collisions)
]


class NoneCollision(HashKey):
    def __init__(self, name, level):
        if name is None:
            raise ValueError("Can't have a NoneCollision with a None value")
        super().__init__(none_collisions[level], name)

    def __eq__(self, other):
        if other is None:
            return False
        return super().__eq__(other)
Exemplo n.º 28
0
 def close(self) -> None:
     self._driver.instantiate(c_long(cInstNotification),
                              c_long(cNotifyRemoveCallback), c_ssize_t(0),
                              c_long(0))
Exemplo n.º 29
0
    def __init__(self, startup_timeout_msecs: int = 20000):
        """Initialise a connection to the WLM server application, starting it if
        necessary.

        :param startup_timeout_msecs: The maximum amount of time the constructor
            will block waiting for the server application to start up, in
            milliseconds. An exception will be thrown if the application has not
            been initialised successfully by then. Note that the server takes
            several seconds to initialise the device on startup.
        """
        self._result_callbacks = []
        self._result_callbacks_lock = threading.Lock()

        # We get notified when auto-calibration starts and end, so we can ignore
        # callback events in between.
        self._calibration_active = False

        self._driver = Driver()

        is_running = self._driver.instantiate(c_long(cInstCheckForWLM),
                                              c_long(0), c_ssize_t(0),
                                              c_long(0))
        if not is_running:
            self._log.info(
                "HighFinesse WLM application not running; starting via DLL.")

            # TODO: Expose LSA selection ("App" or "Ver" parameter) to user.
            wlm_started = self._driver.control_wlm_ex(
                cCtrlWLMShow | cCtrlWLMWait, 0, 0, startup_timeout_msecs, 1)
            if wlm_started == 0:
                raise WlmDataException(
                    "Timed out waiting for LSA WLM application to start.")

        wlm_type = self._driver.get_wlm_version(0)
        if wlm_type != 5:
            raise WlmDataException("Expected WLM version type 5 for LSA.")
        self._device_version = self._driver.get_wlm_version(1)
        wlm_revision = self._driver.get_wlm_version(2)
        wlm_compilation = self._driver.get_wlm_version(3)
        self._log.info(
            "Interface to WLM application initialised (ver. %s, rev. %s.%s).",
            self._device_version, wlm_revision, wlm_compilation)

        if self._driver.get_channels_count(0) != 1:
            raise WlmDataException("More than one LSA channel detected, "
                                   "currently not supported in client code.")

        # The Python ctypes documentation is woefully imprecise here, but it
        # seems logical that we need to keep the callback object itself alive
        # for as long as it is used from C code, not the CFUNCTYPE return value.
        callback_type = CFUNCTYPE(None, c_long, c_long, c_long, c_double,
                                  c_long)
        self._c_callback = callback_type(
            lambda *args: self._callback_ex(*args))
        self._driver.instantiate(c_long(cInstNotification),
                                 c_long(cNotifyInstallCallbackEx),
                                 self._c_callback, c_long(0))

        # Make analysis data arrays available to this process (this is distinct
        # from the analysis mode).
        self._driver.set_analysis(cSignalAnalysis, 1)
Exemplo n.º 30
0

rx, tx = socketpair()
pid = fork()
if pid == 0:
    del tx  # child
    while True:
        buf = rx.recv(sizeof(c_ssize_t))
        expected = c_ssize_t.from_buffer_copy(buf)
        if expected.value == -1:
            print("child exiting")
            break

        jar = rx.recv(expected.value)
        print(f"<- {loads(jar)}[{expected.value}]")

else:
    del rx  # parent
    # Can't send lambdas, must presumably share Decls with reciever
    data = [{"abc": 1, "def": 2}, A(255, 300), f]
    for datum in data:
        jar = dumps(datum)
        sent = c_ssize_t(len(jar))
        tx.send(sent)
        tx.send(jar)
        print(f"-> {datum}[{sent.value}]")

    tx.send(c_ssize_t(-1))
    print("-> [-1]")
    print("Terminated comms")
Exemplo n.º 31
0
if __name__ == '__main__':

    if len(sys.argv) != 2:
        print("Usage fr_spy.py binary");
        sys.exit(1)

    statinfo = os.stat(sys.argv[1])
    filesize = statinfo.st_size
    print(filesize)

    f = open(sys.argv[1], "rb")
    buf = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)
    obj = ctypes.py_object(buf)
    address = ctypes.c_void_p()
    length = ctypes.c_ssize_t()
    ctypes.pythonapi.PyObject_AsReadBuffer(obj, ctypes.byref(address), ctypes.byref(length))
    ptr = address.value
    print(ptr)

    flushandreload_nasm_code = """
        mfence
        rdtsc
        shl   rdx, 32
        or    rax, rdx
        mfence
        mov   rcx, rax  ; Save rax
        mov   rbx, {ptr}
        mov   rax, [rbx]
        mfence
        rdtsc
Exemplo n.º 32
0
    a['BufferedIOBaseType'] = io.BufferedIOBase()
    a['UnicodeIOType'] = TextIO()  # the new StringIO
    a['LoggingAdapterType'] = logging.LoggingAdapter(_logger,
                                                     _dict)  # pickle ok
    if HAS_CTYPES:
        a['CBoolType'] = ctypes.c_bool(1)
        a['CLongDoubleType'] = ctypes.c_longdouble()
except ImportError:
    pass
try:  # python 2.7
    import argparse
    # data types (CH 8)
    a['OrderedDictType'] = collections.OrderedDict(_dict)
    a['CounterType'] = collections.Counter(_dict)
    if HAS_CTYPES:
        a['CSSizeTType'] = ctypes.c_ssize_t()
    # generic operating system services (CH 15)
    a['NullHandlerType'] = logging.NullHandler()  # pickle ok  # new 2.7
    a['ArgParseFileType'] = argparse.FileType()  # pickle ok
except (AttributeError, ImportError):
    pass

# -- pickle fails on all below here -----------------------------------------
# types module (part of CH 8)
a['CodeType'] = compile('', '', 'exec')
a['DictProxyType'] = type.__dict__
a['DictProxyType2'] = _newclass.__dict__
a['EllipsisType'] = Ellipsis
a['ClosedFileType'] = open(os.devnull, 'wb', buffering=0).close()
a['GetSetDescriptorType'] = array.array.typecode
a['LambdaType'] = _lambda = lambda x: lambda y: x  #XXX: works when not imported!
Exemplo n.º 33
0
 def get_column_type(self, i):
     col_type = ctypes.c_ssize_t(0)
     self.SQLColAttribute(self.cur_handle, i + 1, 2,
                          ctypes.byref(ctypes.create_string_buffer(10)), 10,
                          ctypes.c_short(), ctypes.byref(col_type))
     return SqlColTypeEnum(col_type.value).actual