Flutter Engine
The Flutter Engine
mapping_posix.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
5#include "flutter/fml/mapping.h"
6
7#include <fcntl.h>
8#include <sys/mman.h>
9#include <sys/stat.h>
10#include <unistd.h>
11
12#include <type_traits>
13
14#include "flutter/fml/build_config.h"
15#include "flutter/fml/eintr_wrapper.h"
16#include "flutter/fml/unique_fd.h"
17
18namespace fml {
19
21 std::initializer_list<FileMapping::Protection> protection_flags) {
22 int flags = 0;
23 for (auto protection : protection_flags) {
24 switch (protection) {
26 flags |= PROT_READ;
27 break;
29 flags |= PROT_WRITE;
30 break;
32 flags |= PROT_READ | PROT_EXEC;
33 break;
34 }
35 }
36 return flags;
37}
38
39static bool IsWritable(
40 std::initializer_list<FileMapping::Protection> protection_flags) {
41 for (auto protection : protection_flags) {
42 if (protection == FileMapping::Protection::kWrite) {
43 return true;
44 }
45 }
46 return false;
47}
48
49Mapping::Mapping() = default;
50
51Mapping::~Mapping() = default;
52
54 std::initializer_list<Protection> protection) {
55 if (!handle.is_valid()) {
56 return;
57 }
58
59 struct stat stat_buffer = {};
60
61 if (::fstat(handle.get(), &stat_buffer) != 0) {
62 return;
63 }
64
65 if (stat_buffer.st_size == 0) {
66 valid_ = true;
67 return;
68 }
69
70 const auto is_writable = IsWritable(protection);
71
72 auto* mapping =
73 ::mmap(nullptr, stat_buffer.st_size, ToPosixProtectionFlags(protection),
74 is_writable ? MAP_SHARED : MAP_PRIVATE, handle.get(), 0);
75
76 if (mapping == MAP_FAILED) {
77 return;
78 }
79
80 mapping_ = static_cast<uint8_t*>(mapping);
81 size_ = stat_buffer.st_size;
82 valid_ = true;
83 if (is_writable) {
84 mutable_mapping_ = mapping_;
85 }
86}
87
89 if (mapping_ != nullptr) {
90 ::munmap(mapping_, size_);
91 }
92}
93
94size_t FileMapping::GetSize() const {
95 return size_;
96}
97
98const uint8_t* FileMapping::GetMapping() const {
99 return mapping_;
100}
101
103 return mutable_mapping_ == nullptr;
104}
105
107 return valid_;
108}
109
110} // namespace fml
FileMapping(const fml::UniqueFD &fd, std::initializer_list< Protection > protection={ Protection::kRead})
~FileMapping() override
size_t GetSize() const override
bool IsDontNeedSafe() const override
bool IsValid() const
const uint8_t * GetMapping() const override
virtual ~Mapping()
bool is_valid() const
Definition: unique_object.h:89
const T & get() const
Definition: unique_object.h:87
FlutterSemanticsFlag flags
Definition: ascii_trie.cc:9
static bool IsWritable(std::initializer_list< FileMapping::Protection > protection_flags)
static int ToPosixProtectionFlags(std::initializer_list< FileMapping::Protection > protection_flags)