-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheprom.cpp
60 lines (47 loc) · 1.38 KB
/
eprom.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
#include <fcntl.h>
#include <stdio.h>
#include <string>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "error.h"
#include "eprom.h"
#include "exceptions.h"
#include "utils.h"
eprom::eprom(std::string file)
{
fd = open(file.c_str(), O_RDWR);
if (fd == -1)
error_exit("cannot open file %s", file.c_str());
struct stat st;
if (fstat(fd, &st) == -1)
error_exit("cannot stat on file %s", file.c_str());
if (st.st_size == 0)
error_exit("file %s is truncted (0 bytes in size)", file.c_str());
len = st.st_size;
pm = (unsigned char *)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (!pm)
error_exit("failed to create mmap on %s", file.c_str());
}
eprom::eprom(std::string file, uint64_t size)
{
fd = open(file.c_str(), O_RDWR | O_CREAT, 0644);
if (fd == -1)
error_exit("cannot open file %s", file.c_str());
if (ftruncate(fd, size) == -1)
error_exit("cannot ftruncate(%lld) on file %s", file.c_str(), size);
len = size;
pm = (unsigned char *)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (!pm)
error_exit("failed to create mmap on %s", file.c_str());
}
eprom::~eprom()
{
if (msync(pm, len, MS_SYNC) == -1)
error_exit("msync on eprom failed");
if (munmap(pm, len) == -1)
error_exit("munmap on eprom failed");
pm = NULL; // because parent destructor also runs delete [] on pm
close(fd);
}