Python ctypes.get_last_error() Examples

The following are 15 code examples of ctypes.get_last_error(). 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: createminidump.py    From minidump with MIT License 6 votes vote down vote up
def enum_pids():
	
	max_array = c_ulong * 4096 # define long array to capture all the processes
	pProcessIds = max_array() # array to store the list of processes
	pBytesReturned = c_ulong() # the number of bytes returned in the array
	#EnumProcess 
	res = EnumProcesses(
		ctypes.byref(pProcessIds),
		ctypes.sizeof(pProcessIds),
		ctypes.byref(pBytesReturned)
	)
	if res == 0:
		logging.error(WinError(get_last_error()))
		return []
  
	# get the number of returned processes
	nReturned = int(pBytesReturned.value/ctypes.sizeof(c_ulong()))
	return [i for i in pProcessIds[:nReturned]]
	
#https://msdn.microsoft.com/en-us/library/windows/desktop/ms683217(v=vs.85).aspx 
Example #2
Source File: createminidump.py    From minidump with MIT License 6 votes vote down vote up
def enum_process_names():
	pid_to_name = {}
	
	for pid in enum_pids():
		pid_to_name[pid] = 'Not found'
		process_handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
		if process_handle is None:
			logging.debug('[Enum Processes]Failed to open process PID: %d Reason: %s ' % (pid, WinError(get_last_error())))
			continue
		
		image_name = (ctypes.c_char*MAX_PATH)()
		max_path = DWORD(4096)
		#res = GetProcessImageFileName(process_handle, image_name, MAX_PATH)
		res = QueryFullProcessImageName(process_handle, 0 ,image_name, ctypes.byref(max_path))
		if res == 0:
			logging.debug('[Enum Proceses]Failed GetProcessImageFileName on PID: %d Reason: %s ' % (pid, WinError(get_last_error())))
			continue
		
		pid_to_name[pid] = image_name.value.decode()
	return pid_to_name 
Example #3
Source File: utils.py    From ray with Apache License 2.0 6 votes vote down vote up
def set_kill_child_on_death_win32(child_proc):
    """Ensures the child process dies if this process dies (fate-sharing).

    Windows-only. Must be called by the parent, after spawning the child.

    Args:
        child_proc: The subprocess.Popen or subprocess.Handle object.
    """

    if isinstance(child_proc, subprocess.Popen):
        child_proc = child_proc._handle
    assert isinstance(child_proc, subprocess.Handle)

    if detect_fate_sharing_support_win32():
        if not win32_AssignProcessToJobObject(win32_job, int(child_proc)):
            import ctypes
            raise OSError(ctypes.get_last_error(),
                          "AssignProcessToJobObject() failed")
    else:
        assert False, "AssignProcessToJobObject used despite being unavailable" 
Example #4
Source File: streams.py    From win-unicode-console with MIT License 6 votes vote down vote up
def readinto(self, b):
		bytes_to_be_read = len(b)
		if not bytes_to_be_read:
			return 0
		elif bytes_to_be_read % 2:
			raise ValueError("cannot read odd number of bytes from UTF-16-LE encoded console")
		
		buffer = get_buffer(b, writable=True)
		code_units_to_be_read = bytes_to_be_read // 2
		code_units_read = c_ulong()
		
		set_last_error(ERROR_SUCCESS)
		ReadConsoleW(self.handle, buffer, code_units_to_be_read, byref(code_units_read), None)
		last_error = get_last_error()
		if last_error == ERROR_OPERATION_ABORTED:
			time.sleep(0.1)	# wait for KeyboardInterrupt
		if last_error != ERROR_SUCCESS:
			raise WinError(last_error)
		
		if buffer[0] == EOF:
			return 0
		else:
			return 2 * code_units_read.value # bytes read 
Example #5
Source File: streams.py    From win-unicode-console with MIT License 6 votes vote down vote up
def write(self, b):
		bytes_to_be_written = len(b)
		buffer = get_buffer(b)
		code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2
		code_units_written = c_ulong()
		
		if code_units_to_be_written == 0 != bytes_to_be_written:
			raise ValueError("two-byte code units expected, just one byte given")
		
		if not WriteConsoleW(self.handle, buffer, code_units_to_be_written, byref(code_units_written), None):
			exc = WinError(get_last_error())
			if exc.winerror == ERROR_NOT_ENOUGH_MEMORY:
				exc.strerror += " Try to lower `win_unicode_console.streams.MAX_BYTES_WRITTEN`."
			raise exc
		
		return 2 * code_units_written.value # bytes written 
