1 //
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
34 using puffin::BitExtent;
35 using puffin::ByteExtent;
36 using std::string;
37 using std::vector;
38
39 namespace chromeos_update_engine {
40 namespace deflate_utils {
41 namespace {
42
43 // The minimum size for a squashfs image to be processed.
44 const 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.
CopyExtentsToFile(const string & in_path,const vector<Extent> & extents,const string & out_path,size_t block_size)48 bool CopyExtentsToFile(const string& in_path,
49 const vector<Extent>& extents,
50 const string& out_path,
51 size_t block_size) {
52 brillo::Blob data(utils::BlocksInExtents(extents) * block_size);
53 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
IsSquashfsImage(const string & part_path,const FilesystemInterface::File & file)60 bool 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) &&
64 utils::BlocksInExtents(file.extents) >=
65 kMinimumSquashfsImageSize / kBlockSize) {
66 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
IsRegularFile(const FilesystemInterface::File & file)77 bool 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
86 // Realigns subfiles |files| of a splitted file |file| into its correct
87 // positions. This can be used for squashfs, zip, apk, etc.
RealignSplittedFiles(const FilesystemInterface::File & file,vector<FilesystemInterface::File> * files)88 bool 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));
96 TEST_AND_RETURN_FALSE(
97 ShiftBitExtentsOverExtents(file.extents, &in_file.deflates));
98
99 in_file.name = file.name + "/" + in_file.name;
100 num_blocks += utils::BlocksInExtents(in_file.extents);
101 }
102
103 // Check that all files in |in_files| cover the entire image.
104 TEST_AND_RETURN_FALSE(utils::BlocksInExtents(file.extents) == num_blocks);
105 return true;
106 }
107
IsBitExtentInExtent(const Extent & extent,const BitExtent & bit_extent)108 bool 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
114 // Returns whether the given file |name| has an extension listed in
115 // |extensions|.
116
117 } // namespace
118
ToStringPiece(std::string_view s)119 constexpr base::StringPiece ToStringPiece(std::string_view s) {
120 return base::StringPiece(s.data(), s.length());
121 }
122
IsFileExtensions(const std::string_view name,const std::initializer_list<std::string_view> & extensions)123 bool 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 });
133 }
134
ExpandToByteExtent(const BitExtent & extent)135 ByteExtent 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
ShiftExtentsOverExtents(const vector<Extent> & base_extents,vector<Extent> * over_extents)141 bool ShiftExtentsOverExtents(const vector<Extent>& base_extents,
142 vector<Extent>* over_extents) {
143 if (utils::BlocksInExtents(base_extents) <
144 utils::BlocksInExtents(*over_extents)) {
145 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
ShiftBitExtentsOverExtents(const vector<Extent> & base_extents,vector<BitExtent> * over_extents)183 bool 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());
192 TEST_LE(last_extent.offset + last_extent.length,
193 utils::BlocksInExtents(base_extents) * kBlockSize);
194
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
FindDeflates(const vector<Extent> & extents,const vector<BitExtent> & in_deflates)225 vector<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
CompactDeflates(const vector<Extent> & extents,const vector<BitExtent> & in_deflates,vector<BitExtent> * out_deflates)240 bool 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
FindAndCompactDeflates(const vector<Extent> & extents,const vector<BitExtent> & in_deflates,vector<BitExtent> * out_deflates)270 bool 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
DeflatePreprocessFileData(const std::string_view filename,const brillo::Blob & data,vector<puffin::BitExtent> * deflates)278 bool 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
PreprocessPartitionFiles(const PartitionConfig & part,vector<FilesystemInterface::File> * result_files,bool extract_deflates)300 bool PreprocessPartitionFiles(const PartitionConfig& part,
301 vector<FilesystemInterface::File>* result_files,
302 bool extract_deflates) {
303 // 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
308 for (auto& file : tmp_files) {
309 auto is_regular_file = IsRegularFile(file);
310
311 if (is_regular_file && IsSquashfsImage(part.path, file)) {
312 // 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.
319 auto sqfs = SquashfsFilesystem::CreateFromFile(path.value(),
320 extract_deflates,
321 /*load_settings=*/false);
322 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
327 // 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())) {
332 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 }
341
342 if (is_regular_file && extract_deflates && !file.is_compressed) {
343 // 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).
346 bool is_zip = IsFileExtensions(
347 file.name, {".apk", ".zip", ".jar", ".zvoice", ".apex", "capex"});
348 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));
357 // |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 }
364 vector<puffin::BitExtent> deflates;
365 if (!DeflatePreprocessFileData(file.name, data, &deflates)) {
366 LOG(ERROR) << "Failed to preprocess deflate data in partition "
367 << part.name;
368 return false;
369 }
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 }
377 }
378
379 result_files->push_back(file);
380 }
381 return true;
382 }
383
384 } // namespace deflate_utils
385 } // namespace chromeos_update_engine
386