delta_diff_generator.cc revision a461fc37778f6c1c5aad7901417a01933ae2697a
1// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/payload_generator/delta_diff_generator.h"
6
7#include <errno.h>
8#include <fcntl.h>
9#include <inttypes.h>
10#include <sys/stat.h>
11#include <sys/types.h>
12
13#include <algorithm>
14#include <map>
15#include <memory>
16#include <set>
17#include <string>
18#include <utility>
19#include <vector>
20
21#include <base/files/file_path.h>
22#include <base/files/file_util.h>
23#include <base/logging.h>
24#include <base/strings/stringprintf.h>
25#include <base/strings/string_number_conversions.h>
26#include <base/strings/string_util.h>
27#include <bzlib.h>
28
29#include "update_engine/bzip.h"
30#include "update_engine/delta_performer.h"
31#include "update_engine/extent_ranges.h"
32#include "update_engine/file_writer.h"
33#include "update_engine/omaha_hash_calculator.h"
34#include "update_engine/payload_constants.h"
35#include "update_engine/payload_generator/cycle_breaker.h"
36#include "update_engine/payload_generator/extent_mapper.h"
37#include "update_engine/payload_generator/filesystem_iterator.h"
38#include "update_engine/payload_generator/full_update_generator.h"
39#include "update_engine/payload_generator/graph_types.h"
40#include "update_engine/payload_generator/graph_utils.h"
41#include "update_engine/payload_generator/metadata.h"
42#include "update_engine/payload_generator/payload_signer.h"
43#include "update_engine/payload_generator/topological_sort.h"
44#include "update_engine/payload_verifier.h"
45#include "update_engine/subprocess.h"
46#include "update_engine/update_metadata.pb.h"
47#include "update_engine/utils.h"
48
49using std::make_pair;
50using std::map;
51using std::max;
52using std::min;
53using std::pair;
54using std::set;
55using std::string;
56using std::unique_ptr;
57using std::vector;
58
59namespace {
60
61const uint64_t kVersionNumber = 1;
62const uint64_t kFullUpdateChunkSize = 1024 * 1024;  // bytes
63
64const size_t kBlockSize = 4096;  // bytes
65const char kEmptyPath[] = "";
66
67// The maximum destination size allowed for bsdiff. In general, bsdiff should
68// work for arbitrary big files, but the payload generation and payload
69// application requires a significant amount of RAM. We put a hard-limit of
70// 200 MiB that should not affect any released board, but will limit the
71// Chrome binary in ASan builders.
72const off_t kMaxBsdiffDestinationSize = 200 * 1024 * 1024;  // bytes
73
74static const char* kInstallOperationTypes[] = {
75  "REPLACE",
76  "REPLACE_BZ",
77  "MOVE",
78  "BSDIFF"
79};
80
81}  // namespace
82
83namespace chromeos_update_engine {
84
85typedef DeltaDiffGenerator::Block Block;
86typedef map<const DeltaArchiveManifest_InstallOperation*,
87            string> OperationNameMap;
88
89// bytes
90const size_t kRootFSPartitionSize = static_cast<size_t>(2) * 1024 * 1024 * 1024;
91
92// Needed for testing purposes, in case we can't use actual filesystem objects.
93// TODO(garnold) (chromium:331965) Replace this hack with a properly injected
94// parameter in form of a mockable abstract class.
95bool (*get_extents_with_chunk_func)(const string&, off_t, off_t,
96                                    vector<Extent>*) =
97    extent_mapper::ExtentsForFileChunkFibmap;
98
99namespace {
100
101// Stores all the extents of |path| into |extents|. Returns true on success.
102bool GatherExtents(const string& path,
103                   off_t chunk_offset,
104                   off_t chunk_size,
105                   vector<Extent>* extents) {
106  extents->clear();
107  TEST_AND_RETURN_FALSE(
108      get_extents_with_chunk_func(
109          path, chunk_offset, chunk_size, extents));
110  return true;
111}
112
113// For a given regular file which must exist at new_root + path, and
114// may exist at old_root + path, creates a new InstallOperation and
115// adds it to the graph. Also, populates the |blocks| array as
116// necessary, if |blocks| is non-null.  Also, writes the data
117// necessary to send the file down to the client into data_fd, which
118// has length *data_file_size. *data_file_size is updated
119// appropriately. If |existing_vertex| is no kInvalidIndex, use that
120// rather than allocating a new vertex. Returns true on success.
121bool DeltaReadFile(Graph* graph,
122                   Vertex::Index existing_vertex,
123                   vector<Block>* blocks,
124                   const string& old_root,
125                   const string& new_root,
126                   const string& path,  // within new_root
127                   off_t chunk_offset,
128                   off_t chunk_size,
129                   int data_fd,
130                   off_t* data_file_size) {
131  vector<char> data;
132  DeltaArchiveManifest_InstallOperation operation;
133
134  string old_path = (old_root == kEmptyPath) ? kEmptyPath :
135      old_root + path;
136
137  // If bsdiff breaks again, blacklist the problem file by using:
138  //   bsdiff_allowed = (path != "/foo/bar")
139  //
140  // TODO(dgarrett): chromium-os:15274 connect this test to the command line.
141  bool bsdiff_allowed = true;
142
143  if (utils::FileSize(new_root + path) > kMaxBsdiffDestinationSize)
144    bsdiff_allowed = false;
145
146  if (!bsdiff_allowed)
147    LOG(INFO) << "bsdiff blacklisting: " << path;
148
149  TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_path,
150                                                           new_root + path,
151                                                           chunk_offset,
152                                                           chunk_size,
153                                                           bsdiff_allowed,
154                                                           &data,
155                                                           &operation,
156                                                           true));
157
158  // Check if the operation writes nothing.
159  if (operation.dst_extents_size() == 0) {
160    if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
161      LOG(INFO) << "Empty MOVE operation (" << new_root + path << "), skipping";
162      return true;
163    } else {
164      LOG(ERROR) << "Empty non-MOVE operation";
165      return false;
166    }
167  }
168
169  // Write the data
170  if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
171    operation.set_data_offset(*data_file_size);
172    operation.set_data_length(data.size());
173  }
174
175  TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
176  *data_file_size += data.size();
177
178  // Now, insert into graph and blocks vector
179  Vertex::Index vertex = existing_vertex;
180  if (vertex == Vertex::kInvalidIndex) {
181    graph->resize(graph->size() + 1);
182    vertex = graph->size() - 1;
183  }
184  (*graph)[vertex].op = operation;
185  CHECK((*graph)[vertex].op.has_type());
186  (*graph)[vertex].file_name = path;
187  (*graph)[vertex].chunk_offset = chunk_offset;
188  (*graph)[vertex].chunk_size = chunk_size;
189
190  if (blocks)
191    TEST_AND_RETURN_FALSE(DeltaDiffGenerator::AddInstallOpToBlocksVector(
192        (*graph)[vertex].op,
193        *graph,
194        vertex,
195        blocks));
196  return true;
197}
198
199// For each regular file within new_root, creates a node in the graph,
200// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
201// and writes any necessary data to the end of data_fd.
202bool DeltaReadFiles(Graph* graph,
203                    vector<Block>* blocks,
204                    const string& old_root,
205                    const string& new_root,
206                    off_t chunk_size,
207                    int data_fd,
208                    off_t* data_file_size) {
209  set<ino_t> visited_inodes;
210  set<ino_t> visited_src_inodes;
211  for (FilesystemIterator fs_iter(new_root,
212                                  set<string>{"/lost+found"});
213       !fs_iter.IsEnd(); fs_iter.Increment()) {
214    // We never diff symlinks (here, we check that dst file is not a symlink).
215    if (!S_ISREG(fs_iter.GetStat().st_mode))
216      continue;
217
218    // Make sure we visit each inode only once.
219    if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
220      continue;
221    visited_inodes.insert(fs_iter.GetStat().st_ino);
222    off_t dst_size = fs_iter.GetFileSize();
223    if (dst_size == 0)
224      continue;
225
226    LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
227
228    // We can't visit each dst image inode more than once, as that would
229    // duplicate work. Here, we avoid visiting each source image inode
230    // more than once. Technically, we could have multiple operations
231    // that read the same blocks from the source image for diffing, but
232    // we choose not to avoid complexity. Eventually we will move away
233    // from using a graph/cycle detection/etc to generate diffs, and at that
234    // time, it will be easy (non-complex) to have many operations read
235    // from the same source blocks. At that time, this code can die. -adlr
236    bool should_diff_from_source = false;
237    string src_path = old_root + fs_iter.GetPartialPath();
238    struct stat src_stbuf;
239    // We never diff symlinks (here, we check that src file is not a symlink).
240    if (0 == lstat(src_path.c_str(), &src_stbuf) &&
241        S_ISREG(src_stbuf.st_mode)) {
242      should_diff_from_source = !utils::SetContainsKey(visited_src_inodes,
243                                                       src_stbuf.st_ino);
244      visited_src_inodes.insert(src_stbuf.st_ino);
245    }
246
247    off_t size = chunk_size == -1 ? dst_size : chunk_size;
248    off_t step = size;
249    for (off_t offset = 0; offset < dst_size; offset += step) {
250      if (offset + size >= dst_size) {
251        size = -1;  // Read through the end of the file.
252      }
253      TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
254                                          Vertex::kInvalidIndex,
255                                          blocks,
256                                          (should_diff_from_source ?
257                                           old_root :
258                                           kEmptyPath),
259                                          new_root,
260                                          fs_iter.GetPartialPath(),
261                                          offset,
262                                          size,
263                                          data_fd,
264                                          data_file_size));
265    }
266  }
267  return true;
268}
269
270// This class allocates non-existent temp blocks, starting from
271// kTempBlockStart. Other code is responsible for converting these
272// temp blocks into real blocks, as the client can't read or write to
273// these blocks.
274class DummyExtentAllocator {
275 public:
276  DummyExtentAllocator() : next_block_(kTempBlockStart) {}
277  vector<Extent> Allocate(const uint64_t block_count) {
278    vector<Extent> ret(1);
279    ret[0].set_start_block(next_block_);
280    ret[0].set_num_blocks(block_count);
281    next_block_ += block_count;
282    return ret;
283  }
284 private:
285  uint64_t next_block_;
286};
287
288// Reads blocks from image_path that are not yet marked as being written
289// in the blocks array. These blocks that remain are non-file-data blocks.
290// In the future we might consider intelligent diffing between this data
291// and data in the previous image, but for now we just bzip2 compress it
292// and include it in the update.
293// Creates a new node in the graph to write these blocks and writes the
294// appropriate blob to blobs_fd. Reads and updates blobs_length;
295bool ReadUnwrittenBlocks(const vector<Block>& blocks,
296                         int blobs_fd,
297                         off_t* blobs_length,
298                         const string& image_path,
299                         Vertex* vertex) {
300  vertex->file_name = "<rootfs-non-file-data>";
301
302  DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
303  int image_fd = open(image_path.c_str(), O_RDONLY, 000);
304  TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
305  ScopedFdCloser image_fd_closer(&image_fd);
306
307  string temp_file_path;
308  TEST_AND_RETURN_FALSE(utils::MakeTempFile("CrAU_temp_data.XXXXXX",
309                                            &temp_file_path,
310                                            nullptr));
311
312  FILE* file = fopen(temp_file_path.c_str(), "w");
313  TEST_AND_RETURN_FALSE(file);
314  int err = BZ_OK;
315
316  BZFILE* bz_file = BZ2_bzWriteOpen(&err,
317                                    file,
318                                    9,  // max compression
319                                    0,  // verbosity
320                                    0);  // default work factor
321  TEST_AND_RETURN_FALSE(err == BZ_OK);
322
323  vector<Extent> extents;
324  vector<Block>::size_type block_count = 0;
325
326  LOG(INFO) << "Appending left over blocks to extents";
327  for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
328    if (blocks[i].writer != Vertex::kInvalidIndex)
329      continue;
330    if (blocks[i].reader != Vertex::kInvalidIndex) {
331      graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
332    }
333    graph_utils::AppendBlockToExtents(&extents, i);
334    block_count++;
335  }
336
337  // Code will handle 'buf' at any size that's a multiple of kBlockSize,
338  // so we arbitrarily set it to 1024 * kBlockSize.
339  vector<char> buf(1024 * kBlockSize);
340
341  LOG(INFO) << "Reading left over blocks";
342  vector<Block>::size_type blocks_copied_count = 0;
343
344  // For each extent in extents, write the data into BZ2_bzWrite which
345  // sends it to an output file.
346  // We use the temporary buffer 'buf' to hold the data, which may be
347  // smaller than the extent, so in that case we have to loop to get
348  // the extent's data (that's the inner while loop).
349  for (const Extent& extent : extents) {
350    vector<Block>::size_type blocks_read = 0;
351    float printed_progress = -1;
352    while (blocks_read < extent.num_blocks()) {
353      const int copy_block_cnt =
354          min(buf.size() / kBlockSize,
355              static_cast<vector<char>::size_type>(
356                  extent.num_blocks() - blocks_read));
357      ssize_t rc = pread(image_fd,
358                         &buf[0],
359                         copy_block_cnt * kBlockSize,
360                         (extent.start_block() + blocks_read) * kBlockSize);
361      TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
362      TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
363                            copy_block_cnt * kBlockSize);
364      BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
365      TEST_AND_RETURN_FALSE(err == BZ_OK);
366      blocks_read += copy_block_cnt;
367      blocks_copied_count += copy_block_cnt;
368      float current_progress =
369          static_cast<float>(blocks_copied_count) / block_count;
370      if (printed_progress + 0.1 < current_progress ||
371          blocks_copied_count == block_count) {
372        LOG(INFO) << "progress: " << current_progress;
373        printed_progress = current_progress;
374      }
375    }
376  }
377  BZ2_bzWriteClose(&err, bz_file, 0, nullptr, nullptr);
378  TEST_AND_RETURN_FALSE(err == BZ_OK);
379  bz_file = nullptr;
380  TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
381  file = nullptr;
382
383  vector<char> compressed_data;
384  LOG(INFO) << "Reading compressed data off disk";
385  TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
386  TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
387
388  // Add node to graph to write these blocks
389  out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
390  out_op->set_data_offset(*blobs_length);
391  out_op->set_data_length(compressed_data.size());
392  LOG(INFO) << "Rootfs non-data blocks compressed take up "
393            << compressed_data.size();
394  *blobs_length += compressed_data.size();
395  out_op->set_dst_length(kBlockSize * block_count);
396  DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
397
398  TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
399                                        &compressed_data[0],
400                                        compressed_data.size()));
401  LOG(INFO) << "done with extra blocks";
402  return true;
403}
404
405// Writes the uint64_t passed in in host-endian to the file as big-endian.
406// Returns true on success.
407bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
408  uint64_t value_be = htobe64(value);
409  TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)));
410  return true;
411}
412
413// Adds each operation from |graph| to |out_manifest| in the order specified by
414// |order| while building |out_op_name_map| with operation to name
415// mappings. Adds all |kernel_ops| to |out_manifest|. Filters out no-op
416// operations.
417void InstallOperationsToManifest(
418    const Graph& graph,
419    const vector<Vertex::Index>& order,
420    const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
421    DeltaArchiveManifest* out_manifest,
422    OperationNameMap* out_op_name_map) {
423  for (Vertex::Index vertex_index : order) {
424    const Vertex& vertex = graph[vertex_index];
425    const DeltaArchiveManifest_InstallOperation& add_op = vertex.op;
426    if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
427      continue;
428    }
429    DeltaArchiveManifest_InstallOperation* op =
430        out_manifest->add_install_operations();
431    *op = add_op;
432    string name = vertex.file_name;
433    if (vertex.chunk_offset || vertex.chunk_size != -1) {
434      string offset = base::Int64ToString(vertex.chunk_offset);
435      if (vertex.chunk_size != -1) {
436        name += " [" + offset + ", " +
437            base::Int64ToString(vertex.chunk_offset + vertex.chunk_size - 1) +
438            "]";
439      } else {
440        name += " [" + offset + ", end]";
441      }
442    }
443    (*out_op_name_map)[op] = name;
444  }
445  for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
446           kernel_ops.begin(); it != kernel_ops.end(); ++it) {
447    const DeltaArchiveManifest_InstallOperation& add_op = *it;
448    if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
449      continue;
450    }
451    DeltaArchiveManifest_InstallOperation* op =
452        out_manifest->add_kernel_install_operations();
453    *op = add_op;
454  }
455}
456
457void CheckGraph(const Graph& graph) {
458  for (const Vertex& v : graph) {
459    CHECK(v.op.has_type());
460  }
461}
462
463// Delta compresses a kernel partition |new_kernel_part| with knowledge of the
464// old kernel partition |old_kernel_part|. If |old_kernel_part| is an empty
465// string, generates a full update of the partition.
466bool DeltaCompressKernelPartition(
467    const string& old_kernel_part,
468    const string& new_kernel_part,
469    vector<DeltaArchiveManifest_InstallOperation>* ops,
470    int blobs_fd,
471    off_t* blobs_length) {
472  LOG(INFO) << "Delta compressing kernel partition...";
473  LOG_IF(INFO, old_kernel_part.empty()) << "Generating full kernel update...";
474
475  DeltaArchiveManifest_InstallOperation op;
476  vector<char> data;
477  TEST_AND_RETURN_FALSE(
478      DeltaDiffGenerator::ReadFileToDiff(old_kernel_part,
479                                         new_kernel_part,
480                                         0,  // chunk_offset
481                                         -1,  // chunk_size
482                                         true,  // bsdiff_allowed
483                                         &data,
484                                         &op,
485                                         false));
486
487  // Check if the operation writes nothing.
488  if (op.dst_extents_size() == 0) {
489    if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
490      LOG(INFO) << "Empty MOVE operation, nothing to do.";
491      return true;
492    } else {
493      LOG(ERROR) << "Empty non-MOVE operation";
494      return false;
495    }
496  }
497
498  // Write the data.
499  if (op.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
500    op.set_data_offset(*blobs_length);
501    op.set_data_length(data.size());
502  }
503
504  // Add the new install operation.
505  ops->clear();
506  ops->push_back(op);
507
508  TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data[0], data.size()));
509  *blobs_length += data.size();
510
511  LOG(INFO) << "Done delta compressing kernel partition: "
512            << kInstallOperationTypes[op.type()];
513  return true;
514}
515
516struct DeltaObject {
517  DeltaObject(const string& in_name, const int in_type, const off_t in_size)
518      : name(in_name),
519        type(in_type),
520        size(in_size) {}
521  bool operator <(const DeltaObject& object) const {
522    return (size != object.size) ? (size < object.size) : (name < object.name);
523  }
524  string name;
525  int type;
526  off_t size;
527};
528
529void ReportPayloadUsage(const DeltaArchiveManifest& manifest,
530                        const int64_t manifest_metadata_size,
531                        const OperationNameMap& op_name_map) {
532  vector<DeltaObject> objects;
533  off_t total_size = 0;
534
535  // Rootfs install operations.
536  for (int i = 0; i < manifest.install_operations_size(); ++i) {
537    const DeltaArchiveManifest_InstallOperation& op =
538        manifest.install_operations(i);
539    objects.push_back(DeltaObject(op_name_map.find(&op)->second,
540                                  op.type(),
541                                  op.data_length()));
542    total_size += op.data_length();
543  }
544
545  // Kernel install operations.
546  for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
547    const DeltaArchiveManifest_InstallOperation& op =
548        manifest.kernel_install_operations(i);
549    objects.push_back(DeltaObject(base::StringPrintf("<kernel-operation-%d>",
550                                                     i),
551                                  op.type(),
552                                  op.data_length()));
553    total_size += op.data_length();
554  }
555
556  objects.push_back(DeltaObject("<manifest-metadata>",
557                                -1,
558                                manifest_metadata_size));
559  total_size += manifest_metadata_size;
560
561  std::sort(objects.begin(), objects.end());
562
563  static const char kFormatString[] = "%6.2f%% %10jd %-10s %s\n";
564  for (const DeltaObject& object : objects) {
565    fprintf(stderr, kFormatString,
566            object.size * 100.0 / total_size,
567            static_cast<intmax_t>(object.size),
568            object.type >= 0 ? kInstallOperationTypes[object.type] : "-",
569            object.name.c_str());
570  }
571  fprintf(stderr, kFormatString,
572          100.0, static_cast<intmax_t>(total_size), "", "<total>");
573}
574
575// Process a range of blocks from |range_start| to |range_end| in the extent at
576// position |*idx_p| of |extents|. If |do_remove| is true, this range will be
577// removed, which may cause the extent to be trimmed, split or removed entirely.
578// The value of |*idx_p| is updated to point to the next extent to be processed.
579// Returns true iff the next extent to process is a new or updated one.
580bool ProcessExtentBlockRange(vector<Extent>* extents, size_t* idx_p,
581                             const bool do_remove, uint64_t range_start,
582                             uint64_t range_end) {
583  size_t idx = *idx_p;
584  uint64_t start_block = (*extents)[idx].start_block();
585  uint64_t num_blocks = (*extents)[idx].num_blocks();
586  uint64_t range_size = range_end - range_start;
587
588  if (do_remove) {
589    if (range_size == num_blocks) {
590      // Remove the entire extent.
591      extents->erase(extents->begin() + idx);
592    } else if (range_end == num_blocks) {
593      // Trim the end of the extent.
594      (*extents)[idx].set_num_blocks(num_blocks - range_size);
595      idx++;
596    } else if (range_start == 0) {
597      // Trim the head of the extent.
598      (*extents)[idx].set_start_block(start_block + range_size);
599      (*extents)[idx].set_num_blocks(num_blocks - range_size);
600    } else {
601      // Trim the middle, splitting the remainder into two parts.
602      (*extents)[idx].set_num_blocks(range_start);
603      Extent e;
604      e.set_start_block(start_block + range_end);
605      e.set_num_blocks(num_blocks - range_end);
606      idx++;
607      extents->insert(extents->begin() + idx, e);
608    }
609  } else if (range_end == num_blocks) {
610    // Done with this extent.
611    idx++;
612  } else {
613    return false;
614  }
615
616  *idx_p = idx;
617  return true;
618}
619
620// Remove identical corresponding block ranges in |src_extents| and
621// |dst_extents|. Used for preventing moving of blocks onto themselves during
622// MOVE operations. The value of |total_bytes| indicates the actual length of
623// content; this may be slightly less than the total size of blocks, in which
624// case the last block is only partly occupied with data. Returns the total
625// number of bytes removed.
626size_t RemoveIdenticalBlockRanges(vector<Extent>* src_extents,
627                                  vector<Extent>* dst_extents,
628                                  const size_t total_bytes) {
629  size_t src_idx = 0;
630  size_t dst_idx = 0;
631  uint64_t src_offset = 0, dst_offset = 0;
632  bool new_src = true, new_dst = true;
633  size_t removed_bytes = 0, nonfull_block_bytes;
634  bool do_remove = false;
635  while (src_idx < src_extents->size() && dst_idx < dst_extents->size()) {
636    if (new_src) {
637      src_offset = 0;
638      new_src = false;
639    }
640    if (new_dst) {
641      dst_offset = 0;
642      new_dst = false;
643    }
644
645    do_remove = ((*src_extents)[src_idx].start_block() + src_offset ==
646                 (*dst_extents)[dst_idx].start_block() + dst_offset);
647
648    uint64_t src_num_blocks = (*src_extents)[src_idx].num_blocks();
649    uint64_t dst_num_blocks = (*dst_extents)[dst_idx].num_blocks();
650    uint64_t min_num_blocks = min(src_num_blocks - src_offset,
651                                  dst_num_blocks - dst_offset);
652    uint64_t prev_src_offset = src_offset;
653    uint64_t prev_dst_offset = dst_offset;
654    src_offset += min_num_blocks;
655    dst_offset += min_num_blocks;
656
657    new_src = ProcessExtentBlockRange(src_extents, &src_idx, do_remove,
658                                      prev_src_offset, src_offset);
659    new_dst = ProcessExtentBlockRange(dst_extents, &dst_idx, do_remove,
660                                      prev_dst_offset, dst_offset);
661    if (do_remove)
662      removed_bytes += min_num_blocks * kBlockSize;
663  }
664
665  // If we removed the last block and this block is only partly used by file
666  // content, deduct the unused portion from the total removed byte count.
667  if (do_remove && (nonfull_block_bytes = total_bytes % kBlockSize))
668    removed_bytes -= kBlockSize - nonfull_block_bytes;
669
670  return removed_bytes;
671}
672
673}  // namespace
674
675bool DeltaDiffGenerator::ReadFileToDiff(
676    const string& old_filename,
677    const string& new_filename,
678    off_t chunk_offset,
679    off_t chunk_size,
680    bool bsdiff_allowed,
681    vector<char>* out_data,
682    DeltaArchiveManifest_InstallOperation* out_op,
683    bool gather_extents) {
684  // Read new data in
685  vector<char> new_data;
686  TEST_AND_RETURN_FALSE(
687      utils::ReadFileChunk(new_filename, chunk_offset, chunk_size, &new_data));
688
689  TEST_AND_RETURN_FALSE(!new_data.empty());
690  TEST_AND_RETURN_FALSE(chunk_size == -1 ||
691                        static_cast<off_t>(new_data.size()) <= chunk_size);
692
693  vector<char> new_data_bz;
694  TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
695  CHECK(!new_data_bz.empty());
696
697  vector<char> data;  // Data blob that will be written to delta file.
698
699  DeltaArchiveManifest_InstallOperation operation;
700  size_t current_best_size = 0;
701  if (new_data.size() <= new_data_bz.size()) {
702    operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
703    current_best_size = new_data.size();
704    data = new_data;
705  } else {
706    operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
707    current_best_size = new_data_bz.size();
708    data = new_data_bz;
709  }
710
711  // Do we have an original file to consider?
712  off_t old_size = 0;
713  bool original = !old_filename.empty();
714  if (original && (old_size = utils::FileSize(old_filename)) < 0) {
715    // If stat-ing the old file fails, it should be because it doesn't exist.
716    TEST_AND_RETURN_FALSE(!utils::FileExists(old_filename.c_str()));
717    original = false;
718  }
719
720  vector<char> old_data;
721  if (original) {
722    // Read old data
723    TEST_AND_RETURN_FALSE(
724        utils::ReadFileChunk(
725            old_filename, chunk_offset, chunk_size, &old_data));
726    if (old_data == new_data) {
727      // No change in data.
728      operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
729      current_best_size = 0;
730      data.clear();
731    } else if (!old_data.empty() && bsdiff_allowed) {
732      // If the source file is considered bsdiff safe (no bsdiff bugs
733      // triggered), see if BSDIFF encoding is smaller.
734      base::FilePath old_chunk;
735      TEST_AND_RETURN_FALSE(base::CreateTemporaryFile(&old_chunk));
736      ScopedPathUnlinker old_unlinker(old_chunk.value());
737      TEST_AND_RETURN_FALSE(
738          utils::WriteFile(old_chunk.value().c_str(),
739                           &old_data[0], old_data.size()));
740      base::FilePath new_chunk;
741      TEST_AND_RETURN_FALSE(base::CreateTemporaryFile(&new_chunk));
742      ScopedPathUnlinker new_unlinker(new_chunk.value());
743      TEST_AND_RETURN_FALSE(
744          utils::WriteFile(new_chunk.value().c_str(),
745                           &new_data[0], new_data.size()));
746
747      vector<char> bsdiff_delta;
748      TEST_AND_RETURN_FALSE(
749          BsdiffFiles(old_chunk.value(), new_chunk.value(), &bsdiff_delta));
750      CHECK_GT(bsdiff_delta.size(), static_cast<vector<char>::size_type>(0));
751      if (bsdiff_delta.size() < current_best_size) {
752        operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
753        current_best_size = bsdiff_delta.size();
754        data = bsdiff_delta;
755      }
756    }
757  }
758
759  // Set parameters of the operations
760  CHECK_EQ(data.size(), current_best_size);
761
762  vector<Extent> src_extents, dst_extents;
763  if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
764      operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
765    if (gather_extents) {
766      TEST_AND_RETURN_FALSE(
767          GatherExtents(old_filename,
768                        chunk_offset,
769                        chunk_size,
770                        &src_extents));
771    } else {
772      Extent* src_extent = operation.add_src_extents();
773      src_extent->set_start_block(0);
774      src_extent->set_num_blocks((old_size + kBlockSize - 1) / kBlockSize);
775    }
776    operation.set_src_length(old_data.size());
777  }
778
779  if (gather_extents) {
780    TEST_AND_RETURN_FALSE(
781        GatherExtents(new_filename,
782                      chunk_offset,
783                      chunk_size,
784                      &dst_extents));
785  } else {
786    Extent* dst_extent = operation.add_dst_extents();
787    dst_extent->set_start_block(0);
788    dst_extent->set_num_blocks((new_data.size() + kBlockSize - 1) / kBlockSize);
789  }
790  operation.set_dst_length(new_data.size());
791
792  if (gather_extents) {
793    // Remove identical src/dst block ranges in MOVE operations.
794    if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
795      size_t removed_bytes = RemoveIdenticalBlockRanges(
796          &src_extents, &dst_extents, new_data.size());
797
798      // Adjust the file length field accordingly.
799      if (removed_bytes) {
800        operation.set_src_length(old_data.size() - removed_bytes);
801        operation.set_dst_length(new_data.size() - removed_bytes);
802      }
803    }
804
805    // Embed extents in the operation.
806    DeltaDiffGenerator::StoreExtents(src_extents,
807                                     operation.mutable_src_extents());
808    DeltaDiffGenerator::StoreExtents(dst_extents,
809                                     operation.mutable_dst_extents());
810  }
811
812  out_data->swap(data);
813  *out_op = operation;
814
815  return true;
816}
817
818bool DeltaDiffGenerator::InitializePartitionInfo(bool is_kernel,
819                                                 const string& partition,
820                                                 PartitionInfo* info) {
821  int64_t size = 0;
822  if (is_kernel) {
823    size = utils::FileSize(partition);
824  } else {
825    int block_count = 0, block_size = 0;
826    TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(partition,
827                                                   &block_count,
828                                                   &block_size));
829    size = static_cast<int64_t>(block_count) * block_size;
830  }
831  TEST_AND_RETURN_FALSE(size > 0);
832  info->set_size(size);
833  OmahaHashCalculator hasher;
834  TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, size) == size);
835  TEST_AND_RETURN_FALSE(hasher.Finalize());
836  const vector<char>& hash = hasher.raw_hash();
837  info->set_hash(hash.data(), hash.size());
838  LOG(INFO) << partition << ": size=" << size << " hash=" << hasher.hash();
839  return true;
840}
841
842bool InitializePartitionInfos(const string& old_kernel,
843                              const string& new_kernel,
844                              const string& old_rootfs,
845                              const string& new_rootfs,
846                              DeltaArchiveManifest* manifest) {
847  if (!old_kernel.empty()) {
848    TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
849        true,
850        old_kernel,
851        manifest->mutable_old_kernel_info()));
852  }
853  TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
854      true,
855      new_kernel,
856      manifest->mutable_new_kernel_info()));
857  if (!old_rootfs.empty()) {
858    TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
859        false,
860        old_rootfs,
861        manifest->mutable_old_rootfs_info()));
862  }
863  TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
864      false,
865      new_rootfs,
866      manifest->mutable_new_rootfs_info()));
867  return true;
868}
869
870namespace {
871
872// Takes a collection (vector or RepeatedPtrField) of Extent and
873// returns a vector of the blocks referenced, in order.
874template<typename T>
875vector<uint64_t> ExpandExtents(const T& extents) {
876  vector<uint64_t> ret;
877  for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
878    const Extent extent = graph_utils::GetElement(extents, i);
879    if (extent.start_block() == kSparseHole) {
880      ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
881    } else {
882      for (uint64_t block = extent.start_block();
883           block < (extent.start_block() + extent.num_blocks()); block++) {
884        ret.push_back(block);
885      }
886    }
887  }
888  return ret;
889}
890
891// Takes a vector of blocks and returns an equivalent vector of Extent
892// objects.
893vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
894  vector<Extent> new_extents;
895  for (uint64_t block : blocks) {
896    graph_utils::AppendBlockToExtents(&new_extents, block);
897  }
898  return new_extents;
899}
900
901}  // namespace
902
903void DeltaDiffGenerator::SubstituteBlocks(
904    Vertex* vertex,
905    const vector<Extent>& remove_extents,
906    const vector<Extent>& replace_extents) {
907  // First, expand out the blocks that op reads from
908  vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
909  {
910    // Expand remove_extents and replace_extents
911    vector<uint64_t> remove_extents_expanded =
912        ExpandExtents(remove_extents);
913    vector<uint64_t> replace_extents_expanded =
914        ExpandExtents(replace_extents);
915    CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
916    map<uint64_t, uint64_t> conversion;
917    for (vector<uint64_t>::size_type i = 0;
918         i < replace_extents_expanded.size(); i++) {
919      conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
920    }
921    utils::ApplyMap(&read_blocks, conversion);
922    for (auto& edge_prop_pair : vertex->out_edges) {
923      vector<uint64_t> write_before_deps_expanded =
924          ExpandExtents(edge_prop_pair.second.write_extents);
925      utils::ApplyMap(&write_before_deps_expanded, conversion);
926      edge_prop_pair.second.write_extents =
927          CompressExtents(write_before_deps_expanded);
928    }
929  }
930  // Convert read_blocks back to extents
931  vertex->op.clear_src_extents();
932  vector<Extent> new_extents = CompressExtents(read_blocks);
933  DeltaDiffGenerator::StoreExtents(new_extents,
934                                   vertex->op.mutable_src_extents());
935}
936
937bool DeltaDiffGenerator::CutEdges(Graph* graph,
938                                  const set<Edge>& edges,
939                                  vector<CutEdgeVertexes>* out_cuts) {
940  DummyExtentAllocator scratch_allocator;
941  vector<CutEdgeVertexes> cuts;
942  cuts.reserve(edges.size());
943
944  uint64_t scratch_blocks_used = 0;
945  for (const Edge& edge : edges) {
946    cuts.resize(cuts.size() + 1);
947    vector<Extent> old_extents =
948        (*graph)[edge.first].out_edges[edge.second].extents;
949    // Choose some scratch space
950    scratch_blocks_used += graph_utils::EdgeWeight(*graph, edge);
951    cuts.back().tmp_extents =
952        scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, edge));
953    // create vertex to copy original->scratch
954    cuts.back().new_vertex = graph->size();
955    graph->resize(graph->size() + 1);
956    cuts.back().old_src = edge.first;
957    cuts.back().old_dst = edge.second;
958
959    EdgeProperties& cut_edge_properties =
960        (*graph)[edge.first].out_edges.find(edge.second)->second;
961
962    // This should never happen, as we should only be cutting edges between
963    // real file nodes, and write-before relationships are created from
964    // a real file node to a temp copy node:
965    CHECK(cut_edge_properties.write_extents.empty())
966        << "Can't cut edge that has write-before relationship.";
967
968    // make node depend on the copy operation
969    (*graph)[edge.first].out_edges.insert(make_pair(graph->size() - 1,
970                                                   cut_edge_properties));
971
972    // Set src/dst extents and other proto variables for copy operation
973    graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
974    DeltaDiffGenerator::StoreExtents(
975        cut_edge_properties.extents,
976        graph->back().op.mutable_src_extents());
977    DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
978                                     graph->back().op.mutable_dst_extents());
979    graph->back().op.set_src_length(
980        graph_utils::EdgeWeight(*graph, edge) * kBlockSize);
981    graph->back().op.set_dst_length(graph->back().op.src_length());
982
983    // make the dest node read from the scratch space
984    DeltaDiffGenerator::SubstituteBlocks(
985        &((*graph)[edge.second]),
986        (*graph)[edge.first].out_edges[edge.second].extents,
987        cuts.back().tmp_extents);
988
989    // delete the old edge
990    CHECK_EQ(static_cast<Graph::size_type>(1),
991             (*graph)[edge.first].out_edges.erase(edge.second));
992
993    // Add an edge from dst to copy operation
994    EdgeProperties write_before_edge_properties;
995    write_before_edge_properties.write_extents = cuts.back().tmp_extents;
996    (*graph)[edge.second].out_edges.insert(
997        make_pair(graph->size() - 1, write_before_edge_properties));
998  }
999  out_cuts->swap(cuts);
1000  return true;
1001}
1002
1003// Stores all Extents in 'extents' into 'out'.
1004void DeltaDiffGenerator::StoreExtents(
1005    const vector<Extent>& extents,
1006    google::protobuf::RepeatedPtrField<Extent>* out) {
1007  for (const Extent& extent : extents) {
1008    Extent* new_extent = out->Add();
1009    *new_extent = extent;
1010  }
1011}
1012
1013// Creates all the edges for the graph. Writers of a block point to
1014// readers of the same block. This is because for an edge A->B, B
1015// must complete before A executes.
1016void DeltaDiffGenerator::CreateEdges(Graph* graph,
1017                                     const vector<Block>& blocks) {
1018  for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1019    // Blocks with both a reader and writer get an edge
1020    if (blocks[i].reader == Vertex::kInvalidIndex ||
1021        blocks[i].writer == Vertex::kInvalidIndex)
1022      continue;
1023    // Don't have a node depend on itself
1024    if (blocks[i].reader == blocks[i].writer)
1025      continue;
1026    // See if there's already an edge we can add onto
1027    Vertex::EdgeMap::iterator edge_it =
1028        (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
1029    if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
1030      // No existing edge. Create one
1031      (*graph)[blocks[i].writer].out_edges.insert(
1032          make_pair(blocks[i].reader, EdgeProperties()));
1033      edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
1034      CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
1035    }
1036    graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
1037  }
1038}
1039
1040namespace {
1041
1042class SortCutsByTopoOrderLess {
1043 public:
1044  explicit SortCutsByTopoOrderLess(
1045      const vector<vector<Vertex::Index>::size_type>& table)
1046      : table_(table) {}
1047  bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
1048    return table_[a.old_dst] < table_[b.old_dst];
1049  }
1050 private:
1051  const vector<vector<Vertex::Index>::size_type>& table_;
1052};
1053
1054}  // namespace
1055
1056void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
1057    const vector<Vertex::Index>& op_indexes,
1058    vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
1059  vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
1060  for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
1061       i != e; ++i) {
1062    Vertex::Index node = op_indexes[i];
1063    if (table.size() < (node + 1)) {
1064      table.resize(node + 1);
1065    }
1066    table[node] = i;
1067  }
1068  reverse_op_indexes->swap(table);
1069}
1070
1071void DeltaDiffGenerator::SortCutsByTopoOrder(
1072    const vector<Vertex::Index>& op_indexes,
1073    vector<CutEdgeVertexes>* cuts) {
1074  // first, make a reverse lookup table.
1075  vector<vector<Vertex::Index>::size_type> table;
1076  GenerateReverseTopoOrderMap(op_indexes, &table);
1077  SortCutsByTopoOrderLess less(table);
1078  sort(cuts->begin(), cuts->end(), less);
1079}
1080
1081void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
1082                                           vector<Vertex::Index>* op_indexes) {
1083  vector<Vertex::Index> ret;
1084  vector<Vertex::Index> full_ops;
1085  ret.reserve(op_indexes->size());
1086  for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
1087       ++i) {
1088    DeltaArchiveManifest_InstallOperation_Type type =
1089        (*graph)[(*op_indexes)[i]].op.type();
1090    if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
1091        type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
1092      full_ops.push_back((*op_indexes)[i]);
1093    } else {
1094      ret.push_back((*op_indexes)[i]);
1095    }
1096  }
1097  LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
1098            << (full_ops.size() + ret.size()) << " total ops.";
1099  ret.insert(ret.end(), full_ops.begin(), full_ops.end());
1100  op_indexes->swap(ret);
1101}
1102
1103namespace {
1104
1105template<typename T>
1106bool TempBlocksExistInExtents(const T& extents) {
1107  for (int i = 0, e = extents.size(); i < e; ++i) {
1108    Extent extent = graph_utils::GetElement(extents, i);
1109    uint64_t start = extent.start_block();
1110    uint64_t num = extent.num_blocks();
1111    if (start == kSparseHole)
1112      continue;
1113    if (start >= kTempBlockStart ||
1114        (start + num) >= kTempBlockStart) {
1115      LOG(ERROR) << "temp block!";
1116      LOG(ERROR) << "start: " << start << ", num: " << num;
1117      LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
1118      LOG(ERROR) << "returning true";
1119      return true;
1120    }
1121    // check for wrap-around, which would be a bug:
1122    CHECK(start <= (start + num));
1123  }
1124  return false;
1125}
1126
1127// Converts the cuts, which must all have the same |old_dst| member,
1128// to full. It does this by converting the |old_dst| to REPLACE or
1129// REPLACE_BZ, dropping all incoming edges to |old_dst|, and marking
1130// all temp nodes invalid.
1131bool ConvertCutsToFull(
1132    Graph* graph,
1133    const string& new_root,
1134    int data_fd,
1135    off_t* data_file_size,
1136    vector<Vertex::Index>* op_indexes,
1137    vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
1138    const vector<CutEdgeVertexes>& cuts) {
1139  CHECK(!cuts.empty());
1140  set<Vertex::Index> deleted_nodes;
1141  for (const CutEdgeVertexes& cut : cuts) {
1142    TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ConvertCutToFullOp(
1143        graph,
1144        cut,
1145        new_root,
1146        data_fd,
1147        data_file_size));
1148    deleted_nodes.insert(cut.new_vertex);
1149  }
1150  deleted_nodes.insert(cuts[0].old_dst);
1151
1152  vector<Vertex::Index> new_op_indexes;
1153  new_op_indexes.reserve(op_indexes->size());
1154  for (Vertex::Index vertex_index : *op_indexes) {
1155    if (utils::SetContainsKey(deleted_nodes, vertex_index))
1156      continue;
1157    new_op_indexes.push_back(vertex_index);
1158  }
1159  new_op_indexes.push_back(cuts[0].old_dst);
1160  op_indexes->swap(new_op_indexes);
1161  DeltaDiffGenerator::GenerateReverseTopoOrderMap(*op_indexes,
1162                                                  reverse_op_indexes);
1163  return true;
1164}
1165
1166// Tries to assign temp blocks for a collection of cuts, all of which share
1167// the same old_dst member. If temp blocks can't be found, old_dst will be
1168// converted to a REPLACE or REPLACE_BZ operation. Returns true on success,
1169// which can happen even if blocks are converted to full. Returns false
1170// on exceptional error cases.
1171bool AssignBlockForAdjoiningCuts(
1172    Graph* graph,
1173    const string& new_root,
1174    int data_fd,
1175    off_t* data_file_size,
1176    vector<Vertex::Index>* op_indexes,
1177    vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
1178    const vector<CutEdgeVertexes>& cuts) {
1179  CHECK(!cuts.empty());
1180  const Vertex::Index old_dst = cuts[0].old_dst;
1181  // Calculate # of blocks needed
1182  uint64_t blocks_needed = 0;
1183  vector<uint64_t> cuts_blocks_needed(cuts.size());
1184  for (vector<CutEdgeVertexes>::size_type i = 0; i < cuts.size(); ++i) {
1185    uint64_t cut_blocks_needed = 0;
1186    for (const Extent& extent : cuts[i].tmp_extents) {
1187      cut_blocks_needed += extent.num_blocks();
1188    }
1189    blocks_needed += cut_blocks_needed;
1190    cuts_blocks_needed[i] = cut_blocks_needed;
1191  }
1192
1193  // Find enough blocks
1194  ExtentRanges scratch_ranges;
1195  // Each block that's supplying temp blocks and the corresponding blocks:
1196  typedef vector<pair<Vertex::Index, ExtentRanges>> SupplierVector;
1197  SupplierVector block_suppliers;
1198  uint64_t scratch_blocks_found = 0;
1199  for (vector<Vertex::Index>::size_type i = (*reverse_op_indexes)[old_dst] + 1,
1200           e = op_indexes->size(); i < e; ++i) {
1201    Vertex::Index test_node = (*op_indexes)[i];
1202    if (!(*graph)[test_node].valid)
1203      continue;
1204    // See if this node has sufficient blocks
1205    ExtentRanges ranges;
1206    ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
1207    ranges.SubtractExtent(ExtentForRange(
1208        kTempBlockStart, kSparseHole - kTempBlockStart));
1209    ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
1210    // For now, for simplicity, subtract out all blocks in read-before
1211    // dependencies.
1212    for (Vertex::EdgeMap::const_iterator edge_i =
1213             (*graph)[test_node].out_edges.begin(),
1214             edge_e = (*graph)[test_node].out_edges.end();
1215         edge_i != edge_e; ++edge_i) {
1216      ranges.SubtractExtents(edge_i->second.extents);
1217    }
1218    if (ranges.blocks() == 0)
1219      continue;
1220
1221    if (ranges.blocks() + scratch_blocks_found > blocks_needed) {
1222      // trim down ranges
1223      vector<Extent> new_ranges = ranges.GetExtentsForBlockCount(
1224          blocks_needed - scratch_blocks_found);
1225      ranges = ExtentRanges();
1226      ranges.AddExtents(new_ranges);
1227    }
1228    scratch_ranges.AddRanges(ranges);
1229    block_suppliers.push_back(make_pair(test_node, ranges));
1230    scratch_blocks_found += ranges.blocks();
1231    if (scratch_ranges.blocks() >= blocks_needed)
1232      break;
1233  }
1234  if (scratch_ranges.blocks() < blocks_needed) {
1235    LOG(INFO) << "Unable to find sufficient scratch";
1236    TEST_AND_RETURN_FALSE(ConvertCutsToFull(graph,
1237                                            new_root,
1238                                            data_fd,
1239                                            data_file_size,
1240                                            op_indexes,
1241                                            reverse_op_indexes,
1242                                            cuts));
1243    return true;
1244  }
1245  // Use the scratch we found
1246  TEST_AND_RETURN_FALSE(scratch_ranges.blocks() == scratch_blocks_found);
1247
1248  // Make all the suppliers depend on this node
1249  for (const auto& index_range_pair : block_suppliers) {
1250    graph_utils::AddReadBeforeDepExtents(
1251        &(*graph)[index_range_pair.first],
1252        old_dst,
1253        index_range_pair.second.GetExtentsForBlockCount(
1254            index_range_pair.second.blocks()));
1255  }
1256
1257  // Replace temp blocks in each cut
1258  for (vector<CutEdgeVertexes>::size_type i = 0; i < cuts.size(); ++i) {
1259    const CutEdgeVertexes& cut = cuts[i];
1260    vector<Extent> real_extents =
1261        scratch_ranges.GetExtentsForBlockCount(cuts_blocks_needed[i]);
1262    scratch_ranges.SubtractExtents(real_extents);
1263
1264    // Fix the old dest node w/ the real blocks
1265    DeltaDiffGenerator::SubstituteBlocks(&(*graph)[old_dst],
1266                                         cut.tmp_extents,
1267                                         real_extents);
1268
1269    // Fix the new node w/ the real blocks. Since the new node is just a
1270    // copy operation, we can replace all the dest extents w/ the real
1271    // blocks.
1272    DeltaArchiveManifest_InstallOperation *op = &(*graph)[cut.new_vertex].op;
1273    op->clear_dst_extents();
1274    DeltaDiffGenerator::StoreExtents(real_extents, op->mutable_dst_extents());
1275  }
1276  return true;
1277}
1278
1279}  // namespace
1280
1281// Returns true if |op| is a no-op operation that doesn't do any useful work
1282// (e.g., a move operation that copies blocks onto themselves).
1283bool DeltaDiffGenerator::IsNoopOperation(
1284    const DeltaArchiveManifest_InstallOperation& op) {
1285  return (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE &&
1286          ExpandExtents(op.src_extents()) == ExpandExtents(op.dst_extents()));
1287}
1288
1289bool DeltaDiffGenerator::AssignTempBlocks(
1290    Graph* graph,
1291    const string& new_root,
1292    int data_fd,
1293    off_t* data_file_size,
1294    vector<Vertex::Index>* op_indexes,
1295    vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
1296    const vector<CutEdgeVertexes>& cuts) {
1297  CHECK(!cuts.empty());
1298
1299  // group of cuts w/ the same old_dst:
1300  vector<CutEdgeVertexes> cuts_group;
1301
1302  for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
1303       true ; --i) {
1304    LOG(INFO) << "Fixing temp blocks in cut " << i
1305              << ": old dst: " << cuts[i].old_dst << " new vertex: "
1306              << cuts[i].new_vertex << " path: "
1307              << (*graph)[cuts[i].old_dst].file_name;
1308
1309    if (cuts_group.empty() || (cuts_group[0].old_dst == cuts[i].old_dst)) {
1310      cuts_group.push_back(cuts[i]);
1311    } else {
1312      CHECK(!cuts_group.empty());
1313      TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1314                                                        new_root,
1315                                                        data_fd,
1316                                                        data_file_size,
1317                                                        op_indexes,
1318                                                        reverse_op_indexes,
1319                                                        cuts_group));
1320      cuts_group.clear();
1321      cuts_group.push_back(cuts[i]);
1322    }
1323
1324    if (i == e) {
1325      // break out of for() loop
1326      break;
1327    }
1328  }
1329  CHECK(!cuts_group.empty());
1330  TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1331                                                    new_root,
1332                                                    data_fd,
1333                                                    data_file_size,
1334                                                    op_indexes,
1335                                                    reverse_op_indexes,
1336                                                    cuts_group));
1337  return true;
1338}
1339
1340bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1341  size_t idx = 0;
1342  for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1343       ++it, ++idx) {
1344    if (!it->valid)
1345      continue;
1346    const DeltaArchiveManifest_InstallOperation& op = it->op;
1347    if (TempBlocksExistInExtents(op.dst_extents()) ||
1348        TempBlocksExistInExtents(op.src_extents())) {
1349      LOG(INFO) << "bad extents in node " << idx;
1350      LOG(INFO) << "so yeah";
1351      return false;
1352    }
1353
1354    // Check out-edges:
1355    for (const auto& edge_prop_pair : it->out_edges) {
1356      if (TempBlocksExistInExtents(edge_prop_pair.second.extents) ||
1357          TempBlocksExistInExtents(edge_prop_pair.second.write_extents)) {
1358        LOG(INFO) << "bad out edge in node " << idx;
1359        LOG(INFO) << "so yeah";
1360        return false;
1361      }
1362    }
1363  }
1364  return true;
1365}
1366
1367bool DeltaDiffGenerator::ReorderDataBlobs(
1368    DeltaArchiveManifest* manifest,
1369    const string& data_blobs_path,
1370    const string& new_data_blobs_path) {
1371  int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1372  TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1373  ScopedFdCloser in_fd_closer(&in_fd);
1374
1375  DirectFileWriter writer;
1376  TEST_AND_RETURN_FALSE(
1377      writer.Open(new_data_blobs_path.c_str(),
1378                  O_WRONLY | O_TRUNC | O_CREAT,
1379                  0644) == 0);
1380  ScopedFileWriterCloser writer_closer(&writer);
1381  uint64_t out_file_size = 0;
1382
1383  for (int i = 0; i < (manifest->install_operations_size() +
1384                       manifest->kernel_install_operations_size()); i++) {
1385    DeltaArchiveManifest_InstallOperation* op = nullptr;
1386    if (i < manifest->install_operations_size()) {
1387      op = manifest->mutable_install_operations(i);
1388    } else {
1389      op = manifest->mutable_kernel_install_operations(
1390          i - manifest->install_operations_size());
1391    }
1392    if (!op->has_data_offset())
1393      continue;
1394    CHECK(op->has_data_length());
1395    vector<char> buf(op->data_length());
1396    ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1397    TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1398
1399    // Add the hash of the data blobs for this operation
1400    TEST_AND_RETURN_FALSE(AddOperationHash(op, buf));
1401
1402    op->set_data_offset(out_file_size);
1403    TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()));
1404    out_file_size += buf.size();
1405  }
1406  return true;
1407}
1408
1409bool DeltaDiffGenerator::AddOperationHash(
1410    DeltaArchiveManifest_InstallOperation* op,
1411    const vector<char>& buf) {
1412  OmahaHashCalculator hasher;
1413
1414  TEST_AND_RETURN_FALSE(hasher.Update(&buf[0], buf.size()));
1415  TEST_AND_RETURN_FALSE(hasher.Finalize());
1416
1417  const vector<char>& hash = hasher.raw_hash();
1418  op->set_data_sha256_hash(hash.data(), hash.size());
1419  return true;
1420}
1421
1422bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1423                                            const CutEdgeVertexes& cut,
1424                                            const string& new_root,
1425                                            int data_fd,
1426                                            off_t* data_file_size) {
1427  // Drop all incoming edges, keep all outgoing edges
1428
1429  // Keep all outgoing edges
1430  if ((*graph)[cut.old_dst].op.type() !=
1431      DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ &&
1432      (*graph)[cut.old_dst].op.type() !=
1433      DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
1434    Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1435    graph_utils::DropWriteBeforeDeps(&out_edges);
1436
1437    TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1438                                        cut.old_dst,
1439                                        nullptr,
1440                                        kEmptyPath,
1441                                        new_root,
1442                                        (*graph)[cut.old_dst].file_name,
1443                                        (*graph)[cut.old_dst].chunk_offset,
1444                                        (*graph)[cut.old_dst].chunk_size,
1445                                        data_fd,
1446                                        data_file_size));
1447
1448    (*graph)[cut.old_dst].out_edges = out_edges;
1449
1450    // Right now we don't have doubly-linked edges, so we have to scan
1451    // the whole graph.
1452    graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1453  }
1454
1455  // Delete temp node
1456  (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1457  CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1458        (*graph)[cut.old_dst].out_edges.end());
1459  (*graph)[cut.new_vertex].valid = false;
1460  LOG(INFO) << "marked node invalid: " << cut.new_vertex;
1461  return true;
1462}
1463
1464bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1465                                           const string& new_root,
1466                                           int fd,
1467                                           off_t* data_file_size,
1468                                           vector<Vertex::Index>* final_order,
1469                                           Vertex::Index scratch_vertex) {
1470  CycleBreaker cycle_breaker;
1471  LOG(INFO) << "Finding cycles...";
1472  set<Edge> cut_edges;
1473  cycle_breaker.BreakCycles(*graph, &cut_edges);
1474  LOG(INFO) << "done finding cycles";
1475  CheckGraph(*graph);
1476
1477  // Calculate number of scratch blocks needed
1478
1479  LOG(INFO) << "Cutting cycles...";
1480  vector<CutEdgeVertexes> cuts;
1481  TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1482  LOG(INFO) << "done cutting cycles";
1483  LOG(INFO) << "There are " << cuts.size() << " cuts.";
1484  CheckGraph(*graph);
1485
1486  LOG(INFO) << "Creating initial topological order...";
1487  TopologicalSort(*graph, final_order);
1488  LOG(INFO) << "done with initial topo order";
1489  CheckGraph(*graph);
1490
1491  LOG(INFO) << "Moving full ops to the back";
1492  MoveFullOpsToBack(graph, final_order);
1493  LOG(INFO) << "done moving full ops to back";
1494
1495  vector<vector<Vertex::Index>::size_type> inverse_final_order;
1496  GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1497
1498  SortCutsByTopoOrder(*final_order, &cuts);
1499
1500  if (!cuts.empty())
1501    TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1502                                           new_root,
1503                                           fd,
1504                                           data_file_size,
1505                                           final_order,
1506                                           &inverse_final_order,
1507                                           cuts));
1508  LOG(INFO) << "Making sure all temp blocks have been allocated";
1509
1510  // Remove the scratch node, if any
1511  if (scratch_vertex != Vertex::kInvalidIndex) {
1512    final_order->erase(final_order->begin() +
1513                       inverse_final_order[scratch_vertex]);
1514    (*graph)[scratch_vertex].valid = false;
1515    GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1516  }
1517
1518  graph_utils::DumpGraph(*graph);
1519  CHECK(NoTempBlocksRemain(*graph));
1520  LOG(INFO) << "done making sure all temp blocks are allocated";
1521  return true;
1522}
1523
1524void DeltaDiffGenerator::CreateScratchNode(uint64_t start_block,
1525                                           uint64_t num_blocks,
1526                                           Vertex* vertex) {
1527  vertex->file_name = "<scratch>";
1528  vertex->op.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1529  vertex->op.set_data_offset(0);
1530  vertex->op.set_data_length(0);
1531  Extent* extent = vertex->op.add_dst_extents();
1532  extent->set_start_block(start_block);
1533  extent->set_num_blocks(num_blocks);
1534}
1535
1536bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1537    const string& old_root,
1538    const string& old_image,
1539    const string& new_root,
1540    const string& new_image,
1541    const string& old_kernel_part,
1542    const string& new_kernel_part,
1543    const string& output_path,
1544    const string& private_key_path,
1545    off_t chunk_size,
1546    size_t rootfs_partition_size,
1547    const ImageInfo* old_image_info,
1548    const ImageInfo* new_image_info,
1549    uint64_t* metadata_size) {
1550  TEST_AND_RETURN_FALSE(chunk_size == -1 || chunk_size % kBlockSize == 0);
1551  int old_image_block_count = 0, old_image_block_size = 0;
1552  int new_image_block_count = 0, new_image_block_size = 0;
1553  TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(new_image,
1554                                                 &new_image_block_count,
1555                                                 &new_image_block_size));
1556  if (!old_image.empty()) {
1557    TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(old_image,
1558                                                   &old_image_block_count,
1559                                                   &old_image_block_size));
1560    TEST_AND_RETURN_FALSE(old_image_block_size == new_image_block_size);
1561    LOG_IF(WARNING, old_image_block_count != new_image_block_count)
1562        << "Old and new images have different block counts.";
1563
1564    // If new_image_info is present, old_image_info must be present.
1565    TEST_AND_RETURN_FALSE(!old_image_info == !new_image_info);
1566  } else {
1567    // old_image_info must not be present for a full update.
1568    TEST_AND_RETURN_FALSE(!old_image_info);
1569  }
1570
1571  // Sanity checks for the partition size.
1572  TEST_AND_RETURN_FALSE(rootfs_partition_size % kBlockSize == 0);
1573  size_t fs_size = static_cast<size_t>(new_image_block_size) *
1574                   new_image_block_count;
1575  LOG(INFO) << "Rootfs partition size: " << rootfs_partition_size;
1576  LOG(INFO) << "Actual filesystem size: " << fs_size;
1577  TEST_AND_RETURN_FALSE(rootfs_partition_size >= fs_size);
1578
1579  // Sanity check kernel partition arg
1580  TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1581
1582  vector<Block> blocks(max(old_image_block_count, new_image_block_count));
1583  LOG(INFO) << "Invalid block index: " << Vertex::kInvalidIndex;
1584  LOG(INFO) << "Block count: " << blocks.size();
1585  for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1586    CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1587    CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1588  }
1589  Graph graph;
1590  CheckGraph(graph);
1591
1592  const string kTempFileTemplate("CrAU_temp_data.XXXXXX");
1593  string temp_file_path;
1594  unique_ptr<ScopedPathUnlinker> temp_file_unlinker;
1595  off_t data_file_size = 0;
1596
1597  LOG(INFO) << "Reading files...";
1598
1599  // Create empty protobuf Manifest object
1600  DeltaArchiveManifest manifest;
1601
1602  vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1603
1604  vector<Vertex::Index> final_order;
1605  Vertex::Index scratch_vertex = Vertex::kInvalidIndex;
1606  {
1607    int fd;
1608    TEST_AND_RETURN_FALSE(
1609        utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
1610    temp_file_unlinker.reset(new ScopedPathUnlinker(temp_file_path));
1611    TEST_AND_RETURN_FALSE(fd >= 0);
1612    ScopedFdCloser fd_closer(&fd);
1613    if (!old_image.empty()) {
1614      // Delta update
1615
1616      TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1617                                           &blocks,
1618                                           old_root,
1619                                           new_root,
1620                                           chunk_size,
1621                                           fd,
1622                                           &data_file_size));
1623      LOG(INFO) << "done reading normal files";
1624      CheckGraph(graph);
1625
1626      LOG(INFO) << "Starting metadata processing";
1627      TEST_AND_RETURN_FALSE(Metadata::DeltaReadMetadata(&graph,
1628                                                        &blocks,
1629                                                        old_image,
1630                                                        new_image,
1631                                                        fd,
1632                                                        &data_file_size));
1633      LOG(INFO) << "Done metadata processing";
1634      CheckGraph(graph);
1635
1636      graph.resize(graph.size() + 1);
1637      TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1638                                                fd,
1639                                                &data_file_size,
1640                                                new_image,
1641                                                &graph.back()));
1642
1643      // Final scratch block (if there's space)
1644      if (blocks.size() < (rootfs_partition_size / kBlockSize)) {
1645        scratch_vertex = graph.size();
1646        graph.resize(graph.size() + 1);
1647        CreateScratchNode(blocks.size(),
1648                          (rootfs_partition_size / kBlockSize) - blocks.size(),
1649                          &graph.back());
1650      }
1651
1652      // Read kernel partition
1653      TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1654                                                         new_kernel_part,
1655                                                         &kernel_ops,
1656                                                         fd,
1657                                                         &data_file_size));
1658
1659      LOG(INFO) << "done reading kernel";
1660      CheckGraph(graph);
1661
1662      LOG(INFO) << "Creating edges...";
1663      CreateEdges(&graph, blocks);
1664      LOG(INFO) << "Done creating edges";
1665      CheckGraph(graph);
1666
1667      TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1668                                              new_root,
1669                                              fd,
1670                                              &data_file_size,
1671                                              &final_order,
1672                                              scratch_vertex));
1673
1674      // Set the minor version for this payload.
1675      LOG(INFO) << "Adding Delta Minor Version.";
1676      manifest.set_minor_version(DeltaPerformer::kSupportedMinorPayloadVersion);
1677    } else {
1678      // Full update
1679      off_t new_image_size =
1680          static_cast<off_t>(new_image_block_count) * new_image_block_size;
1681      TEST_AND_RETURN_FALSE(FullUpdateGenerator::Run(&graph,
1682                                                     new_kernel_part,
1683                                                     new_image,
1684                                                     new_image_size,
1685                                                     fd,
1686                                                     &data_file_size,
1687                                                     kFullUpdateChunkSize,
1688                                                     kBlockSize,
1689                                                     &kernel_ops,
1690                                                     &final_order));
1691
1692      // Set the minor version for this payload.
1693      LOG(INFO) << "Adding Full Minor Version.";
1694      manifest.set_minor_version(DeltaPerformer::kFullPayloadMinorVersion);
1695    }
1696  }
1697
1698  if (old_image_info)
1699    *(manifest.mutable_old_image_info()) = *old_image_info;
1700
1701  if (new_image_info)
1702    *(manifest.mutable_new_image_info()) = *new_image_info;
1703
1704  OperationNameMap op_name_map;
1705  CheckGraph(graph);
1706  InstallOperationsToManifest(graph,
1707                              final_order,
1708                              kernel_ops,
1709                              &manifest,
1710                              &op_name_map);
1711  CheckGraph(graph);
1712  manifest.set_block_size(kBlockSize);
1713
1714  // Reorder the data blobs with the newly ordered manifest
1715  string ordered_blobs_path;
1716  TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1717      "CrAU_temp_data.ordered.XXXXXX",
1718      &ordered_blobs_path,
1719      nullptr));
1720  ScopedPathUnlinker ordered_blobs_unlinker(ordered_blobs_path);
1721  TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1722                                         temp_file_path,
1723                                         ordered_blobs_path));
1724  temp_file_unlinker.reset();
1725
1726  // Check that install op blobs are in order.
1727  uint64_t next_blob_offset = 0;
1728  {
1729    for (int i = 0; i < (manifest.install_operations_size() +
1730                         manifest.kernel_install_operations_size()); i++) {
1731      DeltaArchiveManifest_InstallOperation* op =
1732          i < manifest.install_operations_size() ?
1733          manifest.mutable_install_operations(i) :
1734          manifest.mutable_kernel_install_operations(
1735              i - manifest.install_operations_size());
1736      if (op->has_data_offset()) {
1737        if (op->data_offset() != next_blob_offset) {
1738          LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
1739                     << next_blob_offset;
1740        }
1741        next_blob_offset += op->data_length();
1742      }
1743    }
1744  }
1745
1746  // Signatures appear at the end of the blobs. Note the offset in the
1747  // manifest
1748  if (!private_key_path.empty()) {
1749    uint64_t signature_blob_length = 0;
1750    TEST_AND_RETURN_FALSE(
1751        PayloadSigner::SignatureBlobLength(vector<string>(1, private_key_path),
1752                                           &signature_blob_length));
1753    AddSignatureOp(next_blob_offset, signature_blob_length, &manifest);
1754  }
1755
1756  TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1757                                                 new_kernel_part,
1758                                                 old_image,
1759                                                 new_image,
1760                                                 &manifest));
1761
1762  // Serialize protobuf
1763  string serialized_manifest;
1764
1765  CheckGraph(graph);
1766  TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1767  CheckGraph(graph);
1768
1769  LOG(INFO) << "Writing final delta file header...";
1770  DirectFileWriter writer;
1771  TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1772                                          O_WRONLY | O_CREAT | O_TRUNC,
1773                                          0644) == 0);
1774  ScopedFileWriterCloser writer_closer(&writer);
1775
1776  // Write header
1777  TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)));
1778
1779  // Write version number
1780  TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
1781
1782  // Write protobuf length
1783  TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1784                                               serialized_manifest.size()));
1785
1786  // Write protobuf
1787  LOG(INFO) << "Writing final delta file protobuf... "
1788            << serialized_manifest.size();
1789  TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
1790                                     serialized_manifest.size()));
1791
1792  // Append the data blobs
1793  LOG(INFO) << "Writing final delta file data blobs...";
1794  int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
1795  ScopedFdCloser blobs_fd_closer(&blobs_fd);
1796  TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1797  for (;;) {
1798    char buf[kBlockSize];
1799    ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1800    if (0 == rc) {
1801      // EOF
1802      break;
1803    }
1804    TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
1805    TEST_AND_RETURN_FALSE(writer.Write(buf, rc));
1806  }
1807
1808  // Write signature blob.
1809  if (!private_key_path.empty()) {
1810    LOG(INFO) << "Signing the update...";
1811    vector<char> signature_blob;
1812    TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(
1813        output_path,
1814        vector<string>(1, private_key_path),
1815        &signature_blob));
1816    TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
1817                                       signature_blob.size()));
1818  }
1819
1820  *metadata_size =
1821      strlen(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
1822  ReportPayloadUsage(manifest, *metadata_size, op_name_map);
1823
1824  LOG(INFO) << "All done. Successfully created delta file with "
1825            << "metadata size = " << *metadata_size;
1826  return true;
1827}
1828
1829// Runs the bsdiff tool on two files and returns the resulting delta in
1830// 'out'. Returns true on success.
1831bool DeltaDiffGenerator::BsdiffFiles(const string& old_file,
1832                                     const string& new_file,
1833                                     vector<char>* out) {
1834  const string kPatchFile = "delta.patchXXXXXX";
1835  string patch_file_path;
1836
1837  TEST_AND_RETURN_FALSE(
1838      utils::MakeTempFile(kPatchFile, &patch_file_path, nullptr));
1839
1840  vector<string> cmd;
1841  cmd.push_back(kBsdiffPath);
1842  cmd.push_back(old_file);
1843  cmd.push_back(new_file);
1844  cmd.push_back(patch_file_path);
1845
1846  int rc = 1;
1847  vector<char> patch_file;
1848  TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc, nullptr));
1849  TEST_AND_RETURN_FALSE(rc == 0);
1850  TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
1851  unlink(patch_file_path.c_str());
1852  return true;
1853}
1854
1855// The |blocks| vector contains a reader and writer for each block on the
1856// filesystem that's being in-place updated. We populate the reader/writer
1857// fields of |blocks| by calling this function.
1858// For each block in |operation| that is read or written, find that block
1859// in |blocks| and set the reader/writer field to the vertex passed.
1860// |graph| is not strictly necessary, but useful for printing out
1861// error messages.
1862bool DeltaDiffGenerator::AddInstallOpToBlocksVector(
1863    const DeltaArchiveManifest_InstallOperation& operation,
1864    const Graph& graph,
1865    Vertex::Index vertex,
1866    vector<Block>* blocks) {
1867  // See if this is already present.
1868  TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
1869
1870  enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
1871  for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
1872    const int extents_size =
1873        (field == READER) ? operation.src_extents_size() :
1874        operation.dst_extents_size();
1875    const char* past_participle = (field == READER) ? "read" : "written";
1876    const google::protobuf::RepeatedPtrField<Extent>& extents =
1877        (field == READER) ? operation.src_extents() : operation.dst_extents();
1878    Vertex::Index Block::*access_type =
1879        (field == READER) ? &Block::reader : &Block::writer;
1880
1881    for (int i = 0; i < extents_size; i++) {
1882      const Extent& extent = extents.Get(i);
1883      if (extent.start_block() == kSparseHole) {
1884        // Hole in sparse file. skip
1885        continue;
1886      }
1887      for (uint64_t block = extent.start_block();
1888           block < (extent.start_block() + extent.num_blocks()); block++) {
1889        if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
1890          LOG(FATAL) << "Block " << block << " is already "
1891                     << past_participle << " by "
1892                     << (*blocks)[block].*access_type << "("
1893                     << graph[(*blocks)[block].*access_type].file_name
1894                     << ") and also " << vertex << "("
1895                     << graph[vertex].file_name << ")";
1896        }
1897        (*blocks)[block].*access_type = vertex;
1898      }
1899    }
1900  }
1901  return true;
1902}
1903
1904void DeltaDiffGenerator::AddSignatureOp(uint64_t signature_blob_offset,
1905                                        uint64_t signature_blob_length,
1906                                        DeltaArchiveManifest* manifest) {
1907  LOG(INFO) << "Making room for signature in file";
1908  manifest->set_signatures_offset(signature_blob_offset);
1909  LOG(INFO) << "set? " << manifest->has_signatures_offset();
1910  // Add a dummy op at the end to appease older clients
1911  DeltaArchiveManifest_InstallOperation* dummy_op =
1912      manifest->add_kernel_install_operations();
1913  dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1914  dummy_op->set_data_offset(signature_blob_offset);
1915  manifest->set_signatures_offset(signature_blob_offset);
1916  dummy_op->set_data_length(signature_blob_length);
1917  manifest->set_signatures_size(signature_blob_length);
1918  Extent* dummy_extent = dummy_op->add_dst_extents();
1919  // Tell the dummy op to write this data to a big sparse hole
1920  dummy_extent->set_start_block(kSparseHole);
1921  dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1922                               kBlockSize);
1923}
1924
1925const char* const kBsdiffPath = "bsdiff";
1926
1927};  // namespace chromeos_update_engine
1928