xref: /aosp_15_r20/external/executorch/examples/mediatek/executor_runner/llama_runner/FileMemMapper.h (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1 /*
2  * Copyright (c) 2024 MediaTek Inc.
3  *
4  * Licensed under the BSD License (the "License"); you may not use this file
5  * except in compliance with the License. See the license file in the root
6  * directory of this source tree for more details.
7  */
8 
9 #include <executorch/runtime/platform/log.h>
10 
11 #include <string>
12 
13 #include <fcntl.h>
14 #include <sys/mman.h>
15 #include <sys/stat.h>
16 #include <unistd.h>
17 
18 namespace example {
19 
20 class FileMemMapper { // Read-only mmap
21  public:
FileMemMapper(const std::string & path)22   explicit FileMemMapper(const std::string& path) {
23     // Get fd
24     mFd = open(path.c_str(), O_RDONLY);
25     if (mFd == -1) {
26       ET_LOG(Error, "Open file fail: %s", path.c_str());
27       return;
28     }
29 
30     // Get size
31     struct stat sb;
32     if (fstat(mFd, &sb) == -1) {
33       ET_LOG(Error, "fstat fail");
34       return;
35     }
36     mSize = sb.st_size;
37 
38     // Map file data to memory
39     mBuffer = mmap(NULL, mSize, PROT_READ, MAP_SHARED, mFd, 0);
40     if (mBuffer == MAP_FAILED) {
41       ET_LOG(Error, "mmap fail");
42       return;
43     }
44 
45     ET_LOG(
46         Debug,
47         "FileMemMapper: Mapped to (fd=%d, size=%zu, addr=%p): %s",
48         mFd,
49         mSize,
50         mBuffer,
51         path.c_str());
52   }
53 
54   // Move ctor
FileMemMapper(FileMemMapper && other)55   explicit FileMemMapper(FileMemMapper&& other)
56       : mFd(other.mFd), mBuffer(other.mBuffer), mSize(other.mSize) {
57     other.mFd = -1;
58     other.mBuffer = nullptr;
59     other.mSize = 0;
60   }
61 
~FileMemMapper()62   ~FileMemMapper() {
63     if (!mBuffer && mFd == -1) {
64       return;
65     }
66 
67     ET_LOG(
68         Debug,
69         "FileMemMapper: Unmapping (fd=%d, size=%zu, addr=%p)",
70         mFd,
71         mSize,
72         mBuffer);
73 
74     if (mBuffer && munmap(mBuffer, mSize) == -1) {
75       ET_LOG(Error, "munmap fail");
76       return;
77     }
78 
79     if (mFd != -1 && close(mFd) == -1) {
80       ET_LOG(Error, "close fail");
81       return;
82     }
83   }
84 
85   template <typename T = void*>
getAddr()86   T getAddr() const {
87     return reinterpret_cast<T>(mBuffer);
88   }
89 
getSize()90   size_t getSize() const {
91     return mSize;
92   }
93 
94  private:
95   int mFd = -1;
96   void* mBuffer = nullptr;
97   size_t mSize = 0;
98 };
99 
100 } // namespace example
101