blob: 8d70749fb8d0f9143b6e69deb9b2d9fc93fbdcaa [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
Darin Petkov8e447e02013-04-16 16:23:50 +020020#include <base/file_path.h>
21#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>
Darin Petkov8e447e02013-04-16 16:23:50 +020024#include <base/string_number_conversions.h>
Darin Petkov880335c2010-10-01 15:52:53 -070025#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040026#include <base/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
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070067namespace {
Andrew de los Reyes27f7d372010-10-07 11:26:07 -070068const size_t kBlockSize = 4096; // bytes
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -080069const string kNonexistentPath = "";
Andrew de los Reyes927179d2010-12-02 11:26:48 -080070
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070071
Darin Petkov68c10d12010-10-14 09:24:37 -070072static const char* kInstallOperationTypes[] = {
73 "REPLACE",
74 "REPLACE_BZ",
75 "MOVE",
76 "BSDIFF"
77};
78
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070079// Stores all Extents for a file into 'out'. Returns true on success.
80bool GatherExtents(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +020081 off_t chunk_offset,
82 off_t chunk_size,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070083 google::protobuf::RepeatedPtrField<Extent>* out) {
84 vector<Extent> extents;
Darin Petkov8e447e02013-04-16 16:23:50 +020085 TEST_AND_RETURN_FALSE(
86 extent_mapper::ExtentsForFileChunkFibmap(
87 path, chunk_offset, chunk_size, &extents));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070088 DeltaDiffGenerator::StoreExtents(extents, out);
89 return true;
90}
91
Andrew de los Reyesef017552010-10-06 17:57:52 -070092// For a given regular file which must exist at new_root + path, and
93// may exist at old_root + path, creates a new InstallOperation and
94// adds it to the graph. Also, populates the |blocks| array as
95// necessary, if |blocks| is non-NULL. Also, writes the data
96// necessary to send the file down to the client into data_fd, which
97// has length *data_file_size. *data_file_size is updated
98// appropriately. If |existing_vertex| is no kInvalidIndex, use that
99// rather than allocating a new vertex. Returns true on success.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700100bool DeltaReadFile(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700101 Vertex::Index existing_vertex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700102 vector<Block>* blocks,
103 const string& old_root,
104 const string& new_root,
105 const string& path, // within new_root
Darin Petkov8e447e02013-04-16 16:23:50 +0200106 off_t chunk_offset,
107 off_t chunk_size,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700108 int data_fd,
109 off_t* data_file_size) {
110 vector<char> data;
111 DeltaArchiveManifest_InstallOperation operation;
112
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800113 string old_path = (old_root == kNonexistentPath) ? kNonexistentPath :
114 old_root + path;
115
Don Garrett1d787092013-03-11 18:07:28 -0700116 // If bsdiff breaks again, blacklist the problem file by using:
117 // bsdiff_allowed = (path != "/foo/bar")
Don Garrett36e60772012-03-29 10:31:20 -0700118 //
Don Garrett1d787092013-03-11 18:07:28 -0700119 // TODO(dgarrett): chromium-os:15274 connect this test to the command line.
Don Garrett36e60772012-03-29 10:31:20 -0700120 bool bsdiff_allowed = true;
Don Garrettf4b28742012-03-27 20:48:06 -0700121
Don Garrett36e60772012-03-29 10:31:20 -0700122 if (!bsdiff_allowed)
123 LOG(INFO) << "bsdiff blacklisting: " << path;
Don Garrettf4b28742012-03-27 20:48:06 -0700124
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800125 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_path,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700126 new_root + path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200127 chunk_offset,
128 chunk_size,
Don Garrett36e60772012-03-29 10:31:20 -0700129 bsdiff_allowed,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700130 &data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700131 &operation,
132 true));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700133
134 // Write the data
135 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
136 operation.set_data_offset(*data_file_size);
137 operation.set_data_length(data.size());
138 }
139
140 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
141 *data_file_size += data.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700142
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700143 // Now, insert into graph and blocks vector
Andrew de los Reyesef017552010-10-06 17:57:52 -0700144 Vertex::Index vertex = existing_vertex;
145 if (vertex == Vertex::kInvalidIndex) {
146 graph->resize(graph->size() + 1);
147 vertex = graph->size() - 1;
148 }
149 (*graph)[vertex].op = operation;
150 CHECK((*graph)[vertex].op.has_type());
151 (*graph)[vertex].file_name = path;
Darin Petkov8e447e02013-04-16 16:23:50 +0200152 (*graph)[vertex].chunk_offset = chunk_offset;
153 (*graph)[vertex].chunk_size = chunk_size;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700154
Andrew de los Reyesef017552010-10-06 17:57:52 -0700155 if (blocks)
Thieu Le5c7d9752010-12-15 16:09:28 -0800156 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::AddInstallOpToBlocksVector(
157 (*graph)[vertex].op,
158 *graph,
159 vertex,
160 blocks));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700161 return true;
162}
163
164// For each regular file within new_root, creates a node in the graph,
165// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
166// and writes any necessary data to the end of data_fd.
167bool DeltaReadFiles(Graph* graph,
168 vector<Block>* blocks,
169 const string& old_root,
170 const string& new_root,
Darin Petkov8e447e02013-04-16 16:23:50 +0200171 off_t chunk_size,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700172 int data_fd,
173 off_t* data_file_size) {
174 set<ino_t> visited_inodes;
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800175 set<ino_t> visited_src_inodes;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700176 for (FilesystemIterator fs_iter(new_root,
177 utils::SetWithValue<string>("/lost+found"));
178 !fs_iter.IsEnd(); fs_iter.Increment()) {
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800179 // We never diff symlinks (here, we check that dst file is not a symlink).
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700180 if (!S_ISREG(fs_iter.GetStat().st_mode))
181 continue;
182
183 // Make sure we visit each inode only once.
184 if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
185 continue;
186 visited_inodes.insert(fs_iter.GetStat().st_ino);
Darin Petkov8e447e02013-04-16 16:23:50 +0200187 off_t dst_size = fs_iter.GetStat().st_size;
188 if (dst_size == 0)
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700189 continue;
190
191 LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700192
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800193 // We can't visit each dst image inode more than once, as that would
194 // duplicate work. Here, we avoid visiting each source image inode
195 // more than once. Technically, we could have multiple operations
196 // that read the same blocks from the source image for diffing, but
197 // we choose not to to avoid complexity. Eventually we will move away
198 // from using a graph/cycle detection/etc to generate diffs, and at that
199 // time, it will be easy (non-complex) to have many operations read
200 // from the same source blocks. At that time, this code can die. -adlr
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800201 bool should_diff_from_source = false;
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800202 string src_path = old_root + fs_iter.GetPartialPath();
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800203 struct stat src_stbuf;
204 // We never diff symlinks (here, we check that src file is not a symlink).
205 if (0 == lstat(src_path.c_str(), &src_stbuf) &&
206 S_ISREG(src_stbuf.st_mode)) {
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800207 should_diff_from_source = !utils::SetContainsKey(visited_src_inodes,
208 src_stbuf.st_ino);
209 visited_src_inodes.insert(src_stbuf.st_ino);
210 }
211
Darin Petkov8e447e02013-04-16 16:23:50 +0200212 off_t size = chunk_size == -1 ? dst_size : chunk_size;
213 off_t step = size;
214 for (off_t offset = 0; offset < dst_size; offset += step) {
215 if (offset + size >= dst_size) {
216 size = -1; // Read through the end of the file.
217 }
218 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
219 Vertex::kInvalidIndex,
220 blocks,
221 (should_diff_from_source ?
222 old_root :
223 kNonexistentPath),
224 new_root,
225 fs_iter.GetPartialPath(),
226 offset,
227 size,
228 data_fd,
229 data_file_size));
230 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700231 }
232 return true;
233}
234
Andrew de los Reyesef017552010-10-06 17:57:52 -0700235// This class allocates non-existent temp blocks, starting from
236// kTempBlockStart. Other code is responsible for converting these
237// temp blocks into real blocks, as the client can't read or write to
238// these blocks.
239class DummyExtentAllocator {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700240 public:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700241 explicit DummyExtentAllocator()
242 : next_block_(kTempBlockStart) {}
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700243 vector<Extent> Allocate(const uint64_t block_count) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700244 vector<Extent> ret(1);
245 ret[0].set_start_block(next_block_);
246 ret[0].set_num_blocks(block_count);
247 next_block_ += block_count;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700248 return ret;
249 }
250 private:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700251 uint64_t next_block_;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700252};
253
254// Reads blocks from image_path that are not yet marked as being written
255// in the blocks array. These blocks that remain are non-file-data blocks.
256// In the future we might consider intelligent diffing between this data
257// and data in the previous image, but for now we just bzip2 compress it
258// and include it in the update.
259// Creates a new node in the graph to write these blocks and writes the
260// appropriate blob to blobs_fd. Reads and updates blobs_length;
261bool ReadUnwrittenBlocks(const vector<Block>& blocks,
262 int blobs_fd,
263 off_t* blobs_length,
264 const string& image_path,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700265 Vertex* vertex) {
Darin Petkovabe7cc92010-10-08 12:29:32 -0700266 vertex->file_name = "<rootfs-non-file-data>";
267
Andrew de los Reyesef017552010-10-06 17:57:52 -0700268 DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700269 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
270 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
271 ScopedFdCloser image_fd_closer(&image_fd);
272
273 string temp_file_path;
274 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
275 &temp_file_path,
276 NULL));
277
278 FILE* file = fopen(temp_file_path.c_str(), "w");
279 TEST_AND_RETURN_FALSE(file);
280 int err = BZ_OK;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700281
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700282 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
283 file,
284 9, // max compression
285 0, // verbosity
286 0); // default work factor
287 TEST_AND_RETURN_FALSE(err == BZ_OK);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700288
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700289 vector<Extent> extents;
290 vector<Block>::size_type block_count = 0;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700291
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700292 LOG(INFO) << "Appending left over blocks to extents";
293 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
294 if (blocks[i].writer != Vertex::kInvalidIndex)
295 continue;
Andrew de los Reyesef017552010-10-06 17:57:52 -0700296 if (blocks[i].reader != Vertex::kInvalidIndex) {
297 graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
298 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700299 graph_utils::AppendBlockToExtents(&extents, i);
300 block_count++;
301 }
302
303 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
304 // so we arbitrarily set it to 1024 * kBlockSize.
305 vector<char> buf(1024 * kBlockSize);
306
307 LOG(INFO) << "Reading left over blocks";
308 vector<Block>::size_type blocks_copied_count = 0;
309
310 // For each extent in extents, write the data into BZ2_bzWrite which
311 // sends it to an output file.
312 // We use the temporary buffer 'buf' to hold the data, which may be
313 // smaller than the extent, so in that case we have to loop to get
314 // the extent's data (that's the inner while loop).
315 for (vector<Extent>::const_iterator it = extents.begin();
316 it != extents.end(); ++it) {
317 vector<Block>::size_type blocks_read = 0;
Andrew de los Reyes4b8740f2010-11-08 17:09:11 -0800318 float printed_progress = -1;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700319 while (blocks_read < it->num_blocks()) {
320 const int copy_block_cnt =
321 min(buf.size() / kBlockSize,
322 static_cast<vector<char>::size_type>(
323 it->num_blocks() - blocks_read));
324 ssize_t rc = pread(image_fd,
325 &buf[0],
326 copy_block_cnt * kBlockSize,
327 (it->start_block() + blocks_read) * kBlockSize);
328 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
329 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
330 copy_block_cnt * kBlockSize);
331 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
332 TEST_AND_RETURN_FALSE(err == BZ_OK);
333 blocks_read += copy_block_cnt;
334 blocks_copied_count += copy_block_cnt;
Andrew de los Reyes4b8740f2010-11-08 17:09:11 -0800335 float current_progress =
336 static_cast<float>(blocks_copied_count) / block_count;
337 if (printed_progress + 0.1 < current_progress ||
338 blocks_copied_count == block_count) {
339 LOG(INFO) << "progress: " << current_progress;
340 printed_progress = current_progress;
341 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700342 }
343 }
344 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
345 TEST_AND_RETURN_FALSE(err == BZ_OK);
346 bz_file = NULL;
347 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
348 file = NULL;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700349
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700350 vector<char> compressed_data;
351 LOG(INFO) << "Reading compressed data off disk";
352 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
353 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700354
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700355 // Add node to graph to write these blocks
356 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
357 out_op->set_data_offset(*blobs_length);
358 out_op->set_data_length(compressed_data.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700359 LOG(INFO) << "Rootfs non-data blocks compressed take up "
360 << compressed_data.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700361 *blobs_length += compressed_data.size();
362 out_op->set_dst_length(kBlockSize * block_count);
363 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700364
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700365 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
366 &compressed_data[0],
367 compressed_data.size()));
368 LOG(INFO) << "done with extra blocks";
369 return true;
370}
371
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700372// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700373// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700374bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
375 uint64_t value_be = htobe64(value);
Don Garrette410e0f2011-11-10 15:39:01 -0800376 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700377 return true;
378}
379
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700380// Adds each operation from |graph| to |out_manifest| in the order specified by
381// |order| while building |out_op_name_map| with operation to name
382// mappings. Adds all |kernel_ops| to |out_manifest|. Filters out no-op
383// operations.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700384void InstallOperationsToManifest(
385 const Graph& graph,
386 const vector<Vertex::Index>& order,
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700387 const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700388 DeltaArchiveManifest* out_manifest,
389 OperationNameMap* out_op_name_map) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700390 for (vector<Vertex::Index>::const_iterator it = order.begin();
391 it != order.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700392 const Vertex& vertex = graph[*it];
393 const DeltaArchiveManifest_InstallOperation& add_op = vertex.op;
394 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
395 continue;
396 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700397 DeltaArchiveManifest_InstallOperation* op =
398 out_manifest->add_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700399 *op = add_op;
Darin Petkov8e447e02013-04-16 16:23:50 +0200400 string name = vertex.file_name;
401 if (vertex.chunk_offset || vertex.chunk_size != -1) {
402 string offset = base::Int64ToString(vertex.chunk_offset);
403 if (vertex.chunk_size != -1) {
404 name += " [" + offset + ", " +
405 base::Int64ToString(vertex.chunk_offset + vertex.chunk_size - 1) +
406 "]";
407 } else {
408 name += " [" + offset + ", end]";
409 }
410 }
411 (*out_op_name_map)[op] = name;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700412 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700413 for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
414 kernel_ops.begin(); it != kernel_ops.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700415 const DeltaArchiveManifest_InstallOperation& add_op = *it;
416 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
417 continue;
418 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700419 DeltaArchiveManifest_InstallOperation* op =
420 out_manifest->add_kernel_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700421 *op = add_op;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700422 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700423}
424
425void CheckGraph(const Graph& graph) {
426 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
427 CHECK(it->op.has_type());
428 }
429}
430
Darin Petkov68c10d12010-10-14 09:24:37 -0700431// Delta compresses a kernel partition |new_kernel_part| with knowledge of the
432// old kernel partition |old_kernel_part|. If |old_kernel_part| is an empty
433// string, generates a full update of the partition.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700434bool DeltaCompressKernelPartition(
435 const string& old_kernel_part,
436 const string& new_kernel_part,
437 vector<DeltaArchiveManifest_InstallOperation>* ops,
438 int blobs_fd,
439 off_t* blobs_length) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700440 LOG(INFO) << "Delta compressing kernel partition...";
Darin Petkov68c10d12010-10-14 09:24:37 -0700441 LOG_IF(INFO, old_kernel_part.empty()) << "Generating full kernel update...";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700442
443 // Add a new install operation
444 ops->resize(1);
445 DeltaArchiveManifest_InstallOperation* op = &(*ops)[0];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700446
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700447 vector<char> data;
Don Garrett36e60772012-03-29 10:31:20 -0700448 TEST_AND_RETURN_FALSE(
449 DeltaDiffGenerator::ReadFileToDiff(old_kernel_part,
450 new_kernel_part,
Darin Petkov8e447e02013-04-16 16:23:50 +0200451 0, // chunk_offset
452 -1, // chunk_size
Don Garrett36e60772012-03-29 10:31:20 -0700453 true, // bsdiff_allowed
454 &data,
455 op,
456 false));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700457
Darin Petkov68c10d12010-10-14 09:24:37 -0700458 // Write the data
459 if (op->type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
460 op->set_data_offset(*blobs_length);
461 op->set_data_length(data.size());
462 }
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700463
Darin Petkov68c10d12010-10-14 09:24:37 -0700464 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data[0], data.size()));
465 *blobs_length += data.size();
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700466
Darin Petkov68c10d12010-10-14 09:24:37 -0700467 LOG(INFO) << "Done delta compressing kernel partition: "
468 << kInstallOperationTypes[op->type()];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700469 return true;
470}
471
Darin Petkov880335c2010-10-01 15:52:53 -0700472struct DeltaObject {
473 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
474 : name(in_name),
475 type(in_type),
476 size(in_size) {}
477 bool operator <(const DeltaObject& object) const {
Darin Petkovd43d6902010-10-14 11:17:50 -0700478 return (size != object.size) ? (size < object.size) : (name < object.name);
Darin Petkov880335c2010-10-01 15:52:53 -0700479 }
480 string name;
481 int type;
482 off_t size;
483};
484
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700485void ReportPayloadUsage(const DeltaArchiveManifest& manifest,
486 const int64_t manifest_metadata_size,
487 const OperationNameMap& op_name_map) {
Darin Petkov880335c2010-10-01 15:52:53 -0700488 vector<DeltaObject> objects;
489 off_t total_size = 0;
490
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700491 // Rootfs install operations.
492 for (int i = 0; i < manifest.install_operations_size(); ++i) {
493 const DeltaArchiveManifest_InstallOperation& op =
494 manifest.install_operations(i);
Darin Petkov8e447e02013-04-16 16:23:50 +0200495 objects.push_back(DeltaObject(op_name_map.find(&op)->second,
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700496 op.type(),
497 op.data_length()));
498 total_size += op.data_length();
Darin Petkov880335c2010-10-01 15:52:53 -0700499 }
500
Darin Petkov880335c2010-10-01 15:52:53 -0700501 // Kernel install operations.
502 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
503 const DeltaArchiveManifest_InstallOperation& op =
504 manifest.kernel_install_operations(i);
505 objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
506 op.type(),
507 op.data_length()));
508 total_size += op.data_length();
509 }
510
Darin Petkov95cf01f2010-10-12 14:59:13 -0700511 objects.push_back(DeltaObject("<manifest-metadata>",
512 -1,
513 manifest_metadata_size));
514 total_size += manifest_metadata_size;
515
Darin Petkov880335c2010-10-01 15:52:53 -0700516 std::sort(objects.begin(), objects.end());
517
518 static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
519 for (vector<DeltaObject>::const_iterator it = objects.begin();
520 it != objects.end(); ++it) {
521 const DeltaObject& object = *it;
522 fprintf(stderr, kFormatString,
523 object.size * 100.0 / total_size,
524 object.size,
Darin Petkov95cf01f2010-10-12 14:59:13 -0700525 object.type >= 0 ? kInstallOperationTypes[object.type] : "-",
Darin Petkov880335c2010-10-01 15:52:53 -0700526 object.name.c_str());
527 }
528 fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
529}
530
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700531} // namespace {}
532
533bool DeltaDiffGenerator::ReadFileToDiff(
534 const string& old_filename,
535 const string& new_filename,
Darin Petkov8e447e02013-04-16 16:23:50 +0200536 off_t chunk_offset,
537 off_t chunk_size,
Don Garrett36e60772012-03-29 10:31:20 -0700538 bool bsdiff_allowed,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700539 vector<char>* out_data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700540 DeltaArchiveManifest_InstallOperation* out_op,
541 bool gather_extents) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700542 // Read new data in
543 vector<char> new_data;
Darin Petkov8e447e02013-04-16 16:23:50 +0200544 TEST_AND_RETURN_FALSE(
545 utils::ReadFileChunk(new_filename, chunk_offset, chunk_size, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700546
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700547 TEST_AND_RETURN_FALSE(!new_data.empty());
Darin Petkov8e447e02013-04-16 16:23:50 +0200548 TEST_AND_RETURN_FALSE(chunk_size == -1 ||
549 static_cast<off_t>(new_data.size()) <= chunk_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700550
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700551 vector<char> new_data_bz;
552 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
553 CHECK(!new_data_bz.empty());
554
555 vector<char> data; // Data blob that will be written to delta file.
556
557 DeltaArchiveManifest_InstallOperation operation;
558 size_t current_best_size = 0;
559 if (new_data.size() <= new_data_bz.size()) {
560 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
561 current_best_size = new_data.size();
562 data = new_data;
563 } else {
564 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
565 current_best_size = new_data_bz.size();
566 data = new_data_bz;
567 }
568
569 // Do we have an original file to consider?
570 struct stat old_stbuf;
Don Garrettf4b28742012-03-27 20:48:06 -0700571 bool original = !old_filename.empty();
572 if (original && 0 != stat(old_filename.c_str(), &old_stbuf)) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700573 // If stat-ing the old file fails, it should be because it doesn't exist.
574 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
Don Garrettf4b28742012-03-27 20:48:06 -0700575 original = false;
Darin Petkov68c10d12010-10-14 09:24:37 -0700576 }
Don Garrettf4b28742012-03-27 20:48:06 -0700577
Darin Petkov8e447e02013-04-16 16:23:50 +0200578 vector<char> old_data;
Don Garrettf4b28742012-03-27 20:48:06 -0700579 if (original) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700580 // Read old data
Darin Petkov8e447e02013-04-16 16:23:50 +0200581 TEST_AND_RETURN_FALSE(
582 utils::ReadFileChunk(
583 old_filename, chunk_offset, chunk_size, &old_data));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700584 if (old_data == new_data) {
585 // No change in data.
586 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
587 current_best_size = 0;
588 data.clear();
Darin Petkov8e447e02013-04-16 16:23:50 +0200589 } else if (!old_data.empty() && bsdiff_allowed) {
Don Garrett36e60772012-03-29 10:31:20 -0700590 // If the source file is considered bsdiff safe (no bsdiff bugs
591 // triggered), see if BSDIFF encoding is smaller.
Darin Petkov8e447e02013-04-16 16:23:50 +0200592 FilePath old_chunk;
593 TEST_AND_RETURN_FALSE(file_util::CreateTemporaryFile(&old_chunk));
594 ScopedPathUnlinker old_unlinker(old_chunk.value());
595 TEST_AND_RETURN_FALSE(
596 utils::WriteFile(old_chunk.value().c_str(),
597 &old_data[0], old_data.size()));
598 FilePath new_chunk;
599 TEST_AND_RETURN_FALSE(file_util::CreateTemporaryFile(&new_chunk));
600 ScopedPathUnlinker new_unlinker(new_chunk.value());
601 TEST_AND_RETURN_FALSE(
602 utils::WriteFile(new_chunk.value().c_str(),
603 &new_data[0], new_data.size()));
604
Don Garrett36e60772012-03-29 10:31:20 -0700605 vector<char> bsdiff_delta;
606 TEST_AND_RETURN_FALSE(
Darin Petkov8e447e02013-04-16 16:23:50 +0200607 BsdiffFiles(old_chunk.value(), new_chunk.value(), &bsdiff_delta));
Don Garrett36e60772012-03-29 10:31:20 -0700608 CHECK_GT(bsdiff_delta.size(), static_cast<vector<char>::size_type>(0));
609 if (bsdiff_delta.size() < current_best_size) {
610 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
611 current_best_size = bsdiff_delta.size();
612 data = bsdiff_delta;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700613 }
614 }
615 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700616
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700617 // Set parameters of the operations
618 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700619
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700620 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
621 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Darin Petkov68c10d12010-10-14 09:24:37 -0700622 if (gather_extents) {
623 TEST_AND_RETURN_FALSE(
Darin Petkov8e447e02013-04-16 16:23:50 +0200624 GatherExtents(old_filename,
625 chunk_offset,
626 chunk_size,
627 operation.mutable_src_extents()));
Darin Petkov68c10d12010-10-14 09:24:37 -0700628 } else {
629 Extent* src_extent = operation.add_src_extents();
630 src_extent->set_start_block(0);
631 src_extent->set_num_blocks(
632 (old_stbuf.st_size + kBlockSize - 1) / kBlockSize);
633 }
Darin Petkov8e447e02013-04-16 16:23:50 +0200634 operation.set_src_length(old_data.size());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700635 }
636
Darin Petkov68c10d12010-10-14 09:24:37 -0700637 if (gather_extents) {
638 TEST_AND_RETURN_FALSE(
Darin Petkov8e447e02013-04-16 16:23:50 +0200639 GatherExtents(new_filename,
640 chunk_offset,
641 chunk_size,
642 operation.mutable_dst_extents()));
Darin Petkov68c10d12010-10-14 09:24:37 -0700643 } else {
644 Extent* dst_extent = operation.add_dst_extents();
645 dst_extent->set_start_block(0);
646 dst_extent->set_num_blocks((new_data.size() + kBlockSize - 1) / kBlockSize);
647 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700648 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700649
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700650 out_data->swap(data);
651 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700652
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700653 return true;
654}
655
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700656bool DeltaDiffGenerator::InitializePartitionInfo(bool is_kernel,
657 const string& partition,
658 PartitionInfo* info) {
Darin Petkov7ea32332010-10-13 10:46:11 -0700659 int64_t size = 0;
660 if (is_kernel) {
661 size = utils::FileSize(partition);
662 } else {
663 int block_count = 0, block_size = 0;
664 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(partition,
665 &block_count,
666 &block_size));
667 size = static_cast<int64_t>(block_count) * block_size;
668 }
669 TEST_AND_RETURN_FALSE(size > 0);
Darin Petkov36a58222010-10-07 22:00:09 -0700670 info->set_size(size);
671 OmahaHashCalculator hasher;
Darin Petkov7ea32332010-10-13 10:46:11 -0700672 TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, size) == size);
Darin Petkov36a58222010-10-07 22:00:09 -0700673 TEST_AND_RETURN_FALSE(hasher.Finalize());
674 const vector<char>& hash = hasher.raw_hash();
675 info->set_hash(hash.data(), hash.size());
Darin Petkovd43d6902010-10-14 11:17:50 -0700676 LOG(INFO) << partition << ": size=" << size << " hash=" << hasher.hash();
Darin Petkov36a58222010-10-07 22:00:09 -0700677 return true;
678}
679
680bool InitializePartitionInfos(const string& old_kernel,
681 const string& new_kernel,
682 const string& old_rootfs,
683 const string& new_rootfs,
684 DeltaArchiveManifest* manifest) {
Darin Petkovd43d6902010-10-14 11:17:50 -0700685 if (!old_kernel.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700686 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
687 true,
688 old_kernel,
689 manifest->mutable_old_kernel_info()));
Darin Petkovd43d6902010-10-14 11:17:50 -0700690 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700691 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
692 true,
693 new_kernel,
694 manifest->mutable_new_kernel_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700695 if (!old_rootfs.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700696 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
697 false,
698 old_rootfs,
699 manifest->mutable_old_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700700 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700701 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
702 false,
703 new_rootfs,
704 manifest->mutable_new_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700705 return true;
706}
707
Andrew de los Reyesef017552010-10-06 17:57:52 -0700708namespace {
709
710// Takes a collection (vector or RepeatedPtrField) of Extent and
711// returns a vector of the blocks referenced, in order.
712template<typename T>
713vector<uint64_t> ExpandExtents(const T& extents) {
714 vector<uint64_t> ret;
715 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
716 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700717 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700718 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700719 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700720 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700721 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700722 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700723 }
724 }
725 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700726 return ret;
727}
728
729// Takes a vector of blocks and returns an equivalent vector of Extent
730// objects.
731vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
732 vector<Extent> new_extents;
733 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
734 it != e; ++it) {
735 graph_utils::AppendBlockToExtents(&new_extents, *it);
736 }
737 return new_extents;
738}
739
740} // namespace {}
741
742void DeltaDiffGenerator::SubstituteBlocks(
743 Vertex* vertex,
744 const vector<Extent>& remove_extents,
745 const vector<Extent>& replace_extents) {
746 // First, expand out the blocks that op reads from
747 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700748 {
749 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700750 vector<uint64_t> remove_extents_expanded =
751 ExpandExtents(remove_extents);
752 vector<uint64_t> replace_extents_expanded =
753 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700754 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700755 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700756 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700757 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700758 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
759 }
760 utils::ApplyMap(&read_blocks, conversion);
761 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
762 e = vertex->out_edges.end(); it != e; ++it) {
763 vector<uint64_t> write_before_deps_expanded =
764 ExpandExtents(it->second.write_extents);
765 utils::ApplyMap(&write_before_deps_expanded, conversion);
766 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700767 }
768 }
769 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700770 vertex->op.clear_src_extents();
771 vector<Extent> new_extents = CompressExtents(read_blocks);
772 DeltaDiffGenerator::StoreExtents(new_extents,
773 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700774}
775
776bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700777 const set<Edge>& edges,
778 vector<CutEdgeVertexes>* out_cuts) {
779 DummyExtentAllocator scratch_allocator;
780 vector<CutEdgeVertexes> cuts;
781 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700782
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700783 uint64_t scratch_blocks_used = 0;
784 for (set<Edge>::const_iterator it = edges.begin();
785 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700786 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700787 vector<Extent> old_extents =
788 (*graph)[it->first].out_edges[it->second].extents;
789 // Choose some scratch space
790 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700791 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700792 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
793 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700794 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700795 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700796 cuts.back().old_src = it->first;
797 cuts.back().old_dst = it->second;
Darin Petkov36a58222010-10-07 22:00:09 -0700798
Andrew de los Reyesef017552010-10-06 17:57:52 -0700799 EdgeProperties& cut_edge_properties =
800 (*graph)[it->first].out_edges.find(it->second)->second;
801
802 // This should never happen, as we should only be cutting edges between
803 // real file nodes, and write-before relationships are created from
804 // a real file node to a temp copy node:
805 CHECK(cut_edge_properties.write_extents.empty())
806 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700807
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700808 // make node depend on the copy operation
809 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700810 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700811
812 // Set src/dst extents and other proto variables for copy operation
813 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
814 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700815 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700816 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700817 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700818 graph->back().op.mutable_dst_extents());
819 graph->back().op.set_src_length(
820 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
821 graph->back().op.set_dst_length(graph->back().op.src_length());
822
823 // make the dest node read from the scratch space
824 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700825 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700826 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700827 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700828
829 // delete the old edge
Mike Frysinger0f9547d2012-02-16 12:11:37 -0500830 CHECK_EQ(static_cast<Graph::size_type>(1),
831 (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700832
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700833 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700834 EdgeProperties write_before_edge_properties;
835 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
836 (*graph)[it->second].out_edges.insert(
837 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700838 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700839 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700840 return true;
841}
842
843// Stores all Extents in 'extents' into 'out'.
844void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700845 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700846 google::protobuf::RepeatedPtrField<Extent>* out) {
847 for (vector<Extent>::const_iterator it = extents.begin();
848 it != extents.end(); ++it) {
849 Extent* new_extent = out->Add();
850 *new_extent = *it;
851 }
852}
853
854// Creates all the edges for the graph. Writers of a block point to
855// readers of the same block. This is because for an edge A->B, B
856// must complete before A executes.
857void DeltaDiffGenerator::CreateEdges(Graph* graph,
858 const vector<Block>& blocks) {
859 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
860 // Blocks with both a reader and writer get an edge
861 if (blocks[i].reader == Vertex::kInvalidIndex ||
862 blocks[i].writer == Vertex::kInvalidIndex)
863 continue;
864 // Don't have a node depend on itself
865 if (blocks[i].reader == blocks[i].writer)
866 continue;
867 // See if there's already an edge we can add onto
868 Vertex::EdgeMap::iterator edge_it =
869 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
870 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
871 // No existing edge. Create one
872 (*graph)[blocks[i].writer].out_edges.insert(
873 make_pair(blocks[i].reader, EdgeProperties()));
874 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700875 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700876 }
877 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
878 }
879}
880
Andrew de los Reyesef017552010-10-06 17:57:52 -0700881namespace {
882
883class SortCutsByTopoOrderLess {
884 public:
885 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
886 : table_(table) {}
887 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
888 return table_[a.old_dst] < table_[b.old_dst];
889 }
890 private:
891 vector<vector<Vertex::Index>::size_type>& table_;
892};
893
894} // namespace {}
895
896void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
897 vector<Vertex::Index>& op_indexes,
898 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
899 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
900 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
901 i != e; ++i) {
902 Vertex::Index node = op_indexes[i];
903 if (table.size() < (node + 1)) {
904 table.resize(node + 1);
905 }
906 table[node] = i;
907 }
908 reverse_op_indexes->swap(table);
909}
910
911void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
912 vector<CutEdgeVertexes>* cuts) {
913 // first, make a reverse lookup table.
914 vector<vector<Vertex::Index>::size_type> table;
915 GenerateReverseTopoOrderMap(op_indexes, &table);
916 SortCutsByTopoOrderLess less(table);
917 sort(cuts->begin(), cuts->end(), less);
918}
919
920void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
921 vector<Vertex::Index>* op_indexes) {
922 vector<Vertex::Index> ret;
923 vector<Vertex::Index> full_ops;
924 ret.reserve(op_indexes->size());
925 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
926 ++i) {
927 DeltaArchiveManifest_InstallOperation_Type type =
928 (*graph)[(*op_indexes)[i]].op.type();
929 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
930 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
931 full_ops.push_back((*op_indexes)[i]);
932 } else {
933 ret.push_back((*op_indexes)[i]);
934 }
935 }
936 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
937 << (full_ops.size() + ret.size()) << " total ops.";
938 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
939 op_indexes->swap(ret);
940}
941
942namespace {
943
944template<typename T>
945bool TempBlocksExistInExtents(const T& extents) {
946 for (int i = 0, e = extents.size(); i < e; ++i) {
947 Extent extent = graph_utils::GetElement(extents, i);
948 uint64_t start = extent.start_block();
949 uint64_t num = extent.num_blocks();
950 if (start == kSparseHole)
951 continue;
952 if (start >= kTempBlockStart ||
953 (start + num) >= kTempBlockStart) {
954 LOG(ERROR) << "temp block!";
955 LOG(ERROR) << "start: " << start << ", num: " << num;
956 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
957 LOG(ERROR) << "returning true";
958 return true;
959 }
960 // check for wrap-around, which would be a bug:
961 CHECK(start <= (start + num));
962 }
963 return false;
964}
965
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700966// Convertes the cuts, which must all have the same |old_dst| member,
967// to full. It does this by converting the |old_dst| to REPLACE or
968// REPLACE_BZ, dropping all incoming edges to |old_dst|, and marking
969// all temp nodes invalid.
970bool ConvertCutsToFull(
971 Graph* graph,
972 const string& new_root,
973 int data_fd,
974 off_t* data_file_size,
975 vector<Vertex::Index>* op_indexes,
976 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
977 const vector<CutEdgeVertexes>& cuts) {
978 CHECK(!cuts.empty());
979 set<Vertex::Index> deleted_nodes;
980 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
981 e = cuts.end(); it != e; ++it) {
982 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ConvertCutToFullOp(
983 graph,
984 *it,
985 new_root,
986 data_fd,
987 data_file_size));
988 deleted_nodes.insert(it->new_vertex);
989 }
990 deleted_nodes.insert(cuts[0].old_dst);
Darin Petkovbc58a7b2010-11-03 11:52:53 -0700991
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700992 vector<Vertex::Index> new_op_indexes;
993 new_op_indexes.reserve(op_indexes->size());
994 for (vector<Vertex::Index>::iterator it = op_indexes->begin(),
995 e = op_indexes->end(); it != e; ++it) {
996 if (utils::SetContainsKey(deleted_nodes, *it))
997 continue;
998 new_op_indexes.push_back(*it);
999 }
1000 new_op_indexes.push_back(cuts[0].old_dst);
1001 op_indexes->swap(new_op_indexes);
1002 DeltaDiffGenerator::GenerateReverseTopoOrderMap(*op_indexes,
1003 reverse_op_indexes);
1004 return true;
1005}
1006
1007// Tries to assign temp blocks for a collection of cuts, all of which share
1008// the same old_dst member. If temp blocks can't be found, old_dst will be
1009// converted to a REPLACE or REPLACE_BZ operation. Returns true on success,
1010// which can happen even if blocks are converted to full. Returns false
1011// on exceptional error cases.
1012bool AssignBlockForAdjoiningCuts(
1013 Graph* graph,
1014 const string& new_root,
1015 int data_fd,
1016 off_t* data_file_size,
1017 vector<Vertex::Index>* op_indexes,
1018 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
1019 const vector<CutEdgeVertexes>& cuts) {
1020 CHECK(!cuts.empty());
1021 const Vertex::Index old_dst = cuts[0].old_dst;
1022 // Calculate # of blocks needed
1023 uint64_t blocks_needed = 0;
1024 map<const CutEdgeVertexes*, uint64_t> cuts_blocks_needed;
1025 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
1026 e = cuts.end(); it != e; ++it) {
1027 uint64_t cut_blocks_needed = 0;
1028 for (vector<Extent>::const_iterator jt = it->tmp_extents.begin(),
1029 je = it->tmp_extents.end(); jt != je; ++jt) {
1030 cut_blocks_needed += jt->num_blocks();
1031 }
1032 blocks_needed += cut_blocks_needed;
1033 cuts_blocks_needed[&*it] = cut_blocks_needed;
1034 }
Darin Petkovbc58a7b2010-11-03 11:52:53 -07001035
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001036 // Find enough blocks
1037 ExtentRanges scratch_ranges;
1038 // Each block that's supplying temp blocks and the corresponding blocks:
1039 typedef vector<pair<Vertex::Index, ExtentRanges> > SupplierVector;
1040 SupplierVector block_suppliers;
1041 uint64_t scratch_blocks_found = 0;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001042 for (vector<Vertex::Index>::size_type i = (*reverse_op_indexes)[old_dst] + 1,
1043 e = op_indexes->size(); i < e; ++i) {
1044 Vertex::Index test_node = (*op_indexes)[i];
1045 if (!(*graph)[test_node].valid)
1046 continue;
1047 // See if this node has sufficient blocks
1048 ExtentRanges ranges;
1049 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
1050 ranges.SubtractExtent(ExtentForRange(
1051 kTempBlockStart, kSparseHole - kTempBlockStart));
1052 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
1053 // For now, for simplicity, subtract out all blocks in read-before
1054 // dependencies.
1055 for (Vertex::EdgeMap::const_iterator edge_i =
1056 (*graph)[test_node].out_edges.begin(),
1057 edge_e = (*graph)[test_node].out_edges.end();
1058 edge_i != edge_e; ++edge_i) {
1059 ranges.SubtractExtents(edge_i->second.extents);
1060 }
1061 if (ranges.blocks() == 0)
1062 continue;
1063
1064 if (ranges.blocks() + scratch_blocks_found > blocks_needed) {
1065 // trim down ranges
1066 vector<Extent> new_ranges = ranges.GetExtentsForBlockCount(
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001067 blocks_needed - scratch_blocks_found);
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001068 ranges = ExtentRanges();
1069 ranges.AddExtents(new_ranges);
1070 }
1071 scratch_ranges.AddRanges(ranges);
1072 block_suppliers.push_back(make_pair(test_node, ranges));
1073 scratch_blocks_found += ranges.blocks();
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001074 if (scratch_ranges.blocks() >= blocks_needed)
1075 break;
1076 }
1077 if (scratch_ranges.blocks() < blocks_needed) {
1078 LOG(INFO) << "Unable to find sufficient scratch";
1079 TEST_AND_RETURN_FALSE(ConvertCutsToFull(graph,
1080 new_root,
1081 data_fd,
1082 data_file_size,
1083 op_indexes,
1084 reverse_op_indexes,
1085 cuts));
1086 return true;
1087 }
1088 // Use the scratch we found
1089 TEST_AND_RETURN_FALSE(scratch_ranges.blocks() == scratch_blocks_found);
1090
1091 // Make all the suppliers depend on this node
1092 for (SupplierVector::iterator it = block_suppliers.begin(),
1093 e = block_suppliers.end(); it != e; ++it) {
1094 graph_utils::AddReadBeforeDepExtents(
1095 &(*graph)[it->first],
1096 old_dst,
1097 it->second.GetExtentsForBlockCount(it->second.blocks()));
1098 }
Darin Petkovbc58a7b2010-11-03 11:52:53 -07001099
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001100 // Replace temp blocks in each cut
1101 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
1102 e = cuts.end(); it != e; ++it) {
1103 vector<Extent> real_extents =
1104 scratch_ranges.GetExtentsForBlockCount(cuts_blocks_needed[&*it]);
1105 scratch_ranges.SubtractExtents(real_extents);
1106
1107 // Fix the old dest node w/ the real blocks
1108 DeltaDiffGenerator::SubstituteBlocks(&(*graph)[old_dst],
1109 it->tmp_extents,
1110 real_extents);
1111
1112 // Fix the new node w/ the real blocks. Since the new node is just a
1113 // copy operation, we can replace all the dest extents w/ the real
1114 // blocks.
1115 DeltaArchiveManifest_InstallOperation *op =
1116 &(*graph)[it->new_vertex].op;
1117 op->clear_dst_extents();
1118 DeltaDiffGenerator::StoreExtents(real_extents, op->mutable_dst_extents());
1119 }
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001120 return true;
1121}
1122
Andrew de los Reyesef017552010-10-06 17:57:52 -07001123} // namespace {}
1124
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001125// Returns true if |op| is a no-op operation that doesn't do any useful work
1126// (e.g., a move operation that copies blocks onto themselves).
1127bool DeltaDiffGenerator::IsNoopOperation(
1128 const DeltaArchiveManifest_InstallOperation& op) {
1129 return (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE &&
1130 ExpandExtents(op.src_extents()) == ExpandExtents(op.dst_extents()));
1131}
1132
Andrew de los Reyesef017552010-10-06 17:57:52 -07001133bool DeltaDiffGenerator::AssignTempBlocks(
1134 Graph* graph,
1135 const string& new_root,
1136 int data_fd,
1137 off_t* data_file_size,
1138 vector<Vertex::Index>* op_indexes,
1139 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001140 const vector<CutEdgeVertexes>& cuts) {
Andrew de los Reyesef017552010-10-06 17:57:52 -07001141 CHECK(!cuts.empty());
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001142
1143 // group of cuts w/ the same old_dst:
1144 vector<CutEdgeVertexes> cuts_group;
1145
Andrew de los Reyesef017552010-10-06 17:57:52 -07001146 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
1147 true ; --i) {
1148 LOG(INFO) << "Fixing temp blocks in cut " << i
1149 << ": old dst: " << cuts[i].old_dst << " new vertex: "
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001150 << cuts[i].new_vertex << " path: "
1151 << (*graph)[cuts[i].old_dst].file_name;
1152
1153 if (cuts_group.empty() || (cuts_group[0].old_dst == cuts[i].old_dst)) {
1154 cuts_group.push_back(cuts[i]);
1155 } else {
1156 CHECK(!cuts_group.empty());
1157 TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1158 new_root,
1159 data_fd,
1160 data_file_size,
1161 op_indexes,
1162 reverse_op_indexes,
1163 cuts_group));
1164 cuts_group.clear();
1165 cuts_group.push_back(cuts[i]);
Andrew de los Reyesef017552010-10-06 17:57:52 -07001166 }
Darin Petkov36a58222010-10-07 22:00:09 -07001167
Andrew de los Reyesef017552010-10-06 17:57:52 -07001168 if (i == e) {
1169 // break out of for() loop
1170 break;
1171 }
1172 }
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001173 CHECK(!cuts_group.empty());
1174 TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1175 new_root,
1176 data_fd,
1177 data_file_size,
1178 op_indexes,
1179 reverse_op_indexes,
1180 cuts_group));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001181 return true;
1182}
1183
1184bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1185 size_t idx = 0;
1186 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1187 ++it, ++idx) {
1188 if (!it->valid)
1189 continue;
1190 const DeltaArchiveManifest_InstallOperation& op = it->op;
1191 if (TempBlocksExistInExtents(op.dst_extents()) ||
1192 TempBlocksExistInExtents(op.src_extents())) {
1193 LOG(INFO) << "bad extents in node " << idx;
1194 LOG(INFO) << "so yeah";
1195 return false;
1196 }
1197
1198 // Check out-edges:
1199 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
1200 je = it->out_edges.end(); jt != je; ++jt) {
1201 if (TempBlocksExistInExtents(jt->second.extents) ||
1202 TempBlocksExistInExtents(jt->second.write_extents)) {
1203 LOG(INFO) << "bad out edge in node " << idx;
1204 LOG(INFO) << "so yeah";
1205 return false;
1206 }
1207 }
1208 }
1209 return true;
1210}
1211
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001212bool DeltaDiffGenerator::ReorderDataBlobs(
1213 DeltaArchiveManifest* manifest,
1214 const std::string& data_blobs_path,
1215 const std::string& new_data_blobs_path) {
1216 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1217 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1218 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001219
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001220 DirectFileWriter writer;
1221 TEST_AND_RETURN_FALSE(
1222 writer.Open(new_data_blobs_path.c_str(),
1223 O_WRONLY | O_TRUNC | O_CREAT,
1224 0644) == 0);
1225 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001226 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001227
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001228 for (int i = 0; i < (manifest->install_operations_size() +
1229 manifest->kernel_install_operations_size()); i++) {
1230 DeltaArchiveManifest_InstallOperation* op = NULL;
1231 if (i < manifest->install_operations_size()) {
1232 op = manifest->mutable_install_operations(i);
1233 } else {
1234 op = manifest->mutable_kernel_install_operations(
1235 i - manifest->install_operations_size());
1236 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001237 if (!op->has_data_offset())
1238 continue;
1239 CHECK(op->has_data_length());
1240 vector<char> buf(op->data_length());
1241 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1242 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1243
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001244 // Add the hash of the data blobs for this operation
1245 TEST_AND_RETURN_FALSE(AddOperationHash(op, buf));
1246
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001247 op->set_data_offset(out_file_size);
Don Garrette410e0f2011-11-10 15:39:01 -08001248 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001249 out_file_size += buf.size();
1250 }
1251 return true;
1252}
1253
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001254bool DeltaDiffGenerator::AddOperationHash(
1255 DeltaArchiveManifest_InstallOperation* op,
1256 const vector<char>& buf) {
1257 OmahaHashCalculator hasher;
1258
1259 TEST_AND_RETURN_FALSE(hasher.Update(&buf[0], buf.size()));
1260 TEST_AND_RETURN_FALSE(hasher.Finalize());
1261
1262 const vector<char>& hash = hasher.raw_hash();
1263 op->set_data_sha256_hash(hash.data(), hash.size());
1264 return true;
1265}
1266
Andrew de los Reyesef017552010-10-06 17:57:52 -07001267bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1268 const CutEdgeVertexes& cut,
1269 const string& new_root,
1270 int data_fd,
1271 off_t* data_file_size) {
1272 // Drop all incoming edges, keep all outgoing edges
Darin Petkov36a58222010-10-07 22:00:09 -07001273
Andrew de los Reyesef017552010-10-06 17:57:52 -07001274 // Keep all outgoing edges
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001275 if ((*graph)[cut.old_dst].op.type() !=
1276 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ &&
1277 (*graph)[cut.old_dst].op.type() !=
1278 DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
1279 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1280 graph_utils::DropWriteBeforeDeps(&out_edges);
Darin Petkov36a58222010-10-07 22:00:09 -07001281
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001282 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1283 cut.old_dst,
1284 NULL,
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -08001285 kNonexistentPath,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001286 new_root,
1287 (*graph)[cut.old_dst].file_name,
Darin Petkov8e447e02013-04-16 16:23:50 +02001288 (*graph)[cut.old_dst].chunk_offset,
1289 (*graph)[cut.old_dst].chunk_size,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001290 data_fd,
1291 data_file_size));
Darin Petkov36a58222010-10-07 22:00:09 -07001292
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001293 (*graph)[cut.old_dst].out_edges = out_edges;
Andrew de los Reyesef017552010-10-06 17:57:52 -07001294
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001295 // Right now we don't have doubly-linked edges, so we have to scan
1296 // the whole graph.
1297 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1298 }
Andrew de los Reyesef017552010-10-06 17:57:52 -07001299
1300 // Delete temp node
1301 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1302 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1303 (*graph)[cut.old_dst].out_edges.end());
1304 (*graph)[cut.new_vertex].valid = false;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001305 LOG(INFO) << "marked node invalid: " << cut.new_vertex;
Andrew de los Reyesef017552010-10-06 17:57:52 -07001306 return true;
1307}
1308
1309bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1310 const string& new_root,
1311 int fd,
1312 off_t* data_file_size,
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001313 vector<Vertex::Index>* final_order,
1314 Vertex::Index scratch_vertex) {
Andrew de los Reyesef017552010-10-06 17:57:52 -07001315 CycleBreaker cycle_breaker;
1316 LOG(INFO) << "Finding cycles...";
1317 set<Edge> cut_edges;
1318 cycle_breaker.BreakCycles(*graph, &cut_edges);
1319 LOG(INFO) << "done finding cycles";
1320 CheckGraph(*graph);
1321
1322 // Calculate number of scratch blocks needed
1323
1324 LOG(INFO) << "Cutting cycles...";
1325 vector<CutEdgeVertexes> cuts;
1326 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1327 LOG(INFO) << "done cutting cycles";
1328 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1329 CheckGraph(*graph);
1330
1331 LOG(INFO) << "Creating initial topological order...";
1332 TopologicalSort(*graph, final_order);
1333 LOG(INFO) << "done with initial topo order";
1334 CheckGraph(*graph);
1335
1336 LOG(INFO) << "Moving full ops to the back";
1337 MoveFullOpsToBack(graph, final_order);
1338 LOG(INFO) << "done moving full ops to back";
1339
1340 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1341 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1342
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001343 SortCutsByTopoOrder(*final_order, &cuts);
1344
Andrew de los Reyesef017552010-10-06 17:57:52 -07001345 if (!cuts.empty())
1346 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1347 new_root,
1348 fd,
1349 data_file_size,
1350 final_order,
1351 &inverse_final_order,
1352 cuts));
1353 LOG(INFO) << "Making sure all temp blocks have been allocated";
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001354
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001355 // Remove the scratch node, if any
1356 if (scratch_vertex != Vertex::kInvalidIndex) {
1357 final_order->erase(final_order->begin() +
1358 inverse_final_order[scratch_vertex]);
1359 (*graph)[scratch_vertex].valid = false;
1360 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1361 }
1362
Andrew de los Reyesef017552010-10-06 17:57:52 -07001363 graph_utils::DumpGraph(*graph);
1364 CHECK(NoTempBlocksRemain(*graph));
1365 LOG(INFO) << "done making sure all temp blocks are allocated";
1366 return true;
1367}
1368
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001369void DeltaDiffGenerator::CreateScratchNode(uint64_t start_block,
1370 uint64_t num_blocks,
1371 Vertex* vertex) {
1372 vertex->file_name = "<scratch>";
1373 vertex->op.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1374 vertex->op.set_data_offset(0);
1375 vertex->op.set_data_length(0);
1376 Extent* extent = vertex->op.add_dst_extents();
1377 extent->set_start_block(start_block);
1378 extent->set_num_blocks(num_blocks);
1379}
1380
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001381bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1382 const string& old_root,
1383 const string& old_image,
1384 const string& new_root,
1385 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001386 const string& old_kernel_part,
1387 const string& new_kernel_part,
1388 const string& output_path,
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001389 const string& private_key_path,
Darin Petkov8e447e02013-04-16 16:23:50 +02001390 off_t chunk_size,
Chris Sosad5ae1562013-04-23 13:20:18 -07001391 size_t rootfs_partition_size,
Don Garrett0dd39852013-04-03 16:55:42 -07001392 const ImageInfo* old_image_info,
1393 const ImageInfo* new_image_info,
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001394 uint64_t* metadata_size) {
Darin Petkov8e447e02013-04-16 16:23:50 +02001395 TEST_AND_RETURN_FALSE(chunk_size == -1 || chunk_size % kBlockSize == 0);
Darin Petkov7ea32332010-10-13 10:46:11 -07001396 int old_image_block_count = 0, old_image_block_size = 0;
1397 int new_image_block_count = 0, new_image_block_size = 0;
1398 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(new_image,
1399 &new_image_block_count,
1400 &new_image_block_size));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001401 if (!old_image.empty()) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001402 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(old_image,
1403 &old_image_block_count,
1404 &old_image_block_size));
1405 TEST_AND_RETURN_FALSE(old_image_block_size == new_image_block_size);
1406 LOG_IF(WARNING, old_image_block_count != new_image_block_count)
1407 << "Old and new images have different block counts.";
Don Garrett0dd39852013-04-03 16:55:42 -07001408
Don Garrett60fc59c2013-10-18 11:43:52 -07001409 // If new_image_info is present, old_image_info must be present.
Don Garrett0dd39852013-04-03 16:55:42 -07001410 TEST_AND_RETURN_FALSE((bool)old_image_info == (bool)new_image_info);
1411 } else {
1412 // old_image_info must not be present for a full update.
1413 TEST_AND_RETURN_FALSE(!old_image_info);
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001414 }
Chris Sosad5ae1562013-04-23 13:20:18 -07001415
1416 // Sanity checks for the partition size.
1417 TEST_AND_RETURN_FALSE(rootfs_partition_size % kBlockSize == 0);
Chris Sosae9f5f422013-05-17 16:11:10 -07001418 size_t fs_size = static_cast<size_t>(new_image_block_size) *
1419 new_image_block_count;
Chris Sosad5ae1562013-04-23 13:20:18 -07001420 LOG(INFO) << "Rootfs partition size: " << rootfs_partition_size;
1421 LOG(INFO) << "Actual filesystem size: " << fs_size;
1422 TEST_AND_RETURN_FALSE(rootfs_partition_size >= fs_size);
1423
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001424 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001425 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1426
Darin Petkov7ea32332010-10-13 10:46:11 -07001427 vector<Block> blocks(max(old_image_block_count, new_image_block_count));
1428 LOG(INFO) << "Invalid block index: " << Vertex::kInvalidIndex;
1429 LOG(INFO) << "Block count: " << blocks.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001430 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1431 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1432 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1433 }
1434 Graph graph;
1435 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001436
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001437 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
1438 string temp_file_path;
Darin Petkov7438a5c2011-08-29 11:56:44 -07001439 scoped_ptr<ScopedPathUnlinker> temp_file_unlinker;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001440 off_t data_file_size = 0;
1441
1442 LOG(INFO) << "Reading files...";
1443
Don Garrettb8dd1d92013-11-22 17:40:02 -08001444 // Create empty protobuf Manifest object
1445 DeltaArchiveManifest manifest;
1446
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001447 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1448
Andrew de los Reyesef017552010-10-06 17:57:52 -07001449 vector<Vertex::Index> final_order;
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001450 Vertex::Index scratch_vertex = Vertex::kInvalidIndex;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001451 {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001452 int fd;
1453 TEST_AND_RETURN_FALSE(
1454 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001455 temp_file_unlinker.reset(new ScopedPathUnlinker(temp_file_path));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001456 TEST_AND_RETURN_FALSE(fd >= 0);
1457 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001458 if (!old_image.empty()) {
1459 // Delta update
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001460
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001461 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1462 &blocks,
1463 old_root,
1464 new_root,
Darin Petkov8e447e02013-04-16 16:23:50 +02001465 chunk_size,
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001466 fd,
1467 &data_file_size));
1468 LOG(INFO) << "done reading normal files";
1469 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001470
Thieu Le5c7d9752010-12-15 16:09:28 -08001471 LOG(INFO) << "Starting metadata processing";
1472 TEST_AND_RETURN_FALSE(Metadata::DeltaReadMetadata(&graph,
1473 &blocks,
1474 old_image,
1475 new_image,
1476 fd,
1477 &data_file_size));
1478 LOG(INFO) << "Done metadata processing";
1479 CheckGraph(graph);
1480
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001481 graph.resize(graph.size() + 1);
1482 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1483 fd,
1484 &data_file_size,
1485 new_image,
1486 &graph.back()));
1487
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001488 // Final scratch block (if there's space)
Chris Sosad5ae1562013-04-23 13:20:18 -07001489 if (blocks.size() < (rootfs_partition_size / kBlockSize)) {
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001490 scratch_vertex = graph.size();
1491 graph.resize(graph.size() + 1);
1492 CreateScratchNode(blocks.size(),
Chris Sosad5ae1562013-04-23 13:20:18 -07001493 (rootfs_partition_size / kBlockSize) - blocks.size(),
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001494 &graph.back());
1495 }
1496
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001497 // Read kernel partition
1498 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1499 new_kernel_part,
1500 &kernel_ops,
1501 fd,
1502 &data_file_size));
1503
1504 LOG(INFO) << "done reading kernel";
1505 CheckGraph(graph);
1506
1507 LOG(INFO) << "Creating edges...";
1508 CreateEdges(&graph, blocks);
1509 LOG(INFO) << "Done creating edges";
1510 CheckGraph(graph);
1511
1512 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1513 new_root,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001514 fd,
1515 &data_file_size,
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001516 &final_order,
1517 scratch_vertex));
Don Garrettb8dd1d92013-11-22 17:40:02 -08001518
1519 // Set the minor version for this payload.
1520 LOG(INFO) << "Adding Delta Minor Version.";
1521 manifest.set_minor_version(DeltaPerformer::kSupportedMinorPayloadVersion);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001522 } else {
1523 // Full update
Darin Petkov7ea32332010-10-13 10:46:11 -07001524 off_t new_image_size =
1525 static_cast<off_t>(new_image_block_count) * new_image_block_size;
Darin Petkov7a22d792010-11-08 14:10:00 -08001526 TEST_AND_RETURN_FALSE(FullUpdateGenerator::Run(&graph,
1527 new_kernel_part,
1528 new_image,
1529 new_image_size,
1530 fd,
1531 &data_file_size,
1532 kFullUpdateChunkSize,
1533 kBlockSize,
1534 &kernel_ops,
1535 &final_order));
Don Garrettb8dd1d92013-11-22 17:40:02 -08001536
1537 // Set the minor version for this payload.
1538 LOG(INFO) << "Adding Full Minor Version.";
1539 manifest.set_minor_version(DeltaPerformer::kFullPayloadMinorVersion);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001540 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001541 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001542
Don Garrett0dd39852013-04-03 16:55:42 -07001543 if (old_image_info)
1544 *(manifest.mutable_old_image_info()) = *old_image_info;
1545
1546 if (new_image_info)
1547 *(manifest.mutable_new_image_info()) = *new_image_info;
1548
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001549 OperationNameMap op_name_map;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001550 CheckGraph(graph);
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001551 InstallOperationsToManifest(graph,
1552 final_order,
1553 kernel_ops,
1554 &manifest,
1555 &op_name_map);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001556 CheckGraph(graph);
1557 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001558
1559 // Reorder the data blobs with the newly ordered manifest
1560 string ordered_blobs_path;
1561 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1562 "/tmp/CrAU_temp_data.ordered.XXXXXX",
1563 &ordered_blobs_path,
Andrew de los Reyese05fc282011-06-02 09:50:08 -07001564 NULL));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001565 ScopedPathUnlinker ordered_blobs_unlinker(ordered_blobs_path);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001566 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1567 temp_file_path,
1568 ordered_blobs_path));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001569 temp_file_unlinker.reset();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001570
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001571 // Check that install op blobs are in order.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001572 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001573 {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001574 for (int i = 0; i < (manifest.install_operations_size() +
1575 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001576 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001577 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001578 manifest.mutable_install_operations(i) :
1579 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001580 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001581 if (op->has_data_offset()) {
1582 if (op->data_offset() != next_blob_offset) {
1583 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001584 << next_blob_offset;
1585 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001586 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001587 }
1588 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001589 }
1590
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001591 // Signatures appear at the end of the blobs. Note the offset in the
1592 // manifest
1593 if (!private_key_path.empty()) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001594 uint64_t signature_blob_length = 0;
1595 TEST_AND_RETURN_FALSE(
Andrew de los Reyesc24e3f32011-08-30 15:45:20 -07001596 PayloadSigner::SignatureBlobLength(vector<string>(1, private_key_path),
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001597 &signature_blob_length));
Darin Petkov9574f7e2011-01-13 10:48:12 -08001598 AddSignatureOp(next_blob_offset, signature_blob_length, &manifest);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001599 }
1600
Darin Petkov36a58222010-10-07 22:00:09 -07001601 TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1602 new_kernel_part,
1603 old_image,
1604 new_image,
1605 &manifest));
1606
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001607 // Serialize protobuf
1608 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001609
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001610 CheckGraph(graph);
1611 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1612 CheckGraph(graph);
1613
1614 LOG(INFO) << "Writing final delta file header...";
1615 DirectFileWriter writer;
1616 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1617 O_WRONLY | O_CREAT | O_TRUNC,
1618 0644) == 0);
1619 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001620
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001621 // Write header
Don Garrette410e0f2011-11-10 15:39:01 -08001622 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001623
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001624 // Write version number
1625 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001626
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001627 // Write protobuf length
1628 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1629 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001630
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001631 // Write protobuf
1632 LOG(INFO) << "Writing final delta file protobuf... "
1633 << serialized_manifest.size();
1634 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
Don Garrette410e0f2011-11-10 15:39:01 -08001635 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001636
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001637 // Append the data blobs
1638 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001639 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001640 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1641 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1642 for (;;) {
1643 char buf[kBlockSize];
1644 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1645 if (0 == rc) {
1646 // EOF
1647 break;
1648 }
1649 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
Don Garrette410e0f2011-11-10 15:39:01 -08001650 TEST_AND_RETURN_FALSE(writer.Write(buf, rc));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001651 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001652
1653 // Write signature blob.
1654 if (!private_key_path.empty()) {
1655 LOG(INFO) << "Signing the update...";
1656 vector<char> signature_blob;
Andrew de los Reyesc24e3f32011-08-30 15:45:20 -07001657 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(
1658 output_path,
1659 vector<string>(1, private_key_path),
1660 &signature_blob));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001661 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
Don Garrette410e0f2011-11-10 15:39:01 -08001662 signature_blob.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001663 }
1664
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001665 *metadata_size =
Darin Petkov95cf01f2010-10-12 14:59:13 -07001666 strlen(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001667 ReportPayloadUsage(manifest, *metadata_size, op_name_map);
Darin Petkov880335c2010-10-01 15:52:53 -07001668
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001669 LOG(INFO) << "All done. Successfully created delta file with "
1670 << "metadata size = " << *metadata_size;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001671 return true;
1672}
1673
Thieu Le5c7d9752010-12-15 16:09:28 -08001674// Runs the bsdiff tool on two files and returns the resulting delta in
1675// 'out'. Returns true on success.
1676bool DeltaDiffGenerator::BsdiffFiles(const string& old_file,
1677 const string& new_file,
1678 vector<char>* out) {
1679 const string kPatchFile = "/tmp/delta.patchXXXXXX";
1680 string patch_file_path;
1681
1682 TEST_AND_RETURN_FALSE(
1683 utils::MakeTempFile(kPatchFile, &patch_file_path, NULL));
1684
1685 vector<string> cmd;
1686 cmd.push_back(kBsdiffPath);
1687 cmd.push_back(old_file);
1688 cmd.push_back(new_file);
1689 cmd.push_back(patch_file_path);
1690
1691 int rc = 1;
1692 vector<char> patch_file;
Darin Petkov85d02b72011-05-17 13:25:51 -07001693 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc, NULL));
Thieu Le5c7d9752010-12-15 16:09:28 -08001694 TEST_AND_RETURN_FALSE(rc == 0);
1695 TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
1696 unlink(patch_file_path.c_str());
1697 return true;
1698}
1699
1700// The |blocks| vector contains a reader and writer for each block on the
1701// filesystem that's being in-place updated. We populate the reader/writer
1702// fields of |blocks| by calling this function.
1703// For each block in |operation| that is read or written, find that block
1704// in |blocks| and set the reader/writer field to the vertex passed.
1705// |graph| is not strictly necessary, but useful for printing out
1706// error messages.
1707bool DeltaDiffGenerator::AddInstallOpToBlocksVector(
1708 const DeltaArchiveManifest_InstallOperation& operation,
1709 const Graph& graph,
1710 Vertex::Index vertex,
1711 vector<Block>* blocks) {
1712 // See if this is already present.
1713 TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
1714
1715 enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
1716 for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
1717 const int extents_size =
1718 (field == READER) ? operation.src_extents_size() :
1719 operation.dst_extents_size();
1720 const char* past_participle = (field == READER) ? "read" : "written";
1721 const google::protobuf::RepeatedPtrField<Extent>& extents =
1722 (field == READER) ? operation.src_extents() : operation.dst_extents();
1723 Vertex::Index Block::*access_type =
1724 (field == READER) ? &Block::reader : &Block::writer;
1725
1726 for (int i = 0; i < extents_size; i++) {
1727 const Extent& extent = extents.Get(i);
1728 if (extent.start_block() == kSparseHole) {
1729 // Hole in sparse file. skip
1730 continue;
1731 }
1732 for (uint64_t block = extent.start_block();
1733 block < (extent.start_block() + extent.num_blocks()); block++) {
1734 if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
1735 LOG(FATAL) << "Block " << block << " is already "
1736 << past_participle << " by "
1737 << (*blocks)[block].*access_type << "("
1738 << graph[(*blocks)[block].*access_type].file_name
1739 << ") and also " << vertex << "("
1740 << graph[vertex].file_name << ")";
1741 }
1742 (*blocks)[block].*access_type = vertex;
1743 }
1744 }
1745 }
1746 return true;
1747}
1748
Darin Petkov9574f7e2011-01-13 10:48:12 -08001749void DeltaDiffGenerator::AddSignatureOp(uint64_t signature_blob_offset,
1750 uint64_t signature_blob_length,
1751 DeltaArchiveManifest* manifest) {
1752 LOG(INFO) << "Making room for signature in file";
1753 manifest->set_signatures_offset(signature_blob_offset);
1754 LOG(INFO) << "set? " << manifest->has_signatures_offset();
1755 // Add a dummy op at the end to appease older clients
1756 DeltaArchiveManifest_InstallOperation* dummy_op =
1757 manifest->add_kernel_install_operations();
1758 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1759 dummy_op->set_data_offset(signature_blob_offset);
1760 manifest->set_signatures_offset(signature_blob_offset);
1761 dummy_op->set_data_length(signature_blob_length);
1762 manifest->set_signatures_size(signature_blob_length);
1763 Extent* dummy_extent = dummy_op->add_dst_extents();
1764 // Tell the dummy op to write this data to a big sparse hole
1765 dummy_extent->set_start_block(kSparseHole);
1766 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1767 kBlockSize);
1768}
1769
Andrew de los Reyes50f36492010-11-01 13:57:12 -07001770const char* const kBsdiffPath = "bsdiff";
1771const char* const kBspatchPath = "bspatch";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001772const char* const kDeltaMagic = "CrAU";
1773
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001774}; // namespace chromeos_update_engine