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 "SysUtil.h"
18
19 #include <fcntl.h>
20 #include <stdint.h> // SIZE_MAX
21 #include <sys/mman.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24
25 #include <string>
26 #include <vector>
27
28 #include <android-base/file.h>
29 #include <android-base/logging.h>
30 #include <android-base/strings.h>
31 #include <android-base/unique_fd.h>
32
MapFD(int fd)33 bool MemMapping::MapFD(int fd) {
34 struct stat sb;
35 if (fstat(fd, &sb) == -1) {
36 PLOG(ERROR) << "fstat(" << fd << ") failed";
37 return false;
38 }
39
40 void* memPtr = mmap(nullptr, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
41 if (memPtr == MAP_FAILED) {
42 PLOG(ERROR) << "mmap(" << sb.st_size << ", R, PRIVATE, " << fd << ", 0) failed";
43 return false;
44 }
45
46 addr = static_cast<unsigned char*>(memPtr);
47 length = sb.st_size;
48 ranges_.clear();
49 ranges_.emplace_back(MappedRange{ memPtr, static_cast<size_t>(sb.st_size) });
50
51 return true;
52 }
53
54 // A "block map" which looks like this (from uncrypt/uncrypt.cpp):
55 //
56 // /dev/block/platform/msm_sdcc.1/by-name/userdata # block device
57 // 49652 4096 # file size in bytes, block size
58 // 3 # count of block ranges
59 // 1000 1008 # block range 0
60 // 2100 2102 # ... block range 1
61 // 30 33 # ... block range 2
62 //
63 // Each block range represents a half-open interval; the line "30 33" reprents the blocks
64 // [30, 31, 32].
MapBlockFile(const std::string & filename)65 bool MemMapping::MapBlockFile(const std::string& filename) {
66 std::string content;
67 if (!android::base::ReadFileToString(filename, &content)) {
68 PLOG(ERROR) << "Failed to read " << filename;
69 return false;
70 }
71
72 std::vector<std::string> lines = android::base::Split(android::base::Trim(content), "\n");
73 if (lines.size() < 4) {
74 LOG(ERROR) << "Block map file is too short: " << lines.size();
75 return false;
76 }
77
78 size_t size;
79 size_t blksize;
80 if (sscanf(lines[1].c_str(), "%zu %zu", &size, &blksize) != 2) {
81 LOG(ERROR) << "Failed to parse file size and block size: " << lines[1];
82 return false;
83 }
84
85 size_t range_count;
86 if (sscanf(lines[2].c_str(), "%zu", &range_count) != 1) {
87 LOG(ERROR) << "Failed to parse block map header: " << lines[2];
88 return false;
89 }
90
91 size_t blocks;
92 if (blksize != 0) {
93 blocks = ((size - 1) / blksize) + 1;
94 }
95 if (size == 0 || blksize == 0 || blocks > SIZE_MAX / blksize || range_count == 0 ||
96 lines.size() != 3 + range_count) {
97 LOG(ERROR) << "Invalid data in block map file: size " << size << ", blksize " << blksize
98 << ", range_count " << range_count << ", lines " << lines.size();
99 return false;
100 }
101
102 // Reserve enough contiguous address space for the whole file.
103 void* reserve = mmap64(nullptr, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
104 if (reserve == MAP_FAILED) {
105 PLOG(ERROR) << "failed to reserve address space";
106 return false;
107 }
108
109 const std::string& block_dev = lines[0];
110 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(block_dev.c_str(), O_RDONLY)));
111 if (fd == -1) {
112 PLOG(ERROR) << "failed to open block device " << block_dev;
113 munmap(reserve, blocks * blksize);
114 return false;
115 }
116
117 ranges_.clear();
118
119 unsigned char* next = static_cast<unsigned char*>(reserve);
120 size_t remaining_size = blocks * blksize;
121 bool success = true;
122 for (size_t i = 0; i < range_count; ++i) {
123 const std::string& line = lines[i + 3];
124
125 size_t start, end;
126 if (sscanf(line.c_str(), "%zu %zu\n", &start, &end) != 2) {
127 LOG(ERROR) << "failed to parse range " << i << ": " << line;
128 success = false;
129 break;
130 }
131 size_t range_size = (end - start) * blksize;
132 if (end <= start || (end - start) > SIZE_MAX / blksize || range_size > remaining_size) {
133 LOG(ERROR) << "Invalid range: " << start << " " << end;
134 success = false;
135 break;
136 }
137
138 void* range_start = mmap64(next, range_size, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd,
139 static_cast<off64_t>(start) * blksize);
140 if (range_start == MAP_FAILED) {
141 PLOG(ERROR) << "failed to map range " << i << ": " << line;
142 success = false;
143 break;
144 }
145 ranges_.emplace_back(MappedRange{ range_start, range_size });
146
147 next += range_size;
148 remaining_size -= range_size;
149 }
150 if (success && remaining_size != 0) {
151 LOG(ERROR) << "Invalid ranges: remaining_size " << remaining_size;
152 success = false;
153 }
154 if (!success) {
155 munmap(reserve, blocks * blksize);
156 return false;
157 }
158
159 addr = static_cast<unsigned char*>(reserve);
160 length = size;
161
162 LOG(INFO) << "mmapped " << range_count << " ranges";
163
164 return true;
165 }
166
MapFile(const std::string & fn)167 bool MemMapping::MapFile(const std::string& fn) {
168 if (fn.empty()) {
169 LOG(ERROR) << "Empty filename";
170 return false;
171 }
172
173 if (fn[0] == '@') {
174 // Block map file "@/cache/recovery/block.map".
175 if (!MapBlockFile(fn.substr(1))) {
176 LOG(ERROR) << "Map of '" << fn << "' failed";
177 return false;
178 }
179 } else {
180 // This is a regular file.
181 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY)));
182 if (fd == -1) {
183 PLOG(ERROR) << "Unable to open '" << fn << "'";
184 return false;
185 }
186
187 if (!MapFD(fd)) {
188 LOG(ERROR) << "Map of '" << fn << "' failed";
189 return false;
190 }
191 }
192 return true;
193 }
194
~MemMapping()195 MemMapping::~MemMapping() {
196 for (const auto& range : ranges_) {
197 if (munmap(range.addr, range.length) == -1) {
198 PLOG(ERROR) << "Failed to munmap(" << range.addr << ", " << range.length << ")";
199 }
200 };
201 ranges_.clear();
202 }
203