-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory.cpp
92 lines (73 loc) · 1.6 KB
/
memory.cpp
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
#include "syscall.h"
#include <sys/mman.h>
#include <unistd.h>
#include "libsyscall_intercept_hook_point.h"
#include "memory.hpp"
namespace {
uint32_t getPagesize()
{
static long page_size = sysconf(_SC_PAGESIZE);
return page_size;
}
uint32_t convertToMultiplePageSize(uint32_t size)
{
uint32_t page_size = getPagesize();
if (size % page_size) {
uint32_t num_pages = (size / page_size) + 1;
return page_size * num_pages;
} else {
return size;
}
}
}
void *mapMemory(unsigned long length)
{
long res = syscall_no_intercept(SYS_mmap, 0, length, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
void *addr = reinterpret_cast<void *>(res);
return (addr != MAP_FAILED) ? addr : nullptr;
}
bool unmapMemory(void *addr, unsigned long length)
{
long res = syscall_no_intercept(SYS_munmap, addr, length);
return (res == 0);
}
MappedMemory::MappedMemory(uint32_t size)
{
m_length = convertToMultiplePageSize(size);
m_addr = mapMemory(m_length);
}
MappedMemory::~MappedMemory()
{
if (!isEmpty()) {
free();
}
}
uint32_t MappedMemory::getSize() const
{
return m_length;
}
void *MappedMemory::data()
{
return m_addr;
}
const void *MappedMemory::data() const
{
return m_addr;
}
bool MappedMemory::allocate(uint32_t size)
{
if (!isEmpty()) {
free();
}
m_length = convertToMultiplePageSize(size);
m_addr = mapMemory(m_length);
return (m_addr != nullptr);
}
void MappedMemory::free()
{
unmapMemory(m_addr, m_length);
}
bool MappedMemory::isEmpty() const
{
return (m_addr == nullptr);
}