blob: 1ebf6bb6a322769339e9885becf1e73560bd46ea [file] [log] [blame]
Don Garrettf4b28742012-03-27 20:48:06 -07001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
adlr@google.com3defe6a2009-12-04 20:57:17 +00002// 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/delta_diff_generator.h"
Darin Petkov880335c2010-10-01 15:52:53 -07006
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07007#include <errno.h>
8#include <fcntl.h>
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07009#include <inttypes.h>
Darin Petkov880335c2010-10-01 15:52:53 -070010#include <sys/stat.h>
11#include <sys/types.h>
12
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070013#include <algorithm>
Andrew de los Reyesef017552010-10-06 17:57:52 -070014#include <map>
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070015#include <set>
16#include <string>
17#include <utility>
18#include <vector>
Darin Petkov880335c2010-10-01 15:52:53 -070019
Alex Vakulenko75039d72014-03-25 12:36:28 -070020#include <base/files/file_path.h>
Darin Petkov8e447e02013-04-16 16:23:50 +020021#include <base/file_util.h>
Darin Petkov880335c2010-10-01 15:52:53 -070022#include <base/logging.h>
Darin Petkov7438a5c2011-08-29 11:56:44 -070023#include <base/memory/scoped_ptr.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070024#include <base/strings/string_number_conversions.h>
25#include <base/strings/string_util.h>
26#include <base/strings/stringprintf.h>
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070027#include <bzlib.h>
Darin Petkov880335c2010-10-01 15:52:53 -070028
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070029#include "update_engine/bzip.h"
30#include "update_engine/cycle_breaker.h"
Don Garrettb8dd1d92013-11-22 17:40:02 -080031#include "update_engine/delta_performer.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070032#include "update_engine/extent_mapper.h"
Andrew de los Reyesef017552010-10-06 17:57:52 -070033#include "update_engine/extent_ranges.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070034#include "update_engine/file_writer.h"
35#include "update_engine/filesystem_iterator.h"
Darin Petkov7a22d792010-11-08 14:10:00 -080036#include "update_engine/full_update_generator.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070037#include "update_engine/graph_types.h"
38#include "update_engine/graph_utils.h"
Thieu Le5c7d9752010-12-15 16:09:28 -080039#include "update_engine/metadata.h"
Darin Petkov36a58222010-10-07 22:00:09 -070040#include "update_engine/omaha_hash_calculator.h"
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -070041#include "update_engine/payload_signer.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070042#include "update_engine/subprocess.h"
43#include "update_engine/topological_sort.h"
44#include "update_engine/update_metadata.pb.h"
45#include "update_engine/utils.h"
46
47using std::make_pair;
Andrew de los Reyesef017552010-10-06 17:57:52 -070048using std::map;
Andrew de los Reyes3270f742010-07-15 22:28:14 -070049using std::max;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070050using std::min;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -070051using std::pair;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070052using std::set;
53using std::string;
54using std::vector;
55
56namespace chromeos_update_engine {
57
58typedef DeltaDiffGenerator::Block Block;
Darin Petkov9fa7ec52010-10-18 11:45:23 -070059typedef map<const DeltaArchiveManifest_InstallOperation*,
Darin Petkov8e447e02013-04-16 16:23:50 +020060 string> OperationNameMap;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070061
Chris Sosaf586b012013-05-21 13:33:42 -070062// bytes
63const size_t kRootFSPartitionSize = static_cast<size_t>(2) * 1024 * 1024 * 1024;
Chris Sosad5ae1562013-04-23 13:20:18 -070064const uint64_t kVersionNumber = 1;
65const uint64_t kFullUpdateChunkSize = 1024 * 1024; // bytes
66
Gilad Arnoldfa404502014-01-01 23:36:12 -080067// Needed for testing purposes, in case we can't use actual filesystem objects.
68// TODO(garnold)(chromium:331965) Replace this hack with a properly injected
69// parameter in form of a mockable abstract class.
70bool (*get_extents_with_chunk_func)(const std::string&, off_t, off_t,
71 std::vector<Extent>*) =
72 extent_mapper::ExtentsForFileChunkFibmap;
73
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070074namespace {
Andrew de los Reyes27f7d372010-10-07 11:26:07 -070075const size_t kBlockSize = 4096; // bytes
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -080076const string kNonexistentPath = "";
Andrew de los Reyes927179d2010-12-02 11:26:48 -080077
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070078
Darin Petkov68c10d12010-10-14 09:24:37 -070079static const char* kInstallOperationTypes[] = {
80 "REPLACE",
81 "REPLACE_BZ",
82 "MOVE",
83 "BSDIFF"
84};
85
Gilad Arnoldfa404502014-01-01 23:36:12 -080086// Stores all the extents of |path| into |extents|. Returns true on success.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070087bool GatherExtents(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +020088 off_t chunk_offset,
89 off_t chunk_size,
Gilad Arnoldfa404502014-01-01 23:36:12 -080090 vector<Extent>* extents) {
91 extents->clear();
Darin Petkov8e447e02013-04-16 16:23:50 +020092 TEST_AND_RETURN_FALSE(
Gilad Arnoldfa404502014-01-01 23:36:12 -080093 get_extents_with_chunk_func(
94 path, chunk_offset, chunk_size, extents));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070095 return true;
96}
97
Andrew de los Reyesef017552010-10-06 17:57:52 -070098// For a given regular file which must exist at new_root + path, and
99// may exist at old_root + path, creates a new InstallOperation and
100// adds it to the graph. Also, populates the |blocks| array as
101// necessary, if |blocks| is non-NULL. Also, writes the data
102// necessary to send the file down to the client into data_fd, which
103// has length *data_file_size. *data_file_size is updated
104// appropriately. If |existing_vertex| is no kInvalidIndex, use that
105// rather than allocating a new vertex. Returns true on success.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700106bool DeltaReadFile(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700107 Vertex::Index existing_vertex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700108 vector<Block>* blocks,
109 const string& old_root,
110 const string& new_root,
111 const string& path, // within new_root
Darin Petkov8e447e02013-04-16 16:23:50 +0200112 off_t chunk_offset,
113 off_t chunk_size,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700114 int data_fd,
115 off_t* data_file_size) {
116 vector<char> data;
117 DeltaArchiveManifest_InstallOperation operation;
118
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800119 string old_path = (old_root == kNonexistentPath) ? kNonexistentPath :
120 old_root + path;
121
Don Garrett1d787092013-03-11 18:07:28 -0700122 // If bsdiff breaks again, blacklist the problem file by using:
123 // bsdiff_allowed = (path != "/foo/bar")
Don Garrett36e60772012-03-29 10:31:20 -0700124 //
Don Garrett1d787092013-03-11 18:07:28 -0700125 // TODO(dgarrett): chromium-os:15274 connect this test to the command line.
Don Garrett36e60772012-03-29 10:31:20 -0700126 bool bsdiff_allowed = true;
Don Garrettf4b28742012-03-27 20:48:06 -0700127
Don Garrett36e60772012-03-29 10:31:20 -0700128 if (!bsdiff_allowed)
129 LOG(INFO) << "bsdiff blacklisting: " << path;
Don Garrettf4b28742012-03-27 20:48:06 -0700130
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800131 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_path,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700132 new_root + path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200133 chunk_offset,
134 chunk_size,
Don Garrett36e60772012-03-29 10:31:20 -0700135 bsdiff_allowed,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700136 &data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700137 &operation,
138 true));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700139
Gilad Arnoldfa404502014-01-01 23:36:12 -0800140 // Check if the operation writes nothing.
141 if (operation.dst_extents_size() == 0) {
142 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
143 LOG(INFO) << "Empty MOVE operation (" << new_root + path << "), skipping";
144 return true;
145 } else {
146 LOG(ERROR) << "Empty non-MOVE operation";
147 return false;
148 }
149 }
150
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700151 // Write the data
152 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
153 operation.set_data_offset(*data_file_size);
154 operation.set_data_length(data.size());
155 }
156
157 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
158 *data_file_size += data.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700159
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700160 // Now, insert into graph and blocks vector
Andrew de los Reyesef017552010-10-06 17:57:52 -0700161 Vertex::Index vertex = existing_vertex;
162 if (vertex == Vertex::kInvalidIndex) {
163 graph->resize(graph->size() + 1);
164 vertex = graph->size() - 1;
165 }
166 (*graph)[vertex].op = operation;
167 CHECK((*graph)[vertex].op.has_type());
168 (*graph)[vertex].file_name = path;
Darin Petkov8e447e02013-04-16 16:23:50 +0200169 (*graph)[vertex].chunk_offset = chunk_offset;
170 (*graph)[vertex].chunk_size = chunk_size;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700171
Andrew de los Reyesef017552010-10-06 17:57:52 -0700172 if (blocks)
Thieu Le5c7d9752010-12-15 16:09:28 -0800173 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::AddInstallOpToBlocksVector(
174 (*graph)[vertex].op,
175 *graph,
176 vertex,
177 blocks));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700178 return true;
179}
180
181// For each regular file within new_root, creates a node in the graph,
182// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
183// and writes any necessary data to the end of data_fd.
184bool DeltaReadFiles(Graph* graph,
185 vector<Block>* blocks,
186 const string& old_root,
187 const string& new_root,
Darin Petkov8e447e02013-04-16 16:23:50 +0200188 off_t chunk_size,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700189 int data_fd,
190 off_t* data_file_size) {
191 set<ino_t> visited_inodes;
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800192 set<ino_t> visited_src_inodes;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700193 for (FilesystemIterator fs_iter(new_root,
194 utils::SetWithValue<string>("/lost+found"));
195 !fs_iter.IsEnd(); fs_iter.Increment()) {
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800196 // We never diff symlinks (here, we check that dst file is not a symlink).
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700197 if (!S_ISREG(fs_iter.GetStat().st_mode))
198 continue;
199
200 // Make sure we visit each inode only once.
201 if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
202 continue;
203 visited_inodes.insert(fs_iter.GetStat().st_ino);
Darin Petkov8e447e02013-04-16 16:23:50 +0200204 off_t dst_size = fs_iter.GetStat().st_size;
205 if (dst_size == 0)
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700206 continue;
207
208 LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700209
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800210 // We can't visit each dst image inode more than once, as that would
211 // duplicate work. Here, we avoid visiting each source image inode
212 // more than once. Technically, we could have multiple operations
213 // that read the same blocks from the source image for diffing, but
214 // we choose not to to avoid complexity. Eventually we will move away
215 // from using a graph/cycle detection/etc to generate diffs, and at that
216 // time, it will be easy (non-complex) to have many operations read
217 // from the same source blocks. At that time, this code can die. -adlr
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800218 bool should_diff_from_source = false;
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800219 string src_path = old_root + fs_iter.GetPartialPath();
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800220 struct stat src_stbuf;
221 // We never diff symlinks (here, we check that src file is not a symlink).
222 if (0 == lstat(src_path.c_str(), &src_stbuf) &&
223 S_ISREG(src_stbuf.st_mode)) {
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800224 should_diff_from_source = !utils::SetContainsKey(visited_src_inodes,
225 src_stbuf.st_ino);
226 visited_src_inodes.insert(src_stbuf.st_ino);
227 }
228
Darin Petkov8e447e02013-04-16 16:23:50 +0200229 off_t size = chunk_size == -1 ? dst_size : chunk_size;
230 off_t step = size;
231 for (off_t offset = 0; offset < dst_size; offset += step) {
232 if (offset + size >= dst_size) {
233 size = -1; // Read through the end of the file.
234 }
235 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
236 Vertex::kInvalidIndex,
237 blocks,
238 (should_diff_from_source ?
239 old_root :
240 kNonexistentPath),
241 new_root,
242 fs_iter.GetPartialPath(),
243 offset,
244 size,
245 data_fd,
246 data_file_size));
247 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700248 }
249 return true;
250}
251
Andrew de los Reyesef017552010-10-06 17:57:52 -0700252// This class allocates non-existent temp blocks, starting from
253// kTempBlockStart. Other code is responsible for converting these
254// temp blocks into real blocks, as the client can't read or write to
255// these blocks.
256class DummyExtentAllocator {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700257 public:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700258 explicit DummyExtentAllocator()
259 : next_block_(kTempBlockStart) {}
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700260 vector<Extent> Allocate(const uint64_t block_count) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700261 vector<Extent> ret(1);
262 ret[0].set_start_block(next_block_);
263 ret[0].set_num_blocks(block_count);
264 next_block_ += block_count;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700265 return ret;
266 }
267 private:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700268 uint64_t next_block_;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700269};
270
271// Reads blocks from image_path that are not yet marked as being written
272// in the blocks array. These blocks that remain are non-file-data blocks.
273// In the future we might consider intelligent diffing between this data
274// and data in the previous image, but for now we just bzip2 compress it
275// and include it in the update.
276// Creates a new node in the graph to write these blocks and writes the
277// appropriate blob to blobs_fd. Reads and updates blobs_length;
278bool ReadUnwrittenBlocks(const vector<Block>& blocks,
279 int blobs_fd,
280 off_t* blobs_length,
281 const string& image_path,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700282 Vertex* vertex) {
Darin Petkovabe7cc92010-10-08 12:29:32 -0700283 vertex->file_name = "<rootfs-non-file-data>";
284
Andrew de los Reyesef017552010-10-06 17:57:52 -0700285 DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700286 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
287 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
288 ScopedFdCloser image_fd_closer(&image_fd);
289
290 string temp_file_path;
Gilad Arnolda6742b32014-01-11 00:18:34 -0800291 TEST_AND_RETURN_FALSE(utils::MakeTempFile("CrAU_temp_data.XXXXXX",
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700292 &temp_file_path,
293 NULL));
294
295 FILE* file = fopen(temp_file_path.c_str(), "w");
296 TEST_AND_RETURN_FALSE(file);
297 int err = BZ_OK;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700298
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700299 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
300 file,
301 9, // max compression
302 0, // verbosity
303 0); // default work factor
304 TEST_AND_RETURN_FALSE(err == BZ_OK);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700305
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700306 vector<Extent> extents;
307 vector<Block>::size_type block_count = 0;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700308
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700309 LOG(INFO) << "Appending left over blocks to extents";
310 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
311 if (blocks[i].writer != Vertex::kInvalidIndex)
312 continue;
Andrew de los Reyesef017552010-10-06 17:57:52 -0700313 if (blocks[i].reader != Vertex::kInvalidIndex) {
314 graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
315 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700316 graph_utils::AppendBlockToExtents(&extents, i);
317 block_count++;
318 }
319
320 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
321 // so we arbitrarily set it to 1024 * kBlockSize.
322 vector<char> buf(1024 * kBlockSize);
323
324 LOG(INFO) << "Reading left over blocks";
325 vector<Block>::size_type blocks_copied_count = 0;
326
327 // For each extent in extents, write the data into BZ2_bzWrite which
328 // sends it to an output file.
329 // We use the temporary buffer 'buf' to hold the data, which may be
330 // smaller than the extent, so in that case we have to loop to get
331 // the extent's data (that's the inner while loop).
332 for (vector<Extent>::const_iterator it = extents.begin();
333 it != extents.end(); ++it) {
334 vector<Block>::size_type blocks_read = 0;
Andrew de los Reyes4b8740f2010-11-08 17:09:11 -0800335 float printed_progress = -1;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700336 while (blocks_read < it->num_blocks()) {
337 const int copy_block_cnt =
338 min(buf.size() / kBlockSize,
339 static_cast<vector<char>::size_type>(
340 it->num_blocks() - blocks_read));
341 ssize_t rc = pread(image_fd,
342 &buf[0],
343 copy_block_cnt * kBlockSize,
344 (it->start_block() + blocks_read) * kBlockSize);
345 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
346 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
347 copy_block_cnt * kBlockSize);
348 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
349 TEST_AND_RETURN_FALSE(err == BZ_OK);
350 blocks_read += copy_block_cnt;
351 blocks_copied_count += copy_block_cnt;
Andrew de los Reyes4b8740f2010-11-08 17:09:11 -0800352 float current_progress =
353 static_cast<float>(blocks_copied_count) / block_count;
354 if (printed_progress + 0.1 < current_progress ||
355 blocks_copied_count == block_count) {
356 LOG(INFO) << "progress: " << current_progress;
357 printed_progress = current_progress;
358 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700359 }
360 }
361 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
362 TEST_AND_RETURN_FALSE(err == BZ_OK);
363 bz_file = NULL;
364 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
365 file = NULL;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700366
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700367 vector<char> compressed_data;
368 LOG(INFO) << "Reading compressed data off disk";
369 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
370 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700371
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700372 // Add node to graph to write these blocks
373 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
374 out_op->set_data_offset(*blobs_length);
375 out_op->set_data_length(compressed_data.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700376 LOG(INFO) << "Rootfs non-data blocks compressed take up "
377 << compressed_data.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700378 *blobs_length += compressed_data.size();
379 out_op->set_dst_length(kBlockSize * block_count);
380 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700381
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700382 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
383 &compressed_data[0],
384 compressed_data.size()));
385 LOG(INFO) << "done with extra blocks";
386 return true;
387}
388
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700389// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700390// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700391bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
392 uint64_t value_be = htobe64(value);
Don Garrette410e0f2011-11-10 15:39:01 -0800393 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700394 return true;
395}
396
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700397// Adds each operation from |graph| to |out_manifest| in the order specified by
398// |order| while building |out_op_name_map| with operation to name
399// mappings. Adds all |kernel_ops| to |out_manifest|. Filters out no-op
400// operations.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700401void InstallOperationsToManifest(
402 const Graph& graph,
403 const vector<Vertex::Index>& order,
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700404 const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700405 DeltaArchiveManifest* out_manifest,
406 OperationNameMap* out_op_name_map) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700407 for (vector<Vertex::Index>::const_iterator it = order.begin();
408 it != order.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700409 const Vertex& vertex = graph[*it];
410 const DeltaArchiveManifest_InstallOperation& add_op = vertex.op;
411 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
412 continue;
413 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700414 DeltaArchiveManifest_InstallOperation* op =
415 out_manifest->add_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700416 *op = add_op;
Darin Petkov8e447e02013-04-16 16:23:50 +0200417 string name = vertex.file_name;
418 if (vertex.chunk_offset || vertex.chunk_size != -1) {
419 string offset = base::Int64ToString(vertex.chunk_offset);
420 if (vertex.chunk_size != -1) {
421 name += " [" + offset + ", " +
422 base::Int64ToString(vertex.chunk_offset + vertex.chunk_size - 1) +
423 "]";
424 } else {
425 name += " [" + offset + ", end]";
426 }
427 }
428 (*out_op_name_map)[op] = name;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700429 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700430 for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
431 kernel_ops.begin(); it != kernel_ops.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700432 const DeltaArchiveManifest_InstallOperation& add_op = *it;
433 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
434 continue;
435 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700436 DeltaArchiveManifest_InstallOperation* op =
437 out_manifest->add_kernel_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700438 *op = add_op;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700439 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700440}
441
442void CheckGraph(const Graph& graph) {
443 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
444 CHECK(it->op.has_type());
445 }
446}
447
Darin Petkov68c10d12010-10-14 09:24:37 -0700448// Delta compresses a kernel partition |new_kernel_part| with knowledge of the
449// old kernel partition |old_kernel_part|. If |old_kernel_part| is an empty
450// string, generates a full update of the partition.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700451bool DeltaCompressKernelPartition(
452 const string& old_kernel_part,
453 const string& new_kernel_part,
454 vector<DeltaArchiveManifest_InstallOperation>* ops,
455 int blobs_fd,
456 off_t* blobs_length) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700457 LOG(INFO) << "Delta compressing kernel partition...";
Darin Petkov68c10d12010-10-14 09:24:37 -0700458 LOG_IF(INFO, old_kernel_part.empty()) << "Generating full kernel update...";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700459
Gilad Arnoldfa404502014-01-01 23:36:12 -0800460 DeltaArchiveManifest_InstallOperation op;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700461 vector<char> data;
Don Garrett36e60772012-03-29 10:31:20 -0700462 TEST_AND_RETURN_FALSE(
463 DeltaDiffGenerator::ReadFileToDiff(old_kernel_part,
464 new_kernel_part,
Darin Petkov8e447e02013-04-16 16:23:50 +0200465 0, // chunk_offset
466 -1, // chunk_size
Don Garrett36e60772012-03-29 10:31:20 -0700467 true, // bsdiff_allowed
468 &data,
Gilad Arnoldfa404502014-01-01 23:36:12 -0800469 &op,
Don Garrett36e60772012-03-29 10:31:20 -0700470 false));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700471
Gilad Arnoldfa404502014-01-01 23:36:12 -0800472 // Check if the operation writes nothing.
473 if (op.dst_extents_size() == 0) {
474 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
475 LOG(INFO) << "Empty MOVE operation, nothing to do.";
476 return true;
477 } else {
478 LOG(ERROR) << "Empty non-MOVE operation";
479 return false;
480 }
Darin Petkov68c10d12010-10-14 09:24:37 -0700481 }
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700482
Gilad Arnoldfa404502014-01-01 23:36:12 -0800483 // Write the data.
484 if (op.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
485 op.set_data_offset(*blobs_length);
486 op.set_data_length(data.size());
487 }
488
489 // Add the new install operation.
490 ops->clear();
491 ops->push_back(op);
492
Darin Petkov68c10d12010-10-14 09:24:37 -0700493 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data[0], data.size()));
494 *blobs_length += data.size();
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700495
Darin Petkov68c10d12010-10-14 09:24:37 -0700496 LOG(INFO) << "Done delta compressing kernel partition: "
Gilad Arnoldfa404502014-01-01 23:36:12 -0800497 << kInstallOperationTypes[op.type()];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700498 return true;
499}
500
Darin Petkov880335c2010-10-01 15:52:53 -0700501struct DeltaObject {
502 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
503 : name(in_name),
504 type(in_type),
505 size(in_size) {}
506 bool operator <(const DeltaObject& object) const {
Darin Petkovd43d6902010-10-14 11:17:50 -0700507 return (size != object.size) ? (size < object.size) : (name < object.name);
Darin Petkov880335c2010-10-01 15:52:53 -0700508 }
509 string name;
510 int type;
511 off_t size;
512};
513
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700514void ReportPayloadUsage(const DeltaArchiveManifest& manifest,
515 const int64_t manifest_metadata_size,
516 const OperationNameMap& op_name_map) {
Darin Petkov880335c2010-10-01 15:52:53 -0700517 vector<DeltaObject> objects;
518 off_t total_size = 0;
519
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700520 // Rootfs install operations.
521 for (int i = 0; i < manifest.install_operations_size(); ++i) {
522 const DeltaArchiveManifest_InstallOperation& op =
523 manifest.install_operations(i);
Darin Petkov8e447e02013-04-16 16:23:50 +0200524 objects.push_back(DeltaObject(op_name_map.find(&op)->second,
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700525 op.type(),
526 op.data_length()));
527 total_size += op.data_length();
Darin Petkov880335c2010-10-01 15:52:53 -0700528 }
529
Darin Petkov880335c2010-10-01 15:52:53 -0700530 // Kernel install operations.
531 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
532 const DeltaArchiveManifest_InstallOperation& op =
533 manifest.kernel_install_operations(i);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700534 objects.push_back(DeltaObject(base::StringPrintf("<kernel-operation-%d>",
535 i),
Darin Petkov880335c2010-10-01 15:52:53 -0700536 op.type(),
537 op.data_length()));
538 total_size += op.data_length();
539 }
540
Darin Petkov95cf01f2010-10-12 14:59:13 -0700541 objects.push_back(DeltaObject("<manifest-metadata>",
542 -1,
543 manifest_metadata_size));
544 total_size += manifest_metadata_size;
545
Darin Petkov880335c2010-10-01 15:52:53 -0700546 std::sort(objects.begin(), objects.end());
547
Alex Vakulenko75039d72014-03-25 12:36:28 -0700548 static const char kFormatString[] = "%6.2f%% %10jd %-10s %s\n";
Darin Petkov880335c2010-10-01 15:52:53 -0700549 for (vector<DeltaObject>::const_iterator it = objects.begin();
550 it != objects.end(); ++it) {
551 const DeltaObject& object = *it;
552 fprintf(stderr, kFormatString,
553 object.size * 100.0 / total_size,
Alex Vakulenko75039d72014-03-25 12:36:28 -0700554 static_cast<intmax_t>(object.size),
Darin Petkov95cf01f2010-10-12 14:59:13 -0700555 object.type >= 0 ? kInstallOperationTypes[object.type] : "-",
Darin Petkov880335c2010-10-01 15:52:53 -0700556 object.name.c_str());
557 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700558 fprintf(stderr, kFormatString,
559 100.0, static_cast<intmax_t>(total_size), "", "<total>");
Darin Petkov880335c2010-10-01 15:52:53 -0700560}
561
Gilad Arnoldfa404502014-01-01 23:36:12 -0800562// Process a range of blocks from |range_start| to |range_end| in the extent at
563// position |*idx_p| of |extents|. If |do_remove| is true, this range will be
564// removed, which may cause the extent to be trimmed, split or removed entirely.
565// The value of |*idx_p| is updated to point to the next extent to be processed.
566// Returns true iff the next extent to process is a new or updated one.
567bool ProcessExtentBlockRange(vector<Extent>* extents, size_t* idx_p,
568 const bool do_remove, uint64_t range_start,
569 uint64_t range_end) {
570 size_t idx = *idx_p;
571 uint64_t start_block = (*extents)[idx].start_block();
572 uint64_t num_blocks = (*extents)[idx].num_blocks();
573 uint64_t range_size = range_end - range_start;
574
575 if (do_remove) {
576 if (range_size == num_blocks) {
577 // Remove the entire extent.
578 extents->erase(extents->begin() + idx);
579 } else if (range_end == num_blocks) {
580 // Trim the end of the extent.
581 (*extents)[idx].set_num_blocks(num_blocks - range_size);
582 idx++;
583 } else if (range_start == 0) {
584 // Trim the head of the extent.
585 (*extents)[idx].set_start_block(start_block + range_size);
586 (*extents)[idx].set_num_blocks(num_blocks - range_size);
587 } else {
588 // Trim the middle, splitting the remainder into two parts.
589 (*extents)[idx].set_num_blocks(range_start);
590 Extent e;
591 e.set_start_block(start_block + range_end);
592 e.set_num_blocks(num_blocks - range_end);
593 idx++;
594 extents->insert(extents->begin() + idx, e);
595 }
596 } else if (range_end == num_blocks) {
597 // Done with this extent.
598 idx++;
599 } else {
600 return false;
601 }
602
603 *idx_p = idx;
604 return true;
605}
606
607// Remove identical corresponding block ranges in |src_extents| and
608// |dst_extents|. Used for preventing moving of blocks onto themselves during
Gilad Arnoldebca5712014-01-10 14:26:37 -0800609// MOVE operations. The value of |total_bytes| indicates the actual length of
610// content; this may be slightly less than the total size of blocks, in which
611// case the last block is only partly occupied with data. Returns the total
612// number of bytes removed.
613size_t RemoveIdenticalBlockRanges(vector<Extent>* src_extents,
614 vector<Extent>* dst_extents,
615 const size_t total_bytes) {
Gilad Arnoldfa404502014-01-01 23:36:12 -0800616 size_t src_idx = 0;
617 size_t dst_idx = 0;
618 uint64_t src_offset = 0, dst_offset = 0;
619 bool new_src = true, new_dst = true;
Gilad Arnoldebca5712014-01-10 14:26:37 -0800620 size_t removed_bytes = 0, nonfull_block_bytes;
621 bool do_remove = false;
Gilad Arnoldfa404502014-01-01 23:36:12 -0800622 while (src_idx < src_extents->size() && dst_idx < dst_extents->size()) {
623 if (new_src) {
624 src_offset = 0;
625 new_src = false;
626 }
627 if (new_dst) {
628 dst_offset = 0;
629 new_dst = false;
630 }
631
Gilad Arnoldebca5712014-01-10 14:26:37 -0800632 do_remove = ((*src_extents)[src_idx].start_block() + src_offset ==
633 (*dst_extents)[dst_idx].start_block() + dst_offset);
Gilad Arnoldfa404502014-01-01 23:36:12 -0800634
635 uint64_t src_num_blocks = (*src_extents)[src_idx].num_blocks();
636 uint64_t dst_num_blocks = (*dst_extents)[dst_idx].num_blocks();
637 uint64_t min_num_blocks = min(src_num_blocks - src_offset,
638 dst_num_blocks - dst_offset);
639 uint64_t prev_src_offset = src_offset;
640 uint64_t prev_dst_offset = dst_offset;
641 src_offset += min_num_blocks;
642 dst_offset += min_num_blocks;
643
644 new_src = ProcessExtentBlockRange(src_extents, &src_idx, do_remove,
645 prev_src_offset, src_offset);
646 new_dst = ProcessExtentBlockRange(dst_extents, &dst_idx, do_remove,
647 prev_dst_offset, dst_offset);
Gilad Arnoldebca5712014-01-10 14:26:37 -0800648 if (do_remove)
649 removed_bytes += min_num_blocks * kBlockSize;
Gilad Arnoldfa404502014-01-01 23:36:12 -0800650 }
Gilad Arnoldebca5712014-01-10 14:26:37 -0800651
652 // If we removed the last block and this block is only partly used by file
653 // content, deduct the unused portion from the total removed byte count.
654 if (do_remove && (nonfull_block_bytes = total_bytes % kBlockSize))
655 removed_bytes -= kBlockSize - nonfull_block_bytes;
656
657 return removed_bytes;
Gilad Arnoldfa404502014-01-01 23:36:12 -0800658}
659
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700660} // namespace {}
661
662bool DeltaDiffGenerator::ReadFileToDiff(
663 const string& old_filename,
664 const string& new_filename,
Darin Petkov8e447e02013-04-16 16:23:50 +0200665 off_t chunk_offset,
666 off_t chunk_size,
Don Garrett36e60772012-03-29 10:31:20 -0700667 bool bsdiff_allowed,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700668 vector<char>* out_data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700669 DeltaArchiveManifest_InstallOperation* out_op,
670 bool gather_extents) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700671 // Read new data in
672 vector<char> new_data;
Darin Petkov8e447e02013-04-16 16:23:50 +0200673 TEST_AND_RETURN_FALSE(
674 utils::ReadFileChunk(new_filename, chunk_offset, chunk_size, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700675
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700676 TEST_AND_RETURN_FALSE(!new_data.empty());
Darin Petkov8e447e02013-04-16 16:23:50 +0200677 TEST_AND_RETURN_FALSE(chunk_size == -1 ||
678 static_cast<off_t>(new_data.size()) <= chunk_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700679
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700680 vector<char> new_data_bz;
681 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
682 CHECK(!new_data_bz.empty());
683
684 vector<char> data; // Data blob that will be written to delta file.
685
686 DeltaArchiveManifest_InstallOperation operation;
687 size_t current_best_size = 0;
688 if (new_data.size() <= new_data_bz.size()) {
689 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
690 current_best_size = new_data.size();
691 data = new_data;
692 } else {
693 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
694 current_best_size = new_data_bz.size();
695 data = new_data_bz;
696 }
697
698 // Do we have an original file to consider?
699 struct stat old_stbuf;
Don Garrettf4b28742012-03-27 20:48:06 -0700700 bool original = !old_filename.empty();
701 if (original && 0 != stat(old_filename.c_str(), &old_stbuf)) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700702 // If stat-ing the old file fails, it should be because it doesn't exist.
703 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
Don Garrettf4b28742012-03-27 20:48:06 -0700704 original = false;
Darin Petkov68c10d12010-10-14 09:24:37 -0700705 }
Don Garrettf4b28742012-03-27 20:48:06 -0700706
Darin Petkov8e447e02013-04-16 16:23:50 +0200707 vector<char> old_data;
Don Garrettf4b28742012-03-27 20:48:06 -0700708 if (original) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700709 // Read old data
Darin Petkov8e447e02013-04-16 16:23:50 +0200710 TEST_AND_RETURN_FALSE(
711 utils::ReadFileChunk(
712 old_filename, chunk_offset, chunk_size, &old_data));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700713 if (old_data == new_data) {
714 // No change in data.
715 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
716 current_best_size = 0;
717 data.clear();
Darin Petkov8e447e02013-04-16 16:23:50 +0200718 } else if (!old_data.empty() && bsdiff_allowed) {
Don Garrett36e60772012-03-29 10:31:20 -0700719 // If the source file is considered bsdiff safe (no bsdiff bugs
720 // triggered), see if BSDIFF encoding is smaller.
Alex Vakulenko75039d72014-03-25 12:36:28 -0700721 base::FilePath old_chunk;
722 TEST_AND_RETURN_FALSE(base::CreateTemporaryFile(&old_chunk));
Darin Petkov8e447e02013-04-16 16:23:50 +0200723 ScopedPathUnlinker old_unlinker(old_chunk.value());
724 TEST_AND_RETURN_FALSE(
725 utils::WriteFile(old_chunk.value().c_str(),
726 &old_data[0], old_data.size()));
Alex Vakulenko75039d72014-03-25 12:36:28 -0700727 base::FilePath new_chunk;
728 TEST_AND_RETURN_FALSE(base::CreateTemporaryFile(&new_chunk));
Darin Petkov8e447e02013-04-16 16:23:50 +0200729 ScopedPathUnlinker new_unlinker(new_chunk.value());
730 TEST_AND_RETURN_FALSE(
731 utils::WriteFile(new_chunk.value().c_str(),
732 &new_data[0], new_data.size()));
733
Don Garrett36e60772012-03-29 10:31:20 -0700734 vector<char> bsdiff_delta;
735 TEST_AND_RETURN_FALSE(
Darin Petkov8e447e02013-04-16 16:23:50 +0200736 BsdiffFiles(old_chunk.value(), new_chunk.value(), &bsdiff_delta));
Don Garrett36e60772012-03-29 10:31:20 -0700737 CHECK_GT(bsdiff_delta.size(), static_cast<vector<char>::size_type>(0));
738 if (bsdiff_delta.size() < current_best_size) {
739 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
740 current_best_size = bsdiff_delta.size();
741 data = bsdiff_delta;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700742 }
743 }
744 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700745
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700746 // Set parameters of the operations
747 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700748
Gilad Arnoldfa404502014-01-01 23:36:12 -0800749 vector<Extent> src_extents, dst_extents;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700750 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
751 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Darin Petkov68c10d12010-10-14 09:24:37 -0700752 if (gather_extents) {
753 TEST_AND_RETURN_FALSE(
Darin Petkov8e447e02013-04-16 16:23:50 +0200754 GatherExtents(old_filename,
755 chunk_offset,
756 chunk_size,
Gilad Arnoldfa404502014-01-01 23:36:12 -0800757 &src_extents));
Darin Petkov68c10d12010-10-14 09:24:37 -0700758 } else {
759 Extent* src_extent = operation.add_src_extents();
760 src_extent->set_start_block(0);
761 src_extent->set_num_blocks(
762 (old_stbuf.st_size + kBlockSize - 1) / kBlockSize);
763 }
Darin Petkov8e447e02013-04-16 16:23:50 +0200764 operation.set_src_length(old_data.size());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700765 }
766
Darin Petkov68c10d12010-10-14 09:24:37 -0700767 if (gather_extents) {
768 TEST_AND_RETURN_FALSE(
Darin Petkov8e447e02013-04-16 16:23:50 +0200769 GatherExtents(new_filename,
770 chunk_offset,
771 chunk_size,
Gilad Arnoldfa404502014-01-01 23:36:12 -0800772 &dst_extents));
Darin Petkov68c10d12010-10-14 09:24:37 -0700773 } else {
774 Extent* dst_extent = operation.add_dst_extents();
775 dst_extent->set_start_block(0);
776 dst_extent->set_num_blocks((new_data.size() + kBlockSize - 1) / kBlockSize);
777 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700778 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700779
Gilad Arnoldfa404502014-01-01 23:36:12 -0800780 if (gather_extents) {
781 // Remove identical src/dst block ranges in MOVE operations.
Gilad Arnoldebca5712014-01-10 14:26:37 -0800782 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
783 size_t removed_bytes = RemoveIdenticalBlockRanges(
784 &src_extents, &dst_extents, new_data.size());
785
786 // Adjust the file length field accordingly.
787 if (removed_bytes) {
788 operation.set_src_length(old_data.size() - removed_bytes);
789 operation.set_dst_length(new_data.size() - removed_bytes);
790 }
791 }
Gilad Arnoldfa404502014-01-01 23:36:12 -0800792
793 // Embed extents in the operation.
794 DeltaDiffGenerator::StoreExtents(src_extents,
795 operation.mutable_src_extents());
796 DeltaDiffGenerator::StoreExtents(dst_extents,
797 operation.mutable_dst_extents());
798 }
799
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700800 out_data->swap(data);
801 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700802
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700803 return true;
804}
805
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700806bool DeltaDiffGenerator::InitializePartitionInfo(bool is_kernel,
807 const string& partition,
808 PartitionInfo* info) {
Darin Petkov7ea32332010-10-13 10:46:11 -0700809 int64_t size = 0;
810 if (is_kernel) {
811 size = utils::FileSize(partition);
812 } else {
813 int block_count = 0, block_size = 0;
814 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(partition,
815 &block_count,
816 &block_size));
817 size = static_cast<int64_t>(block_count) * block_size;
818 }
819 TEST_AND_RETURN_FALSE(size > 0);
Darin Petkov36a58222010-10-07 22:00:09 -0700820 info->set_size(size);
821 OmahaHashCalculator hasher;
Darin Petkov7ea32332010-10-13 10:46:11 -0700822 TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, size) == size);
Darin Petkov36a58222010-10-07 22:00:09 -0700823 TEST_AND_RETURN_FALSE(hasher.Finalize());
824 const vector<char>& hash = hasher.raw_hash();
825 info->set_hash(hash.data(), hash.size());
Darin Petkovd43d6902010-10-14 11:17:50 -0700826 LOG(INFO) << partition << ": size=" << size << " hash=" << hasher.hash();
Darin Petkov36a58222010-10-07 22:00:09 -0700827 return true;
828}
829
830bool InitializePartitionInfos(const string& old_kernel,
831 const string& new_kernel,
832 const string& old_rootfs,
833 const string& new_rootfs,
834 DeltaArchiveManifest* manifest) {
Darin Petkovd43d6902010-10-14 11:17:50 -0700835 if (!old_kernel.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700836 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
837 true,
838 old_kernel,
839 manifest->mutable_old_kernel_info()));
Darin Petkovd43d6902010-10-14 11:17:50 -0700840 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700841 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
842 true,
843 new_kernel,
844 manifest->mutable_new_kernel_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700845 if (!old_rootfs.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700846 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
847 false,
848 old_rootfs,
849 manifest->mutable_old_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700850 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700851 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
852 false,
853 new_rootfs,
854 manifest->mutable_new_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700855 return true;
856}
857
Andrew de los Reyesef017552010-10-06 17:57:52 -0700858namespace {
859
860// Takes a collection (vector or RepeatedPtrField) of Extent and
861// returns a vector of the blocks referenced, in order.
862template<typename T>
863vector<uint64_t> ExpandExtents(const T& extents) {
864 vector<uint64_t> ret;
865 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
866 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700867 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700868 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700869 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700870 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700871 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700872 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700873 }
874 }
875 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700876 return ret;
877}
878
879// Takes a vector of blocks and returns an equivalent vector of Extent
880// objects.
881vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
882 vector<Extent> new_extents;
883 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
884 it != e; ++it) {
885 graph_utils::AppendBlockToExtents(&new_extents, *it);
886 }
887 return new_extents;
888}
889
890} // namespace {}
891
892void DeltaDiffGenerator::SubstituteBlocks(
893 Vertex* vertex,
894 const vector<Extent>& remove_extents,
895 const vector<Extent>& replace_extents) {
896 // First, expand out the blocks that op reads from
897 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700898 {
899 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700900 vector<uint64_t> remove_extents_expanded =
901 ExpandExtents(remove_extents);
902 vector<uint64_t> replace_extents_expanded =
903 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700904 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700905 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700906 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700907 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700908 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
909 }
910 utils::ApplyMap(&read_blocks, conversion);
911 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
912 e = vertex->out_edges.end(); it != e; ++it) {
913 vector<uint64_t> write_before_deps_expanded =
914 ExpandExtents(it->second.write_extents);
915 utils::ApplyMap(&write_before_deps_expanded, conversion);
916 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700917 }
918 }
919 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700920 vertex->op.clear_src_extents();
921 vector<Extent> new_extents = CompressExtents(read_blocks);
922 DeltaDiffGenerator::StoreExtents(new_extents,
923 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700924}
925
926bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700927 const set<Edge>& edges,
928 vector<CutEdgeVertexes>* out_cuts) {
929 DummyExtentAllocator scratch_allocator;
930 vector<CutEdgeVertexes> cuts;
931 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700932
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700933 uint64_t scratch_blocks_used = 0;
934 for (set<Edge>::const_iterator it = edges.begin();
935 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700936 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700937 vector<Extent> old_extents =
938 (*graph)[it->first].out_edges[it->second].extents;
939 // Choose some scratch space
940 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700941 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700942 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
943 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700944 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700945 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700946 cuts.back().old_src = it->first;
947 cuts.back().old_dst = it->second;
Darin Petkov36a58222010-10-07 22:00:09 -0700948
Andrew de los Reyesef017552010-10-06 17:57:52 -0700949 EdgeProperties& cut_edge_properties =
950 (*graph)[it->first].out_edges.find(it->second)->second;
951
952 // This should never happen, as we should only be cutting edges between
953 // real file nodes, and write-before relationships are created from
954 // a real file node to a temp copy node:
955 CHECK(cut_edge_properties.write_extents.empty())
956 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700957
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700958 // make node depend on the copy operation
959 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700960 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700961
962 // Set src/dst extents and other proto variables for copy operation
963 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
964 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700965 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700966 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700967 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700968 graph->back().op.mutable_dst_extents());
969 graph->back().op.set_src_length(
970 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
971 graph->back().op.set_dst_length(graph->back().op.src_length());
972
973 // make the dest node read from the scratch space
974 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700975 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700976 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700977 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700978
979 // delete the old edge
Mike Frysinger0f9547d2012-02-16 12:11:37 -0500980 CHECK_EQ(static_cast<Graph::size_type>(1),
981 (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700982
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700983 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700984 EdgeProperties write_before_edge_properties;
985 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
986 (*graph)[it->second].out_edges.insert(
987 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700988 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700989 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700990 return true;
991}
992
993// Stores all Extents in 'extents' into 'out'.
994void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700995 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700996 google::protobuf::RepeatedPtrField<Extent>* out) {
997 for (vector<Extent>::const_iterator it = extents.begin();
998 it != extents.end(); ++it) {
999 Extent* new_extent = out->Add();
1000 *new_extent = *it;
1001 }
1002}
1003
1004// Creates all the edges for the graph. Writers of a block point to
1005// readers of the same block. This is because for an edge A->B, B
1006// must complete before A executes.
1007void DeltaDiffGenerator::CreateEdges(Graph* graph,
1008 const vector<Block>& blocks) {
1009 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1010 // Blocks with both a reader and writer get an edge
1011 if (blocks[i].reader == Vertex::kInvalidIndex ||
1012 blocks[i].writer == Vertex::kInvalidIndex)
1013 continue;
1014 // Don't have a node depend on itself
1015 if (blocks[i].reader == blocks[i].writer)
1016 continue;
1017 // See if there's already an edge we can add onto
1018 Vertex::EdgeMap::iterator edge_it =
1019 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
1020 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
1021 // No existing edge. Create one
1022 (*graph)[blocks[i].writer].out_edges.insert(
1023 make_pair(blocks[i].reader, EdgeProperties()));
1024 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -07001025 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001026 }
1027 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
1028 }
1029}
1030
Andrew de los Reyesef017552010-10-06 17:57:52 -07001031namespace {
1032
1033class SortCutsByTopoOrderLess {
1034 public:
1035 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
1036 : table_(table) {}
1037 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
1038 return table_[a.old_dst] < table_[b.old_dst];
1039 }
1040 private:
1041 vector<vector<Vertex::Index>::size_type>& table_;
1042};
1043
1044} // namespace {}
1045
1046void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
1047 vector<Vertex::Index>& op_indexes,
1048 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
1049 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
1050 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
1051 i != e; ++i) {
1052 Vertex::Index node = op_indexes[i];
1053 if (table.size() < (node + 1)) {
1054 table.resize(node + 1);
1055 }
1056 table[node] = i;
1057 }
1058 reverse_op_indexes->swap(table);
1059}
1060
1061void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
1062 vector<CutEdgeVertexes>* cuts) {
1063 // first, make a reverse lookup table.
1064 vector<vector<Vertex::Index>::size_type> table;
1065 GenerateReverseTopoOrderMap(op_indexes, &table);
1066 SortCutsByTopoOrderLess less(table);
1067 sort(cuts->begin(), cuts->end(), less);
1068}
1069
1070void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
1071 vector<Vertex::Index>* op_indexes) {
1072 vector<Vertex::Index> ret;
1073 vector<Vertex::Index> full_ops;
1074 ret.reserve(op_indexes->size());
1075 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
1076 ++i) {
1077 DeltaArchiveManifest_InstallOperation_Type type =
1078 (*graph)[(*op_indexes)[i]].op.type();
1079 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
1080 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
1081 full_ops.push_back((*op_indexes)[i]);
1082 } else {
1083 ret.push_back((*op_indexes)[i]);
1084 }
1085 }
1086 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
1087 << (full_ops.size() + ret.size()) << " total ops.";
1088 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
1089 op_indexes->swap(ret);
1090}
1091
1092namespace {
1093
1094template<typename T>
1095bool TempBlocksExistInExtents(const T& extents) {
1096 for (int i = 0, e = extents.size(); i < e; ++i) {
1097 Extent extent = graph_utils::GetElement(extents, i);
1098 uint64_t start = extent.start_block();
1099 uint64_t num = extent.num_blocks();
1100 if (start == kSparseHole)
1101 continue;
1102 if (start >= kTempBlockStart ||
1103 (start + num) >= kTempBlockStart) {
1104 LOG(ERROR) << "temp block!";
1105 LOG(ERROR) << "start: " << start << ", num: " << num;
1106 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
1107 LOG(ERROR) << "returning true";
1108 return true;
1109 }
1110 // check for wrap-around, which would be a bug:
1111 CHECK(start <= (start + num));
1112 }
1113 return false;
1114}
1115
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001116// Convertes the cuts, which must all have the same |old_dst| member,
1117// to full. It does this by converting the |old_dst| to REPLACE or
1118// REPLACE_BZ, dropping all incoming edges to |old_dst|, and marking
1119// all temp nodes invalid.
1120bool ConvertCutsToFull(
1121 Graph* graph,
1122 const string& new_root,
1123 int data_fd,
1124 off_t* data_file_size,
1125 vector<Vertex::Index>* op_indexes,
1126 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
1127 const vector<CutEdgeVertexes>& cuts) {
1128 CHECK(!cuts.empty());
1129 set<Vertex::Index> deleted_nodes;
1130 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
1131 e = cuts.end(); it != e; ++it) {
1132 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ConvertCutToFullOp(
1133 graph,
1134 *it,
1135 new_root,
1136 data_fd,
1137 data_file_size));
1138 deleted_nodes.insert(it->new_vertex);
1139 }
1140 deleted_nodes.insert(cuts[0].old_dst);
Darin Petkovbc58a7b2010-11-03 11:52:53 -07001141
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001142 vector<Vertex::Index> new_op_indexes;
1143 new_op_indexes.reserve(op_indexes->size());
1144 for (vector<Vertex::Index>::iterator it = op_indexes->begin(),
1145 e = op_indexes->end(); it != e; ++it) {
1146 if (utils::SetContainsKey(deleted_nodes, *it))
1147 continue;
1148 new_op_indexes.push_back(*it);
1149 }
1150 new_op_indexes.push_back(cuts[0].old_dst);
1151 op_indexes->swap(new_op_indexes);
1152 DeltaDiffGenerator::GenerateReverseTopoOrderMap(*op_indexes,
1153 reverse_op_indexes);
1154 return true;
1155}
1156
1157// Tries to assign temp blocks for a collection of cuts, all of which share
1158// the same old_dst member. If temp blocks can't be found, old_dst will be
1159// converted to a REPLACE or REPLACE_BZ operation. Returns true on success,
1160// which can happen even if blocks are converted to full. Returns false
1161// on exceptional error cases.
1162bool AssignBlockForAdjoiningCuts(
1163 Graph* graph,
1164 const string& new_root,
1165 int data_fd,
1166 off_t* data_file_size,
1167 vector<Vertex::Index>* op_indexes,
1168 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
1169 const vector<CutEdgeVertexes>& cuts) {
1170 CHECK(!cuts.empty());
1171 const Vertex::Index old_dst = cuts[0].old_dst;
1172 // Calculate # of blocks needed
1173 uint64_t blocks_needed = 0;
1174 map<const CutEdgeVertexes*, uint64_t> cuts_blocks_needed;
1175 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
1176 e = cuts.end(); it != e; ++it) {
1177 uint64_t cut_blocks_needed = 0;
1178 for (vector<Extent>::const_iterator jt = it->tmp_extents.begin(),
1179 je = it->tmp_extents.end(); jt != je; ++jt) {
1180 cut_blocks_needed += jt->num_blocks();
1181 }
1182 blocks_needed += cut_blocks_needed;
1183 cuts_blocks_needed[&*it] = cut_blocks_needed;
1184 }
Darin Petkovbc58a7b2010-11-03 11:52:53 -07001185
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001186 // Find enough blocks
1187 ExtentRanges scratch_ranges;
1188 // Each block that's supplying temp blocks and the corresponding blocks:
1189 typedef vector<pair<Vertex::Index, ExtentRanges> > SupplierVector;
1190 SupplierVector block_suppliers;
1191 uint64_t scratch_blocks_found = 0;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001192 for (vector<Vertex::Index>::size_type i = (*reverse_op_indexes)[old_dst] + 1,
1193 e = op_indexes->size(); i < e; ++i) {
1194 Vertex::Index test_node = (*op_indexes)[i];
1195 if (!(*graph)[test_node].valid)
1196 continue;
1197 // See if this node has sufficient blocks
1198 ExtentRanges ranges;
1199 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
1200 ranges.SubtractExtent(ExtentForRange(
1201 kTempBlockStart, kSparseHole - kTempBlockStart));
1202 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
1203 // For now, for simplicity, subtract out all blocks in read-before
1204 // dependencies.
1205 for (Vertex::EdgeMap::const_iterator edge_i =
1206 (*graph)[test_node].out_edges.begin(),
1207 edge_e = (*graph)[test_node].out_edges.end();
1208 edge_i != edge_e; ++edge_i) {
1209 ranges.SubtractExtents(edge_i->second.extents);
1210 }
1211 if (ranges.blocks() == 0)
1212 continue;
1213
1214 if (ranges.blocks() + scratch_blocks_found > blocks_needed) {
1215 // trim down ranges
1216 vector<Extent> new_ranges = ranges.GetExtentsForBlockCount(
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001217 blocks_needed - scratch_blocks_found);
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001218 ranges = ExtentRanges();
1219 ranges.AddExtents(new_ranges);
1220 }
1221 scratch_ranges.AddRanges(ranges);
1222 block_suppliers.push_back(make_pair(test_node, ranges));
1223 scratch_blocks_found += ranges.blocks();
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001224 if (scratch_ranges.blocks() >= blocks_needed)
1225 break;
1226 }
1227 if (scratch_ranges.blocks() < blocks_needed) {
1228 LOG(INFO) << "Unable to find sufficient scratch";
1229 TEST_AND_RETURN_FALSE(ConvertCutsToFull(graph,
1230 new_root,
1231 data_fd,
1232 data_file_size,
1233 op_indexes,
1234 reverse_op_indexes,
1235 cuts));
1236 return true;
1237 }
1238 // Use the scratch we found
1239 TEST_AND_RETURN_FALSE(scratch_ranges.blocks() == scratch_blocks_found);
1240
1241 // Make all the suppliers depend on this node
1242 for (SupplierVector::iterator it = block_suppliers.begin(),
1243 e = block_suppliers.end(); it != e; ++it) {
1244 graph_utils::AddReadBeforeDepExtents(
1245 &(*graph)[it->first],
1246 old_dst,
1247 it->second.GetExtentsForBlockCount(it->second.blocks()));
1248 }
Darin Petkovbc58a7b2010-11-03 11:52:53 -07001249
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001250 // Replace temp blocks in each cut
1251 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
1252 e = cuts.end(); it != e; ++it) {
1253 vector<Extent> real_extents =
1254 scratch_ranges.GetExtentsForBlockCount(cuts_blocks_needed[&*it]);
1255 scratch_ranges.SubtractExtents(real_extents);
1256
1257 // Fix the old dest node w/ the real blocks
1258 DeltaDiffGenerator::SubstituteBlocks(&(*graph)[old_dst],
1259 it->tmp_extents,
1260 real_extents);
1261
1262 // Fix the new node w/ the real blocks. Since the new node is just a
1263 // copy operation, we can replace all the dest extents w/ the real
1264 // blocks.
1265 DeltaArchiveManifest_InstallOperation *op =
1266 &(*graph)[it->new_vertex].op;
1267 op->clear_dst_extents();
1268 DeltaDiffGenerator::StoreExtents(real_extents, op->mutable_dst_extents());
1269 }
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001270 return true;
1271}
1272
Andrew de los Reyesef017552010-10-06 17:57:52 -07001273} // namespace {}
1274
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001275// Returns true if |op| is a no-op operation that doesn't do any useful work
1276// (e.g., a move operation that copies blocks onto themselves).
1277bool DeltaDiffGenerator::IsNoopOperation(
1278 const DeltaArchiveManifest_InstallOperation& op) {
1279 return (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE &&
1280 ExpandExtents(op.src_extents()) == ExpandExtents(op.dst_extents()));
1281}
1282
Andrew de los Reyesef017552010-10-06 17:57:52 -07001283bool DeltaDiffGenerator::AssignTempBlocks(
1284 Graph* graph,
1285 const string& new_root,
1286 int data_fd,
1287 off_t* data_file_size,
1288 vector<Vertex::Index>* op_indexes,
1289 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001290 const vector<CutEdgeVertexes>& cuts) {
Andrew de los Reyesef017552010-10-06 17:57:52 -07001291 CHECK(!cuts.empty());
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001292
1293 // group of cuts w/ the same old_dst:
1294 vector<CutEdgeVertexes> cuts_group;
1295
Andrew de los Reyesef017552010-10-06 17:57:52 -07001296 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
1297 true ; --i) {
1298 LOG(INFO) << "Fixing temp blocks in cut " << i
1299 << ": old dst: " << cuts[i].old_dst << " new vertex: "
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001300 << cuts[i].new_vertex << " path: "
1301 << (*graph)[cuts[i].old_dst].file_name;
1302
1303 if (cuts_group.empty() || (cuts_group[0].old_dst == cuts[i].old_dst)) {
1304 cuts_group.push_back(cuts[i]);
1305 } else {
1306 CHECK(!cuts_group.empty());
1307 TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1308 new_root,
1309 data_fd,
1310 data_file_size,
1311 op_indexes,
1312 reverse_op_indexes,
1313 cuts_group));
1314 cuts_group.clear();
1315 cuts_group.push_back(cuts[i]);
Andrew de los Reyesef017552010-10-06 17:57:52 -07001316 }
Darin Petkov36a58222010-10-07 22:00:09 -07001317
Andrew de los Reyesef017552010-10-06 17:57:52 -07001318 if (i == e) {
1319 // break out of for() loop
1320 break;
1321 }
1322 }
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001323 CHECK(!cuts_group.empty());
1324 TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1325 new_root,
1326 data_fd,
1327 data_file_size,
1328 op_indexes,
1329 reverse_op_indexes,
1330 cuts_group));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001331 return true;
1332}
1333
1334bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1335 size_t idx = 0;
1336 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1337 ++it, ++idx) {
1338 if (!it->valid)
1339 continue;
1340 const DeltaArchiveManifest_InstallOperation& op = it->op;
1341 if (TempBlocksExistInExtents(op.dst_extents()) ||
1342 TempBlocksExistInExtents(op.src_extents())) {
1343 LOG(INFO) << "bad extents in node " << idx;
1344 LOG(INFO) << "so yeah";
1345 return false;
1346 }
1347
1348 // Check out-edges:
1349 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
1350 je = it->out_edges.end(); jt != je; ++jt) {
1351 if (TempBlocksExistInExtents(jt->second.extents) ||
1352 TempBlocksExistInExtents(jt->second.write_extents)) {
1353 LOG(INFO) << "bad out edge in node " << idx;
1354 LOG(INFO) << "so yeah";
1355 return false;
1356 }
1357 }
1358 }
1359 return true;
1360}
1361
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001362bool DeltaDiffGenerator::ReorderDataBlobs(
1363 DeltaArchiveManifest* manifest,
1364 const std::string& data_blobs_path,
1365 const std::string& new_data_blobs_path) {
1366 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1367 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1368 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001369
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001370 DirectFileWriter writer;
1371 TEST_AND_RETURN_FALSE(
1372 writer.Open(new_data_blobs_path.c_str(),
1373 O_WRONLY | O_TRUNC | O_CREAT,
1374 0644) == 0);
1375 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001376 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001377
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001378 for (int i = 0; i < (manifest->install_operations_size() +
1379 manifest->kernel_install_operations_size()); i++) {
1380 DeltaArchiveManifest_InstallOperation* op = NULL;
1381 if (i < manifest->install_operations_size()) {
1382 op = manifest->mutable_install_operations(i);
1383 } else {
1384 op = manifest->mutable_kernel_install_operations(
1385 i - manifest->install_operations_size());
1386 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001387 if (!op->has_data_offset())
1388 continue;
1389 CHECK(op->has_data_length());
1390 vector<char> buf(op->data_length());
1391 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1392 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1393
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001394 // Add the hash of the data blobs for this operation
1395 TEST_AND_RETURN_FALSE(AddOperationHash(op, buf));
1396
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001397 op->set_data_offset(out_file_size);
Don Garrette410e0f2011-11-10 15:39:01 -08001398 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001399 out_file_size += buf.size();
1400 }
1401 return true;
1402}
1403
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001404bool DeltaDiffGenerator::AddOperationHash(
1405 DeltaArchiveManifest_InstallOperation* op,
1406 const vector<char>& buf) {
1407 OmahaHashCalculator hasher;
1408
1409 TEST_AND_RETURN_FALSE(hasher.Update(&buf[0], buf.size()));
1410 TEST_AND_RETURN_FALSE(hasher.Finalize());
1411
1412 const vector<char>& hash = hasher.raw_hash();
1413 op->set_data_sha256_hash(hash.data(), hash.size());
1414 return true;
1415}
1416
Andrew de los Reyesef017552010-10-06 17:57:52 -07001417bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1418 const CutEdgeVertexes& cut,
1419 const string& new_root,
1420 int data_fd,
1421 off_t* data_file_size) {
1422 // Drop all incoming edges, keep all outgoing edges
Darin Petkov36a58222010-10-07 22:00:09 -07001423
Andrew de los Reyesef017552010-10-06 17:57:52 -07001424 // Keep all outgoing edges
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001425 if ((*graph)[cut.old_dst].op.type() !=
1426 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ &&
1427 (*graph)[cut.old_dst].op.type() !=
1428 DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
1429 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1430 graph_utils::DropWriteBeforeDeps(&out_edges);
Darin Petkov36a58222010-10-07 22:00:09 -07001431
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001432 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1433 cut.old_dst,
1434 NULL,
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -08001435 kNonexistentPath,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001436 new_root,
1437 (*graph)[cut.old_dst].file_name,
Darin Petkov8e447e02013-04-16 16:23:50 +02001438 (*graph)[cut.old_dst].chunk_offset,
1439 (*graph)[cut.old_dst].chunk_size,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001440 data_fd,
1441 data_file_size));
Darin Petkov36a58222010-10-07 22:00:09 -07001442
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001443 (*graph)[cut.old_dst].out_edges = out_edges;
Andrew de los Reyesef017552010-10-06 17:57:52 -07001444
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001445 // Right now we don't have doubly-linked edges, so we have to scan
1446 // the whole graph.
1447 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1448 }
Andrew de los Reyesef017552010-10-06 17:57:52 -07001449
1450 // Delete temp node
1451 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1452 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1453 (*graph)[cut.old_dst].out_edges.end());
1454 (*graph)[cut.new_vertex].valid = false;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001455 LOG(INFO) << "marked node invalid: " << cut.new_vertex;
Andrew de los Reyesef017552010-10-06 17:57:52 -07001456 return true;
1457}
1458
1459bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1460 const string& new_root,
1461 int fd,
1462 off_t* data_file_size,
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001463 vector<Vertex::Index>* final_order,
1464 Vertex::Index scratch_vertex) {
Andrew de los Reyesef017552010-10-06 17:57:52 -07001465 CycleBreaker cycle_breaker;
1466 LOG(INFO) << "Finding cycles...";
1467 set<Edge> cut_edges;
1468 cycle_breaker.BreakCycles(*graph, &cut_edges);
1469 LOG(INFO) << "done finding cycles";
1470 CheckGraph(*graph);
1471
1472 // Calculate number of scratch blocks needed
1473
1474 LOG(INFO) << "Cutting cycles...";
1475 vector<CutEdgeVertexes> cuts;
1476 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1477 LOG(INFO) << "done cutting cycles";
1478 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1479 CheckGraph(*graph);
1480
1481 LOG(INFO) << "Creating initial topological order...";
1482 TopologicalSort(*graph, final_order);
1483 LOG(INFO) << "done with initial topo order";
1484 CheckGraph(*graph);
1485
1486 LOG(INFO) << "Moving full ops to the back";
1487 MoveFullOpsToBack(graph, final_order);
1488 LOG(INFO) << "done moving full ops to back";
1489
1490 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1491 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1492
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001493 SortCutsByTopoOrder(*final_order, &cuts);
1494
Andrew de los Reyesef017552010-10-06 17:57:52 -07001495 if (!cuts.empty())
1496 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1497 new_root,
1498 fd,
1499 data_file_size,
1500 final_order,
1501 &inverse_final_order,
1502 cuts));
1503 LOG(INFO) << "Making sure all temp blocks have been allocated";
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001504
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001505 // Remove the scratch node, if any
1506 if (scratch_vertex != Vertex::kInvalidIndex) {
1507 final_order->erase(final_order->begin() +
1508 inverse_final_order[scratch_vertex]);
1509 (*graph)[scratch_vertex].valid = false;
1510 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1511 }
1512
Andrew de los Reyesef017552010-10-06 17:57:52 -07001513 graph_utils::DumpGraph(*graph);
1514 CHECK(NoTempBlocksRemain(*graph));
1515 LOG(INFO) << "done making sure all temp blocks are allocated";
1516 return true;
1517}
1518
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001519void DeltaDiffGenerator::CreateScratchNode(uint64_t start_block,
1520 uint64_t num_blocks,
1521 Vertex* vertex) {
1522 vertex->file_name = "<scratch>";
1523 vertex->op.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1524 vertex->op.set_data_offset(0);
1525 vertex->op.set_data_length(0);
1526 Extent* extent = vertex->op.add_dst_extents();
1527 extent->set_start_block(start_block);
1528 extent->set_num_blocks(num_blocks);
1529}
1530
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001531bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1532 const string& old_root,
1533 const string& old_image,
1534 const string& new_root,
1535 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001536 const string& old_kernel_part,
1537 const string& new_kernel_part,
1538 const string& output_path,
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001539 const string& private_key_path,
Darin Petkov8e447e02013-04-16 16:23:50 +02001540 off_t chunk_size,
Chris Sosad5ae1562013-04-23 13:20:18 -07001541 size_t rootfs_partition_size,
Don Garrett0dd39852013-04-03 16:55:42 -07001542 const ImageInfo* old_image_info,
1543 const ImageInfo* new_image_info,
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001544 uint64_t* metadata_size) {
Darin Petkov8e447e02013-04-16 16:23:50 +02001545 TEST_AND_RETURN_FALSE(chunk_size == -1 || chunk_size % kBlockSize == 0);
Darin Petkov7ea32332010-10-13 10:46:11 -07001546 int old_image_block_count = 0, old_image_block_size = 0;
1547 int new_image_block_count = 0, new_image_block_size = 0;
1548 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(new_image,
1549 &new_image_block_count,
1550 &new_image_block_size));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001551 if (!old_image.empty()) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001552 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(old_image,
1553 &old_image_block_count,
1554 &old_image_block_size));
1555 TEST_AND_RETURN_FALSE(old_image_block_size == new_image_block_size);
1556 LOG_IF(WARNING, old_image_block_count != new_image_block_count)
1557 << "Old and new images have different block counts.";
Don Garrett0dd39852013-04-03 16:55:42 -07001558
Don Garrett60fc59c2013-10-18 11:43:52 -07001559 // If new_image_info is present, old_image_info must be present.
Don Garrett0dd39852013-04-03 16:55:42 -07001560 TEST_AND_RETURN_FALSE((bool)old_image_info == (bool)new_image_info);
1561 } else {
1562 // old_image_info must not be present for a full update.
1563 TEST_AND_RETURN_FALSE(!old_image_info);
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001564 }
Chris Sosad5ae1562013-04-23 13:20:18 -07001565
1566 // Sanity checks for the partition size.
1567 TEST_AND_RETURN_FALSE(rootfs_partition_size % kBlockSize == 0);
Chris Sosae9f5f422013-05-17 16:11:10 -07001568 size_t fs_size = static_cast<size_t>(new_image_block_size) *
1569 new_image_block_count;
Chris Sosad5ae1562013-04-23 13:20:18 -07001570 LOG(INFO) << "Rootfs partition size: " << rootfs_partition_size;
1571 LOG(INFO) << "Actual filesystem size: " << fs_size;
1572 TEST_AND_RETURN_FALSE(rootfs_partition_size >= fs_size);
1573
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001574 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001575 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1576
Darin Petkov7ea32332010-10-13 10:46:11 -07001577 vector<Block> blocks(max(old_image_block_count, new_image_block_count));
1578 LOG(INFO) << "Invalid block index: " << Vertex::kInvalidIndex;
1579 LOG(INFO) << "Block count: " << blocks.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001580 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1581 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1582 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1583 }
1584 Graph graph;
1585 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001586
Gilad Arnolda6742b32014-01-11 00:18:34 -08001587 const string kTempFileTemplate("CrAU_temp_data.XXXXXX");
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001588 string temp_file_path;
Darin Petkov7438a5c2011-08-29 11:56:44 -07001589 scoped_ptr<ScopedPathUnlinker> temp_file_unlinker;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001590 off_t data_file_size = 0;
1591
1592 LOG(INFO) << "Reading files...";
1593
Don Garrettb8dd1d92013-11-22 17:40:02 -08001594 // Create empty protobuf Manifest object
1595 DeltaArchiveManifest manifest;
1596
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001597 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1598
Andrew de los Reyesef017552010-10-06 17:57:52 -07001599 vector<Vertex::Index> final_order;
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001600 Vertex::Index scratch_vertex = Vertex::kInvalidIndex;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001601 {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001602 int fd;
1603 TEST_AND_RETURN_FALSE(
1604 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001605 temp_file_unlinker.reset(new ScopedPathUnlinker(temp_file_path));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001606 TEST_AND_RETURN_FALSE(fd >= 0);
1607 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001608 if (!old_image.empty()) {
1609 // Delta update
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001610
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001611 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1612 &blocks,
1613 old_root,
1614 new_root,
Darin Petkov8e447e02013-04-16 16:23:50 +02001615 chunk_size,
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001616 fd,
1617 &data_file_size));
1618 LOG(INFO) << "done reading normal files";
1619 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001620
Thieu Le5c7d9752010-12-15 16:09:28 -08001621 LOG(INFO) << "Starting metadata processing";
1622 TEST_AND_RETURN_FALSE(Metadata::DeltaReadMetadata(&graph,
1623 &blocks,
1624 old_image,
1625 new_image,
1626 fd,
1627 &data_file_size));
1628 LOG(INFO) << "Done metadata processing";
1629 CheckGraph(graph);
1630
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001631 graph.resize(graph.size() + 1);
1632 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1633 fd,
1634 &data_file_size,
1635 new_image,
1636 &graph.back()));
1637
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001638 // Final scratch block (if there's space)
Chris Sosad5ae1562013-04-23 13:20:18 -07001639 if (blocks.size() < (rootfs_partition_size / kBlockSize)) {
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001640 scratch_vertex = graph.size();
1641 graph.resize(graph.size() + 1);
1642 CreateScratchNode(blocks.size(),
Chris Sosad5ae1562013-04-23 13:20:18 -07001643 (rootfs_partition_size / kBlockSize) - blocks.size(),
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001644 &graph.back());
1645 }
1646
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001647 // Read kernel partition
1648 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1649 new_kernel_part,
1650 &kernel_ops,
1651 fd,
1652 &data_file_size));
1653
1654 LOG(INFO) << "done reading kernel";
1655 CheckGraph(graph);
1656
1657 LOG(INFO) << "Creating edges...";
1658 CreateEdges(&graph, blocks);
1659 LOG(INFO) << "Done creating edges";
1660 CheckGraph(graph);
1661
1662 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1663 new_root,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001664 fd,
1665 &data_file_size,
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001666 &final_order,
1667 scratch_vertex));
Don Garrettb8dd1d92013-11-22 17:40:02 -08001668
1669 // Set the minor version for this payload.
1670 LOG(INFO) << "Adding Delta Minor Version.";
1671 manifest.set_minor_version(DeltaPerformer::kSupportedMinorPayloadVersion);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001672 } else {
1673 // Full update
Darin Petkov7ea32332010-10-13 10:46:11 -07001674 off_t new_image_size =
1675 static_cast<off_t>(new_image_block_count) * new_image_block_size;
Darin Petkov7a22d792010-11-08 14:10:00 -08001676 TEST_AND_RETURN_FALSE(FullUpdateGenerator::Run(&graph,
1677 new_kernel_part,
1678 new_image,
1679 new_image_size,
1680 fd,
1681 &data_file_size,
1682 kFullUpdateChunkSize,
1683 kBlockSize,
1684 &kernel_ops,
1685 &final_order));
Don Garrettb8dd1d92013-11-22 17:40:02 -08001686
1687 // Set the minor version for this payload.
1688 LOG(INFO) << "Adding Full Minor Version.";
1689 manifest.set_minor_version(DeltaPerformer::kFullPayloadMinorVersion);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001690 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001691 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001692
Don Garrett0dd39852013-04-03 16:55:42 -07001693 if (old_image_info)
1694 *(manifest.mutable_old_image_info()) = *old_image_info;
1695
1696 if (new_image_info)
1697 *(manifest.mutable_new_image_info()) = *new_image_info;
1698
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001699 OperationNameMap op_name_map;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001700 CheckGraph(graph);
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001701 InstallOperationsToManifest(graph,
1702 final_order,
1703 kernel_ops,
1704 &manifest,
1705 &op_name_map);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001706 CheckGraph(graph);
1707 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001708
1709 // Reorder the data blobs with the newly ordered manifest
1710 string ordered_blobs_path;
1711 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
Gilad Arnolda6742b32014-01-11 00:18:34 -08001712 "CrAU_temp_data.ordered.XXXXXX",
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001713 &ordered_blobs_path,
Andrew de los Reyese05fc282011-06-02 09:50:08 -07001714 NULL));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001715 ScopedPathUnlinker ordered_blobs_unlinker(ordered_blobs_path);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001716 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1717 temp_file_path,
1718 ordered_blobs_path));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001719 temp_file_unlinker.reset();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001720
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001721 // Check that install op blobs are in order.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001722 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001723 {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001724 for (int i = 0; i < (manifest.install_operations_size() +
1725 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001726 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001727 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001728 manifest.mutable_install_operations(i) :
1729 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001730 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001731 if (op->has_data_offset()) {
1732 if (op->data_offset() != next_blob_offset) {
1733 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001734 << next_blob_offset;
1735 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001736 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001737 }
1738 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001739 }
1740
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001741 // Signatures appear at the end of the blobs. Note the offset in the
1742 // manifest
1743 if (!private_key_path.empty()) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001744 uint64_t signature_blob_length = 0;
1745 TEST_AND_RETURN_FALSE(
Andrew de los Reyesc24e3f32011-08-30 15:45:20 -07001746 PayloadSigner::SignatureBlobLength(vector<string>(1, private_key_path),
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001747 &signature_blob_length));
Darin Petkov9574f7e2011-01-13 10:48:12 -08001748 AddSignatureOp(next_blob_offset, signature_blob_length, &manifest);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001749 }
1750
Darin Petkov36a58222010-10-07 22:00:09 -07001751 TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1752 new_kernel_part,
1753 old_image,
1754 new_image,
1755 &manifest));
1756
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001757 // Serialize protobuf
1758 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001759
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001760 CheckGraph(graph);
1761 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1762 CheckGraph(graph);
1763
1764 LOG(INFO) << "Writing final delta file header...";
1765 DirectFileWriter writer;
1766 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1767 O_WRONLY | O_CREAT | O_TRUNC,
1768 0644) == 0);
1769 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001770
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001771 // Write header
Don Garrette410e0f2011-11-10 15:39:01 -08001772 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001773
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001774 // Write version number
1775 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001776
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001777 // Write protobuf length
1778 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1779 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001780
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001781 // Write protobuf
1782 LOG(INFO) << "Writing final delta file protobuf... "
1783 << serialized_manifest.size();
1784 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
Don Garrette410e0f2011-11-10 15:39:01 -08001785 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001786
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001787 // Append the data blobs
1788 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001789 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001790 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1791 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1792 for (;;) {
1793 char buf[kBlockSize];
1794 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1795 if (0 == rc) {
1796 // EOF
1797 break;
1798 }
1799 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
Don Garrette410e0f2011-11-10 15:39:01 -08001800 TEST_AND_RETURN_FALSE(writer.Write(buf, rc));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001801 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001802
1803 // Write signature blob.
1804 if (!private_key_path.empty()) {
1805 LOG(INFO) << "Signing the update...";
1806 vector<char> signature_blob;
Andrew de los Reyesc24e3f32011-08-30 15:45:20 -07001807 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(
1808 output_path,
1809 vector<string>(1, private_key_path),
1810 &signature_blob));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001811 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
Don Garrette410e0f2011-11-10 15:39:01 -08001812 signature_blob.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001813 }
1814
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001815 *metadata_size =
Darin Petkov95cf01f2010-10-12 14:59:13 -07001816 strlen(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001817 ReportPayloadUsage(manifest, *metadata_size, op_name_map);
Darin Petkov880335c2010-10-01 15:52:53 -07001818
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001819 LOG(INFO) << "All done. Successfully created delta file with "
1820 << "metadata size = " << *metadata_size;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001821 return true;
1822}
1823
Thieu Le5c7d9752010-12-15 16:09:28 -08001824// Runs the bsdiff tool on two files and returns the resulting delta in
1825// 'out'. Returns true on success.
1826bool DeltaDiffGenerator::BsdiffFiles(const string& old_file,
1827 const string& new_file,
1828 vector<char>* out) {
Gilad Arnolda6742b32014-01-11 00:18:34 -08001829 const string kPatchFile = "delta.patchXXXXXX";
Thieu Le5c7d9752010-12-15 16:09:28 -08001830 string patch_file_path;
1831
1832 TEST_AND_RETURN_FALSE(
1833 utils::MakeTempFile(kPatchFile, &patch_file_path, NULL));
1834
1835 vector<string> cmd;
1836 cmd.push_back(kBsdiffPath);
1837 cmd.push_back(old_file);
1838 cmd.push_back(new_file);
1839 cmd.push_back(patch_file_path);
1840
1841 int rc = 1;
1842 vector<char> patch_file;
Darin Petkov85d02b72011-05-17 13:25:51 -07001843 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc, NULL));
Thieu Le5c7d9752010-12-15 16:09:28 -08001844 TEST_AND_RETURN_FALSE(rc == 0);
1845 TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
1846 unlink(patch_file_path.c_str());
1847 return true;
1848}
1849
1850// The |blocks| vector contains a reader and writer for each block on the
1851// filesystem that's being in-place updated. We populate the reader/writer
1852// fields of |blocks| by calling this function.
1853// For each block in |operation| that is read or written, find that block
1854// in |blocks| and set the reader/writer field to the vertex passed.
1855// |graph| is not strictly necessary, but useful for printing out
1856// error messages.
1857bool DeltaDiffGenerator::AddInstallOpToBlocksVector(
1858 const DeltaArchiveManifest_InstallOperation& operation,
1859 const Graph& graph,
1860 Vertex::Index vertex,
1861 vector<Block>* blocks) {
1862 // See if this is already present.
1863 TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
1864
1865 enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
1866 for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
1867 const int extents_size =
1868 (field == READER) ? operation.src_extents_size() :
1869 operation.dst_extents_size();
1870 const char* past_participle = (field == READER) ? "read" : "written";
1871 const google::protobuf::RepeatedPtrField<Extent>& extents =
1872 (field == READER) ? operation.src_extents() : operation.dst_extents();
1873 Vertex::Index Block::*access_type =
1874 (field == READER) ? &Block::reader : &Block::writer;
1875
1876 for (int i = 0; i < extents_size; i++) {
1877 const Extent& extent = extents.Get(i);
1878 if (extent.start_block() == kSparseHole) {
1879 // Hole in sparse file. skip
1880 continue;
1881 }
1882 for (uint64_t block = extent.start_block();
1883 block < (extent.start_block() + extent.num_blocks()); block++) {
1884 if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
1885 LOG(FATAL) << "Block " << block << " is already "
1886 << past_participle << " by "
1887 << (*blocks)[block].*access_type << "("
1888 << graph[(*blocks)[block].*access_type].file_name
1889 << ") and also " << vertex << "("
1890 << graph[vertex].file_name << ")";
1891 }
1892 (*blocks)[block].*access_type = vertex;
1893 }
1894 }
1895 }
1896 return true;
1897}
1898
Darin Petkov9574f7e2011-01-13 10:48:12 -08001899void DeltaDiffGenerator::AddSignatureOp(uint64_t signature_blob_offset,
1900 uint64_t signature_blob_length,
1901 DeltaArchiveManifest* manifest) {
1902 LOG(INFO) << "Making room for signature in file";
1903 manifest->set_signatures_offset(signature_blob_offset);
1904 LOG(INFO) << "set? " << manifest->has_signatures_offset();
1905 // Add a dummy op at the end to appease older clients
1906 DeltaArchiveManifest_InstallOperation* dummy_op =
1907 manifest->add_kernel_install_operations();
1908 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1909 dummy_op->set_data_offset(signature_blob_offset);
1910 manifest->set_signatures_offset(signature_blob_offset);
1911 dummy_op->set_data_length(signature_blob_length);
1912 manifest->set_signatures_size(signature_blob_length);
1913 Extent* dummy_extent = dummy_op->add_dst_extents();
1914 // Tell the dummy op to write this data to a big sparse hole
1915 dummy_extent->set_start_block(kSparseHole);
1916 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1917 kBlockSize);
1918}
1919
Andrew de los Reyes50f36492010-11-01 13:57:12 -07001920const char* const kBsdiffPath = "bsdiff";
1921const char* const kBspatchPath = "bspatch";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001922const char* const kDeltaMagic = "CrAU";
1923
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001924}; // namespace chromeos_update_engine