1 /*
2 * Copyright 2006 The Android Open Source Project
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 "otautil/sysutil.h"
18
19 #include <errno.h> // TEMP_FAILURE_RETRY
20 #include <fcntl.h>
21 #include <inttypes.h>
22 #include <sys/mman.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25
26 #include <algorithm>
27 #include <limits>
28 #include <string>
29 #include <vector>
30
31 #include <android-base/file.h>
32 #include <android-base/logging.h>
33 #include <android-base/properties.h>
34 #include <android-base/strings.h>
35 #include <android-base/unique_fd.h>
36 #include <cutils/android_reboot.h>
37
ParseBlockMapFile(const std::string & block_map_path)38 BlockMapData BlockMapData::ParseBlockMapFile(const std::string& block_map_path) {
39 std::string content;
40 if (!android::base::ReadFileToString(block_map_path, &content)) {
41 LOG(ERROR) << "Failed to read " << block_map_path;
42 return {};
43 }
44
45 std::vector<std::string> lines = android::base::Split(android::base::Trim(content), "\n");
46 if (lines.size() < 4) {
47 LOG(ERROR) << "Block map file is too short: " << lines.size();
48 return {};
49 }
50
51 const std::string& block_dev = lines[0];
52
53 uint64_t file_size;
54 uint32_t blksize;
55 if (sscanf(lines[1].c_str(), "%" SCNu64 "%" SCNu32, &file_size, &blksize) != 2) {
56 LOG(ERROR) << "Failed to parse file size and block size: " << lines[1];
57 return {};
58 }
59
60 if (file_size == 0 || blksize == 0) {
61 LOG(ERROR) << "Invalid size in block map file: size " << file_size << ", blksize " << blksize;
62 return {};
63 }
64
65 size_t range_count;
66 if (sscanf(lines[2].c_str(), "%zu", &range_count) != 1) {
67 LOG(ERROR) << "Failed to parse block map header: " << lines[2];
68 return {};
69 }
70
71 uint64_t blocks = ((file_size - 1) / blksize) + 1;
72 if (blocks > std::numeric_limits<uint32_t>::max() || range_count == 0 ||
73 lines.size() != 3 + range_count) {
74 LOG(ERROR) << "Invalid data in block map file: size " << file_size << ", blksize " << blksize
75 << ", range_count " << range_count << ", lines " << lines.size();
76 return {};
77 }
78
79 RangeSet ranges;
80 uint64_t remaining_blocks = blocks;
81 for (size_t i = 0; i < range_count; ++i) {
82 const std::string& line = lines[i + 3];
83 uint64_t start, end;
84 if (sscanf(line.c_str(), "%" SCNu64 "%" SCNu64, &start, &end) != 2) {
85 LOG(ERROR) << "failed to parse range " << i << ": " << line;
86 return {};
87 }
88 uint64_t range_blocks = end - start;
89 if (end <= start || range_blocks > remaining_blocks) {
90 LOG(ERROR) << "Invalid range: " << start << " " << end;
91 return {};
92 }
93 ranges.PushBack({ start, end });
94 remaining_blocks -= range_blocks;
95 }
96
97 return BlockMapData(block_dev, file_size, blksize, std::move(ranges));
98 }
99
MapFD(int fd)100 bool MemMapping::MapFD(int fd) {
101 struct stat sb;
102 if (fstat(fd, &sb) == -1) {
103 PLOG(ERROR) << "fstat(" << fd << ") failed";
104 return false;
105 }
106
107 void* memPtr = mmap(nullptr, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
108 if (memPtr == MAP_FAILED) {
109 PLOG(ERROR) << "mmap(" << sb.st_size << ", R, PRIVATE, " << fd << ", 0) failed";
110 return false;
111 }
112
113 addr = static_cast<unsigned char*>(memPtr);
114 length = sb.st_size;
115 ranges_.clear();
116 ranges_.emplace_back(MappedRange{ memPtr, static_cast<size_t>(sb.st_size) });
117
118 return true;
119 }
120
MapBlockFile(const std::string & filename)121 bool MemMapping::MapBlockFile(const std::string& filename) {
122 auto block_map_data = BlockMapData::ParseBlockMapFile(filename);
123 if (!block_map_data) {
124 return false;
125 }
126
127 if (block_map_data.file_size() > std::numeric_limits<size_t>::max()) {
128 LOG(ERROR) << "File size is too large for mmap " << block_map_data.file_size();
129 return false;
130 }
131
132 // Reserve enough contiguous address space for the whole file.
133 uint32_t blksize = block_map_data.block_size();
134 uint64_t blocks = ((block_map_data.file_size() - 1) / blksize) + 1;
135 void* reserve = mmap(nullptr, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
136 if (reserve == MAP_FAILED) {
137 PLOG(ERROR) << "failed to reserve address space";
138 return false;
139 }
140
141 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(block_map_data.path().c_str(), O_RDONLY)));
142 if (fd == -1) {
143 PLOG(ERROR) << "failed to open block device " << block_map_data.path();
144 munmap(reserve, blocks * blksize);
145 return false;
146 }
147
148 ranges_.clear();
149
150 auto next = static_cast<unsigned char*>(reserve);
151 size_t remaining_size = blocks * blksize;
152 for (const auto& [start, end] : block_map_data.block_ranges()) {
153 size_t range_size = (end - start) * blksize;
154 void* range_start = mmap(next, range_size, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd,
155 static_cast<off_t>(start) * blksize);
156 if (range_start == MAP_FAILED) {
157 PLOG(ERROR) << "failed to map range " << start << ": " << end;
158 munmap(reserve, blocks * blksize);
159 return false;
160 }
161 ranges_.emplace_back(MappedRange{ range_start, range_size });
162
163 next += range_size;
164 remaining_size -= range_size;
165 }
166 if (remaining_size != 0) {
167 LOG(ERROR) << "Invalid ranges: remaining_size " << remaining_size;
168 munmap(reserve, blocks * blksize);
169 return false;
170 }
171
172 addr = static_cast<unsigned char*>(reserve);
173 length = block_map_data.file_size();
174
175 LOG(INFO) << "mmapped " << block_map_data.block_ranges().size() << " ranges";
176
177 return true;
178 }
179
MapFile(const std::string & fn)180 bool MemMapping::MapFile(const std::string& fn) {
181 if (fn.empty()) {
182 LOG(ERROR) << "Empty filename";
183 return false;
184 }
185
186 if (fn[0] == '@') {
187 // Block map file "@/cache/recovery/block.map".
188 if (!MapBlockFile(fn.substr(1))) {
189 LOG(ERROR) << "Map of '" << fn << "' failed";
190 return false;
191 }
192 } else {
193 // This is a regular file.
194 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY)));
195 if (fd == -1) {
196 PLOG(ERROR) << "Unable to open '" << fn << "'";
197 return false;
198 }
199
200 if (!MapFD(fd)) {
201 LOG(ERROR) << "Map of '" << fn << "' failed";
202 return false;
203 }
204 }
205 return true;
206 }
207
~MemMapping()208 MemMapping::~MemMapping() {
209 for (const auto& range : ranges_) {
210 if (munmap(range.addr, range.length) == -1) {
211 PLOG(ERROR) << "Failed to munmap(" << range.addr << ", " << range.length << ")";
212 }
213 };
214 ranges_.clear();
215 }
216
reboot(const std::string & command)217 bool reboot(const std::string& command) {
218 std::string cmd = command;
219 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
220 cmd += ",quiescent";
221 }
222 return android::base::SetProperty(ANDROID_RB_PROPERTY, cmd);
223 }
224
StringVectorToNullTerminatedArray(const std::vector<std::string> & args)225 std::vector<char*> StringVectorToNullTerminatedArray(const std::vector<std::string>& args) {
226 std::vector<char*> result(args.size());
227 std::transform(args.cbegin(), args.cend(), result.begin(),
228 [](const std::string& arg) { return const_cast<char*>(arg.c_str()); });
229 result.push_back(nullptr);
230 return result;
231 }
232