1 #ifndef _APITEST_GUARD_H
2 #define _APITEST_GUARD_H
3
4 #include <ndk/mmfuncs.h>
5 #include <ndk/psfuncs.h>
6
7 static
8 inline
9 PVOID
AllocateGuarded(_In_ SIZE_T SizeRequested)10 AllocateGuarded(
11 _In_ SIZE_T SizeRequested)
12 {
13 NTSTATUS Status;
14 SIZE_T Size = PAGE_ROUND_UP(SizeRequested + PAGE_SIZE);
15 PVOID VirtualMemory = NULL;
16 PCHAR StartOfBuffer;
17
18 Status = NtAllocateVirtualMemory(NtCurrentProcess(), &VirtualMemory, 0, &Size, MEM_RESERVE, PAGE_NOACCESS);
19
20 if (!NT_SUCCESS(Status))
21 return NULL;
22
23 Size -= PAGE_SIZE;
24 if (Size)
25 {
26 Status = NtAllocateVirtualMemory(NtCurrentProcess(), &VirtualMemory, 0, &Size, MEM_COMMIT, PAGE_READWRITE);
27 if (!NT_SUCCESS(Status))
28 {
29 Size = 0;
30 Status = NtFreeVirtualMemory(NtCurrentProcess(), &VirtualMemory, &Size, MEM_RELEASE);
31 ok(Status == STATUS_SUCCESS, "Status = %lx\n", Status);
32 return NULL;
33 }
34 }
35
36 StartOfBuffer = VirtualMemory;
37 StartOfBuffer += Size - SizeRequested;
38
39 return StartOfBuffer;
40 }
41
42 static
43 inline
44 VOID
FreeGuarded(_In_ PVOID Pointer)45 FreeGuarded(
46 _In_ PVOID Pointer)
47 {
48 NTSTATUS Status;
49 PVOID VirtualMemory = (PVOID)PAGE_ROUND_DOWN((SIZE_T)Pointer);
50 SIZE_T Size = 0;
51
52 Status = NtFreeVirtualMemory(NtCurrentProcess(), &VirtualMemory, &Size, MEM_RELEASE);
53 ok(Status == STATUS_SUCCESS, "Status = %lx\n", Status);
54 }
55
56 static
57 inline
58 VOID
MakeReadOnly(PVOID Pointer,SIZE_T SizeRequested)59 MakeReadOnly(
60 PVOID Pointer,
61 SIZE_T SizeRequested)
62 {
63 NTSTATUS Status;
64 SIZE_T Size = PAGE_ROUND_UP(SizeRequested);
65 PVOID VirtualMemory = (PVOID)PAGE_ROUND_DOWN((SIZE_T)Pointer);
66
67 if (Size)
68 {
69 Status = NtAllocateVirtualMemory(NtCurrentProcess(), &VirtualMemory, 0, &Size, MEM_COMMIT, PAGE_READWRITE);
70 if (!NT_SUCCESS(Status))
71 {
72 Size = 0;
73 Status = NtFreeVirtualMemory(NtCurrentProcess(), &VirtualMemory, &Size, MEM_RELEASE);
74 ok(Status == STATUS_SUCCESS, "Status = %lx\n", Status);
75 }
76 }
77 }
78
79 #endif /* _APITEST_GUARD_H */
80