Python ctypes.c_uint32() Examples

The following are 30 code examples of ctypes.c_uint32(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ctypes , or try the search function .
Example #1
Source File: test_dtype.py    From recruit with Apache License 2.0 8 votes vote down vote up
def test_union_with_struct_packed(self):
        class Struct(ctypes.Structure):
            _pack_ = 1
            _fields_ = [
                ('one', ctypes.c_uint8),
                ('two', ctypes.c_uint32)
            ]

        class Union(ctypes.Union):
            _fields_ = [
                ('a', ctypes.c_uint8),
                ('b', ctypes.c_uint16),
                ('c', ctypes.c_uint32),
                ('d', Struct),
            ]
        expected = np.dtype(dict(
            names=['a', 'b', 'c', 'd'],
            formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],
            offsets=[0, 0, 0, 0],
            itemsize=ctypes.sizeof(Union)
        ))
        self.check(Union, expected) 
Example #2
Source File: darwin.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def platformSetRegCtx(self, tid, ctx):

        state = STRUCT_X86_THREAD_STATE64()

        # Sync up a struct first...
        scount = ctypes.c_uint32(ctypes.sizeof(state) / 8)
        ret = self.libc.thread_get_state(tid, x86_THREAD_STATE64, addrof(state), addrof(scount));
        if ret != 0:
            raise Exception('thread_get_state (THREAD_STATE64) failed: 0x%.8x' % ret)

        # Export our shit into it...
        ctx._rctx_Export(state)

        scount = ctypes.sizeof(state) / 8
        r = self.libc.thread_set_state(tid, x86_THREAD_STATE64, addrof(state), scount)
        if r != 0:
            raise Exception('thread_set_state (THREAD_STATE64) failed: 0x%.8x' % r)

        state = STRUCT_X86_DEBUG_STATE64()
        ctx._rctx_Export(state)
        scount = ctypes.sizeof(state) / 8
        r = self.libc.thread_set_state(tid, x86_DEBUG_STATE64, addrof(state), scount)
        if r != 0:
            raise Exception('thread_set_state (DEBUG_STATE64) failed: 0x%.8x' % r) 
Example #3
Source File: emake.py    From emake with GNU General Public License v2.0 6 votes vote down vote up
def pathshort (self, path):
		path = os.path.abspath(path)
		if self.unix:
			return path
		if not self.GetShortPathName:
			self.kernel32 = None
			self.textdata = None
			try:
				import ctypes
				self.kernel32 = ctypes.windll.LoadLibrary("kernel32.dll")
				self.textdata = ctypes.create_string_buffer('\000' * 1024)
				self.GetShortPathName = self.kernel32.GetShortPathNameA
				args = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int ]
				self.GetShortPathName.argtypes = args
				self.GetShortPathName.restype = ctypes.c_uint32
			except: pass
		if not self.GetShortPathName:
			return path
		retval = self.GetShortPathName(path, self.textdata, 1024)
		shortpath = self.textdata.value
		if retval <= 0:
			return ''
		return shortpath
	
	# 读取ini文件 
Example #4
Source File: firefox_decrypt.py    From firefox_decrypt with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        # Locate libnss and try loading it
        self.NSS = None
        self.load_libnss()

        SlotInfoPtr = ct.POINTER(self.PK11SlotInfo)
        SECItemPtr = ct.POINTER(self.SECItem)

        self._set_ctypes(ct.c_int, "NSS_Init", ct.c_char_p)
        self._set_ctypes(ct.c_int, "NSS_Shutdown")
        self._set_ctypes(SlotInfoPtr, "PK11_GetInternalKeySlot")
        self._set_ctypes(None, "PK11_FreeSlot", SlotInfoPtr)
        self._set_ctypes(ct.c_int, "PK11_CheckUserPassword", SlotInfoPtr, ct.c_char_p)
        self._set_ctypes(ct.c_int, "PK11SDR_Decrypt", SECItemPtr, SECItemPtr, ct.c_void_p)
        self._set_ctypes(None, "SECITEM_ZfreeItem", SECItemPtr, ct.c_int)

        # for error handling
        self._set_ctypes(ct.c_int, "PORT_GetError")
        self._set_ctypes(ct.c_char_p, "PR_ErrorToName", ct.c_int)
        self._set_ctypes(ct.c_char_p, "PR_ErrorToString", ct.c_int, ct.c_uint32) 
