blob: 4d67c4ed5779fa82108b15f133b45d23ec9bf3a5 [file] [log] [blame]
Darin Petkovc0b7a532010-09-29 15:18:14 -07001// Copyright (c) 2010 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>
Darin Petkov880335c2010-10-01 15:52:53 -07009#include <sys/stat.h>
10#include <sys/types.h>
11
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070012#include <algorithm>
13#include <set>
14#include <string>
15#include <utility>
16#include <vector>
Darin Petkov880335c2010-10-01 15:52:53 -070017
18#include <base/logging.h>
19#include <base/string_util.h>
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070020#include <bzlib.h>
Darin Petkov880335c2010-10-01 15:52:53 -070021
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070022#include "update_engine/bzip.h"
23#include "update_engine/cycle_breaker.h"
24#include "update_engine/extent_mapper.h"
25#include "update_engine/file_writer.h"
26#include "update_engine/filesystem_iterator.h"
27#include "update_engine/graph_types.h"
28#include "update_engine/graph_utils.h"
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -070029#include "update_engine/payload_signer.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070030#include "update_engine/subprocess.h"
31#include "update_engine/topological_sort.h"
32#include "update_engine/update_metadata.pb.h"
33#include "update_engine/utils.h"
34
35using std::make_pair;
Andrew de los Reyes3270f742010-07-15 22:28:14 -070036using std::max;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070037using std::min;
38using std::set;
39using std::string;
40using std::vector;
41
42namespace chromeos_update_engine {
43
44typedef DeltaDiffGenerator::Block Block;
45
46namespace {
47const size_t kBlockSize = 4096;
Darin Petkovc0b7a532010-09-29 15:18:14 -070048const size_t kRootFSPartitionSize = 1 * 1024 * 1024 * 1024; // 1 GiB
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070049const uint64_t kVersionNumber = 1;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070050
51// Stores all Extents for a file into 'out'. Returns true on success.
52bool GatherExtents(const string& path,
53 google::protobuf::RepeatedPtrField<Extent>* out) {
54 vector<Extent> extents;
55 TEST_AND_RETURN_FALSE(extent_mapper::ExtentsForFileFibmap(path, &extents));
56 DeltaDiffGenerator::StoreExtents(extents, out);
57 return true;
58}
59
60// Runs the bsdiff tool on two files and returns the resulting delta in
61// 'out'. Returns true on success.
62bool BsdiffFiles(const string& old_file,
63 const string& new_file,
64 vector<char>* out) {
65 const string kPatchFile = "/tmp/delta.patchXXXXXX";
66 string patch_file_path;
67
68 TEST_AND_RETURN_FALSE(
69 utils::MakeTempFile(kPatchFile, &patch_file_path, NULL));
70
71 vector<string> cmd;
72 cmd.push_back(kBsdiffPath);
73 cmd.push_back(old_file);
74 cmd.push_back(new_file);
75 cmd.push_back(patch_file_path);
76
77 int rc = 1;
78 vector<char> patch_file;
79 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc));
80 TEST_AND_RETURN_FALSE(rc == 0);
81 TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
82 unlink(patch_file_path.c_str());
83 return true;
84}
85
86// The blocks vector contains a reader and writer for each block on the
87// filesystem that's being in-place updated. We populate the reader/writer
88// fields of blocks by calling this function.
89// For each block in 'operation' that is read or written, find that block
90// in 'blocks' and set the reader/writer field to the vertex passed.
91// 'graph' is not strictly necessary, but useful for printing out
92// error messages.
93bool AddInstallOpToBlocksVector(
94 const DeltaArchiveManifest_InstallOperation& operation,
95 vector<Block>* blocks,
96 const Graph& graph,
97 Vertex::Index vertex) {
98 LOG(INFO) << "AddInstallOpToBlocksVector(" << vertex << "), "
99 << graph[vertex].file_name;
100 // See if this is already present.
101 TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700102
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700103 enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
104 for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
105 const int extents_size =
106 (field == READER) ? operation.src_extents_size() :
107 operation.dst_extents_size();
108 const char* past_participle = (field == READER) ? "read" : "written";
109 const google::protobuf::RepeatedPtrField<Extent>& extents =
110 (field == READER) ? operation.src_extents() : operation.dst_extents();
111 Vertex::Index Block::*access_type =
112 (field == READER) ? &Block::reader : &Block::writer;
113
114 for (int i = 0; i < extents_size; i++) {
115 const Extent& extent = extents.Get(i);
116 if (extent.start_block() == kSparseHole) {
117 // Hole in sparse file. skip
118 continue;
119 }
120 for (uint64_t block = extent.start_block();
121 block < (extent.start_block() + extent.num_blocks()); block++) {
122 LOG(INFO) << "ext: " << i << " block: " << block;
123 if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
124 LOG(FATAL) << "Block " << block << " is already "
125 << past_participle << " by "
126 << (*blocks)[block].*access_type << "("
127 << graph[(*blocks)[block].*access_type].file_name
128 << ") and also " << vertex << "("
129 << graph[vertex].file_name << ")";
130 }
131 (*blocks)[block].*access_type = vertex;
132 }
133 }
134 }
135 return true;
136}
137
138// For a given regular file which must exist at new_root + path, and may
139// exist at old_root + path, creates a new InstallOperation and adds it to
140// the graph. Also, populates the 'blocks' array as necessary.
141// Also, writes the data necessary to send the file down to the client
142// into data_fd, which has length *data_file_size. *data_file_size is
143// updated appropriately.
144// Returns true on success.
145bool DeltaReadFile(Graph* graph,
146 vector<Block>* blocks,
147 const string& old_root,
148 const string& new_root,
149 const string& path, // within new_root
150 int data_fd,
151 off_t* data_file_size) {
152 vector<char> data;
153 DeltaArchiveManifest_InstallOperation operation;
154
155 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_root + path,
156 new_root + path,
157 &data,
158 &operation));
159
160 // Write the data
161 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
162 operation.set_data_offset(*data_file_size);
163 operation.set_data_length(data.size());
164 }
165
166 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
167 *data_file_size += data.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700168
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700169 // Now, insert into graph and blocks vector
170 graph->resize(graph->size() + 1);
171 graph->back().op = operation;
172 CHECK(graph->back().op.has_type());
173 graph->back().file_name = path;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700174
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700175 TEST_AND_RETURN_FALSE(AddInstallOpToBlocksVector(graph->back().op,
176 blocks,
177 *graph,
178 graph->size() - 1));
179 return true;
180}
181
182// For each regular file within new_root, creates a node in the graph,
183// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
184// and writes any necessary data to the end of data_fd.
185bool DeltaReadFiles(Graph* graph,
186 vector<Block>* blocks,
187 const string& old_root,
188 const string& new_root,
189 int data_fd,
190 off_t* data_file_size) {
191 set<ino_t> visited_inodes;
192 for (FilesystemIterator fs_iter(new_root,
193 utils::SetWithValue<string>("/lost+found"));
194 !fs_iter.IsEnd(); fs_iter.Increment()) {
195 if (!S_ISREG(fs_iter.GetStat().st_mode))
196 continue;
197
198 // Make sure we visit each inode only once.
199 if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
200 continue;
201 visited_inodes.insert(fs_iter.GetStat().st_ino);
202 if (fs_iter.GetStat().st_size == 0)
203 continue;
204
205 LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700206
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700207 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
208 blocks,
209 old_root,
210 new_root,
211 fs_iter.GetPartialPath(),
212 data_fd,
213 data_file_size));
214 }
215 return true;
216}
217
Darin Petkovc0b7a532010-09-29 15:18:14 -0700218// Attempts to find |block_count| blocks to use as scratch space. Returns true
219// on success. Right now we return exactly as many blocks as are required.
220//
221// TODO(adlr): Consider returning all scratch blocks, even if there are extras,
222// to make it easier for a scratch allocator to find contiguous regions for
223// specific scratch writes.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700224bool FindScratchSpace(const vector<Block>& blocks,
225 vector<Block>::size_type block_count,
226 vector<Extent>* out) {
Darin Petkovc0b7a532010-09-29 15:18:14 -0700227 // Scan |blocks| for blocks that are neither read, nor written. If we don't
228 // find enough of those, look past the end of |blocks| till the end of the
229 // partition. If we don't find |block_count| scratch blocks, return false.
230 //
231 // TODO(adlr): Return blocks that are written by operations that don't have
232 // incoming edges (and thus, can be deferred until all old blocks are read by
233 // other operations).
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700234 vector<Extent> ret;
235 vector<Block>::size_type blocks_found = 0;
Darin Petkovc0b7a532010-09-29 15:18:14 -0700236 const size_t kPartitionBlocks = kRootFSPartitionSize / kBlockSize;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700237 for (vector<Block>::size_type i = 0;
Darin Petkovc0b7a532010-09-29 15:18:14 -0700238 i < kPartitionBlocks && blocks_found < block_count; i++) {
239 if (i >= blocks.size() ||
240 (blocks[i].reader == Vertex::kInvalidIndex &&
241 blocks[i].writer == Vertex::kInvalidIndex)) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700242 graph_utils::AppendBlockToExtents(&ret, i);
243 blocks_found++;
244 }
245 }
Darin Petkovc0b7a532010-09-29 15:18:14 -0700246 LOG(INFO) << "found " << blocks_found << " scratch blocks";
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700247 if (blocks_found == block_count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700248 out->swap(ret);
249 return true;
250 }
251 return false;
252}
253
254// This class takes a collection of Extents and allows the client to
255// allocate space from these extents. The client must not request more
256// space then exists in the source extents. Space is allocated from the
257// beginning of the source extents on; no consideration is paid to
258// fragmentation.
259class LinearExtentAllocator {
260 public:
261 explicit LinearExtentAllocator(const vector<Extent>& extents)
262 : extents_(extents),
263 extent_index_(0),
264 extent_blocks_allocated_(0) {}
265 vector<Extent> Allocate(const uint64_t block_count) {
266 vector<Extent> ret;
267 for (uint64_t blocks = 0; blocks < block_count; blocks++) {
268 CHECK_LT(extent_index_, extents_.size());
269 CHECK_LT(extent_blocks_allocated_, extents_[extent_index_].num_blocks());
270 graph_utils::AppendBlockToExtents(
271 &ret,
272 extents_[extent_index_].start_block() + extent_blocks_allocated_);
273 extent_blocks_allocated_++;
274 if (extent_blocks_allocated_ >= extents_[extent_index_].num_blocks()) {
275 extent_blocks_allocated_ = 0;
276 extent_index_++;
277 }
278 }
279 return ret;
280 }
281 private:
282 const vector<Extent> extents_;
283 vector<Extent>::size_type extent_index_; // current Extent
284 // number of blocks allocated from the current extent
285 uint64_t extent_blocks_allocated_;
286};
287
288// Reads blocks from image_path that are not yet marked as being written
289// in the blocks array. These blocks that remain are non-file-data blocks.
290// In the future we might consider intelligent diffing between this data
291// and data in the previous image, but for now we just bzip2 compress it
292// and include it in the update.
293// Creates a new node in the graph to write these blocks and writes the
294// appropriate blob to blobs_fd. Reads and updates blobs_length;
295bool ReadUnwrittenBlocks(const vector<Block>& blocks,
296 int blobs_fd,
297 off_t* blobs_length,
298 const string& image_path,
299 DeltaArchiveManifest_InstallOperation* out_op) {
300 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
301 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
302 ScopedFdCloser image_fd_closer(&image_fd);
303
304 string temp_file_path;
305 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
306 &temp_file_path,
307 NULL));
308
309 FILE* file = fopen(temp_file_path.c_str(), "w");
310 TEST_AND_RETURN_FALSE(file);
311 int err = BZ_OK;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700312
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700313 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
314 file,
315 9, // max compression
316 0, // verbosity
317 0); // default work factor
318 TEST_AND_RETURN_FALSE(err == BZ_OK);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700319
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700320 vector<Extent> extents;
321 vector<Block>::size_type block_count = 0;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700322
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700323 LOG(INFO) << "Appending left over blocks to extents";
324 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
325 if (blocks[i].writer != Vertex::kInvalidIndex)
326 continue;
327 graph_utils::AppendBlockToExtents(&extents, i);
328 block_count++;
329 }
330
331 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
332 // so we arbitrarily set it to 1024 * kBlockSize.
333 vector<char> buf(1024 * kBlockSize);
334
335 LOG(INFO) << "Reading left over blocks";
336 vector<Block>::size_type blocks_copied_count = 0;
337
338 // For each extent in extents, write the data into BZ2_bzWrite which
339 // sends it to an output file.
340 // We use the temporary buffer 'buf' to hold the data, which may be
341 // smaller than the extent, so in that case we have to loop to get
342 // the extent's data (that's the inner while loop).
343 for (vector<Extent>::const_iterator it = extents.begin();
344 it != extents.end(); ++it) {
345 vector<Block>::size_type blocks_read = 0;
346 while (blocks_read < it->num_blocks()) {
347 const int copy_block_cnt =
348 min(buf.size() / kBlockSize,
349 static_cast<vector<char>::size_type>(
350 it->num_blocks() - blocks_read));
351 ssize_t rc = pread(image_fd,
352 &buf[0],
353 copy_block_cnt * kBlockSize,
354 (it->start_block() + blocks_read) * kBlockSize);
355 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
356 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
357 copy_block_cnt * kBlockSize);
358 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
359 TEST_AND_RETURN_FALSE(err == BZ_OK);
360 blocks_read += copy_block_cnt;
361 blocks_copied_count += copy_block_cnt;
362 LOG(INFO) << "progress: " << ((float)blocks_copied_count)/block_count;
363 }
364 }
365 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
366 TEST_AND_RETURN_FALSE(err == BZ_OK);
367 bz_file = NULL;
368 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
369 file = NULL;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700370
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700371 vector<char> compressed_data;
372 LOG(INFO) << "Reading compressed data off disk";
373 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
374 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700375
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700376 // Add node to graph to write these blocks
377 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
378 out_op->set_data_offset(*blobs_length);
379 out_op->set_data_length(compressed_data.size());
380 *blobs_length += compressed_data.size();
381 out_op->set_dst_length(kBlockSize * block_count);
382 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700383
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700384 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
385 &compressed_data[0],
386 compressed_data.size()));
387 LOG(INFO) << "done with extra blocks";
388 return true;
389}
390
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700391// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700392// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700393bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
394 uint64_t value_be = htobe64(value);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700395 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)) ==
396 sizeof(value_be));
397 return true;
398}
399
400// Adds each operation from the graph to the manifest in the order
401// specified by 'order'.
402void InstallOperationsToManifest(
403 const Graph& graph,
404 const vector<Vertex::Index>& order,
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700405 const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700406 DeltaArchiveManifest* out_manifest) {
407 for (vector<Vertex::Index>::const_iterator it = order.begin();
408 it != order.end(); ++it) {
409 DeltaArchiveManifest_InstallOperation* op =
410 out_manifest->add_install_operations();
411 *op = graph[*it].op;
412 }
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) {
415 DeltaArchiveManifest_InstallOperation* op =
416 out_manifest->add_kernel_install_operations();
417 *op = *it;
418 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700419}
420
421void CheckGraph(const Graph& graph) {
422 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
423 CHECK(it->op.has_type());
424 }
425}
426
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700427// Delta compresses a kernel partition new_kernel_part with knowledge of
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700428// the old kernel partition old_kernel_part.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700429bool DeltaCompressKernelPartition(
430 const string& old_kernel_part,
431 const string& new_kernel_part,
432 vector<DeltaArchiveManifest_InstallOperation>* ops,
433 int blobs_fd,
434 off_t* blobs_length) {
435 // For now, just bsdiff the kernel partition as a whole.
436 // TODO(adlr): Use knowledge of how the kernel partition is laid out
437 // to more efficiently compress it.
438
439 LOG(INFO) << "Delta compressing kernel partition...";
440
441 // Add a new install operation
442 ops->resize(1);
443 DeltaArchiveManifest_InstallOperation* op = &(*ops)[0];
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700444 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700445 op->set_data_offset(*blobs_length);
446
447 // Do the actual compression
448 vector<char> data;
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700449 TEST_AND_RETURN_FALSE(utils::ReadFile(new_kernel_part, &data));
450 TEST_AND_RETURN_FALSE(!data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700451
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700452 vector<char> data_bz;
453 TEST_AND_RETURN_FALSE(BzipCompress(data, &data_bz));
454 CHECK(!data_bz.empty());
455
456 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data_bz[0], data_bz.size()));
457 *blobs_length += data_bz.size();
458
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700459 off_t new_part_size = utils::FileSize(new_kernel_part);
460 TEST_AND_RETURN_FALSE(new_part_size >= 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700461
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700462 op->set_data_length(data_bz.size());
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700463
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700464 op->set_dst_length(new_part_size);
465
Andrew de los Reyes877ca8d2010-09-07 14:42:49 -0700466 // There's a single dest extent
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700467 Extent* dst_extent = op->add_dst_extents();
468 dst_extent->set_start_block(0);
469 dst_extent->set_num_blocks((new_part_size + kBlockSize - 1) / kBlockSize);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700470
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700471 LOG(INFO) << "Done compressing kernel partition.";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700472 return true;
473}
474
Darin Petkov880335c2010-10-01 15:52:53 -0700475struct DeltaObject {
476 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
477 : name(in_name),
478 type(in_type),
479 size(in_size) {}
480 bool operator <(const DeltaObject& object) const {
481 return size < object.size;
482 }
483 string name;
484 int type;
485 off_t size;
486};
487
488static const char* kInstallOperationTypes[] = {
489 "REPLACE",
490 "REPLACE_BZ",
491 "MOVE",
492 "BSDIFF"
493};
494
495void ReportPayloadUsage(const Graph& graph,
496 const DeltaArchiveManifest& manifest) {
497 vector<DeltaObject> objects;
498 off_t total_size = 0;
499
500 // Graph nodes with information about file names.
501 for (Vertex::Index node = 0; node < graph.size(); node++) {
502 objects.push_back(DeltaObject(graph[node].file_name,
503 graph[node].op.type(),
504 graph[node].op.data_length()));
505 total_size += graph[node].op.data_length();
506 }
507
508 // Final rootfs operation writing non-file-data.
509 const DeltaArchiveManifest_InstallOperation& final_op =
510 manifest.install_operations(manifest.install_operations_size() - 1);
511 objects.push_back(DeltaObject("<rootfs-final-operation>",
512 final_op.type(),
513 final_op.data_length()));
514 total_size += final_op.data_length();
515
516 // Kernel install operations.
517 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
518 const DeltaArchiveManifest_InstallOperation& op =
519 manifest.kernel_install_operations(i);
520 objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
521 op.type(),
522 op.data_length()));
523 total_size += op.data_length();
524 }
525
526 std::sort(objects.begin(), objects.end());
527
528 static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
529 for (vector<DeltaObject>::const_iterator it = objects.begin();
530 it != objects.end(); ++it) {
531 const DeltaObject& object = *it;
532 fprintf(stderr, kFormatString,
533 object.size * 100.0 / total_size,
534 object.size,
535 kInstallOperationTypes[object.type],
536 object.name.c_str());
537 }
538 fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
539}
540
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700541} // namespace {}
542
543bool DeltaDiffGenerator::ReadFileToDiff(
544 const string& old_filename,
545 const string& new_filename,
546 vector<char>* out_data,
547 DeltaArchiveManifest_InstallOperation* out_op) {
548 // Read new data in
549 vector<char> new_data;
550 TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700551
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700552 TEST_AND_RETURN_FALSE(!new_data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700553
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700554 vector<char> new_data_bz;
555 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
556 CHECK(!new_data_bz.empty());
557
558 vector<char> data; // Data blob that will be written to delta file.
559
560 DeltaArchiveManifest_InstallOperation operation;
561 size_t current_best_size = 0;
562 if (new_data.size() <= new_data_bz.size()) {
563 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
564 current_best_size = new_data.size();
565 data = new_data;
566 } else {
567 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
568 current_best_size = new_data_bz.size();
569 data = new_data_bz;
570 }
571
572 // Do we have an original file to consider?
573 struct stat old_stbuf;
574 if (0 != stat(old_filename.c_str(), &old_stbuf)) {
575 // If stat-ing the old file fails, it should be because it doesn't exist.
576 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
577 } else {
578 // Read old data
579 vector<char> old_data;
580 TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
581 if (old_data == new_data) {
582 // No change in data.
583 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
584 current_best_size = 0;
585 data.clear();
586 } else {
587 // Try bsdiff of old to new data
588 vector<char> bsdiff_delta;
589 TEST_AND_RETURN_FALSE(
590 BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
591 CHECK_GT(bsdiff_delta.size(), 0);
592 if (bsdiff_delta.size() < current_best_size) {
593 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
594 current_best_size = bsdiff_delta.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700595
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700596 data = bsdiff_delta;
597 }
598 }
599 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700600
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700601 // Set parameters of the operations
602 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700603
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700604 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
605 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
606 TEST_AND_RETURN_FALSE(
607 GatherExtents(old_filename, operation.mutable_src_extents()));
608 operation.set_src_length(old_stbuf.st_size);
609 }
610
611 TEST_AND_RETURN_FALSE(
612 GatherExtents(new_filename, operation.mutable_dst_extents()));
613 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700614
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700615 out_data->swap(data);
616 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700617
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700618 return true;
619}
620
621void DeltaDiffGenerator::SubstituteBlocks(
622 DeltaArchiveManifest_InstallOperation* op,
623 const vector<Extent>& remove_extents,
624 const vector<Extent>& replace_extents) {
625 // First, expand out the blocks that op reads from
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700626 vector<uint64_t> read_blocks;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700627 for (int i = 0; i < op->src_extents_size(); i++) {
628 const Extent& extent = op->src_extents(i);
629 if (extent.start_block() == kSparseHole) {
630 read_blocks.resize(read_blocks.size() + extent.num_blocks(), kSparseHole);
631 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700632 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700633 block < (extent.start_block() + extent.num_blocks()); block++) {
634 read_blocks.push_back(block);
635 }
636 }
637 }
638 {
639 // Expand remove_extents and replace_extents
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700640 vector<uint64_t> remove_extents_expanded;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700641 for (vector<Extent>::const_iterator it = remove_extents.begin();
642 it != remove_extents.end(); ++it) {
643 const Extent& extent = *it;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700644 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700645 block < (extent.start_block() + extent.num_blocks()); block++) {
646 remove_extents_expanded.push_back(block);
647 }
648 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700649 vector<uint64_t> replace_extents_expanded;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700650 for (vector<Extent>::const_iterator it = replace_extents.begin();
651 it != replace_extents.end(); ++it) {
652 const Extent& extent = *it;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700653 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700654 block < (extent.start_block() + extent.num_blocks()); block++) {
655 replace_extents_expanded.push_back(block);
656 }
657 }
658 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700659 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700660 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700661 vector<uint64_t>::size_type index = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700662 CHECK(utils::VectorIndexOf(read_blocks,
663 remove_extents_expanded[i],
664 &index));
665 CHECK(read_blocks[index] == remove_extents_expanded[i]);
666 read_blocks[index] = replace_extents_expanded[i];
667 }
668 }
669 // Convert read_blocks back to extents
670 op->clear_src_extents();
671 vector<Extent> new_extents;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700672 for (vector<uint64_t>::const_iterator it = read_blocks.begin();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700673 it != read_blocks.end(); ++it) {
674 graph_utils::AppendBlockToExtents(&new_extents, *it);
675 }
676 DeltaDiffGenerator::StoreExtents(new_extents, op->mutable_src_extents());
677}
678
679bool DeltaDiffGenerator::CutEdges(Graph* graph,
680 const vector<Block>& blocks,
681 const set<Edge>& edges) {
682 // First, find enough scratch space for the edges we'll be cutting.
683 vector<Block>::size_type blocks_required = 0;
684 for (set<Edge>::const_iterator it = edges.begin(); it != edges.end(); ++it) {
685 blocks_required += graph_utils::EdgeWeight(*graph, *it);
686 }
687 vector<Extent> scratch_extents;
688 LOG(INFO) << "requesting " << blocks_required << " blocks of scratch";
689 TEST_AND_RETURN_FALSE(
690 FindScratchSpace(blocks, blocks_required, &scratch_extents));
691 LinearExtentAllocator scratch_allocator(scratch_extents);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700692
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700693 uint64_t scratch_blocks_used = 0;
694 for (set<Edge>::const_iterator it = edges.begin();
695 it != edges.end(); ++it) {
696 vector<Extent> old_extents =
697 (*graph)[it->first].out_edges[it->second].extents;
698 // Choose some scratch space
699 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
700 LOG(INFO) << "using " << graph_utils::EdgeWeight(*graph, *it)
701 << " scratch blocks ("
702 << scratch_blocks_used << ")";
703 vector<Extent> scratch =
704 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
705 // create vertex to copy original->scratch
706 graph->resize(graph->size() + 1);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700707
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700708 // make node depend on the copy operation
709 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
710 EdgeProperties()));
711
712 // Set src/dst extents and other proto variables for copy operation
713 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
714 DeltaDiffGenerator::StoreExtents(
715 (*graph)[it->first].out_edges[it->second].extents,
716 graph->back().op.mutable_src_extents());
717 DeltaDiffGenerator::StoreExtents(scratch,
718 graph->back().op.mutable_dst_extents());
719 graph->back().op.set_src_length(
720 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
721 graph->back().op.set_dst_length(graph->back().op.src_length());
722
723 // make the dest node read from the scratch space
724 DeltaDiffGenerator::SubstituteBlocks(
725 &((*graph)[it->second].op),
726 (*graph)[it->first].out_edges[it->second].extents,
727 scratch);
728
729 // delete the old edge
730 CHECK_EQ(1, (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700731
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700732 // Add an edge from dst to copy operation
733 (*graph)[it->second].out_edges.insert(make_pair(graph->size() - 1,
734 EdgeProperties()));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700735 }
736 return true;
737}
738
739// Stores all Extents in 'extents' into 'out'.
740void DeltaDiffGenerator::StoreExtents(
741 vector<Extent>& extents,
742 google::protobuf::RepeatedPtrField<Extent>* out) {
743 for (vector<Extent>::const_iterator it = extents.begin();
744 it != extents.end(); ++it) {
745 Extent* new_extent = out->Add();
746 *new_extent = *it;
747 }
748}
749
750// Creates all the edges for the graph. Writers of a block point to
751// readers of the same block. This is because for an edge A->B, B
752// must complete before A executes.
753void DeltaDiffGenerator::CreateEdges(Graph* graph,
754 const vector<Block>& blocks) {
755 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
756 // Blocks with both a reader and writer get an edge
757 if (blocks[i].reader == Vertex::kInvalidIndex ||
758 blocks[i].writer == Vertex::kInvalidIndex)
759 continue;
760 // Don't have a node depend on itself
761 if (blocks[i].reader == blocks[i].writer)
762 continue;
763 // See if there's already an edge we can add onto
764 Vertex::EdgeMap::iterator edge_it =
765 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
766 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
767 // No existing edge. Create one
768 (*graph)[blocks[i].writer].out_edges.insert(
769 make_pair(blocks[i].reader, EdgeProperties()));
770 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700771 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700772 }
773 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
774 }
775}
776
777bool DeltaDiffGenerator::ReorderDataBlobs(
778 DeltaArchiveManifest* manifest,
779 const std::string& data_blobs_path,
780 const std::string& new_data_blobs_path) {
781 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
782 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
783 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -0700784
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700785 DirectFileWriter writer;
786 TEST_AND_RETURN_FALSE(
787 writer.Open(new_data_blobs_path.c_str(),
788 O_WRONLY | O_TRUNC | O_CREAT,
789 0644) == 0);
790 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700791 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700792
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700793 for (int i = 0; i < (manifest->install_operations_size() +
794 manifest->kernel_install_operations_size()); i++) {
795 DeltaArchiveManifest_InstallOperation* op = NULL;
796 if (i < manifest->install_operations_size()) {
797 op = manifest->mutable_install_operations(i);
798 } else {
799 op = manifest->mutable_kernel_install_operations(
800 i - manifest->install_operations_size());
801 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700802 if (!op->has_data_offset())
803 continue;
804 CHECK(op->has_data_length());
805 vector<char> buf(op->data_length());
806 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
807 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
808
809 op->set_data_offset(out_file_size);
810 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()) ==
811 static_cast<ssize_t>(buf.size()));
812 out_file_size += buf.size();
813 }
814 return true;
815}
816
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700817bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
818 const string& old_root,
819 const string& old_image,
820 const string& new_root,
821 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700822 const string& old_kernel_part,
823 const string& new_kernel_part,
824 const string& output_path,
825 const string& private_key_path) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700826 struct stat old_image_stbuf;
827 TEST_AND_RETURN_FALSE_ERRNO(stat(old_image.c_str(), &old_image_stbuf) == 0);
828 struct stat new_image_stbuf;
829 TEST_AND_RETURN_FALSE_ERRNO(stat(new_image.c_str(), &new_image_stbuf) == 0);
830 LOG_IF(WARNING, new_image_stbuf.st_size != old_image_stbuf.st_size)
831 << "Old and new images are different sizes.";
832 LOG_IF(FATAL, new_image_stbuf.st_size % kBlockSize)
833 << "New image not a multiple of block size " << kBlockSize;
834 LOG_IF(FATAL, old_image_stbuf.st_size % kBlockSize)
835 << "Old image not a multiple of block size " << kBlockSize;
836
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700837 // Sanity check kernel partition args
838 TEST_AND_RETURN_FALSE(utils::FileSize(old_kernel_part) >= 0);
839 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
840
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700841 vector<Block> blocks(max(old_image_stbuf.st_size / kBlockSize,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700842 new_image_stbuf.st_size / kBlockSize));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700843 LOG(INFO) << "invalid: " << Vertex::kInvalidIndex;
844 LOG(INFO) << "len: " << blocks.size();
845 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
846 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
847 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
848 }
849 Graph graph;
850 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700851
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700852 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
853 string temp_file_path;
854 off_t data_file_size = 0;
855
856 LOG(INFO) << "Reading files...";
857
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700858 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
859
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700860 DeltaArchiveManifest_InstallOperation final_op;
861 {
862 int fd;
863 TEST_AND_RETURN_FALSE(
864 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
865 TEST_AND_RETURN_FALSE(fd >= 0);
866 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700867
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700868 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
869 &blocks,
870 old_root,
871 new_root,
872 fd,
873 &data_file_size));
874 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700875
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700876 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
877 fd,
878 &data_file_size,
879 new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700880 &final_op));
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700881
882 // Read kernel partition
883 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
884 new_kernel_part,
885 &kernel_ops,
886 fd,
887 &data_file_size));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700888 }
889 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700890
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700891 LOG(INFO) << "Creating edges...";
892 CreateEdges(&graph, blocks);
893 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700894
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700895 CycleBreaker cycle_breaker;
896 LOG(INFO) << "Finding cycles...";
897 set<Edge> cut_edges;
898 cycle_breaker.BreakCycles(graph, &cut_edges);
899 CheckGraph(graph);
900
901 // Calculate number of scratch blocks needed
902
903 LOG(INFO) << "Cutting cycles...";
904 TEST_AND_RETURN_FALSE(CutEdges(&graph, blocks, cut_edges));
905 CheckGraph(graph);
906
907 vector<Vertex::Index> final_order;
908 LOG(INFO) << "Ordering...";
909 TopologicalSort(graph, &final_order);
910 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700911
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700912 // Convert to protobuf Manifest object
913 DeltaArchiveManifest manifest;
914 CheckGraph(graph);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700915 InstallOperationsToManifest(graph, final_order, kernel_ops, &manifest);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700916 {
917 // Write final operation
918 DeltaArchiveManifest_InstallOperation* op =
919 manifest.add_install_operations();
920 *op = final_op;
921 CHECK(op->has_type());
922 LOG(INFO) << "final op length: " << op->data_length();
923 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700924
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700925 CheckGraph(graph);
926 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700927
928 // Reorder the data blobs with the newly ordered manifest
929 string ordered_blobs_path;
930 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
931 "/tmp/CrAU_temp_data.ordered.XXXXXX",
932 &ordered_blobs_path,
933 false));
934 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
935 temp_file_path,
936 ordered_blobs_path));
937
938 // Check that install op blobs are in order and that all blocks are written.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700939 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700940 {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700941 vector<uint32_t> written_count(blocks.size(), 0);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700942 for (int i = 0; i < (manifest.install_operations_size() +
943 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700944 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700945 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700946 manifest.mutable_install_operations(i) :
947 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700948 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700949 for (int j = 0; j < op->dst_extents_size(); j++) {
950 const Extent& extent = op->dst_extents(j);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700951 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700952 block < (extent.start_block() + extent.num_blocks()); block++) {
Darin Petkovc0b7a532010-09-29 15:18:14 -0700953 if (block < blocks.size())
954 written_count[block]++;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700955 }
956 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700957 if (op->has_data_offset()) {
958 if (op->data_offset() != next_blob_offset) {
959 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700960 << next_blob_offset;
961 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700962 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700963 }
964 }
965 // check all blocks written to
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700966 for (vector<uint32_t>::size_type i = 0; i < written_count.size(); i++) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700967 if (written_count[i] == 0) {
968 LOG(FATAL) << "block " << i << " not written!";
969 }
970 }
971 }
972
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700973 // Signatures appear at the end of the blobs. Note the offset in the
974 // manifest
975 if (!private_key_path.empty()) {
976 LOG(INFO) << "Making room for signature in file";
977 manifest.set_signatures_offset(next_blob_offset);
978 LOG(INFO) << "set? " << manifest.has_signatures_offset();
979 // Add a dummy op at the end to appease older clients
980 DeltaArchiveManifest_InstallOperation* dummy_op =
981 manifest.add_kernel_install_operations();
982 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
983 dummy_op->set_data_offset(next_blob_offset);
984 manifest.set_signatures_offset(next_blob_offset);
985 uint64_t signature_blob_length = 0;
986 TEST_AND_RETURN_FALSE(
987 PayloadSigner::SignatureBlobLength(private_key_path,
988 &signature_blob_length));
989 dummy_op->set_data_length(signature_blob_length);
990 manifest.set_signatures_size(signature_blob_length);
991 Extent* dummy_extent = dummy_op->add_dst_extents();
992 // Tell the dummy op to write this data to a big sparse hole
993 dummy_extent->set_start_block(kSparseHole);
994 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
995 kBlockSize);
996 }
997
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700998 // Serialize protobuf
999 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001000
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001001 CheckGraph(graph);
1002 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1003 CheckGraph(graph);
1004
1005 LOG(INFO) << "Writing final delta file header...";
1006 DirectFileWriter writer;
1007 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1008 O_WRONLY | O_CREAT | O_TRUNC,
1009 0644) == 0);
1010 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001011
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001012 // Write header
1013 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)) ==
Andrew de los Reyes08c4e272010-04-15 14:02:17 -07001014 static_cast<ssize_t>(strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001015
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001016 // Write version number
1017 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001018
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001019 // Write protobuf length
1020 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1021 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001022
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001023 // Write protobuf
1024 LOG(INFO) << "Writing final delta file protobuf... "
1025 << serialized_manifest.size();
1026 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
1027 serialized_manifest.size()) ==
1028 static_cast<ssize_t>(serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001029
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001030 // Append the data blobs
1031 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001032 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001033 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1034 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1035 for (;;) {
1036 char buf[kBlockSize];
1037 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1038 if (0 == rc) {
1039 // EOF
1040 break;
1041 }
1042 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
1043 TEST_AND_RETURN_FALSE(writer.Write(buf, rc) == rc);
1044 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001045
1046 // Write signature blob.
1047 if (!private_key_path.empty()) {
1048 LOG(INFO) << "Signing the update...";
1049 vector<char> signature_blob;
1050 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(output_path,
1051 private_key_path,
1052 &signature_blob));
1053 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
1054 signature_blob.size()) ==
1055 static_cast<ssize_t>(signature_blob.size()));
1056 }
1057
Darin Petkov880335c2010-10-01 15:52:53 -07001058 ReportPayloadUsage(graph, manifest);
1059
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001060 LOG(INFO) << "All done. Successfully created delta file.";
1061 return true;
1062}
1063
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001064const char* const kBsdiffPath = "/usr/bin/bsdiff";
1065const char* const kBspatchPath = "/usr/bin/bspatch";
1066const char* const kDeltaMagic = "CrAU";
1067
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001068}; // namespace chromeos_update_engine