Python ctypes.GetLastError() Examples
The following are 30
code examples of ctypes.GetLastError().
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: ae.py From Splunk-Assessment-of-Mitigation-Implementations with The Unlicense | 7 votes |
def checkFirmwareType(self): # Load in kernel32.dll kernel32_dll = ctypes.WinDLL("C:\\Windows\\System32\\kernel32.dll") # Because we're using bogus parameters in the function call, it # should always fail (return 0). if kernel32_dll.GetFirmwareEnvironmentVariableW(ctypes.c_wchar_p(""), ctypes.c_wchar_p("{00000000-0000-0000-0000-000000000000}"), None, ctypes.c_int(0)) == 0: # Check the last error returned to determine firmware type. # If the error is anything other than ERROR_INVALID_FUNCTION # or ERROR_NOACCESS, raise an exception. last_error = ctypes.GetLastError() if last_error == self._ERROR_INVALID_FUNCTION: return "Legacy" elif last_error == self._ERROR_NOACCESS: return "UEFI" else: raise ctypes.WinError() else: return "Unknown" # Check for PAE, SMEP, SMAP, and NX hardware support using CPUID.
Example #2
Source File: win32_file_watcher.py From python-compat-runtime with Apache License 2.0 | 6 votes |
def _monitor(self): buff = ctypes.create_string_buffer(_BUFF_SIZE) while not self._stop.isSet(): size_returned = ctypes.c_ulong(0) result = ctypes.windll.kernel32.ReadDirectoryChangesW( self._directory_handle, buff, ctypes.c_ulong(_BUFF_SIZE), True, # recursive. ctypes.c_ulong(_FILE_NOTIFY_CHANGE_ANY), ctypes.byref(size_returned), None, None) # this is a blocking call. if result == 0 and ctypes.GetLastError() == _ERROR_NOTIFY_ENUM_DIR: logging.warning('Buffer overflow while monitoring for file changes.') # we need to notify that something changed anyway with self._lock: self._change_set |= {'Unknown file'} if result != 0 and size_returned.value != 0: additional_changes = _parse_buffer(buff) with self._lock: self._change_set |= additional_changes self._change_event.set()
Example #3
Source File: file_path.py From luci-py with Apache License 2.0 | 6 votes |
def enable_privilege(name): """Enables the privilege for the current process token. Returns: - True if the assignment is successful. """ SE_PRIVILEGE_ENABLED = 2 ERROR_NOT_ALL_ASSIGNED = 1300 size = ctypes.sizeof(TOKEN_PRIVILEGES) + ctypes.sizeof(LUID_AND_ATTRIBUTES) buf = ctypes.create_string_buffer(size) tp = ctypes.cast(buf, ctypes.POINTER(TOKEN_PRIVILEGES)).contents tp.count = 1 tp.get_array()[0].LUID = get_luid(name) tp.get_array()[0].Attributes = SE_PRIVILEGE_ENABLED token = get_process_token() try: if not AdjustTokenPrivileges(token, False, tp, 0, None, None): # pylint: disable=undefined-variable raise WindowsError( u'AdjustTokenPrivileges(%r): failed: %s' % (name, ctypes.GetLastError())) finally: windll.kernel32.CloseHandle(token) return ctypes.GetLastError() != ERROR_NOT_ALL_ASSIGNED
Example #4
Source File: file_path.py From luci-py with Apache License 2.0 | 6 votes |
def GetShortPathName(long_path): """Returns the Windows short path equivalent for a 'long' path.""" path = fs.extend(long_path) chars = windll.kernel32.GetShortPathNameW(path, None, 0) if chars: p = wintypes.create_unicode_buffer(chars) if windll.kernel32.GetShortPathNameW(path, p, chars): return fs.trim(p.value) err = ctypes.GetLastError() if err: # pylint: disable=undefined-variable msg = u'GetShortPathName(%s): %s (%d)' % ( long_path, FormatError(err), err) raise WindowsError(err, msg.encode('utf-8')) return None
Example #5
Source File: file_path.py From luci-py with Apache License 2.0 | 6 votes |
def QueryDosDevice(drive_letter): """Returns the Windows 'native' path for a DOS drive letter.""" assert re.match(r'^[a-zA-Z]:$', drive_letter), drive_letter assert isinstance(drive_letter, six.text_type) # Guesswork. QueryDosDeviceW never returns the required number of bytes. chars = 1024 drive_letter = drive_letter p = wintypes.create_unicode_buffer(chars) if not windll.kernel32.QueryDosDeviceW(drive_letter, p, chars): err = ctypes.GetLastError() if err: # pylint: disable=undefined-variable msg = u'QueryDosDevice(%s): %s (%d)' % ( drive_letter, FormatError(err), err) raise WindowsError(err, msg.encode('utf-8')) return p.value
Example #6
Source File: windows.py From cloudbase-init with Apache License 2.0 | 6 votes |
def get_volumes(self): """Retrieve a list with all the volumes found on all disks.""" volumes = [] volume = ctypes.create_unicode_buffer(chr(0) * self.MAX_PATH) handle_volumes = kernel32.FindFirstVolumeW(volume, self.MAX_PATH) if handle_volumes == self.INVALID_HANDLE_VALUE: raise exception.WindowsCloudbaseInitException( "FindFirstVolumeW failed: %r") try: while True: volumes.append(volume.value) found = kernel32.FindNextVolumeW(handle_volumes, volume, self.MAX_PATH) if not found: errno = ctypes.GetLastError() if errno == self.ERROR_NO_MORE_FILES: break else: raise exception.WindowsCloudbaseInitException( "FindNextVolumeW failed: %r") finally: kernel32.FindVolumeClose(handle_volumes) return volumes
Example #7
Source File: lib_win32.py From marsnake with GNU General Public License v3.0 | 6 votes |
def get_user_name(): global os_encoding DWORD = c_uint32 nSize = DWORD(0) windll.advapi32.GetUserNameA(None, byref(nSize)) error = GetLastError() ERROR_INSUFFICIENT_BUFFER = 122 if error != ERROR_INSUFFICIENT_BUFFER: raise WinError(error) lpBuffer = create_string_buffer('', nSize.value + 1) success = windll.advapi32.GetUserNameA(lpBuffer, byref(nSize)) if not success: raise WinError() return lpBuffer.value.decode(encoding = os_encoding).encode("utf8")
Example #8
Source File: terminal.py From terminal with MIT License | 6 votes |
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 #9
Source File: winutil.py From flare-fakenet-ng with Apache License 2.0 | 6 votes |
def get_process_image_filename(self, pid): process_name = None if pid == 4: # Skip the inevitable errno 87, invalid parameter process_name = 'System' elif pid: hProcess = windll.kernel32.OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, False, pid) if hProcess: lpImageFileName = create_string_buffer(MAX_PATH) if windll.psapi.GetProcessImageFileNameA(hProcess, lpImageFileName, MAX_PATH) > 0: process_name = os.path.basename(lpImageFileName.value) else: self.logger.error('Failed to call GetProcessImageFileNameA, %d' % (ctypes.GetLastError())) windll.kernel32.CloseHandle(hProcess) return process_name
Example #10
Source File: terminal.py From collection with MIT License | 6 votes |
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 #11
Source File: win32_support.py From honeything with GNU General Public License v3.0 | 6 votes |
def fcntl(fd, op, arg=0): if op == F_GETFD or op == F_GETFL: return 0 elif op == F_SETFD: # Check that the flag is CLOEXEC and translate if arg == FD_CLOEXEC: success = SetHandleInformation(fd, HANDLE_FLAG_INHERIT, arg) if not success: raise ctypes.GetLastError() else: raise ValueError("Unsupported arg") #elif op == F_SETFL: ## Check that the flag is NONBLOCK and translate #if arg == os.O_NONBLOCK: ##pass #result = ioctlsocket(fd, FIONBIO, 1) #if result != 0: #raise ctypes.GetLastError() #else: #raise ValueError("Unsupported arg") else: raise ValueError("Unsupported op")
Example #12
Source File: SessionChangeNotifier.py From EventGhost with GNU General Public License v2.0 | 6 votes |
def Register(self): success = WTSRegisterSessionNotification( eg.messageReceiver.hwnd, NOTIFY_FOR_ALL_SESSIONS ) if success: self.inited = True return errorNum = GetLastError() # if we get the error RPC_S_INVALID_BINDING (1702), the system # hasn't started all needed services. For this reason we wait some # time and try it again. if errorNum == 1702: self.retryCount += 1 if self.retryCount > 60: # if we tried it to often, give up eg.PrintError("WTSRegisterSessionNotification timeout") return eg.scheduler.AddTask(2.0, self.Register) return # some other error has happened raise SystemError("WTSRegisterSessionNotification", errorNum)
Example #13
Source File: symbol_tool.py From windbgtool with MIT License | 6 votes |
def load_pdb(self, pdb_filename): size = os.path.getsize(pdb_filename) module_base = 0x10000000 module_base = SymLoadModuleEx( self.process, 0, ctypes.c_char_p(pdb_filename.encode('utf-8')), None, module_base, size, None, 0 ) if not module_base: raise Exception('Failed SymLoadModuleEx last error: %d' % ctypes.GetLastError()) print('module_base: %x' % module_base) return module_base
Example #14
Source File: _advapi32_ctypes.py From scalyr-agent-2 with Apache License 2.0 | 5 votes |
def get_error(): error = ctypes.GetLastError() return (error, ctypes.FormatError(error))
Example #15
Source File: fs.py From luci-py with Apache License 2.0 | 5 votes |
def remove(path): """Removes a symlink on Windows 7 and later. Does not delete the link source. If path is not a link, but a non-empty directory, will fail with a WindowsError. Useful material: CreateSymbolicLinkW: https://msdn.microsoft.com/library/windows/desktop/aa363866.aspx DeleteFileW: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363915(v=vs.85).aspx RemoveDirectoryW: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365488(v=vs.85).aspx """ path = extend(path) # pylint: disable=undefined-variable # isdir is generated dynamically. if isdir(path): if not RemoveDirectory(path): # pylint: disable=undefined-variable raise WindowsError( u'unlink(%r): could not remove directory: %s' % (path, ctypes.GetLastError())) else: if not DeleteFile(path): # pylint: disable=undefined-variable raise WindowsError( u'unlink(%r): could not delete file: %s' % (path, ctypes.GetLastError()))
Example #16
Source File: _kernel32_ctypes.py From scalyr-agent-2 with Apache License 2.0 | 5 votes |
def get_error(): error = ctypes.GetLastError() return (error, ctypes.FormatError(error))
Example #17
Source File: _secur32_ctypes.py From scalyr-agent-2 with Apache License 2.0 | 5 votes |
def get_error(): error = ctypes.GetLastError() return (error, ctypes.FormatError(error))
Example #18
Source File: _crypt32_ctypes.py From scalyr-agent-2 with Apache License 2.0 | 5 votes |
def get_error(): error = ctypes.GetLastError() return (error, ctypes.FormatError(error))
Example #19
Source File: file_path.py From luci-py with Apache License 2.0 | 5 votes |
def MoveFileEx(oldpath, newpath, flags): """Calls MoveFileEx, converting errors to WindowsError exceptions.""" old_p = fs.extend(oldpath) new_p = fs.extend(newpath) if not windll.kernel32.MoveFileExW(old_p, new_p, int(flags)): # pylint: disable=undefined-variable err = ctypes.GetLastError() msg = u'MoveFileEx(%s, %s, %d): %s (%d)' % ( oldpath, newpath, flags, FormatError(err), err) raise WindowsError(err, msg.encode('utf-8'))
Example #20
Source File: subprocess42.py From luci-py with Apache License 2.0 | 5 votes |
def ReadFile(handle, desired_bytes): """Calls kernel32.ReadFile().""" c_read = wintypes.DWORD() buff = wintypes.create_string_buffer(desired_bytes+1) # If it fails, the buffer will probably(?) not be affected. windll.kernel32.ReadFile( handle, buff, desired_bytes, wintypes.byref(c_read), None) # NULL terminate it. buff[c_read.value] = '\x00' return wintypes.GetLastError(), buff.value
Example #21
Source File: subprocess42.py From luci-py with Apache License 2.0 | 5 votes |
def PeekNamedPipe(handle): """Calls kernel32.PeekNamedPipe(). Simplified version.""" c_avail = wintypes.DWORD() c_message = wintypes.DWORD() success = windll.kernel32.PeekNamedPipe( handle, None, 0, None, wintypes.byref(c_avail), wintypes.byref(c_message)) if not success: raise OSError(wintypes.GetLastError()) return c_avail.value
Example #22
Source File: subprocess42.py From luci-py with Apache License 2.0 | 5 votes |
def __init__(self, containment): # The first process to be added to the job object. self._proc = None # https://docs.microsoft.com/windows/desktop/api/jobapi2/nf-jobapi2-createjobobjectw self._hjob = ctypes.windll.kernel32.CreateJobObjectW(None, None) if not self._hjob: # pylint: disable=undefined-variable raise WindowsError( 'Failed to create job object: %s' % ctypes.GetLastError()) # TODO(maruel): Use a completion port to listen to messages as described # at # https://docs.microsoft.com/windows/desktop/api/winnt/ns-winnt-_jobobject_associate_completion_port # TODO(maruel): Enable configuring the limit, like maximum number of # processes, working set size. obj = JOBOBJECT_EXTENDED_LIMIT_INFORMATION() obj.BasicLimitInformation.LimitFlags = ( JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION| JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE) if containment.limit_processes: obj.BasicLimitInformation.ActiveProcessLimit = ( containment.limit_processes) obj.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS if containment.limit_total_committed_memory: obj.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_JOB_MEMORY obj.JobMemoryLimit = containment.limit_total_committed_memory self._set_information(obj) # Add UI limitations. # TODO(maruel): The limitations currently used are based on Chromium's # testing needs. For example many unit tests use the clipboard, or change # the display settings (!) obj = JOBOBJECT_BASIC_UI_RESTRICTIONS( UIRestrictionsClass= JOB_OBJECT_UILIMIT_DESKTOP| JOB_OBJECT_UILIMIT_EXITWINDOWS| JOB_OBJECT_UILIMIT_GLOBALATOMS| JOB_OBJECT_UILIMIT_HANDLES) self._set_information(obj)
Example #23
Source File: subprocess42.py From luci-py with Apache License 2.0 | 5 votes |
def _set_information(self, obj): # https://docs.microsoft.com/windows/desktop/api/jobapi2/nf-jobapi2-setinformationjobobject if not ctypes.windll.kernel32.SetInformationJobObject( self._hjob, obj.info_type, ctypes.byref(obj), ctypes.sizeof(obj)): # pylint: disable=undefined-variable raise WindowsError( 'Failed to adjust job object with type %s: %s' % (obj.info_type, ctypes.GetLastError()))
Example #24
Source File: stream.py From luci-py with Apache License 2.0 | 5 votes |
def _connect_raw(self): # This is a similar procedure to the one in # https://github.com/microsoft/go-winio/blob/master/pipe.go (tryDialPipe) while True: try: return open(self._name, 'wb+', buffering=0) except (OSError, IOError): if GetLastError() != self.ERROR_PIPE_BUSY: raise time.sleep(0.001) # 1ms
Example #25
Source File: __init__.py From OpenXMolar with BSD 3-Clause "New" or "Revised" License | 5 votes |
def WinError(code=None, descr=None): if code is None: code = ctypes.GetLastError() if descr is None: descr = ctypes.FormatError(code).strip() return WindowsError(code, descr)
Example #26
Source File: storage.py From ok-client with Apache License 2.0 | 5 votes |
def replace_transactional(source, destination): # Like os.replace, but tries to be actually atomic when possible on Windows. if windll: error_code = 50 # ERROR_NOT_SUPPORTED if windll.ktmw32: tx = windll.ktmw32.CreateTransaction(None, None, 0, 0, 0, 0, None) if tx != HANDLE(-1).value: try: error_code = 0 if windll.kernel32.MoveFileTransactedW(source, destination, windll.kernel32.MoveFileTransactedW.argtypes[2](), None, 0x1 | 0x2, tx) and windll.ktmw32.CommitTransaction(tx) else ctypes.GetLastError() finally: windll.kernel32.CloseHandle(tx) else: error_code = ctypes.GetLastError() if error_code: raise ctypes.WinError(error_code) else: raise NotImplementedError("transactional file systems not supported")
Example #27
Source File: win.py From Pokemon-Terminal with GNU General Public License v3.0 | 5 votes |
def __raise_last_error(): err_no = ctypes.GetLastError() raise WindowsError(err_no, ctypes.FormatError(err_no))
Example #28
Source File: win.py From Pokemon-Terminal with GNU General Public License v3.0 | 5 votes |
def exists(name: str) -> bool: event = ctypes.windll.kernel32.OpenEventW(WindowsNamedEvent.__SYNCHRONIZE | WindowsNamedEvent.__EVENT_MODIFY_STATE, False, name) if event == 0: if ctypes.GetLastError() == WindowsNamedEvent.__ERROR_FILE_NOT_FOUND: return False else: WindowsNamedEvent.__raise_last_error() else: result = ctypes.windll.kernel32.CloseHandle(event) if result == 0: WindowsNamedEvent.__raise_last_error() return True
Example #29
Source File: windows.py From EventGhost with GNU General Public License v2.0 | 5 votes |
def set_close_exec(fd): success = SetHandleInformation(fd, HANDLE_FLAG_INHERIT, 0) if not success: raise ctypes.GetLastError()
Example #30
Source File: windows.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def set_close_exec(fd): success = SetHandleInformation(fd, HANDLE_FLAG_INHERIT, 0) if not success: raise ctypes.GetLastError()