Skip to content

Instantly share code, notes, and snippets.

@PJB3005
Created November 25, 2023 21:17
Show Gist options
  • Save PJB3005/fe7927f42cfa0bd8c5e1dd0c152038d7 to your computer and use it in GitHub Desktop.
Save PJB3005/fe7927f42cfa0bd8c5e1dd0c152038d7 to your computer and use it in GitHub Desktop.
VirtualAlloc2 funnies
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <stdio.h>
#define SIZE (32ull * 1024 * 1024 * 1024)
#define BLOCKS (32 * 32)
#define BLOCK_SIZE (SIZE / BLOCKS)
#define PAGE_SIZE (4096)
void print_error(char* area, DWORD error);
int main()
{
printf("foo!\n");
// Based on https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc2#examples
PCHAR range = (PCHAR) VirtualAlloc2(
NULL,
NULL,
SIZE,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
NULL,
0
);
printf("Range: %p, end: %p\n", range, (range + SIZE));
DWORD error = GetLastError();
for (int i = 0; i < BLOCKS - 1; i++)
{
PCHAR chunk = range + (BLOCK_SIZE * i);
printf("VirtualFree %i: %p, %llu\n", i, chunk, BLOCK_SIZE);
BOOL result = VirtualFree(
chunk,
BLOCK_SIZE,
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
if (!result)
{
print_error("VirtualFree", GetLastError());
}
}
HANDLE zero = CreateFileMappingW(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
BLOCK_SIZE,
NULL
);
if (zero == NULL)
{
print_error("CreateFileMappingW", GetLastError());
}
for (int i = 0; i < BLOCKS - 1; i++)
{
PCHAR chunk = range + (BLOCK_SIZE * i);
PVOID result = MapViewOfFile3(
zero,
NULL,
chunk,
0,
BLOCK_SIZE,
MEM_REPLACE_PLACEHOLDER,
PAGE_READONLY,
NULL,
0
);
if (result == NULL)
{
print_error("MapViewOfFile3", GetLastError());
}
}
int* page = range + 5000 * 4096;
printf("Read: %d\n", *page);
// *page = 5;
Sleep(1000000);
}
void print_error(char* area, DWORD error)
{
char errBuf[512];
DWORD errChars = FormatMessageA(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error,
0,
errBuf,
sizeof(errBuf),
NULL);
if (errChars == 0) {
fprintf(stderr, "Failed to print previous error!\n");
exit(1);
}
fprintf(stderr, "%s: %s", area, errBuf);
exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment