1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/*
 * PROJECT:         ReactOS kernel-mode tests
 * LICENSE:         GPLv2+ - See COPYING in the top level directory
 * PURPOSE:         Kernel-Mode Test Suite ZwAllocateVirtualMemory/ZwFreeVirtualMemory
 * PROGRAMMER:      Nikolay Borisov <nib9@aber.ac.uk>
 */

#include <kmt_test.h>

#define ROUND_DOWN(n,align) (((ULONG_PTR)n) & ~((align) - 1l))
#define DEFAULT_ALLOC_SIZE 200
#define IGNORE -1
#define PAGE_NOPROT 0x0 //MEM_RESERVE has this type of "protection"

/* These are being used in ZwMapViewOfSection as well */
const char TestString[] = "TheLongBrownFoxJumpedTheWhiteRabbitTheLongBrownFoxJumpedTheWhiteRabbitTheLongBrownFoxJumpedTheWhiteRabbitTheLongBrownFoxJumpedTheWhiteRabbitTheLongBrownFoxJumpedTheWhiteRabbitTheLongBrownFoxJumpedThe";
const ULONG TestStringSize = sizeof(TestString);

VOID Test_ZwAllocateVirtualMemory(VOID);

typedef struct _TEST_CONTEXT
{
    HANDLE ProcessHandle;
    SIZE_T RegionSize;
    ULONG AllocationType;
    ULONG Protect;
    PVOID Bases[1024];
    SHORT ThreadId;
} TEST_CONTEXT, *PTEST_CONTEXT;


#define ALLOC_MEMORY_WITH_FREE(ProcessHandle, BaseAddress, ZeroBits, RegionSize, AllocationType, Protect, RetStatus, FreeStatus)   \
    do {                                                                                                                   \
        PVOID __BaseSave = BaseAddress;                                                                                    \
        Status = ZwAllocateVirtualMemory(ProcessHandle, &BaseAddress, ZeroBits, &RegionSize, AllocationType, Protect);     \
        ok_eq_hex(Status, RetStatus);                                                                                      \
        if (__BaseSave != NULL)                                                                                            \
            ok_eq_pointer(BaseAddress, __BaseSave);                                                                        \
        else if (!NT_SUCCESS(Status))                                                                                      \
            ok_eq_pointer(BaseAddress, NULL);                                                                              \
        RegionSize = 0;                                                                                                    \
        Status = ZwFreeVirtualMemory(ProcessHandle, &BaseAddress, &RegionSize, MEM_RELEASE);                               \
        if (FreeStatus != IGNORE) ok_eq_hex(Status, FreeStatus);                                                           \
        BaseAddress = NULL;                                                                                                \
        RegionSize = DEFAULT_ALLOC_SIZE;                                                                                   \
    } while (0)                                                                                                            \



static
BOOLEAN
CheckBuffer(PVOID Buffer, SIZE_T Size, UCHAR Value)
{
    PUCHAR Array = Buffer;
    SIZE_T i;

    for (i = 0; i < Size; i++)
    {
        if (Array[i] != Value)
        {
            trace("Expected %x, found %x at offset %lu\n", Value, Array[i], (ULONG)i);
            return FALSE;
        }
    }
    return TRUE;
}

static
SIZE_T
CheckBufferRead(CONST VOID *Source, CONST VOID *Destination, SIZE_T Length, NTSTATUS ExpectedStatus)
{
    SIZE_T Match = 0;

    KmtStartSeh()
        Match = RtlCompareMemory(Source, Destination, Length);
    KmtEndSeh(ExpectedStatus);

    return Match;
}

static
VOID
CheckBufferReadWrite(PVOID Destination, CONST VOID *Source, SIZE_T Length, NTSTATUS ExpectedStatus)
{
    //do a little bit of writing/reading to memory
    SIZE_T Match = 0;

    KmtStartSeh()
        RtlCopyMemory(Destination, Source, Length);
    KmtEndSeh(ExpectedStatus);

    Match = CheckBufferRead(Source, Destination, Length, ExpectedStatus);
    if (ExpectedStatus == STATUS_SUCCESS) ok_eq_int(Match, Length);
}


