blob: 30e3f67a25d2669c57267e4a6a74da2f0277f667 [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
Kelvin Zhangcb2dc882021-11-22 09:26:50 -0800119constexpr base::StringPiece ToStringPiece(std::string_view s) {
120 return base::StringPiece(s.data(), s.length());
121}
122
123bool IsFileExtensions(
124 const std::string_view name,
125 const std::initializer_list<std::string_view>& extensions) {
126 return any_of(extensions.begin(),
127 extensions.end(),
128 [name = ToStringPiece(name)](const auto& ext) {
129 return base::EndsWith(name,
130 ToStringPiece(ext),
131 base::CompareCase::INSENSITIVE_ASCII);
132 });
Sen Jiang23bae402018-11-13 11:27:29 -0800133}
134
Amin Hassani3cd4df12017-08-25 11:21:53 -0700135ByteExtent ExpandToByteExtent(const BitExtent& extent) {
136 uint64_t offset = extent.offset / 8;
137 uint64_t length = ((extent.offset + extent.length + 7) / 8) - offset;
138 return {offset, length};
139}
140
Amin Hassani924183b2017-09-27 14:50:59 -0700141bool ShiftExtentsOverExtents(const vector<Extent>& base_extents,
142 vector<Extent>* over_extents) {
Amin Hassanid8b67f42017-12-06 13:47:52 -0800143 if (utils::BlocksInExtents(base_extents) <
144 utils::BlocksInExtents(*over_extents)) {
Amin Hassani924183b2017-09-27 14:50:59 -0700145 LOG(ERROR) << "over_extents have more blocks than base_extents! Invalid!";
146 return false;
147 }
148 for (size_t idx = 0; idx < over_extents->size(); idx++) {
149 auto over_ext = &over_extents->at(idx);
150 auto gap_blocks = base_extents[0].start_block();
151 auto last_end_block = base_extents[0].start_block();
152 for (auto base_ext : base_extents) { // We need to modify |base_ext|, so we
153 // use copy.
154 gap_blocks += base_ext.start_block() - last_end_block;
155 last_end_block = base_ext.start_block() + base_ext.num_blocks();
156 base_ext.set_start_block(base_ext.start_block() - gap_blocks);
157 if (over_ext->start_block() >= base_ext.start_block() &&
158 over_ext->start_block() <
159 base_ext.start_block() + base_ext.num_blocks()) {
160 if (over_ext->start_block() + over_ext->num_blocks() <=
161 base_ext.start_block() + base_ext.num_blocks()) {
162 // |over_ext| is inside |base_ext|, increase its start block.
163 over_ext->set_start_block(over_ext->start_block() + gap_blocks);
164 } else {
165 // |over_ext| spills over this |base_ext|, split it into two.
166 auto new_blocks = base_ext.start_block() + base_ext.num_blocks() -
167 over_ext->start_block();
168 vector<Extent> new_extents = {
169 ExtentForRange(gap_blocks + over_ext->start_block(), new_blocks),
170 ExtentForRange(over_ext->start_block() + new_blocks,
171 over_ext->num_blocks() - new_blocks)};
172 *over_ext = new_extents[0];
173 over_extents->insert(std::next(over_extents->begin(), idx + 1),
174 new_extents[1]);
175 }
176 break; // We processed |over_ext|, so break the loop;
177 }
178 }
179 }
180 return true;
181}
182
Amin Hassani3cd4df12017-08-25 11:21:53 -0700183bool ShiftBitExtentsOverExtents(const vector<Extent>& base_extents,
184 vector<BitExtent>* over_extents) {
185 if (over_extents->empty()) {
186 return true;
187 }
188
189 // This check is needed to make sure the number of bytes in |over_extents|
190 // does not exceed |base_extents|.
191 auto last_extent = ExpandToByteExtent(over_extents->back());
Kelvin Zhangcb2dc882021-11-22 09:26:50 -0800192 TEST_LE(last_extent.offset + last_extent.length,
193 utils::BlocksInExtents(base_extents) * kBlockSize);
Amin Hassani3cd4df12017-08-25 11:21:53 -0700194
195 for (auto o_ext = over_extents->begin(); o_ext != over_extents->end();) {
196 size_t gap_blocks = base_extents[0].start_block();
197 size_t last_end_block = base_extents[0].start_block();
198 bool o_ext_processed = false;
199 for (auto b_ext : base_extents) { // We need to modify |b_ext|, so we copy.
200 gap_blocks += b_ext.start_block() - last_end_block;
201 last_end_block = b_ext.start_block() + b_ext.num_blocks();
202 b_ext.set_start_block(b_ext.start_block() - gap_blocks);
203 auto byte_o_ext = ExpandToByteExtent(*o_ext);
204 if (byte_o_ext.offset >= b_ext.start_block() * kBlockSize &&
205 byte_o_ext.offset <
206 (b_ext.start_block() + b_ext.num_blocks()) * kBlockSize) {
207 if ((byte_o_ext.offset + byte_o_ext.length) <=
208 (b_ext.start_block() + b_ext.num_blocks()) * kBlockSize) {
209 // |o_ext| is inside |b_ext|, increase its start block.
210 o_ext->offset += gap_blocks * kBlockSize * 8;
211 ++o_ext;
212 } else {
213 // |o_ext| spills over this |b_ext|, remove it.
214 o_ext = over_extents->erase(o_ext);
215 }
216 o_ext_processed = true;
217 break; // We processed o_ext, so break the loop;
218 }
219 }
220 TEST_AND_RETURN_FALSE(o_ext_processed);
221 }
222 return true;
223}
224
225vector<BitExtent> FindDeflates(const vector<Extent>& extents,
226 const vector<BitExtent>& in_deflates) {
227 vector<BitExtent> result;
228 // TODO(ahassani): Replace this with binary_search style search.
229 for (const auto& deflate : in_deflates) {
230 for (const auto& extent : extents) {
231 if (IsBitExtentInExtent(extent, deflate)) {
232 result.push_back(deflate);
233 break;
234 }
235 }
236 }
237 return result;
238}
239
240bool CompactDeflates(const vector<Extent>& extents,
241 const vector<BitExtent>& in_deflates,
242 vector<BitExtent>* out_deflates) {
243 size_t bytes_passed = 0;
244 out_deflates->reserve(in_deflates.size());
245 for (const auto& extent : extents) {
246 size_t gap_bytes = extent.start_block() * kBlockSize - bytes_passed;
247 for (const auto& deflate : in_deflates) {
248 if (IsBitExtentInExtent(extent, deflate)) {
249 out_deflates->emplace_back(deflate.offset - (gap_bytes * 8),
250 deflate.length);
251 }
252 }
253 bytes_passed += extent.num_blocks() * kBlockSize;
254 }
255
256 // All given |in_deflates| items should've been inside one of the extents in
257 // |extents|.
258 TEST_AND_RETURN_FALSE(in_deflates.size() == out_deflates->size());
259
260 // Make sure all outgoing deflates are ordered and non-overlapping.
261 auto result = std::adjacent_find(out_deflates->begin(),
262 out_deflates->end(),
263 [](const BitExtent& a, const BitExtent& b) {
264 return (a.offset + a.length) > b.offset;
265 });
266 TEST_AND_RETURN_FALSE(result == out_deflates->end());
267 return true;
268}
269
270bool FindAndCompactDeflates(const vector<Extent>& extents,
271 const vector<BitExtent>& in_deflates,
272 vector<BitExtent>* out_deflates) {
273 auto found_deflates = FindDeflates(extents, in_deflates);
274 TEST_AND_RETURN_FALSE(CompactDeflates(extents, found_deflates, out_deflates));
275 return true;
276}
277
Kelvin Zhangcb2dc882021-11-22 09:26:50 -0800278bool DeflatePreprocessFileData(const std::string_view filename,
279 const brillo::Blob& data,
280 vector<puffin::BitExtent>* deflates) {
281 bool is_zip = IsFileExtensions(
282 filename, {".apk", ".zip", ".jar", ".zvoice", ".apex", "capex"});
283 bool is_gzip = IsFileExtensions(filename, {".gz", ".gzip", ".tgz"});
284 if (is_zip) {
285 if (!puffin::LocateDeflatesInZipArchive(data, deflates)) {
286 LOG(ERROR) << "Failed to locate deflates in zip file " << filename;
287 deflates->clear();
288 return false;
289 }
290 } else if (is_gzip) {
291 if (!puffin::LocateDeflatesInGzip(data, deflates)) {
292 LOG(ERROR) << "Failed to locate deflates in gzip file " << filename;
293 deflates->clear();
294 return false;
295 }
296 }
297 return true;
298}
299
Sen Jiangce39e672018-11-28 16:43:00 -0800300bool PreprocessPartitionFiles(const PartitionConfig& part,
301 vector<FilesystemInterface::File>* result_files,
302 bool extract_deflates) {
Amin Hassani924183b2017-09-27 14:50:59 -0700303 // Get the file system files.
304 vector<FilesystemInterface::File> tmp_files;
305 part.fs_interface->GetFiles(&tmp_files);
306 result_files->reserve(tmp_files.size());
307
Tianjie Xu1a7bb2c2018-01-22 17:56:57 -0800308 for (auto& file : tmp_files) {
Håkan Kviste4d414e2019-06-28 08:05:06 +0200309 auto is_regular_file = IsRegularFile(file);
310
311 if (is_regular_file && IsSquashfsImage(part.path, file)) {
Amin Hassani924183b2017-09-27 14:50:59 -0700312 // Read the image into a file.
313 base::FilePath path;
314 TEST_AND_RETURN_FALSE(base::CreateTemporaryFile(&path));
315 ScopedPathUnlinker old_unlinker(path.value());
316 TEST_AND_RETURN_FALSE(
317 CopyExtentsToFile(part.path, file.extents, path.value(), kBlockSize));
318 // Test if it is actually a Squashfs file.
Amin Hassani77c25fc2019-01-29 10:24:19 -0800319 auto sqfs = SquashfsFilesystem::CreateFromFile(path.value(),
320 extract_deflates,
321 /*load_settings=*/false);
Amin Hassani924183b2017-09-27 14:50:59 -0700322 if (sqfs) {
323 // It is an squashfs file. Get its files to replace with itself.
324 vector<FilesystemInterface::File> files;
325 sqfs->GetFiles(&files);
326
Amin Hassani3cd4df12017-08-25 11:21:53 -0700327 // Replace squashfs file with its files only if |files| has at least two
328 // files or if it has some deflates (since it is better to replace it to
329 // take advantage of the deflates.)
330 if (files.size() > 1 ||
331 (files.size() == 1 && !files[0].deflates.empty())) {
Amin Hassani924183b2017-09-27 14:50:59 -0700332 TEST_AND_RETURN_FALSE(RealignSplittedFiles(file, &files));
333 result_files->insert(result_files->end(), files.begin(), files.end());
334 continue;
335 }
336 } else {
337 LOG(WARNING) << "We thought file: " << file.name
338 << " was a Squashfs file, but it was not.";
339 }
340 }
Tianjie Xu1a7bb2c2018-01-22 17:56:57 -0800341
Tianjie55abd3c2020-06-19 00:22:59 -0700342 if (is_regular_file && extract_deflates && !file.is_compressed) {
Sen Jiang23bae402018-11-13 11:27:29 -0800343 // Search for deflates if the file is in zip or gzip format.
344 // .zvoice files may eventually move out of rootfs. If that happens,
345 // remove ".zvoice" (crbug.com/782918).
Sen Jiang812e9d12018-11-21 16:40:37 -0800346 bool is_zip = IsFileExtensions(
Kelvin Zhangdc1f2582021-09-13 16:43:41 -0700347 file.name, {".apk", ".zip", ".jar", ".zvoice", ".apex", "capex"});
Sen Jiang23bae402018-11-13 11:27:29 -0800348 bool is_gzip = IsFileExtensions(file.name, {".gz", ".gzip", ".tgz"});
349 if (is_zip || is_gzip) {
350 brillo::Blob data;
351 TEST_AND_RETURN_FALSE(utils::ReadExtents(
352 part.path,
353 file.extents,
354 &data,
355 kBlockSize * utils::BlocksInExtents(file.extents),
356 kBlockSize));
Kelvin Zhang6fbf5942021-12-09 14:06:25 -0800357 // |data| read from disk always has size multiple of kBlockSize. So it
358 // might contain trailing garbage data and confuse the gzip/zip
359 // processors. Trim them.
360 if (file.file_stat.st_size > 0 &&
361 static_cast<size_t>(file.file_stat.st_size) < data.size()) {
362 data.resize(file.file_stat.st_size);
363 }
Sen Jiang23bae402018-11-13 11:27:29 -0800364 vector<puffin::BitExtent> deflates;
Kelvin Zhangcb2dc882021-11-22 09:26:50 -0800365 if (!DeflatePreprocessFileData(file.name, data, &deflates)) {
366 LOG(ERROR) << "Failed to preprocess deflate data in partition "
367 << part.name;
368 return false;
Sen Jiang23bae402018-11-13 11:27:29 -0800369 }
370 // Shift the deflate's extent to the offset starting from the beginning
371 // of the current partition; and the delta processor will align the
372 // extents in a continuous buffer later.
373 TEST_AND_RETURN_FALSE(
374 ShiftBitExtentsOverExtents(file.extents, &deflates));
375 file.deflates = std::move(deflates);
376 }
Tianjie Xu1a7bb2c2018-01-22 17:56:57 -0800377 }
378
Amin Hassani924183b2017-09-27 14:50:59 -0700379 result_files->push_back(file);
380 }
Amin Hassani924183b2017-09-27 14:50:59 -0700381 return true;
382}
383
384} // namespace deflate_utils
385} // namespace chromeos_update_engine