示例#1
0
文件: coredump.py 项目: cyrillos/criu
	def _gen_fpregset(self, pid, tid):
		"""
		Generate NT_FPREGSET note for thread tid of process pid.
		"""
		core	= self.cores[tid]
		regs	= core["thread_info"]["fpregs"]

		fpregset = elf.elf_fpregset_t()
		ctypes.memset(ctypes.addressof(fpregset), 0, ctypes.sizeof(fpregset))

		fpregset.cwd		= regs["cwd"]
		fpregset.swd		= regs["swd"]
		fpregset.ftw		= regs["twd"]
		fpregset.fop		= regs["fop"]
		fpregset.rip		= regs["rip"]
		fpregset.rdp		= regs["rdp"]
		fpregset.mxcsr		= regs["mxcsr"]
		fpregset.mxcr_mask	= regs["mxcsr_mask"]
		fpregset.st_space	= (ctypes.c_uint * len(regs["st_space"]))(*regs["st_space"])
		fpregset.xmm_space	= (ctypes.c_uint * len(regs["xmm_space"]))(*regs["xmm_space"])
		#fpregset.padding	= regs["padding"] unused

		nhdr = elf.Elf64_Nhdr()
		nhdr.n_namesz	= 5
		nhdr.n_descsz	= ctypes.sizeof(elf.elf_fpregset_t())
		nhdr.n_type	= elf.NT_FPREGSET

		note = elf_note()
		note.data	= fpregset
		note.owner	= "CORE"
		note.nhdr 	= nhdr

		return note
示例#2
0
文件: coredump.py 项目: cyrillos/criu
	def _gen_ehdr(self, pid, phdrs):
		"""
		Generate elf header for process pid with program headers phdrs.
		"""
		ehdr = elf.Elf64_Ehdr()

		ctypes.memset(ctypes.addressof(ehdr), 0, ctypes.sizeof(ehdr))
		ehdr.e_ident[elf.EI_MAG0]	= elf.ELFMAG0
		ehdr.e_ident[elf.EI_MAG1]	= elf.ELFMAG1
		ehdr.e_ident[elf.EI_MAG2]	= elf.ELFMAG2
		ehdr.e_ident[elf.EI_MAG3]	= elf.ELFMAG3
		ehdr.e_ident[elf.EI_CLASS]	= elf.ELFCLASS64
		ehdr.e_ident[elf.EI_DATA]	= elf.ELFDATA2LSB
		ehdr.e_ident[elf.EI_VERSION]	= elf.EV_CURRENT

		ehdr.e_type		= elf.ET_CORE
		ehdr.e_machine		= elf.EM_X86_64
		ehdr.e_version		= elf.EV_CURRENT
		ehdr.e_phoff		= ctypes.sizeof(elf.Elf64_Ehdr())
		ehdr.e_ehsize		= ctypes.sizeof(elf.Elf64_Ehdr())
		ehdr.e_phentsize	= ctypes.sizeof(elf.Elf64_Phdr())
		#FIXME Case len(phdrs) > PN_XNUM should be handled properly.
		# See fs/binfmt_elf.c from linux kernel.
		ehdr.e_phnum	= len(phdrs)

		return ehdr
示例#3
0
    def write(self, audio_data, length):
        # Pass audio_data=None to write silence
        if length == 0:
            return 0

        with self._lock:
            write_ptr = self._ds_buffer.lock(self._write_cursor_ring, length)
            assert 0 < length <= self._buffer_size
            assert length == write_ptr.audio_length_1.value + write_ptr.audio_length_2.value

            if audio_data:
                ctypes.memmove(write_ptr.audio_ptr_1, audio_data.data, write_ptr.audio_length_1.value)
                audio_data.consume(write_ptr.audio_length_1.value, self.source_group.audio_format)
                if write_ptr.audio_length_2.value > 0:
                    ctypes.memmove(write_ptr.audio_ptr_2, audio_data.data, write_ptr.audio_length_2.value)
                    audio_data.consume(write_ptr.audio_length_2.value, self.source_group.audio_format)
            else:
                if self.source_group.audio_format.sample_size == 8:
                    c = 0x80
                else:
                    c = 0
                ctypes.memset(write_ptr.audio_ptr_1, c, write_ptr.audio_length_1.value)
                if write_ptr.audio_length_2.value > 0:
                    ctypes.memset(write_ptr.audio_ptr_2, c, write_ptr.audio_length_2.value)
            self._ds_buffer.unlock(write_ptr)

            self._write_cursor += length
            self._write_cursor_ring += length
            self._write_cursor_ring %= self._buffer_size
示例#4
0
    def win_pick(window, starting_color):
        paste = None
        start_color = None
        if starting_color is not None:
            start_color = hexstr_to_bgr(starting_color[1:])
        s = sublime.load_settings("ColorPicker.sublime-settings")
        custom_colors = s.get("custom_colors", ['0'] * 16)

        if len(custom_colors) < 16:
            custom_colors = ['0'] * 16
            s.set('custom_colors', custom_colors)

        cc = CHOOSECOLOR()
        ctypes.memset(ctypes.byref(cc), 0, ctypes.sizeof(cc))
        cc.lStructSize = ctypes.sizeof(cc)

        if sublime_version == 2:
            cc.hwndOwner = window.hwnd()
        else:
            # Temporary fix for Sublime Text 3 - For some reason the hwnd crashes it
            # Of course, clicking out of the colour picker and into Sublime will make
            # Sublime not respond, but as soon as you exit the colour picker it's ok
            cc.hwndOwner = None

        cc.Flags = CC_SOLIDCOLOR | CC_FULLOPEN | CC_RGBINIT
        cc.rgbResult = c_uint32(start_color) if not paste and start_color else get_pixel()
        cc.lpCustColors = to_custom_color_array(custom_colors)

        if ChooseColorW(ctypes.byref(cc)):
            color = bgr_to_hexstr(cc.rgbResult)
        else:
            color = None

        return color