Example #5
Source File: test_dtype.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_union_with_struct_packed(self):
        class Struct(ctypes.Structure):
            _pack_ = 1
            _fields_ = [
                ('one', ctypes.c_uint8),
                ('two', ctypes.c_uint32)
            ]

        class Union(ctypes.Union):
            _fields_ = [
                ('a', ctypes.c_uint8),
                ('b', ctypes.c_uint16),
                ('c', ctypes.c_uint32),
                ('d', Struct),
            ]
        expected = np.dtype(dict(
            names=['a', 'b', 'c', 'd'],
            formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],
            offsets=[0, 0, 0, 0],
            itemsize=ctypes.sizeof(Union)
        ))
        self.check(Union, expected) 
Example #6
Source File: test_ctypeslib.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_padded_union(self):
        dt = np.dtype(dict(
            names=['a', 'b'],
            offsets=[0, 0],
            formats=[np.uint16, np.uint32],
            itemsize=5,
        ))

        ct = np.ctypeslib.as_ctypes_type(dt)
        assert_(issubclass(ct, ctypes.Union))
        assert_equal(ctypes.sizeof(ct), dt.itemsize)
        assert_equal(ct._fields_, [
            ('a', ctypes.c_uint16),
            ('b', ctypes.c_uint32),
            ('', ctypes.c_char * 5),  # padding
        ]) 
Example #7
Source File: test_dtype.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_large_packed_structure(self):
        class PackedStructure(ctypes.Structure):
            _pack_ = 2
            _fields_ = [
                ('a', ctypes.c_uint8),
                ('b', ctypes.c_uint16),
                ('c', ctypes.c_uint8),
                ('d', ctypes.c_uint16),
                ('e', ctypes.c_uint32),
                ('f', ctypes.c_uint32),
                ('g', ctypes.c_uint8)
                ]
        expected = np.dtype(dict(
            formats=[np.uint8, np.uint16, np.uint8, np.uint16, np.uint32, np.uint32, np.uint8 ],
            offsets=[0, 2, 4, 6, 8, 12, 16],
            names=['a', 'b', 'c', 'd', 'e', 'f', 'g'],
            itemsize=18))
        self.check(PackedStructure, expected) 
Example #8
Source File: test_ctypeslib.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_padded_union(self):
        dt = np.dtype(dict(
            names=['a', 'b'],
            offsets=[0, 0],
            formats=[np.uint16, np.uint32],
            itemsize=5,
        ))

        ct = np.ctypeslib.as_ctypes_type(dt)
        assert_(issubclass(ct, ctypes.Union))
        assert_equal(ctypes.sizeof(ct), dt.itemsize)
        assert_equal(ct._fields_, [
            ('a', ctypes.c_uint16),
            ('b', ctypes.c_uint32),
            ('', ctypes.c_char * 5),  # padding
        ]) 
