delta_diff_utils.cc revision 49fdb09d1ff2e078fa44c26540a5b82900df0f9a
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// TODO: Remove these pragmas when b/35721782 is fixed.
21#pragma clang diagnostic push
22#pragma clang diagnostic ignored "-Wmacro-redefined"
23#include <ext2fs/ext2fs.h>
24#pragma clang diagnostic pop
25#include <unistd.h>
26
27#include <algorithm>
28#include <map>
29
30#include <base/files/file_util.h>
31#include <base/format_macros.h>
32#include <base/strings/stringprintf.h>
33#include <base/threading/simple_thread.h>
34#include <brillo/data_encoding.h>
35
36#include "update_engine/common/hash_calculator.h"
37#include "update_engine/common/subprocess.h"
38#include "update_engine/common/utils.h"
39#include "update_engine/payload_generator/block_mapping.h"
40#include "update_engine/payload_generator/bzip.h"
41#include "update_engine/payload_generator/delta_diff_generator.h"
42#include "update_engine/payload_generator/extent_ranges.h"
43#include "update_engine/payload_generator/extent_utils.h"
44#include "update_engine/payload_generator/xz.h"
45
46using std::map;
47using std::string;
48using std::vector;
49
50namespace chromeos_update_engine {
51namespace {
52
53const char* const kBsdiffPath = "bsdiff";
54
55// The maximum destination size allowed for bsdiff. In general, bsdiff should
56// work for arbitrary big files, but the payload generation and payload
57// application requires a significant amount of RAM. We put a hard-limit of
58// 200 MiB that should not affect any released board, but will limit the
59// Chrome binary in ASan builders.
60const uint64_t kMaxBsdiffDestinationSize = 200 * 1024 * 1024;  // bytes
61
62// The maximum destination size allowed for puffdiff. In general, puffdiff
63// should work for arbitrary big files, but the payload application is quite
64// memory intensive, so we limit these operations to 50 MiB.
65const uint64_t kMaxPuffdiffDestinationSize = 50 * 1024 * 1024;  // bytes
66
67// Process a range of blocks from |range_start| to |range_end| in the extent at
68// position |*idx_p| of |extents|. If |do_remove| is true, this range will be
69// removed, which may cause the extent to be trimmed, split or removed entirely.
70// The value of |*idx_p| is updated to point to the next extent to be processed.
71// Returns true iff the next extent to process is a new or updated one.
72bool ProcessExtentBlockRange(vector<Extent>* extents, size_t* idx_p,
73                             const bool do_remove, uint64_t range_start,
74                             uint64_t range_end) {
75  size_t idx = *idx_p;
76  uint64_t start_block = (*extents)[idx].start_block();
77  uint64_t num_blocks = (*extents)[idx].num_blocks();
78  uint64_t range_size = range_end - range_start;
79
80  if (do_remove) {
81    if (range_size == num_blocks) {
82      // Remove the entire extent.
83      extents->erase(extents->begin() + idx);
84    } else if (range_end == num_blocks) {
85      // Trim the end of the extent.
86      (*extents)[idx].set_num_blocks(num_blocks - range_size);
87      idx++;
88    } else if (range_start == 0) {
89      // Trim the head of the extent.
90      (*extents)[idx].set_start_block(start_block + range_size);
91      (*extents)[idx].set_num_blocks(num_blocks - range_size);
92    } else {
93      // Trim the middle, splitting the remainder into two parts.
94      (*extents)[idx].set_num_blocks(range_start);
95      Extent e;
96      e.set_start_block(start_block + range_end);
97      e.set_num_blocks(num_blocks - range_end);
98      idx++;
99      extents->insert(extents->begin() + idx, e);
100    }
101  } else if (range_end == num_blocks) {
102    // Done with this extent.
103    idx++;
104  } else {
105    return false;
106  }
107
108  *idx_p = idx;
109  return true;
110}
111
112// Remove identical corresponding block ranges in |src_extents| and
113// |dst_extents|. Used for preventing moving of blocks onto themselves during
114// MOVE operations. The value of |total_bytes| indicates the actual length of
115// content; this may be slightly less than the total size of blocks, in which
116// case the last block is only partly occupied with data. Returns the total
117// number of bytes removed.
118size_t RemoveIdenticalBlockRanges(vector<Extent>* src_extents,
119                                  vector<Extent>* dst_extents,
120                                  const size_t total_bytes) {
121  size_t src_idx = 0;
122  size_t dst_idx = 0;
123  uint64_t src_offset = 0, dst_offset = 0;
124  size_t removed_bytes = 0, nonfull_block_bytes;
125  bool do_remove = false;
126  while (src_idx < src_extents->size() && dst_idx < dst_extents->size()) {
127    do_remove = ((*src_extents)[src_idx].start_block() + src_offset ==
128                 (*dst_extents)[dst_idx].start_block() + dst_offset);
129
130    uint64_t src_num_blocks = (*src_extents)[src_idx].num_blocks();
131    uint64_t dst_num_blocks = (*dst_extents)[dst_idx].num_blocks();
132    uint64_t min_num_blocks = std::min(src_num_blocks - src_offset,
133                                       dst_num_blocks - dst_offset);
134    uint64_t prev_src_offset = src_offset;
135    uint64_t prev_dst_offset = dst_offset;
136    src_offset += min_num_blocks;
137    dst_offset += min_num_blocks;
138
139    bool new_src = ProcessExtentBlockRange(src_extents, &src_idx, do_remove,
140                                           prev_src_offset, src_offset);
141    bool new_dst = ProcessExtentBlockRange(dst_extents, &dst_idx, do_remove,
142                                           prev_dst_offset, dst_offset);
143    if (new_src) {
144      src_offset = 0;
145    }
146    if (new_dst) {
147      dst_offset = 0;
148    }
149
150    if (do_remove)
151      removed_bytes += min_num_blocks * kBlockSize;
152  }
153
154  // If we removed the last block and this block is only partly used by file
155  // content, deduct the unused portion from the total removed byte count.
156  if (do_remove && (nonfull_block_bytes = total_bytes % kBlockSize))
157    removed_bytes -= kBlockSize - nonfull_block_bytes;
158
159  return removed_bytes;
160}
161
162}  // namespace
163
164namespace diff_utils {
165
166// This class encapsulates a file delta processing thread work. The
167// processor computes the delta between the source and target files;
168// and write the compressed delta to the blob.
169class FileDeltaProcessor : public base::DelegateSimpleThread::Delegate {
170 public:
171  FileDeltaProcessor(const string& old_part,
172                     const string& new_part,
173                     const PayloadVersion& version,
174                     const vector<Extent>& old_extents,
175                     const vector<Extent>& new_extents,
176                     const string& name,
177                     ssize_t chunk_blocks,
178                     BlobFileWriter* blob_file)
179      : old_part_(old_part),
180        new_part_(new_part),
181        version_(version),
182        old_extents_(old_extents),
183        new_extents_(new_extents),
184        name_(name),
185        chunk_blocks_(chunk_blocks),
186        blob_file_(blob_file) {}
187
188  FileDeltaProcessor(FileDeltaProcessor&& processor) = default;
189
190  ~FileDeltaProcessor() override = default;
191
192  // Overrides DelegateSimpleThread::Delegate.
193  // Calculate the list of operations and write their corresponding deltas to
194  // the blob_file.
195  void Run() override;
196
197  // Merge each file processor's ops list to aops.
198  void MergeOperation(vector<AnnotatedOperation>* aops);
199
200 private:
201  const string& old_part_;
202  const string& new_part_;
203  const PayloadVersion& version_;
204
205  // The block ranges of the old/new file within the src/tgt image
206  const vector<Extent> old_extents_;
207  const vector<Extent> new_extents_;
208  const string name_;
209  // Block limit of one aop.
210  ssize_t chunk_blocks_;
211  BlobFileWriter* blob_file_;
212
213  // The list of ops to reach the new file from the old file.
214  vector<AnnotatedOperation> file_aops_;
215
216  DISALLOW_COPY_AND_ASSIGN(FileDeltaProcessor);
217};
218
219void FileDeltaProcessor::Run() {
220  TEST_AND_RETURN(blob_file_ != nullptr);
221
222  if (!DeltaReadFile(&file_aops_,
223                     old_part_,
224                     new_part_,
225                     old_extents_,
226                     new_extents_,
227                     name_,
228                     chunk_blocks_,
229                     version_,
230                     blob_file_)) {
231    LOG(ERROR) << "Failed to generate delta for " << name_ << " ("
232               << BlocksInExtents(new_extents_) << " blocks)";
233  }
234}
235
236void FileDeltaProcessor::MergeOperation(vector<AnnotatedOperation>* aops) {
237  aops->reserve(aops->size() + file_aops_.size());
238  std::move(file_aops_.begin(), file_aops_.end(), std::back_inserter(*aops));
239}
240
241bool DeltaReadPartition(vector<AnnotatedOperation>* aops,
242                        const PartitionConfig& old_part,
243                        const PartitionConfig& new_part,
244                        ssize_t hard_chunk_blocks,
245                        size_t soft_chunk_blocks,
246                        const PayloadVersion& version,
247                        BlobFileWriter* blob_file) {
248  ExtentRanges old_visited_blocks;
249  ExtentRanges new_visited_blocks;
250
251  TEST_AND_RETURN_FALSE(DeltaMovedAndZeroBlocks(
252      aops,
253      old_part.path,
254      new_part.path,
255      old_part.size / kBlockSize,
256      new_part.size / kBlockSize,
257      soft_chunk_blocks,
258      version,
259      blob_file,
260      &old_visited_blocks,
261      &new_visited_blocks));
262
263  map<string, vector<Extent>> old_files_map;
264  if (old_part.fs_interface) {
265    vector<FilesystemInterface::File> old_files;
266    old_part.fs_interface->GetFiles(&old_files);
267    for (const FilesystemInterface::File& file : old_files)
268      old_files_map[file.name] = file.extents;
269  }
270
271  TEST_AND_RETURN_FALSE(new_part.fs_interface);
272  vector<FilesystemInterface::File> new_files;
273  new_part.fs_interface->GetFiles(&new_files);
274
275  vector<FileDeltaProcessor> file_delta_processors;
276
277  // The processing is very straightforward here, we generate operations for
278  // every file (and pseudo-file such as the metadata) in the new filesystem
279  // based on the file with the same name in the old filesystem, if any.
280  // Files with overlapping data blocks (like hardlinks or filesystems with tail
281  // packing or compression where the blocks store more than one file) are only
282  // generated once in the new image, but are also used only once from the old
283  // image due to some simplifications (see below).
284  for (const FilesystemInterface::File& new_file : new_files) {
285    // Ignore the files in the new filesystem without blocks. Symlinks with
286    // data blocks (for example, symlinks bigger than 60 bytes in ext2) are
287    // handled as normal files. We also ignore blocks that were already
288    // processed by a previous file.
289    vector<Extent> new_file_extents = FilterExtentRanges(
290        new_file.extents, new_visited_blocks);
291    new_visited_blocks.AddExtents(new_file_extents);
292
293    if (new_file_extents.empty())
294      continue;
295
296    LOG(INFO) << "Encoding file " << new_file.name << " ("
297              << BlocksInExtents(new_file_extents) << " blocks)";
298
299    // We can't visit each dst image inode more than once, as that would
300    // duplicate work. Here, we avoid visiting each source image inode
301    // more than once. Technically, we could have multiple operations
302    // that read the same blocks from the source image for diffing, but
303    // we choose not to avoid complexity. Eventually we will move away
304    // from using a graph/cycle detection/etc to generate diffs, and at that
305    // time, it will be easy (non-complex) to have many operations read
306    // from the same source blocks. At that time, this code can die. -adlr
307    vector<Extent> old_file_extents = FilterExtentRanges(
308        old_files_map[new_file.name], old_visited_blocks);
309    old_visited_blocks.AddExtents(old_file_extents);
310
311    file_delta_processors.emplace_back(old_part.path,
312                                       new_part.path,
313                                       version,
314                                       std::move(old_file_extents),
315                                       std::move(new_file_extents),
316                                       new_file.name,  // operation name
317                                       hard_chunk_blocks,
318                                       blob_file);
319  }
320
321  size_t max_threads = GetMaxThreads();
322  base::DelegateSimpleThreadPool thread_pool("incremental-update-generator",
323                                             max_threads);
324  thread_pool.Start();
325  for (auto& processor : file_delta_processors) {
326    thread_pool.AddWork(&processor);
327  }
328  thread_pool.JoinAll();
329
330  for (auto& processor : file_delta_processors) {
331    processor.MergeOperation(aops);
332  }
333
334  // Process all the blocks not included in any file. We provided all the unused
335  // blocks in the old partition as available data.
336  vector<Extent> new_unvisited = {
337      ExtentForRange(0, new_part.size / kBlockSize)};
338  new_unvisited = FilterExtentRanges(new_unvisited, new_visited_blocks);
339  if (new_unvisited.empty())
340    return true;
341
342  vector<Extent> old_unvisited;
343  if (old_part.fs_interface) {
344    old_unvisited.push_back(ExtentForRange(0, old_part.size / kBlockSize));
345    old_unvisited = FilterExtentRanges(old_unvisited, old_visited_blocks);
346  }
347
348  LOG(INFO) << "Scanning " << BlocksInExtents(new_unvisited)
349            << " unwritten blocks using chunk size of "
350            << soft_chunk_blocks << " blocks.";
351  // We use the soft_chunk_blocks limit for the <non-file-data> as we don't
352  // really know the structure of this data and we should not expect it to have
353  // redundancy between partitions.
354  TEST_AND_RETURN_FALSE(DeltaReadFile(aops,
355                                      old_part.path,
356                                      new_part.path,
357                                      old_unvisited,
358                                      new_unvisited,
359                                      "<non-file-data>",  // operation name
360                                      soft_chunk_blocks,
361                                      version,
362                                      blob_file));
363
364  return true;
365}
366
367bool DeltaMovedAndZeroBlocks(vector<AnnotatedOperation>* aops,
368                             const string& old_part,
369                             const string& new_part,
370                             size_t old_num_blocks,
371                             size_t new_num_blocks,
372                             ssize_t chunk_blocks,
373                             const PayloadVersion& version,
374                             BlobFileWriter* blob_file,
375                             ExtentRanges* old_visited_blocks,
376                             ExtentRanges* new_visited_blocks) {
377  vector<BlockMapping::BlockId> old_block_ids;
378  vector<BlockMapping::BlockId> new_block_ids;
379  TEST_AND_RETURN_FALSE(MapPartitionBlocks(old_part,
380                                           new_part,
381                                           old_num_blocks * kBlockSize,
382                                           new_num_blocks * kBlockSize,
383                                           kBlockSize,
384                                           &old_block_ids,
385                                           &new_block_ids));
386
387  // If the update is inplace, we map all the blocks that didn't move,
388  // regardless of the contents since they are already copied and no operation
389  // is required.
390  if (version.InplaceUpdate()) {
391    uint64_t num_blocks = std::min(old_num_blocks, new_num_blocks);
392    for (uint64_t block = 0; block < num_blocks; block++) {
393      if (old_block_ids[block] == new_block_ids[block] &&
394          !old_visited_blocks->ContainsBlock(block) &&
395          !new_visited_blocks->ContainsBlock(block)) {
396        old_visited_blocks->AddBlock(block);
397        new_visited_blocks->AddBlock(block);
398      }
399    }
400  }
401
402  // A mapping from the block_id to the list of block numbers with that block id
403  // in the old partition. This is used to lookup where in the old partition
404  // is a block from the new partition.
405  map<BlockMapping::BlockId, vector<uint64_t>> old_blocks_map;
406
407  for (uint64_t block = old_num_blocks; block-- > 0; ) {
408    if (old_block_ids[block] != 0 && !old_visited_blocks->ContainsBlock(block))
409      old_blocks_map[old_block_ids[block]].push_back(block);
410
411    // Mark all zeroed blocks in the old image as "used" since it doesn't make
412    // any sense to spend I/O to read zeros from the source partition and more
413    // importantly, these could sometimes be blocks discarded in the SSD which
414    // would read non-zero values.
415    if (old_block_ids[block] == 0)
416      old_visited_blocks->AddBlock(block);
417  }
418
419  // The collection of blocks in the new partition with just zeros. This is a
420  // common case for free-space that's also problematic for bsdiff, so we want
421  // to optimize it using REPLACE_BZ operations. The blob for a REPLACE_BZ of
422  // just zeros is so small that it doesn't make sense to spend the I/O reading
423  // zeros from the old partition.
424  vector<Extent> new_zeros;
425
426  vector<Extent> old_identical_blocks;
427  vector<Extent> new_identical_blocks;
428
429  for (uint64_t block = 0; block < new_num_blocks; block++) {
430    // Only produce operations for blocks that were not yet visited.
431    if (new_visited_blocks->ContainsBlock(block))
432      continue;
433    if (new_block_ids[block] == 0) {
434      AppendBlockToExtents(&new_zeros, block);
435      continue;
436    }
437
438    auto old_blocks_map_it = old_blocks_map.find(new_block_ids[block]);
439    // Check if the block exists in the old partition at all.
440    if (old_blocks_map_it == old_blocks_map.end() ||
441        old_blocks_map_it->second.empty())
442      continue;
443
444    AppendBlockToExtents(&old_identical_blocks,
445                         old_blocks_map_it->second.back());
446    AppendBlockToExtents(&new_identical_blocks, block);
447    // We can't reuse source blocks in minor version 1 because the cycle
448    // breaking algorithm used in the in-place update doesn't support that.
449    if (version.InplaceUpdate())
450      old_blocks_map_it->second.pop_back();
451  }
452
453  // Produce operations for the zero blocks split per output extent.
454  // TODO(deymo): Produce ZERO operations instead of calling DeltaReadFile().
455  size_t num_ops = aops->size();
456  new_visited_blocks->AddExtents(new_zeros);
457  for (const Extent& extent : new_zeros) {
458    TEST_AND_RETURN_FALSE(DeltaReadFile(aops,
459                                        "",
460                                        new_part,
461                                        vector<Extent>(),        // old_extents
462                                        vector<Extent>{extent},  // new_extents
463                                        "<zeros>",
464                                        chunk_blocks,
465                                        version,
466                                        blob_file));
467  }
468  LOG(INFO) << "Produced " << (aops->size() - num_ops) << " operations for "
469            << BlocksInExtents(new_zeros) << " zeroed blocks";
470
471  // Produce MOVE/SOURCE_COPY operations for the moved blocks.
472  num_ops = aops->size();
473  if (chunk_blocks == -1)
474    chunk_blocks = new_num_blocks;
475  uint64_t used_blocks = 0;
476  old_visited_blocks->AddExtents(old_identical_blocks);
477  new_visited_blocks->AddExtents(new_identical_blocks);
478  for (const Extent& extent : new_identical_blocks) {
479    // We split the operation at the extent boundary or when bigger than
480    // chunk_blocks.
481    for (uint64_t op_block_offset = 0; op_block_offset < extent.num_blocks();
482         op_block_offset += chunk_blocks) {
483      aops->emplace_back();
484      AnnotatedOperation* aop = &aops->back();
485      aop->name = "<identical-blocks>";
486      aop->op.set_type(version.OperationAllowed(InstallOperation::SOURCE_COPY)
487                           ? InstallOperation::SOURCE_COPY
488                           : InstallOperation::MOVE);
489
490      uint64_t chunk_num_blocks =
491          std::min(static_cast<uint64_t>(extent.num_blocks()) - op_block_offset,
492                   static_cast<uint64_t>(chunk_blocks));
493
494      // The current operation represents the move/copy operation for the
495      // sublist starting at |used_blocks| of length |chunk_num_blocks| where
496      // the src and dst are from |old_identical_blocks| and
497      // |new_identical_blocks| respectively.
498      StoreExtents(
499          ExtentsSublist(old_identical_blocks, used_blocks, chunk_num_blocks),
500          aop->op.mutable_src_extents());
501
502      Extent* op_dst_extent = aop->op.add_dst_extents();
503      op_dst_extent->set_start_block(extent.start_block() + op_block_offset);
504      op_dst_extent->set_num_blocks(chunk_num_blocks);
505      CHECK(
506          vector<Extent>{*op_dst_extent} ==  // NOLINT(whitespace/braces)
507          ExtentsSublist(new_identical_blocks, used_blocks, chunk_num_blocks));
508
509      used_blocks += chunk_num_blocks;
510    }
511  }
512  LOG(INFO) << "Produced " << (aops->size() - num_ops) << " operations for "
513            << used_blocks << " identical blocks moved";
514
515  return true;
516}
517
518bool DeltaReadFile(vector<AnnotatedOperation>* aops,
519                   const string& old_part,
520                   const string& new_part,
521                   const vector<Extent>& old_extents,
522                   const vector<Extent>& new_extents,
523                   const string& name,
524                   ssize_t chunk_blocks,
525                   const PayloadVersion& version,
526                   BlobFileWriter* blob_file) {
527  brillo::Blob data;
528  InstallOperation operation;
529
530  uint64_t total_blocks = BlocksInExtents(new_extents);
531  if (chunk_blocks == -1)
532    chunk_blocks = total_blocks;
533
534  for (uint64_t block_offset = 0; block_offset < total_blocks;
535      block_offset += chunk_blocks) {
536    // Split the old/new file in the same chunks. Note that this could drop
537    // some information from the old file used for the new chunk. If the old
538    // file is smaller (or even empty when there's no old file) the chunk will
539    // also be empty.
540    vector<Extent> old_extents_chunk = ExtentsSublist(
541        old_extents, block_offset, chunk_blocks);
542    vector<Extent> new_extents_chunk = ExtentsSublist(
543        new_extents, block_offset, chunk_blocks);
544    NormalizeExtents(&old_extents_chunk);
545    NormalizeExtents(&new_extents_chunk);
546
547    TEST_AND_RETURN_FALSE(ReadExtentsToDiff(old_part,
548                                            new_part,
549                                            old_extents_chunk,
550                                            new_extents_chunk,
551                                            version,
552                                            &data,
553                                            &operation));
554
555    // Check if the operation writes nothing.
556    if (operation.dst_extents_size() == 0) {
557      if (operation.type() == InstallOperation::MOVE) {
558        LOG(INFO) << "Empty MOVE operation ("
559                  << name << "), skipping";
560        continue;
561      } else {
562        LOG(ERROR) << "Empty non-MOVE operation";
563        return false;
564      }
565    }
566
567    // Now, insert into the list of operations.
568    AnnotatedOperation aop;
569    aop.name = name;
570    if (static_cast<uint64_t>(chunk_blocks) < total_blocks) {
571      aop.name = base::StringPrintf("%s:%" PRIu64,
572                                    name.c_str(), block_offset / chunk_blocks);
573    }
574    aop.op = operation;
575
576    // Write the data
577    TEST_AND_RETURN_FALSE(aop.SetOperationBlob(data, blob_file));
578    aops->emplace_back(aop);
579  }
580  return true;
581}
582
583bool GenerateBestFullOperation(const brillo::Blob& new_data,
584                               const PayloadVersion& version,
585                               brillo::Blob* out_blob,
586                               InstallOperation_Type* out_type) {
587  if (new_data.empty())
588    return false;
589
590  if (version.OperationAllowed(InstallOperation::ZERO) &&
591      std::all_of(
592          new_data.begin(), new_data.end(), [](uint8_t x) { return x == 0; })) {
593    // The read buffer is all zeros, so produce a ZERO operation. No need to
594    // check other types of operations in this case.
595    *out_blob = brillo::Blob();
596    *out_type = InstallOperation::ZERO;
597    return true;
598  }
599
600  bool out_blob_set = false;
601
602  // Try compressing |new_data| with xz first.
603  if (version.OperationAllowed(InstallOperation::REPLACE_XZ)) {
604    brillo::Blob new_data_xz;
605    if (XzCompress(new_data, &new_data_xz) && !new_data_xz.empty()) {
606      *out_type = InstallOperation::REPLACE_XZ;
607      *out_blob = std::move(new_data_xz);
608      out_blob_set = true;
609    }
610  }
611
612  // Try compressing it with bzip2.
613  if (version.OperationAllowed(InstallOperation::REPLACE_BZ)) {
614    brillo::Blob new_data_bz;
615    // TODO(deymo): Implement some heuristic to determine if it is worth trying
616    // to compress the blob with bzip2 if we already have a good REPLACE_XZ.
617    if (BzipCompress(new_data, &new_data_bz) && !new_data_bz.empty() &&
618        (!out_blob_set || out_blob->size() > new_data_bz.size())) {
619      // A REPLACE_BZ is better or nothing else was set.
620      *out_type = InstallOperation::REPLACE_BZ;
621      *out_blob = std::move(new_data_bz);
622      out_blob_set = true;
623    }
624  }
625
626  // If nothing else worked or it was badly compressed we try a REPLACE.
627  if (!out_blob_set || out_blob->size() >= new_data.size()) {
628    *out_type = InstallOperation::REPLACE;
629    // This needs to make a copy of the data in the case bzip or xz didn't
630    // compress well, which is not the common case so the performance hit is
631    // low.
632    *out_blob = new_data;
633  }
634  return true;
635}
636
637bool ReadExtentsToDiff(const string& old_part,
638                       const string& new_part,
639                       const vector<Extent>& old_extents,
640                       const vector<Extent>& new_extents,
641                       const PayloadVersion& version,
642                       brillo::Blob* out_data,
643                       InstallOperation* out_op) {
644  InstallOperation operation;
645
646  // We read blocks from old_extents and write blocks to new_extents.
647  uint64_t blocks_to_read = BlocksInExtents(old_extents);
648  uint64_t blocks_to_write = BlocksInExtents(new_extents);
649
650  // Disable bsdiff, and puffdiff when the data is too big.
651  bool bsdiff_allowed =
652      version.OperationAllowed(InstallOperation::SOURCE_BSDIFF) ||
653      version.OperationAllowed(InstallOperation::BSDIFF);
654  if (bsdiff_allowed &&
655      blocks_to_read * kBlockSize > kMaxBsdiffDestinationSize) {
656    LOG(INFO) << "bsdiff blacklisted, data too big: "
657              << blocks_to_read * kBlockSize << " bytes";
658    bsdiff_allowed = false;
659  }
660
661  bool puffdiff_allowed = version.OperationAllowed(InstallOperation::PUFFDIFF);
662  if (puffdiff_allowed &&
663      blocks_to_read * kBlockSize > kMaxPuffdiffDestinationSize) {
664    LOG(INFO) << "puffdiff blacklisted, data too big: "
665              << blocks_to_read * kBlockSize << " bytes";
666    puffdiff_allowed = false;
667  }
668
669  // Make copies of the extents so we can modify them.
670  vector<Extent> src_extents = old_extents;
671  vector<Extent> dst_extents = new_extents;
672
673  // Read in bytes from new data.
674  brillo::Blob new_data;
675  TEST_AND_RETURN_FALSE(utils::ReadExtents(new_part,
676                                           new_extents,
677                                           &new_data,
678                                           kBlockSize * blocks_to_write,
679                                           kBlockSize));
680  TEST_AND_RETURN_FALSE(!new_data.empty());
681
682  // Data blob that will be written to delta file.
683  brillo::Blob data_blob;
684
685  // Try generating a full operation for the given new data, regardless of the
686  // old_data.
687  InstallOperation_Type op_type;
688  TEST_AND_RETURN_FALSE(
689      GenerateBestFullOperation(new_data, version, &data_blob, &op_type));
690  operation.set_type(op_type);
691
692  brillo::Blob old_data;
693  if (blocks_to_read > 0) {
694    // Read old data.
695    TEST_AND_RETURN_FALSE(
696        utils::ReadExtents(old_part, src_extents, &old_data,
697                           kBlockSize * blocks_to_read, kBlockSize));
698    if (old_data == new_data) {
699      // No change in data.
700      operation.set_type(version.OperationAllowed(InstallOperation::SOURCE_COPY)
701                             ? InstallOperation::SOURCE_COPY
702                             : InstallOperation::MOVE);
703      data_blob = brillo::Blob();
704    } else if (bsdiff_allowed || puffdiff_allowed) {
705      // If the source file is considered bsdiff safe (no bsdiff bugs
706      // triggered), see if BSDIFF encoding is smaller.
707      base::FilePath old_chunk;
708      TEST_AND_RETURN_FALSE(base::CreateTemporaryFile(&old_chunk));
709      ScopedPathUnlinker old_unlinker(old_chunk.value());
710      TEST_AND_RETURN_FALSE(utils::WriteFile(
711          old_chunk.value().c_str(), old_data.data(), old_data.size()));
712      base::FilePath new_chunk;
713      TEST_AND_RETURN_FALSE(base::CreateTemporaryFile(&new_chunk));
714      ScopedPathUnlinker new_unlinker(new_chunk.value());
715      TEST_AND_RETURN_FALSE(utils::WriteFile(
716          new_chunk.value().c_str(), new_data.data(), new_data.size()));
717
718      if (bsdiff_allowed) {
719        brillo::Blob bsdiff_delta;
720        TEST_AND_RETURN_FALSE(DiffFiles(
721            kBsdiffPath, old_chunk.value(), new_chunk.value(), &bsdiff_delta));
722        CHECK_GT(bsdiff_delta.size(), static_cast<brillo::Blob::size_type>(0));
723        if (bsdiff_delta.size() < data_blob.size()) {
724          operation.set_type(
725              version.OperationAllowed(InstallOperation::SOURCE_BSDIFF)
726                  ? InstallOperation::SOURCE_BSDIFF
727                  : InstallOperation::BSDIFF);
728          data_blob = std::move(bsdiff_delta);
729        }
730      }
731      if (puffdiff_allowed) {
732        LOG(ERROR) << "puffdiff is not supported yet!";
733        return false;
734      }
735    }
736  }
737
738  size_t removed_bytes = 0;
739  // Remove identical src/dst block ranges in MOVE operations.
740  if (operation.type() == InstallOperation::MOVE) {
741    removed_bytes = RemoveIdenticalBlockRanges(
742        &src_extents, &dst_extents, new_data.size());
743  }
744  // Set legacy src_length and dst_length fields.
745  operation.set_src_length(old_data.size() - removed_bytes);
746  operation.set_dst_length(new_data.size() - removed_bytes);
747
748  // Embed extents in the operation.
749  StoreExtents(src_extents, operation.mutable_src_extents());
750  StoreExtents(dst_extents, operation.mutable_dst_extents());
751
752  // Replace operations should not have source extents.
753  if (IsAReplaceOperation(operation.type())) {
754    operation.clear_src_extents();
755    operation.clear_src_length();
756  }
757
758  *out_data = std::move(data_blob);
759  *out_op = operation;
760  return true;
761}
762
763// Runs the bsdiff tool in |diff_path| on two files and returns the
764// resulting delta in |out|. Returns true on success.
765bool DiffFiles(const string& diff_path,
766               const string& old_file,
767               const string& new_file,
768               brillo::Blob* out) {
769  const string kPatchFile = "delta.patchXXXXXX";
770  string patch_file_path;
771
772  TEST_AND_RETURN_FALSE(
773      utils::MakeTempFile(kPatchFile, &patch_file_path, nullptr));
774
775  vector<string> cmd;
776  cmd.push_back(diff_path);
777  cmd.push_back(old_file);
778  cmd.push_back(new_file);
779  cmd.push_back(patch_file_path);
780
781  int rc = 1;
782  string stdout;
783  TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc, &stdout));
784  if (rc != 0) {
785    LOG(ERROR) << diff_path << " returned " << rc << std::endl << stdout;
786    return false;
787  }
788  TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
789  unlink(patch_file_path.c_str());
790  return true;
791}
792
793bool IsAReplaceOperation(InstallOperation_Type op_type) {
794  return (op_type == InstallOperation::REPLACE ||
795          op_type == InstallOperation::REPLACE_BZ ||
796          op_type == InstallOperation::REPLACE_XZ);
797}
798
799// Returns true if |op| is a no-op operation that doesn't do any useful work
800// (e.g., a move operation that copies blocks onto themselves).
801bool IsNoopOperation(const InstallOperation& op) {
802  return (op.type() == InstallOperation::MOVE &&
803          ExpandExtents(op.src_extents()) == ExpandExtents(op.dst_extents()));
804}
805
806void FilterNoopOperations(vector<AnnotatedOperation>* ops) {
807  ops->erase(
808      std::remove_if(
809          ops->begin(), ops->end(),
810          [](const AnnotatedOperation& aop){return IsNoopOperation(aop.op);}),
811      ops->end());
812}
813
814bool InitializePartitionInfo(const PartitionConfig& part, PartitionInfo* info) {
815  info->set_size(part.size);
816  HashCalculator hasher;
817  TEST_AND_RETURN_FALSE(hasher.UpdateFile(part.path, part.size) ==
818                        static_cast<off_t>(part.size));
819  TEST_AND_RETURN_FALSE(hasher.Finalize());
820  const brillo::Blob& hash = hasher.raw_hash();
821  info->set_hash(hash.data(), hash.size());
822  LOG(INFO) << part.path << ": size=" << part.size
823            << " hash=" << brillo::data_encoding::Base64Encode(hash);
824  return true;
825}
826
827bool CompareAopsByDestination(AnnotatedOperation first_aop,
828                              AnnotatedOperation second_aop) {
829  // We want empty operations to be at the end of the payload.
830  if (!first_aop.op.dst_extents().size() || !second_aop.op.dst_extents().size())
831    return ((!first_aop.op.dst_extents().size()) <
832            (!second_aop.op.dst_extents().size()));
833  uint32_t first_dst_start = first_aop.op.dst_extents(0).start_block();
834  uint32_t second_dst_start = second_aop.op.dst_extents(0).start_block();
835  return first_dst_start < second_dst_start;
836}
837
838bool IsExtFilesystem(const string& device) {
839  brillo::Blob header;
840  // See include/linux/ext2_fs.h for more details on the structure. We obtain
841  // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
842  // library.
843  if (!utils::ReadFileChunk(
844          device, 0, SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE, &header) ||
845      header.size() < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
846    return false;
847
848  const uint8_t* superblock = header.data() + SUPERBLOCK_OFFSET;
849
850  // ext3_fs.h: ext3_super_block.s_blocks_count
851  uint32_t block_count =
852      *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
853
854  // ext3_fs.h: ext3_super_block.s_log_block_size
855  uint32_t log_block_size =
856      *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
857
858  // ext3_fs.h: ext3_super_block.s_magic
859  uint16_t magic =
860      *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
861
862  block_count = le32toh(block_count);
863  log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
864  magic = le16toh(magic);
865
866  if (magic != EXT2_SUPER_MAGIC)
867    return false;
868
869  // Sanity check the parameters.
870  TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
871                        log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
872  TEST_AND_RETURN_FALSE(block_count > 0);
873  return true;
874}
875
876// Return the number of CPUs on the machine, and 4 threads in minimum.
877size_t GetMaxThreads() {
878  return std::max(sysconf(_SC_NPROCESSORS_ONLN), 4L);
879}
880
881}  // namespace diff_utils
882
883}  // namespace chromeos_update_engine
884