static
VOID
SimpleErrorChecks(VOID)
{
    NTSTATUS Status;
    PVOID Base = NULL;
    SIZE_T RegionSize = DEFAULT_ALLOC_SIZE;

    //HANDLE TESTS
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_SUCCESS, STATUS_SUCCESS);
    ALLOC_MEMORY_WITH_FREE(NULL, Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_INVALID_HANDLE, STATUS_INVALID_HANDLE);
    ALLOC_MEMORY_WITH_FREE((HANDLE)(ULONG_PTR)0xDEADBEEFDEADBEEFull, Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_INVALID_HANDLE, STATUS_INVALID_HANDLE);

    //BASE ADDRESS TESTS
    Base = (PVOID)0x00567A20;
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_CONFLICTING_ADDRESSES, STATUS_UNABLE_TO_DELETE_SECTION);

    Base = (PVOID) 0x60000000;
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_SUCCESS, STATUS_SUCCESS);

    Base = (PVOID)((char *)MmSystemRangeStart + 200);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_INVALID_PARAMETER_2, STATUS_INVALID_PARAMETER_2);

    /* http://jira.reactos.org/browse/CORE-6814 */
    RegionSize = 0x1000;
    Base = Test_ZwAllocateVirtualMemory;
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, MEM_COMMIT, PAGE_READWRITE, STATUS_INVALID_PARAMETER_2, STATUS_INVALID_PARAMETER_2);

    //ZERO BITS TESTS
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 21, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_NO_MEMORY, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 22, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_INVALID_PARAMETER_3, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, -1, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_INVALID_PARAMETER_3, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 3, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_SUCCESS, STATUS_SUCCESS);

    //REGION SIZE TESTS
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_SUCCESS, STATUS_SUCCESS);
    RegionSize = -1;
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_INVALID_PARAMETER_4, STATUS_MEMORY_NOT_ALLOCATED);
    RegionSize = 0;
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_INVALID_PARAMETER_4, STATUS_MEMORY_NOT_ALLOCATED);
    RegionSize = 0xFFFFFFFF; // 4 gb  is invalid
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_INVALID_PARAMETER_4, STATUS_MEMORY_NOT_ALLOCATED);

    //Allocation type tests
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, MEM_PHYSICAL, PAGE_READWRITE, STATUS_INVALID_PARAMETER_5, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESET), PAGE_READWRITE, STATUS_INVALID_PARAMETER_5, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, 0, PAGE_READWRITE, STATUS_INVALID_PARAMETER_5, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, MEM_TOP_DOWN, PAGE_READWRITE, STATUS_INVALID_PARAMETER_5, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_TOP_DOWN | MEM_RESET), PAGE_READWRITE, STATUS_INVALID_PARAMETER_5, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_TOP_DOWN | MEM_COMMIT), PAGE_READWRITE, STATUS_SUCCESS, STATUS_SUCCESS);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_PHYSICAL | MEM_RESERVE), PAGE_READWRITE, STATUS_SUCCESS, STATUS_SUCCESS);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_PHYSICAL | MEM_COMMIT), PAGE_READWRITE, STATUS_INVALID_PARAMETER_5, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_RESET | MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE, STATUS_INVALID_PARAMETER_5, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, -1, PAGE_READWRITE, STATUS_INVALID_PARAMETER_5, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize,  MEM_COMMIT, PAGE_READWRITE, STATUS_SUCCESS, STATUS_SUCCESS);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize,  MEM_RESERVE, PAGE_READWRITE, STATUS_SUCCESS, STATUS_SUCCESS);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize,  MEM_RESERVE, PAGE_WRITECOPY, STATUS_INVALID_PAGE_PROTECTION, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize,  MEM_RESERVE, PAGE_EXECUTE_WRITECOPY, STATUS_INVALID_PAGE_PROTECTION, STATUS_MEMORY_NOT_ALLOCATED);

    //Memory protection tests
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), 0, STATUS_INVALID_PAGE_PROTECTION, STATUS_MEMORY_NOT_ALLOCATED);
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), -1, STATUS_INVALID_PAGE_PROTECTION, STATUS_MEMORY_NOT_ALLOCATED);
    if (!KmtIsCheckedBuild)
    {
        ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), (PAGE_NOACCESS | PAGE_GUARD), STATUS_INVALID_PAGE_PROTECTION, STATUS_MEMORY_NOT_ALLOCATED);
        ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), (PAGE_NOACCESS | PAGE_WRITECOMBINE), STATUS_INVALID_PAGE_PROTECTION, STATUS_MEMORY_NOT_ALLOCATED);
    }
    ALLOC_MEMORY_WITH_FREE(NtCurrentProcess(), Base, 0, RegionSize, (MEM_COMMIT | MEM_RESERVE), (PAGE_READONLY | PAGE_WRITECOMBINE), STATUS_SUCCESS, STATUS_SUCCESS);
}


