Imported Upstream version 1.4.0
[platform/core/ml/nnfw.git] / compiler / tfl-verify / src / Model.cpp
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
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 "Model.h"
18
19 #include <cwrap/Fildes.h>
20
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <sys/stat.h>
24 #include <sys/mman.h>
25
26 namespace
27 {
28
29 class MemoryMappedModel final : public ModelData
30 {
31 public:
32   /**
33    * @require fd and data SHOULD be valid
34    */
35   explicit MemoryMappedModel(int fd, void *data, size_t size) : _fd{fd}, _data{data}, _size{size}
36   {
37     // DO NOTHING
38   }
39
40 public:
41   ~MemoryMappedModel()
42   {
43     munmap(_data, _size);
44     close(_fd);
45   }
46
47 public:
48   MemoryMappedModel(const MemoryMappedModel &) = delete;
49   MemoryMappedModel(MemoryMappedModel &&) = delete;
50
51 public:
52   const void *data(void) const override { return _data; };
53   const size_t size(void) const override { return _size; };
54
55 private:
56   int _fd = -1;
57   void *_data = nullptr;
58   size_t _size = 0;
59 };
60
61 } // namespace
62
63 std::unique_ptr<ModelData> load_modeldata(const std::string &path)
64 {
65   cwrap::Fildes fd(open(path.c_str(), O_RDONLY));
66
67   if (fd.get() == -1)
68   {
69     // Return nullptr on open failure
70     return nullptr;
71   }
72
73   struct stat st;
74   if (fstat(fd.get(), &st) == -1)
75   {
76     // Return nullptr on fstat failure
77     return nullptr;
78   }
79
80   auto size = st.st_size;
81   auto data = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd.get(), 0);
82
83   if (data == MAP_FAILED)
84   {
85     // Return nullptr on mmap failure
86     return nullptr;
87   }
88
89   return std::unique_ptr<ModelData>{new MemoryMappedModel(fd.release(), data, size)};
90 }