使用ctypes.sizeof时,ctypes定义的PROCESSENTRY32产生不正确的大小

时间:2018-09-02 17:56:57

标签: python winapi ctypes

class PROCESSENTRY32(ctypes.Structure):
    _pack_ = 8
    _fields_ = [
            ("dwSize",              ctypes.c_ulong),
            ("cntUsage",            ctypes.c_ulong),
            ("th32ProcessID",       ctypes.c_ulong),
            ("th32DefaultHeapID",   ctypes.POINTER(ctypes.c_uint64)),
            ("th32ModuleID",        ctypes.c_ulong),
            ("cntThreads",          ctypes.c_ulong),
            ("th32ParentProcessID", ctypes.c_ulong),
            ("pcPriClassBase",      ctypes.c_long),
            ("dwFlags",             ctypes.c_ulong),
            ("szExeFile",           ctypes.c_char*MAX_PATH)
            ]

这是我的结构定义;最初的一些评论是,带有/不带有_pack_=8的结构不会显示正确的大小,_pack_=1也不会显示正确的大小。我基于Process32First在调用后设置ERROR_BAD_LENGTH错误代码这一事实来解决这个问题。我不知道为什么会是快照本身。

def process32_first(snapshot_handle, process_entry_pointer, _ctypes_configuration=(
                    ("hSnapshot", (ctypes.c_voidp, True)),
                    ("lppe", (ctypes.POINTER(PROCESSENTRY32), True))
                   )):
    process32_first = import_winapi_function(
        "kernel32",
        "Process32First",
        argtypes_from_ctypes_configuration(_ctypes_configuration),
        ctypes.c_int
    )
    return process32_first(
        ctypes_configuration_param_select(_ctypes_configuration, 0) or snapshot_handle,
        ctypes_configuration_param_select(_ctypes_configuration, 1) or process_entry_pointer
    )

ctypes_configuration_param_select仅在_ctypes_configuration中选择不是True的预设值,或采用用户指定的输入。在import_winapi_call中,将参数和返回类型分别设置为WinAPI定义的ctypes.c_voidpctypes.POINTER(PROCESSENTRY32)。返回类型为ctypes.c_int,代表BOOL

if __name__ == "__main__":
    snapshot = debug_fn(create_toolhelp32_snapshot, 0x2, 0)
    pe = PROCESSENTRY32()
    pe.dwSize = ctypes.sizeof(PROCESSENTRY32)
    debug_fn(process32_first, snapshot, ctypes.pointer(pe))

这是该函数的实际用法和该结构的定义; debug_fn只是一个包装,将实际的函数调用夹在两个GetLastError调用之间,表示之前和之后的错误代码。

总而言之,debug_fn(process32_first, ...)调用产生的呼叫后错误代码为24 / ERROR_BAD_LENGTH,我将其归因于ctypes大小错误的PROCESSENTRY32 / pe结构。

我该如何解决?

编辑:

以下是ctypes_configuration_param_selectargtypes_from_ctypes_configurationimport_winapi_functionWinAPIFunctiondebug_fn

def argtypes_from_ctypes_configuration(ctypes_configuration):
    return tuple(v[0] for _, v in ctypes_configuration)

def ctypes_configuration_param_select(ctypes_configuration, idx):
    return ctypes_configuration[idx][1][1] if ctypes_configuration[idx][1][1] is not True else False

import_winapi_function定义:

def import_winapi_function(namespace, name, argtypes, restype, is_unicode=UNICODE):
    gle = function_cache['kernel32.GetLastError']
    sle = function_cache['kernel32.SetLastError']
    gpa = function_cache['kernel32.GetProcAddress']
    gmh = function_cache['kernel32.GetModuleHandleA']

    name += "W" if is_unicode else "A"
    qual_fn_name = f"{namespace}.{name}"
    if qual_fn_name in function_cache:
        return function_cache[qual_fn_name]
    namespace_handle = gmh(create_string(namespace, False))
    if gle() == 127:
        sle(0)
        raise LookupError(f"Module: {namespace} doesn't exist.")
    function_handle = gpa(namespace_handle, create_string(name, False))
    if gle() != 127:
        function_cache[qual_fn_name] = WinAPIFunction(namespace, name, function_handle, restype, argtypes)
        return function_cache[qual_fn_name]
    sle(0) 
    name = name[:-1]
    qual_fn_name = qual_fn_name[:-1]
    if qual_fn_name in function_cache:
        return function_cache[qual_fn_name]
    function_handle = gpa(namespace_handle, create_string(name, False))
    if gle() == 127:
        sle(0)
        raise LookupError(f"Function: {namespace}.{name} doesn't exist.")
    function_cache[qual_fn_name] = WinAPIFunction(namespace, name, function_handle, restype, argtypes)
    return function_cache[qual_fn_name]

WinAPIFunction定义:

class WinAPIFunction(object):
    def __init__(self, module, name, handle, restype, argtypes):
        self.module = module
        self.name = name
        self.handle = handle
        self.argtypes = argtypes
        self.restype = restype 
    def __repr__(self):
        return f"<{self.module}.{self.name} @ {hex(self.handle)}>"
    __str__ = __repr__
    def __call__(self, *args):
        return ctypes.WINFUNCTYPE(self.restype, *self.argtypes)(self.handle)(*args)

还有debug_fn

def debug_fn(fn, *args, **kwargs):
    gle = get_last_error  # changeable
    print(f"\n{fn}:")
    print(f"\tget_last_error: {gle()}")
    res = fn(*args, **kwargs)
    print(f"\tret. code: {res}")
    print(f"\tget_last_error: {gle()}\n")
    return res

如果您想复制我的代码;那么您只需要function_cache和上面的代码段即可:

MAX_PATH = 260
function_cache = {
        "kernel32.GetProcAddress": ctypes.windll.kernel32.GetProcAddress,
        "kernel32.SetLastError": ctypes.windll.kernel32.SetLastError,
        "kernel32.GetModuleHandleA": ctypes.windll.kernel32.GetModuleHandleA,
        "kernel32.GetLastError": ctypes.windll.kernel32.GetLastError
        }  # primitive definitions, not WinAPIFunction instances

function_cache['kernel32.GetProcAddress'].argtypes = (
    ctypes.c_voidp,
    ctypes.POINTER(ctypes.c_char)
)
function_cache['kernel32.GetProcAddress'].restype = ctypes.c_voidp

function_cache['kernel32.SetLastError'].argtypes = (
    ctypes.c_ulong,
)
function_cache['kernel32.SetLastError'].restype = None

function_cache['kernel32.GetModuleHandleA'].argtypes = (
    ctypes.POINTER(ctypes.c_char),
)
function_cache['kernel32.GetModuleHandleA'].restype = ctypes.c_voidp

function_cache['kernel32.GetLastError'].argtypes = ()
function_cache['kernel32.GetLastError'].restype = ctypes.c_ulong

UNICODE在我的环境中设置为True。

1 个答案:

答案 0 :(得分:-1)

该结构的 <span class="circle small" [ngClass]="statusColor"></span> 成员应该是szExeFile(或者最好是TCHAR,正如我在其他地方告诉过的那样),而不是定义的WCHARPROCESSENTRY定义和data types(请参阅CHAR)定义。