示例#5
0
文件: iplist.py 项目: unixnut/iptool
def get_addrs(s, interfaces, family = None):
    """Match semantics only work for address family, so do a dump and return an
    associative array (indexed by interface ID) of arrays of address info (each
    elemnt being an associative array)."""

    if family is None:
        payload = rtnl.Rtgenmsg()
        payload.rtgen_family = socket.AF_UNSPEC    # socket.AF_INET
    else:
        payload = if_addr.Ifaddrmsg()
        ctypes.memset(ctypes.addressof(payload), 0, ctypes.sizeof(payload))
        payload.ifa_family = family
        ## payload.ifa_family = socket.AF_INET
        ## payload.ifa_flags = 
        ## payload.ifa_index = i

    d = {}
    for buf in s.transact(rtnl.RTM_GETADDR, payload):
        # Get all the addresses and then store each one in a list belonging to
        # its respective interface ID
        for info in s.process_messages(buf, get_addr_info, interfaces):
            if info['interface'] in d:
                d[info['interface']].append(info)
            else:
                d[info['interface']] = [info]

    return d
示例#6
0
def getBGR32(dc, bitmap):
	"""
	Returns a (raw BGR str, (width, height)) for C{dc}, C{bitmap}.
	Guaranteed to be 32-bit.  Note that the origin of the returned image is
	in the bottom-left corner, and the image has 32-bit line padding.
	"""
	bmpInfo = bitmap.GetInfo()
	width, height = bmpInfo['bmWidth'], bmpInfo['bmHeight']

	bmi = BITMAPINFO()
	ctypes.memset(ctypes.byref(bmi), 0x00, ctypes.sizeof(bmi))
	bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
	bmi.bmiHeader.biWidth = width
	bmi.bmiHeader.biHeight = height
	bmi.bmiHeader.biBitCount = 24
	bmi.bmiHeader.biPlanes = 1

	bufferLen = height * ((width * 3 + 3) & -4)
	pbBits = ctypes.create_string_buffer(bufferLen)

	ret = ctypes.windll.gdi32.GetDIBits(
		dc.GetHandleAttrib(),
		bitmap.GetHandle(),
		0,
		height,
		ctypes.byref(pbBits),
		ctypes.pointer(bmi),
		win32con.DIB_RGB_COLORS)
	if ret == 0:
		raise DIBFailed("Return code 0 from GetDIBits")

	assert len(pbBits.raw) == bufferLen, len(pbBits.raw)

	return pbBits.raw, (width, height)
示例#7
0
    def fromdict(cls, credential, flags=0):
        unsupported = set(credential.keys()) - SUPPORTED_CREDKEYS
        if len(unsupported):
            raise ValueError("Unsupported keys: {0}".format(unsupported))
        if flags != 0:
            raise ValueError("flag != 0 not yet supported")

        c_creds = cls()
        c_pcreds = PCREDENTIAL(c_creds)

        # zero-out memory
        ctypes.memset(c_pcreds, 0, ctypes.sizeof(c_creds))

        for key in SUPPORTED_CREDKEYS:
            if key in credential:
                if key != 'CredentialBlob':
                    setattr(c_creds, key, credential[key])
                else:
                    blob = make_unicode(credential['CredentialBlob'])
                    blob_data = ctypes.create_unicode_buffer(blob)
                    # Create_unicode_buffer adds a NULL at the end of the
                    # string we do not want that.
                    c_creds.CredentialBlobSize = \
                        ctypes.sizeof(blob_data) - \
                        ctypes.sizeof(ctypes.c_wchar)
                    c_creds.CredentialBlob = ctypes.cast(blob_data, LPBYTE)
        return c_creds
示例#8
0
    def _update_data(self):
        # Moment of truth
        ioctl(self.kernel_socket.fileno(), self.magic_number, self.iwrequest)
        output = self.essid.tostring().strip(b"\x00").decode()

        if output:
            self._data["full_text"] = output
            self._data["color"] = self.color_normal
            self.urgent = False
        else:
            self._data["full_text"] = "{} disconnected".format(self.interface)
            self._data["color"] = self.color_critical
            self.urgent = True

        # Regenerate for reuse
        # memset essid to zeros
        # Set length to self.length again
        # [24], because:
        # [0-15] array with interface name
        # [16-23] 8-byte memory adress to self.essid
        # [24] one-byte value with length
        # ioctl sets length byte to the actual essid length, causes OSError
        # if not re-set to default value
        ctypes.memset(self.address, 0, self.iwrequest[24])
        self.iwrequest[24] = self.length
def getClipboardAndSave():
    win32clipboard.OpenClipboard()
    try:
        if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_DIB):
            data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB)
        else:
            print('clipboard does not contain an image in DIB format')
            sys.exit(1)
    finally:
        win32clipboard.CloseClipboard()

    bmih = BITMAPINFOHEADER()
    ctypes.memmove(ctypes.pointer(bmih), data, SIZEOF_BITMAPINFOHEADER)

    if bmih.biCompression != BI_BITFIELDS:  # RGBA?
        print('insupported compression type {}'.format(bmih.biCompression))
        sys.exit(1)

    bmfh = BITMAPFILEHEADER()
    ctypes.memset(ctypes.pointer(bmfh), 0, SIZEOF_BITMAPFILEHEADER)  # zero structure
    bmfh.bfType = ord('B') | (ord('M') << 8)
    bmfh.bfSize = SIZEOF_BITMAPFILEHEADER + len(data)  # file size
    SIZEOF_COLORTABLE = 0
    bmfh.bfOffBits = SIZEOF_BITMAPFILEHEADER + SIZEOF_BITMAPINFOHEADER + SIZEOF_COLORTABLE

    baseName= getFileName()
    bmp_filename = baseName+".bmp"
    png_filename = baseName+".jpg"
    with open(bmp_filename, 'wb') as bmp_file:
        bmp_file.write(bmfh)
        bmp_file.write(data)
    print('file "{}" created from clipboard image'.format(bmp_filename))
    convertBmp2Png(bmp_filename,png_filename)
    return png_filename
