1 /**
2 * Copyright 2023 Huawei Technologies Co., Ltd
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 "src/common/mmap_utils.h"
18 #include "src/common/file_utils.h"
19 #if !defined(_WIN32) && !defined(_WIN64)
20 #include <sys/mman.h>
21 #include <fcntl.h>
22 #include <sys/stat.h>
23 #endif
24
25 namespace mindspore {
26 namespace lite {
ReadFileByMmap(const std::string & file,size_t * size,bool populate)27 void *ReadFileByMmap(const std::string &file, size_t *size, bool populate) {
28 #if !defined(_WIN32) && !defined(_WIN64) && !defined(MS_COMPILE_IOS)
29 auto real_path = RealPath(file.c_str());
30 MS_CHECK_TRUE_RET(!real_path.empty(), nullptr);
31 auto fd = open(real_path.c_str(), O_RDONLY);
32 if (fd == -1) {
33 MS_LOG(ERROR) << "Could not open " << file;
34 return nullptr;
35 }
36 struct stat fd_stat;
37 if (fstat(fd, &fd_stat) != 0) {
38 MS_LOG(ERROR) << "Get fd stat error.";
39 (void)close(fd);
40 return nullptr;
41 }
42 *size = static_cast<size_t>(fd_stat.st_size);
43 void *mmap_buffers;
44 if (populate) {
45 mmap_buffers = mmap(nullptr, *size, PROT_READ, MAP_SHARED | MAP_POPULATE, fd, 0);
46 } else {
47 mmap_buffers = mmap(nullptr, *size, PROT_READ, MAP_SHARED, fd, 0);
48 }
49 (void)close(fd);
50 if (mmap_buffers == MAP_FAILED) {
51 MS_LOG(ERROR) << "Model mmap failed.";
52 return nullptr;
53 }
54 return mmap_buffers;
55 #else
56 MS_LOG(ERROR) << "Mmap is unsupported on windows.";
57 return nullptr;
58 #endif
59 }
60
UnmapMmapBuffer(void * buffer,size_t size)61 void UnmapMmapBuffer(void *buffer, size_t size) {
62 #if !defined(_WIN32) && !defined(_WIN64)
63 auto ret = munmap(buffer, size);
64 if (ret != RET_OK) {
65 MS_LOG(ERROR) << "munmap failed ret: " << ret << ", err: " << strerror(errno);
66 }
67 #else
68 MS_LOG(ERROR) << "Mmap is unsupported on windows.";
69 #endif
70 }
71 } // namespace lite
72 } // namespace mindspore
73