static
NTSTATUS
SimpleAllocation(VOID)
{
    NTSTATUS Status;
    PVOID Base = NULL;
    SIZE_T RegionSize = DEFAULT_ALLOC_SIZE;

    //////////////////////////////////////////////////////////////////////////
    //Normal operation
    //////////////////////////////////////////////////////////////////////////
    Status = ZwAllocateVirtualMemory(NtCurrentProcess(), &Base, 0, &RegionSize, MEM_COMMIT, PAGE_READWRITE);<--- Status is assigned
    ok_eq_size(RegionSize, 4096);

    //check for the zero-filled pages
    ok_bool_true(CheckBuffer(Base, RegionSize, 0), "The buffer is not zero-filled");

    CheckBufferReadWrite(Base, TestString, TestStringSize, STATUS_SUCCESS);

    // try freeing
    RegionSize = 0;
    Status = ZwFreeVirtualMemory(NtCurrentProcess(), &Base, &RegionSize, MEM_RELEASE);<--- Status is overwritten
    ok_eq_hex(Status, STATUS_SUCCESS);
    ok_eq_size(RegionSize, PAGE_SIZE);

    //////////////////////////////////////////////////////////////////////////
    // COMMIT AND RESERVE SCENARIO AND STATE CHANGE
    //////////////////////////////////////////////////////////////////////////
    //reserve and then commit
    Base = NULL;
    RegionSize = DEFAULT_ALLOC_SIZE;
    Status = ZwAllocateVirtualMemory(NtCurrentProcess(), &Base, 0, &RegionSize, MEM_RESERVE, PAGE_READWRITE);<--- Status is assigned
    Test_NtQueryVirtualMemory(Base, RegionSize, MEM_RESERVE, PAGE_NOPROT);
    CheckBufferReadWrite(Base, TestString, TestStringSize, STATUS_ACCESS_VIOLATION);


    Status = ZwAllocateVirtualMemory(NtCurrentProcess(), &Base, 0, &RegionSize, MEM_COMMIT, PAGE_READWRITE);<--- Status is overwritten
    CheckBufferReadWrite(Base, TestString, TestStringSize, STATUS_SUCCESS);
    Test_NtQueryVirtualMemory(Base, RegionSize, MEM_COMMIT, PAGE_READWRITE);

    RegionSize = 0;
    ZwFreeVirtualMemory(NtCurrentProcess(), &Base, &RegionSize, MEM_RELEASE);

    //////////////////////////////////////////////////////////////////////////
    // TRY READING/WRITING TO INVALID PROTECTION PAGES
    //////////////////////////////////////////////////////////////////////////
    RegionSize = DEFAULT_ALLOC_SIZE;
    Base = NULL;
    ZwAllocateVirtualMemory(NtCurrentProcess(), &Base, 0, &RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_NOACCESS);

    KmtStartSeh()
        RtlCopyMemory(Base, TestString, TestStringSize);
    KmtEndSeh(STATUS_ACCESS_VIOLATION);

    Test_NtQueryVirtualMemory(Base, RegionSize, MEM_COMMIT, PAGE_NOACCESS);
    CheckBufferRead(Base, TestString, TestStringSize, STATUS_ACCESS_VIOLATION);

    RegionSize = 0;
    ZwFreeVirtualMemory(NtCurrentProcess(), &Base, &RegionSize, MEM_RELEASE);

    ZwAllocateVirtualMemory(NtCurrentProcess(), &Base, 0, &RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READONLY);
    KmtStartSeh()
        RtlCopyMemory(Base, TestString, TestStringSize);
    KmtEndSeh(STATUS_ACCESS_VIOLATION);

    Test_NtQueryVirtualMemory(Base, RegionSize, MEM_COMMIT, PAGE_READONLY);

    ok_bool_true(CheckBuffer(Base, TestStringSize, 0), "Couldn't read a read-only buffer");

    RegionSize = 0;
    ZwFreeVirtualMemory(NtCurrentProcess(), &Base, &RegionSize, MEM_RELEASE);

    //////////////////////////////////////////////////////////////////////////
    // GUARD PAGES
    //////////////////////////////////////////////////////////////////////////

    RegionSize = 1000;
    Base = NULL;
    ZwAllocateVirtualMemory(NtCurrentProcess(), &Base, 0, &RegionSize, (MEM_COMMIT | MEM_RESERVE), (PAGE_GUARD | PAGE_READWRITE));

    Test_NtQueryVirtualMemory(Base, RegionSize, MEM_COMMIT, (PAGE_GUARD | PAGE_READWRITE));
    KmtStartSeh()
        RtlCopyMemory(Base, TestString, TestStringSize);
    KmtEndSeh(STATUS_GUARD_PAGE_VIOLATION);

    Test_NtQueryVirtualMemory(Base, RegionSize, MEM_COMMIT, PAGE_READWRITE);

    KmtStartSeh()
        RtlCopyMemory(Base, TestString, TestStringSize);
    KmtEndSeh(STATUS_SUCCESS);

    RegionSize = 0;
    ZwFreeVirtualMemory(NtCurrentProcess(), &Base, &RegionSize, MEM_RELEASE);

    return Status;
}


