MCPcopy Create free account
hub / github.com/bailey27/cppcryptfs / LockZeroBuffer

Class LockZeroBuffer

libcppcryptfs/util/LockZeroBuffer.h:41–101  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

39
40template<typename T>
41class LockZeroBuffer
42{
43private:
44 BOOL m_IsLocked;
45public:
46 // disallow copying
47 LockZeroBuffer(LockZeroBuffer const&) = delete;
48 void operator=(LockZeroBuffer const&) = delete;
49
50 BOOL IsLocked() { return m_IsLocked; };
51 T *m_buf;
52 DWORD m_len;
53
54 void Clear()
55 {
56 if (m_buf)
57 SecureZeroMemory(m_buf, sizeof(T)*m_len);
58 }
59
60 LockZeroBuffer(DWORD len, bool throw_if_not_locked)
61 {
62 m_len = len;
63 m_buf = new T[m_len];
64 m_IsLocked = VirtualLock(m_buf, sizeof(T)*m_len);
65 if (!m_IsLocked) {
66 // The amount of memory that can be locked is a little bit less than the
67 // minimum working set size, which defaults to 200KB.
68 //
69 // Attempt to increase the minimum working set size to 1MB
70
71 const SIZE_T desired_min_ws = 1024 * 1024;
72
73 SIZE_T min_ws, max_ws;
74
75 if (GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws, &max_ws)) {
76 if (min_ws < desired_min_ws) {
77 max_ws = max(max_ws, desired_min_ws);
78 if (SetProcessWorkingSetSize(GetCurrentProcess(), desired_min_ws, max_ws)) {
79 m_IsLocked = VirtualLock(m_buf, sizeof(T)*m_len);
80 }
81 }
82 }
83 }
84 if (!m_IsLocked && throw_if_not_locked) {
85 delete[] m_buf;
86 string mes = "LockZeroBuffer: unable to lock buffer of " + to_string(sizeof(T) * m_len) + " bytes";
87 throw std::exception(mes.c_str());
88 }
89 memset(m_buf, 0, sizeof(T)*m_len);
90 }
91
92 virtual ~LockZeroBuffer()
93 {
94 if (m_buf) {
95 Clear();
96 if (m_IsLocked)
97 VirtualUnlock(m_buf, sizeof(T)*m_len);
98 delete[] m_buf;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected