2 * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
27 class MemoryMappedModel final : public tflinspect::Model
31 * @require fd and data SHOULD be valid
33 explicit MemoryMappedModel(int fd, void *data, size_t size) : _fd{fd}, _data{data}, _size{size}
46 MemoryMappedModel(const MemoryMappedModel &) = delete;
47 MemoryMappedModel(MemoryMappedModel &&) = delete;
50 const ::tflite::Model *model(void) const override { return ::tflite::GetModel(_data); }
54 void *_data = nullptr;
58 class FileDescriptor final
61 FileDescriptor(int value) : _value{value}
67 // NOTE Copy is not allowed
68 FileDescriptor(const FileDescriptor &) = delete;
71 // NOTE Move is allowed
72 FileDescriptor(FileDescriptor &&fd) { _value = fd.release(); }
79 // Close on descturction
85 int value(void) const { return _value; }
104 std::unique_ptr<Model> load_tflite(const std::string &path)
106 FileDescriptor fd = open(path.c_str(), O_RDONLY);
108 if (fd.value() == -1)
110 // Return nullptr on open failure
115 if (fstat(fd.value(), &st) == -1)
117 // Return nullptr on fstat failure
121 auto size = st.st_size;
122 auto data = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd.value(), 0);
124 if (data == MAP_FAILED)
126 // Return nullptr on mmap failure
130 // Check if file is a valid Flatbuffer file
131 const uint8_t *u8data = reinterpret_cast<const uint8_t *>(data);
132 flatbuffers::Verifier verifier{u8data, static_cast<size_t>(size)};
133 if (!tflite::VerifyModelBuffer(verifier))
140 return std::unique_ptr<tflinspect::Model>{new MemoryMappedModel(fd.release(), data, size)};
143 } // namespace tflinspect