static
VOID
CustomBaseAllocation(VOID)
{
    NTSTATUS Status;
    SIZE_T RegionSize = 200;
    PVOID Base =  (PVOID) 0x60025000;
    PVOID ActualStartingAddress = (PVOID)ROUND_DOWN(Base, MM_ALLOCATION_GRANULARITY); //it is rounded down to the nearest allocation granularity (64k) address
    PVOID EndingAddress = (PVOID)(((ULONG_PTR)Base + RegionSize - 1) | (PAGE_SIZE - 1));
    SIZE_T ActualSize = BYTES_TO_PAGES((ULONG_PTR)EndingAddress - (ULONG_PTR)ActualStartingAddress) * PAGE_SIZE; //calculates the actual size based on the required pages

    // allocate the memory
    Status = ZwAllocateVirtualMemory(NtCurrentProcess(), (PVOID *)&Base, 0, &RegionSize, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE);
    ok_eq_hex(Status, STATUS_SUCCESS);
    ok_eq_size(RegionSize, ActualSize);
    ok_eq_ulong(Base, ActualStartingAddress);
    Test_NtQueryVirtualMemory(ActualStartingAddress, ActualSize, MEM_COMMIT, PAGE_READWRITE);

    // try freeing
    RegionSize = 0;
    Status = ZwFreeVirtualMemory(NtCurrentProcess(), (PVOID *)&Base, &RegionSize, MEM_RELEASE);
    ok_eq_hex(Status, STATUS_SUCCESS);
    ok_eq_ulong(RegionSize, ActualSize);
}


