LedBars/RpiLedBars/src/smi/VitualMemory.cpp
2021-07-24 00:09:43 +01:00

37 lines
765 B
C++

#include "VitualMemory.hpp"
#include <stdexcept>
#include "utils.h"
#include <fcntl.h>
// #include <sys/ioctl.h>
#include <stdint.h>
#include <sys/mman.h>
#include <unistd.h>
VitualMemory::VitualMemory(void *addr, int size) {
int fd;
roundSize = PAGE_ROUNDUP(size);
if ((fd = open("/dev/mem", O_RDWR | O_SYNC | O_CLOEXEC)) < 0) {
throw std::runtime_error("Error: can't open /dev/mem, run using sudo");
}
mem = mmap(0, roundSize, PROT_WRITE | PROT_READ, MAP_SHARED, fd, (uint32_t)addr);
close(fd);
#if _DEBUG
printf("Map %p -> %p\n", (void *)addr, mem);
#endif // _DEBUG
if (mem == MAP_FAILED) {
throw std::runtime_error("Error: can't map memory");
}
}
VitualMemory::~VitualMemory() {
if (mem) {
munmap(mem, roundSize);
}
}