Example #9
Source File: messages.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _ar_arsdk_encode_type_info(cls, ar_argtype):
        arsdk_encode_type_info_map = {
            arsdkparser.ArArgType.I8: (od.ARSDK_ARG_TYPE_I8, "i8", ctypes.c_int8),
            arsdkparser.ArArgType.U8: (od.ARSDK_ARG_TYPE_U8, "u8", ctypes.c_uint8),
            arsdkparser.ArArgType.I16: (od.ARSDK_ARG_TYPE_I16, "i16", ctypes.c_int16),
            arsdkparser.ArArgType.U16: (od.ARSDK_ARG_TYPE_U16, "u16", ctypes.c_uint16),
            arsdkparser.ArArgType.I32: (od.ARSDK_ARG_TYPE_I32, "i32", ctypes.c_int32),
            arsdkparser.ArArgType.U32: (od.ARSDK_ARG_TYPE_U32, "u32", ctypes.c_uint32),
            arsdkparser.ArArgType.I64: (od.ARSDK_ARG_TYPE_I64, "i64", ctypes.c_int64),
            arsdkparser.ArArgType.U64: (od.ARSDK_ARG_TYPE_U64, "u64", ctypes.c_uint64),
            arsdkparser.ArArgType.FLOAT: (od.ARSDK_ARG_TYPE_FLOAT, "f32", ctypes.c_float),
            arsdkparser.ArArgType.DOUBLE: (od.ARSDK_ARG_TYPE_DOUBLE, "f64", ctypes.c_double),
            arsdkparser.ArArgType.STRING: (od.ARSDK_ARG_TYPE_STRING, "cstr", od.char_pointer_cast),
            arsdkparser.ArArgType.ENUM: (od.ARSDK_ARG_TYPE_ENUM, "i32", ctypes.c_int32),
        }
        return arsdk_encode_type_info_map[ar_argtype] 
Example #10
Source File: term.py    From xyppy with MIT License 6 votes vote down vote up
def getch_impl():
    # TODO: This windows impl keeps pipes/redirects from working. Need ReadFile for that,
    # with more complicated handling (personally, I'm just going to keep using unix/cygwin
    # for pipe-y debug stuff...)
    # TODO: Windows escape seqs via ReadConsoleInput, convert to VT100 seqs for more commonality.
    if is_windows:
        stdin_handle = ctypes.windll.kernel32.GetStdHandle(ctypes.c_ulong(-10))
        one_char_buf = ctypes.c_uint32()
        chars_read = ctypes.c_uint32()
        # NOTE: W version of this function == ERROR_NOACCESS after text color set in photopia!?
        result = ctypes.windll.kernel32.ReadConsoleA(stdin_handle,
                                                     ctypes.byref(one_char_buf),
                                                     1,
                                                     ctypes.byref(chars_read),
                                                     0)

        if result == 0 or chars_read.value != 1:
            last_err = ctypes.windll.kernel32.GetLastError()
            print('LAST ERR', last_err)
            err('failed to read console')

        return chr(one_char_buf.value)
    else: #Unix
        return sys.stdin.read(1) 
Example #11
Source File: utils_net.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def get_netmask(self):
        """
        Get ip network netmask
        """
        if not CTYPES_SUPPORT:
            raise exceptions.TestSkipError("Getting the netmask requires "
                                           "python > 2.4")
        ifreq = struct.pack('16sH14s', self.name.encode(),
                            socket.AF_INET, b'\x00' * 14)
        try:
            res = fcntl.ioctl(sockfd, arch.SIOCGIFNETMASK, ifreq)
        except IOError:
            return 0
        netmask = socket.ntohl(struct.unpack('16sH2xI8x', res)[2])

        return 32 - int(math.log(ctypes.c_uint32(~netmask).value + 1, 2)) 
Example #12
Source File: terminal.py    From terminal with MIT License 6 votes vote down vote up
def win32_path_short (self, path):
		if not path:
			return ''
		path = os.path.abspath(path)
		if self.unix:
			return path
		self._win32_load_kernel()
		if not self.GetShortPathName:
			try:
				import ctypes
				self.GetShortPathName = self.kernel32.GetShortPathNameA
				args = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32 ]
				self.GetShortPathName.argtypes = args
				self.GetShortPathName.restype = ctypes.c_uint32
			except: pass
		if not self.GetShortPathName:
			return path
		retval = self.GetShortPathName(path, self.textdata, 2048)
		shortpath = self.textdata.value
		if retval <= 0:
			import ctypes
			print 'ERROR(%d): %s'%(ctypes.GetLastError(), path)
			return ''
		return shortpath 