static
NTSTATUS
StressTesting(ULONG AllocationType)
{
    NTSTATUS Status = STATUS_SUCCESS;
    NTSTATUS ReturnStatus = STATUS_SUCCESS;
    static PVOID bases[1024]; //assume we are going to allocate only 5 gigs. static here means the arrays is not allocated on the stack but in the BSS segment of the driver
    ULONG Index = 0;
    PVOID Base = NULL;
    SIZE_T RegionSize = 5 * 1024 * 1024; // 5 megabytes;

    RtlZeroMemory(bases, sizeof(bases));

    for (Index = 0; Index < RTL_NUMBER_OF(bases) && NT_SUCCESS(Status); Index++)
    {
        Status = ZwAllocateVirtualMemory(NtCurrentProcess(), &Base, 0, &RegionSize, AllocationType, PAGE_READWRITE);

        bases[Index] = Base;
        if ((Index % 10) == 0)
        {
            if (AllocationType == MEM_COMMIT && NT_SUCCESS(Status))
            {
                CheckBufferReadWrite(Base, TestString, TestStringSize, STATUS_SUCCESS);
            }
            else
            {
                CheckBufferReadWrite(Base, TestString, TestStringSize, STATUS_ACCESS_VIOLATION);
            }
        }

        Base = NULL;
    }

    trace("Finished reserving. Error code %x. Chunks allocated: %d\n", Status, Index );

    ReturnStatus = Status;

    //free the allocated memory so that we can continue with the tests
    Status = STATUS_SUCCESS;
    Index = 0;
    while (NT_SUCCESS(Status) && Index < RTL_NUMBER_OF(bases))
    {
        RegionSize = 0;
        Status = ZwFreeVirtualMemory(NtCurrentProcess(), &bases[Index], &RegionSize, MEM_RELEASE);
        bases[Index++] = NULL;
    }

    return ReturnStatus;
}


static
VOID
NTAPI
SystemProcessTestWorker(PVOID StartContext)
{
   NTSTATUS Status = STATUS_SUCCESS;
   PTEST_CONTEXT Context = (PTEST_CONTEXT)StartContext;
   ULONG Index = 0;
   PVOID Base = NULL;

   PAGED_CODE();

   RtlZeroMemory(Context->Bases, sizeof(Context->Bases));

   Status = ZwAllocateVirtualMemory(NtCurrentProcess(), &Base, 0, &Context->RegionSize, Context->AllocationType, Context->Protect);
   ZwFreeVirtualMemory(NtCurrentProcess(), &Base, &Context->RegionSize, MEM_RELEASE);
   Base = NULL;

    //if the previous allocation has failed there is no need to do the loop
    while (NT_SUCCESS(Status) && Index < RTL_NUMBER_OF(Context->Bases))
    {
        Status = ZwAllocateVirtualMemory(NtCurrentProcess(), &Base, 0, &Context->RegionSize, Context->AllocationType, Context->Protect);

        Context->Bases[Index] = Base;
        if ((Index % 10) == 0)
        {
            if (Context->AllocationType == MEM_COMMIT)
            {
                CheckBufferReadWrite(Base, TestString, TestStringSize, STATUS_SUCCESS);
            }
            else
            {
                CheckBufferReadWrite(Base, TestString, TestStringSize, STATUS_ACCESS_VIOLATION);
            }
        }

        Base = NULL;
        Index++;
    }

    trace("[SYSTEM THREAD %d]. Error code %x. Chunks allocated: %d\n", Context->ThreadId, Status, Index);

    //free the allocated memory so that we can continue with the tests
    Status = STATUS_SUCCESS;
    Index = 0;
    while (NT_SUCCESS(Status) && Index < RTL_NUMBER_OF(Context->Bases))
    {
        Context->RegionSize = 0;
        Status = ZwFreeVirtualMemory(NtCurrentProcess(), &Context->Bases[Index], &Context->RegionSize, MEM_RELEASE);
        Context->Bases[Index++] = NULL;
    }

    PsTerminateSystemThread(Status);
}


static
VOID
KmtInitTestContext(PTEST_CONTEXT Ctx, SHORT ThreadId, ULONG RegionSize, ULONG AllocationType, ULONG Protect)
{
    PAGED_CODE();

    Ctx->AllocationType = AllocationType;
    Ctx->Protect = Protect;
    Ctx->RegionSize = RegionSize;
    Ctx->ThreadId = ThreadId;
}


