Python ctypes.wintypes.HMODULE Examples

The following are 11 code examples of ctypes.wintypes.HMODULE(). 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.wintypes , or try the search function .
Example #1
Source File: DatabaseBuilder.py    From apiscout with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check_aslr():
    # first check for a potentially rebased user32.dll
    from ctypes import windll
    from ctypes import wintypes
    check_dlls = ["user32.dll", "kernel32.dll", "ntdll.dll"]
    offsets = []
    is_aslr = False
    windll.kernel32.GetModuleHandleW.restype = wintypes.HMODULE
    windll.kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
    windll.kernel32.GetModuleFileNameW.restype = wintypes.DWORD
    windll.kernel32.GetModuleFileNameW.argtypes = [wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD]
    for dll_name in check_dlls:
        h_module_base = windll.kernel32.GetModuleHandleW(dll_name)
        # next get the module's file path
        module_path = ctypes.create_unicode_buffer(255)
        windll.kernel32.GetModuleFileNameW(h_module_base, module_path, 255)
        # then the ImageBase from python.exe file
        pe = pefile.PE(module_path.value)
        pe_header_base_addr = pe.OPTIONAL_HEADER.ImageBase
        offsets.append(pe_header_base_addr - h_module_base)
    for dll_name, offset in zip(check_dlls, offsets):
        LOG.debug("Memory vs. File ImageBase offset (%s): 0x%x", dll_name, offset)
        is_aslr |= offset != 0
    return is_aslr 
Example #2
Source File: __init__.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def copyload_shared_lib(dst_prefix=TESTFILE_PREFIX):
        """Ctx manager which picks up a random shared DLL lib used
        by this process, copies it in another location and loads it
        in memory via ctypes.
        Return the new absolutized, normcased path.
        """
        from ctypes import wintypes
        from ctypes import WinError
        ext = ".dll"
        dst = tempfile.mktemp(prefix=dst_prefix, suffix=ext)
        libs = [x.path for x in psutil.Process().memory_maps() if
                os.path.splitext(x.path)[1].lower() == ext and
                'python' in os.path.basename(x.path).lower() and
                'wow64' not in x.path.lower()]
        src = random.choice(libs)
        shutil.copyfile(src, dst)
        cfile = None
        try:
            cfile = ctypes.WinDLL(dst)
            yield dst
        finally:
            # Work around OverflowError:
            # - https://ci.appveyor.com/project/giampaolo/psutil/build/1207/
            #       job/o53330pbnri9bcw7
            # - http://bugs.python.org/issue30286
            # - http://stackoverflow.com/questions/23522055
            if cfile is not None:
                FreeLibrary = ctypes.windll.kernel32.FreeLibrary
                FreeLibrary.argtypes = [wintypes.HMODULE]
                ret = FreeLibrary(cfile._handle)
                if ret == 0:
                    WinError()
            safe_rmpath(dst) 
Example #3
Source File: hotkeys.py    From PyPipboyApp with GNU General Public License v3.0 5 votes vote down vote up
def listener():
    try:
        #print("LLHookey: in listener")
        from ctypes import windll, CFUNCTYPE, POINTER, c_int, c_void_p, byref
        import atexit
        event_types = {0x100: 'key down', #WM_KeyDown for normal keys
           0x101: 'key up', #WM_KeyUp for normal keys
           0x104: 'key down', # WM_SYSKEYDOWN, used for Alt key.
           0x105: 'key up', # WM_SYSKEYUP, used for Alt key.
          }
        def low_level_handler(nCode, wParam, lParam):
            
            event = KeyEvent(event_types[wParam], lParam[0], lParam[1],
                              lParam[2] == 32, lParam[3])
            for h in handlers:
                h(event)
            #Be nice, return next hook
            return windll.user32.CallNextHookEx(hook_id, nCode, wParam, lParam)
    
        
        # Our low level handler signature.
        CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))
        # Convert the Python handler into C pointer.
        pointer = CMPFUNC(low_level_handler)
        #Added 4-18-15 for move to ctypes:
        windll.kernel32.GetModuleHandleW.restype = wintypes.HMODULE
        windll.kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
        # Hook both key up and key down events for common keys (non-system).
        hook_id = windll.user32.SetWindowsHookExA(0x00D, pointer,
                                                 windll.kernel32.GetModuleHandleW(None), 0)
    
        # Register to remove the hook when the interpreter exits.
        atexit.register(windll.user32.UnhookWindowsHookEx, hook_id)
        msg = windll.user32.GetMessageW(None, 0, 0,0)
        windll.user32.TranslateMessage(byref(msg))
        windll.user32.DispatchMessageW(byref(msg))
    except:
        traceback.print_exc(file=sys.stdout) 
