Addition of Remapping and Unmapping to Memory class

This commit is contained in:
◱ PixelyIon 2019-08-18 03:48:27 +05:30
parent 92c1491a84
commit 449f0a0248
2 changed files with 25 additions and 9 deletions

View File

@ -1,23 +1,34 @@
#include <sys/mman.h> #include <sys/mman.h>
#include <syslog.h> #include <cerrno>
#include <vector>
#include "memory.h" #include "memory.h"
#include "../constant.h" #include "../constant.h"
namespace lightSwitch::hw { namespace lightSwitch::hw {
// TODO: Boundary checks
Memory::Memory() { Memory::Memory() {
// Map stack memory
// Memory::Map(constant::stack_addr, constant::stack_size, stack);
// Map TLS memory // Map TLS memory
Memory::Map(constant::tls_addr, constant::tls_size, tls); Memory::Map(constant::tls_addr, constant::tls_size, tls);
} }
void Memory::Map(uint64_t address, size_t size, Region region) { void Memory::Map(uint64_t address, size_t size, Region region) {
region_map.insert(std::pair<Region, RegionData>(region, {address, size}));
void *ptr = mmap((void *) address, size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON | MAP_FIXED, 0, 0); void *ptr = mmap((void *) address, size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON | MAP_FIXED, 0, 0);
if (!ptr) if (ptr == MAP_FAILED)
throw exception("An occurred while mapping region"); throw exception("An occurred while mapping region at " + std::to_string(address));
region_map.insert(std::pair<Region, RegionData>(region, {address, size}));
}
void Memory::Remap(Region region, size_t size) {
RegionData region_data = region_map.at(region);
void *ptr = mremap((void *) region_data.address, region_data.size, size, 0);
if (ptr == MAP_FAILED)
throw exception("An occurred while unmapping region: " + std::string(strerror(errno)));
region_map[region].size = size;
}
void Memory::Unmap(Region region) {
RegionData region_data = region_map.at(region);
int err = munmap((void *) region_data.address, region_data.size);
if (err == -1)
throw exception("An occurred while unmapping region: " + std::string(strerror(errno)));
} }
void Memory::Write(void *data, uint64_t offset, size_t size) { void Memory::Write(void *data, uint64_t offset, size_t size) {

View File

@ -1,5 +1,6 @@
#pragma once #pragma once
#include "../constant.h"
#include <string> #include <string>
#include <map> #include <map>
@ -7,7 +8,7 @@ namespace lightSwitch::hw {
class Memory { class Memory {
public: public:
enum Region { enum Region {
stack, tls, text, rodata, data, bss heap, tls, text, rodata, data, bss
}; };
struct RegionData { struct RegionData {
uint64_t address; uint64_t address;
@ -19,6 +20,10 @@ namespace lightSwitch::hw {
void Map(uint64_t address, size_t size, Region region); void Map(uint64_t address, size_t size, Region region);
void Remap(Region region, size_t size);
void Unmap(Region region);
void Write(void *data, uint64_t offset, size_t size); void Write(void *data, uint64_t offset, size_t size);
template<typename T> template<typename T>