• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "lang_id/common/file/mmap.h"
18 
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <stdint.h>
22 #include <string.h>
23 #ifdef _WIN32
24 #include <winbase.h>
25 #include <windows.h>
26 #else
27 #include <sys/mman.h>
28 #include <unistd.h>
29 #endif
30 #include <sys/stat.h>
31 
32 #include "lang_id/common/lite_base/logging.h"
33 #include "lang_id/common/lite_base/macros.h"
34 
35 namespace libtextclassifier3 {
36 namespace mobile {
37 
38 namespace {
GetErrorMmapHandle()39 inline MmapHandle GetErrorMmapHandle() { return MmapHandle(nullptr, 0); }
40 }  // anonymous namespace
41 
42 #ifdef _WIN32
43 
44 namespace {
GetLastSystemError()45 inline std::string GetLastSystemError() {
46   LPTSTR message_buffer;
47   DWORD error_code = GetLastError();
48   FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
49                     FORMAT_MESSAGE_IGNORE_INSERTS,
50                 NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
51                 (LPTSTR)&message_buffer, 0, NULL);
52   std::string result(message_buffer);
53   LocalFree(message_buffer);
54   return result;
55 }
56 
57 // Class for automatically closing a Win32 HANDLE on exit from a scope.
58 class Win32HandleCloser {
59  public:
Win32HandleCloser(HANDLE handle)60   explicit Win32HandleCloser(HANDLE handle) : handle_(handle) {}
~Win32HandleCloser()61   ~Win32HandleCloser() {
62     bool result = CloseHandle(handle_);
63     if (!result) {
64       const DWORD last_error = GetLastError();
65       SAFTM_LOG(ERROR) << "Error closing handle: " << last_error << ": "
66                        << GetLastSystemError();
67     }
68   }
69 
70  private:
71   const HANDLE handle_;
72 
73   SAFTM_DISALLOW_COPY_AND_ASSIGN(Win32HandleCloser);
74 };
75 }  // namespace
76 
MmapFile(const std::string & filename)77 MmapHandle MmapFile(const std::string &filename) {
78   HANDLE handle =
79       CreateFile(filename.c_str(),  // File to open.
80                  GENERIC_READ,      // Open for reading.
81                  FILE_SHARE_READ,   // Share for reading.
82                  NULL,              // Default security.
83                  OPEN_EXISTING,     // Existing file only.
84                  FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,  // Normal file.
85                  NULL);  // No attr. template.
86   if (handle == INVALID_HANDLE_VALUE) {
87     const std::string last_error = GetLastSystemError();
88     SAFTM_LOG(ERROR) << "Error opening " << filename << ": " << last_error;
89     return GetErrorMmapHandle();
90   }
91 
92   // Make sure we close handle no matter how we exit this function.
93   Win32HandleCloser handle_closer(handle);
94 
95   return MmapFile(handle);
96 }
97 
MmapFile(HANDLE file_handle)98 MmapHandle MmapFile(HANDLE file_handle) {
99   // Get the file size.
100   DWORD file_size_high = 0;
101   DWORD file_size_low = GetFileSize(file_handle, &file_size_high);
102   if (file_size_low == INVALID_FILE_SIZE && GetLastError() != NO_ERROR) {
103     const std::string last_error = GetLastSystemError();
104     SAFTM_LOG(ERROR) << "Unable to stat fd: " << last_error;
105     return GetErrorMmapHandle();
106   }
107   size_t file_size_in_bytes = (static_cast<size_t>(file_size_high) << 32) +
108                               static_cast<size_t>(file_size_low);
109 
110   // Create a file mapping object that refers to the file.
111   HANDLE file_mapping_object =
112       CreateFileMappingA(file_handle, nullptr, PAGE_READONLY, 0, 0, nullptr);
113   if (file_mapping_object == NULL) {
114     const std::string last_error = GetLastSystemError();
115     SAFTM_LOG(ERROR) << "Error while mmapping: " << last_error;
116     return GetErrorMmapHandle();
117   }
118   Win32HandleCloser handle_closer(file_mapping_object);
119 
120   // Map the file mapping object into memory.
121   void *mmap_addr =
122       MapViewOfFile(file_mapping_object, FILE_MAP_READ, 0, 0,  // File offset.
123                     0  // Number of bytes to map; 0 means map the whole file.
124       );
125   if (mmap_addr == nullptr) {
126     const std::string last_error = GetLastSystemError();
127     SAFTM_LOG(ERROR) << "Error while mmapping: " << last_error;
128     return GetErrorMmapHandle();
129   }
130 
131   return MmapHandle(mmap_addr, file_size_in_bytes);
132 }
133 
Unmap(MmapHandle mmap_handle)134 bool Unmap(MmapHandle mmap_handle) {
135   if (!mmap_handle.ok()) {
136     // Unmapping something that hasn't been mapped is trivially successful.
137     return true;
138   }
139   bool succeeded = UnmapViewOfFile(mmap_handle.start());
140   if (!succeeded) {
141     const std::string last_error = GetLastSystemError();
142     SAFTM_LOG(ERROR) << "Error during Unmap / UnmapViewOfFile: " << last_error;
143     return false;
144   }
145   return true;
146 }
147 
148 #else
149 
150 namespace {
GetLastSystemError()151 inline std::string GetLastSystemError() { return std::string(strerror(errno)); }
152 
153 class FileCloser {
154  public:
FileCloser(int fd)155   explicit FileCloser(int fd) : fd_(fd) {}
~FileCloser()156   ~FileCloser() {
157     int result = close(fd_);
158     if (result != 0) {
159       const std::string last_error = GetLastSystemError();
160       SAFTM_LOG(ERROR) << "Error closing file descriptor: " << last_error;
161     }
162   }
163 
164  private:
165   const int fd_;
166 
167   SAFTM_DISALLOW_COPY_AND_ASSIGN(FileCloser);
168 };
169 }  // namespace
170 
MmapFile(const std::string & filename)171 MmapHandle MmapFile(const std::string &filename) {
172   int fd = open(filename.c_str(), O_RDONLY);
173 
174   if (fd < 0) {
175     const std::string last_error = GetLastSystemError();
176     SAFTM_LOG(ERROR) << "Error opening " << filename << ": " << last_error;
177     return GetErrorMmapHandle();
178   }
179 
180   // Make sure we close fd no matter how we exit this function.  As the man page
181   // for mmap clearly states: "closing the file descriptor does not unmap the
182   // region."  Hence, we can close fd as soon as we return from here.
183   FileCloser file_closer(fd);
184 
185   return MmapFile(fd);
186 }
187 
MmapFile(int fd)188 MmapHandle MmapFile(int fd) {
189   // Get file stats to obtain file size.
190   struct stat sb;
191   if (fstat(fd, &sb) != 0) {
192     const std::string last_error = GetLastSystemError();
193     SAFTM_LOG(ERROR) << "Unable to stat fd: " << last_error;
194     return GetErrorMmapHandle();
195   }
196   size_t file_size_in_bytes = static_cast<size_t>(sb.st_size);
197 
198   // Perform actual mmap.
199   return MmapFile(fd, /*offset_in_bytes=*/0, file_size_in_bytes);
200 }
201 
MmapFile(int fd,size_t offset_in_bytes,size_t size_in_bytes)202 MmapHandle MmapFile(int fd, size_t offset_in_bytes, size_t size_in_bytes) {
203   // Make sure the offset is a multiple of the page size, as returned by
204   // sysconf(_SC_PAGE_SIZE); this is required by the man-page for mmap.
205   static const size_t kPageSize = sysconf(_SC_PAGE_SIZE);
206   const size_t aligned_offset = (offset_in_bytes / kPageSize) * kPageSize;
207   const size_t alignment_shift = offset_in_bytes - aligned_offset;
208   const size_t aligned_length = size_in_bytes + alignment_shift;
209 
210   void *mmap_addr = mmap(
211 
212       // Let system pick address for mmapp-ed data.
213       nullptr,
214 
215       aligned_length,
216 
217       // One can read / write the mapped data (but see MAP_PRIVATE below).
218       // Normally, we expect only to read it, but in the future, we may want to
219       // write it, to fix e.g., endianness differences.
220       PROT_READ | PROT_WRITE,
221 
222       // Updates to mmaped data are *not* propagated to actual file.
223       // AFAIK(salcianu) that's anyway not possible on Android.
224       MAP_PRIVATE,
225 
226       // Descriptor of file to mmap.
227       fd,
228 
229       aligned_offset);
230   if (mmap_addr == MAP_FAILED) {
231     const std::string last_error = GetLastSystemError();
232     SAFTM_LOG(ERROR) << "Error while mmapping: " << last_error;
233     return GetErrorMmapHandle();
234   }
235 
236   return MmapHandle(static_cast<char *>(mmap_addr) + alignment_shift,
237                     size_in_bytes);
238 }
239 
Unmap(MmapHandle mmap_handle)240 bool Unmap(MmapHandle mmap_handle) {
241   if (!mmap_handle.ok()) {
242     // Unmapping something that hasn't been mapped is trivially successful.
243     return true;
244   }
245   if (munmap(mmap_handle.start(), mmap_handle.num_bytes()) != 0) {
246     const std::string last_error = GetLastSystemError();
247     SAFTM_LOG(ERROR) << "Error during Unmap / munmap: " << last_error;
248     return false;
249   }
250   return true;
251 }
252 
253 #endif
254 
255 }  // namespace mobile
256 }  // namespace nlp_saft
257