Python ctypes.string_at() Examples

The following are 30 code examples of ctypes.string_at(). 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: server.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
	print("Preloading cache directories")

	# print("Testing reload")
	# server.tree.tree.reloadTree()
	# print("Starting RPC server")
	try:
		run()

	except:
		# abort /hard/ if we exceptioned out of the main run.
		# This should (hopeully) cause the OS to terminate any
		# remaining threads.
		# As it is, I've been having issues with the main thread failing
		# with 'OSError: [Errno 24] Too many open files', killing the main thread
		# and leaving some of the amqp interface threads dangling.
		# Somehow, it's not being caught in the `except Exception:` handler
		# in run(). NFI how.
		import ctypes
		ctypes.string_at(0) 
Example #2
Source File: spi.py    From rpi3-webiopi with Apache License 2.0 6 votes vote down vote up
def xfer(self, txbuff=None):
        length = len(txbuff)
        if PYTHON_MAJOR >= 3:
            _txbuff = bytes(txbuff)
            _txptr = ctypes.create_string_buffer(_txbuff)
        else:
            _txbuff = str(bytearray(txbuff))
            _txptr = ctypes.create_string_buffer(_txbuff)
        _rxptr = ctypes.create_string_buffer(length)
        
        data = struct.pack("QQLLHBBL",  #64 64 32 32 16 8 8 32 b = 32B
                    ctypes.addressof(_txptr),
                    ctypes.addressof(_rxptr),
                    length,
                    self.speed,
                    0, #delay
                    self.bits,
                    0, # cs_change,
                    0  # pad
                    )
        
        fcntl.ioctl(self.fd, SPI_IOC_MESSAGE(len(data)), data)
        _rxbuff = ctypes.string_at(_rxptr, length)
        return bytearray(_rxbuff) 
Example #3
Source File: firefox_decrypt.py    From firefox_decrypt with GNU General Public License v3.0 6 votes vote down vote up
def decode(self, data64):
        data = b64decode(data64)
        inp = self.SECItem(0, data, len(data))
        out = self.SECItem(0, None, 0)

        e = self._PK11SDR_Decrypt(inp, out, None)
        LOG.debug("Decryption of data returned %s", e)
        try:
            if e == -1:
                LOG.error("Password decryption failed. Passwords protected by a Master Password!")
                self.handle_error()
                raise Exit(Exit.NEED_MASTER_PASSWORD)

            res = ct.string_at(out.data, out.len).decode(LIB_ENCODING)
        finally:
            # Avoid leaking SECItem
            self._SECITEM_ZfreeItem(out, 0)

        return res 
Example #4
Source File: leveldb.py    From leveldb-py with MIT License 6 votes vote down vote up
def get(self, key, verify_checksums=False, fill_cache=True):
        error = ctypes.POINTER(ctypes.c_char)()
        options = _ldb.leveldb_readoptions_create()
        _ldb.leveldb_readoptions_set_verify_checksums(options,
                verify_checksums)
        _ldb.leveldb_readoptions_set_fill_cache(options, fill_cache)
        if self._snapshot is not None:
            _ldb.leveldb_readoptions_set_snapshot(options, self._snapshot.ref)
        size = ctypes.c_size_t(0)
        val_p = _ldb.leveldb_get(self._db.ref, options, key, len(key),
                ctypes.byref(size), ctypes.byref(error))
        if bool(val_p):
            val = ctypes.string_at(val_p, size.value)
            _ldb.leveldb_free(ctypes.cast(val_p, ctypes.c_void_p))
        else:
            val = None
        _ldb.leveldb_readoptions_destroy(options)
        _checkError(error)
        return val

    # pylint: disable=W0212 
Example #5
Source File: spi.py    From Adafruit_Python_PureIO with MIT License 6 votes vote down vote up
def readbytes(self, length, max_speed_hz=0, bits_per_word=0, delay=0):
        """Perform half-duplex SPI read as a binary string
        """
        receive_buffer = create_string_buffer(length)
        spi_ioc_transfer = struct.pack(
            SPI._IOC_TRANSFER_FORMAT,
            0,
            addressof(receive_buffer),
            length,
            max_speed_hz,
            delay,
            bits_per_word,
            0,
            0,
            0,
            0,
        )
        ioctl(self.handle, SPI._IOC_MESSAGE, spi_ioc_transfer)
        return string_at(receive_buffer, length) 