Example #6
Source File: createminidump.py    From minidump with MIT License 5 votes vote down vote up
def is64bitProc(process_handle):
	is64 = BOOL()
	res = IsWow64Process(process_handle, ctypes.byref(is64))
	if res == 0:
		logging.warning('Failed to get process version info!')
		WinError(get_last_error())
	return not bool(is64.value)
	
# https://waitfordebug.wordpress.com/2012/01/27/pid-enumeration-on-windows-with-pure-python-ctypes/ 
Example #7
Source File: createminidump.py    From minidump with MIT License 5 votes vote down vote up
def create_dump(pid, output_filename, mindumptype, with_debug = False):
	if with_debug:
		logging.debug('Enabling SeDebugPrivilege')
		assigned = enable_debug_privilege()
		msg = ['failure', 'success'][assigned]
		logging.debug('SeDebugPrivilege assignment %s' % msg)
	
	logging.debug('Opening process PID: %d' % pid)
	process_handle = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
	if process_handle is None:
		logging.warning('Failed to open process PID: %d' % pid)
		logging.error(WinError(get_last_error()))
		return
	logging.debug('Process handle: 0x%04x' % process_handle)
	is64 = is64bitProc(process_handle)
	if is64 != IS_PYTHON_64:
		logging.warning('process architecture mismatch! This could case error! Python arch: %s Target process arch: %s' % ('x86' if not IS_PYTHON_64 else 'x64', 'x86' if not is64 else 'x64'))
	
	logging.debug('Creating file handle for output file')
	file_handle = CreateFile(output_filename, FILE_GENERIC_READ | FILE_GENERIC_WRITE, 0, None,  FILE_CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, None)
	if file_handle == -1:
		logging.warning('Failed to create file')
		logging.error(WinError(get_last_error()))
		return
	logging.debug('Dumping process to file')
	res = MiniDumpWriteDump(process_handle, pid, file_handle, mindumptype, 0,0,0)
	if not bool(res):
		logging.warning('Failed to dump process to file')
		logging.error(WinError(get_last_error()))
	logging.info('Dump file created succsessfully')
	CloseHandle(file_handle)
	CloseHandle(process_handle) 
Example #8
Source File: usb1.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_errno():
        raise NotImplementedError(
            'Your python version does not support errno/last_error'
        ) 
Example #9
Source File: usb1.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def getPollFDList(self):
        """
        Return file descriptors to be used to poll USB events.
        You should not have to call this method, unless you are integrating
        this class with a polling mechanism.
        """
        pollfd_p_p = libusb1.libusb_get_pollfds(self.__context_p)
        if not pollfd_p_p:
            errno = get_errno()
            if errno:
                raise OSError(errno)
            else:
                # Assume not implemented
                raise NotImplementedError(
                    'Your libusb does not seem to implement pollable FDs')
        try:
            result = []
            append = result.append
            fd_index = 0
            while pollfd_p_p[fd_index]:
                append((
                    pollfd_p_p[fd_index].contents.fd,
                    pollfd_p_p[fd_index].contents.events,
                ))
                fd_index += 1
        finally:
            _free(pollfd_p_p)
        return result 
Example #10
Source File: win32.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def enable_ctrl_c_support() -> None:
    """Enable ctrl+c support for aea.cli command to be tested on windows platform."""
    if platform.system() != "Windows":
        return

    kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)  # type: ignore

    if not kernel32.SetConsoleCtrlHandler(None, False):
        logger.debug(f"SetConsoleCtrlHandler Error: {ctypes.get_last_error()}")  # type: ignore 
Example #11
Source File: platform_utils_win32.py    From git-repo with Apache License 2.0 5 votes vote down vote up
def _create_symlink(source, link_name, dwFlags):
  if not CreateSymbolicLinkW(link_name, source,
                             dwFlags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE):
    # See https://github.com/golang/go/pull/24307/files#diff-b87bc12e4da2497308f9ef746086e4f0
    # "the unprivileged create flag is unsupported below Windows 10 (1703, v10.0.14972).
    # retry without it."
    if not CreateSymbolicLinkW(link_name, source, dwFlags):
      code = get_last_error()
      error_desc = FormatError(code).strip()
      if code == ERROR_PRIVILEGE_NOT_HELD:
        raise OSError(errno.EPERM, error_desc, link_name)
      _raise_winerror(
          code,
          'Error creating symbolic link \"%s\"'.format(link_name)) 
