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     PLOG(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   if (remaining_blocks != 0) {
98     LOG(ERROR) << "Invalid ranges: remaining blocks " << remaining_blocks;
99     return {};
100   }
101 
102   return BlockMapData(block_dev, file_size, blksize, std::move(ranges));
103 }
104 
MapFD(int fd)105 bool MemMapping::MapFD(int fd) {
106   struct stat sb;
107   if (fstat(fd, &sb) == -1) {
108     PLOG(ERROR) << "fstat(" << fd << ") failed";
109     return false;
110   }
111 
112   void* memPtr = mmap(nullptr, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
113   if (memPtr == MAP_FAILED) {
114     PLOG(ERROR) << "mmap(" << sb.st_size << ", R, PRIVATE, " << fd << ", 0) failed";
115     return false;
116   }
117 
118   addr = static_cast<unsigned char*>(memPtr);
119   length = sb.st_size;
120   ranges_.clear();
121   ranges_.emplace_back(MappedRange{ memPtr, static_cast<size_t>(sb.st_size) });
122 
123   return true;
124 }
125 
MapBlockFile(const std::string & filename)126 bool MemMapping::MapBlockFile(const std::string& filename) {
127   auto block_map_data = BlockMapData::ParseBlockMapFile(filename);
128   if (!block_map_data) {
129     return false;
130   }
131 
132   if (block_map_data.file_size() > std::numeric_limits<size_t>::max()) {
133     LOG(ERROR) << "File size is too large for mmap " << block_map_data.file_size();
134     return false;
135   }
136 
137   // Reserve enough contiguous address space for the whole file.
138   uint32_t blksize = block_map_data.block_size();
139   uint64_t blocks = ((block_map_data.file_size() - 1) / blksize) + 1;
140   void* reserve = mmap(nullptr, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
141   if (reserve == MAP_FAILED) {
142     PLOG(ERROR) << "failed to reserve address space";
143     return false;
144   }
145 
146   android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(block_map_data.path().c_str(), O_RDONLY)));
147   if (fd == -1) {
148     PLOG(ERROR) << "failed to open block device " << block_map_data.path();
149     munmap(reserve, blocks * blksize);
150     return false;
151   }
152 
153   ranges_.clear();
154 
155   auto next = static_cast<unsigned char*>(reserve);
156   size_t remaining_size = blocks * blksize;
157   for (const auto& [start, end] : block_map_data.block_ranges()) {
158     size_t range_size = (end - start) * blksize;
159     void* range_start = mmap(next, range_size, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd,
160                              static_cast<off_t>(start) * blksize);
161     if (range_start == MAP_FAILED) {
162       PLOG(ERROR) << "failed to map range " << start << ": " << end;
163       munmap(reserve, blocks * blksize);
164       return false;
165     }
166     ranges_.emplace_back(MappedRange{ range_start, range_size });
167 
168     next += range_size;
169     remaining_size -= range_size;
170   }
171   if (remaining_size != 0) {
172     LOG(ERROR) << "Invalid ranges: remaining_size " << remaining_size;
173     munmap(reserve, blocks * blksize);
174     return false;
175   }
176 
177   addr = static_cast<unsigned char*>(reserve);
178   length = block_map_data.file_size();
179 
180   LOG(INFO) << "mmapped " << block_map_data.block_ranges().size() << " ranges";
181 
182   return true;
183 }
184 
MapFile(const std::string & fn)185 bool MemMapping::MapFile(const std::string& fn) {
186   if (fn.empty()) {
187     LOG(ERROR) << "Empty filename";
188     return false;
189   }
190 
191   if (fn[0] == '@') {
192     // Block map file "@/cache/recovery/block.map".
193     if (!MapBlockFile(fn.substr(1))) {
194       LOG(ERROR) << "Map of '" << fn << "' failed";
195       return false;
196     }
197   } else {
198     // This is a regular file.
199     android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY)));
200     if (fd == -1) {
201       PLOG(ERROR) << "Unable to open '" << fn << "'";
202       return false;
203     }
204 
205     if (!MapFD(fd)) {
206       LOG(ERROR) << "Map of '" << fn << "' failed";
207       return false;
208     }
209   }
210   return true;
211 }
212 
~MemMapping()213 MemMapping::~MemMapping() {
214   for (const auto& range : ranges_) {
215     if (munmap(range.addr, range.length) == -1) {
216       PLOG(ERROR) << "Failed to munmap(" << range.addr << ", " << range.length << ")";
217     }
218   };
219   ranges_.clear();
220 }
221 
Reboot(std::string_view target)222 void Reboot(std::string_view target) {
223   std::string cmd = "reboot," + std::string(target);
224   // Honor the quiescent mode if applicable.
225   if (target != "bootloader" && target != "fastboot" &&
226       android::base::GetBoolProperty("ro.boot.quiescent", false)) {
227     cmd += ",quiescent";
228   }
229   if (!android::base::SetProperty(ANDROID_RB_PROPERTY, cmd)) {
230     LOG(FATAL) << "Reboot failed";
231   }
232 
233   while (true) pause();
234 }
235 
Shutdown(std::string_view target)236 bool Shutdown(std::string_view target) {
237   std::string cmd = "shutdown," + std::string(target);
238   return android::base::SetProperty(ANDROID_RB_PROPERTY, cmd);
239 }
240 
StringVectorToNullTerminatedArray(const std::vector<std::string> & args)241 std::vector<char*> StringVectorToNullTerminatedArray(const std::vector<std::string>& args) {
242   std::vector<char*> result(args.size());
243   std::transform(args.cbegin(), args.cend(), result.begin(),
244                  [](const std::string& arg) { return const_cast<char*>(arg.c_str()); });
245   result.push_back(nullptr);
246   return result;
247 }
248