Ejemplo n.º 1
0
def GetStdHandle(nStdHandle):
    """
    Retrieves a handle to the specified standard
    device (standard input, standard output, or standard error).

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms683231

    :param int nStdHandle:
        The standard device to retrieve.

    :rtype: pywincffi.wintypes.HANDLE
    :return:
        Returns a handle to the standard device retrieved.
    """
    _, library = dist.load()
    input_check("nStdHandle", nStdHandle,
                allowed_values=(library.STD_INPUT_HANDLE,
                                library.STD_OUTPUT_HANDLE,
                                library.STD_ERROR_HANDLE))

    handle = library.GetStdHandle(nStdHandle)

    if handle == library.INVALID_HANDLE_VALUE:  # pragma: no cover
        raise WindowsAPIError(
            "GetStdHandle", "Invalid Handle", library.INVALID_HANDLE_VALUE,
            expected_return_code="not %r" % library.INVALID_HANDLE_VALUE)

    return HANDLE(handle)
Ejemplo n.º 2
0
def WaitForSingleObject(hHandle, dwMilliseconds):
    """
    Waits for the specified object to be in a signaled state
    or for ``dwMiliseconds`` to elapse.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms687032

    :param pywincffi.wintypes.HANDLE hHandle:
        The handle to wait on.

    :param int dwMilliseconds:
        The time-out interval.
    """
    input_check("hHandle", hHandle, HANDLE)
    input_check("dwMilliseconds", dwMilliseconds, integer_types)

    ffi, library = dist.load()
    result = library.WaitForSingleObject(wintype_to_cdata(hHandle),
                                         ffi.cast("DWORD", dwMilliseconds))

    if result == library.WAIT_FAILED:
        raise WindowsAPIError("WaitForSingleObject",
                              "Wait Failed",
                              ffi.getwinerror()[-1],
                              return_code=result,
                              expected_return_code="not %s" % result)

    error_check("WaitForSingleObject")

    return result
Ejemplo n.º 3
0
    def test_warning(self):

        with self.assertWarns(Warning):
            WindowsAPIError("function",
                            "there was a problem",
                            1,
                            return_code="foo")
Ejemplo n.º 4
0
 def test_message_return_code_and_expected_code_is_none(self):
     error = WindowsAPIError("function",
                             "there was a problem",
                             1,
                             return_code=None,
                             expected_return_code=None)
     self.assertEqual(
         error.message,
         "Error when calling function. Message from Windows API was 'there "
         "was a problem' (errno: 1).")
Ejemplo n.º 5
0
 def test_repr(self):
     error = WindowsAPIError("function",
                             "there was a problem",
                             1,
                             return_code=0,
                             expected_return_code=1)
     self.assertEqual(
         repr(error),
         "WindowsAPIError('function', 'there was a problem', 1, "
         "return_code=0, expected_return_code=1)")
Ejemplo n.º 6
0
def error_check(function, code=None, expected=None):
    """
    Checks the results of a return code against an expected result.  If
    a code is not provided we'll use :func:`ffi.getwinerror` to retrieve
    the code.

    :param str function:
        The Windows API function being called.

    :keyword int code:
        An explicit code to compare against.

    :keyword int expected:
        The code we expect to have as a result of a successful
        call.  This can also be passed ``pywincffi.core.checks.Enums.NON_ZERO``
        if ``code`` can be anything but zero.

    :raises pywincffi.exceptions.WindowsAPIError:
        Raised if we receive an unexpected result from a Windows API call
    """
    ffi, _ = dist.load()
    errno, error_message = ffi.getwinerror()

    logger.debug("error_check(%r, code=%r, expected=%r)", function, code,
                 expected)

    if code is not None:
        if expected == Enums.NON_ZERO and code == 0:
            raise WindowsAPIError(function,
                                  error_message,
                                  errno,
                                  return_code=code,
                                  expected_return_code=expected)
        return

    if errno != 0:
        raise WindowsAPIError(function,
                              error_message,
                              errno,
                              return_code=code,
                              expected_return_code=expected)
Ejemplo n.º 7
0
def WSACreateEvent():
    """
    Creates a new event object.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms741561

    :rtype: :class:`pywincffi.wintypes.objects.WSAEVENT`
    :returns:
        Returns a handle to a new event object.
    """
    _, library = dist.load()
    event = library.WSACreateEvent()

    if library.wsa_invalid_event(event):
        errno = WSAGetLastError()
        raise WindowsAPIError("WSACreateEvent", "Socket error %d" % errno,
                              errno)

    return WSAEVENT(event)
