| 26 | }; |
| 27 | |
| 28 | void SC::VirtualMemoryTest::virtualMemory() |
| 29 | { |
| 30 | //! [VirtualMemorySnippet] |
| 31 | // This test uses two pages initially and just one page later |
| 32 | // On Windows and Linux default Page size is typically 4Kb |
| 33 | // On macOS default page size is typically 16 Kb |
| 34 | const size_t moreThanOnePageSize = VirtualMemory::getPageSize() + 1024; |
| 35 | const size_t lessThanOnePageSize = VirtualMemory::getPageSize() - 1024; |
| 36 | SC_TEST_EXPECT(lessThanOnePageSize > 0); // sanity check just in case |
| 37 | |
| 38 | void* reference = Memory::allocate(moreThanOnePageSize, 1); |
| 39 | memset(reference, 1, moreThanOnePageSize); |
| 40 | auto releaseLater = MakeDeferred([&] { Memory::release(reference); }); |
| 41 | |
| 42 | VirtualMemory virtualMemory; |
| 43 | |
| 44 | // Reserve 2 pages of virtual memory |
| 45 | SC_TEST_EXPECT(virtualMemory.reserve(2 * VirtualMemory::getPageSize())); |
| 46 | |
| 47 | // Request to use less than one page of virtual memory |
| 48 | SC_TEST_EXPECT(virtualMemory.commit(lessThanOnePageSize)); |
| 49 | char* memory = static_cast<char*>(virtualMemory.data()); |
| 50 | |
| 51 | // Check that memory is writable and fill it with 1 |
| 52 | memset(memory, 1, lessThanOnePageSize); |
| 53 | |
| 54 | // Let's now extend this block from one to two pages |
| 55 | SC_TEST_EXPECT(virtualMemory.commit(moreThanOnePageSize)); |
| 56 | |
| 57 | // Fill the "newly committed" pages with 1 |
| 58 | memset(memory + lessThanOnePageSize, 1, moreThanOnePageSize - lessThanOnePageSize); |
| 59 | |
| 60 | // Make sure that previously reserved address is stable |
| 61 | SC_TEST_EXPECT(memory == virtualMemory.data()); |
| 62 | |
| 63 | // Check that all allocated bytes are addressable and contain expected pattern |
| 64 | SC_TEST_EXPECT(memcmp(memory, reference, moreThanOnePageSize) == 0); |
| 65 | |
| 66 | // Now let's de-commit everything but the first page |
| 67 | SC_TEST_EXPECT(virtualMemory.decommit(lessThanOnePageSize)); |
| 68 | |
| 69 | // Address should stay stable |
| 70 | SC_TEST_EXPECT(memory == virtualMemory.data()); |
| 71 | SC_TEST_EXPECT(memcmp(memory, reference, lessThanOnePageSize) == 0); |
| 72 | |
| 73 | // Decommit everything (not really needed if we're going to release() soon) |
| 74 | SC_TEST_EXPECT(virtualMemory.decommit(0)); |
| 75 | SC_TEST_EXPECT(memory == virtualMemory.data()); |
| 76 | |
| 77 | // Release explicitly when the reservation should be returned before scope exit. |
| 78 | // The VirtualMemory destructor would otherwise release it automatically. |
| 79 | virtualMemory.release(); |
| 80 | SC_TEST_EXPECT(virtualMemory.data() == nullptr); |
| 81 | //! [VirtualMemorySnippet] |
| 82 | } |
| 83 | |
| 84 | namespace SC |
nothing calls this directly
no test coverage detected