Example #13
Source File: terminal.py    From terminal with MIT License 6 votes vote down vote up
def win32_path_full (self, path):
		if not path:
			return ''
		path = os.path.abspath(path)
		if self.unix:
			return path
		self._win32_load_kernel()
		if not self.GetFullPathName:
			try:
				import ctypes
				self.GetFullPathName = self.kernel32.GetFullPathNameA
				args = [ ctypes.c_char_p, ctypes.c_int32, ctypes.c_char_p ]
				self.GetFullPathName.argtypes = args + [ctypes.c_char_p]
				self.GetFullPathName.restype = ctypes.c_uint32
			except: pass
		if not self.GetFullPathName:
			return path
		retval = self.GetFullPathName(path, 2048, self.textdata, None)
		fullpath = self.textdata.value
		if retval <= 0:
			return ''
		return fullpath

	# win32 get long pathname 
Example #14
Source File: terminal.py    From terminal with MIT License 6 votes vote down vote up
def win32_path_long (self, path):
		if not path:
			return ''
		path = os.path.abspath(path)
		if self.unix:
			return path
		self._win32_load_kernel()
		if not self.GetLongPathName:
			try:
				import ctypes
				self.GetLongPathName = self.kernel32.GetLongPathNameA
				args = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32 ]
				self.GetLongPathName.argtypes = args
				self.GetLongPathName.restype = ctypes.c_uint32
			except: pass
		if not self.GetLongPathName:
			return path
		retval = self.GetLongPathName(path, self.textdata, 2048)
		longpath = self.textdata.value
		if retval <= 0:
			return ''
		return longpath 
Example #15
Source File: pcl_helper.py    From Attentional-PointNet with GNU General Public License v3.0 6 votes vote down vote up
def float_to_rgb(float_rgb):
    """ Converts a packed float RGB format to an RGB list

        Args:
            float_rgb: RGB value packed as a float

        Returns:
            color (list): 3-element list of integers [0-255,0-255,0-255]
    """
    s = struct.pack('>f', float_rgb)
    i = struct.unpack('>l', s)[0]
    pack = ctypes.c_uint32(i).value

    r = (pack & 0x00FF0000) >> 16
    g = (pack & 0x0000FF00) >> 8
    b = (pack & 0x000000FF)

    color = [r,g,b]

    return color 
Example #16
Source File: library.py    From picosdk-python-wrappers with ISC License 6 votes vote down vote up
def _python_get_unit_info(self, handle, info_type):
        string_size = 255
        info = self._create_empty_string_buffer()
        if len(self._get_unit_info.argtypes) == 4:
            info_len = self._get_unit_info(c_int16(handle), info, c_int16(string_size), c_int16(info_type))
            if info_len > 0:
                return info.value[:info_len]
        elif len(self._get_unit_info.argtypes) == 5:
            required_size = c_int16(0)
            status = self._get_unit_info(c_int16(handle),
                                         info,
                                         c_int16(string_size),
                                         byref(required_size),
                                         c_uint32(info_type))
            if status == self.PICO_STATUS['PICO_OK']:
                if required_size.value < string_size:
                    return info.value[:required_size.value]
        return "" 
Example #17
Source File: pcl_helper.py    From Attentional-PointNet with GNU General Public License v3.0 6 votes vote down vote up
def float_to_rgb(float_rgb):
    """ Converts a packed float RGB format to an RGB list

        Args:
            float_rgb: RGB value packed as a float

        Returns:
            color (list): 3-element list of integers [0-255,0-255,0-255]
    """
    s = struct.pack('>f', float_rgb)
    i = struct.unpack('>l', s)[0]
    pack = ctypes.c_uint32(i).value

    r = (pack & 0x00FF0000) >> 16
    g = (pack & 0x0000FF00) >> 8
    b = (pack & 0x000000FF)

    color = [r,g,b]

    return color 
Example #18
Source File: catalog1.py    From fcatalog_server with GNU General Public License v3.0 6 votes vote down vote up
def sign(self,data,num_perms):
        """
        Sign data using <num_perms> permutations.
        """
        if len(data) < 4:
            raise Catalog1Error('data must be at least of size 4 bytes.')

        arr_perms = ctypes.c_uint32 * num_perms
        # Initialize array for return value:
        s = arr_perms()
        res = self._csign(data,len(data),s,num_perms)

        if res != 0:
            raise Catalog1Error(\
                    'Error number: {} when calling sign()'.format(res))

        return list(s)


