blob: febc1c303dae4f37925e7ede063a152e0b4ac267 [file] [log] [blame]
Amin Hassani924183b2017-09-27 14:50:59 -07001//
2// Copyright (C) 2017 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 "update_engine/payload_generator/deflate_utils.h"
18
19#include <algorithm>
20#include <string>
21#include <utility>
22
23#include <base/files/file_util.h>
24#include <base/logging.h>
25#include <base/strings/string_util.h>
26
27#include "update_engine/common/utils.h"
28#include "update_engine/payload_generator/delta_diff_generator.h"
29#include "update_engine/payload_generator/extent_ranges.h"
30#include "update_engine/payload_generator/extent_utils.h"
31#include "update_engine/payload_generator/squashfs_filesystem.h"
32#include "update_engine/update_metadata.pb.h"
33
Amin Hassani3cd4df12017-08-25 11:21:53 -070034using puffin::BitExtent;
35using puffin::ByteExtent;
Amin Hassani232f8f92019-01-14 16:15:31 -080036using std::string;
37using std::vector;
Amin Hassani924183b2017-09-27 14:50:59 -070038
39namespace chromeos_update_engine {
40namespace deflate_utils {
41namespace {
42
43// The minimum size for a squashfs image to be processed.
44const uint64_t kMinimumSquashfsImageSize = 1 * 1024 * 1024; // bytes
45
46// TODO(*): Optimize this so we don't have to read all extents into memory in
47// case it is large.
48bool CopyExtentsToFile(const string& in_path,
Andrew9d5a61d2020-03-26 13:40:37 -070049 const vector<Extent>& extents,
Amin Hassani924183b2017-09-27 14:50:59 -070050 const string& out_path,
51 size_t block_size) {
Amin Hassanid8b67f42017-12-06 13:47:52 -080052 brillo::Blob data(utils::BlocksInExtents(extents) * block_size);
Amin Hassani924183b2017-09-27 14:50:59 -070053 TEST_AND_RETURN_FALSE(
54 utils::ReadExtents(in_path, extents, &data, data.size(), block_size));
55 TEST_AND_RETURN_FALSE(
56 utils::WriteFile(out_path.c_str(), data.data(), data.size()));
57 return true;
58}
59
60bool IsSquashfsImage(const string& part_path,
61 const FilesystemInterface::File& file) {
62 // Only check for files with img postfix.
63 if (base::EndsWith(file.name, ".img", base::CompareCase::SENSITIVE) &&
Amin Hassanid8b67f42017-12-06 13:47:52 -080064 utils::BlocksInExtents(file.extents) >=
65 kMinimumSquashfsImageSize / kBlockSize) {
Amin Hassani924183b2017-09-27 14:50:59 -070066 brillo::Blob super_block;
67 TEST_AND_RETURN_FALSE(
68 utils::ReadFileChunk(part_path,
69 file.extents[0].start_block() * kBlockSize,
70 100,
71 &super_block));
72 return SquashfsFilesystem::IsSquashfsImage(super_block);
73 }
74 return false;
75}
76
Håkan Kviste4d414e2019-06-28 08:05:06 +020077bool IsRegularFile(const FilesystemInterface::File& file) {
78 // If inode is 0, then stat information is invalid for some psuedo files
79 if (file.file_stat.st_ino != 0 &&
80 (file.file_stat.st_mode & S_IFMT) == S_IFREG) {
81 return true;
82 }
83 return false;
84}
85
Amin Hassani924183b2017-09-27 14:50:59 -070086// Realigns subfiles |files| of a splitted file |file| into its correct
87// positions. This can be used for squashfs, zip, apk, etc.
88bool RealignSplittedFiles(const FilesystemInterface::File& file,
89 vector<FilesystemInterface::File>* files) {
90 // We have to shift all the Extents in |files|, based on the Extents of the
91 // |file| itself.
92 size_t num_blocks = 0;
93 for (auto& in_file : *files) { // We need to modify so no constant.
94 TEST_AND_RETURN_FALSE(
95 ShiftExtentsOverExtents(file.extents, &in_file.extents));
Amin Hassani3cd4df12017-08-25 11:21:53 -070096 TEST_AND_RETURN_FALSE(
97 ShiftBitExtentsOverExtents(file.extents, &in_file.deflates));
98
Amin Hassani924183b2017-09-27 14:50:59 -070099 in_file.name = file.name + "/" + in_file.name;
Amin Hassanid8b67f42017-12-06 13:47:52 -0800100 num_blocks += utils::BlocksInExtents(in_file.extents);
Amin Hassani924183b2017-09-27 14:50:59 -0700101 }
102
103 // Check that all files in |in_files| cover the entire image.
Amin Hassanid8b67f42017-12-06 13:47:52 -0800104 TEST_AND_RETURN_FALSE(utils::BlocksInExtents(file.extents) == num_blocks);
Amin Hassani924183b2017-09-27 14:50:59 -0700105 return true;
106}
107
Amin Hassani3cd4df12017-08-25 11:21:53 -0700108bool IsBitExtentInExtent(const Extent& extent, const BitExtent& bit_extent) {
109 return (bit_extent.offset / 8) >= (extent.start_block() * kBlockSize) &&
110 ((bit_extent.offset + bit_extent.length + 7) / 8) <=
111 ((extent.start_block() + extent.num_blocks()) * kBlockSize);
112}
113
Sen Jiang23bae402018-11-13 11:27:29 -0800114// Returns whether the given file |name| has an extension listed in
115// |extensions|.
Kelvin Zhang0af01222021-10-05 13:36:47 -0700116
117} // namespace
118
Sen Jiang23bae402018-11-13 11:27:29 -0800119bool IsFileExtensions(const string& name,
120 const std::initializer_list<string>& extensions) {
121 return any_of(extensions.begin(), extensions.end(), [&name](const auto& ext) {
122 return base::EndsWith(name, ext, base::CompareCase::INSENSITIVE_ASCII);
123 });
124}
125
Amin Hassani3cd4df12017-08-25 11:21:53 -0700126ByteExtent ExpandToByteExtent(const BitExtent& extent) {
127 uint64_t offset = extent.offset / 8;
128 uint64_t length = ((extent.offset + extent.length + 7) / 8) - offset;
129 return {offset, length};
130}
131
Amin Hassani924183b2017-09-27 14:50:59 -0700132bool ShiftExtentsOverExtents(const vector<Extent>& base_extents,
133 vector<Extent>* over_extents) {
Amin Hassanid8b67f42017-12-06 13:47:52 -0800134 if (utils::BlocksInExtents(base_extents) <
135 utils::BlocksInExtents(*over_extents)) {
Amin Hassani924183b2017-09-27 14:50:59 -0700136 LOG(ERROR) << "over_extents have more blocks than base_extents! Invalid!";
137 return false;
138 }
139 for (size_t idx = 0; idx < over_extents->size(); idx++) {
140 auto over_ext = &over_extents->at(idx);
141 auto gap_blocks = base_extents[0].start_block();
142 auto last_end_block = base_extents[0].start_block();
143 for (auto base_ext : base_extents) { // We need to modify |base_ext|, so we
144 // use copy.
145 gap_blocks += base_ext.start_block() - last_end_block;
146 last_end_block = base_ext.start_block() + base_ext.num_blocks();
147 base_ext.set_start_block(base_ext.start_block() - gap_blocks);
148 if (over_ext->start_block() >= base_ext.start_block() &&
149 over_ext->start_block() <
150 base_ext.start_block() + base_ext.num_blocks()) {
151 if (over_ext->start_block() + over_ext->num_blocks() <=
152 base_ext.start_block() + base_ext.num_blocks()) {
153 // |over_ext| is inside |base_ext|, increase its start block.
154 over_ext->set_start_block(over_ext->start_block() + gap_blocks);
155 } else {
156 // |over_ext| spills over this |base_ext|, split it into two.
157 auto new_blocks = base_ext.start_block() + base_ext.num_blocks() -
158 over_ext->start_block();
159 vector<Extent> new_extents = {
160 ExtentForRange(gap_blocks + over_ext->start_block(), new_blocks),
161 ExtentForRange(over_ext->start_block() + new_blocks,
162 over_ext->num_blocks() - new_blocks)};
163 *over_ext = new_extents[0];
164 over_extents->insert(std::next(over_extents->begin(), idx + 1),
165 new_extents[1]);
166 }
167 break; // We processed |over_ext|, so break the loop;
168 }
169 }
170 }
171 return true;
172}
173
Amin Hassani3cd4df12017-08-25 11:21:53 -0700174bool ShiftBitExtentsOverExtents(const vector<Extent>& base_extents,
175 vector<BitExtent>* over_extents) {
176 if (over_extents->empty()) {
177 return true;
178 }
179
180 // This check is needed to make sure the number of bytes in |over_extents|
181 // does not exceed |base_extents|.
182 auto last_extent = ExpandToByteExtent(over_extents->back());
183 TEST_AND_RETURN_FALSE(last_extent.offset + last_extent.length <=
Amin Hassanid8b67f42017-12-06 13:47:52 -0800184 utils::BlocksInExtents(base_extents) * kBlockSize);
Amin Hassani3cd4df12017-08-25 11:21:53 -0700185
186 for (auto o_ext = over_extents->begin(); o_ext != over_extents->end();) {
187 size_t gap_blocks = base_extents[0].start_block();
188 size_t last_end_block = base_extents[0].start_block();
189 bool o_ext_processed = false;
190 for (auto b_ext : base_extents) { // We need to modify |b_ext|, so we copy.
191 gap_blocks += b_ext.start_block() - last_end_block;
192 last_end_block = b_ext.start_block() + b_ext.num_blocks();
193 b_ext.set_start_block(b_ext.start_block() - gap_blocks);
194 auto byte_o_ext = ExpandToByteExtent(*o_ext);
195 if (byte_o_ext.offset >= b_ext.start_block() * kBlockSize &&
196 byte_o_ext.offset <
197 (b_ext.start_block() + b_ext.num_blocks()) * kBlockSize) {
198 if ((byte_o_ext.offset + byte_o_ext.length) <=
199 (b_ext.start_block() + b_ext.num_blocks()) * kBlockSize) {
200 // |o_ext| is inside |b_ext|, increase its start block.
201 o_ext->offset += gap_blocks * kBlockSize * 8;
202 ++o_ext;
203 } else {
204 // |o_ext| spills over this |b_ext|, remove it.
205 o_ext = over_extents->erase(o_ext);
206 }
207 o_ext_processed = true;
208 break; // We processed o_ext, so break the loop;
209 }
210 }
211 TEST_AND_RETURN_FALSE(o_ext_processed);
212 }
213 return true;
214}
215
216vector<BitExtent> FindDeflates(const vector<Extent>& extents,
217 const vector<BitExtent>& in_deflates) {
218 vector<BitExtent> result;
219 // TODO(ahassani): Replace this with binary_search style search.
220 for (const auto& deflate : in_deflates) {
221 for (const auto& extent : extents) {
222 if (IsBitExtentInExtent(extent, deflate)) {
223 result.push_back(deflate);
224 break;
225 }
226 }
227 }
228 return result;
229}
230
231bool CompactDeflates(const vector<Extent>& extents,
232 const vector<BitExtent>& in_deflates,
233 vector<BitExtent>* out_deflates) {
234 size_t bytes_passed = 0;
235 out_deflates->reserve(in_deflates.size());
236 for (const auto& extent : extents) {
237 size_t gap_bytes = extent.start_block() * kBlockSize - bytes_passed;
238 for (const auto& deflate : in_deflates) {
239 if (IsBitExtentInExtent(extent, deflate)) {
240 out_deflates->emplace_back(deflate.offset - (gap_bytes * 8),
241 deflate.length);
242 }
243 }
244 bytes_passed += extent.num_blocks() * kBlockSize;
245 }
246
247 // All given |in_deflates| items should've been inside one of the extents in
248 // |extents|.
249 TEST_AND_RETURN_FALSE(in_deflates.size() == out_deflates->size());
250
251 // Make sure all outgoing deflates are ordered and non-overlapping.
252 auto result = std::adjacent_find(out_deflates->begin(),
253 out_deflates->end(),
254 [](const BitExtent& a, const BitExtent& b) {
255 return (a.offset + a.length) > b.offset;
256 });
257 TEST_AND_RETURN_FALSE(result == out_deflates->end());
258 return true;
259}
260
261bool FindAndCompactDeflates(const vector<Extent>& extents,
262 const vector<BitExtent>& in_deflates,
263 vector<BitExtent>* out_deflates) {
264 auto found_deflates = FindDeflates(extents, in_deflates);
265 TEST_AND_RETURN_FALSE(CompactDeflates(extents, found_deflates, out_deflates));
266 return true;
267}
268
Sen Jiangce39e672018-11-28 16:43:00 -0800269bool PreprocessPartitionFiles(const PartitionConfig& part,
270 vector<FilesystemInterface::File>* result_files,
271 bool extract_deflates) {
Amin Hassani924183b2017-09-27 14:50:59 -0700272 // Get the file system files.
273 vector<FilesystemInterface::File> tmp_files;
274 part.fs_interface->GetFiles(&tmp_files);
275 result_files->reserve(tmp_files.size());
276
Tianjie Xu1a7bb2c2018-01-22 17:56:57 -0800277 for (auto& file : tmp_files) {
Håkan Kviste4d414e2019-06-28 08:05:06 +0200278 auto is_regular_file = IsRegularFile(file);
279
280 if (is_regular_file && IsSquashfsImage(part.path, file)) {
Amin Hassani924183b2017-09-27 14:50:59 -0700281 // Read the image into a file.
282 base::FilePath path;
283 TEST_AND_RETURN_FALSE(base::CreateTemporaryFile(&path));
284 ScopedPathUnlinker old_unlinker(path.value());
285 TEST_AND_RETURN_FALSE(
286 CopyExtentsToFile(part.path, file.extents, path.value(), kBlockSize));
287 // Test if it is actually a Squashfs file.
Amin Hassani77c25fc2019-01-29 10:24:19 -0800288 auto sqfs = SquashfsFilesystem::CreateFromFile(path.value(),
289 extract_deflates,
290 /*load_settings=*/false);
Amin Hassani924183b2017-09-27 14:50:59 -0700291 if (sqfs) {
292 // It is an squashfs file. Get its files to replace with itself.
293 vector<FilesystemInterface::File> files;
294 sqfs->GetFiles(&files);
295
Amin Hassani3cd4df12017-08-25 11:21:53 -0700296 // Replace squashfs file with its files only if |files| has at least two
297 // files or if it has some deflates (since it is better to replace it to
298 // take advantage of the deflates.)
299 if (files.size() > 1 ||
300 (files.size() == 1 && !files[0].deflates.empty())) {
Amin Hassani924183b2017-09-27 14:50:59 -0700301 TEST_AND_RETURN_FALSE(RealignSplittedFiles(file, &files));
302 result_files->insert(result_files->end(), files.begin(), files.end());
303 continue;
304 }
305 } else {
306 LOG(WARNING) << "We thought file: " << file.name
307 << " was a Squashfs file, but it was not.";
308 }
309 }
Tianjie Xu1a7bb2c2018-01-22 17:56:57 -0800310
Tianjie55abd3c2020-06-19 00:22:59 -0700311 if (is_regular_file && extract_deflates && !file.is_compressed) {
Sen Jiang23bae402018-11-13 11:27:29 -0800312 // Search for deflates if the file is in zip or gzip format.
313 // .zvoice files may eventually move out of rootfs. If that happens,
314 // remove ".zvoice" (crbug.com/782918).
Sen Jiang812e9d12018-11-21 16:40:37 -0800315 bool is_zip = IsFileExtensions(
Kelvin Zhangdc1f2582021-09-13 16:43:41 -0700316 file.name, {".apk", ".zip", ".jar", ".zvoice", ".apex", "capex"});
Sen Jiang23bae402018-11-13 11:27:29 -0800317 bool is_gzip = IsFileExtensions(file.name, {".gz", ".gzip", ".tgz"});
318 if (is_zip || is_gzip) {
319 brillo::Blob data;
320 TEST_AND_RETURN_FALSE(utils::ReadExtents(
321 part.path,
322 file.extents,
323 &data,
324 kBlockSize * utils::BlocksInExtents(file.extents),
325 kBlockSize));
326 vector<puffin::BitExtent> deflates;
327 if (is_zip) {
328 TEST_AND_RETURN_FALSE(
329 puffin::LocateDeflatesInZipArchive(data, &deflates));
330 } else if (is_gzip) {
331 TEST_AND_RETURN_FALSE(puffin::LocateDeflatesInGzip(data, &deflates));
332 }
333 // Shift the deflate's extent to the offset starting from the beginning
334 // of the current partition; and the delta processor will align the
335 // extents in a continuous buffer later.
336 TEST_AND_RETURN_FALSE(
337 ShiftBitExtentsOverExtents(file.extents, &deflates));
338 file.deflates = std::move(deflates);
339 }
Tianjie Xu1a7bb2c2018-01-22 17:56:57 -0800340 }
341
Amin Hassani924183b2017-09-27 14:50:59 -0700342 result_files->push_back(file);
343 }
Amin Hassani924183b2017-09-27 14:50:59 -0700344 return true;
345}
346
347} // namespace deflate_utils
348} // namespace chromeos_update_engine