def OpenProcessToken(ProcessHandle, DesiredAccess): token = HANDLE() if advapi32.OpenProcessToken(ProcessHandle, DesiredAccess, byref(token)) == 0: raise WinError() return token.value
def nonzero(result, func, arguments): if result == 0: raise WinError() return result
def s_ok(result, func, arguments): if result != S_OK: raise WinError(result) # no error code set in windows return result
def ErrCheckBool(result, func, args): """errcheck function for Windows functions that return a BOOL True on success""" if not result: raise WinError() return args
def set_noinherit(sock: socket.socket) -> None: """Mark the given socket fd as non-inheritable to child processes""" if not _SetHandleInformation(sock.fileno(), 1, 0): raise WinError()
def PostMessage(hwnd, msg, wParam, lParam): if not user32.PostMessageW(hwnd, msg, wParam, lParam): raise WinError()
def Read(self, data, address=None, size=None): """Read data from the memory block""" if not address: address = self.mem_address if hasattr(address, 'value'): address = address.value if size: nSize = win32structures.ULONG_PTR(size) else: nSize = win32structures.ULONG_PTR(sizeof(data)) if self.size < nSize.value: raise Exception( ('Read: RemoteMemoryBlock is too small ({0} bytes),' + ' {1} is required.').format(self.size, nSize.value)) if hex(address).lower().startswith('0xffffff'): raise Exception('Read: RemoteMemoryBlock has incorrect address =' + hex(address)) lpNumberOfBytesRead = c_size_t(0) ret = win32functions.ReadProcessMemory(c_void_p(self.process), c_void_p(address), byref(data), nSize, byref(lpNumberOfBytesRead)) # disabled as it often returns an error - but # seems to work fine anyway!! if ret == 0: # try again ret = win32functions.ReadProcessMemory(c_void_p(self.process), c_void_p(address), byref(data), nSize, byref(lpNumberOfBytesRead)) if ret == 0: last_error = win32api.GetLastError() if last_error != win32defines.ERROR_PARTIAL_COPY: ActionLogger().log('Read: WARNING! self.mem_address =' + hex(self.mem_address) + ' data address =' + str(byref(data))) ActionLogger().log( 'LastError = ' + str(last_error) + ': ' + win32api.FormatMessage(last_error).rstrip()) else: ActionLogger().log('Error: ERROR_PARTIAL_COPY') ActionLogger().log('\nRead: WARNING! self.mem_address =' + hex(self.mem_address) + ' data address =' + str(byref(data))) ActionLogger().log('lpNumberOfBytesRead =' + str(lpNumberOfBytesRead) + ' nSize =' + str(nSize)) raise WinError() else: ActionLogger().log('Warning! Read OK: 2nd attempt!') #else: # print 'Read OK: lpNumberOfBytesRead =', lpNumberOfBytesRead, ' nSize =', nSize self.CheckGuardSignature() return data
def _errCheck(result, func, args): if result == 0: raise WinError() return args
def GetDiskFreeSpaceExErrCheck(result, unused_func, args): if not result: raise WinError() return args[1].value
def errcheck(result, func, args): if 0 == result: raise WinError() return WinFunc.errcheck(result, func, args)
def errcheck(result, func, args): if result == -1 or not result: raise WinError() return result
def _send(self, args): cmdl = join_args(args) reg.SetValueEx(self._ipc_key, 'TempAppCmdLine', 0, reg.REG_SZ, cmdl) if not winapi.SetEvent(self._event): raise WinError()
def GetStdHandle(handleID): h = kernel32.GetStdHandle(handleID) if h == 0: raise WinError() return h
def SetThreadExecutionState(esFlags): res = kernel32.SetThreadExecutionState(esFlags) if not res: raise WinError() return res
def FindWindow(className, windowName): res = user32.FindWindowW(className, windowName) if res == 0: raise WinError() return res
def ListDevices(): devices = {} guid = GUID() CLSIDFromString("{A5DCBF10-6530-11D2-901F-00C04FB951ED}", byref(guid)) hDevInfo = SetupDiGetClassDevs( guid, "USB", # Enumerator 0, DIGCF_PRESENT | DIGCF_ALLCLASSES ) if hDevInfo == INVALID_HANDLE_VALUE: raise WinError() deviceInfoData = SP_DEVINFO_DATA() deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA) driverInfoData = SP_DRVINFO_DATA() driverInfoData.cbSize = sizeof(SP_DRVINFO_DATA) deviceInstallParams = SP_DEVINSTALL_PARAMS() deviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS) i = 0 while True: if not SetupDiEnumDeviceInfo(hDevInfo, i, byref(deviceInfoData)): err = GetLastError() if err == ERROR_NO_MORE_ITEMS: break else: raise WinError(err) i += 1 hardwareId = WinUsb.GetDeviceHardwareId(hDevInfo, deviceInfoData) if hardwareId.startswith("USB\\ROOT_HUB"): continue driverInfoData.DriverVersion = 0 SetupDiGetDeviceInstallParams( hDevInfo, byref(deviceInfoData), byref(deviceInstallParams) ) deviceInstallParams.FlagsEx |= DI_FLAGSEX_INSTALLEDDRIVER SetupDiSetDeviceInstallParams( hDevInfo, byref(deviceInfoData), byref(deviceInstallParams) ) SetupDiBuildDriverInfoList( hDevInfo, byref(deviceInfoData), SPDIT_COMPATDRIVER ) if not SetupDiEnumDriverInfo( hDevInfo, byref(deviceInfoData), SPDIT_COMPATDRIVER, 0, byref(driverInfoData) ): err = GetLastError() if err == ERROR_NO_MORE_ITEMS: devices[hardwareId] = DeviceInfo( name = "<unknown name>", version = "", hardwareId = hardwareId, provider = "<unknown provider", ) continue else: raise WinError(err) version = driverInfoData.DriverVersion versionStr = "%d.%d.%d.%d" % ( (version >> 48) & 0xFFFF, (version >> 32) & 0xFFFF, (version >> 16) & 0xFFFF, version & 0xFFFF ) devices[hardwareId] = DeviceInfo( driverInfoData.Description, versionStr, hardwareId, driverInfoData.ProviderName, ) return devices
def MessageBox(hwnd, text, caption, type): res = user32.MessageBoxW(hwnd, text, caption, type) if res == 0: raise WinError() return res
def bool_errcheck(result, func, args): if not result: raise WinError() return args
def terminate(self): """Terminates the timer. This should be called from the thread that initiated the timer. """ if not user32.KillTimer(self.hwnd, self.idEvent): raise WinError()
def CreateToolhelp32Snapshot(dwFlags=2, th32ProcessID=0): hSnapshot = windll.kernel32.CreateToolhelp32Snapshot( dwFlags, th32ProcessID) if hSnapshot == INVALID_HANDLE_VALUE: raise WinError() return hSnapshot
def ErrCheckResumeThread(result, func, args): if result == -1: raise WinError() return args
def GetExitCodeProcess(h): exitcode = DWORD() r = _GetExitCodeProcess(h, byref(exitcode)) if r is 0: raise WinError() return exitcode.value
def ErrCheckHandle(result, func, args): """errcheck function for Windows functions that return a HANDLE.""" if not result: raise WinError() return AutoHANDLE(result)
def err_on_zero_or_null_check(result, func, args): if not result: raise WinError() return args
def register_event_source(app_name): """Registers an event source and returns an open handle. Raises WinError on error.""" handle = RegisterEventSourceW(None, unicode(app_name)) if handle == 0: raise WinError() return handle
def set_sock_no_inherit(sock): # mark the given socket fd as non-inheritable (Windows). if not _SetHandleInformation(sock.fileno(), 1, 0): raise WinError()
def validhandle(result, func, arguments): if result == INVALID_HANDLE_VALUE: raise WinError() return result
def getClientRect(hwnd): r = RECT() if not user32.GetClientRect(hwnd, byref(r)): raise WinError() return r
def get_disk_stats(whichdir, reserved_space=0): """Return disk statistics for the storage disk, in the form of a dict with the following fields. total: total bytes on disk free_for_root: bytes actually free on disk free_for_nonroot: bytes free for "a non-privileged user" [Unix] or the current user [Windows]; might take into account quotas depending on platform used: bytes used on disk avail: bytes available excluding reserved space An AttributeError can occur if the OS has no API to get disk information. An EnvironmentError can occur if the OS call fails. whichdir is a directory on the filesystem in question -- the answer is about the filesystem, not about the directory, so the directory is used only to specify which filesystem. reserved_space is how many bytes to subtract from the answer, so you can pass how many bytes you would like to leave unused on this filesystem as reserved_space. """ if have_GetDiskFreeSpaceExW: # If this is a Windows system and GetDiskFreeSpaceExW is available, use it. # (This might put up an error dialog unless # SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX) has been called, # which we do in allmydata.windows.fixups.initialize().) n_free_for_nonroot = c_ulonglong(0) n_total = c_ulonglong(0) n_free_for_root = c_ulonglong(0) retval = GetDiskFreeSpaceExW(whichdir, byref(n_free_for_nonroot), byref(n_total), byref(n_free_for_root)) if retval == 0: raise OSError( "WinError: %s\n attempting to get disk statistics for %r" % (WinError(get_last_error()), whichdir)) free_for_nonroot = n_free_for_nonroot.value total = n_total.value free_for_root = n_free_for_root.value else: # For Unix-like systems. # <http://docs.python.org/library/os.html#os.statvfs> # <http://opengroup.org/onlinepubs/7990989799/xsh/fstatvfs.html> # <http://opengroup.org/onlinepubs/7990989799/xsh/sysstatvfs.h.html> s = os.statvfs(whichdir) # on my mac laptop: # statvfs(2) is a wrapper around statfs(2). # statvfs.f_frsize = statfs.f_bsize : # "minimum unit of allocation" (statvfs) # "fundamental file system block size" (statfs) # statvfs.f_bsize = statfs.f_iosize = stat.st_blocks : preferred IO size # on an encrypted home directory ("FileVault"), it gets f_blocks # wrong, and s.f_blocks*s.f_frsize is twice the size of my disk, # but s.f_bavail*s.f_frsize is correct total = s.f_frsize * s.f_blocks free_for_root = s.f_frsize * s.f_bfree free_for_nonroot = s.f_frsize * s.f_bavail # valid for all platforms: used = total - free_for_root avail = max(free_for_nonroot - reserved_space, 0) return { 'total': total, 'free_for_root': free_for_root, 'free_for_nonroot': free_for_nonroot, 'used': used, 'avail': avail, }
def virtualAllocEx(*args): res = kernel32.VirtualAllocEx(*args) if res == 0: raise WinError() return res