示例#10
0
文件: utils.py 项目: Dischi/kaa-base
def set_process_name(name):
    """
    On Linux systems later than 2.6.9, this function sets the process name as it
    appears in ps, and so that it can be found with killall(1) and pidof(8).

    .. note::
       name will be truncated to the cumulative length of the original process
       name and all its arguments; once updated, passed arguments will no
       longer be visible.

       This function currently only works properly with Python 2.  With Python
       3, the process will be found with killall(1), but ps(1) and pidof(8)
       will not see the new name.
    """
    libc = ctypes.CDLL(ctypes.util.find_library("c"))
    maxsize = len(open('/proc/%s/cmdline' % os.getpid()).readline())
    name0 = name + '\x00'

    # Python 3's Py_GetArgcArgv() does not return the original argv, but rather
    # a wchar_t copy of it, which means we can't use it.
    if sys.hexversion < 0x03000000:
        c_char_pp = ctypes.POINTER(ctypes.c_char_p)
        Py_GetArgcArgv = ctypes.pythonapi.Py_GetArgcArgv
        Py_GetArgcArgv.restype = None
        Py_GetArgcArgv.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(c_char_pp)]

        argc = ctypes.c_int(0)
        argv = c_char_pp()
        Py_GetArgcArgv(argc, argv)

        ctypes.memset(argv.contents, 0, maxsize)
        ctypes.memmove(argv.contents, name0, len(name0))

    libc.prctl(ctypes.c_int(15), ctypes.c_char_p(name0), 0, 0, 0)  # 15 == PR_SET_NAME
示例#11
0
	def authCallback(self, prompt, buffer, bufferLength, echo, verify, userData):
		"""
		(const char *prompt, char *buf, size_t len,
			int echo, int verify, void *userdata)
		called like this:
			("Enter your username: "******"""
		self.logger.debug("authCallback: '%s', %s, %i, %i, %i, %s", prompt,  buffer,  bufferLength, echo, verify, userData)
		ret = None
		if 'username' in prompt:
			ret = self.username()
		elif 'password' in prompt:
			ret = self.password()
		elif 'SSL' in prompt:
			fingerprint = re.search("fingerprint: ([\\w\\d:]+)", prompt).group(1)
			ret = self.ssl(fingerprint)
		else:
			self.logger.warning("authCallback: unknown prompt: '%s'", prompt)
			return -1
		
		for i in range(len(ret)):
			ctypes.memset(buffer+i, ord(ret[i]), 1)
		if self.debug:
			buffString = ctypes.string_at(buffer, len(ret))
			if 'password' in prompt:
				if ret and ret in buffString:
					buffString = buffString.replace(ret, PASSWORD_SAFE)
			self.logger.debug("returning: '%s'", buffString)
		return 0
示例#12
0
def from_hbitmap(hdc, hbitmap, w, h):
    bmi = BITMAPINFO()
    ctypes.memset(ctypes.byref(bmi), 0, ctypes.sizeof(bmi))
    bmi.bmiHeader.biSize        = ctypes.sizeof(BITMAPINFOHEADER)
    bmi.bmiHeader.biWidth       = w
    bmi.bmiHeader.biHeight      = -h
    bmi.bmiHeader.biPlanes      = 1
    bmi.bmiHeader.biBitCount    = 32
    bmi.bmiHeader.biCompression = win32con.BI_RGB
    bmi.bmiHeader.biSizeImage   = w * h * 4

    image = QImage(w, h, QImage.Format_ARGB32_Premultiplied)

    data = ctypes.create_string_buffer(bmi.bmiHeader.biSizeImage)
    memcpy = ctypes.cdll.msvcrt.memcpy
    if gdi32.GetDIBits(hdc, hbitmap, 0, h, data, ctypes.byref(bmi),
                       win32con.DIB_RGB_COLORS):
        for y in xrange(h):
            dest = image.scanLine(y)
            dest.setsize(w * 4)
            bpl = image.bytesPerLine()
            i = y * bpl
            dest[:] = data[i:i+bpl]
    else:
        logger.warning(
            'converting hIcon to QPixmap, failed to get bitmap bits')
    return image
示例#13
0
    def write(self, audio_data, length):
        # Pass audio_data=None to write silence
        if length == 0:
            return 0

        self.lock()

        p1 = ctypes.c_void_p()
        l1 = lib.DWORD()
        p2 = ctypes.c_void_p()
        l2 = lib.DWORD()
        self._buffer.Lock(self._write_cursor_ring, length,
                          ctypes.byref(p1), l1, ctypes.byref(p2), l2, 0)
        assert length == l1.value + l2.value

        if audio_data:
            ctypes.memmove(p1, audio_data.data, l1.value)
            audio_data.consume(l1.value, self.source_group.audio_format)
            if l2.value:
                ctypes.memmove(p2, audio_data.data, l2.value)
                audio_data.consume(l2.value, self.source_group.audio_format)
        else:
            ctypes.memset(p1, 0, l1.value)
            if l2.value:
                ctypes.memset(p2, 0, l2.value)
        self._buffer.Unlock(p1, l1, p2, l2)

        self._write_cursor += length
        self._write_cursor_ring += length
        self._write_cursor_ring %= self._buffer_size
        self.unlock()