Example #6
Source File: pybass.py    From pybass with Apache License 2.0 5 votes vote down vote up
def get_tags_as_list(handle, tags = BASS_TAG_OGG):
	result_as_list = []
	addr = BASS_ChannelGetTags(handle, tags)
	str_tag = ''
	while isinstance(str_tag, str):
		str_tag = ctypes.string_at(addr)
		addr += len(str_tag) + 1
		if str_tag:
			if 32 < bass_ord(str_tag[0]) < 256:
				result_as_list.append(tuple(str_tag.split('=')))
			else:
				str_tag = None
	return result_as_list 
Example #7
Source File: errcheck.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def check_sized_string(result, func, cargs):
    """
    Error checking for routines that return explicitly sized strings.

    This frees the memory allocated by GEOS at the result pointer.
    """
    if not result:
        raise GEOSException('Invalid string pointer returned by GEOS C function "%s"' % func.__name__)
    # A c_size_t object is passed in by reference for the second
    # argument on these routines, and its needed to determine the
    # correct size.
    s = string_at(result, last_arg_byref(cargs))
    # Freeing the memory allocated within GEOS
    free(result)
    return s 
Example #8
Source File: test_nsjail.py    From snekbox with MIT License 5 votes vote down vote up
def test_sigsegv_returns_139(self):  # In honour of Juan.
        code = dedent("""
            import ctypes
            ctypes.string_at(0)
        """).strip()

        result = self.nsjail.python3(code)
        self.assertEqual(result.returncode, 139)
        self.assertEqual(result.stdout, "")
        self.assertEqual(result.stderr, None) 
Example #9
Source File: ifaces.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def get_iface(iface_type_str):
    iface_type = ctypes.create_string_buffer(iface_type_str)

    str_p = ctypes.c_char_p()
    pt = ctypes.pointer(str_p)

    if LIB.select_iface(iface_type, pt) != 0:
        return False

    return ctypes.string_at(str_p) 
