forked from cryfs/cryfs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_windows.cpp
More file actions
50 lines (38 loc) · 1.39 KB
/
memory_windows.cpp
File metadata and controls
50 lines (38 loc) · 1.39 KB
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
#if defined(_MSC_VER)
#include "memory.h"
#include <Windows.h>
#include <stdexcept>
#include <cpp-utils/logging/logging.h>
using namespace cpputils::logging;
namespace cpputils {
void* UnswappableAllocator::allocate(size_t size) {
// VirtualAlloc allocates memory in full pages. This is needed, because VirtualUnlock unlocks full pages
// and might otherwise unlock unrelated memory of other allocations.
// allocate pages
void* data = ::VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (nullptr == data) {
throw std::runtime_error("Error calling VirtualAlloc. Errno: " + std::to_string(GetLastError()));
}
// lock allocated pages into RAM
const BOOL success = ::VirtualLock(data, size);
if (!success) {
throw std::runtime_error("Error calling VirtualLock. Errno: " + std::to_string(GetLastError()));
}
return data;
}
void UnswappableAllocator::free(void* data, size_t size) {
// overwrite the memory with zeroes before we free it
std::memset(data, 0, size);
// unlock allocated pages from RAM
BOOL success = ::VirtualUnlock(data, size);
if (!success) {
throw std::runtime_error("Error calling VirtualUnlock. Errno: " + std::to_string(GetLastError()));
}
// free allocated pages
success = ::VirtualFree(data, 0, MEM_RELEASE);
if (!success) {
throw std::runtime_error("Error calling VirtualFree. Errno: " + std::to_string(GetLastError()));
}
}
}
#endif