示例#14
0
 def __call__(self, struct):
     ctype = get_ctype(self)
     obj = ctype()
     pool = PoolRecord(obj)
     ctypes.memset(ctypes.pointer(obj), 0, ctypes.sizeof(ctype))
     self.fill(pool, obj, struct)
     return pool
示例#15
0
文件: gaia.py 项目: eklitzke/gaia
def get_records(names):
    """Get multiple A records, in parallel.

    Args:
      names - a list of names to lookup

    Returns:
      dictionary mapping lookup names to IP addresses
    """
    result = {}

    # set up the array of gaicb pointers
    reqs = (c_gaicb_p * len(names))()
    for i, name in enumerate(names):
        g = gaicb()
        ctypes.memset(ctypes.byref(g), 0, ctypes.sizeof(gaicb))
        g.ar_name = name
        reqs[i] = ctypes.pointer(g)

    # get the records; this does i/o and blocks
    ret = getaddrinfo_a(GAI_WAIT, reqs, len(names), None)
    assert ret == 0

    # parse the records out of all the structs
    for req in reqs:
        name = req.contents.ar_name
        res = req.contents.ar_result.contents
        ret = getnameinfo(res.ai_addr, res.ai_addrlen,
                          host, NI_MAXHOST, None, 0, NI_NUMERICHOST)
        assert ret == 0
        result[name] = host.value

    return result
示例#16
0
def do_replay(args):
    "Main replay function"

    handle, access = TryOpenFile(args.device_path)
    if handle is None:
        return

    fp = open('replay.dump', 'r')
    lineno = 1
    while lineno < args.start:
        fp.readline()
        lineno += 1
    while lineno <= args.end:
        line = fp.readline()
        if not line:
            break
        ioctl_code, input_ptr, input_length, output_ptr, output_length, b = eval(line) # Ugh...
        ctypes.memset(buffer_ptr, 0, 0x1000)
        offset = 0
        while offset < input_length:
            buffer_ptr[offset] = b[offset]
            offset += 1
        print('Replaying call #%d...' % lineno)
        status = DeviceIoControl(handle, ioctl_code, input_ptr, input_length, output_ptr, output_length)
        print('IOCTL result: %08X' % status)
        lineno += 1
    NtClose(handle)
示例#17
0
def _set_argv(process_name):
  """
  Overwrites our argv in a similar fashion to how it's done in C with:
  strcpy(argv[0], "new_name");
  """

  if Py_GetArgcArgv is None:
    return

  global _PROCESS_NAME

  # both gets the current process name and initializes _MAX_NAME_LENGTH

  current_name = get_process_name()

  argv, argc = ctypes.c_int(0), argc_t()
  Py_GetArgcArgv(argv, ctypes.pointer(argc))

  if len(process_name) > _MAX_NAME_LENGTH:
    raise IOError("Can't rename process to something longer than our initial name (this would overwrite memory used for the env)")

  # space we need to clear
  zero_size = max(len(current_name), len(process_name))

  ctypes.memset(argc.contents, 0, zero_size + 1)  # null terminate the string's end
  ctypes.memmove(argc.contents, process_name, len(process_name))
  _PROCESS_NAME = process_name
示例#18
0
def zerome(string):
    """
    securely erase strings ...
    for windows: ctypes.cdll.msvcrt.memset
    """
    bufsize = len(string) + 1
    offset = sys.getsizeof(string) - bufsize
    ctypes.memset(id(string) + offset, 0, bufsize)
示例#19
0
文件: device.py 项目: mvduin/py-uio
 def fill( rgn, length=None, offset=0, value=0 ):
     if value not in range(256):
         raise ValueError( "invalid fill value" )
     if length is None:
         length = rgn.mappable
     # map ctypes instance (does all necessary error checking)
     mem = (ubyte * length).from_buffer( rgn._mmap, offset )
     ctypes.memset( mem, value, length )
示例#20
0
def _shred( string ):
    """Find memory of a string and override it."""
    f = "finding offset"
    header = ctypes.string_at( id(f), sys.getsizeof(f) ).find(f)
    location = id(string) + header
    size = sys.getsizeof(string) - header
    #print "Clearing 0x%08x size %i bytes" % (location, size)
    ctypes.memset( location, 0, size )
示例#21
0
def RawValue(typecode_or_type, *args):
    '''
    Returns a ctypes object allocated from shared memory
    '''
    type_ = typecode_to_type.get(typecode_or_type, typecode_or_type)
    obj = _new_value(type_)
    ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj))
    obj.__init__(*args)
    return obj