Ejemplo n.º 8
0
def CreateToolhelp32Snapshot(dwFlags, th32ProcessID):
    """
    Takes a snapshot of the specified processes, as well as the heaps,
    modules, and threads used by these processes.

    .. seealso::

        https://msdn.microsoft.com/en-us/ms682489

    :param int dwFlags:
        The portions of the system to be included in the snapshot.

    :param int th32ProcessID:
        The process identifier of the process to be included in the snapshot.

    :rtype: :class:`pywincffi.wintypes.HANDLE`

    :return:
        If the function succeeds,
        it returns an open handle to the specified snapshot.
    """
    input_check("dwFlags", dwFlags, integer_types)
    input_check("th32ProcessID", th32ProcessID, integer_types)
    ffi, library = dist.load()
    process_list = library.CreateToolhelp32Snapshot(
        ffi.cast("DWORD", dwFlags),
        ffi.cast("DWORD", th32ProcessID)
    )

    if process_list == library.INVALID_HANDLE_VALUE:  # pragma: no cover
        raise WindowsAPIError(
            "CreateToolhelp32Snapshot", "Invalid Handle",
            library.INVALID_HANDLE_VALUE,
            expected_return_code="not %r" % library.INVALID_HANDLE_VALUE)

    error_check("CreateToolhelp32Snapshot")

    return HANDLE(process_list)
Ejemplo n.º 9
0
def WSAEventSelect(socket, hEventObject, lNetworkEvents):
    """
    Specifies an event object to be associated with the specified set of
    FD_XXX network events.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms741576

    :param pywincffi.wintypes.objects.SOCKET socket:
        The socket object to associate the selected network events with.

    :param pywincffi.wintypes.objects.WSAEVENT hEventObject:
        A handle which identifies the event object to be associated
        with the network events.

    :param int lNetworkEvents:
        A bitmask which specifies the combination of ``FD_XXX`` network
        events which the application has interest in.
    """
    input_check("socket", socket, allowed_types=(SOCKET, ))
    input_check("hEventObject", hEventObject, allowed_types=(HANDLE, ))
    input_check("lNetworkEvents", lNetworkEvents, integer_types)

    ffi, library = dist.load()

    code = library.WSAEventSelect(wintype_to_cdata(socket),
                                  wintype_to_cdata(hEventObject),
                                  ffi.cast("long", lNetworkEvents))

    if code == library.SOCKET_ERROR:
        errno = WSAGetLastError()
        raise WindowsAPIError("WSAEventSelect", "Socket error %d" % errno,
                              errno)

    error_check("WSAEventSelect", code, expected=0)
Ejemplo n.º 10
0
 def raise_(*_):
     raise WindowsAPIError("", "", library.ERROR_ALREADY_EXISTS)
Ejemplo n.º 11
0
 def test_attribute_expected_code(self):
     error = WindowsAPIError("function",
                             "there was a problem",
                             1,
                             return_code=0)
     self.assertEqual(error.return_code, 0)
Ejemplo n.º 12
0
def CreateConsoleScreenBuffer(
        dwDesiredAccess, dwShareMode, lpSecurityAttributes=None, dwFlags=None):
    """
    Creates a console screen buffer.

    .. seealso::

        https://docs.microsoft.com/en-us/windows/console/createconsolescreenbuffer

    :type dwDesiredAccess: int or None
    :param dwDesiredAccess:
         The access to the console screen buffer. If `None` is provided
         then the Windows APIs will use a default security descriptor.

    :type dwShareMode: int or None
    :param dwShareMode:
        Controls the options for sharing the resulting handle. If `None` or
        0 then the resulting buffer cannot be shared.

    :keyword pywincffi.wintypes.SECURITY_ATTRIBUTES lpSecurityAttributes:
        Extra security attributes that determine if the resulting handle
        can be inherited. If `None` is provided, which is the default, then
        the handle cannot be inherited.

    :keyword int dwFlags:
        The type of console buffer to create. The flag is superficial because
        it only accepts None or ``CONSOLE_TEXTMODE_BUFFER`` as inputs. If no
        value is provided, which is the default, then
        ``CONSOLE_TEXTMODE_BUFFER`` is automatically used.

    :rtype: :class:`pywincffi.wintypes.HANDLE``
    :returns:
        Returns the handle created by the underlying C function.
        :func:`pywincffi.kernel32.CloseHandle` should be called on the handle
        when you are done with it.
    """
    ffi, library = dist.load()

    if dwDesiredAccess is None:
        dwDesiredAccess = ffi.NULL

    if dwShareMode is None:
        dwShareMode = 0

    if dwFlags is None:
        dwFlags = library.CONSOLE_TEXTMODE_BUFFER

    input_check(
        "dwDesiredAccess", dwDesiredAccess, allowed_values=(
            ffi.NULL,
            library.GENERIC_READ,
            library.GENERIC_WRITE,
            library.GENERIC_READ | library.GENERIC_WRITE
        ))
    input_check(
        "dwShareMode", dwShareMode, allowed_values=(
            0,
            library.FILE_SHARE_READ,
            library.FILE_SHARE_WRITE,
            library.FILE_SHARE_READ | library.FILE_SHARE_WRITE,
        ))
    input_check(
        "dwFlags", dwFlags,
        allowed_values=(
            library.CONSOLE_TEXTMODE_BUFFER,
        ))
    input_check(
        "lpSecurityAttributes", lpSecurityAttributes,
        allowed_types=(NoneType, SECURITY_ATTRIBUTES))

    if lpSecurityAttributes is None:
        lpSecurityAttributes = ffi.NULL

    handle = library.CreateConsoleScreenBuffer(
        ffi.cast("DWORD", dwDesiredAccess),
        ffi.cast("DWORD", dwShareMode),
        lpSecurityAttributes,
        ffi.cast("DWORD", dwFlags),
        ffi.NULL  # _reserved_
    )

    if handle == library.INVALID_HANDLE_VALUE:  # pragma: no cover
        raise WindowsAPIError(
            "CreateConsoleScreenBuffer", "Invalid Handle",
            library.INVALID_HANDLE_VALUE,
            expected_return_code="not INVALID_HANDLE_VALUE")

    return HANDLE(handle)