Example #10
Source File: registry.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def Reg2Py(data, size, data_type):
    if data_type == winreg.REG_DWORD:
        if size == 0:
            return 0
        return ctypes.cast(data, ctypes.POINTER(ctypes.c_int)).contents.value
    elif data_type == winreg.REG_SZ or data_type == winreg.REG_EXPAND_SZ:
        return ctypes.wstring_at(data, size // 2).rstrip(u"\x00")
    elif data_type == winreg.REG_MULTI_SZ:
        return ctypes.wstring_at(data, size // 2).rstrip(u"\x00").split(u"\x00")
    else:
        if size == 0:
            return None
        return ctypes.string_at(data, size) 
Example #11
Source File: spi.py    From Adafruit_Python_PureIO with MIT License 5 votes vote down vote up
def transfer(self, data, max_speed_hz=0, bits_per_word=0, delay=0):
        """Perform full-duplex SPI transfer
        """
        data = array.array("B", data).tostring()
        receive_data = []

        chunks = [
            data[i : i + SPI_CHUNK_SIZE] for i in range(0, len(data), SPI_CHUNK_SIZE)
        ]
        for chunk in chunks:
            length = len(chunk)
            receive_buffer = create_string_buffer(length)
            transmit_buffer = create_string_buffer(chunk)
            spi_ioc_transfer = struct.pack(
                SPI._IOC_TRANSFER_FORMAT,
                addressof(transmit_buffer),
                addressof(receive_buffer),
                length,
                max_speed_hz,
                delay,
                bits_per_word,
                0,
                0,
                0,
                0,
            )
            ioctl(self.handle, SPI._IOC_MESSAGE, spi_ioc_transfer)
            receive_data += string_at(receive_buffer, length)
        return receive_data 
Example #12
Source File: geometries.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def wkb(self):
        "Returns the WKB representation of the Geometry."
        if sys.byteorder == 'little':
            byteorder = 1  # wkbNDR (from ogr_core.h)
        else:
            byteorder = 0  # wkbXDR
        sz = self.wkb_size
        # Creating the unsigned character buffer, and passing it in by reference.
        buf = (c_ubyte * sz)()
        capi.to_wkb(self.ptr, byteorder, byref(buf))
        # Returning a buffer of the string at the pointer.
        return six.memoryview(string_at(buf, sz)) 
Example #13
Source File: leveldb.py    From leveldb-py with MIT License 5 votes vote down vote up
def _checkError(error):
    if bool(error):
        message = ctypes.string_at(error)
        _ldb.leveldb_free(ctypes.cast(error, ctypes.c_void_p))
        raise Error(message) 
Example #14
Source File: leveldb.py    From leveldb-py with MIT License 5 votes vote down vote up
def val(self):
        length = ctypes.c_size_t(0)
        val_p = _ldb.leveldb_iter_value(self._ref.ref, ctypes.byref(length))
        assert bool(val_p)
        return ctypes.string_at(val_p, length.value) 
Example #15
Source File: pybass.py    From pybass with Apache License 2.0 5 votes vote down vote up
def get_tags(handle, tags = BASS_TAG_OGG):
	result = []
	addr = BASS_ChannelGetTags(handle, tags)
	res = b''
	while isinstance(res, (str, bytes)):
		res = ctypes.string_at(addr)
		#if sys.hexversion >= 0x03000000:
			#res = ctypes.wstring_at(addr)
		addr += len(res) + 1
		if res:
			if 32 < bass_ord(res[0]) < 256:
				result.append(res)
			else:
				res = None
	return result 
Example #16
Source File: leveldb.py    From leveldb-py with MIT License 5 votes vote down vote up
def key(self):
        length = ctypes.c_size_t(0)
        val_p = _ldb.leveldb_iter_key(self._ref.ref, ctypes.byref(length))
        assert bool(val_p)
        return ctypes.string_at(val_p, length.value) 
Example #17
Source File: pybass.py    From pybass with Apache License 2.0 5 votes vote down vote up
def get_tags_as_dict(handle, tags = BASS_TAG_OGG):
	result_as_dict = {}
	addr = BASS_ChannelGetTags(handle, tags)
	str_tag = ''
	while isinstance(str_tag, str):
		str_tag = ctypes.string_at(addr)
		addr += len(str_tag) + 1
		if str_tag:
			if 32 < bass_ord(str_tag[0]) < 256:
				key, value = str_tag.split('=')
				result_as_dict[key] = value
			else:
				str_tag = None
	return result_as_dict 
Example #18
Source File: errcheck.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def check_string(result, func, cargs):
    """
    Error checking for routines that return strings.

    This frees the memory allocated by GEOS at the result pointer.
    """
    if not result:
        raise GEOSException('Error encountered checking string return value in GEOS C function "%s".' % func.__name__)
    # Getting the string value at the pointer address.
    s = string_at(result)
    # Freeing the memory allocated within GEOS
    free(result)
    return s 
Example #19
Source File: _ffi.py    From oscrypto with MIT License 5 votes vote down vote up
def native(type_, value):
        if isinstance(value, type_):
            return value
        if sys.version_info < (3,) and type_ == int and isinstance(value, int_types):
            return value
        if isinstance(value, ctypes.Array) and value._type_ == ctypes.c_byte:
            return ctypes.string_at(ctypes.addressof(value), value._length_)
        return type_(value.value) 
Example #20
Source File: errcheck.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def check_string(result, func, cargs, offset=-1, str_result=False):
    """
    Checks the string output returned from the given function, and frees
    the string pointer allocated by OGR.  The `str_result` keyword
    may be used when the result is the string pointer, otherwise
    the OGR error code is assumed.  The `offset` keyword may be used
    to extract the string pointer passed in by-reference at the given
    slice offset in the function arguments.
    """
    if str_result:
        # For routines that return a string.
        ptr = result
        if not ptr:
            s = None
        else:
            s = string_at(result)
    else:
        # Error-code return specified.
        check_err(result)
        ptr = ptr_byref(cargs, offset)
        # Getting the string value
        s = ptr.value
    # Correctly freeing the allocated memory behind GDAL pointer
    # with the VSIFree routine.
    if ptr:
        lgdal.VSIFree(ptr)
    return s

# ### DataSource, Layer error-checking ###


# ### Envelope checking ### 
Example #21
Source File: prototypes.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def check_string(result, func, cargs):
    if result:
        s = string_at(result)
        free(result)
    else:
        s = ''
    return s.decode(GEOIP_DEFAULT_ENCODING) 
Example #22
Source File: cpp32.py    From msl-loadlib with MIT License 5 votes vote down vote up
def reverse_string_v2(self, original):
        """Reverse a string (version 2).

        In this method C++ allocates the memory for the reversed string and passes
        the string to Python.

        The corresponding C++ code is

        .. code-block:: cpp

            char* reverse_string_v2(char* original, int n) {
                char* reversed = new char[n];
                for (int i = 0; i < n; i++) {
                    reversed[i] = original[n - i - 1];
                }
                return reversed;
            }

        See the corresponding 64-bit :meth:`~.cpp64.Cpp64.reverse_string_v2` method.

        Parameters
        ----------
        original : :class:`str`
            The original string.

        Returns
        -------
        :class:`str`
            The string reversed.
        """
        n = len(original)
        self.lib.reverse_string_v2.restype = ctypes.c_char_p
        rev = self.lib.reverse_string_v2(ctypes.c_char_p(original.encode()),
                                         ctypes.c_int32(n))
        return ctypes.string_at(rev, n).decode() 
Example #23
Source File: darwin.py    From nightmare with GNU General Public License v2.0 5 votes vote down vote up
def platformReadMemory(self, address, size):
        pval = ctypes.c_void_p(0)
        sval = ctypes.c_uint32(0)
        r = self.libc.mach_vm_read(self.task, address, size, addrof(pval), addrof(sval));
        #r = self.libc.vm_read(self.task, address, size, addrof(pval), addrof(sval));
        if r != 0:
            raise Exception('mach_vm_read failed at 0x%.8x: 0x%.8x' % (address,r))
        buf = ctypes.string_at(pval.value, sval.value)
        self.libc.vm_deallocate(self.myport, pval, sval)
        return buf 
Example #24
Source File: __init__.py    From nightmare with GNU General Public License v2.0 5 votes vote down vote up
def platformReadMemory(self, address, size):
        pval = ctypes.c_void_p(0)
        sval = ctypes.c_uint32(0)
        r = self.libc.mach_vm_read(self.task, address, size, addrof(pval), addrof(sval));
        #r = self.libc.vm_read(self.task, address, size, addrof(pval), addrof(sval));
        if r != 0:
            raise Exception('mach_vm_read failed at 0x%.8x: 0x%.8x' % (address,r))
        buf = ctypes.string_at(pval.value, sval.value)
        self.libc.vm_deallocate(self.myport, pval, sval)
        return buf 
Example #25
Source File: basictest.py    From nightmare with GNU General Public License v2.0 5 votes vote down vote up
def dostuff():
    print '++ Hi! Im the new thread! (sleeping for 3)\n'
    time.sleep(3)
    print '++ Now Im going to memory fault (reading 0x41414141)\n'
    try:
        x = ctypes.string_at(0x41414141, 20)
    except Exception, e:
        print e 
Example #26
Source File: ShaderBuffer.py    From PyEngine3D with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_buffer_data(self):
        # too slow..
        glBindBuffer(self.target, self.buffer)
        data_ptr = glMapBuffer(self.target, GL_READ_ONLY)
        glUnmapBuffer(self.target)
        glBindBuffer(self.target, 0)

        data_string = string_at(data_ptr, self.data_size)
        return np.fromstring(data_string, dtype=self.dtype) 
Example #27
Source File: errcheck.py    From bioforum with MIT License 5 votes vote down vote up
def check_sized_string(result, func, cargs):
    """
    Error checking for routines that return explicitly sized strings.

    This frees the memory allocated by GEOS at the result pointer.
    """
    if not result:
        raise GEOSException('Invalid string pointer returned by GEOS C function "%s"' % func.__name__)
    # A c_size_t object is passed in by reference for the second
    # argument on these routines, and its needed to determine the
    # correct size.
    s = string_at(result, last_arg_byref(cargs))
    # Freeing the memory allocated within GEOS
    free(result)
    return s 
Example #28
Source File: errcheck.py    From bioforum with MIT License 5 votes vote down vote up
def check_string(result, func, cargs):
    """
    Error checking for routines that return strings.

    This frees the memory allocated by GEOS at the result pointer.
    """
    if not result:
        raise GEOSException('Error encountered checking string return value in GEOS C function "%s".' % func.__name__)
    # Getting the string value at the pointer address.
    s = string_at(result)
    # Freeing the memory allocated within GEOS
    free(result)
    return s 
Example #29
Source File: OSXProcess.py    From memorpy with GNU General Public License v3.0 5 votes vote down vote up
def read_bytes(self, address, bytes = 4):
        pdata = ctypes.c_void_p(0)
        data_cnt = ctypes.c_uint32(0)
        
        ret = libc.mach_vm_read(self.task, ctypes.c_ulonglong(address), ctypes.c_longlong(bytes), ctypes.pointer(pdata), ctypes.pointer(data_cnt));
        #if ret==1:
        #    return ""
        if ret!=0:
            raise ProcessException("mach_vm_read returned : %s"%ret)
        buf=ctypes.string_at(pdata.value, data_cnt.value)
        libc.vm_deallocate(self.mytask, pdata, data_cnt)
        return buf 
Example #30
Source File: leveldb.py    From Amulet-Core with MIT License 5 votes vote down vote up
def _checkError(err):
    """Utility function for checking the error code returned by some leveldb functions."""
    if bool(err):  # Not an empty null-terminated string
        message = ctypes.string_at(err)
        ldb.leveldb_free(ctypes.cast(err, ctypes.c_void_p))
        raise Exception(message)