• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 "updater/target_files.h"
18 
19 #include <unistd.h>
20 
21 #include <algorithm>
22 #include <filesystem>
23 #include <memory>
24 
25 #include <android-base/logging.h>
26 #include <android-base/strings.h>
27 #include <sparse/sparse.h>
28 
SimgToImg(int input_fd,int output_fd)29 static bool SimgToImg(int input_fd, int output_fd) {
30   if (lseek64(input_fd, 0, SEEK_SET) == -1) {
31     PLOG(ERROR) << "Failed to lseek64 on the input sparse image";
32     return false;
33   }
34 
35   if (lseek64(output_fd, 0, SEEK_SET) == -1) {
36     PLOG(ERROR) << "Failed to lseek64 on the output raw image";
37     return false;
38   }
39 
40   std::unique_ptr<sparse_file, decltype(&sparse_file_destroy)> s_file(
41       sparse_file_import(input_fd, true, false), sparse_file_destroy);
42   if (!s_file) {
43     LOG(ERROR) << "Failed to import the sparse image.";
44     return false;
45   }
46 
47   if (sparse_file_write(s_file.get(), output_fd, false, false, false) < 0) {
48     PLOG(ERROR) << "Failed to output the raw image file.";
49     return false;
50   }
51 
52   return true;
53 }
54 
ParsePropertyFile(const std::string_view prop_content,std::map<std::string,std::string,std::less<>> * props_map)55 static bool ParsePropertyFile(const std::string_view prop_content,
56                               std::map<std::string, std::string, std::less<>>* props_map) {
57   LOG(INFO) << "Start parsing build property\n";
58   std::vector<std::string> lines = android::base::Split(std::string(prop_content), "\n");
59   for (const auto& line : lines) {
60     if (line.empty() || line[0] == '#') continue;
61     auto pos = line.find('=');
62     if (pos == std::string::npos) continue;
63     std::string key = line.substr(0, pos);
64     std::string value = line.substr(pos + 1);
65     LOG(INFO) << key << ": " << value;
66     props_map->emplace(key, value);
67   }
68 
69   return true;
70 }
71 
ParseFstab(const std::string_view fstab,std::vector<FstabInfo> * fstab_info_list)72 static bool ParseFstab(const std::string_view fstab, std::vector<FstabInfo>* fstab_info_list) {
73   LOG(INFO) << "parsing fstab\n";
74   std::vector<std::string> lines = android::base::Split(std::string(fstab), "\n");
75   for (const auto& line : lines) {
76     if (line.empty() || line[0] == '#') continue;
77 
78     // <block_device>  <mount_point>  <fs_type>  <mount_flags>  optional:<fs_mgr_flags>
79     std::vector<std::string> tokens = android::base::Split(line, " ");
80     tokens.erase(std::remove(tokens.begin(), tokens.end(), ""), tokens.end());
81     if (tokens.size() != 4 && tokens.size() != 5) {
82       LOG(ERROR) << "Unexpected token size: " << tokens.size() << std::endl
83                  << "Error parsing fstab line: " << line;
84       return false;
85     }
86 
87     const auto& blockdev = tokens[0];
88     const auto& mount_point = tokens[1];
89     const auto& fs_type = tokens[2];
90     if (!android::base::StartsWith(mount_point, "/")) {
91       LOG(WARNING) << "mount point '" << mount_point << "' does not start with '/'";
92       continue;
93     }
94 
95     // The simulator only supports ext4 and emmc for now.
96     if (fs_type != "ext4" && fs_type != "emmc") {
97       LOG(WARNING) << "Unsupported fs_type in " << line;
98       continue;
99     }
100 
101     fstab_info_list->emplace_back(blockdev, mount_point, fs_type);
102   }
103 
104   return true;
105 }
106 
EntryExists(const std::string_view name) const107 bool TargetFile::EntryExists(const std::string_view name) const {
108   if (extracted_input_) {
109     std::string entry_path = path_ + "/" + std::string(name);
110     if (access(entry_path.c_str(), O_RDONLY) != 0) {
111       PLOG(WARNING) << "Failed to access " << entry_path;
112       return false;
113     }
114     return true;
115   }
116 
117   CHECK(handle_);
118   ZipEntry64 img_entry;
119   return FindEntry(handle_, name, &img_entry) == 0;
120 }
121 
ReadEntryToString(const std::string_view name,std::string * content) const122 bool TargetFile::ReadEntryToString(const std::string_view name, std::string* content) const {
123   if (extracted_input_) {
124     std::string entry_path = path_ + "/" + std::string(name);
125     return android::base::ReadFileToString(entry_path, content);
126   }
127 
128   CHECK(handle_);
129   ZipEntry64 entry;
130   if (auto find_err = FindEntry(handle_, name, &entry); find_err != 0) {
131     LOG(ERROR) << "failed to find " << name << " in the package: " << ErrorCodeString(find_err);
132     return false;
133   }
134 
135   if (entry.uncompressed_length == 0) {
136     content->clear();
137     return true;
138   }
139 
140   if (entry.uncompressed_length > std::numeric_limits<size_t>::max()) {
141     LOG(ERROR) << "Failed to extract " << name
142                << " because's uncompressed size exceeds size of address space. "
143                << entry.uncompressed_length;
144     return false;
145   }
146 
147   content->resize(entry.uncompressed_length);
148   if (auto extract_err = ExtractToMemory(
149           handle_, &entry, reinterpret_cast<uint8_t*>(&content->at(0)), entry.uncompressed_length);
150       extract_err != 0) {
151     LOG(ERROR) << "failed to read " << name << " from package: " << ErrorCodeString(extract_err);
152     return false;
153   }
154 
155   return true;
156 }
157 
ExtractEntryToTempFile(const std::string_view name,TemporaryFile * temp_file) const158 bool TargetFile::ExtractEntryToTempFile(const std::string_view name,
159                                         TemporaryFile* temp_file) const {
160   if (extracted_input_) {
161     std::string entry_path = path_ + "/" + std::string(name);
162     return std::filesystem::copy_file(entry_path, temp_file->path,
163                                       std::filesystem::copy_options::overwrite_existing);
164   }
165 
166   CHECK(handle_);
167   ZipEntry64 entry;
168   if (auto find_err = FindEntry(handle_, name, &entry); find_err != 0) {
169     LOG(ERROR) << "failed to find " << name << " in the package: " << ErrorCodeString(find_err);
170     return false;
171   }
172 
173   if (auto status = ExtractEntryToFile(handle_, &entry, temp_file->fd); status != 0) {
174     LOG(ERROR) << "Failed to extract zip entry " << name << " : " << ErrorCodeString(status);
175     return false;
176   }
177   return true;
178 }
179 
Open()180 bool TargetFile::Open() {
181   if (!extracted_input_) {
182     if (auto ret = OpenArchive(path_.c_str(), &handle_); ret != 0) {
183       LOG(ERROR) << "failed to open source target file " << path_ << ": " << ErrorCodeString(ret);
184       return false;
185     }
186   }
187 
188   // Parse the misc info.
189   std::string misc_info_content;
190   if (!ReadEntryToString("META/misc_info.txt", &misc_info_content)) {
191     return false;
192   }
193   if (!ParsePropertyFile(misc_info_content, &misc_info_)) {
194     return false;
195   }
196 
197   return true;
198 }
199 
GetBuildProps(std::map<std::string,std::string,std::less<>> * props_map) const200 bool TargetFile::GetBuildProps(std::map<std::string, std::string, std::less<>>* props_map) const {
201   props_map->clear();
202   // Parse the source zip to mock the system props and block devices. We try all the possible
203   // locations for build props.
204   constexpr std::string_view kPropLocations[] = {
205     "SYSTEM/build.prop",
206     "VENDOR/build.prop",
207     "PRODUCT/build.prop",
208     "SYSTEM_EXT/build.prop",
209     "SYSTEM/vendor/build.prop",
210     "SYSTEM/product/build.prop",
211     "SYSTEM/system_ext/build.prop",
212     "ODM/build.prop",  // legacy
213     "ODM/etc/build.prop",
214     "VENDOR/odm/build.prop",  // legacy
215     "VENDOR/odm/etc/build.prop",
216   };
217   for (const auto& name : kPropLocations) {
218     std::string build_prop_content;
219     if (!ReadEntryToString(name, &build_prop_content)) {
220       continue;
221     }
222     std::map<std::string, std::string, std::less<>> props;
223     if (!ParsePropertyFile(build_prop_content, &props)) {
224       LOG(ERROR) << "Failed to parse build prop in " << name;
225       return false;
226     }
227     for (const auto& [key, value] : props) {
228       if (auto it = props_map->find(key); it != props_map->end() && it->second != value) {
229         LOG(WARNING) << "Property " << key << " has different values in property files, we got "
230                      << it->second << " and " << value;
231       }
232       props_map->emplace(key, value);
233     }
234   }
235 
236   return true;
237 }
238 
ExtractImage(const std::string_view entry_name,const FstabInfo & fstab_info,const std::string_view work_dir,TemporaryFile * image_file) const239 bool TargetFile::ExtractImage(const std::string_view entry_name, const FstabInfo& fstab_info,
240                               const std::string_view work_dir, TemporaryFile* image_file) const {
241   if (!EntryExists(entry_name)) {
242     return false;
243   }
244 
245   // We don't need extra work for 'emmc'; use the image file as the block device.
246   if (fstab_info.fs_type == "emmc" || misc_info_.find("extfs_sparse_flag") == misc_info_.end()) {
247     if (!ExtractEntryToTempFile(entry_name, image_file)) {
248       return false;
249     }
250   } else {  // treated as ext4 sparse image
251     TemporaryFile sparse_image{ std::string(work_dir) };
252     if (!ExtractEntryToTempFile(entry_name, &sparse_image)) {
253       return false;
254     }
255 
256     // Convert the sparse image to raw.
257     if (!SimgToImg(sparse_image.fd, image_file->fd)) {
258       LOG(ERROR) << "Failed to convert " << fstab_info.mount_point << " to raw.";
259       return false;
260     }
261   }
262 
263   return true;
264 }
265 
ParseFstabInfo(std::vector<FstabInfo> * fstab_info_list) const266 bool TargetFile::ParseFstabInfo(std::vector<FstabInfo>* fstab_info_list) const {
267   // Parse the fstab file and extract the image files. The location of the fstab actually depends
268   // on some flags e.g. "no_recovery", "recovery_as_boot". Here we just try all possibilities.
269   constexpr std::string_view kRecoveryFstabLocations[] = {
270     "RECOVERY/RAMDISK/system/etc/recovery.fstab",
271     "RECOVERY/RAMDISK/etc/recovery.fstab",
272     "BOOT/RAMDISK/system/etc/recovery.fstab",
273     "BOOT/RAMDISK/etc/recovery.fstab",
274   };
275   std::string fstab_content;
276   for (const auto& name : kRecoveryFstabLocations) {
277     if (std::string content; ReadEntryToString(name, &content)) {
278       fstab_content = std::move(content);
279       break;
280     }
281   }
282   if (fstab_content.empty()) {
283     LOG(ERROR) << "Failed to parse the recovery fstab file";
284     return false;
285   }
286 
287   // Extract the images and convert them to raw.
288   if (!ParseFstab(fstab_content, fstab_info_list)) {
289     LOG(ERROR) << "Failed to mount the block devices for source build.";
290     return false;
291   }
292 
293   return true;
294 }
295