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