示例#22
0
文件: coredump.py 项目: cyrillos/criu
	def _gen_prstatus(self, pid, tid):
		"""
		Generate NT_PRSTATUS note for thread tid of process pid.
		"""
		core	= self.cores[tid]
		regs	= core["thread_info"]["gpregs"]
		pstree	= self.pstree[pid]

		prstatus = elf.elf_prstatus()

		ctypes.memset(ctypes.addressof(prstatus), 0, ctypes.sizeof(prstatus))

		#FIXME setting only some of the fields for now. Revisit later.
		prstatus.pr_pid		= tid
		prstatus.pr_ppid	= pstree["ppid"]
		prstatus.pr_pgrp	= pstree["pgid"]
		prstatus.pr_sid		= pstree["sid"]

		prstatus.pr_reg.r15		= regs["r15"]
		prstatus.pr_reg.r14		= regs["r14"]
		prstatus.pr_reg.r13		= regs["r13"]
		prstatus.pr_reg.r12		= regs["r12"]
		prstatus.pr_reg.rbp		= regs["bp"]
		prstatus.pr_reg.rbx		= regs["bx"]
		prstatus.pr_reg.r11		= regs["r11"]
		prstatus.pr_reg.r10		= regs["r10"]
		prstatus.pr_reg.r9		= regs["r9"]
		prstatus.pr_reg.r8		= regs["r8"]
		prstatus.pr_reg.rax		= regs["ax"]
		prstatus.pr_reg.rcx		= regs["cx"]
		prstatus.pr_reg.rdx		= regs["dx"]
		prstatus.pr_reg.rsi		= regs["si"]
		prstatus.pr_reg.rdi		= regs["di"]
		prstatus.pr_reg.orig_rax	= regs["orig_ax"]
		prstatus.pr_reg.rip		= regs["ip"]
		prstatus.pr_reg.cs		= regs["cs"]
		prstatus.pr_reg.eflags		= regs["flags"]
		prstatus.pr_reg.rsp		= regs["sp"]
		prstatus.pr_reg.ss		= regs["ss"]
		prstatus.pr_reg.fs_base		= regs["fs_base"]
		prstatus.pr_reg.gs_base		= regs["gs_base"]
		prstatus.pr_reg.ds		= regs["ds"]
		prstatus.pr_reg.es		= regs["es"]
		prstatus.pr_reg.fs		= regs["fs"]
		prstatus.pr_reg.gs		= regs["gs"]

		nhdr = elf.Elf64_Nhdr()
		nhdr.n_namesz	= 5
		nhdr.n_descsz	= ctypes.sizeof(elf.elf_prstatus())
		nhdr.n_type	= elf.NT_PRSTATUS

		note = elf_note()
		note.data	= prstatus
		note.owner	= "CORE"
		note.nhdr 	= nhdr

		return note
示例#23
0
文件: terminal.py 项目: ckelsel/vim
	def _win32_load_kernel (self):
		if self.unix:
			return False
		import ctypes
		if not self.kernel32:
			self.kernel32 = ctypes.windll.LoadLibrary("kernel32.dll")
		if not self.textdata:
			self.textdata = ctypes.create_string_buffer('0' * 2048)
		ctypes.memset(self.textdata, 0, 2048)
		return True
    def ioctl(self, driver_handle: ctypes.c_void_p, ioctl_code: ctypes.c_ulong, input_bytes: ctypes.c_void_p, input_bytes_count: ctypes.c_size_t, output_bytes: ctypes.c_void_p, output_bytes_count: ctypes.c_size_t):
        """ Wrapper for DeviceIoControl """
        overlapped = self.libk.OVERLAPPED()
        ctypes.memset(ctypes.addressof(overlapped), 0, ctypes.sizeof(overlapped))

        ret = ctypes.windll.kernel32.DeviceIoControl(driver_handle, ioctl_code, input_bytes, input_bytes_count, output_bytes, output_bytes_count, None, ctypes.byref(overlapped))

        # We expect this to error, which matches the others ^_^
        if ret == False:
            raise ctypes.WinError()
示例#25
0
 def set_arg_name(self, new_name):
     self.argc = ctypes.c_int(0)
     self.argv = self.argv_ptr()
     self.Py_GetArgcArgv(self.argc, ctypes.pointer(self.argv))
     old_size = len(self.get_arg_name())
     size = len(new_name)
     if size >= self.max_size:
       size = self.max_size
     zero_size = max(old_size, size)
     ctypes.memset(self.argv.contents, 0, (zero_size + 1)) # We're terminated
     ctypes.memmove(self.argv.contents, new_name, size)
示例#26
0
    def delete_save_at_index(self, index):
        """Remove the save at the given index."""
        directory_frames, data_blocks = self._gather_save(index)
        for frame in directory_frames:
            # reset frame to unused state
            memset(addressof(frame), 0, sizeof(frame))
            DirectoryFrame.__init__(frame)

        for data_block in data_blocks:
            # zero out block
            memset(addressof(data_block), 0, sizeof(data_block))
示例#27
0
def RawArray(typecode_or_type, size_or_initializer):
    type_ = typecode_to_type.get(typecode_or_type, typecode_or_type)
    if isinstance(size_or_initializer, (int, long)):
        type_ = type_ * size_or_initializer
        obj = _new_value(type_)
        ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj))
        return obj
    else:
        type_ = type_ * len(size_or_initializer)
        result = _new_value(type_)
        result.__init__(*size_or_initializer)
        return result
示例#28
0
文件: vacutils.py 项目: yuw726/vac
def setProcessName(processName):

   try:
     # Load the libc symbols
     libc = ctypes.cdll.LoadLibrary('libc.so.6')

     # Set up the C-style string
     s = ctypes.create_string_buffer(len(processName) + 1)
     s.value = processName

     # PR_SET_NAME=15 in /usr/include/linux/prctl.h
     libc.prctl(15, ctypes.byref(s), 0, 0, 0) 

   except:
     logLine('Failed setting process name to ' + processName + ' using prctl')
     return
              
   try:
     # Now find argv[] so we can overwrite it too     
     argc_t = ctypes.POINTER(ctypes.c_char_p)

     Py_GetArgcArgv = ctypes.pythonapi.Py_GetArgcArgv
     Py_GetArgcArgv.restype = None
     Py_GetArgcArgv.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(argc_t)]

     argv = ctypes.c_int(0)
     argc = argc_t()
     Py_GetArgcArgv(argv, ctypes.pointer(argc))

     # Count up the available space
     currentSize = -1

     for oneArg in argc:
       try:
         # start from -1 to cancel the first "+ 1"
         currentSize += len(oneArg) + 1
       except:
         break

     # Cannot write more than already there
     if len(processName) > currentSize:
       processName = processName[:currentSize]

     # Zero what is already there
     ctypes.memset(argc.contents, 0, currentSize + 1)

     # Write in the new process name
     ctypes.memmove(argc.contents, processName, len(processName))

   except:
     logLine('Failed setting process name in argv[] to ' + processName)
     return
          