# Initialize one instance for this module: 
Example #19
Source File: library.py    From picosdk-python-wrappers with ISC License 6 votes vote down vote up
def set_null_trigger(self, device):
        auto_trigger_after_millis = 1
        if hasattr(self, '_set_trigger') and len(self._set_trigger.argtypes) == 6:
            PS2000_NONE = 5
            return_code = self._set_trigger(c_int16(device.handle),
                                            c_int16(PS2000_NONE),
                                            c_int16(0),
                                            c_int16(0),
                                            c_int16(0),
                                            c_int16(auto_trigger_after_millis))
            if return_code == 0:
                raise InvalidTriggerParameters()
        elif hasattr(self, '_set_simple_trigger') and len(self._set_simple_trigger.argtypes) == 7:
            enabled = False
            status = self._set_simple_trigger(c_int16(device.handle),
                                              c_int16(int(enabled)),
                                              c_int32(self.PICO_CHANNEL['A']),
                                              c_int16(0),
                                              c_int32(self.PICO_THRESHOLD_DIRECTION['NONE']),
                                              c_uint32(0),
                                              c_int16(auto_trigger_after_millis))
            if status != self.PICO_STATUS['PICO_OK']:
                raise InvalidTriggerParameters("set_simple_trigger failed (%s)" % constants.pico_tag(status))
        else:
            raise NotImplementedError("not done other driver types yet") 
Example #20
Source File: __init__.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def platformSetRegCtx(self, tid, ctx):

        state = STRUCT_X86_THREAD_STATE64()

        # Sync up a struct first...
        scount = ctypes.c_uint32(ctypes.sizeof(state) / 8)
        ret = self.libc.thread_get_state(tid, x86_THREAD_STATE64, addrof(state), addrof(scount));
        if ret != 0:
            raise Exception('thread_get_state (THREAD_STATE64) failed: 0x%.8x' % ret)

        # Export our shit into it...
        ctx._rctx_Export(state)

        scount = ctypes.sizeof(state) / 8
        r = self.libc.thread_set_state(tid, x86_THREAD_STATE64, addrof(state), scount)
        if r != 0:
            raise Exception('thread_set_state (THREAD_STATE64) failed: 0x%.8x' % r)

        state = STRUCT_X86_DEBUG_STATE64()
        ctx._rctx_Export(state)
        scount = ctypes.sizeof(state) / 8
        r = self.libc.thread_set_state(tid, x86_DEBUG_STATE64, addrof(state), scount)
        if r != 0:
            raise Exception('thread_set_state (DEBUG_STATE64) failed: 0x%.8x' % r) 
Example #21
Source File: darwin.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def NOTplatformPs(self):
        ctl = SysctlType()
        ctl.one = CTL_KERN
        ctl.two = KERN_PROC
        ctl.three = KERN_PROC_ALL

        size = ctypes.c_uint32()
        self.libc.sysctl(addrof(ctl), 3, None, addrof(size), None, 0)
        count = size.value / ctypes.sizeof(kinfo_proc)
        buf = (kinfo_proc * count)()
        self.libc.sysctl(addrof(ctl), 3, buf,  addrof(size), None, 0)
        ret = []
        for i in range(count):
            pid = buf[i].kp_proc.p_pid
            if pid == 0: # Skip the crazy kernel things...
                continue
            name = buf[i].kp_proc.p_comm
            ret.append((pid,name))
        ret.reverse()
        return ret 