Example #4
Source File: __init__.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def copyload_shared_lib(dst_prefix=TESTFILE_PREFIX):
        """Ctx manager which picks up a random shared DLL lib used
        by this process, copies it in another location and loads it
        in memory via ctypes.
        Return the new absolutized, normcased path.
        """
        from ctypes import wintypes
        from ctypes import WinError
        ext = ".dll"
        dst = tempfile.mktemp(prefix=dst_prefix, suffix=ext)
        libs = [x.path for x in psutil.Process().memory_maps() if
                os.path.splitext(x.path)[1].lower() == ext and
                'python' in os.path.basename(x.path).lower() and
                'wow64' not in x.path.lower()]
        src = random.choice(libs)
        shutil.copyfile(src, dst)
        cfile = None
        try:
            cfile = ctypes.WinDLL(dst)
            yield dst
        finally:
            # Work around OverflowError:
            # - https://ci.appveyor.com/project/giampaolo/psutil/build/1207/
            #       job/o53330pbnri9bcw7
            # - http://bugs.python.org/issue30286
            # - http://stackoverflow.com/questions/23522055
            if cfile is not None:
                FreeLibrary = ctypes.windll.kernel32.FreeLibrary
                FreeLibrary.argtypes = [wintypes.HMODULE]
                ret = FreeLibrary(cfile._handle)
                if ret == 0:
                    WinError()
            safe_rmpath(dst) 
Example #5
Source File: install_package.py    From r-bridge-install with Apache License 2.0 5 votes vote down vote up
def bridge_running(product):
    """ Check if the R ArcGIS bridge is running. Installation wil fail
    if the DLL is currently loaded."""
    running = False
    # check for the correct DLL
    if product == 'Pro':
        proxy_name = "rarcproxy_pro.dll"
    else:
        proxy_name = "rarcproxy.dll"
    kdll.GetModuleHandleW.restype = wintypes.HMODULE
    kdll.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
    dll_handle = kdll.GetModuleHandleW(proxy_name)  # memory address of DLL
    if dll_handle is not None:
        running = True
    return running 
Example #6
Source File: aceinna_ins.py    From gnss-ins-sim with MIT License 5 votes vote down vote up
def reset(self):
        '''
        Reset the fusion process to uninitialized state.
        '''
        windll.kernel32.FreeLibrary.argtypes = [wintypes.HMODULE]
        windll.kernel32.FreeLibrary(self.sim_engine._handle)
        self.sim_engine = cdll.LoadLibrary(self.sim_lib)
        self.sim_engine.SimInitialize(pointer(self.sim_config)) 
Example #7
Source File: win.py    From gd.py with MIT License 5 votes vote down vote up
def get_module_handle(module_name: wintypes.LPCSTR) -> wintypes.HMODULE:
    pass 
Example #8
Source File: win.py    From gd.py with MIT License 5 votes vote down vote up
def get_proc_address(
    module_handle: wintypes.HMODULE, proc_name: wintypes.LPCSTR
) -> wintypes.LPVOID:
    pass 
Example #9
Source File: __init__.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def copyload_shared_lib(dst_prefix=TESTFILE_PREFIX):
        """Ctx manager which picks up a random shared DLL lib used
        by this process, copies it in another location and loads it
        in memory via ctypes.
        Return the new absolutized, normcased path.
        """
        from ctypes import wintypes
        from ctypes import WinError
        ext = ".dll"
        dst = tempfile.mktemp(prefix=dst_prefix, suffix=ext)
        libs = [x.path for x in psutil.Process().memory_maps() if
                os.path.splitext(x.path)[1].lower() == ext and
                'python' in os.path.basename(x.path).lower() and
                'wow64' not in x.path.lower()]
        src = random.choice(libs)
        shutil.copyfile(src, dst)
        cfile = None
        try:
            cfile = ctypes.WinDLL(dst)
            yield dst
        finally:
            # Work around OverflowError:
            # - https://ci.appveyor.com/project/giampaolo/psutil/build/1207/
            #       job/o53330pbnri9bcw7
            # - http://bugs.python.org/issue30286
            # - http://stackoverflow.com/questions/23522055
            if cfile is not None:
                FreeLibrary = ctypes.windll.kernel32.FreeLibrary
                FreeLibrary.argtypes = [wintypes.HMODULE]
                ret = FreeLibrary(cfile._handle)
                if ret == 0:
                    WinError()
            safe_rmpath(dst) 