示例#29
0
 def reset(self):
     """Reset the match.  Parameters are set to their default value, any
     flags are cleared."""
     ct.memset(ct.byref(self._target_buf), 0, self.size)
     self._update_pointers()
     t = self._ptr[0]
     t.u.user.name = self.name
     t.u.target_size = self.size
     t.u.user.revision = self._revision
     self._flags = ct.c_uint(0)
     if self._module.init:
         self._module.init(self._ptr)
示例#30
0
文件: table.py 项目: billyom/bcc
 def __init__(self, table, keytype):
     self.Key = keytype
     self.table = table
     k = self.Key()
     kp = ct.pointer(k)
     # if 0 is a valid key, try a few alternatives
     if k in table:
         ct.memset(kp, 0xff, ct.sizeof(k))
         if k in table:
             ct.memset(kp, 0x55, ct.sizeof(k))
             if k in table:
                 raise Exception("Unable to allocate iterator")
     self.key = k
示例#31
0
 def initLib(self):
     '''
         加载C库并初始化,初始化成功则赋值给self.lib
     '''
     try:
         lib = ctypes.cdll.LoadLibrary('libcds_libc_cds.so')
         cds_cfg = ctypes.create_string_buffer('', 4096)
         ctypes.memset(ctypes.addressof(cds_cfg), 0, ctypes.sizeof(cds_cfg))
         ret = lib.CDS_Init(ctypes.c_ulong(0), cds_cfg)
         if ret < 0:
             print "init uniview's libcds_libc_cds.so failed: %s" % ret
         else:
             self.lib = lib
     except Exception:
         print traceback.format_exc()
示例#32
0
 def query_positions(self, query_type):
     self.login_code = self.login()
     #清空信息缓存
     memset(ctypes.byref(self.trader_Ree), 0x0, 1024 * 1024)
     if self.login_code != None and self.login_code != 0:
         self.dll.JL_QueryData(
             self.login_code, bytes(str(self.trader_user),
                                    'ascii'), query_type,
             self.trader_Ree)  # 这里是查询函数 104 是查询资金的编码,查询结果保存在Ree里
         if self.trader_Ree != None:
             self.trader_Ree.value.decode('gbk', 'ignore').split('|')
             return True
         else:
             pass
     return False
示例#33
0
def __vciFormatError(library_instance, function, HRESULT):
    """ Format a VCI error and attach failed function and decoded HRESULT
        :param CLibrary library_instance:
            Mapped instance of IXXAT vcinpl library
        :param callable function:
            Failed function
        :param HRESULT HRESULT:
            HRESULT returned by vcinpl call
        :return:
            Formatted string
    """
    buf = ctypes.create_string_buffer(constants.VCI_MAX_ERRSTRLEN)
    ctypes.memset(buf, 0, constants.VCI_MAX_ERRSTRLEN)
    library_instance.vciFormatError(HRESULT, buf, constants.VCI_MAX_ERRSTRLEN)
    return "function {} failed ({})".format(function._name, buf.value.decode('utf-8', 'replace'))
示例#34
0
文件: fuse.py 项目: nick4fake/FLACCue
    def fgetattr(self, path, buf, fip):
        ctypes.memset(buf, 0, ctypes.sizeof(c_stat))

        st = buf.contents
        if not fip:
            fh = fip
        elif self.raw_fi:
            fh = fip.contents
        else:
            fh = fip.contents.fh

        attrs = self.operations('getattr', self._decode_optional_path(path),
                                fh)
        set_st_attrs(st, attrs, use_ns=self.use_ns)
        return 0
示例#35
0
def RawArray(typecode_or_type, size_or_initializer):
    '''
    Returns a ctypes array allocated from shared memory
    '''
    type_ = typecode_to_type.get(typecode_or_type, typecode_or_type)
    if isinstance(size_or_initializer, int):
        type_ = type_ * size_or_initializer
        obj = _new_value(type_)
        ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj))
        return obj
    else:
        type_ = type_ * len(size_or_initializer)
        result = _new_value(type_)
        result.__init__(*size_or_initializer)
        return result
示例#36
0
def _setArgv(processName):
    """
  Overwrites our argv in a similar fashion to how it's done in C with:
  strcpy(argv[0], "new_name");
  """

    global currentProcessName, maxNameLength

    argv = ctypes.c_int(0)
    argc = argc_t()
    Py_GetArgcArgv(argv, ctypes.pointer(argc))

    # The original author did the memset for 256, while Jake did it for the
    # processName length (capped at 1608). I'm not sure of the reasons for
    # either of these limits, but setting it to anything higher than than the
    # length of the null terminated process name should be pointless, so opting
    # for Jake's implementation on this.

    if currentProcessName == None:
        # Getting argv via...
        # currentProcessName = " ".join(["python"] + sys.argv)
        #
        # doesn't do the trick since this will miss interpretor arguments like...
        # python -W ignore::DeprecationWarning myScript.py
        #
        # Hence we're fetching this via our ctypes argv. Alternatively we could
        # use ps, though this is less desirable:
        # "ps -p %i -o args" % os.getpid()

        args = []
        for i in range(100):
            if argc[i] == None: break
            args.append(str(argc[i]))

        currentProcessName = " ".join(args)
        maxNameLength = len(currentProcessName)

    if len(processName) > maxNameLength:
        msg = "can't rename process to something longer than our initial name since this would overwrite memory used for the env"
        raise IOError(msg)

    # space we need to clear
    zeroSize = max(len(currentProcessName), len(processName))

    ctypes.memset(argc.contents, 0,
                  zeroSize + 1)  # null terminate the string's end
    ctypes.memmove(argc.contents, processName, len(processName))
    currentProcessName = processName
