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 #if defined(__clang__)
21 // TODO(*): Remove these pragmas when b/35721782 is fixed.
22 #pragma clang diagnostic push
23 #pragma clang diagnostic ignored "-Wmacro-redefined"
24 #endif
25 #include <ext2fs/ext2fs.h>
26 #if defined(__clang__)
27 #pragma clang diagnostic pop
28 #endif
29 #include <unistd.h>
30 
31 #include <algorithm>
32 #include <functional>
33 #include <list>
34 #include <map>
35 #include <memory>
36 #include <numeric>
37 #include <utility>
38 
39 #include <base/files/file_util.h>
40 #include <base/format_macros.h>
41 #include <base/strings/string_util.h>
42 #include <base/strings/stringprintf.h>
43 #include <base/threading/simple_thread.h>
44 #include <base/time/time.h>
45 #include <brillo/data_encoding.h>
46 #include <bsdiff/bsdiff.h>
47 #include <bsdiff/patch_writer_factory.h>
48 #include <puffin/utils.h>
49 
50 #include "update_engine/common/hash_calculator.h"
51 #include "update_engine/common/subprocess.h"
52 #include "update_engine/common/utils.h"
53 #include "update_engine/payload_consumer/payload_constants.h"
54 #include "update_engine/payload_generator/ab_generator.h"
55 #include "update_engine/payload_generator/block_mapping.h"
56 #include "update_engine/payload_generator/bzip.h"
57 #include "update_engine/payload_generator/deflate_utils.h"
58 #include "update_engine/payload_generator/delta_diff_generator.h"
59 #include "update_engine/payload_generator/extent_ranges.h"
60 #include "update_engine/payload_generator/extent_utils.h"
61 #include "update_engine/payload_generator/squashfs_filesystem.h"
62 #include "update_engine/payload_generator/xz.h"
63 
64 using std::list;
65 using std::map;
66 using std::string;
67 using std::vector;
68 
69 namespace chromeos_update_engine {
70 namespace {
71 
72 // The maximum destination size allowed for bsdiff. In general, bsdiff should
73 // work for arbitrary big files, but the payload generation and payload
74 // application requires a significant amount of RAM. We put a hard-limit of
75 // 200 MiB that should not affect any released board, but will limit the
76 // Chrome binary in ASan builders.
77 const uint64_t kMaxBsdiffDestinationSize = 200 * 1024 * 1024;  // bytes
78 
79 // The maximum destination size allowed for puffdiff. In general, puffdiff
80 // should work for arbitrary big files, but the payload application is quite
81 // memory intensive, so we limit these operations to 150 MiB.
82 const uint64_t kMaxPuffdiffDestinationSize = 150 * 1024 * 1024;  // bytes
83 
84 const int kBrotliCompressionQuality = 11;
85 
86 // Storing a diff operation has more overhead over replace operation in the
87 // manifest, we need to store an additional src_sha256_hash which is 32 bytes
88 // and not compressible, and also src_extents which could use anywhere from a
89 // few bytes to hundreds of bytes depending on the number of extents.
90 // This function evaluates the overhead tradeoff and determines if it's worth to
91 // use a diff operation with data blob of |diff_size| and |num_src_extents|
92 // 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)93 bool IsDiffOperationBetter(const InstallOperation& op,
94                            size_t old_blob_size,
95                            size_t diff_size,
96                            size_t num_src_extents) {
97   if (!diff_utils::IsAReplaceOperation(op.type()))
98     return diff_size < old_blob_size;
99 
100   // Reference: https://developers.google.com/protocol-buffers/docs/encoding
101   // For |src_sha256_hash| we need 1 byte field number/type, 1 byte size and 32
102   // bytes data, for |src_extents| we need 1 byte field number/type and 1 byte
103   // size.
104   constexpr size_t kDiffOverhead = 1 + 1 + 32 + 1 + 1;
105   // Each extent has two variable length encoded uint64, here we use a rough
106   // estimate of 6 bytes overhead per extent, since |num_blocks| is usually
107   // very small.
108   constexpr size_t kDiffOverheadPerExtent = 6;
109 
110   return diff_size + kDiffOverhead + num_src_extents * kDiffOverheadPerExtent <
111          old_blob_size;
112 }
113 
114 // Returns the levenshtein distance between string |a| and |b|.
115 // https://en.wikipedia.org/wiki/Levenshtein_distance
LevenshteinDistance(const string & a,const string & b)116 int LevenshteinDistance(const string& a, const string& b) {
117   vector<int> distances(a.size() + 1);
118   std::iota(distances.begin(), distances.end(), 0);
119 
120   for (size_t i = 1; i <= b.size(); i++) {
121     distances[0] = i;
122     int previous_distance = i - 1;
123     for (size_t j = 1; j <= a.size(); j++) {
124       int new_distance =
125           std::min({distances[j] + 1,
126                     distances[j - 1] + 1,
127                     previous_distance + (a[j - 1] == b[i - 1] ? 0 : 1)});
128       previous_distance = distances[j];
129       distances[j] = new_distance;
130     }
131   }
132   return distances.back();
133 }
134 }  // namespace
135 
136 namespace diff_utils {
137 
138 // This class encapsulates a file delta processing thread work. The
139 // processor computes the delta between the source and target files;
140 // and write the compressed delta to the blob.
141 class FileDeltaProcessor : public base::DelegateSimpleThread::Delegate {
142  public:
FileDeltaProcessor(const string & old_part,const string & new_part,const PayloadVersion & version,const vector<Extent> & old_extents,const vector<Extent> & new_extents,const vector<puffin::BitExtent> & old_deflates,const vector<puffin::BitExtent> & new_deflates,const string & name,ssize_t chunk_blocks,BlobFileWriter * blob_file)143   FileDeltaProcessor(const string& old_part,
144                      const string& new_part,
145                      const PayloadVersion& version,
146                      const vector<Extent>& old_extents,
147                      const vector<Extent>& new_extents,
148                      const vector<puffin::BitExtent>& old_deflates,
149                      const vector<puffin::BitExtent>& new_deflates,
150                      const string& name,
151                      ssize_t chunk_blocks,
152                      BlobFileWriter* blob_file)
153       : old_part_(old_part),
154         new_part_(new_part),
155         version_(version),
156         old_extents_(old_extents),
157         new_extents_(new_extents),
158         new_extents_blocks_(utils::BlocksInExtents(new_extents)),
159         old_deflates_(old_deflates),
160         new_deflates_(new_deflates),
161         name_(name),
162         chunk_blocks_(chunk_blocks),
163         blob_file_(blob_file) {}
164 
operator >(const FileDeltaProcessor & other) const165   bool operator>(const FileDeltaProcessor& other) const {
166     return new_extents_blocks_ > other.new_extents_blocks_;
167   }
168 
169   ~FileDeltaProcessor() override = default;
170 
171   // Overrides DelegateSimpleThread::Delegate.
172   // Calculate the list of operations and write their corresponding deltas to
173   // the blob_file.
174   void Run() override;
175 
176   // Merge each file processor's ops list to aops.
177   bool MergeOperation(vector<AnnotatedOperation>* aops);
178 
179  private:
180   const string& old_part_;  // NOLINT(runtime/member_string_references)
181   const string& new_part_;  // NOLINT(runtime/member_string_references)
182   const PayloadVersion& version_;
183 
184   // The block ranges of the old/new file within the src/tgt image
185   const vector<Extent> old_extents_;
186   const vector<Extent> new_extents_;
187   const size_t new_extents_blocks_;
188   const vector<puffin::BitExtent> old_deflates_;
189   const vector<puffin::BitExtent> new_deflates_;
190   const string name_;
191   // Block limit of one aop.
192   const ssize_t chunk_blocks_;
193   BlobFileWriter* blob_file_;
194 
195   // The list of ops to reach the new file from the old file.
196   vector<AnnotatedOperation> file_aops_;
197 
198   bool failed_ = false;
199 
200   DISALLOW_COPY_AND_ASSIGN(FileDeltaProcessor);
201 };
202 
Run()203 void FileDeltaProcessor::Run() {
204   TEST_AND_RETURN(blob_file_ != nullptr);
205   base::TimeTicks start = base::TimeTicks::Now();
206 
207   if (!DeltaReadFile(&file_aops_,
208                      old_part_,
209                      new_part_,
210                      old_extents_,
211                      new_extents_,
212                      old_deflates_,
213                      new_deflates_,
214                      name_,
215                      chunk_blocks_,
216                      version_,
217                      blob_file_)) {
218     LOG(ERROR) << "Failed to generate delta for " << name_ << " ("
219                << new_extents_blocks_ << " blocks)";
220     failed_ = true;
221     return;
222   }
223 
224   if (!ABGenerator::FragmentOperations(
225           version_, &file_aops_, new_part_, blob_file_)) {
226     LOG(ERROR) << "Failed to fragment operations for " << name_;
227     failed_ = true;
228     return;
229   }
230 
231   LOG(INFO) << "Encoded file " << name_ << " (" << new_extents_blocks_
232             << " blocks) in " << (base::TimeTicks::Now() - start);
233 }
234 
MergeOperation(vector<AnnotatedOperation> * aops)235 bool FileDeltaProcessor::MergeOperation(vector<AnnotatedOperation>* aops) {
236   if (failed_)
237     return false;
238   aops->reserve(aops->size() + file_aops_.size());
239   std::move(file_aops_.begin(), file_aops_.end(), std::back_inserter(*aops));
240   return true;
241 }
242 
GetOldFile(const map<string,FilesystemInterface::File> & old_files_map,const string & new_file_name)243 FilesystemInterface::File GetOldFile(
244     const map<string, FilesystemInterface::File>& old_files_map,
245     const string& new_file_name) {
246   if (old_files_map.empty())
247     return {};
248 
249   auto old_file_iter = old_files_map.find(new_file_name);
250   if (old_file_iter != old_files_map.end())
251     return old_file_iter->second;
252 
253   // No old file matches the new file name. Use a similar file with the
254   // shortest levenshtein distance instead.
255   // This works great if the file has version number in it, but even for
256   // a completely new file, using a similar file can still help.
257   int min_distance =
258       LevenshteinDistance(new_file_name, old_files_map.begin()->first);
259   const FilesystemInterface::File* old_file = &old_files_map.begin()->second;
260   for (const auto& pair : old_files_map) {
261     int distance = LevenshteinDistance(new_file_name, pair.first);
262     if (distance < min_distance) {
263       min_distance = distance;
264       old_file = &pair.second;
265     }
266   }
267   LOG(INFO) << "Using " << old_file->name << " as source for " << new_file_name;
268   return *old_file;
269 }
270 
DeltaReadPartition(vector<AnnotatedOperation> * aops,const PartitionConfig & old_part,const PartitionConfig & new_part,ssize_t hard_chunk_blocks,size_t soft_chunk_blocks,const PayloadVersion & version,BlobFileWriter * blob_file)271 bool DeltaReadPartition(vector<AnnotatedOperation>* aops,
272                         const PartitionConfig& old_part,
273                         const PartitionConfig& new_part,
274                         ssize_t hard_chunk_blocks,
275                         size_t soft_chunk_blocks,
276                         const PayloadVersion& version,
277                         BlobFileWriter* blob_file) {
278   ExtentRanges old_visited_blocks;
279   ExtentRanges new_visited_blocks;
280 
281   // If verity is enabled, mark those blocks as visited to skip generating
282   // operations for them.
283   if (version.minor >= kVerityMinorPayloadVersion &&
284       !new_part.verity.IsEmpty()) {
285     LOG(INFO) << "Skipping verity hash tree blocks: "
286               << ExtentsToString({new_part.verity.hash_tree_extent});
287     new_visited_blocks.AddExtent(new_part.verity.hash_tree_extent);
288     LOG(INFO) << "Skipping verity FEC blocks: "
289               << ExtentsToString({new_part.verity.fec_extent});
290     new_visited_blocks.AddExtent(new_part.verity.fec_extent);
291   }
292 
293   ExtentRanges old_zero_blocks;
294   TEST_AND_RETURN_FALSE(DeltaMovedAndZeroBlocks(aops,
295                                                 old_part.path,
296                                                 new_part.path,
297                                                 old_part.size / kBlockSize,
298                                                 new_part.size / kBlockSize,
299                                                 soft_chunk_blocks,
300                                                 version,
301                                                 blob_file,
302                                                 &old_visited_blocks,
303                                                 &new_visited_blocks,
304                                                 &old_zero_blocks));
305 
306   bool puffdiff_allowed = version.OperationAllowed(InstallOperation::PUFFDIFF);
307   map<string, FilesystemInterface::File> old_files_map;
308   if (old_part.fs_interface) {
309     vector<FilesystemInterface::File> old_files;
310     TEST_AND_RETURN_FALSE(deflate_utils::PreprocessPartitionFiles(
311         old_part, &old_files, puffdiff_allowed));
312     for (const FilesystemInterface::File& file : old_files)
313       old_files_map[file.name] = file;
314   }
315 
316   TEST_AND_RETURN_FALSE(new_part.fs_interface);
317   vector<FilesystemInterface::File> new_files;
318   TEST_AND_RETURN_FALSE(deflate_utils::PreprocessPartitionFiles(
319       new_part, &new_files, puffdiff_allowed));
320 
321   list<FileDeltaProcessor> file_delta_processors;
322 
323   // The processing is very straightforward here, we generate operations for
324   // every file (and pseudo-file such as the metadata) in the new filesystem
325   // based on the file with the same name in the old filesystem, if any.
326   // Files with overlapping data blocks (like hardlinks or filesystems with tail
327   // packing or compression where the blocks store more than one file) are only
328   // generated once in the new image, but are also used only once from the old
329   // image due to some simplifications (see below).
330   for (const FilesystemInterface::File& new_file : new_files) {
331     // Ignore the files in the new filesystem without blocks. Symlinks with
332     // data blocks (for example, symlinks bigger than 60 bytes in ext2) are
333     // handled as normal files. We also ignore blocks that were already
334     // processed by a previous file.
335     vector<Extent> new_file_extents =
336         FilterExtentRanges(new_file.extents, new_visited_blocks);
337     new_visited_blocks.AddExtents(new_file_extents);
338 
339     if (new_file_extents.empty())
340       continue;
341 
342     // We can't visit each dst image inode more than once, as that would
343     // duplicate work. Here, we avoid visiting each source image inode
344     // more than once. Technically, we could have multiple operations
345     // that read the same blocks from the source image for diffing, but
346     // we choose not to avoid complexity. Eventually we will move away
347     // from using a graph/cycle detection/etc to generate diffs, and at that
348     // time, it will be easy (non-complex) to have many operations read
349     // from the same source blocks. At that time, this code can die. -adlr
350     FilesystemInterface::File old_file =
351         GetOldFile(old_files_map, new_file.name);
352     auto old_file_extents =
353         FilterExtentRanges(old_file.extents, old_zero_blocks);
354     old_visited_blocks.AddExtents(old_file_extents);
355 
356     file_delta_processors.emplace_back(old_part.path,
357                                        new_part.path,
358                                        version,
359                                        std::move(old_file_extents),
360                                        std::move(new_file_extents),
361                                        old_file.deflates,
362                                        new_file.deflates,
363                                        new_file.name,  // operation name
364                                        hard_chunk_blocks,
365                                        blob_file);
366   }
367   // Process all the blocks not included in any file. We provided all the unused
368   // blocks in the old partition as available data.
369   vector<Extent> new_unvisited = {
370       ExtentForRange(0, new_part.size / kBlockSize)};
371   new_unvisited = FilterExtentRanges(new_unvisited, new_visited_blocks);
372   if (!new_unvisited.empty()) {
373     vector<Extent> old_unvisited;
374     if (old_part.fs_interface) {
375       old_unvisited.push_back(ExtentForRange(0, old_part.size / kBlockSize));
376       old_unvisited = FilterExtentRanges(old_unvisited, old_visited_blocks);
377     }
378 
379     LOG(INFO) << "Scanning " << utils::BlocksInExtents(new_unvisited)
380               << " unwritten blocks using chunk size of " << soft_chunk_blocks
381               << " blocks.";
382     // We use the soft_chunk_blocks limit for the <non-file-data> as we don't
383     // really know the structure of this data and we should not expect it to
384     // have redundancy between partitions.
385     file_delta_processors.emplace_back(
386         old_part.path,
387         new_part.path,
388         version,
389         std::move(old_unvisited),
390         std::move(new_unvisited),
391         vector<puffin::BitExtent>{},  // old_deflates,
392         vector<puffin::BitExtent>{},  // new_deflates
393         "<non-file-data>",            // operation name
394         soft_chunk_blocks,
395         blob_file);
396   }
397 
398   size_t max_threads = GetMaxThreads();
399 
400   // Sort the files in descending order based on number of new blocks to make
401   // sure we start the largest ones first.
402   if (file_delta_processors.size() > max_threads) {
403     file_delta_processors.sort(std::greater<FileDeltaProcessor>());
404   }
405 
406   base::DelegateSimpleThreadPool thread_pool("incremental-update-generator",
407                                              max_threads);
408   thread_pool.Start();
409   for (auto& processor : file_delta_processors) {
410     thread_pool.AddWork(&processor);
411   }
412   thread_pool.JoinAll();
413 
414   for (auto& processor : file_delta_processors) {
415     TEST_AND_RETURN_FALSE(processor.MergeOperation(aops));
416   }
417 
418   return true;
419 }
420 
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 PayloadVersion & version,BlobFileWriter * blob_file,ExtentRanges * old_visited_blocks,ExtentRanges * new_visited_blocks,ExtentRanges * old_zero_blocks)421 bool DeltaMovedAndZeroBlocks(vector<AnnotatedOperation>* aops,
422                              const string& old_part,
423                              const string& new_part,
424                              size_t old_num_blocks,
425                              size_t new_num_blocks,
426                              ssize_t chunk_blocks,
427                              const PayloadVersion& version,
428                              BlobFileWriter* blob_file,
429                              ExtentRanges* old_visited_blocks,
430                              ExtentRanges* new_visited_blocks,
431                              ExtentRanges* old_zero_blocks) {
432   vector<BlockMapping::BlockId> old_block_ids;
433   vector<BlockMapping::BlockId> new_block_ids;
434   TEST_AND_RETURN_FALSE(MapPartitionBlocks(old_part,
435                                            new_part,
436                                            old_num_blocks * kBlockSize,
437                                            new_num_blocks * kBlockSize,
438                                            kBlockSize,
439                                            &old_block_ids,
440                                            &new_block_ids));
441 
442   // A mapping from the block_id to the list of block numbers with that block id
443   // in the old partition. This is used to lookup where in the old partition
444   // is a block from the new partition.
445   map<BlockMapping::BlockId, vector<uint64_t>> old_blocks_map;
446 
447   for (uint64_t block = old_num_blocks; block-- > 0;) {
448     if (old_block_ids[block] != 0 && !old_visited_blocks->ContainsBlock(block))
449       old_blocks_map[old_block_ids[block]].push_back(block);
450 
451     // Mark all zeroed blocks in the old image as "used" since it doesn't make
452     // any sense to spend I/O to read zeros from the source partition and more
453     // importantly, these could sometimes be blocks discarded in the SSD which
454     // would read non-zero values.
455     if (old_block_ids[block] == 0)
456       old_zero_blocks->AddBlock(block);
457   }
458   old_visited_blocks->AddRanges(*old_zero_blocks);
459 
460   // The collection of blocks in the new partition with just zeros. This is a
461   // common case for free-space that's also problematic for bsdiff, so we want
462   // to optimize it using REPLACE_BZ operations. The blob for a REPLACE_BZ of
463   // just zeros is so small that it doesn't make sense to spend the I/O reading
464   // zeros from the old partition.
465   vector<Extent> new_zeros;
466 
467   vector<Extent> old_identical_blocks;
468   vector<Extent> new_identical_blocks;
469 
470   for (uint64_t block = 0; block < new_num_blocks; block++) {
471     // Only produce operations for blocks that were not yet visited.
472     if (new_visited_blocks->ContainsBlock(block))
473       continue;
474     if (new_block_ids[block] == 0) {
475       AppendBlockToExtents(&new_zeros, block);
476       continue;
477     }
478 
479     auto old_blocks_map_it = old_blocks_map.find(new_block_ids[block]);
480     // Check if the block exists in the old partition at all.
481     if (old_blocks_map_it == old_blocks_map.end() ||
482         old_blocks_map_it->second.empty())
483       continue;
484 
485     AppendBlockToExtents(&old_identical_blocks,
486                          old_blocks_map_it->second.back());
487     AppendBlockToExtents(&new_identical_blocks, block);
488   }
489 
490   if (chunk_blocks == -1)
491     chunk_blocks = new_num_blocks;
492 
493   // Produce operations for the zero blocks split per output extent.
494   size_t num_ops = aops->size();
495   new_visited_blocks->AddExtents(new_zeros);
496   for (const Extent& extent : new_zeros) {
497     if (version.OperationAllowed(InstallOperation::ZERO)) {
498       for (uint64_t offset = 0; offset < extent.num_blocks();
499            offset += chunk_blocks) {
500         uint64_t num_blocks =
501             std::min(static_cast<uint64_t>(extent.num_blocks()) - offset,
502                      static_cast<uint64_t>(chunk_blocks));
503         InstallOperation operation;
504         operation.set_type(InstallOperation::ZERO);
505         *(operation.add_dst_extents()) =
506             ExtentForRange(extent.start_block() + offset, num_blocks);
507         aops->push_back({.name = "<zeros>", .op = operation});
508       }
509     } else {
510       TEST_AND_RETURN_FALSE(DeltaReadFile(aops,
511                                           "",
512                                           new_part,
513                                           {},        // old_extents
514                                           {extent},  // new_extents
515                                           {},        // old_deflates
516                                           {},        // new_deflates
517                                           "<zeros>",
518                                           chunk_blocks,
519                                           version,
520                                           blob_file));
521     }
522   }
523   LOG(INFO) << "Produced " << (aops->size() - num_ops) << " operations for "
524             << utils::BlocksInExtents(new_zeros) << " zeroed blocks";
525 
526   // Produce MOVE/SOURCE_COPY operations for the moved blocks.
527   num_ops = aops->size();
528   uint64_t used_blocks = 0;
529   old_visited_blocks->AddExtents(old_identical_blocks);
530   new_visited_blocks->AddExtents(new_identical_blocks);
531   for (const Extent& extent : new_identical_blocks) {
532     // We split the operation at the extent boundary or when bigger than
533     // chunk_blocks.
534     for (uint64_t op_block_offset = 0; op_block_offset < extent.num_blocks();
535          op_block_offset += chunk_blocks) {
536       aops->emplace_back();
537       AnnotatedOperation* aop = &aops->back();
538       aop->name = "<identical-blocks>";
539       aop->op.set_type(InstallOperation::SOURCE_COPY);
540 
541       uint64_t chunk_num_blocks =
542           std::min(static_cast<uint64_t>(extent.num_blocks()) - op_block_offset,
543                    static_cast<uint64_t>(chunk_blocks));
544 
545       // The current operation represents the move/copy operation for the
546       // sublist starting at |used_blocks| of length |chunk_num_blocks| where
547       // the src and dst are from |old_identical_blocks| and
548       // |new_identical_blocks| respectively.
549       StoreExtents(
550           ExtentsSublist(old_identical_blocks, used_blocks, chunk_num_blocks),
551           aop->op.mutable_src_extents());
552 
553       Extent* op_dst_extent = aop->op.add_dst_extents();
554       op_dst_extent->set_start_block(extent.start_block() + op_block_offset);
555       op_dst_extent->set_num_blocks(chunk_num_blocks);
556       CHECK(
557           vector<Extent>{*op_dst_extent} ==  // NOLINT(whitespace/braces)
558           ExtentsSublist(new_identical_blocks, used_blocks, chunk_num_blocks));
559 
560       used_blocks += chunk_num_blocks;
561     }
562   }
563   LOG(INFO) << "Produced " << (aops->size() - num_ops) << " operations for "
564             << used_blocks << " identical blocks moved";
565 
566   return true;
567 }
568 
DeltaReadFile(vector<AnnotatedOperation> * aops,const string & old_part,const string & new_part,const vector<Extent> & old_extents,const vector<Extent> & new_extents,const vector<puffin::BitExtent> & old_deflates,const vector<puffin::BitExtent> & new_deflates,const string & name,ssize_t chunk_blocks,const PayloadVersion & version,BlobFileWriter * blob_file)569 bool DeltaReadFile(vector<AnnotatedOperation>* aops,
570                    const string& old_part,
571                    const string& new_part,
572                    const vector<Extent>& old_extents,
573                    const vector<Extent>& new_extents,
574                    const vector<puffin::BitExtent>& old_deflates,
575                    const vector<puffin::BitExtent>& new_deflates,
576                    const string& name,
577                    ssize_t chunk_blocks,
578                    const PayloadVersion& version,
579                    BlobFileWriter* blob_file) {
580   brillo::Blob data;
581   InstallOperation operation;
582 
583   uint64_t total_blocks = utils::BlocksInExtents(new_extents);
584   if (chunk_blocks == 0) {
585     LOG(ERROR) << "Invalid number of chunk_blocks. Cannot be 0.";
586     return false;
587   }
588 
589   if (chunk_blocks == -1)
590     chunk_blocks = total_blocks;
591 
592   for (uint64_t block_offset = 0; block_offset < total_blocks;
593        block_offset += chunk_blocks) {
594     // Split the old/new file in the same chunks. Note that this could drop
595     // some information from the old file used for the new chunk. If the old
596     // file is smaller (or even empty when there's no old file) the chunk will
597     // also be empty.
598     vector<Extent> old_extents_chunk =
599         ExtentsSublist(old_extents, block_offset, chunk_blocks);
600     vector<Extent> new_extents_chunk =
601         ExtentsSublist(new_extents, block_offset, chunk_blocks);
602     NormalizeExtents(&old_extents_chunk);
603     NormalizeExtents(&new_extents_chunk);
604 
605     TEST_AND_RETURN_FALSE(ReadExtentsToDiff(old_part,
606                                             new_part,
607                                             old_extents_chunk,
608                                             new_extents_chunk,
609                                             old_deflates,
610                                             new_deflates,
611                                             version,
612                                             &data,
613                                             &operation));
614 
615     // Check if the operation writes nothing.
616     if (operation.dst_extents_size() == 0) {
617       LOG(ERROR) << "Empty non-MOVE operation";
618       return false;
619     }
620 
621     // Now, insert into the list of operations.
622     AnnotatedOperation aop;
623     aop.name = name;
624     if (static_cast<uint64_t>(chunk_blocks) < total_blocks) {
625       aop.name = base::StringPrintf(
626           "%s:%" PRIu64, name.c_str(), block_offset / chunk_blocks);
627     }
628     aop.op = operation;
629 
630     // Write the data
631     TEST_AND_RETURN_FALSE(aop.SetOperationBlob(data, blob_file));
632     aops->emplace_back(aop);
633   }
634   return true;
635 }
636 
GenerateBestFullOperation(const brillo::Blob & new_data,const PayloadVersion & version,brillo::Blob * out_blob,InstallOperation::Type * out_type)637 bool GenerateBestFullOperation(const brillo::Blob& new_data,
638                                const PayloadVersion& version,
639                                brillo::Blob* out_blob,
640                                InstallOperation::Type* out_type) {
641   if (new_data.empty())
642     return false;
643 
644   if (version.OperationAllowed(InstallOperation::ZERO) &&
645       std::all_of(
646           new_data.begin(), new_data.end(), [](uint8_t x) { return x == 0; })) {
647     // The read buffer is all zeros, so produce a ZERO operation. No need to
648     // check other types of operations in this case.
649     *out_blob = brillo::Blob();
650     *out_type = InstallOperation::ZERO;
651     return true;
652   }
653 
654   bool out_blob_set = false;
655 
656   // Try compressing |new_data| with xz first.
657   if (version.OperationAllowed(InstallOperation::REPLACE_XZ)) {
658     brillo::Blob new_data_xz;
659     if (XzCompress(new_data, &new_data_xz) && !new_data_xz.empty()) {
660       *out_type = InstallOperation::REPLACE_XZ;
661       *out_blob = std::move(new_data_xz);
662       out_blob_set = true;
663     }
664   }
665 
666   // Try compressing it with bzip2.
667   if (version.OperationAllowed(InstallOperation::REPLACE_BZ)) {
668     brillo::Blob new_data_bz;
669     // TODO(deymo): Implement some heuristic to determine if it is worth trying
670     // to compress the blob with bzip2 if we already have a good REPLACE_XZ.
671     if (BzipCompress(new_data, &new_data_bz) && !new_data_bz.empty() &&
672         (!out_blob_set || out_blob->size() > new_data_bz.size())) {
673       // A REPLACE_BZ is better or nothing else was set.
674       *out_type = InstallOperation::REPLACE_BZ;
675       *out_blob = std::move(new_data_bz);
676       out_blob_set = true;
677     }
678   }
679 
680   // If nothing else worked or it was badly compressed we try a REPLACE.
681   if (!out_blob_set || out_blob->size() >= new_data.size()) {
682     *out_type = InstallOperation::REPLACE;
683     // This needs to make a copy of the data in the case bzip or xz didn't
684     // compress well, which is not the common case so the performance hit is
685     // low.
686     *out_blob = new_data;
687   }
688   return true;
689 }
690 
ReadExtentsToDiff(const string & old_part,const string & new_part,const vector<Extent> & old_extents,const vector<Extent> & new_extents,const vector<puffin::BitExtent> & old_deflates,const vector<puffin::BitExtent> & new_deflates,const PayloadVersion & version,brillo::Blob * out_data,InstallOperation * out_op)691 bool ReadExtentsToDiff(const string& old_part,
692                        const string& new_part,
693                        const vector<Extent>& old_extents,
694                        const vector<Extent>& new_extents,
695                        const vector<puffin::BitExtent>& old_deflates,
696                        const vector<puffin::BitExtent>& new_deflates,
697                        const PayloadVersion& version,
698                        brillo::Blob* out_data,
699                        InstallOperation* out_op) {
700   InstallOperation operation;
701 
702   // We read blocks from old_extents and write blocks to new_extents.
703   uint64_t blocks_to_read = utils::BlocksInExtents(old_extents);
704   uint64_t blocks_to_write = utils::BlocksInExtents(new_extents);
705 
706   // Disable bsdiff, and puffdiff when the data is too big.
707   bool bsdiff_allowed =
708       version.OperationAllowed(InstallOperation::SOURCE_BSDIFF);
709   if (bsdiff_allowed &&
710       blocks_to_read * kBlockSize > kMaxBsdiffDestinationSize) {
711     LOG(INFO) << "bsdiff ignored, data too big: " << blocks_to_read * kBlockSize
712               << " bytes";
713     bsdiff_allowed = false;
714   }
715 
716   bool puffdiff_allowed = version.OperationAllowed(InstallOperation::PUFFDIFF);
717   if (puffdiff_allowed &&
718       blocks_to_read * kBlockSize > kMaxPuffdiffDestinationSize) {
719     LOG(INFO) << "puffdiff ignored, data too big: "
720               << blocks_to_read * kBlockSize << " bytes";
721     puffdiff_allowed = false;
722   }
723 
724   // Make copies of the extents so we can modify them.
725   vector<Extent> src_extents = old_extents;
726   vector<Extent> dst_extents = new_extents;
727 
728   // Read in bytes from new data.
729   brillo::Blob new_data;
730   TEST_AND_RETURN_FALSE(utils::ReadExtents(new_part,
731                                            new_extents,
732                                            &new_data,
733                                            kBlockSize * blocks_to_write,
734                                            kBlockSize));
735   TEST_AND_RETURN_FALSE(!new_data.empty());
736 
737   // Data blob that will be written to delta file.
738   brillo::Blob data_blob;
739 
740   // Try generating a full operation for the given new data, regardless of the
741   // old_data.
742   InstallOperation::Type op_type;
743   TEST_AND_RETURN_FALSE(
744       GenerateBestFullOperation(new_data, version, &data_blob, &op_type));
745   operation.set_type(op_type);
746 
747   brillo::Blob old_data;
748   if (blocks_to_read > 0) {
749     // Read old data.
750     TEST_AND_RETURN_FALSE(utils::ReadExtents(old_part,
751                                              src_extents,
752                                              &old_data,
753                                              kBlockSize * blocks_to_read,
754                                              kBlockSize));
755     if (old_data == new_data) {
756       // No change in data.
757       operation.set_type(InstallOperation::SOURCE_COPY);
758       data_blob = brillo::Blob();
759     } else if (IsDiffOperationBetter(
760                    operation, data_blob.size(), 0, src_extents.size())) {
761       // No point in trying diff if zero blob size diff operation is
762       // still worse than replace.
763       if (bsdiff_allowed) {
764         base::FilePath patch;
765         TEST_AND_RETURN_FALSE(base::CreateTemporaryFile(&patch));
766         ScopedPathUnlinker unlinker(patch.value());
767 
768         std::unique_ptr<bsdiff::PatchWriterInterface> bsdiff_patch_writer;
769         InstallOperation::Type operation_type = InstallOperation::SOURCE_BSDIFF;
770         if (version.OperationAllowed(InstallOperation::BROTLI_BSDIFF)) {
771           bsdiff_patch_writer =
772               bsdiff::CreateBSDF2PatchWriter(patch.value(),
773                                              bsdiff::CompressorType::kBrotli,
774                                              kBrotliCompressionQuality);
775           operation_type = InstallOperation::BROTLI_BSDIFF;
776         } else {
777           bsdiff_patch_writer = bsdiff::CreateBsdiffPatchWriter(patch.value());
778         }
779 
780         brillo::Blob bsdiff_delta;
781         TEST_AND_RETURN_FALSE(0 == bsdiff::bsdiff(old_data.data(),
782                                                   old_data.size(),
783                                                   new_data.data(),
784                                                   new_data.size(),
785                                                   bsdiff_patch_writer.get(),
786                                                   nullptr));
787 
788         TEST_AND_RETURN_FALSE(utils::ReadFile(patch.value(), &bsdiff_delta));
789         CHECK_GT(bsdiff_delta.size(), static_cast<brillo::Blob::size_type>(0));
790         if (IsDiffOperationBetter(operation,
791                                   data_blob.size(),
792                                   bsdiff_delta.size(),
793                                   src_extents.size())) {
794           operation.set_type(operation_type);
795           data_blob = std::move(bsdiff_delta);
796         }
797       }
798       if (puffdiff_allowed) {
799         // Find all deflate positions inside the given extents and then put all
800         // deflates together because we have already read all the extents into
801         // one buffer.
802         vector<puffin::BitExtent> src_deflates;
803         TEST_AND_RETURN_FALSE(deflate_utils::FindAndCompactDeflates(
804             src_extents, old_deflates, &src_deflates));
805 
806         vector<puffin::BitExtent> dst_deflates;
807         TEST_AND_RETURN_FALSE(deflate_utils::FindAndCompactDeflates(
808             dst_extents, new_deflates, &dst_deflates));
809 
810         puffin::RemoveEqualBitExtents(
811             old_data, new_data, &src_deflates, &dst_deflates);
812 
813         // See crbug.com/915559.
814         if (version.minor <= kPuffdiffMinorPayloadVersion) {
815           TEST_AND_RETURN_FALSE(puffin::RemoveDeflatesWithBadDistanceCaches(
816               old_data, &src_deflates));
817 
818           TEST_AND_RETURN_FALSE(puffin::RemoveDeflatesWithBadDistanceCaches(
819               new_data, &dst_deflates));
820         }
821 
822         // Only Puffdiff if both files have at least one deflate left.
823         if (!src_deflates.empty() && !dst_deflates.empty()) {
824           brillo::Blob puffdiff_delta;
825           string temp_file_path;
826           TEST_AND_RETURN_FALSE(utils::MakeTempFile(
827               "puffdiff-delta.XXXXXX", &temp_file_path, nullptr));
828           ScopedPathUnlinker temp_file_unlinker(temp_file_path);
829 
830           // Perform PuffDiff operation.
831           TEST_AND_RETURN_FALSE(puffin::PuffDiff(old_data,
832                                                  new_data,
833                                                  src_deflates,
834                                                  dst_deflates,
835                                                  temp_file_path,
836                                                  &puffdiff_delta));
837           TEST_AND_RETURN_FALSE(puffdiff_delta.size() > 0);
838           if (IsDiffOperationBetter(operation,
839                                     data_blob.size(),
840                                     puffdiff_delta.size(),
841                                     src_extents.size())) {
842             operation.set_type(InstallOperation::PUFFDIFF);
843             data_blob = std::move(puffdiff_delta);
844           }
845         }
846       }
847     }
848   }
849 
850   // WARNING: We always set legacy |src_length| and |dst_length| fields for
851   // BSDIFF. For SOURCE_BSDIFF we only set them for minor version 3 and
852   // lower. This is needed because we used to use these two parameters in the
853   // SOURCE_BSDIFF for minor version 3 and lower, but we do not need them
854   // anymore in higher minor versions. This means if we stop adding these
855   // parameters for those minor versions, the delta payloads will be invalid.
856   if (operation.type() == InstallOperation::SOURCE_BSDIFF &&
857       version.minor <= kOpSrcHashMinorPayloadVersion) {
858     operation.set_src_length(old_data.size());
859     operation.set_dst_length(new_data.size());
860   }
861 
862   // Embed extents in the operation. Replace (all variants), zero and discard
863   // operations should not have source extents.
864   if (!IsNoSourceOperation(operation.type())) {
865     StoreExtents(src_extents, operation.mutable_src_extents());
866   }
867   // All operations have dst_extents.
868   StoreExtents(dst_extents, operation.mutable_dst_extents());
869 
870   *out_data = std::move(data_blob);
871   *out_op = operation;
872   return true;
873 }
874 
IsAReplaceOperation(InstallOperation::Type op_type)875 bool IsAReplaceOperation(InstallOperation::Type op_type) {
876   return (op_type == InstallOperation::REPLACE ||
877           op_type == InstallOperation::REPLACE_BZ ||
878           op_type == InstallOperation::REPLACE_XZ);
879 }
880 
IsNoSourceOperation(InstallOperation::Type op_type)881 bool IsNoSourceOperation(InstallOperation::Type op_type) {
882   return (IsAReplaceOperation(op_type) || op_type == InstallOperation::ZERO ||
883           op_type == InstallOperation::DISCARD);
884 }
885 
InitializePartitionInfo(const PartitionConfig & part,PartitionInfo * info)886 bool InitializePartitionInfo(const PartitionConfig& part, PartitionInfo* info) {
887   info->set_size(part.size);
888   HashCalculator hasher;
889   TEST_AND_RETURN_FALSE(hasher.UpdateFile(part.path, part.size) ==
890                         static_cast<off_t>(part.size));
891   TEST_AND_RETURN_FALSE(hasher.Finalize());
892   const brillo::Blob& hash = hasher.raw_hash();
893   info->set_hash(hash.data(), hash.size());
894   LOG(INFO) << part.path << ": size=" << part.size
895             << " hash=" << brillo::data_encoding::Base64Encode(hash);
896   return true;
897 }
898 
CompareAopsByDestination(AnnotatedOperation first_aop,AnnotatedOperation second_aop)899 bool CompareAopsByDestination(AnnotatedOperation first_aop,
900                               AnnotatedOperation second_aop) {
901   // We want empty operations to be at the end of the payload.
902   if (!first_aop.op.dst_extents().size() || !second_aop.op.dst_extents().size())
903     return ((!first_aop.op.dst_extents().size()) <
904             (!second_aop.op.dst_extents().size()));
905   uint32_t first_dst_start = first_aop.op.dst_extents(0).start_block();
906   uint32_t second_dst_start = second_aop.op.dst_extents(0).start_block();
907   return first_dst_start < second_dst_start;
908 }
909 
IsExtFilesystem(const string & device)910 bool IsExtFilesystem(const string& device) {
911   brillo::Blob header;
912   // See include/linux/ext2_fs.h for more details on the structure. We obtain
913   // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
914   // library.
915   if (!utils::ReadFileChunk(
916           device, 0, SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE, &header) ||
917       header.size() < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
918     return false;
919 
920   const uint8_t* superblock = header.data() + SUPERBLOCK_OFFSET;
921 
922   // ext3_fs.h: ext3_super_block.s_blocks_count
923   uint32_t block_count =
924       *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
925 
926   // ext3_fs.h: ext3_super_block.s_log_block_size
927   uint32_t log_block_size =
928       *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
929 
930   // ext3_fs.h: ext3_super_block.s_magic
931   uint16_t magic =
932       *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
933 
934   block_count = le32toh(block_count);
935   log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
936   magic = le16toh(magic);
937 
938   if (magic != EXT2_SUPER_MAGIC)
939     return false;
940 
941   // Validation check the parameters.
942   TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
943                         log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
944   TEST_AND_RETURN_FALSE(block_count > 0);
945   return true;
946 }
947 
948 // Return the number of CPUs on the machine, and 4 threads in minimum.
GetMaxThreads()949 size_t GetMaxThreads() {
950   return std::max(sysconf(_SC_NPROCESSORS_ONLN), 4L);
951 }
952 
953 }  // namespace diff_utils
954 
955 }  // namespace chromeos_update_engine
956