static
VOID
SystemProcessTest(VOID)
{
    NTSTATUS Status;
    HANDLE Thread1 = INVALID_HANDLE_VALUE;
    HANDLE Thread2 = INVALID_HANDLE_VALUE;
    PVOID ThreadObjects[2] = { NULL };
    OBJECT_ATTRIBUTES ObjectAttributes;
    PTEST_CONTEXT StartContext1;
    PTEST_CONTEXT StartContext2;

    PAGED_CODE();

    StartContext1 = ExAllocatePoolWithTag(PagedPool, sizeof(TEST_CONTEXT), 'tXTC');
    StartContext2 = ExAllocatePoolWithTag(PagedPool, sizeof(TEST_CONTEXT), 'tXTC');
    if (StartContext1 == NULL || StartContext2 == NULL)
    {
        trace("Error allocating space for context structs\n");
        goto cleanup;
    }

    KmtInitTestContext(StartContext1, 1, 1 * 1024 * 1024, MEM_COMMIT, PAGE_READWRITE);
    KmtInitTestContext(StartContext2, 2, 3 * 1024 * 1024, MEM_COMMIT, PAGE_READWRITE);
    InitializeObjectAttributes(&ObjectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);

    Status = PsCreateSystemThread(&Thread1, THREAD_ALL_ACCESS, &ObjectAttributes, NULL, NULL, SystemProcessTestWorker, StartContext1);
    if (!NT_SUCCESS(Status))
    {
        trace("Error creating thread1\n");
        goto cleanup;
    }

    Status = ObReferenceObjectByHandle(Thread1, THREAD_ALL_ACCESS, *PsThreadType, KernelMode, &ThreadObjects[0], NULL);
    if (!NT_SUCCESS(Status))
    {
        trace("error referencing thread1\n");
        goto cleanup;
    }

    Status = PsCreateSystemThread(&Thread2, THREAD_ALL_ACCESS, &ObjectAttributes, NULL, NULL, SystemProcessTestWorker, StartContext2);
    if (!NT_SUCCESS(Status))
    {
        trace("Error creating thread2\n");
        goto cleanup;
    }

    Status = ObReferenceObjectByHandle(Thread2, THREAD_ALL_ACCESS, *PsThreadType, KernelMode, &ThreadObjects[1], NULL);
    if (!NT_SUCCESS(Status))
    {
        trace("error referencing thread2\n");
        goto cleanup;
    }

cleanup:

    if (ThreadObjects[0])
        Status = KeWaitForSingleObject(ThreadObjects[0], Executive, KernelMode, FALSE, NULL);

    if (StartContext1 != NULL)
        ExFreePoolWithTag(StartContext1, 'tXTC');

    if (ThreadObjects[1])
        Status = KeWaitForSingleObject(ThreadObjects[1], Executive, KernelMode, FALSE, NULL);

    if (StartContext2 != NULL)
        ExFreePoolWithTag(StartContext2, 'tXTC');

    if (ThreadObjects[0] != NULL)
        ObDereferenceObject(ThreadObjects[0]);

    if (ThreadObjects[1] != NULL)
        ObDereferenceObject(ThreadObjects[1]);

    if (Thread1 != INVALID_HANDLE_VALUE)
        ZwClose(Thread1);

    if (Thread2 != INVALID_HANDLE_VALUE)
        ZwClose(Thread2);
}


START_TEST(ZwAllocateVirtualMemory)
{
    NTSTATUS Status;

    SimpleErrorChecks();

    SimpleAllocation();

    CustomBaseAllocation();

    Status = StressTesting(MEM_RESERVE);
    ok_eq_hex(Status, STATUS_NO_MEMORY);

    Status = STATUS_SUCCESS;<--- Status is assigned
    Status = StressTesting(MEM_COMMIT);<--- Status is overwritten
    ok_eq_hex(Status, STATUS_NO_MEMORY);

    SystemProcessTest();
}