Ejemplo n.º 13
0
 def test_attribute_api_error_message(self):
     error = WindowsAPIError("function",
                             "there was a problem",
                             1,
                             return_code=0)
     self.assertEqual(error.error, "there was a problem")
Ejemplo n.º 14
0
 def new_open_process(*args, **kwargs):
     raise WindowsAPIError("", "", 42)
Ejemplo n.º 15
0
def MsgWaitForMultipleObjects(
        pHandles, bWaitAll, dwMilliseconds, dwWakeMask, nCount=None):
    """
    Waits until one or all of the specified objects are in a singled state
    or the timeout elapses.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms684242

    :param list pHandles:
        A list or tuple of :class:`pywincffi.wintypes.HANDLE` to wait on.
        See Microsoft's documentation for more information about the contents
        of this argument.

    :param bool bWaitAll:
        If True then this function will return when the states of all
        objects in ``pHandles`` are signaled.

    :param int dwMilliseconds:
        The timeout interval in milliseconds.

    :param int dwWakeMask:
        The input types for which an input event object handle will be added
        to the array of handles.  See Microsoft's documentation for more
        detailed information.

    :keyword int nCount:
        The number of object handles in ``pHandles``.  By default this will
        be determined by checking the length of the input to ``pHandles``.

    :raises WindowsAPIError:
        Raised if the underlying Windows function returns ``WAIT_FAILED``.

    :rtype: int
    :return:
        Returns the value of the event which caused the function to
        return.  See Microsoft's documentation for full details on what
        this could be.
    """
    input_check("pHandles", pHandles, (list, tuple))

    if nCount is None:
        nCount = len(pHandles)

    input_check("bWaitAll", bWaitAll, bool)
    input_check("dwMilliseconds", dwMilliseconds, integer_types)
    input_check("dwWakeMask", dwWakeMask, integer_types)
    input_check("nCount", nCount, integer_types)

    ffi, library = dist.load()

    # Verify input types and build a <cdata HANDLE> array out of the
    # input Python HANDLE list/tuple to be passed to the underlying API.
    pHandles_cdata = ffi.new("HANDLE[]", nCount)
    for i, handle in enumerate(pHandles):
        input_check("pHandles[%d]" % i, handle, HANDLE)
        pHandles_cdata[i] = wintype_to_cdata(handle)

    code = library.MsgWaitForMultipleObjects(
        nCount,
        pHandles_cdata,
        bWaitAll,
        dwMilliseconds,
        dwWakeMask
    )

    if code == library.WAIT_FAILED:
        code, message = ffi.getwinerror()
        raise WindowsAPIError(
            "MsgWaitForMultipleObjects", message, code)

    return code
Ejemplo n.º 16
0
 def raise_(*_):
     raise WindowsAPIError("CreateEvent", "", -1)
Ejemplo n.º 17
0
 def test_ivar_code(self):
     error = WindowsAPIError("function",
                             "there was a problem",
                             1,
                             return_code=0)
     self.assertEqual(error.errno, 1)