Exemple #1
0
    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
Exemple #2
0
    def rush(enable=True, realtime=False):
        """Raise the priority of the current thread/process.
        Set with rush(True) or rush(False)
        Beware and don't take priority until after debugging your code
        and ensuring you have a way out (e.g. an escape sequence of
        keys within the display loop). Otherwise you could end up locked
        out and having to reboot!
        """
        if enable:
            gc.disable()
        else:
            gc.enable()
        if importWindllFailed:
            return False

        pr_rights = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION
        pr = windll.OpenProcess(pr_rights, FALSE, os.getpid())
        thr = windll.GetCurrentThread()

        if enable:
            if realtime:
                windll.SetPriorityClass(pr, REALTIME_PRIORITY_CLASS)
                windll.SetThreadPriority(thr, THREAD_PRIORITY_TIME_CRITICAL)
            else:
                windll.SetPriorityClass(pr, HIGH_PRIORITY_CLASS)
                windll.SetThreadPriority(thr, THREAD_PRIORITY_HIGHEST)
        else:
            windll.SetPriorityClass(pr, NORMAL_PRIORITY_CLASS)
            windll.SetThreadPriority(thr, THREAD_PRIORITY_NORMAL)
        err = get_last_error()
        if err:
            set_last_error(0)
            return False
        return True
def write_bytes(process_handle, address, buffer):
    """Writes a buffer (number of bytes) to a specified address in a process

    Keyword arguments:
    process_handle -- handle to process
    address -- address in process to write to
    buffer -- a bytearray or bytes object to write at [address]
    """
    c_data = c_char_p(bytes(buffer))
    c_data_ = cast(c_data, POINTER(c_char))
    __WriteProcessMemory__(process_handle, address, c_data_, len(buffer), None)
    err = get_last_error()
    if err:
        set_last_error(0)
def write_byte(process_handle, address, value):
    """Writes a single byte at a specified address in a process

    Keyword arguments:
    process_handle -- handle to process
    address -- address in process to write to
    value -- value to write at [address]
    """
    c_data = c_char_p(struct.pack("B", value))
    c_data_ = cast(c_data, POINTER(c_char))
    __WriteProcessMemory__(process_handle, address, c_data_, SIZE_CHAR, None)
    err = get_last_error()
    if err:
        set_last_error(0)
	def readwcharsinto(self, buf, n):
		nr = DWORD(n)
		old_error = ctypes.get_last_error()
		ctypes.set_last_error(0)
		success = ReadConsoleW(self.handle, buf, nr, ctypes.byref(nr), ctypes.c_void_p())
		error = ctypes.get_last_error()
		ctypes.set_last_error(old_error)
		if not success: raise ctypes.WinError(error)
		ERROR_OPERATION_ABORTED = 995
		if nr.value == 0 and error == ERROR_OPERATION_ABORTED:
			# Apparently this can trigger pending KeyboardInterrupts?
			time.sleep(1.0 / (1 << 64))
			raise KeyboardInterrupt()  # If Python doesn't raise it, we can
		return nr.value
Exemple #6
0
def write_double(process_handle, address, value):
    """Writes a single double at a specified address in a process

    Keyword arguments:
    process_handle -- handle to process
    address -- address in process to write to
    value -- value to write at [address]
    """
    c_data = c_char_p(struct.pack("d", value))
    c_data_ = cast(c_data, POINTER(c_char))
    __wPM__(process_handle, address, c_data_, SIZE_DOUBLE, None)
    err = get_last_error()
    if err:
        set_last_error(0)
Exemple #7
0
def read_double(process_handle, address):
    """Reads a single double at a specified address from a process
    Returns an double which is the value at [address]

    Keyword arguments:
    process_handle -- handle to process
    address -- address in process to read from
    """
    buffer = create_string_buffer(SIZE_DOUBLE)
    bytes_read = c_size_t()
    __rPM__(process_handle, address, buffer, SIZE_DOUBLE, byref(bytes_read))
    err = get_last_error()
    if err:
        set_last_error(0)
        #print(ERR_CODE.get(err, err))
    return struct.unpack("d", buffer[0:SIZE_DOUBLE])[0]
def read_short(process_handle, address):
    """Reads an short at a specified address from a process
    Returns an short which is the value at [address]

    Keyword arguments:
    process_handle -- handle to process
    address -- address in process to read from
    """
    buffer = create_string_buffer(SIZE_SHORT)
    bytes_read = c_size_t()
    __ReadProcessMemory__(process_handle, address, buffer, SIZE_SHORT,
                          byref(bytes_read))
    err = get_last_error()
    if err:
        set_last_error(0)
        #print(ERR_CODE.get(err, err))
    return struct.unpack("H", buffer[0:SIZE_SHORT])[0]