示例#37
0
def SetInfoForStringDescriptor(cfg, manufacturer, productDescription,
                               serialNumber):

    # verify length of strings
    if (len(manufacturer) >= _ft.FT_MAX_MANUFACTURER_SIZE):
        return False
    if (len(productDescription) >= _ft.FT_MAX_DESCRIPTION_SIZE):
        return False
    if (len(serialNumber) >= _ft.FT_MAX_SERIAL_NUMBER_SIZE):
        return False

    # convert strings to bytearrays
    manufacturer = bytearray(manufacturer, 'utf-8')
    productDescription = bytearray(productDescription, 'utf-8')
    serialNumber = bytearray(serialNumber, 'utf-8')

    ctypes.memset(cfg.StringDescriptors, 0, 128)
    desc = cfg.StringDescriptors

    # copy manufacturer
    offset = 0
    desc[offset] = len(manufacturer) * 2 + 2
    desc[offset + 1] = 0x3
    offset += 2
    for i in range(0, len(manufacturer)):
        desc[int(offset + (i * 2))] = manufacturer[i]
        desc[int(offset + (i * 2) + 1)] = 0x0

    # copy product description
    offset += len(manufacturer) * 2
    desc[offset] = len(productDescription) * 2 + 2
    desc[offset + 1] = 0x3
    offset += 2
    for i in range(0, len(productDescription)):
        desc[int(offset + (i * 2))] = productDescription[i]
        desc[int(offset + (i * 2) + 1)] = 0x0

    # copy serial number
    offset += len(productDescription) * 2
    desc[offset] = len(serialNumber) * 2 + 2
    desc[offset + 1] = 0x3
    offset += 2
    for i in range(0, len(serialNumber)):
        desc[int(offset + (i * 2))] = serialNumber[i]
        desc[int(offset + (i * 2) + 1)] = 0x0

    #for e in desc: print "%x" % e
    return True
示例#38
0
    def __set__(self, instance, value):
        if instance is None:
            raise AttributeError()
        data = getattr(instance, self.data)
        sizeof = ctypes.sizeof(data)
        value_len = len(value)

        if value_len > sizeof:
            raise ValueError(
                'value too long (should be at most {} bytes)'.format(sizeof))

        if self.size is not None:
            setattr(instance, self.size, value_len)

        ctypes.memset(data, 0, sizeof)
        ctypes.memmove(data, value, value_len)
示例#39
0
 def finalize(self, isa, callconv=0, options=None):
     """
     The program object is safe to be deleted after ``finalize``.
     """
     code_object = drvapi.hsa_code_object_t()
     control_directives = drvapi.hsa_ext_control_directives_t()
     ctypes.memset(ctypes.byref(control_directives), 0,
                   ctypes.sizeof(control_directives))
     hsa.hsa_ext_program_finalize(self._id,
                                  isa,
                                  callconv,
                                  control_directives,
                                  options,
                                  enums.HSA_CODE_OBJECT_TYPE_PROGRAM,
                                  ctypes.byref(code_object))
     return CodeObject(code_object)
示例#40
0
def bit_sort(input_file, output_file):
    vector = BitVector()
    ctypes.memset(vector, 0, len(vector))

    with open(input_file, 'r') as input_fd:
        while True:
            line = input_fd.readline()
            if not line:
                with open(output_file, 'w') as output_fd:
                    for i in range(MAX):
                        if get_bit(vector, i):
                            output_fd.write('%07d\n' % i)
                return
            else:
                num = int(line.strip())
                set_bit(vector, num)
示例#41
0
def _reset(ADQAPI, adq_cu, adq_num, base_addr, hist_size):
    # Write zero to all bins

    if ADQAPI.ADQ_IsUSB3Device(adq_cu, adq_num):
        zero_block = (ct.c_uint32 * hist_size)()
        ct.memset(ct.byref(zero_block), 0, hist_size)
        status = ADQAPI.ADQ_WriteBlockUserRegister(adq_cu, adq_num, 2,
                                                   base_addr,
                                                   ct.byref(zero_block),
                                                   hist_size * 4, 1)
        print('ADQAPI.ADQ_WriteBlockUserRegister returned {}'.format(
            adq_status(status)))
    else:
        for idx in range(hist_size):
            ADQAPI.ADQ_WriteUserRegister(adq_cu, adq_num, 2, base_addr + idx,
                                         0x0, 0x0, 0)
示例#42
0
def to_sockaddr(ip, port):
    if ":" not in ip:
        sin = sockaddr_in()
        ctypes.memset(ctypes.byref(sin), 0, ctypes.sizeof(sin))
        sin.sin_family = socket.AF_INET
        sin.sin_addr.s_addr = inet_addr(ip)
        sin.sin_port = socket.htons(port)
        return sin
    else:
        sin6 = sockaddr_in6()
        ctypes.memset(ctypes.byref(sin6), 0, ctypes.sizeof(sin6))
        sin6.sin6_family = socket.AF_INET6
        d = inet_pton(socket.AF_INET6, ip)
        # it seems like there should be a better way to do this...
        ctypes.memmove(sin6.sin6_addr.Byte, d, ctypes.sizeof(sin6.sin6_addr.Byte))
        sin6.sin6_port = socket.htons(port)
        return sin6
示例#43
0
文件: render.py 项目: cnmade/kitty
def add_dline(buf, cell_width, position, thickness, cell_height):
    a = min(position - thickness, cell_height - 1)
    b = min(position, cell_height - 1)
    top, bottom = min(a, b), max(a, b)
    deficit = 2 - (bottom - top)
    if deficit > 0:
        if bottom + deficit < cell_height:
            bottom += deficit
        elif bottom < cell_height - 1:
            bottom += 1
            if deficit > 1:
                top -= deficit - 1
        else:
            top -= deficit
    for y in {top, bottom}:
        ctypes.memset(
            ctypes.addressof(buf) + (cell_width * y), 255, cell_width)
