Every process has a PEB
The Process Environment Block is a structure in your own address space where Windows keeps facts about the process: where the EXE is loaded, the command line, the loaded modules, whether a debugger is attached. API functions read it for you: GetModuleHandleW(NULL) returns a field of it, GetCommandLineW() another, IsDebuggerPresent() a third. Debuggers, Process Explorer and the loader read it directly.
Each thread has a TEB (Thread Environment Block), and on x64 the gs segment register points at the current thread's TEB. The TEB holds a pointer to the PEB at offset 0x60:
PEB *peb = (PEB *)__readgsqword(0x60); // compiler intrinsic: read qword at gs:[0x60]NtQueryInformationProcess with ProcessBasicInformation reports the same address in PebBaseAddress.
The fields you will meet
| Offset (x64) | Field | Means |
|---|---|---|
0x02 | BeingDebugged | 1 while a debugger is attached (IsDebuggerPresent returns it) |
0x10 | ImageBaseAddress | where the EXE is mapped (GetModuleHandleW(NULL)) |
0x18 | Ldr | the loader's data: lists of loaded modules |
0x20 | ProcessParameters | image path, command line, current directory, environment |
winternl.h declares a partial PEB; most fields are named Reserved. Writing your own small struct with the documented offsets, as this lesson does, makes the layout explicit.
UNICODE_STRING
Kernel and ntdll structures store strings as a UNICODE_STRING: a pointer plus a length in bytes, not necessarily 0-terminated.
typedef struct { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING;
// characters = Length / sizeof(WCHAR)
printf("%.*ls", (int)(s.Length / sizeof(WCHAR)), s.Buffer);The loader's module list
Ldr points at a PEB_LDR_DATA that holds three circular doubly linked lists of LDR_DATA_TABLE_ENTRY records, one per loaded module, in load order, memory order and initialization order. The list nodes are LIST_ENTRYs inside each record, exactly the LIST_ENTRY / CONTAINING_RECORD pattern from the C capstone:
LIST_ENTRY *head = &peb->Ldr->InMemoryOrderModuleList;
for (LIST_ENTRY *e = head->Flink; e != head; e = e->Flink) {
LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(e, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
// mod->DllBase, mod->FullDllName ...
}The order always starts the same way: the EXE, then ntdll.dll, kernel32.dll, kernelbase.dll. This lesson only reads these structures. Modifying them corrupts the process.
BeingDebugged becomes 1, and the debugger's stack and register views show you the very addresses you print.