Example #22
Source File: __init__.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def platformGetRegCtx(self, tid):
        ctx = self.archGetRegCtx()
        # NOTE: the tid *is* the port...

        state = STRUCT_X86_THREAD_STATE64()
        scount = ctypes.c_uint32(ctypes.sizeof(state) / 4)
        ret = self.libc.thread_get_state(tid, x86_THREAD_STATE64, addrof(state), addrof(scount));
        if ret != 0:
            self.libc.mach_error("thread_get_state x86_THREAD_STATE64 failed:", ret)
            raise Exception('thread_get_state (THREAD_STATE64) failed: 0x%.8x' % ret)
        ctx._rctx_Import(state)

        state = STRUCT_X86_DEBUG_STATE64()
        scount = ctypes.c_uint32(ctypes.sizeof(state) / 4)
        ret = self.libc.thread_get_state(tid, x86_DEBUG_STATE64, addrof(state), addrof(scount));
        if ret != 0:
            self.libc.mach_error("thread_get_state x86_DEBUG_STATE64 failed:", ret)
            raise Exception('thread_get_state (DEBUG_STATE64) failed: 0x%.8x' % ret)
        ctx._rctx_Import(state)

        return ctx 
Example #23
Source File: __init__.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def platformSetRegCtx(self, tid, ctx):

        state = STRUCT_X86_THREAD_STATE32()

        # Sync up a struct first...
        scount = ctypes.c_uint32(ctypes.sizeof(state) / 4)
        ret = self.libc.thread_get_state(tid, x86_THREAD_STATE32, addrof(state), addrof(scount));
        if ret != 0:
            raise Exception('thread_get_state (THREAD_STATE32) failed: 0x%.8x' % ret)

        # Export our shit into it...
        ctx._rctx_Export(state)

        scount = ctypes.sizeof(state) / 4
        r = self.libc.thread_set_state(tid, x86_THREAD_STATE32, addrof(state), scount)
        if r != 0:
            raise Exception('thread_set_state (THREAD_STATE32) failed: 0x%.8x' % r)

        state = STRUCT_X86_DEBUG_STATE32()
        ctx._rctx_Export(state)
        scount = ctypes.sizeof(state) / 4
        r = self.libc.thread_set_state(tid, x86_DEBUG_STATE32, addrof(state), scount)
        if r != 0:
            raise Exception('thread_set_state (DEBUG_STATE32) failed: 0x%.8x' % r) 
Example #24
Source File: gmacpyutil.py    From macops with Apache License 2.0 6 votes vote down vote up
def ConfigureIOKit():
  """Sets up IOKit.

  We use ctypes to call functions in shared libraries to create, access and
  manipulate C data types in Python. For more information about ctypes, see:

  http://python.net/crew/theller/ctypes/
  http://code.rancidbacon.com/LearningAboutMacOSXNativePythonProgramming

  Returns:
    io_lib: IOKit library
  """
  io_lib = ctypes.cdll.LoadLibrary(
      '/System/Library/Frameworks/IOKit.framework/IOKit')
  io_lib.IOPMAssertionCreateWithName.argtypes = [
      ctypes.c_void_p,
      ctypes.c_uint32,
      ctypes.c_void_p,
      ctypes.POINTER(ctypes.c_uint32)]
  io_lib.IOPMAssertionRelease.argtypes = [ctypes.c_uint32]
  return io_lib 
Example #25
Source File: darwin.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def platformGetRegCtx(self, tid):
        ctx = self.archGetRegCtx()
        # NOTE: the tid *is* the port...

        state = STRUCT_X86_THREAD_STATE32()
        scount = ctypes.c_uint32(ctypes.sizeof(state) / 4)
        ret = self.libc.thread_get_state(tid, x86_THREAD_STATE32, addrof(state), addrof(scount));
        if ret != 0:
            raise Exception('thread_get_state (THREAD_STATE32) failed: 0x%.8x' % ret)
        ctx._rctx_Import(state)

        state = STRUCT_X86_DEBUG_STATE32()
        scount = ctypes.c_uint32(ctypes.sizeof(state) / 4)
        ret = self.libc.thread_get_state(tid, x86_DEBUG_STATE32, addrof(state), addrof(scount));
        if ret != 0:
            raise Exception('thread_get_state (DEBUG_STATE32) failed: 0x%.8x' % ret)
        ctx._rctx_Import(state)

        return ctx 