Exemple #9
0
def read_bytes(process_handle, address, length):
    """Reads an array of bytes at a specified address from a process
    Returns a list which is values at [address], with a length of [length]

    Keyword arguments:
    process_handle -- handle to process
    address -- address in process to read from
    length -- number of bytes to read
    """
    buffer = create_string_buffer(length)
    bytes_read = c_size_t()
    __rPM__(process_handle, address, buffer, length, byref(bytes_read))
    err = get_last_error()
    if err:
        set_last_error(0)
        #print(ERR_CODE.get(err, err))
    return bytearray(buffer[0:length])
Exemple #10
0
def set_owner(hwnd, hwnd_owner):
    """
    Changes the owner window of the given window
    :param hwnd:
    :param hwnd_owner:
    """

    _update_window = ctypes.windll.user32.UpdateWindow

    # WIN32 vs WIN64 - from a macro in winuser.h
    if ctypes.sizeof(ctypes.wintypes.HWND) == ctypes.sizeof(ctypes.c_long):
        _LONG = ctypes.wintypes.LONG
        _set_window_long = ctypes.windll.user32.SetWindowLongW
        _set_window_long.argtypes = [
            ctypes.wintypes.HWND, ctypes.c_int, ctypes.wintypes.LONG
        ]
        _set_window_long.restype = ctypes.c_void_p
    elif ctypes.sizeof(ctypes.wintypes.HWND) == ctypes.sizeof(
            ctypes.c_longlong):
        _LONG = ctypes.wintypes.HWND
        _set_window_long = ctypes.windll.user32.SetWindowLongPtrW
        _set_window_long.argtypes = [
            ctypes.wintypes.HWND, ctypes.c_int, ctypes.wintypes.HWND
        ]
        _set_window_long.restype = _LONG

    last_error = ctypes.set_last_error(0)
    try:
        result = _set_window_long(ctypes.wintypes.HWND(hwnd),
                                  ctypes.c_int(GWL_HWNDPARENT),
                                  _LONG(hwnd_owner))
    finally:
        last_error = ctypes.set_last_error(last_error)

    if not result and last_error:
        raise ctypes.WinError(last_error)

    _update_window(hwnd_owner)

    return result
Exemple #11
0
    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
Exemple #12
0
    def priority(level=0, pid=None):
        # 0 = normal priority
        # 1 = high
        # 2 = realtime
        gc.disable() if level > 0 else gc.enable()

        if kernel32 is None and avrt is None:
            # nothing to do if we don't have these
            return False

        pid = os.getpid()
        process = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION, 0, pid)
        thread = kernel32.GetCurrentThread()

        if thread in thread_pool.keys():
            thread_grp = thread_pool[thread]
        else:
            thread_grp = {'mmcss': None}
            thread_pool[thread] = thread_grp

        # if this is a MMCSS scheduled thread, need to revert to normal first
        if avrt and thread_grp['mmcss']:
            avrt.AvRevertMmThreadCharacteristics(thread_grp['mmcss'])
            thread_grp['mmcss'] = None

        # clear error if anything?
        err = get_last_error()
        if err:
            set_last_error(0)
            return False

        if level == 1:
            kernel32.SetPriorityClass(process, HIGH_PRIORITY_CLASS)
            if avrt:
                tmp = LPDWORD()
                thread_grp['mmcss'] = avrt.AvSetMmMaxThreadCharacteristicsA(LPCSTR(b'Pro Audio'),
                                                                            LPCSTR(b'Capture'),
                                                                            byref(tmp))
            if not thread_grp['mmcss']:  # failed
                kernel32.SetThreadPriority(thread, THREAD_PRIORITY_HIGHEST)

        elif level >= 2:
            # first try to set time critical
            if (not kernel32.SetPriorityClass(process, REALTIME_PRIORITY_CLASS) or
                    kernel32.GetPriorityClass(process) != REALTIME_PRIORITY_CLASS):
                # try for high priority scheduling instead
                kernel32.SetPriorityClass(process, HIGH_PRIORITY_CLASS)
            if avrt:
                tmp = LPDWORD()
                thread_grp['mmcss'] = avrt.AvSetMmMaxThreadCharacteristicsA(LPCSTR(b'Pro Audio'),
                                                                            LPCSTR(b'Capture'),
                                                                            byref(tmp))
            if not thread_grp['mmcss']:  # failed
                kernel32.SetThreadPriority(
                    thread, THREAD_PRIORITY_ABOVE_NORMAL)

        else:
            kernel32.SetPriorityClass(process, NORMAL_PRIORITY_CLASS)
            kernel32.SetThreadPriority(thread, THREAD_PRIORITY_NORMAL)

        return True