Itoyori  v0.0.1
file_mem.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <fcntl.h>
4 #include <sys/stat.h>
5 
6 #include "ityr/common/util.hpp"
8 #include "ityr/ori/util.hpp"
9 
10 namespace ityr::ori {
11 
12 class file_mem {
13 public:
14  file_mem() {}
15 
16  explicit file_mem(const std::string& fpath)
17  : fd_(file_open(fpath)),
18  size_(file_size(fd_)) {}
19 
20  ~file_mem() { destroy(); }
21 
22  file_mem(const file_mem&) = delete;
23  file_mem& operator=(const file_mem&) = delete;
24 
26  : fd_(fm.fd_), size_(fm.size_) { fm.fd_ = -1; }
28  destroy();
29  fd_ = fm.fd_;
30  size_ = fm.size_;
31  fm.fd_ = -1;
32  return *this;
33  }
34 
35  std::size_t size() const { return size_; }
36 
37  void map_to_vm(void* addr, std::size_t size, std::size_t offset) const {
38  ITYR_CHECK(addr != nullptr);
39  ITYR_CHECK(reinterpret_cast<uintptr_t>(addr) % common::get_page_size() == 0);
40  ITYR_CHECK(offset % common::get_page_size() == 0);
41  ITYR_CHECK(offset + size <= size_);
42 
43  void* ret = mmap(addr, size, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd_, offset);
44  if (ret == MAP_FAILED) {
45  perror("mmap");
46  common::die("[ityr::ori::file_mem] mmap(%p, %lu, ...) failed", addr, size);
47  }
48  }
49 
50 private:
51  void destroy() {
52  if (fd_ != -1) {
53  file_close(fd_);
54  }
55  }
56 
57  static int file_open(const std::string& fpath) {
58  int fd = open(fpath.c_str(), O_RDONLY);
59  if (fd == -1) {
60  perror("open");
61  common::die("[ityr::ori::file_mem] open() failed");
62  }
63  return fd;
64  }
65 
66  static void file_close(int fd) {
67  if (close(fd) == -1) {
68  perror("close");
69  common::die("[ityr::ori::file_mem] close() failed");
70  }
71  }
72 
73  static std::size_t file_size(int fd) {
74  struct stat sb;
75  if (fstat(fd, &sb) == -1) {
76  perror("fstat");
77  abort();
78  }
79  return sb.st_size;
80  }
81 
82  int fd_ = -1;
83  std::size_t size_;
84 };
85 
86 }
Definition: file_mem.hpp:12
void map_to_vm(void *addr, std::size_t size, std::size_t offset) const
Definition: file_mem.hpp:37
file_mem(const file_mem &)=delete
file_mem & operator=(const file_mem &)=delete
file_mem & operator=(file_mem &&fm)
Definition: file_mem.hpp:27
file_mem(const std::string &fpath)
Definition: file_mem.hpp:16
file_mem()
Definition: file_mem.hpp:14
~file_mem()
Definition: file_mem.hpp:20
std::size_t size() const
Definition: file_mem.hpp:35
file_mem(file_mem &&fm)
Definition: file_mem.hpp:25
#define ITYR_CHECK(cond)
Definition: util.hpp:48
std::size_t get_page_size()
Definition: util.hpp:170
Definition: block_region_set.hpp:9