/
MemoryAllocator.hpp
61 lines (50 loc) · 1.3 KB
/
MemoryAllocator.hpp
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
#pragma once
#include "pch.h"
#include "MemoryHelper.hpp"
template<typename DataType>
class MemoryAllocator {
private:
DataType AllocatedData;
SIZE_T AllocatedSize;
public:
MemoryAllocator(DataType Data, SIZE_T Size) {
this->AllocatedData = Data;
this->AllocatedSize = Size;
if (Size != 0) {
Data = (DataType)AllocateMemory(Size);
if (Data)
memset(Data, 0, Size);
}
}
MemoryAllocator(DataType* Data, SIZE_T Size) {
this->AllocatedData = nullptr;
this->AllocatedSize = Size;
if (Size != 0) {
*Data = (DataType)AllocateMemory(Size);
if (*Data) {
memset(*Data, 0, Size);
this->AllocatedData = *Data;
}
}
}
~MemoryAllocator() {
if (this->AllocatedData) {
ExFreePoolWithTag(this->AllocatedData, DRIVER_TAG);
this->AllocatedData = nullptr;
}
}
NTSTATUS CopyData(DataType Data, SIZE_T Size) {
SIZE_T bytesWritten = 0;
NTSTATUS status = STATUS_INVALID_PARAMETER;
if (!Data || !this->AllocatedData)
return STATUS_INVALID_BUFFER_SIZE;
if (Size > this->AllocatedSize)
return status;
status = MmCopyVirtualMemory(PsGetCurrentProcess(), Data, PsGetCurrentProcess(), this->AllocatedData, Size,
KernelMode, &bytesWritten);
if (NT_SUCCESS(status)) {
status = bytesWritten == Size ? STATUS_SUCCESS : STATUS_INVALID_BUFFER_SIZE;
}
return status;
}
};