Example #10
Source File: __init__.py    From psutil with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def copyload_shared_lib(suffix=""):
        """Ctx manager which picks up a random shared DLL lib used
        by this process, copies it in another location and loads it
        in memory via ctypes.
        Return the new absolutized, normcased path.
        """
        from ctypes import wintypes
        from ctypes import WinError
        ext = ".dll"
        dst = get_testfn(suffix=suffix + ext)
        libs = [x.path for x in psutil.Process().memory_maps() if
                x.path.lower().endswith(ext) and
                'python' in os.path.basename(x.path).lower() and
                'wow64' not in x.path.lower()]
        if PYPY and not libs:
            libs = [x.path for x in psutil.Process().memory_maps() if
                    'pypy' in os.path.basename(x.path).lower()]
        src = random.choice(libs)
        shutil.copyfile(src, dst)
        cfile = None
        try:
            cfile = ctypes.WinDLL(dst)
            yield dst
        finally:
            # Work around OverflowError:
            # - https://ci.appveyor.com/project/giampaolo/psutil/build/1207/
            #       job/o53330pbnri9bcw7
            # - http://bugs.python.org/issue30286
            # - http://stackoverflow.com/questions/23522055
            if cfile is not None:
                FreeLibrary = ctypes.windll.kernel32.FreeLibrary
                FreeLibrary.argtypes = [wintypes.HMODULE]
                ret = FreeLibrary(cfile._handle)
                if ret == 0:
                    WinError()
            safe_rmpath(dst)


# ===================================================================
# --- Exit funs (first is executed last)
# ===================================================================


# this is executed first 
Example #11
Source File: threadpoolctl.py    From threadpoolctl with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _find_modules_with_enum_process_module_ex(self):
        """Loop through loaded libraries and return binders on supported ones

        This function is expected to work on windows system only.
        This code is adapted from code by Philipp Hagemeister @phihag available
        at https://stackoverflow.com/questions/17474574
        """
        from ctypes.wintypes import DWORD, HMODULE, MAX_PATH

        PROCESS_QUERY_INFORMATION = 0x0400
        PROCESS_VM_READ = 0x0010

        LIST_MODULES_ALL = 0x03

        ps_api = self._get_windll("Psapi")
        kernel_32 = self._get_windll("kernel32")

        h_process = kernel_32.OpenProcess(
            PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
            False, os.getpid())
        if not h_process:  # pragma: no cover
            raise OSError("Could not open PID %s" % os.getpid())

        try:
            buf_count = 256
            needed = DWORD()
            # Grow the buffer until it becomes large enough to hold all the
            # module headers
            while True:
                buf = (HMODULE * buf_count)()
                buf_size = ctypes.sizeof(buf)
                if not ps_api.EnumProcessModulesEx(
                        h_process, ctypes.byref(buf), buf_size,
                        ctypes.byref(needed), LIST_MODULES_ALL):
                    raise OSError("EnumProcessModulesEx failed")
                if buf_size >= needed.value:
                    break
                buf_count = needed.value // (buf_size // buf_count)

            count = needed.value // (buf_size // buf_count)
            h_modules = map(HMODULE, buf[:count])

            # Loop through all the module headers and get the module path
            buf = ctypes.create_unicode_buffer(MAX_PATH)
            n_size = DWORD()
            for h_module in h_modules:

                # Get the path of the current module
                if not ps_api.GetModuleFileNameExW(
                        h_process, h_module, ctypes.byref(buf),
                        ctypes.byref(n_size)):
                    raise OSError("GetModuleFileNameEx failed")
                filepath = buf.value

                # Store the module if it is supported and selected
                self._make_module_from_path(filepath)
        finally:
            kernel_32.CloseHandle(h_process)