示例#44
0
    def render(self):
        if not self.svg:
            self.composition = None
            self.rendered_svg = None
            return

        if self.svg == self.rendered_svg:
            return

        overlay_size = self.render_size * self.scale_factor
        stride = libcairo.cairo_format_stride_for_width(
            int(cairo.FORMAT_ARGB32), overlay_size.width)
        overlay_buffer = Gst.Buffer.new_allocate(None,
                                                 stride * overlay_size.height)
        with _gst_buffer_map(overlay_buffer, Gst.MapFlags.WRITE) as mapped:
            # Fill with transparency and create surface from buffer.
            ctypes.memset(ctypes.addressof(mapped), 0, ctypes.sizeof(mapped))
            surface = libcairo.cairo_image_surface_create_for_data(
                ctypes.addressof(mapped), int(cairo.FORMAT_ARGB32),
                overlay_size.width, overlay_size.height, stride)

            # Render the SVG overlay.
            data = self.svg.encode('utf-8')
            context = libcairo.cairo_create(surface)
            libcairo.cairo_scale(context, self.scale_factor, self.scale_factor)
            handle = librsvg.rsvg_handle_new_from_data(data, len(data), 0)
            librsvg.rsvg_handle_render_cairo(handle, context)
            librsvg.rsvg_handle_close(handle, 0)
            libgobject.g_object_unref(handle)
            libcairo.cairo_surface_flush(surface)
            libcairo.cairo_surface_destroy(surface)
            libcairo.cairo_destroy(context)

            # Attach overlay to VideoOverlayComposition.
            GstVideo.buffer_add_video_meta(overlay_buffer,
                                           GstVideo.VideoFrameFlags.NONE,
                                           GstVideo.VideoFormat.BGRA,
                                           overlay_size.width,
                                           overlay_size.height)
            rect = GstVideo.VideoOverlayRectangle.new_raw(
                overlay_buffer, 0, 0, self.render_size.width,
                self.render_size.height,
                GstVideo.VideoOverlayFormatFlags.PREMULTIPLIED_ALPHA)
            self.composition = GstVideo.VideoOverlayComposition.new(rect)
            self.rendered_svg = self.svg
示例#45
0
def get_screenshot():
    window_handle = _get_window_handle()
    dimensions = _get_window_dimensions(window_handle)
    window_dc = ctypes.windll.user32.GetWindowDC(window_handle)
    bitmap_dc = ctypes.windll.gdi32.CreateCompatibleDC(window_dc)
    bitmap = ctypes.windll.gdi32.CreateCompatibleBitmap(
        window_dc, dimensions.width, dimensions.height)
    ctypes.windll.gdi32.SelectObject(bitmap_dc, bitmap)

    try:
        result = ctypes.windll.user32.PrintWindow(window_handle, bitmap_dc,
                                                  PW_RENDERFULLCONTENT)
        if result == 0:
            raise ScreenshotError("PrintWindow failed")

        bmi = BITMAPINFO()
        ctypes.memset(ctypes.byref(bmi), 0x00, ctypes.sizeof(bmi))
        bmi.header.size = ctypes.sizeof(BITMAPINFOHEADER)
        bmi.header.width = dimensions.width
        bmi.header.height = dimensions.height
        bmi.header.planes = 1
        bmi.header.bit_count = 24

        row_size = ((dimensions.width * bmi.header.bit_count + 31) // 32) * 4
        buffer_size = row_size * dimensions.height
        buffer = ctypes.create_string_buffer(buffer_size)

        ctypes.windll.gdi32.GetDIBits(
            bitmap_dc,
            bitmap,
            0,
            dimensions.height,
            ctypes.byref(buffer),
            ctypes.byref(bmi),
            DIB_RGB_COLORS,
        )
        if result == 0 or result == ERROR_INVALID_PARAMETER:
            raise ScreenshotError("GetDIBits failed")

        return PIL.Image.frombuffer("RGB", dimensions, buffer, "raw", "BGR",
                                    row_size, -1)
    finally:
        ctypes.windll.gdi32.DeleteDC(bitmap_dc)
        ctypes.windll.gdi32.DeleteObject(bitmap)
        ctypes.windll.user32.ReleaseDC(window_handle, window_dc)
示例#46
0
文件: mm.py 项目: derez/thundergate
    def alloc(self, sz=None):
        if sz == None:
            sz = self.page_sz
        if sz > self.page_sz:
            raise Exception("too big")

        victim = self.get_free(sz)
        if None is victim:
            victim = self.get_page()

        if victim[1] > sz:
            self.free_list += [(victim[0] + sz, victim[1] - sz)]

        self.allocations[victim[0]] = sz

        ctypes.memset(victim[0], 0, sz)

        return victim[0]
示例#47
0
        def ioctl(self, driver_handle: ctypes.c_void_p,
                  ioctl_code: ctypes.c_ulong, input_bytes: ctypes.c_void_p,
                  input_bytes_count: ctypes.c_size_t,
                  output_bytes: ctypes.c_void_p,
                  output_bytes_count: ctypes.c_size_t):
            """ Wrapper for DeviceIoControl """
            overlapped = self.libk.OVERLAPPED()
            ctypes.memset(ctypes.addressof(overlapped), 0,
                          ctypes.sizeof(overlapped))

            ret = ctypes.windll.kernel32.DeviceIoControl(
                driver_handle, ioctl_code, input_bytes,
                input_bytes_count, output_bytes, output_bytes_count, None,
                ctypes.byref(overlapped))

            # We expect this to error, which matches the others ^_^
            if ret == False:
                raise ctypes.WinError()