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