Example #12
Source File: platform_utils_win32.py    From git-repo with Apache License 2.0 5 votes vote down vote up
def readlink(path):
  reparse_point_handle = CreateFileW(path,
                                     0,
                                     0,
                                     None,
                                     OPEN_EXISTING,
                                     FILE_FLAG_OPEN_REPARSE_POINT |
                                     FILE_FLAG_BACKUP_SEMANTICS,
                                     None)
  if reparse_point_handle == INVALID_HANDLE_VALUE:
    _raise_winerror(
        get_last_error(),
        'Error opening symbolic link \"%s\"'.format(path))
  target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
  n_bytes_returned = DWORD()
  io_result = DeviceIoControl(reparse_point_handle,
                              FSCTL_GET_REPARSE_POINT,
                              None,
                              0,
                              target_buffer,
                              len(target_buffer),
                              byref(n_bytes_returned),
                              None)
  CloseHandle(reparse_point_handle)
  if not io_result:
    _raise_winerror(
        get_last_error(),
        'Error reading symbolic link \"%s\"'.format(path))
  rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer)
  if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK:
    return _preserve_encoding(path, rdb.SymbolicLinkReparseBuffer.PrintName)
  elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
    return _preserve_encoding(path, rdb.MountPointReparseBuffer.PrintName)
  # Unsupported reparse point type
  _raise_winerror(
      ERROR_NOT_SUPPORTED,
      'Error reading symbolic link \"%s\"'.format(path)) 
Example #13
Source File: sniffer.py    From pyspinel with Apache License 2.0 5 votes vote down vote up
def check_fifo(fifo):
    if sys.platform == 'win32':
        kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
        handle = msvcrt.get_osfhandle(fifo.fileno())
        data = b''
        p_data = ctypes.c_char_p(data)
        written = ctypes.c_ulong(0)
        while True:
            time.sleep(FIFO_CHECK_INTERVAL)
            if not kernel32.WriteFile(handle, p_data, 0, ctypes.byref(written),
                                      None):
                error = ctypes.get_last_error()
                if error in (
                        0xe8,  # ERROR_NO_DATA
                        0xe9,  # ERROR_PIPE_NOT_CONNECTED
                ):
                    os._exit(0)
                else:
                    raise ctypes.WinError(error)
    else:
        while True:
            time.sleep(FIFO_CHECK_INTERVAL)
            try:
                os.stat(fifo.name)
            except OSError:
                os._exit(0) 
Example #14
Source File: streams.py    From win-unicode-console with MIT License 5 votes vote down vote up
def is_a_console(self):
		if self.handle is None:
			return False
		
		if GetConsoleMode(self.handle, byref(c_ulong())):
			return True
		else:
			last_error = get_last_error()
			if last_error == ERROR_INVALID_HANDLE:
				return False
			else:
				raise WinError(last_error) 
Example #15
Source File: running.py    From thonny with MIT License 5 votes vote down vote up
def _check_alloc_console(self) -> None:
        if sys.executable.endswith("pythonw.exe"):
            # These don't have console allocated.
            # Console is required for sending interrupts.

            # AllocConsole would be easier but flashes console window

            import ctypes

            kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)

            exe = sys.executable.replace("pythonw.exe", "python.exe")

            cmd = [exe, "-c", "print('Hi!'); input()"]
            child = subprocess.Popen(
                cmd,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                shell=True,
            )
            child.stdout.readline()
            result = kernel32.AttachConsole(child.pid)
            if not result:
                err = ctypes.get_last_error()
                logging.info("Could not allocate console. Error code: " + str(err))
            child.stdin.write(b"\n")
            try:
                child.stdin.flush()
            except Exception:
                # May happen eg. when installation path has "&" in it
                # See https://bitbucket.org/plas/thonny/issues/508/cant-allocate-windows-console-when
                # Without flush the console window becomes visible, but Thonny can be still used
                logging.getLogger("thonny").exception("Problem with finalizing console allocation")