Windows 使用者模式下的 Native API 是 Win32 API 的底層支撐。微軟未公開文件化,但透過 NtQuerySystemInformation 可取得極豐富的系統資訊(進程、執行緒、記憶體、I/O、效能計數器等 50+ 類別)。本文整理核心結構與呼叫範例,僅供研究學習,生產環境請優先使用 Win32 API (PSAPI/ToolHelp32/WMI)。
typedef NTSTATUS (__stdcall *NTQUERYSYSTEMINFORMATION)(
IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
IN OUT PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT PULONG ReturnLength OPTIONAL
);
動態載入:GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQuerySystemInformation")。
typedef struct _SYSTEM_PROCESSES {
ULONG NextEntryDelta; // 下一筆偏移
ULONG ThreadCount;
ULONG Reserved1[6];
LARGE_INTEGER CreateTime; // 建立時間
LARGE_INTEGER UserTime; // User-mode CPU 時間
LARGE_INTEGER KernelTime; // Kernel-mode CPU 時間
UNICODE_STRING ProcessName; // 進程名稱
KPRIORITY BasePriority;
ULONG ProcessId;
ULONG InheritedFromProcessId; // 父進程 PID
ULONG HandleCount;
ULONG Reserved2[2];
VM_COUNTERS VmCounters; // 虛擬記憶體計數
IO_COUNTERS IoCounters; // I/O 計數
SYSTEM_THREADS Threads[1]; // 執行緒陣列
} SYSTEM_PROCESSES, *PSYSTEM_PROCESSES;
typedef struct _SYSTEM_THREADS {
LARGE_INTEGER KernelTime, UserTime, CreateTime;
ULONG WaitTime;
PVOID StartAddress;
CLIENT_ID ClientId;
KPRIORITY Priority, BasePriority;
ULONG ContextSwitchCount;
THREAD_STATE State;
KWAIT_REASON WaitReason;
} SYSTEM_THREADS;
遍歷方式:依 NextEntryDelta 移動指標,直到為 0。
提供 70+ 效能計數器:IdleProcessTime、ReadOperationCount、PageFaultCount、CommitPages、PoolPagedBytes 等,適合自製工作管理員效能頁籤。
SystemMemoryInformation (5) — 記憶體總覽SystemHandleInformation (16) — 系統控制碼表SystemModuleInformation (11) — 載入驅動模組清單
NTSTATUS status;
ULONG len = 0;
PVOID buf = NULL;
// 第一次呼叫取得所需緩衝區大小
status = NtQuerySystemInformation(SystemProcessInformation, NULL, 0, &len);
buf = VirtualAlloc(NULL, len, MEM_COMMIT, PAGE_READWRITE);
status = NtQuerySystemInformation(SystemProcessInformation, buf, len, NULL);
PSYSTEM_PROCESSES p = (PSYSTEM_PROCESSES)buf;
while (true) {
wprintf(L"PID: %u Name: %wZ Threads: %u Handles: %u\n",
p->ProcessId, &p->ProcessName, p->ThreadCount, p->HandleCount);
if (p->NextEntryDelta == 0) break;
p = (PSYSTEM_PROCESSES)((BYTE*)p + p->NextEntryDelta);
}
VirtualFree(buf, 0, MEM_RELEASE);
ntdll.lib 或動態載入FZ5FZ 團隊,專注網路/系統安全研究與原創技術分享。
完整 Demo 含進程/執行緒/模組/控制碼/記憶體/效能等多頁籤監控介面。