Processes: improve performance (Windows)

This commit is contained in:
李通洲
2022-11-21 13:05:53 +08:00
parent 19c5904561
commit 308408a962
3 changed files with 49 additions and 5 deletions
+45 -1
View File
@@ -1,12 +1,54 @@
extern "C" {
#include "processes.h"
}
#include "util/windows/wmi.hpp"
#ifdef FF_USE_WIN_NTAPI
#include <winternl.h>
static inline void wrapFree(SYSTEM_PROCESS_INFORMATION** ptr)
{
free(*ptr);
}
uint32_t ffDetectProcesses(FFinstance* instance, FFstrbuf* error)
{
FF_UNUSED(instance);
ULONG size = 0;
if(NtQuerySystemInformation(SystemProcessInformation, nullptr, 0, &size) != (NTSTATUS)0xC0000004 /*STATUS_INFO_LENGTH_MISMATCH*/)
{
ffStrbufAppendS(error, "NtQuerySystemInformation(SystemProcessInformation, NULL) failed");
return 0;
}
size += sizeof(SystemProcessInformation) * 5; //What if new processes are created during two syscalls?
SYSTEM_PROCESS_INFORMATION* __attribute__((__cleanup__(wrapFree))) pstart = (SYSTEM_PROCESS_INFORMATION*)malloc(size);
if(!pstart)
{
ffStrbufAppendF(error, "malloc(%u) failed", (unsigned)size);
return 0;
}
if(!NT_SUCCESS(NtQuerySystemInformation(SystemProcessInformation, pstart, size, nullptr)))
{
ffStrbufAppendS(error, "NtQuerySystemInformation(SystemProcessInformation, pstart) failed");
return 0;
}
uint32_t result = 1; //Init with 1 because we test for ptr->NextEntryOffset
for (auto ptr = pstart; ptr->NextEntryOffset; ptr = (SYSTEM_PROCESS_INFORMATION*)((uint8_t*)ptr + ptr->NextEntryOffset))
++result;
return result;
}
#else
#include "util/windows/wmi.hpp"
uint32_t ffDetectProcesses(FFinstance* instance, FFstrbuf* error)
{
FFWmiQuery query(L"SELECT NumberOfProcesses FROM Win32_OperatingSystem", error);
if(!query)
return 0;
@@ -23,3 +65,5 @@ uint32_t ffDetectProcesses(FFinstance* instance, FFstrbuf* error)
return 0;
}
}
#endif