1 //
2 // Copyright (C) 2015 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/delta_diff_utils.h"
18
19 #include <endian.h>
20 #include <sys/user.h>
21 #if defined(__clang__)
22 // TODO(*): Remove these pragmas when b/35721782 is fixed.
23 #pragma clang diagnostic push
24 #pragma clang diagnostic ignored "-Wmacro-redefined"
25 #endif
26 #include <ext2fs/ext2fs.h>
27 #if defined(__clang__)
28 #pragma clang diagnostic pop
29 #endif
30 #include <unistd.h>
31
32 #include <algorithm>
33 #include <functional>
34 #include <limits>
35 #include <list>
36 #include <map>
37 #include <memory>
38 #include <numeric>
39 #include <utility>
40 #include <vector>
41
42 #include <base/files/file_util.h>
43 #include <base/format_macros.h>
44 #include <base/strings/string_util.h>
45 #include <base/strings/stringprintf.h>
46 #include <base/threading/simple_thread.h>
47 #include <brillo/data_encoding.h>
48 #include <bsdiff/bsdiff.h>
49 #include <bsdiff/constants.h>
50 #include <bsdiff/control_entry.h>
51 #include <bsdiff/patch_reader.h>
52 #include <bsdiff/patch_writer_factory.h>
53 #include <puffin/brotli_util.h>
54 #include <puffin/utils.h>
55 #include <zucchini/buffer_view.h>
56 #include <zucchini/patch_writer.h>
57 #include <zucchini/zucchini.h>
58
59 #include "update_engine/common/hash_calculator.h"
60 #include "update_engine/common/subprocess.h"
61 #include "update_engine/common/utils.h"
62 #include "update_engine/payload_consumer/payload_constants.h"
63 #include "update_engine/payload_generator/ab_generator.h"
64 #include "update_engine/payload_generator/block_mapping.h"
65 #include "update_engine/payload_generator/bzip.h"
66 #include "update_engine/payload_generator/deflate_utils.h"
67 #include "update_engine/payload_generator/delta_diff_generator.h"
68 #include "update_engine/payload_generator/extent_ranges.h"
69 #include "update_engine/payload_generator/extent_utils.h"
70 #include "update_engine/payload_generator/merge_sequence_generator.h"
71 #include "update_engine/payload_generator/squashfs_filesystem.h"
72 #include "update_engine/payload_generator/xz.h"
73 #include "update_engine/lz4diff/lz4diff.h"
74
75 using std::list;
76 using std::map;
77 using std::string;
78 using std::vector;
79
80 namespace chromeos_update_engine {
81 namespace {
82
83 // The maximum destination size allowed for bsdiff. In general, bsdiff should
84 // work for arbitrary big files, but the payload generation and payload
85 // application requires a significant amount of RAM. We put a hard-limit of
86 // 200 MiB that should not affect any released board, but will limit the
87 // Chrome binary in ASan builders.
88 const uint64_t kMaxBsdiffDestinationSize = 200 * 1024 * 1024; // bytes
89
90 // The maximum destination size allowed for puffdiff. In general, puffdiff
91 // should work for arbitrary big files, but the payload application is quite
92 // memory intensive, so we limit these operations to 150 MiB.
93 const uint64_t kMaxPuffdiffDestinationSize = 150 * 1024 * 1024; // bytes
94
95 // The maximum destination size allowed for zucchini. We are conservative here
96 // as zucchini tends to use more peak memory.
97 const uint64_t kMaxZucchiniDestinationSize = 150 * 1024 * 1024; // bytes
98
99 const int kBrotliCompressionQuality = 11;
100
101 // Storing a diff operation has more overhead over replace operation in the
102 // manifest, we need to store an additional src_sha256_hash which is 32 bytes
103 // and not compressible, and also src_extents which could use anywhere from a
104 // few bytes to hundreds of bytes depending on the number of extents.
105 // This function evaluates the overhead tradeoff and determines if it's worth to
106 // use a diff operation with data blob of |diff_size| and |num_src_extents|
107 // extents over an existing |op| with data blob of |old_blob_size|.
IsDiffOperationBetter(const InstallOperation & op,size_t old_blob_size,size_t diff_size,size_t num_src_extents)108 bool IsDiffOperationBetter(const InstallOperation& op,
109 size_t old_blob_size,
110 size_t diff_size,
111 size_t num_src_extents) {
112 if (!diff_utils::IsAReplaceOperation(op.type()))
113 return diff_size < old_blob_size;
114
115 // Reference: https://developers.google.com/protocol-buffers/docs/encoding
116 // For |src_sha256_hash| we need 1 byte field number/type, 1 byte size and 32
117 // bytes data, for |src_extents| we need 1 byte field number/type and 1 byte
118 // size.
119 constexpr size_t kDiffOverhead = 1 + 1 + 32 + 1 + 1;
120 // Each extent has two variable length encoded uint64, here we use a rough
121 // estimate of 6 bytes overhead per extent, since |num_blocks| is usually
122 // very small.
123 constexpr size_t kDiffOverheadPerExtent = 6;
124
125 return diff_size + kDiffOverhead + num_src_extents * kDiffOverheadPerExtent <
126 old_blob_size;
127 }
128
129 // Returns the levenshtein distance between string |a| and |b|.
130 // https://en.wikipedia.org/wiki/Levenshtein_distance
LevenshteinDistance(const string & a,const string & b)131 int LevenshteinDistance(const string& a, const string& b) {
132 vector<int> distances(a.size() + 1);
133 std::iota(distances.begin(), distances.end(), 0);
134
135 for (size_t i = 1; i <= b.size(); i++) {
136 distances[0] = i;
137 int previous_distance = i - 1;
138 for (size_t j = 1; j <= a.size(); j++) {
139 int new_distance =
140 std::min({distances[j] + 1,
141 distances[j - 1] + 1,
142 previous_distance + (a[j - 1] == b[i - 1] ? 0 : 1)});
143 previous_distance = distances[j];
144 distances[j] = new_distance;
145 }
146 }
147 return distances.back();
148 }
149
ShouldCreateNewOp(const std::vector<CowMergeOperation> & ops,size_t src_block,size_t dst_block,size_t src_offset)150 static bool ShouldCreateNewOp(const std::vector<CowMergeOperation>& ops,
151 size_t src_block,
152 size_t dst_block,
153 size_t src_offset) {
154 if (ops.empty()) {
155 return true;
156 }
157 const auto& op = ops.back();
158 if (op.src_offset() != src_offset) {
159 return true;
160 }
161 const auto& src_extent = op.src_extent();
162 const auto& dst_extent = op.dst_extent();
163 return src_extent.start_block() + src_extent.num_blocks() != src_block ||
164 dst_extent.start_block() + dst_extent.num_blocks() != dst_block;
165 }
166
AppendXorBlock(std::vector<CowMergeOperation> * ops,size_t src_block,size_t dst_block,size_t src_offset)167 void AppendXorBlock(std::vector<CowMergeOperation>* ops,
168 size_t src_block,
169 size_t dst_block,
170 size_t src_offset) {
171 if (!ops->empty() && ExtentContains(ops->back().dst_extent(), dst_block)) {
172 return;
173 }
174 CHECK_NE(src_block, std::numeric_limits<uint64_t>::max());
175 CHECK_NE(dst_block, std::numeric_limits<uint64_t>::max());
176 if (ShouldCreateNewOp(*ops, src_block, dst_block, src_offset)) {
177 auto& op = ops->emplace_back();
178 op.mutable_src_extent()->set_start_block(src_block);
179 op.mutable_src_extent()->set_num_blocks(1);
180 op.mutable_dst_extent()->set_start_block(dst_block);
181 op.mutable_dst_extent()->set_num_blocks(1);
182 op.set_src_offset(src_offset);
183 op.set_type(CowMergeOperation::COW_XOR);
184 } else {
185 auto& op = ops->back();
186 auto& src_extent = *op.mutable_src_extent();
187 auto& dst_extent = *op.mutable_dst_extent();
188 src_extent.set_num_blocks(src_extent.num_blocks() + 1);
189 dst_extent.set_num_blocks(dst_extent.num_blocks() + 1);
190 }
191 }
192
193 } // namespace
194
195 namespace diff_utils {
GenerateBestDiffOperation(AnnotatedOperation * aop,brillo::Blob * data_blob)196 bool BestDiffGenerator::GenerateBestDiffOperation(AnnotatedOperation* aop,
197 brillo::Blob* data_blob) {
198 std::vector<std::pair<InstallOperation_Type, size_t>> diff_candidates = {
199 {InstallOperation::SOURCE_BSDIFF, kMaxBsdiffDestinationSize},
200 {InstallOperation::PUFFDIFF, kMaxPuffdiffDestinationSize},
201 {InstallOperation::ZUCCHINI, kMaxZucchiniDestinationSize},
202 };
203
204 return GenerateBestDiffOperation(diff_candidates, aop, data_blob);
205 }
206
207 std::vector<bsdiff::CompressorType>
GetUsableCompressorTypes() const208 BestDiffGenerator::GetUsableCompressorTypes() const {
209 return config_.compressors;
210 }
211
GenerateBestDiffOperation(const std::vector<std::pair<InstallOperation_Type,size_t>> & diff_candidates,AnnotatedOperation * aop,brillo::Blob * data_blob)212 bool BestDiffGenerator::GenerateBestDiffOperation(
213 const std::vector<std::pair<InstallOperation_Type, size_t>>&
214 diff_candidates,
215 AnnotatedOperation* aop,
216 brillo::Blob* data_blob) {
217 CHECK(aop);
218 CHECK(data_blob);
219 if (!old_block_info_.blocks.empty() && !new_block_info_.blocks.empty() &&
220 config_.OperationEnabled(InstallOperation::LZ4DIFF_BSDIFF) &&
221 config_.OperationEnabled(InstallOperation::LZ4DIFF_PUFFDIFF)) {
222 brillo::Blob patch;
223 InstallOperation::Type op_type;
224 if (Lz4Diff(old_data_,
225 new_data_,
226 old_block_info_,
227 new_block_info_,
228 &patch,
229 &op_type)) {
230 aop->op.set_type(op_type);
231 // LZ4DIFF is likely significantly better than BSDIFF/PUFFDIFF when
232 // working with EROFS. So no need to even try other diffing algorithms.
233 *data_blob = std::move(patch);
234 return true;
235 }
236 }
237
238 const uint64_t input_bytes = std::max(utils::BlocksInExtents(src_extents_),
239 utils::BlocksInExtents(dst_extents_)) *
240 kBlockSize;
241
242 for (auto [op_type, limit] : diff_candidates) {
243 if (!config_.OperationEnabled(op_type)) {
244 continue;
245 }
246
247 // Disable the specific diff algorithm when the data is too big.
248 if (input_bytes > limit) {
249 LOG(INFO) << op_type << " ignored, file " << aop->name
250 << " too big: " << input_bytes << " bytes";
251 continue;
252 }
253
254 // Prefer BROTLI_BSDIFF as it gives smaller patch size.
255 if (op_type == InstallOperation::SOURCE_BSDIFF &&
256 config_.OperationEnabled(InstallOperation::BROTLI_BSDIFF)) {
257 op_type = InstallOperation::BROTLI_BSDIFF;
258 }
259
260 switch (op_type) {
261 case InstallOperation::SOURCE_BSDIFF:
262 case InstallOperation::BROTLI_BSDIFF:
263 TEST_AND_RETURN_FALSE(
264 TryBsdiffAndUpdateOperation(op_type, aop, data_blob));
265 break;
266 case InstallOperation::PUFFDIFF:
267 TEST_AND_RETURN_FALSE(TryPuffdiffAndUpdateOperation(aop, data_blob));
268 break;
269 case InstallOperation::ZUCCHINI:
270 TEST_AND_RETURN_FALSE(TryZucchiniAndUpdateOperation(aop, data_blob));
271 break;
272 default:
273 NOTREACHED();
274 }
275 }
276
277 return true;
278 }
279
TryBsdiffAndUpdateOperation(InstallOperation_Type operation_type,AnnotatedOperation * aop,brillo::Blob * data_blob)280 bool BestDiffGenerator::TryBsdiffAndUpdateOperation(
281 InstallOperation_Type operation_type,
282 AnnotatedOperation* aop,
283 brillo::Blob* data_blob) {
284 base::FilePath patch;
285 TEST_AND_RETURN_FALSE(base::CreateTemporaryFile(&patch));
286 ScopedPathUnlinker unlinker(patch.value());
287
288 std::unique_ptr<bsdiff::PatchWriterInterface> bsdiff_patch_writer;
289 if (operation_type == InstallOperation::BROTLI_BSDIFF) {
290 bsdiff_patch_writer = bsdiff::CreateBSDF2PatchWriter(
291 patch.value(), GetUsableCompressorTypes(), kBrotliCompressionQuality);
292 } else {
293 bsdiff_patch_writer = bsdiff::CreateBsdiffPatchWriter(patch.value());
294 }
295
296 brillo::Blob bsdiff_delta;
297 TEST_AND_RETURN_FALSE(0 == bsdiff::bsdiff(old_data_.data(),
298 old_data_.size(),
299 new_data_.data(),
300 new_data_.size(),
301 bsdiff_patch_writer.get(),
302 nullptr));
303
304 TEST_AND_RETURN_FALSE(utils::ReadFile(patch.value(), &bsdiff_delta));
305 TEST_AND_RETURN_FALSE(!bsdiff_delta.empty());
306
307 InstallOperation& operation = aop->op;
308 if (IsDiffOperationBetter(operation,
309 data_blob->size(),
310 bsdiff_delta.size(),
311 src_extents_.size())) {
312 // VABC XOR won't work with compressed files just yet.
313 if (config_.enable_vabc_xor) {
314 StoreExtents(src_extents_, operation.mutable_src_extents());
315 diff_utils::PopulateXorOps(aop, bsdiff_delta);
316 }
317 operation.set_type(operation_type);
318 *data_blob = std::move(bsdiff_delta);
319 }
320 return true;
321 }
322
TryPuffdiffAndUpdateOperation(AnnotatedOperation * aop,brillo::Blob * data_blob)323 bool BestDiffGenerator::TryPuffdiffAndUpdateOperation(AnnotatedOperation* aop,
324 brillo::Blob* data_blob) {
325 // Only Puffdiff if both files have at least one deflate left.
326 if (!old_deflates_.empty() && !new_deflates_.empty()) {
327 brillo::Blob puffdiff_delta;
328 ScopedTempFile temp_file("puffdiff-delta.XXXXXX");
329 // Perform PuffDiff operation.
330 TEST_AND_RETURN_FALSE(puffin::PuffDiff(old_data_,
331 new_data_,
332 old_deflates_,
333 new_deflates_,
334 GetUsableCompressorTypes(),
335 temp_file.path(),
336 &puffdiff_delta));
337 TEST_AND_RETURN_FALSE(!puffdiff_delta.empty());
338
339 InstallOperation& operation = aop->op;
340 if (IsDiffOperationBetter(operation,
341 data_blob->size(),
342 puffdiff_delta.size(),
343 src_extents_.size())) {
344 operation.set_type(InstallOperation::PUFFDIFF);
345 *data_blob = std::move(puffdiff_delta);
346 }
347 }
348 return true;
349 }
350
TryZucchiniAndUpdateOperation(AnnotatedOperation * aop,brillo::Blob * data_blob)351 bool BestDiffGenerator::TryZucchiniAndUpdateOperation(AnnotatedOperation* aop,
352 brillo::Blob* data_blob) {
353 // zip files are ignored for now. We expect puffin to perform better on those.
354 // Investigate whether puffin over zucchini yields better results on those.
355 if (!deflate_utils::IsFileExtensions(
356 aop->name,
357 {".ko",
358 ".so",
359 ".art",
360 ".odex",
361 ".vdex",
362 "<kernel>",
363 "<modem-partition>",
364 /*, ".capex",".jar", ".apk", ".apex"*/})) {
365 return true;
366 }
367 zucchini::ConstBufferView src_bytes(old_data_.data(), old_data_.size());
368 zucchini::ConstBufferView dst_bytes(new_data_.data(), new_data_.size());
369
370 zucchini::EnsemblePatchWriter patch_writer(src_bytes, dst_bytes);
371 auto status = zucchini::GenerateBuffer(src_bytes, dst_bytes, &patch_writer);
372 TEST_AND_RETURN_FALSE(status == zucchini::status::kStatusSuccess);
373
374 brillo::Blob zucchini_delta(patch_writer.SerializedSize());
375 patch_writer.SerializeInto({zucchini_delta.data(), zucchini_delta.size()});
376
377 // Compress the delta with brotli.
378 // TODO(197361113) support compressing the delta with different algorithms,
379 // similar to the usage in puffin.
380 brillo::Blob compressed_delta;
381 TEST_AND_RETURN_FALSE(puffin::BrotliEncode(
382 zucchini_delta.data(), zucchini_delta.size(), &compressed_delta));
383
384 InstallOperation& operation = aop->op;
385 if (IsDiffOperationBetter(operation,
386 data_blob->size(),
387 compressed_delta.size(),
388 src_extents_.size())) {
389 operation.set_type(InstallOperation::ZUCCHINI);
390 *data_blob = std::move(compressed_delta);
391 }
392
393 return true;
394 }
395
396 // This class encapsulates a file delta processing thread work. The
397 // processor computes the delta between the source and target files;
398 // and write the compressed delta to the blob.
399 class FileDeltaProcessor : public base::DelegateSimpleThread::Delegate {
400 public:
FileDeltaProcessor(const string & old_part,const string & new_part,const PayloadGenerationConfig & config,const File & old_extents,const File & new_extents,const string & name,ssize_t chunk_blocks,BlobFileWriter * blob_file)401 FileDeltaProcessor(const string& old_part,
402 const string& new_part,
403 const PayloadGenerationConfig& config,
404 const File& old_extents,
405 const File& new_extents,
406 const string& name,
407 ssize_t chunk_blocks,
408 BlobFileWriter* blob_file)
409 : old_part_(old_part),
410 new_part_(new_part),
411 config_(config),
412 old_extents_(old_extents),
413 new_extents_(new_extents),
414 new_extents_blocks_(utils::BlocksInExtents(new_extents.extents)),
415 name_(name),
416 chunk_blocks_(chunk_blocks),
417 blob_file_(blob_file) {}
418
operator >(const FileDeltaProcessor & other) const419 bool operator>(const FileDeltaProcessor& other) const {
420 return new_extents_blocks_ > other.new_extents_blocks_;
421 }
422
423 ~FileDeltaProcessor() override = default;
424
425 // Overrides DelegateSimpleThread::Delegate.
426 // Calculate the list of operations and write their corresponding deltas to
427 // the blob_file.
428 void Run() override;
429
430 // Merge each file processor's ops list to aops.
431 bool MergeOperation(vector<AnnotatedOperation>* aops);
432
433 private:
434 const string& old_part_; // NOLINT(runtime/member_string_references)
435 const string& new_part_; // NOLINT(runtime/member_string_references)
436 const PayloadGenerationConfig& config_;
437
438 // The block ranges of the old/new file within the src/tgt image
439 const File old_extents_;
440 const File new_extents_;
441 const size_t new_extents_blocks_;
442 const string name_;
443 // Block limit of one aop.
444 const ssize_t chunk_blocks_;
445 BlobFileWriter* blob_file_;
446
447 // The list of ops to reach the new file from the old file.
448 vector<AnnotatedOperation> file_aops_;
449
450 bool failed_ = false;
451
452 DISALLOW_COPY_AND_ASSIGN(FileDeltaProcessor);
453 };
454
Run()455 void FileDeltaProcessor::Run() {
456 TEST_AND_RETURN(blob_file_ != nullptr);
457 base::TimeTicks start = base::TimeTicks::Now();
458
459 if (!DeltaReadFile(&file_aops_,
460 old_part_,
461 new_part_,
462 old_extents_,
463 new_extents_,
464 chunk_blocks_,
465 config_,
466 blob_file_)) {
467 LOG(ERROR) << "Failed to generate delta for " << name_ << " ("
468 << new_extents_blocks_ << " blocks)";
469 failed_ = true;
470 return;
471 }
472
473 if (!ABGenerator::FragmentOperations(
474 config_.version, &file_aops_, new_part_, blob_file_)) {
475 LOG(ERROR) << "Failed to fragment operations for " << name_;
476 failed_ = true;
477 return;
478 }
479
480 LOG(INFO) << "Encoded file " << name_ << " (" << new_extents_blocks_
481 << " blocks) in " << (base::TimeTicks::Now() - start);
482 }
483
MergeOperation(vector<AnnotatedOperation> * aops)484 bool FileDeltaProcessor::MergeOperation(vector<AnnotatedOperation>* aops) {
485 if (failed_)
486 return false;
487 std::move(file_aops_.begin(), file_aops_.end(), std::back_inserter(*aops));
488 return true;
489 }
490
GetOldFile(const map<string,FilesystemInterface::File> & old_files_map,const string & new_file_name)491 FilesystemInterface::File GetOldFile(
492 const map<string, FilesystemInterface::File>& old_files_map,
493 const string& new_file_name) {
494 if (old_files_map.empty())
495 return {};
496
497 auto old_file_iter = old_files_map.find(new_file_name);
498 if (old_file_iter != old_files_map.end())
499 return old_file_iter->second;
500
501 // No old file matches the new file name. Use a similar file with the
502 // shortest levenshtein distance instead.
503 // This works great if the file has version number in it, but even for
504 // a completely new file, using a similar file can still help.
505 int min_distance =
506 LevenshteinDistance(new_file_name, old_files_map.begin()->first);
507 const FilesystemInterface::File* old_file = &old_files_map.begin()->second;
508 for (const auto& pair : old_files_map) {
509 int distance = LevenshteinDistance(new_file_name, pair.first);
510 if (distance < min_distance) {
511 min_distance = distance;
512 old_file = &pair.second;
513 }
514 }
515 LOG(INFO) << "Using " << old_file->name << " as source for " << new_file_name;
516 return *old_file;
517 }
518
RemoveDuplicateBlocks(const std::vector<Extent> & extents)519 std::vector<Extent> RemoveDuplicateBlocks(const std::vector<Extent>& extents) {
520 ExtentRanges extent_set;
521 std::vector<Extent> ret;
522 for (const auto& extent : extents) {
523 auto vec = FilterExtentRanges({extent}, extent_set);
524 ret.insert(ret.end(),
525 std::make_move_iterator(vec.begin()),
526 std::make_move_iterator(vec.end()));
527 extent_set.AddExtent(extent);
528 }
529 return ret;
530 }
531
DeltaReadPartition(vector<AnnotatedOperation> * aops,const PartitionConfig & old_part,const PartitionConfig & new_part,ssize_t hard_chunk_blocks,size_t soft_chunk_blocks,const PayloadGenerationConfig & config,BlobFileWriter * blob_file)532 bool DeltaReadPartition(vector<AnnotatedOperation>* aops,
533 const PartitionConfig& old_part,
534 const PartitionConfig& new_part,
535 ssize_t hard_chunk_blocks,
536 size_t soft_chunk_blocks,
537 const PayloadGenerationConfig& config,
538 BlobFileWriter* blob_file) {
539 const auto& version = config.version;
540 ExtentRanges old_visited_blocks;
541 ExtentRanges new_visited_blocks;
542
543 // If verity is enabled, mark those blocks as visited to skip generating
544 // operations for them.
545 if (version.minor >= kVerityMinorPayloadVersion &&
546 !new_part.verity.IsEmpty()) {
547 LOG(INFO) << "Skipping verity hash tree blocks: "
548 << ExtentsToString({new_part.verity.hash_tree_extent});
549 new_visited_blocks.AddExtent(new_part.verity.hash_tree_extent);
550 LOG(INFO) << "Skipping verity FEC blocks: "
551 << ExtentsToString({new_part.verity.fec_extent});
552 new_visited_blocks.AddExtent(new_part.verity.fec_extent);
553 }
554
555 const bool puffdiff_allowed =
556 config.OperationEnabled(InstallOperation::PUFFDIFF);
557
558 TEST_AND_RETURN_FALSE(new_part.fs_interface);
559 vector<FilesystemInterface::File> new_files;
560 TEST_AND_RETURN_FALSE(deflate_utils::PreprocessPartitionFiles(
561 new_part, &new_files, puffdiff_allowed));
562
563 ExtentRanges old_zero_blocks;
564 // Prematurely removing moved blocks will render compression info useless.
565 // Even if a single block inside a 100MB file is filtered out, the entire
566 // 100MB file can't be decompressed. In this case we will fallback to BSDIFF,
567 // which performs much worse than LZ4diff. It's better to let LZ4DIFF perform
568 // decompression, and let underlying BSDIFF to take care of moved blocks.
569 // TODO(b/206729162) Implement block filtering with compression block info
570 const auto no_compressed_files =
571 std::all_of(new_files.begin(), new_files.end(), [](const File& a) {
572 return a.compressed_file_info.blocks.empty();
573 });
574 if (!config.OperationEnabled(InstallOperation::LZ4DIFF_BSDIFF) ||
575 no_compressed_files) {
576 TEST_AND_RETURN_FALSE(DeltaMovedAndZeroBlocks(aops,
577 old_part.path,
578 new_part.path,
579 old_part.size / kBlockSize,
580 new_part.size / kBlockSize,
581 soft_chunk_blocks,
582 config,
583 blob_file,
584 &old_visited_blocks,
585 &new_visited_blocks,
586 &old_zero_blocks));
587 }
588
589 map<string, FilesystemInterface::File> old_files_map;
590 if (old_part.fs_interface) {
591 vector<FilesystemInterface::File> old_files;
592 TEST_AND_RETURN_FALSE(deflate_utils::PreprocessPartitionFiles(
593 old_part, &old_files, puffdiff_allowed));
594 for (const FilesystemInterface::File& file : old_files)
595 old_files_map[file.name] = file;
596 }
597
598 list<FileDeltaProcessor> file_delta_processors;
599
600 // The processing is very straightforward here, we generate operations for
601 // every file (and pseudo-file such as the metadata) in the new filesystem
602 // based on the file with the same name in the old filesystem, if any.
603 // Files with overlapping data blocks (like hardlinks or filesystems with tail
604 // packing or compression where the blocks store more than one file) are only
605 // generated once in the new image, but are also used only once from the old
606 // image due to some simplifications (see below).
607 for (const FilesystemInterface::File& new_file : new_files) {
608 // Ignore the files in the new filesystem without blocks. Symlinks with
609 // data blocks (for example, symlinks bigger than 60 bytes in ext2) are
610 // handled as normal files. We also ignore blocks that were already
611 // processed by a previous file.
612 vector<Extent> new_file_extents =
613 FilterExtentRanges(new_file.extents, new_visited_blocks);
614 new_visited_blocks.AddExtents(new_file_extents);
615
616 if (new_file_extents.empty())
617 continue;
618
619 FilesystemInterface::File old_file =
620 GetOldFile(old_files_map, new_file.name);
621 old_visited_blocks.AddExtents(old_file.extents);
622
623 // TODO(b/177104308) Filtering |new_file_extents| might confuse puffdiff, as
624 // we might filterout extents with deflate streams. PUFFDIFF is written with
625 // that in mind, so it will try to adapt to the filtered extents.
626 // Correctness is intact, but might yield larger patch sizes. From what we
627 // experimented, this has little impact on OTA size. Meanwhile, XOR ops
628 // depend on this. So filter out duplicate blocks from new file.
629 // TODO(b/194237829) |old_file.extents| is used instead of the de-duped
630 // |old_file_extents|. This is because zucchini diffing algorithm works
631 // better when given the full source file.
632 // Current logic:
633 // 1. src extent is completely unfiltered. It may contain
634 // duplicate blocks across files, within files, it may contain zero blocks,
635 // etc.
636 // 2. dst extent is completely filtered, no duplicate blocks or zero blocks
637 // whatsoever.
638 auto filtered_new_file = new_file;
639 filtered_new_file.extents = RemoveDuplicateBlocks(new_file_extents);
640 file_delta_processors.emplace_back(old_part.path,
641 new_part.path,
642 config,
643 std::move(old_file),
644 std::move(filtered_new_file),
645 new_file.name, // operation name
646 hard_chunk_blocks,
647 blob_file);
648 }
649 // Process all the blocks not included in any file. We provided all the unused
650 // blocks in the old partition as available data.
651 vector<Extent> new_unvisited = {
652 ExtentForRange(0, new_part.size / kBlockSize)};
653 new_unvisited = FilterExtentRanges(new_unvisited, new_visited_blocks);
654 if (!new_unvisited.empty()) {
655 vector<Extent> old_unvisited;
656 if (old_part.fs_interface) {
657 old_unvisited.push_back(ExtentForRange(0, old_part.size / kBlockSize));
658 old_unvisited = FilterExtentRanges(old_unvisited, old_visited_blocks);
659 }
660
661 LOG(INFO) << "Scanning " << utils::BlocksInExtents(new_unvisited)
662 << " unwritten blocks using chunk size of " << soft_chunk_blocks
663 << " blocks.";
664 // We use the soft_chunk_blocks limit for the <non-file-data> as we don't
665 // really know the structure of this data and we should not expect it to
666 // have redundancy between partitions.
667 File old_file;
668 old_file.extents = old_unvisited;
669 File new_file;
670 new_file.extents = RemoveDuplicateBlocks(new_unvisited);
671 file_delta_processors.emplace_back(old_part.path,
672 new_part.path,
673 config,
674 old_file,
675 new_file,
676 "<non-file-data>", // operation name
677 soft_chunk_blocks,
678 blob_file);
679 }
680
681 size_t max_threads = GetMaxThreads();
682
683 // Sort the files in descending order based on number of new blocks to make
684 // sure we start the largest ones first.
685 if (file_delta_processors.size() > max_threads) {
686 file_delta_processors.sort(std::greater<FileDeltaProcessor>());
687 }
688
689 base::DelegateSimpleThreadPool thread_pool("incremental-update-generator",
690 max_threads);
691 thread_pool.Start();
692 for (auto& processor : file_delta_processors) {
693 thread_pool.AddWork(&processor);
694 }
695 thread_pool.JoinAll();
696
697 for (auto& processor : file_delta_processors) {
698 TEST_AND_RETURN_FALSE(processor.MergeOperation(aops));
699 }
700
701 return true;
702 }
703
DeltaMovedAndZeroBlocks(vector<AnnotatedOperation> * aops,const string & old_part,const string & new_part,size_t old_num_blocks,size_t new_num_blocks,ssize_t chunk_blocks,const PayloadGenerationConfig & config,BlobFileWriter * blob_file,ExtentRanges * old_visited_blocks,ExtentRanges * new_visited_blocks,ExtentRanges * old_zero_blocks)704 bool DeltaMovedAndZeroBlocks(vector<AnnotatedOperation>* aops,
705 const string& old_part,
706 const string& new_part,
707 size_t old_num_blocks,
708 size_t new_num_blocks,
709 ssize_t chunk_blocks,
710 const PayloadGenerationConfig& config,
711 BlobFileWriter* blob_file,
712 ExtentRanges* old_visited_blocks,
713 ExtentRanges* new_visited_blocks,
714 ExtentRanges* old_zero_blocks) {
715 vector<BlockMapping::BlockId> old_block_ids;
716 vector<BlockMapping::BlockId> new_block_ids;
717 TEST_AND_RETURN_FALSE(MapPartitionBlocks(old_part,
718 new_part,
719 old_num_blocks * kBlockSize,
720 new_num_blocks * kBlockSize,
721 kBlockSize,
722 &old_block_ids,
723 &new_block_ids));
724
725 // A mapping from the block_id to the list of block numbers with that block id
726 // in the old partition. This is used to lookup where in the old partition
727 // is a block from the new partition.
728 map<BlockMapping::BlockId, vector<uint64_t>> old_blocks_map;
729
730 for (uint64_t block = old_num_blocks; block-- > 0;) {
731 if (old_block_ids[block] != 0 && !old_visited_blocks->ContainsBlock(block))
732 old_blocks_map[old_block_ids[block]].push_back(block);
733
734 // Mark all zeroed blocks in the old image as "used" since it doesn't make
735 // any sense to spend I/O to read zeros from the source partition and more
736 // importantly, these could sometimes be blocks discarded in the SSD which
737 // would read non-zero values.
738 if (old_block_ids[block] == 0)
739 old_zero_blocks->AddBlock(block);
740 }
741 old_visited_blocks->AddRanges(*old_zero_blocks);
742
743 // The collection of blocks in the new partition with just zeros. This is a
744 // common case for free-space that's also problematic for bsdiff, so we want
745 // to optimize it using REPLACE_BZ operations. The blob for a REPLACE_BZ of
746 // just zeros is so small that it doesn't make sense to spend the I/O reading
747 // zeros from the old partition.
748 vector<Extent> new_zeros;
749
750 vector<Extent> old_identical_blocks;
751 vector<Extent> new_identical_blocks;
752
753 for (uint64_t block = 0; block < new_num_blocks; block++) {
754 // Only produce operations for blocks that were not yet visited.
755 if (new_visited_blocks->ContainsBlock(block))
756 continue;
757 if (new_block_ids[block] == 0) {
758 AppendBlockToExtents(&new_zeros, block);
759 continue;
760 }
761
762 auto old_blocks_map_it = old_blocks_map.find(new_block_ids[block]);
763 // Check if the block exists in the old partition at all.
764 if (old_blocks_map_it == old_blocks_map.end() ||
765 old_blocks_map_it->second.empty())
766 continue;
767
768 AppendBlockToExtents(&old_identical_blocks,
769 old_blocks_map_it->second.back());
770 AppendBlockToExtents(&new_identical_blocks, block);
771 }
772
773 if (chunk_blocks == -1)
774 chunk_blocks = new_num_blocks;
775
776 // Produce operations for the zero blocks split per output extent.
777 size_t num_ops = aops->size();
778 new_visited_blocks->AddExtents(new_zeros);
779 for (const Extent& extent : new_zeros) {
780 if (config.OperationEnabled(InstallOperation::ZERO)) {
781 for (uint64_t offset = 0; offset < extent.num_blocks();
782 offset += chunk_blocks) {
783 uint64_t num_blocks =
784 std::min(static_cast<uint64_t>(extent.num_blocks()) - offset,
785 static_cast<uint64_t>(chunk_blocks));
786 InstallOperation operation;
787 operation.set_type(InstallOperation::ZERO);
788 *(operation.add_dst_extents()) =
789 ExtentForRange(extent.start_block() + offset, num_blocks);
790 aops->push_back({.name = "<zeros>", .op = operation});
791 }
792 } else {
793 File old_file;
794 File new_file;
795 new_file.name = "<zeros>";
796 new_file.extents = {extent};
797 TEST_AND_RETURN_FALSE(DeltaReadFile(aops,
798 "",
799 new_part,
800 old_file, // old_extents
801 new_file, // new_extents
802 chunk_blocks,
803 config,
804 blob_file));
805 }
806 }
807 LOG(INFO) << "Produced " << (aops->size() - num_ops) << " operations for "
808 << utils::BlocksInExtents(new_zeros) << " zeroed blocks";
809
810 // Produce MOVE/SOURCE_COPY operations for the moved blocks.
811 num_ops = aops->size();
812 uint64_t used_blocks = 0;
813 old_visited_blocks->AddExtents(old_identical_blocks);
814 new_visited_blocks->AddExtents(new_identical_blocks);
815 for (const Extent& extent : new_identical_blocks) {
816 // We split the operation at the extent boundary or when bigger than
817 // chunk_blocks.
818 for (uint64_t op_block_offset = 0; op_block_offset < extent.num_blocks();
819 op_block_offset += chunk_blocks) {
820 aops->emplace_back();
821 AnnotatedOperation* aop = &aops->back();
822 aop->name = "<identical-blocks>";
823 aop->op.set_type(InstallOperation::SOURCE_COPY);
824
825 uint64_t chunk_num_blocks =
826 std::min(static_cast<uint64_t>(extent.num_blocks()) - op_block_offset,
827 static_cast<uint64_t>(chunk_blocks));
828
829 // The current operation represents the move/copy operation for the
830 // sublist starting at |used_blocks| of length |chunk_num_blocks| where
831 // the src and dst are from |old_identical_blocks| and
832 // |new_identical_blocks| respectively.
833 StoreExtents(
834 ExtentsSublist(old_identical_blocks, used_blocks, chunk_num_blocks),
835 aop->op.mutable_src_extents());
836
837 Extent* op_dst_extent = aop->op.add_dst_extents();
838 op_dst_extent->set_start_block(extent.start_block() + op_block_offset);
839 op_dst_extent->set_num_blocks(chunk_num_blocks);
840 CHECK(
841 vector<Extent>{*op_dst_extent} == // NOLINT(whitespace/braces)
842 ExtentsSublist(new_identical_blocks, used_blocks, chunk_num_blocks));
843
844 used_blocks += chunk_num_blocks;
845 }
846 }
847 LOG(INFO) << "Produced " << (aops->size() - num_ops) << " operations for "
848 << used_blocks << " identical blocks moved";
849
850 return true;
851 }
852
DeltaReadFile(std::vector<AnnotatedOperation> * aops,const std::string & old_part,const std::string & new_part,const File & old_file,const File & new_file,ssize_t chunk_blocks,const PayloadGenerationConfig & config,BlobFileWriter * blob_file)853 bool DeltaReadFile(std::vector<AnnotatedOperation>* aops,
854 const std::string& old_part,
855 const std::string& new_part,
856 const File& old_file,
857 const File& new_file,
858 ssize_t chunk_blocks,
859 const PayloadGenerationConfig& config,
860 BlobFileWriter* blob_file) {
861 const auto& old_extents = old_file.extents;
862 const auto& new_extents = new_file.extents;
863 const auto& name = new_file.name;
864
865 brillo::Blob data;
866
867 uint64_t total_blocks = utils::BlocksInExtents(new_extents);
868 if (chunk_blocks == 0) {
869 LOG(ERROR) << "Invalid number of chunk_blocks. Cannot be 0.";
870 return false;
871 }
872
873 if (chunk_blocks == -1)
874 chunk_blocks = total_blocks;
875
876 for (uint64_t block_offset = 0; block_offset < total_blocks;
877 block_offset += chunk_blocks) {
878 // Split the old/new file in the same chunks. Note that this could drop
879 // some information from the old file used for the new chunk. If the old
880 // file is smaller (or even empty when there's no old file) the chunk will
881 // also be empty.
882 vector<Extent> old_extents_chunk =
883 ExtentsSublist(old_extents, block_offset, chunk_blocks);
884 vector<Extent> new_extents_chunk =
885 ExtentsSublist(new_extents, block_offset, chunk_blocks);
886 NormalizeExtents(&old_extents_chunk);
887 NormalizeExtents(&new_extents_chunk);
888
889 // Now, insert into the list of operations.
890 AnnotatedOperation aop;
891 aop.name = new_file.name;
892 TEST_AND_RETURN_FALSE(ReadExtentsToDiff(old_part,
893 new_part,
894 old_extents_chunk,
895 new_extents_chunk,
896 old_file,
897 new_file,
898 config,
899 &data,
900 &aop));
901
902 // Check if the operation writes nothing.
903 if (aop.op.dst_extents_size() == 0) {
904 LOG(ERROR) << "Empty non-MOVE operation";
905 return false;
906 }
907
908 if (static_cast<uint64_t>(chunk_blocks) < total_blocks) {
909 aop.name = base::StringPrintf(
910 "%s:%" PRIu64, name.c_str(), block_offset / chunk_blocks);
911 }
912
913 // Write the data
914 TEST_AND_RETURN_FALSE(aop.SetOperationBlob(data, blob_file));
915 aops->emplace_back(aop);
916 }
917 return true;
918 }
919
GenerateBestFullOperation(const brillo::Blob & new_data,const PayloadVersion & version,brillo::Blob * out_blob,InstallOperation::Type * out_type)920 bool GenerateBestFullOperation(const brillo::Blob& new_data,
921 const PayloadVersion& version,
922 brillo::Blob* out_blob,
923 InstallOperation::Type* out_type) {
924 if (new_data.empty())
925 return false;
926
927 if (version.OperationAllowed(InstallOperation::ZERO) &&
928 std::all_of(
929 new_data.begin(), new_data.end(), [](uint8_t x) { return x == 0; })) {
930 // The read buffer is all zeros, so produce a ZERO operation. No need to
931 // check other types of operations in this case.
932 *out_blob = brillo::Blob();
933 *out_type = InstallOperation::ZERO;
934 return true;
935 }
936
937 bool out_blob_set = false;
938
939 // Try compressing |new_data| with xz first.
940 if (version.OperationAllowed(InstallOperation::REPLACE_XZ)) {
941 brillo::Blob new_data_xz;
942 if (XzCompress(new_data, &new_data_xz) && !new_data_xz.empty()) {
943 *out_type = InstallOperation::REPLACE_XZ;
944 *out_blob = std::move(new_data_xz);
945 out_blob_set = true;
946 }
947 }
948
949 // Try compressing it with bzip2.
950 if (version.OperationAllowed(InstallOperation::REPLACE_BZ)) {
951 brillo::Blob new_data_bz;
952 // TODO(deymo): Implement some heuristic to determine if it is worth trying
953 // to compress the blob with bzip2 if we already have a good REPLACE_XZ.
954 if (BzipCompress(new_data, &new_data_bz) && !new_data_bz.empty() &&
955 (!out_blob_set || out_blob->size() > new_data_bz.size())) {
956 // A REPLACE_BZ is better or nothing else was set.
957 *out_type = InstallOperation::REPLACE_BZ;
958 *out_blob = std::move(new_data_bz);
959 out_blob_set = true;
960 }
961 }
962
963 // If nothing else worked or it was badly compressed we try a REPLACE.
964 if (!out_blob_set || out_blob->size() >= new_data.size()) {
965 *out_type = InstallOperation::REPLACE;
966 // This needs to make a copy of the data in the case bzip or xz didn't
967 // compress well, which is not the common case so the performance hit is
968 // low.
969 *out_blob = new_data;
970 }
971 return true;
972 }
973
974 // Decide which blocks are similar from bsdiff patch.
975 // Blocks included in out_op->xor_map will be converted to COW_XOR during OTA
976 // installation
PopulateXorOps(AnnotatedOperation * aop,const uint8_t * data,size_t size)977 bool PopulateXorOps(AnnotatedOperation* aop, const uint8_t* data, size_t size) {
978 bsdiff::BsdiffPatchReader patch_reader;
979 TEST_AND_RETURN_FALSE(patch_reader.Init(data, size));
980 ControlEntry entry;
981 size_t new_off = 0;
982 int64_t old_off = 0;
983 auto& xor_ops = aop->xor_ops;
984 size_t total_xor_blocks = 0;
985 const auto new_file_size =
986 utils::BlocksInExtents(aop->op.dst_extents()) * kBlockSize;
987 while (new_off < new_file_size) {
988 if (!patch_reader.ParseControlEntry(&entry)) {
989 LOG(ERROR)
990 << "Exhausted bsdiff patch data before reaching end of new file. "
991 "Current position: "
992 << new_off << " new file size: " << new_file_size;
993 return false;
994 }
995 if (old_off >= 0) {
996 auto dst_off_aligned = utils::RoundUp(new_off, kBlockSize);
997 const auto skip = dst_off_aligned - new_off;
998 auto src_off = old_off + skip;
999 const size_t chunk_size =
1000 entry.diff_size - std::min(skip, entry.diff_size);
1001 const auto xor_blocks = (chunk_size + kBlockSize / 2) / kBlockSize;
1002 total_xor_blocks += xor_blocks;
1003 // Append chunk_size/kBlockSize number of XOR blocks, subject to rounding
1004 // rules: if decimal part of that division is >= 0.5, round up.
1005 for (size_t i = 0; i < xor_blocks; i++) {
1006 AppendXorBlock(
1007 &xor_ops,
1008 GetNthBlock(aop->op.src_extents(), src_off / kBlockSize),
1009 GetNthBlock(aop->op.dst_extents(), dst_off_aligned / kBlockSize),
1010 src_off % kBlockSize);
1011 src_off += kBlockSize;
1012 dst_off_aligned += kBlockSize;
1013 }
1014 }
1015
1016 old_off += entry.diff_size + entry.offset_increment;
1017 new_off += entry.diff_size + entry.extra_size;
1018 }
1019
1020 for (auto& op : xor_ops) {
1021 CHECK_EQ(op.src_extent().num_blocks(), op.dst_extent().num_blocks());
1022 // If |src_offset| is greater than 0, then we are reading 1
1023 // extra block at the end of src_extent. This dependency must
1024 // be honored during merge sequence generation, or we can end
1025 // up with a corrupted device after merge.
1026 if (op.src_offset() > 0) {
1027 op.mutable_src_extent()->set_num_blocks(op.dst_extent().num_blocks() + 1);
1028 }
1029 }
1030
1031 if (xor_ops.size() > 0) {
1032 // TODO(177104308) Filter out duplicate blocks in XOR op
1033 LOG(INFO) << "Added " << total_xor_blocks << " XOR blocks, "
1034 << total_xor_blocks * 100.0f / new_off * kBlockSize
1035 << "% of blocks in this InstallOp are XOR";
1036 }
1037 return true;
1038 }
1039
ReadExtentsToDiff(const string & old_part,const string & new_part,const vector<Extent> & src_extents,const vector<Extent> & dst_extents,const File & old_file,const File & new_file,const PayloadGenerationConfig & config,brillo::Blob * out_data,AnnotatedOperation * out_op)1040 bool ReadExtentsToDiff(const string& old_part,
1041 const string& new_part,
1042 const vector<Extent>& src_extents,
1043 const vector<Extent>& dst_extents,
1044 const File& old_file,
1045 const File& new_file,
1046 const PayloadGenerationConfig& config,
1047 brillo::Blob* out_data,
1048 AnnotatedOperation* out_op) {
1049 const auto& version = config.version;
1050 AnnotatedOperation& aop = *out_op;
1051 InstallOperation& operation = aop.op;
1052
1053 // We read blocks from old_extents and write blocks to new_extents.
1054 const uint64_t blocks_to_read = utils::BlocksInExtents(src_extents);
1055 const uint64_t blocks_to_write = utils::BlocksInExtents(dst_extents);
1056
1057 // All operations have dst_extents.
1058 StoreExtents(dst_extents, operation.mutable_dst_extents());
1059
1060 // Read in bytes from new data.
1061 brillo::Blob new_data;
1062 TEST_AND_RETURN_FALSE(utils::ReadExtents(new_part,
1063 dst_extents,
1064 &new_data,
1065 kBlockSize * blocks_to_write,
1066 kBlockSize));
1067 TEST_AND_RETURN_FALSE(!new_data.empty());
1068
1069 // Data blob that will be written to delta file.
1070 brillo::Blob data_blob;
1071
1072 // Try generating a full operation for the given new data, regardless of the
1073 // old_data.
1074 InstallOperation::Type op_type;
1075 TEST_AND_RETURN_FALSE(
1076 GenerateBestFullOperation(new_data, version, &data_blob, &op_type));
1077 operation.set_type(op_type);
1078
1079 if (blocks_to_read > 0) {
1080 brillo::Blob old_data;
1081 // Read old data.
1082 TEST_AND_RETURN_FALSE(utils::ReadExtents(old_part,
1083 src_extents,
1084 &old_data,
1085 kBlockSize * blocks_to_read,
1086 kBlockSize));
1087 if (old_data == new_data) {
1088 // No change in data.
1089 operation.set_type(InstallOperation::SOURCE_COPY);
1090 data_blob = brillo::Blob();
1091 } else if (IsDiffOperationBetter(
1092 operation, data_blob.size(), 0, src_extents.size())) {
1093 // No point in trying diff if zero blob size diff operation is
1094 // still worse than replace.
1095
1096 BestDiffGenerator best_diff_generator(old_data,
1097 new_data,
1098 src_extents,
1099 dst_extents,
1100 old_file,
1101 new_file,
1102 config);
1103 if (!best_diff_generator.GenerateBestDiffOperation(&aop, &data_blob)) {
1104 LOG(INFO) << "Failed to generate diff for " << new_file.name;
1105 return false;
1106 }
1107 }
1108 }
1109
1110 // WARNING: We always set legacy |src_length| and |dst_length| fields for
1111 // BSDIFF. For SOURCE_BSDIFF we only set them for minor version 3 and
1112 // lower. This is needed because we used to use these two parameters in the
1113 // SOURCE_BSDIFF for minor version 3 and lower, but we do not need them
1114 // anymore in higher minor versions. This means if we stop adding these
1115 // parameters for those minor versions, the delta payloads will be invalid.
1116 if (operation.type() == InstallOperation::SOURCE_BSDIFF &&
1117 version.minor <= kOpSrcHashMinorPayloadVersion) {
1118 operation.set_src_length(blocks_to_read * kBlockSize);
1119 operation.set_dst_length(blocks_to_write * kBlockSize);
1120 }
1121
1122 // Embed extents in the operation. Replace (all variants), zero and discard
1123 // operations should not have source extents.
1124 if (!IsNoSourceOperation(operation.type())) {
1125 if (operation.src_extents_size() == 0) {
1126 StoreExtents(src_extents, operation.mutable_src_extents());
1127 }
1128 } else {
1129 operation.clear_src_extents();
1130 }
1131
1132 *out_data = std::move(data_blob);
1133 *out_op = aop;
1134 return true;
1135 }
1136
IsAReplaceOperation(InstallOperation::Type op_type)1137 bool IsAReplaceOperation(InstallOperation::Type op_type) {
1138 return (op_type == InstallOperation::REPLACE ||
1139 op_type == InstallOperation::REPLACE_BZ ||
1140 op_type == InstallOperation::REPLACE_XZ);
1141 }
1142
IsNoSourceOperation(InstallOperation::Type op_type)1143 bool IsNoSourceOperation(InstallOperation::Type op_type) {
1144 return (IsAReplaceOperation(op_type) || op_type == InstallOperation::ZERO ||
1145 op_type == InstallOperation::DISCARD);
1146 }
1147
InitializePartitionInfo(const PartitionConfig & part,PartitionInfo * info)1148 bool InitializePartitionInfo(const PartitionConfig& part, PartitionInfo* info) {
1149 info->set_size(part.size);
1150 HashCalculator hasher;
1151 TEST_AND_RETURN_FALSE(hasher.UpdateFile(part.path, part.size) ==
1152 static_cast<off_t>(part.size));
1153 TEST_AND_RETURN_FALSE(hasher.Finalize());
1154 const brillo::Blob& hash = hasher.raw_hash();
1155 info->set_hash(hash.data(), hash.size());
1156 LOG(INFO) << part.path << ": size=" << part.size
1157 << " hash=" << HexEncode(hash);
1158 return true;
1159 }
1160
CompareAopsByDestination(AnnotatedOperation first_aop,AnnotatedOperation second_aop)1161 bool CompareAopsByDestination(AnnotatedOperation first_aop,
1162 AnnotatedOperation second_aop) {
1163 // We want empty operations to be at the end of the payload.
1164 if (!first_aop.op.dst_extents().size() || !second_aop.op.dst_extents().size())
1165 return ((!first_aop.op.dst_extents().size()) <
1166 (!second_aop.op.dst_extents().size()));
1167 uint32_t first_dst_start = first_aop.op.dst_extents(0).start_block();
1168 uint32_t second_dst_start = second_aop.op.dst_extents(0).start_block();
1169 return first_dst_start < second_dst_start;
1170 }
1171
IsExtFilesystem(const string & device)1172 bool IsExtFilesystem(const string& device) {
1173 brillo::Blob header;
1174 // See include/linux/ext2_fs.h for more details on the structure. We obtain
1175 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
1176 // library.
1177 if (!utils::ReadFileChunk(
1178 device, 0, SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE, &header) ||
1179 header.size() < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
1180 return false;
1181
1182 const uint8_t* superblock = header.data() + SUPERBLOCK_OFFSET;
1183
1184 // ext3_fs.h: ext3_super_block.s_blocks_count
1185 uint32_t block_count =
1186 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
1187
1188 // ext3_fs.h: ext3_super_block.s_log_block_size
1189 uint32_t log_block_size =
1190 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
1191
1192 // ext3_fs.h: ext3_super_block.s_magic
1193 uint16_t magic =
1194 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
1195
1196 block_count = le32toh(block_count);
1197 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
1198 magic = le16toh(magic);
1199
1200 if (magic != EXT2_SUPER_MAGIC)
1201 return false;
1202
1203 // Validation check the parameters.
1204 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
1205 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
1206 TEST_AND_RETURN_FALSE(block_count > 0);
1207 return true;
1208 }
1209
1210 // Return the number of CPUs on the machine, and 4 threads in minimum.
GetMaxThreads()1211 size_t GetMaxThreads() {
1212 return std::max(sysconf(_SC_NPROCESSORS_ONLN), 4L);
1213 }
1214
1215 } // namespace diff_utils
1216
1217 } // namespace chromeos_update_engine
1218