Flutter Engine
 
Loading...
Searching...
No Matches
mmap_file.cc
Go to the documentation of this file.
1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
6
7#include <fcntl.h>
8#include <sys/mman.h>
9#include <sys/stat.h>
10
11#include "third_party/abseil-cpp/absl/strings/str_cat.h"
12
13absl::StatusOr<MMapFile> MMapFile::Make(std::string_view path) {
14 int fd = open(path.data(), O_RDONLY);
15 if (fd < 0) {
16 return absl::UnavailableError("can't open file");
17 }
18
19 struct stat st;
20 if (fstat(fd, &st) < 0) {
21 close(fd);
22 return absl::UnavailableError("can't stat file");
23 }
24
25 if (st.st_size <= 0) {
26 close(fd);
27 return absl::InvalidArgumentError("file of zero length");
28 }
29
30 const char* data = static_cast<const char*>(
31 mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0));
32
33 if (data == MAP_FAILED) {
34 close(fd);
35 return absl::UnavailableError(
36 absl::StrCat("can't mmap file (", path, "): ", std::strerror(errno)));
37 }
38
39 return MMapFile(fd, data, st.st_size);
40}
41
43 if (data_) {
44 munmap(const_cast<char*>(data_), size_);
45 }
46 if (fd_ >= 0) {
47 close(fd_);
48 }
49}
50
52 fd_ = other.fd_;
53 data_ = other.data_;
54 size_ = other.size_;
55 other.fd_ = -1;
56 other.data_ = nullptr;
57 other.size_ = 0;
58}
59
60MMapFile::MMapFile(int fd, const char* data, size_t size)
61 : fd_(fd), data_(data), size_(size) {}
A memory mapped file.
Definition mmap_file.h:12
static absl::StatusOr< MMapFile > Make(std::string_view path)
Definition mmap_file.cc:13
MMapFile(const MMapFile &)=delete
std::shared_ptr< const fml::Mapping > data