blob: 23c2dd0335afbff549bf5cc8f569849717b13f72 [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>
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
20#include <base/logging.h>
21#include <base/string_util.h>
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070022#include <bzlib.h>
Darin Petkov880335c2010-10-01 15:52:53 -070023
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070024#include "update_engine/bzip.h"
25#include "update_engine/cycle_breaker.h"
26#include "update_engine/extent_mapper.h"
Andrew de los Reyesef017552010-10-06 17:57:52 -070027#include "update_engine/extent_ranges.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070028#include "update_engine/file_writer.h"
29#include "update_engine/filesystem_iterator.h"
30#include "update_engine/graph_types.h"
31#include "update_engine/graph_utils.h"
Darin Petkov36a58222010-10-07 22:00:09 -070032#include "update_engine/omaha_hash_calculator.h"
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -070033#include "update_engine/payload_signer.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070034#include "update_engine/subprocess.h"
35#include "update_engine/topological_sort.h"
36#include "update_engine/update_metadata.pb.h"
37#include "update_engine/utils.h"
38
39using std::make_pair;
Andrew de los Reyesef017552010-10-06 17:57:52 -070040using std::map;
Andrew de los Reyes3270f742010-07-15 22:28:14 -070041using std::max;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070042using std::min;
43using std::set;
44using std::string;
45using std::vector;
46
47namespace chromeos_update_engine {
48
49typedef DeltaDiffGenerator::Block Block;
50
51namespace {
Andrew de los Reyes27f7d372010-10-07 11:26:07 -070052const size_t kBlockSize = 4096; // bytes
Darin Petkovc0b7a532010-09-29 15:18:14 -070053const size_t kRootFSPartitionSize = 1 * 1024 * 1024 * 1024; // 1 GiB
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070054const uint64_t kVersionNumber = 1;
Andrew de los Reyes27f7d372010-10-07 11:26:07 -070055const uint64_t kFullUpdateChunkSize = 128 * 1024; // bytes
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070056
57// Stores all Extents for a file into 'out'. Returns true on success.
58bool GatherExtents(const string& path,
59 google::protobuf::RepeatedPtrField<Extent>* out) {
60 vector<Extent> extents;
61 TEST_AND_RETURN_FALSE(extent_mapper::ExtentsForFileFibmap(path, &extents));
62 DeltaDiffGenerator::StoreExtents(extents, out);
63 return true;
64}
65
66// Runs the bsdiff tool on two files and returns the resulting delta in
67// 'out'. Returns true on success.
68bool BsdiffFiles(const string& old_file,
69 const string& new_file,
70 vector<char>* out) {
71 const string kPatchFile = "/tmp/delta.patchXXXXXX";
72 string patch_file_path;
73
74 TEST_AND_RETURN_FALSE(
75 utils::MakeTempFile(kPatchFile, &patch_file_path, NULL));
76
77 vector<string> cmd;
78 cmd.push_back(kBsdiffPath);
79 cmd.push_back(old_file);
80 cmd.push_back(new_file);
81 cmd.push_back(patch_file_path);
82
83 int rc = 1;
84 vector<char> patch_file;
85 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc));
86 TEST_AND_RETURN_FALSE(rc == 0);
87 TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
88 unlink(patch_file_path.c_str());
89 return true;
90}
91
92// The blocks vector contains a reader and writer for each block on the
93// filesystem that's being in-place updated. We populate the reader/writer
94// fields of blocks by calling this function.
95// For each block in 'operation' that is read or written, find that block
96// in 'blocks' and set the reader/writer field to the vertex passed.
97// 'graph' is not strictly necessary, but useful for printing out
98// error messages.
99bool AddInstallOpToBlocksVector(
100 const DeltaArchiveManifest_InstallOperation& operation,
101 vector<Block>* blocks,
102 const Graph& graph,
103 Vertex::Index vertex) {
104 LOG(INFO) << "AddInstallOpToBlocksVector(" << vertex << "), "
105 << graph[vertex].file_name;
106 // See if this is already present.
107 TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700108
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700109 enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
110 for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
111 const int extents_size =
112 (field == READER) ? operation.src_extents_size() :
113 operation.dst_extents_size();
114 const char* past_participle = (field == READER) ? "read" : "written";
115 const google::protobuf::RepeatedPtrField<Extent>& extents =
116 (field == READER) ? operation.src_extents() : operation.dst_extents();
117 Vertex::Index Block::*access_type =
118 (field == READER) ? &Block::reader : &Block::writer;
119
120 for (int i = 0; i < extents_size; i++) {
121 const Extent& extent = extents.Get(i);
122 if (extent.start_block() == kSparseHole) {
123 // Hole in sparse file. skip
124 continue;
125 }
126 for (uint64_t block = extent.start_block();
127 block < (extent.start_block() + extent.num_blocks()); block++) {
128 LOG(INFO) << "ext: " << i << " block: " << block;
129 if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
130 LOG(FATAL) << "Block " << block << " is already "
131 << past_participle << " by "
132 << (*blocks)[block].*access_type << "("
133 << graph[(*blocks)[block].*access_type].file_name
134 << ") and also " << vertex << "("
135 << graph[vertex].file_name << ")";
136 }
137 (*blocks)[block].*access_type = vertex;
138 }
139 }
140 }
141 return true;
142}
143
Andrew de los Reyesef017552010-10-06 17:57:52 -0700144// For a given regular file which must exist at new_root + path, and
145// may exist at old_root + path, creates a new InstallOperation and
146// adds it to the graph. Also, populates the |blocks| array as
147// necessary, if |blocks| is non-NULL. Also, writes the data
148// necessary to send the file down to the client into data_fd, which
149// has length *data_file_size. *data_file_size is updated
150// appropriately. If |existing_vertex| is no kInvalidIndex, use that
151// rather than allocating a new vertex. Returns true on success.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700152bool DeltaReadFile(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700153 Vertex::Index existing_vertex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700154 vector<Block>* blocks,
155 const string& old_root,
156 const string& new_root,
157 const string& path, // within new_root
158 int data_fd,
159 off_t* data_file_size) {
160 vector<char> data;
161 DeltaArchiveManifest_InstallOperation operation;
162
163 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_root + path,
164 new_root + path,
165 &data,
166 &operation));
167
168 // Write the data
169 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
170 operation.set_data_offset(*data_file_size);
171 operation.set_data_length(data.size());
172 }
173
174 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
175 *data_file_size += data.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700176
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700177 // Now, insert into graph and blocks vector
Andrew de los Reyesef017552010-10-06 17:57:52 -0700178 Vertex::Index vertex = existing_vertex;
179 if (vertex == Vertex::kInvalidIndex) {
180 graph->resize(graph->size() + 1);
181 vertex = graph->size() - 1;
182 }
183 (*graph)[vertex].op = operation;
184 CHECK((*graph)[vertex].op.has_type());
185 (*graph)[vertex].file_name = path;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700186
Andrew de los Reyesef017552010-10-06 17:57:52 -0700187 if (blocks)
188 TEST_AND_RETURN_FALSE(AddInstallOpToBlocksVector((*graph)[vertex].op,
189 blocks,
190 *graph,
191 vertex));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700192 return true;
193}
194
195// For each regular file within new_root, creates a node in the graph,
196// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
197// and writes any necessary data to the end of data_fd.
198bool DeltaReadFiles(Graph* graph,
199 vector<Block>* blocks,
200 const string& old_root,
201 const string& new_root,
202 int data_fd,
203 off_t* data_file_size) {
204 set<ino_t> visited_inodes;
205 for (FilesystemIterator fs_iter(new_root,
206 utils::SetWithValue<string>("/lost+found"));
207 !fs_iter.IsEnd(); fs_iter.Increment()) {
208 if (!S_ISREG(fs_iter.GetStat().st_mode))
209 continue;
210
211 // Make sure we visit each inode only once.
212 if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
213 continue;
214 visited_inodes.insert(fs_iter.GetStat().st_ino);
215 if (fs_iter.GetStat().st_size == 0)
216 continue;
217
218 LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700219
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700220 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700221 Vertex::kInvalidIndex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700222 blocks,
223 old_root,
224 new_root,
225 fs_iter.GetPartialPath(),
226 data_fd,
227 data_file_size));
228 }
229 return true;
230}
231
Andrew de los Reyesef017552010-10-06 17:57:52 -0700232// This class allocates non-existent temp blocks, starting from
233// kTempBlockStart. Other code is responsible for converting these
234// temp blocks into real blocks, as the client can't read or write to
235// these blocks.
236class DummyExtentAllocator {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700237 public:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700238 explicit DummyExtentAllocator()
239 : next_block_(kTempBlockStart) {}
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700240 vector<Extent> Allocate(const uint64_t block_count) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700241 vector<Extent> ret(1);
242 ret[0].set_start_block(next_block_);
243 ret[0].set_num_blocks(block_count);
244 next_block_ += block_count;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700245 return ret;
246 }
247 private:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700248 uint64_t next_block_;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700249};
250
251// Reads blocks from image_path that are not yet marked as being written
252// in the blocks array. These blocks that remain are non-file-data blocks.
253// In the future we might consider intelligent diffing between this data
254// and data in the previous image, but for now we just bzip2 compress it
255// and include it in the update.
256// Creates a new node in the graph to write these blocks and writes the
257// appropriate blob to blobs_fd. Reads and updates blobs_length;
258bool ReadUnwrittenBlocks(const vector<Block>& blocks,
259 int blobs_fd,
260 off_t* blobs_length,
261 const string& image_path,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700262 Vertex* vertex) {
263 DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700264 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
265 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
266 ScopedFdCloser image_fd_closer(&image_fd);
267
268 string temp_file_path;
269 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
270 &temp_file_path,
271 NULL));
272
273 FILE* file = fopen(temp_file_path.c_str(), "w");
274 TEST_AND_RETURN_FALSE(file);
275 int err = BZ_OK;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700276
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700277 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
278 file,
279 9, // max compression
280 0, // verbosity
281 0); // default work factor
282 TEST_AND_RETURN_FALSE(err == BZ_OK);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700283
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700284 vector<Extent> extents;
285 vector<Block>::size_type block_count = 0;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700286
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700287 LOG(INFO) << "Appending left over blocks to extents";
288 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
289 if (blocks[i].writer != Vertex::kInvalidIndex)
290 continue;
Andrew de los Reyesef017552010-10-06 17:57:52 -0700291 if (blocks[i].reader != Vertex::kInvalidIndex) {
292 graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
293 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700294 graph_utils::AppendBlockToExtents(&extents, i);
295 block_count++;
296 }
297
298 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
299 // so we arbitrarily set it to 1024 * kBlockSize.
300 vector<char> buf(1024 * kBlockSize);
301
302 LOG(INFO) << "Reading left over blocks";
303 vector<Block>::size_type blocks_copied_count = 0;
304
305 // For each extent in extents, write the data into BZ2_bzWrite which
306 // sends it to an output file.
307 // We use the temporary buffer 'buf' to hold the data, which may be
308 // smaller than the extent, so in that case we have to loop to get
309 // the extent's data (that's the inner while loop).
310 for (vector<Extent>::const_iterator it = extents.begin();
311 it != extents.end(); ++it) {
312 vector<Block>::size_type blocks_read = 0;
313 while (blocks_read < it->num_blocks()) {
314 const int copy_block_cnt =
315 min(buf.size() / kBlockSize,
316 static_cast<vector<char>::size_type>(
317 it->num_blocks() - blocks_read));
318 ssize_t rc = pread(image_fd,
319 &buf[0],
320 copy_block_cnt * kBlockSize,
321 (it->start_block() + blocks_read) * kBlockSize);
322 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
323 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
324 copy_block_cnt * kBlockSize);
325 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
326 TEST_AND_RETURN_FALSE(err == BZ_OK);
327 blocks_read += copy_block_cnt;
328 blocks_copied_count += copy_block_cnt;
329 LOG(INFO) << "progress: " << ((float)blocks_copied_count)/block_count;
330 }
331 }
332 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
333 TEST_AND_RETURN_FALSE(err == BZ_OK);
334 bz_file = NULL;
335 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
336 file = NULL;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700337
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700338 vector<char> compressed_data;
339 LOG(INFO) << "Reading compressed data off disk";
340 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
341 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700342
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700343 // Add node to graph to write these blocks
344 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
345 out_op->set_data_offset(*blobs_length);
346 out_op->set_data_length(compressed_data.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700347 LOG(INFO) << "Rootfs non-data blocks compressed take up "
348 << compressed_data.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700349 *blobs_length += compressed_data.size();
350 out_op->set_dst_length(kBlockSize * block_count);
351 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700352
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700353 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
354 &compressed_data[0],
355 compressed_data.size()));
356 LOG(INFO) << "done with extra blocks";
357 return true;
358}
359
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700360// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700361// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700362bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
363 uint64_t value_be = htobe64(value);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700364 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)) ==
365 sizeof(value_be));
366 return true;
367}
368
369// Adds each operation from the graph to the manifest in the order
370// specified by 'order'.
371void InstallOperationsToManifest(
372 const Graph& graph,
373 const vector<Vertex::Index>& order,
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700374 const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700375 DeltaArchiveManifest* out_manifest) {
376 for (vector<Vertex::Index>::const_iterator it = order.begin();
377 it != order.end(); ++it) {
378 DeltaArchiveManifest_InstallOperation* op =
379 out_manifest->add_install_operations();
380 *op = graph[*it].op;
381 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700382 for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
383 kernel_ops.begin(); it != kernel_ops.end(); ++it) {
384 DeltaArchiveManifest_InstallOperation* op =
385 out_manifest->add_kernel_install_operations();
386 *op = *it;
387 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700388}
389
390void CheckGraph(const Graph& graph) {
391 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
392 CHECK(it->op.has_type());
393 }
394}
395
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700396// Delta compresses a kernel partition new_kernel_part with knowledge of
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700397// the old kernel partition old_kernel_part.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700398bool DeltaCompressKernelPartition(
399 const string& old_kernel_part,
400 const string& new_kernel_part,
401 vector<DeltaArchiveManifest_InstallOperation>* ops,
402 int blobs_fd,
403 off_t* blobs_length) {
404 // For now, just bsdiff the kernel partition as a whole.
405 // TODO(adlr): Use knowledge of how the kernel partition is laid out
406 // to more efficiently compress it.
407
408 LOG(INFO) << "Delta compressing kernel partition...";
409
410 // Add a new install operation
411 ops->resize(1);
412 DeltaArchiveManifest_InstallOperation* op = &(*ops)[0];
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700413 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700414 op->set_data_offset(*blobs_length);
415
416 // Do the actual compression
417 vector<char> data;
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700418 TEST_AND_RETURN_FALSE(utils::ReadFile(new_kernel_part, &data));
419 TEST_AND_RETURN_FALSE(!data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700420
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700421 vector<char> data_bz;
422 TEST_AND_RETURN_FALSE(BzipCompress(data, &data_bz));
423 CHECK(!data_bz.empty());
424
425 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data_bz[0], data_bz.size()));
426 *blobs_length += data_bz.size();
427
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700428 off_t new_part_size = utils::FileSize(new_kernel_part);
429 TEST_AND_RETURN_FALSE(new_part_size >= 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700430
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700431 op->set_data_length(data_bz.size());
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700432
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700433 op->set_dst_length(new_part_size);
434
Andrew de los Reyes877ca8d2010-09-07 14:42:49 -0700435 // There's a single dest extent
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700436 Extent* dst_extent = op->add_dst_extents();
437 dst_extent->set_start_block(0);
438 dst_extent->set_num_blocks((new_part_size + kBlockSize - 1) / kBlockSize);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700439
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700440 LOG(INFO) << "Done compressing kernel partition.";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700441 return true;
442}
443
Darin Petkov880335c2010-10-01 15:52:53 -0700444struct DeltaObject {
445 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
446 : name(in_name),
447 type(in_type),
448 size(in_size) {}
449 bool operator <(const DeltaObject& object) const {
450 return size < object.size;
451 }
452 string name;
453 int type;
454 off_t size;
455};
456
457static const char* kInstallOperationTypes[] = {
458 "REPLACE",
459 "REPLACE_BZ",
460 "MOVE",
461 "BSDIFF"
462};
463
464void ReportPayloadUsage(const Graph& graph,
465 const DeltaArchiveManifest& manifest) {
466 vector<DeltaObject> objects;
467 off_t total_size = 0;
468
469 // Graph nodes with information about file names.
470 for (Vertex::Index node = 0; node < graph.size(); node++) {
471 objects.push_back(DeltaObject(graph[node].file_name,
472 graph[node].op.type(),
473 graph[node].op.data_length()));
474 total_size += graph[node].op.data_length();
475 }
476
477 // Final rootfs operation writing non-file-data.
478 const DeltaArchiveManifest_InstallOperation& final_op =
479 manifest.install_operations(manifest.install_operations_size() - 1);
480 objects.push_back(DeltaObject("<rootfs-final-operation>",
481 final_op.type(),
482 final_op.data_length()));
483 total_size += final_op.data_length();
484
485 // Kernel install operations.
486 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
487 const DeltaArchiveManifest_InstallOperation& op =
488 manifest.kernel_install_operations(i);
489 objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
490 op.type(),
491 op.data_length()));
492 total_size += op.data_length();
493 }
494
495 std::sort(objects.begin(), objects.end());
496
497 static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
498 for (vector<DeltaObject>::const_iterator it = objects.begin();
499 it != objects.end(); ++it) {
500 const DeltaObject& object = *it;
501 fprintf(stderr, kFormatString,
502 object.size * 100.0 / total_size,
503 object.size,
504 kInstallOperationTypes[object.type],
505 object.name.c_str());
506 }
507 fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
508}
509
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700510} // namespace {}
511
512bool DeltaDiffGenerator::ReadFileToDiff(
513 const string& old_filename,
514 const string& new_filename,
515 vector<char>* out_data,
516 DeltaArchiveManifest_InstallOperation* out_op) {
517 // Read new data in
518 vector<char> new_data;
519 TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700520
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700521 TEST_AND_RETURN_FALSE(!new_data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700522
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700523 vector<char> new_data_bz;
524 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
525 CHECK(!new_data_bz.empty());
526
527 vector<char> data; // Data blob that will be written to delta file.
528
529 DeltaArchiveManifest_InstallOperation operation;
530 size_t current_best_size = 0;
531 if (new_data.size() <= new_data_bz.size()) {
532 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
533 current_best_size = new_data.size();
534 data = new_data;
535 } else {
536 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
537 current_best_size = new_data_bz.size();
538 data = new_data_bz;
539 }
540
541 // Do we have an original file to consider?
542 struct stat old_stbuf;
543 if (0 != stat(old_filename.c_str(), &old_stbuf)) {
544 // If stat-ing the old file fails, it should be because it doesn't exist.
545 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
546 } else {
547 // Read old data
548 vector<char> old_data;
549 TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
550 if (old_data == new_data) {
551 // No change in data.
552 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
553 current_best_size = 0;
554 data.clear();
555 } else {
556 // Try bsdiff of old to new data
557 vector<char> bsdiff_delta;
558 TEST_AND_RETURN_FALSE(
559 BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
560 CHECK_GT(bsdiff_delta.size(), 0);
561 if (bsdiff_delta.size() < current_best_size) {
562 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
563 current_best_size = bsdiff_delta.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700564
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700565 data = bsdiff_delta;
566 }
567 }
568 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700569
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700570 // Set parameters of the operations
571 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700572
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700573 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
574 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
575 TEST_AND_RETURN_FALSE(
576 GatherExtents(old_filename, operation.mutable_src_extents()));
577 operation.set_src_length(old_stbuf.st_size);
578 }
579
580 TEST_AND_RETURN_FALSE(
581 GatherExtents(new_filename, operation.mutable_dst_extents()));
582 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700583
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700584 out_data->swap(data);
585 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700586
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700587 return true;
588}
589
Darin Petkov36a58222010-10-07 22:00:09 -0700590bool InitializePartitionInfo(const string& partition, PartitionInfo* info) {
591 const off_t size = utils::FileSize(partition);
592 TEST_AND_RETURN_FALSE(size >= 0);
593 info->set_size(size);
594 OmahaHashCalculator hasher;
595 TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, -1) == size);
596 TEST_AND_RETURN_FALSE(hasher.Finalize());
597 const vector<char>& hash = hasher.raw_hash();
598 info->set_hash(hash.data(), hash.size());
599 return true;
600}
601
602bool InitializePartitionInfos(const string& old_kernel,
603 const string& new_kernel,
604 const string& old_rootfs,
605 const string& new_rootfs,
606 DeltaArchiveManifest* manifest) {
607 if (!old_kernel.empty()) {
608 TEST_AND_RETURN_FALSE(
609 InitializePartitionInfo(old_kernel,
610 manifest->mutable_old_kernel_info()));
611 }
612 TEST_AND_RETURN_FALSE(
613 InitializePartitionInfo(new_kernel, manifest->mutable_new_kernel_info()));
614 if (!old_rootfs.empty()) {
615 TEST_AND_RETURN_FALSE(
616 InitializePartitionInfo(old_rootfs,
617 manifest->mutable_old_rootfs_info()));
618 }
619 TEST_AND_RETURN_FALSE(
620 InitializePartitionInfo(new_rootfs, manifest->mutable_new_rootfs_info()));
621 return true;
622}
623
Andrew de los Reyesef017552010-10-06 17:57:52 -0700624namespace {
625
626// Takes a collection (vector or RepeatedPtrField) of Extent and
627// returns a vector of the blocks referenced, in order.
628template<typename T>
629vector<uint64_t> ExpandExtents(const T& extents) {
630 vector<uint64_t> ret;
631 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
632 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700633 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700634 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700635 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700636 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700637 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700638 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700639 }
640 }
641 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700642 return ret;
643}
644
645// Takes a vector of blocks and returns an equivalent vector of Extent
646// objects.
647vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
648 vector<Extent> new_extents;
649 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
650 it != e; ++it) {
651 graph_utils::AppendBlockToExtents(&new_extents, *it);
652 }
653 return new_extents;
654}
655
656} // namespace {}
657
658void DeltaDiffGenerator::SubstituteBlocks(
659 Vertex* vertex,
660 const vector<Extent>& remove_extents,
661 const vector<Extent>& replace_extents) {
662 // First, expand out the blocks that op reads from
663 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700664 {
665 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700666 vector<uint64_t> remove_extents_expanded =
667 ExpandExtents(remove_extents);
668 vector<uint64_t> replace_extents_expanded =
669 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700670 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700671 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700672 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700673 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700674 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
675 }
676 utils::ApplyMap(&read_blocks, conversion);
677 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
678 e = vertex->out_edges.end(); it != e; ++it) {
679 vector<uint64_t> write_before_deps_expanded =
680 ExpandExtents(it->second.write_extents);
681 utils::ApplyMap(&write_before_deps_expanded, conversion);
682 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700683 }
684 }
685 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700686 vertex->op.clear_src_extents();
687 vector<Extent> new_extents = CompressExtents(read_blocks);
688 DeltaDiffGenerator::StoreExtents(new_extents,
689 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700690}
691
692bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700693 const set<Edge>& edges,
694 vector<CutEdgeVertexes>* out_cuts) {
695 DummyExtentAllocator scratch_allocator;
696 vector<CutEdgeVertexes> cuts;
697 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700698
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700699 uint64_t scratch_blocks_used = 0;
700 for (set<Edge>::const_iterator it = edges.begin();
701 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700702 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700703 vector<Extent> old_extents =
704 (*graph)[it->first].out_edges[it->second].extents;
705 // Choose some scratch space
706 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
707 LOG(INFO) << "using " << graph_utils::EdgeWeight(*graph, *it)
708 << " scratch blocks ("
709 << scratch_blocks_used << ")";
Andrew de los Reyesef017552010-10-06 17:57:52 -0700710 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700711 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
712 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700713 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700714 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700715 cuts.back().old_src = it->first;
716 cuts.back().old_dst = it->second;
Darin Petkov36a58222010-10-07 22:00:09 -0700717
Andrew de los Reyesef017552010-10-06 17:57:52 -0700718 EdgeProperties& cut_edge_properties =
719 (*graph)[it->first].out_edges.find(it->second)->second;
720
721 // This should never happen, as we should only be cutting edges between
722 // real file nodes, and write-before relationships are created from
723 // a real file node to a temp copy node:
724 CHECK(cut_edge_properties.write_extents.empty())
725 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700726
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700727 // make node depend on the copy operation
728 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700729 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700730
731 // Set src/dst extents and other proto variables for copy operation
732 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
733 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700734 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700735 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700736 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700737 graph->back().op.mutable_dst_extents());
738 graph->back().op.set_src_length(
739 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
740 graph->back().op.set_dst_length(graph->back().op.src_length());
741
742 // make the dest node read from the scratch space
743 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700744 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700745 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700746 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700747
748 // delete the old edge
749 CHECK_EQ(1, (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700750
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700751 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700752 EdgeProperties write_before_edge_properties;
753 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
754 (*graph)[it->second].out_edges.insert(
755 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700756 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700757 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700758 return true;
759}
760
761// Stores all Extents in 'extents' into 'out'.
762void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700763 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700764 google::protobuf::RepeatedPtrField<Extent>* out) {
765 for (vector<Extent>::const_iterator it = extents.begin();
766 it != extents.end(); ++it) {
767 Extent* new_extent = out->Add();
768 *new_extent = *it;
769 }
770}
771
772// Creates all the edges for the graph. Writers of a block point to
773// readers of the same block. This is because for an edge A->B, B
774// must complete before A executes.
775void DeltaDiffGenerator::CreateEdges(Graph* graph,
776 const vector<Block>& blocks) {
777 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
778 // Blocks with both a reader and writer get an edge
779 if (blocks[i].reader == Vertex::kInvalidIndex ||
780 blocks[i].writer == Vertex::kInvalidIndex)
781 continue;
782 // Don't have a node depend on itself
783 if (blocks[i].reader == blocks[i].writer)
784 continue;
785 // See if there's already an edge we can add onto
786 Vertex::EdgeMap::iterator edge_it =
787 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
788 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
789 // No existing edge. Create one
790 (*graph)[blocks[i].writer].out_edges.insert(
791 make_pair(blocks[i].reader, EdgeProperties()));
792 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700793 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700794 }
795 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
796 }
797}
798
Andrew de los Reyesef017552010-10-06 17:57:52 -0700799namespace {
800
801class SortCutsByTopoOrderLess {
802 public:
803 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
804 : table_(table) {}
805 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
806 return table_[a.old_dst] < table_[b.old_dst];
807 }
808 private:
809 vector<vector<Vertex::Index>::size_type>& table_;
810};
811
812} // namespace {}
813
814void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
815 vector<Vertex::Index>& op_indexes,
816 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
817 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
818 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
819 i != e; ++i) {
820 Vertex::Index node = op_indexes[i];
821 if (table.size() < (node + 1)) {
822 table.resize(node + 1);
823 }
824 table[node] = i;
825 }
826 reverse_op_indexes->swap(table);
827}
828
829void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
830 vector<CutEdgeVertexes>* cuts) {
831 // first, make a reverse lookup table.
832 vector<vector<Vertex::Index>::size_type> table;
833 GenerateReverseTopoOrderMap(op_indexes, &table);
834 SortCutsByTopoOrderLess less(table);
835 sort(cuts->begin(), cuts->end(), less);
836}
837
838void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
839 vector<Vertex::Index>* op_indexes) {
840 vector<Vertex::Index> ret;
841 vector<Vertex::Index> full_ops;
842 ret.reserve(op_indexes->size());
843 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
844 ++i) {
845 DeltaArchiveManifest_InstallOperation_Type type =
846 (*graph)[(*op_indexes)[i]].op.type();
847 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
848 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
849 full_ops.push_back((*op_indexes)[i]);
850 } else {
851 ret.push_back((*op_indexes)[i]);
852 }
853 }
854 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
855 << (full_ops.size() + ret.size()) << " total ops.";
856 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
857 op_indexes->swap(ret);
858}
859
860namespace {
861
862template<typename T>
863bool TempBlocksExistInExtents(const T& extents) {
864 for (int i = 0, e = extents.size(); i < e; ++i) {
865 Extent extent = graph_utils::GetElement(extents, i);
866 uint64_t start = extent.start_block();
867 uint64_t num = extent.num_blocks();
868 if (start == kSparseHole)
869 continue;
870 if (start >= kTempBlockStart ||
871 (start + num) >= kTempBlockStart) {
872 LOG(ERROR) << "temp block!";
873 LOG(ERROR) << "start: " << start << ", num: " << num;
874 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
875 LOG(ERROR) << "returning true";
876 return true;
877 }
878 // check for wrap-around, which would be a bug:
879 CHECK(start <= (start + num));
880 }
881 return false;
882}
883
884} // namespace {}
885
886bool DeltaDiffGenerator::AssignTempBlocks(
887 Graph* graph,
888 const string& new_root,
889 int data_fd,
890 off_t* data_file_size,
891 vector<Vertex::Index>* op_indexes,
892 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
893 vector<CutEdgeVertexes>& cuts) {
894 CHECK(!cuts.empty());
895 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
896 true ; --i) {
897 LOG(INFO) << "Fixing temp blocks in cut " << i
898 << ": old dst: " << cuts[i].old_dst << " new vertex: "
899 << cuts[i].new_vertex;
900 const uint64_t blocks_needed =
901 graph_utils::BlocksInExtents(cuts[i].tmp_extents);
902 LOG(INFO) << "Scanning for usable blocks (" << blocks_needed << " needed)";
903 // For now, just look for a single op w/ sufficient blocks, not
904 // considering blocks from outgoing read-before deps.
905 Vertex::Index node = cuts[i].old_dst;
906 DeltaArchiveManifest_InstallOperation_Type node_type =
907 (*graph)[node].op.type();
908 if (node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
909 node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
910 LOG(INFO) << "This was already converted to full, so skipping.";
911 // Delete the temp node and pointer to it from old src
912 if (!(*graph)[cuts[i].old_src].out_edges.erase(cuts[i].new_vertex)) {
913 LOG(INFO) << "Odd. node " << cuts[i].old_src << " didn't point to "
914 << cuts[i].new_vertex;
915 }
916 (*graph)[cuts[i].new_vertex].valid = false;
917 vector<Vertex::Index>::size_type new_topo_idx =
918 (*reverse_op_indexes)[cuts[i].new_vertex];
919 op_indexes->erase(op_indexes->begin() + new_topo_idx);
920 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
921 continue;
922 }
923 bool found_node = false;
924 for (vector<Vertex::Index>::size_type j = (*reverse_op_indexes)[node] + 1,
925 je = op_indexes->size(); j < je; ++j) {
926 Vertex::Index test_node = (*op_indexes)[j];
927 // See if this node has sufficient blocks
928 ExtentRanges ranges;
929 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
930 ranges.SubtractExtent(ExtentForRange(
931 kTempBlockStart, kSparseHole - kTempBlockStart));
932 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
933 // For now, for simplicity, subtract out all blocks in read-before
934 // dependencies.
935 for (Vertex::EdgeMap::const_iterator edge_i =
936 (*graph)[test_node].out_edges.begin(),
937 edge_e = (*graph)[test_node].out_edges.end();
938 edge_i != edge_e; ++edge_i) {
939 ranges.SubtractExtents(edge_i->second.extents);
940 }
Darin Petkov36a58222010-10-07 22:00:09 -0700941
Andrew de los Reyesef017552010-10-06 17:57:52 -0700942 uint64_t blocks_found = ranges.blocks();
943 if (blocks_found < blocks_needed) {
944 if (blocks_found > 0)
945 LOG(INFO) << "insufficient blocks found in topo node " << j
946 << " (node " << (*op_indexes)[j] << "). Found only "
947 << blocks_found;
948 continue;
949 }
950 found_node = true;
951 LOG(INFO) << "Found sufficient blocks in topo node " << j
952 << " (node " << (*op_indexes)[j] << ")";
953 // Sub in the blocks, and make the node supplying the blocks
954 // depend on old_dst.
955 vector<Extent> real_extents =
956 ranges.GetExtentsForBlockCount(blocks_needed);
Darin Petkov36a58222010-10-07 22:00:09 -0700957
Andrew de los Reyesef017552010-10-06 17:57:52 -0700958 // Fix the old dest node w/ the real blocks
959 SubstituteBlocks(&(*graph)[node],
960 cuts[i].tmp_extents,
961 real_extents);
Darin Petkov36a58222010-10-07 22:00:09 -0700962
Andrew de los Reyesef017552010-10-06 17:57:52 -0700963 // Fix the new node w/ the real blocks. Since the new node is just a
964 // copy operation, we can replace all the dest extents w/ the real
965 // blocks.
966 DeltaArchiveManifest_InstallOperation *op =
967 &(*graph)[cuts[i].new_vertex].op;
968 op->clear_dst_extents();
969 StoreExtents(real_extents, op->mutable_dst_extents());
Darin Petkov36a58222010-10-07 22:00:09 -0700970
Andrew de los Reyesef017552010-10-06 17:57:52 -0700971 // Add an edge from the real-block supplier to the old dest block.
972 graph_utils::AddReadBeforeDepExtents(&(*graph)[test_node],
973 node,
974 real_extents);
975 break;
976 }
977 if (!found_node) {
978 // convert to full op
979 LOG(WARNING) << "Failed to find enough temp blocks for cut " << i
980 << " with old dest (graph node " << node
981 << "). Converting to a full op, at the expense of a "
982 << "good compression ratio.";
983 TEST_AND_RETURN_FALSE(ConvertCutToFullOp(graph,
984 cuts[i],
985 new_root,
986 data_fd,
987 data_file_size));
988 // move the full op to the back
989 vector<Vertex::Index> new_op_indexes;
990 for (vector<Vertex::Index>::const_iterator iter_i = op_indexes->begin(),
991 iter_e = op_indexes->end(); iter_i != iter_e; ++iter_i) {
992 if ((*iter_i == cuts[i].old_dst) || (*iter_i == cuts[i].new_vertex))
993 continue;
994 new_op_indexes.push_back(*iter_i);
995 }
996 new_op_indexes.push_back(cuts[i].old_dst);
997 op_indexes->swap(new_op_indexes);
Darin Petkov36a58222010-10-07 22:00:09 -0700998
Andrew de los Reyesef017552010-10-06 17:57:52 -0700999 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
1000 }
1001 if (i == e) {
1002 // break out of for() loop
1003 break;
1004 }
1005 }
1006 return true;
1007}
1008
1009bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1010 size_t idx = 0;
1011 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1012 ++it, ++idx) {
1013 if (!it->valid)
1014 continue;
1015 const DeltaArchiveManifest_InstallOperation& op = it->op;
1016 if (TempBlocksExistInExtents(op.dst_extents()) ||
1017 TempBlocksExistInExtents(op.src_extents())) {
1018 LOG(INFO) << "bad extents in node " << idx;
1019 LOG(INFO) << "so yeah";
1020 return false;
1021 }
1022
1023 // Check out-edges:
1024 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
1025 je = it->out_edges.end(); jt != je; ++jt) {
1026 if (TempBlocksExistInExtents(jt->second.extents) ||
1027 TempBlocksExistInExtents(jt->second.write_extents)) {
1028 LOG(INFO) << "bad out edge in node " << idx;
1029 LOG(INFO) << "so yeah";
1030 return false;
1031 }
1032 }
1033 }
1034 return true;
1035}
1036
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001037bool DeltaDiffGenerator::ReorderDataBlobs(
1038 DeltaArchiveManifest* manifest,
1039 const std::string& data_blobs_path,
1040 const std::string& new_data_blobs_path) {
1041 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1042 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1043 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001044
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001045 DirectFileWriter writer;
1046 TEST_AND_RETURN_FALSE(
1047 writer.Open(new_data_blobs_path.c_str(),
1048 O_WRONLY | O_TRUNC | O_CREAT,
1049 0644) == 0);
1050 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001051 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001052
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001053 for (int i = 0; i < (manifest->install_operations_size() +
1054 manifest->kernel_install_operations_size()); i++) {
1055 DeltaArchiveManifest_InstallOperation* op = NULL;
1056 if (i < manifest->install_operations_size()) {
1057 op = manifest->mutable_install_operations(i);
1058 } else {
1059 op = manifest->mutable_kernel_install_operations(
1060 i - manifest->install_operations_size());
1061 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001062 if (!op->has_data_offset())
1063 continue;
1064 CHECK(op->has_data_length());
1065 vector<char> buf(op->data_length());
1066 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1067 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1068
1069 op->set_data_offset(out_file_size);
1070 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()) ==
1071 static_cast<ssize_t>(buf.size()));
1072 out_file_size += buf.size();
1073 }
1074 return true;
1075}
1076
Andrew de los Reyesef017552010-10-06 17:57:52 -07001077bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1078 const CutEdgeVertexes& cut,
1079 const string& new_root,
1080 int data_fd,
1081 off_t* data_file_size) {
1082 // Drop all incoming edges, keep all outgoing edges
Darin Petkov36a58222010-10-07 22:00:09 -07001083
Andrew de los Reyesef017552010-10-06 17:57:52 -07001084 // Keep all outgoing edges
1085 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1086 graph_utils::DropWriteBeforeDeps(&out_edges);
Darin Petkov36a58222010-10-07 22:00:09 -07001087
Andrew de los Reyesef017552010-10-06 17:57:52 -07001088 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1089 cut.old_dst,
1090 NULL,
1091 "/-!@:&*nonexistent_path",
1092 new_root,
1093 (*graph)[cut.old_dst].file_name,
1094 data_fd,
1095 data_file_size));
Darin Petkov36a58222010-10-07 22:00:09 -07001096
Andrew de los Reyesef017552010-10-06 17:57:52 -07001097 (*graph)[cut.old_dst].out_edges = out_edges;
1098
1099 // Right now we don't have doubly-linked edges, so we have to scan
1100 // the whole graph.
1101 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1102
1103 // Delete temp node
1104 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1105 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1106 (*graph)[cut.old_dst].out_edges.end());
1107 (*graph)[cut.new_vertex].valid = false;
1108 return true;
1109}
1110
1111bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1112 const string& new_root,
1113 int fd,
1114 off_t* data_file_size,
1115 vector<Vertex::Index>* final_order) {
1116 CycleBreaker cycle_breaker;
1117 LOG(INFO) << "Finding cycles...";
1118 set<Edge> cut_edges;
1119 cycle_breaker.BreakCycles(*graph, &cut_edges);
1120 LOG(INFO) << "done finding cycles";
1121 CheckGraph(*graph);
1122
1123 // Calculate number of scratch blocks needed
1124
1125 LOG(INFO) << "Cutting cycles...";
1126 vector<CutEdgeVertexes> cuts;
1127 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1128 LOG(INFO) << "done cutting cycles";
1129 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1130 CheckGraph(*graph);
1131
1132 LOG(INFO) << "Creating initial topological order...";
1133 TopologicalSort(*graph, final_order);
1134 LOG(INFO) << "done with initial topo order";
1135 CheckGraph(*graph);
1136
1137 LOG(INFO) << "Moving full ops to the back";
1138 MoveFullOpsToBack(graph, final_order);
1139 LOG(INFO) << "done moving full ops to back";
1140
1141 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1142 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1143
1144 if (!cuts.empty())
1145 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1146 new_root,
1147 fd,
1148 data_file_size,
1149 final_order,
1150 &inverse_final_order,
1151 cuts));
1152 LOG(INFO) << "Making sure all temp blocks have been allocated";
1153 graph_utils::DumpGraph(*graph);
1154 CHECK(NoTempBlocksRemain(*graph));
1155 LOG(INFO) << "done making sure all temp blocks are allocated";
1156 return true;
1157}
1158
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001159bool DeltaDiffGenerator::ReadFullUpdateFromDisk(
1160 Graph* graph,
1161 const std::string& new_kernel_part,
1162 const std::string& new_image,
1163 int fd,
1164 off_t* data_file_size,
1165 off_t chunk_size,
1166 vector<DeltaArchiveManifest_InstallOperation>* kernel_ops,
1167 std::vector<Vertex::Index>* final_order) {
1168 TEST_AND_RETURN_FALSE(chunk_size > 0);
1169 TEST_AND_RETURN_FALSE((chunk_size % kBlockSize) == 0);
Darin Petkov36a58222010-10-07 22:00:09 -07001170
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001171 // Get the sizes early in the function, so we can fail fast if the user
1172 // passed us bad paths.
1173 const off_t image_size = utils::FileSize(new_image);
1174 TEST_AND_RETURN_FALSE(image_size >= 0);
1175 const off_t kernel_size = utils::FileSize(new_kernel_part);
1176 TEST_AND_RETURN_FALSE(kernel_size >= 0);
1177
1178 off_t part_sizes[] = { image_size, kernel_size };
1179 string paths[] = { new_image, new_kernel_part };
1180
1181 for (int partition = 0; partition < 2; ++partition) {
1182 const string& path = paths[partition];
1183 LOG(INFO) << "compressing " << path;
1184
1185 int in_fd = open(path.c_str(), O_RDONLY, 0);
1186 TEST_AND_RETURN_FALSE(in_fd >= 0);
1187 ScopedFdCloser in_fd_closer(&in_fd);
1188
1189 for (off_t bytes_left = part_sizes[partition], counter = 0, offset = 0;
1190 bytes_left > 0;
1191 bytes_left -= chunk_size, ++counter, offset += chunk_size) {
1192 LOG(INFO) << "offset = " << offset;
1193 DeltaArchiveManifest_InstallOperation* op = NULL;
1194 if (partition == 0) {
1195 graph->resize(graph->size() + 1);
1196 graph->back().file_name = path + StringPrintf("-%" PRIi64, counter);
1197 op = &graph->back().op;
1198 final_order->push_back(graph->size() - 1);
1199 } else {
1200 kernel_ops->resize(kernel_ops->size() + 1);
1201 op = &kernel_ops->back();
1202 }
1203 LOG(INFO) << "have an op";
Darin Petkov36a58222010-10-07 22:00:09 -07001204
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001205 vector<char> buf(min(bytes_left, chunk_size));
1206 LOG(INFO) << "buf size: " << buf.size();
1207 ssize_t bytes_read = -1;
Darin Petkov36a58222010-10-07 22:00:09 -07001208
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001209 TEST_AND_RETURN_FALSE(utils::PReadAll(
1210 in_fd, &buf[0], buf.size(), offset, &bytes_read));
1211 TEST_AND_RETURN_FALSE(bytes_read == static_cast<ssize_t>(buf.size()));
Darin Petkov36a58222010-10-07 22:00:09 -07001212
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001213 vector<char> buf_compressed;
Darin Petkov36a58222010-10-07 22:00:09 -07001214
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001215 TEST_AND_RETURN_FALSE(BzipCompress(buf, &buf_compressed));
1216 const bool compress = buf_compressed.size() < buf.size();
1217 const vector<char>& use_buf = compress ? buf_compressed : buf;
1218 if (compress) {
1219 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1220 } else {
1221 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1222 }
1223 op->set_data_offset(*data_file_size);
1224 *data_file_size += use_buf.size();
1225 op->set_data_length(use_buf.size());
1226 Extent* dst_extent = op->add_dst_extents();
1227 dst_extent->set_start_block(offset / kBlockSize);
1228 dst_extent->set_num_blocks(chunk_size / kBlockSize);
1229 }
1230 }
1231
1232 return true;
1233}
1234
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001235bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1236 const string& old_root,
1237 const string& old_image,
1238 const string& new_root,
1239 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001240 const string& old_kernel_part,
1241 const string& new_kernel_part,
1242 const string& output_path,
1243 const string& private_key_path) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001244 struct stat old_image_stbuf;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001245 struct stat new_image_stbuf;
1246 TEST_AND_RETURN_FALSE_ERRNO(stat(new_image.c_str(), &new_image_stbuf) == 0);
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001247 if (!old_image.empty()) {
1248 TEST_AND_RETURN_FALSE_ERRNO(stat(old_image.c_str(), &old_image_stbuf) == 0);
1249 LOG_IF(WARNING, new_image_stbuf.st_size != old_image_stbuf.st_size)
1250 << "Old and new images are different sizes.";
1251 LOG_IF(FATAL, old_image_stbuf.st_size % kBlockSize)
1252 << "Old image not a multiple of block size " << kBlockSize;
1253 // Sanity check kernel partition arg
1254 TEST_AND_RETURN_FALSE(utils::FileSize(old_kernel_part) >= 0);
1255 } else {
1256 old_image_stbuf.st_size = 0;
1257 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001258 LOG_IF(FATAL, new_image_stbuf.st_size % kBlockSize)
1259 << "New image not a multiple of block size " << kBlockSize;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001260
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001261 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001262 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1263
Andrew de los Reyes3270f742010-07-15 22:28:14 -07001264 vector<Block> blocks(max(old_image_stbuf.st_size / kBlockSize,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001265 new_image_stbuf.st_size / kBlockSize));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001266 LOG(INFO) << "invalid: " << Vertex::kInvalidIndex;
1267 LOG(INFO) << "len: " << blocks.size();
1268 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1269 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1270 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1271 }
1272 Graph graph;
1273 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001274
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001275 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
1276 string temp_file_path;
1277 off_t data_file_size = 0;
1278
1279 LOG(INFO) << "Reading files...";
1280
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001281 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1282
Andrew de los Reyesef017552010-10-06 17:57:52 -07001283 vector<Vertex::Index> final_order;
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001284 if (!old_image.empty()) {
1285 // Delta update
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001286 int fd;
1287 TEST_AND_RETURN_FALSE(
1288 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
1289 TEST_AND_RETURN_FALSE(fd >= 0);
1290 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001291
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001292 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1293 &blocks,
1294 old_root,
1295 new_root,
1296 fd,
1297 &data_file_size));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001298 LOG(INFO) << "done reading normal files";
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001299 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001300
Andrew de los Reyesef017552010-10-06 17:57:52 -07001301 graph.resize(graph.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001302 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1303 fd,
1304 &data_file_size,
1305 new_image,
Andrew de los Reyesef017552010-10-06 17:57:52 -07001306 &graph.back()));
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001307
1308 // Read kernel partition
1309 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1310 new_kernel_part,
1311 &kernel_ops,
1312 fd,
1313 &data_file_size));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001314
1315 LOG(INFO) << "done reading kernel";
1316 CheckGraph(graph);
1317
1318 LOG(INFO) << "Creating edges...";
1319 CreateEdges(&graph, blocks);
1320 LOG(INFO) << "Done creating edges";
1321 CheckGraph(graph);
1322
1323 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1324 new_root,
1325 fd,
1326 &data_file_size,
1327 &final_order));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001328 } else {
1329 // Full update
1330 int fd = 0;
1331 TEST_AND_RETURN_FALSE(ReadFullUpdateFromDisk(&graph,
1332 new_kernel_part,
1333 new_image,
1334 fd,
1335 &data_file_size,
1336 kFullUpdateChunkSize,
1337 &kernel_ops,
1338 &final_order));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001339 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001340
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001341 // Convert to protobuf Manifest object
1342 DeltaArchiveManifest manifest;
1343 CheckGraph(graph);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001344 InstallOperationsToManifest(graph, final_order, kernel_ops, &manifest);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001345
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001346 CheckGraph(graph);
1347 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001348
1349 // Reorder the data blobs with the newly ordered manifest
1350 string ordered_blobs_path;
1351 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1352 "/tmp/CrAU_temp_data.ordered.XXXXXX",
1353 &ordered_blobs_path,
1354 false));
1355 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1356 temp_file_path,
1357 ordered_blobs_path));
1358
1359 // Check that install op blobs are in order and that all blocks are written.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001360 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001361 {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001362 vector<uint32_t> written_count(blocks.size(), 0);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001363 for (int i = 0; i < (manifest.install_operations_size() +
1364 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001365 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001366 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001367 manifest.mutable_install_operations(i) :
1368 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001369 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001370 for (int j = 0; j < op->dst_extents_size(); j++) {
1371 const Extent& extent = op->dst_extents(j);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001372 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001373 block < (extent.start_block() + extent.num_blocks()); block++) {
Darin Petkovc0b7a532010-09-29 15:18:14 -07001374 if (block < blocks.size())
1375 written_count[block]++;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001376 }
1377 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001378 if (op->has_data_offset()) {
1379 if (op->data_offset() != next_blob_offset) {
1380 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001381 << next_blob_offset;
1382 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001383 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001384 }
1385 }
1386 // check all blocks written to
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001387 for (vector<uint32_t>::size_type i = 0; i < written_count.size(); i++) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001388 if (written_count[i] == 0) {
1389 LOG(FATAL) << "block " << i << " not written!";
1390 }
1391 }
1392 }
1393
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001394 // Signatures appear at the end of the blobs. Note the offset in the
1395 // manifest
1396 if (!private_key_path.empty()) {
1397 LOG(INFO) << "Making room for signature in file";
1398 manifest.set_signatures_offset(next_blob_offset);
1399 LOG(INFO) << "set? " << manifest.has_signatures_offset();
1400 // Add a dummy op at the end to appease older clients
1401 DeltaArchiveManifest_InstallOperation* dummy_op =
1402 manifest.add_kernel_install_operations();
1403 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1404 dummy_op->set_data_offset(next_blob_offset);
1405 manifest.set_signatures_offset(next_blob_offset);
1406 uint64_t signature_blob_length = 0;
1407 TEST_AND_RETURN_FALSE(
1408 PayloadSigner::SignatureBlobLength(private_key_path,
1409 &signature_blob_length));
1410 dummy_op->set_data_length(signature_blob_length);
1411 manifest.set_signatures_size(signature_blob_length);
1412 Extent* dummy_extent = dummy_op->add_dst_extents();
1413 // Tell the dummy op to write this data to a big sparse hole
1414 dummy_extent->set_start_block(kSparseHole);
1415 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1416 kBlockSize);
1417 }
1418
Darin Petkov36a58222010-10-07 22:00:09 -07001419 TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1420 new_kernel_part,
1421 old_image,
1422 new_image,
1423 &manifest));
1424
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001425 // Serialize protobuf
1426 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001427
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001428 CheckGraph(graph);
1429 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1430 CheckGraph(graph);
1431
1432 LOG(INFO) << "Writing final delta file header...";
1433 DirectFileWriter writer;
1434 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1435 O_WRONLY | O_CREAT | O_TRUNC,
1436 0644) == 0);
1437 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001438
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001439 // Write header
1440 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)) ==
Andrew de los Reyes08c4e272010-04-15 14:02:17 -07001441 static_cast<ssize_t>(strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001442
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001443 // Write version number
1444 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001445
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001446 // Write protobuf length
1447 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1448 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001449
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001450 // Write protobuf
1451 LOG(INFO) << "Writing final delta file protobuf... "
1452 << serialized_manifest.size();
1453 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
1454 serialized_manifest.size()) ==
1455 static_cast<ssize_t>(serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001456
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001457 // Append the data blobs
1458 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001459 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001460 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1461 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1462 for (;;) {
1463 char buf[kBlockSize];
1464 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1465 if (0 == rc) {
1466 // EOF
1467 break;
1468 }
1469 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
1470 TEST_AND_RETURN_FALSE(writer.Write(buf, rc) == rc);
1471 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001472
1473 // Write signature blob.
1474 if (!private_key_path.empty()) {
1475 LOG(INFO) << "Signing the update...";
1476 vector<char> signature_blob;
1477 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(output_path,
1478 private_key_path,
1479 &signature_blob));
1480 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
1481 signature_blob.size()) ==
1482 static_cast<ssize_t>(signature_blob.size()));
1483 }
1484
Darin Petkov880335c2010-10-01 15:52:53 -07001485 ReportPayloadUsage(graph, manifest);
1486
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001487 LOG(INFO) << "All done. Successfully created delta file.";
1488 return true;
1489}
1490
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001491const char* const kBsdiffPath = "/usr/bin/bsdiff";
1492const char* const kBspatchPath = "/usr/bin/bspatch";
1493const char* const kDeltaMagic = "CrAU";
1494
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001495}; // namespace chromeos_update_engine