Example #26
Source File: darwin.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def platformSetRegCtx(self, tid, ctx):

        state = STRUCT_X86_THREAD_STATE32()

        # Sync up a struct first...
        scount = ctypes.c_uint32(ctypes.sizeof(state) / 4)
        ret = self.libc.thread_get_state(tid, x86_THREAD_STATE32, addrof(state), addrof(scount));
        if ret != 0:
            raise Exception('thread_get_state (THREAD_STATE32) failed: 0x%.8x' % ret)

        # Export our shit into it...
        ctx._rctx_Export(state)

        scount = ctypes.sizeof(state) / 4
        r = self.libc.thread_set_state(tid, x86_THREAD_STATE32, addrof(state), scount)
        if r != 0:
            raise Exception('thread_set_state (THREAD_STATE32) failed: 0x%.8x' % r)

        state = STRUCT_X86_DEBUG_STATE32()
        ctx._rctx_Export(state)
        scount = ctypes.sizeof(state) / 4
        r = self.libc.thread_set_state(tid, x86_DEBUG_STATE32, addrof(state), scount)
        if r != 0:
            raise Exception('thread_set_state (DEBUG_STATE32) failed: 0x%.8x' % r) 
Example #27
Source File: darwin.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def platformGetRegCtx(self, tid):
        ctx = self.archGetRegCtx()
        # NOTE: the tid *is* the port...

        state = STRUCT_X86_THREAD_STATE64()
        scount = ctypes.c_uint32(ctypes.sizeof(state) / 4)
        ret = self.libc.thread_get_state(tid, x86_THREAD_STATE64, addrof(state), addrof(scount));
        if ret != 0:
            self.libc.mach_error("thread_get_state x86_THREAD_STATE64 failed:", ret)
            raise Exception('thread_get_state (THREAD_STATE64) failed: 0x%.8x' % ret)
        ctx._rctx_Import(state)

        state = STRUCT_X86_DEBUG_STATE64()
        scount = ctypes.c_uint32(ctypes.sizeof(state) / 4)
        ret = self.libc.thread_get_state(tid, x86_DEBUG_STATE64, addrof(state), addrof(scount));
        if ret != 0:
            self.libc.mach_error("thread_get_state x86_DEBUG_STATE64 failed:", ret)
            raise Exception('thread_get_state (DEBUG_STATE64) failed: 0x%.8x' % ret)
        ctx._rctx_Import(state)

        return ctx 
Example #28
Source File: test_dtype.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_large_packed_structure(self):
        class PackedStructure(ctypes.Structure):
            _pack_ = 2
            _fields_ = [
                ('a', ctypes.c_uint8),
                ('b', ctypes.c_uint16),
                ('c', ctypes.c_uint8),
                ('d', ctypes.c_uint16),
                ('e', ctypes.c_uint32),
                ('f', ctypes.c_uint32),
                ('g', ctypes.c_uint8)
                ]
        expected = np.dtype(dict(
            formats=[np.uint8, np.uint16, np.uint8, np.uint16, np.uint32, np.uint32, np.uint8 ],
            offsets=[0, 2, 4, 6, 8, 12, 16],
            names=['a', 'b', 'c', 'd', 'e', 'f', 'g'],
            itemsize=18))
        self.check(PackedStructure, expected) 
Example #29
Source File: test_ctypeslib.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_structure_aligned(self):
        dt = np.dtype([
            ('a', np.uint16),
            ('b', np.uint32),
        ], align=True)

        ct = np.ctypeslib.as_ctypes_type(dt)
        assert_(issubclass(ct, ctypes.Structure))
        assert_equal(ctypes.sizeof(ct), dt.itemsize)
        assert_equal(ct._fields_, [
            ('a', ctypes.c_uint16),
            ('', ctypes.c_char * 2),  # padding
            ('b', ctypes.c_uint32),
        ]) 
Example #30
Source File: get_system_info.py    From py-cpuinfo with MIT License 5 votes vote down vote up
def _run_asm(self, *machine_code):
		import ctypes

		asm = ASM(ctypes.c_uint32, (), machine_code)
		asm.compile()
		retval = asm.run()
		asm.free()
		return retval

	# http://en.wikipedia.org/wiki/CPUID#EAX.3D0:_Get_vendor_ID