blob: 2e04e2a7fea11e81e081e1eb3c5c516c7964f2a1 [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) {
Darin Petkovabe7cc92010-10-08 12:29:32 -0700263 vertex->file_name = "<rootfs-non-file-data>";
264
Andrew de los Reyesef017552010-10-06 17:57:52 -0700265 DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700266 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
267 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
268 ScopedFdCloser image_fd_closer(&image_fd);
269
270 string temp_file_path;
271 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
272 &temp_file_path,
273 NULL));
274
275 FILE* file = fopen(temp_file_path.c_str(), "w");
276 TEST_AND_RETURN_FALSE(file);
277 int err = BZ_OK;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700278
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700279 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
280 file,
281 9, // max compression
282 0, // verbosity
283 0); // default work factor
284 TEST_AND_RETURN_FALSE(err == BZ_OK);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700285
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700286 vector<Extent> extents;
287 vector<Block>::size_type block_count = 0;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700288
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700289 LOG(INFO) << "Appending left over blocks to extents";
290 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
291 if (blocks[i].writer != Vertex::kInvalidIndex)
292 continue;
Andrew de los Reyesef017552010-10-06 17:57:52 -0700293 if (blocks[i].reader != Vertex::kInvalidIndex) {
294 graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
295 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700296 graph_utils::AppendBlockToExtents(&extents, i);
297 block_count++;
298 }
299
300 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
301 // so we arbitrarily set it to 1024 * kBlockSize.
302 vector<char> buf(1024 * kBlockSize);
303
304 LOG(INFO) << "Reading left over blocks";
305 vector<Block>::size_type blocks_copied_count = 0;
306
307 // For each extent in extents, write the data into BZ2_bzWrite which
308 // sends it to an output file.
309 // We use the temporary buffer 'buf' to hold the data, which may be
310 // smaller than the extent, so in that case we have to loop to get
311 // the extent's data (that's the inner while loop).
312 for (vector<Extent>::const_iterator it = extents.begin();
313 it != extents.end(); ++it) {
314 vector<Block>::size_type blocks_read = 0;
315 while (blocks_read < it->num_blocks()) {
316 const int copy_block_cnt =
317 min(buf.size() / kBlockSize,
318 static_cast<vector<char>::size_type>(
319 it->num_blocks() - blocks_read));
320 ssize_t rc = pread(image_fd,
321 &buf[0],
322 copy_block_cnt * kBlockSize,
323 (it->start_block() + blocks_read) * kBlockSize);
324 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
325 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
326 copy_block_cnt * kBlockSize);
327 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
328 TEST_AND_RETURN_FALSE(err == BZ_OK);
329 blocks_read += copy_block_cnt;
330 blocks_copied_count += copy_block_cnt;
331 LOG(INFO) << "progress: " << ((float)blocks_copied_count)/block_count;
332 }
333 }
334 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
335 TEST_AND_RETURN_FALSE(err == BZ_OK);
336 bz_file = NULL;
337 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
338 file = NULL;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700339
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700340 vector<char> compressed_data;
341 LOG(INFO) << "Reading compressed data off disk";
342 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
343 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700344
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700345 // Add node to graph to write these blocks
346 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
347 out_op->set_data_offset(*blobs_length);
348 out_op->set_data_length(compressed_data.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700349 LOG(INFO) << "Rootfs non-data blocks compressed take up "
350 << compressed_data.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700351 *blobs_length += compressed_data.size();
352 out_op->set_dst_length(kBlockSize * block_count);
353 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700354
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700355 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
356 &compressed_data[0],
357 compressed_data.size()));
358 LOG(INFO) << "done with extra blocks";
359 return true;
360}
361
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700362// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700363// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700364bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
365 uint64_t value_be = htobe64(value);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700366 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)) ==
367 sizeof(value_be));
368 return true;
369}
370
371// Adds each operation from the graph to the manifest in the order
372// specified by 'order'.
373void InstallOperationsToManifest(
374 const Graph& graph,
375 const vector<Vertex::Index>& order,
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700376 const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700377 DeltaArchiveManifest* out_manifest) {
378 for (vector<Vertex::Index>::const_iterator it = order.begin();
379 it != order.end(); ++it) {
380 DeltaArchiveManifest_InstallOperation* op =
381 out_manifest->add_install_operations();
382 *op = graph[*it].op;
383 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700384 for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
385 kernel_ops.begin(); it != kernel_ops.end(); ++it) {
386 DeltaArchiveManifest_InstallOperation* op =
387 out_manifest->add_kernel_install_operations();
388 *op = *it;
389 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700390}
391
392void CheckGraph(const Graph& graph) {
393 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
394 CHECK(it->op.has_type());
395 }
396}
397
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700398// Delta compresses a kernel partition new_kernel_part with knowledge of
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700399// the old kernel partition old_kernel_part.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700400bool DeltaCompressKernelPartition(
401 const string& old_kernel_part,
402 const string& new_kernel_part,
403 vector<DeltaArchiveManifest_InstallOperation>* ops,
404 int blobs_fd,
405 off_t* blobs_length) {
406 // For now, just bsdiff the kernel partition as a whole.
407 // TODO(adlr): Use knowledge of how the kernel partition is laid out
408 // to more efficiently compress it.
409
410 LOG(INFO) << "Delta compressing kernel partition...";
411
412 // Add a new install operation
413 ops->resize(1);
414 DeltaArchiveManifest_InstallOperation* op = &(*ops)[0];
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700415 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700416 op->set_data_offset(*blobs_length);
417
418 // Do the actual compression
419 vector<char> data;
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700420 TEST_AND_RETURN_FALSE(utils::ReadFile(new_kernel_part, &data));
421 TEST_AND_RETURN_FALSE(!data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700422
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700423 vector<char> data_bz;
424 TEST_AND_RETURN_FALSE(BzipCompress(data, &data_bz));
425 CHECK(!data_bz.empty());
426
427 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data_bz[0], data_bz.size()));
428 *blobs_length += data_bz.size();
429
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700430 off_t new_part_size = utils::FileSize(new_kernel_part);
431 TEST_AND_RETURN_FALSE(new_part_size >= 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700432
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700433 op->set_data_length(data_bz.size());
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700434
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700435 op->set_dst_length(new_part_size);
436
Andrew de los Reyes877ca8d2010-09-07 14:42:49 -0700437 // There's a single dest extent
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700438 Extent* dst_extent = op->add_dst_extents();
439 dst_extent->set_start_block(0);
440 dst_extent->set_num_blocks((new_part_size + kBlockSize - 1) / kBlockSize);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700441
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700442 LOG(INFO) << "Done compressing kernel partition.";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700443 return true;
444}
445
Darin Petkov880335c2010-10-01 15:52:53 -0700446struct DeltaObject {
447 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
448 : name(in_name),
449 type(in_type),
450 size(in_size) {}
451 bool operator <(const DeltaObject& object) const {
452 return size < object.size;
453 }
454 string name;
455 int type;
456 off_t size;
457};
458
459static const char* kInstallOperationTypes[] = {
460 "REPLACE",
461 "REPLACE_BZ",
462 "MOVE",
463 "BSDIFF"
464};
465
466void ReportPayloadUsage(const Graph& graph,
467 const DeltaArchiveManifest& manifest) {
468 vector<DeltaObject> objects;
469 off_t total_size = 0;
470
471 // Graph nodes with information about file names.
472 for (Vertex::Index node = 0; node < graph.size(); node++) {
Darin Petkovabe7cc92010-10-08 12:29:32 -0700473 const Vertex& vertex = graph[node];
474 if (!vertex.valid) {
475 continue;
476 }
477 objects.push_back(DeltaObject(vertex.file_name,
478 vertex.op.type(),
479 vertex.op.data_length()));
480 total_size += vertex.op.data_length();
Darin Petkov880335c2010-10-01 15:52:53 -0700481 }
482
Darin Petkov880335c2010-10-01 15:52:53 -0700483 // Kernel install operations.
484 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
485 const DeltaArchiveManifest_InstallOperation& op =
486 manifest.kernel_install_operations(i);
487 objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
488 op.type(),
489 op.data_length()));
490 total_size += op.data_length();
491 }
492
493 std::sort(objects.begin(), objects.end());
494
495 static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
496 for (vector<DeltaObject>::const_iterator it = objects.begin();
497 it != objects.end(); ++it) {
498 const DeltaObject& object = *it;
499 fprintf(stderr, kFormatString,
500 object.size * 100.0 / total_size,
501 object.size,
502 kInstallOperationTypes[object.type],
503 object.name.c_str());
504 }
505 fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
506}
507
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700508} // namespace {}
509
510bool DeltaDiffGenerator::ReadFileToDiff(
511 const string& old_filename,
512 const string& new_filename,
513 vector<char>* out_data,
514 DeltaArchiveManifest_InstallOperation* out_op) {
515 // Read new data in
516 vector<char> new_data;
517 TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700518
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700519 TEST_AND_RETURN_FALSE(!new_data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700520
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700521 vector<char> new_data_bz;
522 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
523 CHECK(!new_data_bz.empty());
524
525 vector<char> data; // Data blob that will be written to delta file.
526
527 DeltaArchiveManifest_InstallOperation operation;
528 size_t current_best_size = 0;
529 if (new_data.size() <= new_data_bz.size()) {
530 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
531 current_best_size = new_data.size();
532 data = new_data;
533 } else {
534 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
535 current_best_size = new_data_bz.size();
536 data = new_data_bz;
537 }
538
539 // Do we have an original file to consider?
540 struct stat old_stbuf;
541 if (0 != stat(old_filename.c_str(), &old_stbuf)) {
542 // If stat-ing the old file fails, it should be because it doesn't exist.
543 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
544 } else {
545 // Read old data
546 vector<char> old_data;
547 TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
548 if (old_data == new_data) {
549 // No change in data.
550 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
551 current_best_size = 0;
552 data.clear();
553 } else {
554 // Try bsdiff of old to new data
555 vector<char> bsdiff_delta;
556 TEST_AND_RETURN_FALSE(
557 BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
558 CHECK_GT(bsdiff_delta.size(), 0);
559 if (bsdiff_delta.size() < current_best_size) {
560 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
561 current_best_size = bsdiff_delta.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700562
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700563 data = bsdiff_delta;
564 }
565 }
566 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700567
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700568 // Set parameters of the operations
569 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700570
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700571 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
572 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
573 TEST_AND_RETURN_FALSE(
574 GatherExtents(old_filename, operation.mutable_src_extents()));
575 operation.set_src_length(old_stbuf.st_size);
576 }
577
578 TEST_AND_RETURN_FALSE(
579 GatherExtents(new_filename, operation.mutable_dst_extents()));
580 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700581
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700582 out_data->swap(data);
583 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700584
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700585 return true;
586}
587
Darin Petkov36a58222010-10-07 22:00:09 -0700588bool InitializePartitionInfo(const string& partition, PartitionInfo* info) {
589 const off_t size = utils::FileSize(partition);
590 TEST_AND_RETURN_FALSE(size >= 0);
591 info->set_size(size);
592 OmahaHashCalculator hasher;
593 TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, -1) == size);
594 TEST_AND_RETURN_FALSE(hasher.Finalize());
595 const vector<char>& hash = hasher.raw_hash();
596 info->set_hash(hash.data(), hash.size());
597 return true;
598}
599
600bool InitializePartitionInfos(const string& old_kernel,
601 const string& new_kernel,
602 const string& old_rootfs,
603 const string& new_rootfs,
604 DeltaArchiveManifest* manifest) {
605 if (!old_kernel.empty()) {
606 TEST_AND_RETURN_FALSE(
607 InitializePartitionInfo(old_kernel,
608 manifest->mutable_old_kernel_info()));
609 }
610 TEST_AND_RETURN_FALSE(
611 InitializePartitionInfo(new_kernel, manifest->mutable_new_kernel_info()));
612 if (!old_rootfs.empty()) {
613 TEST_AND_RETURN_FALSE(
614 InitializePartitionInfo(old_rootfs,
615 manifest->mutable_old_rootfs_info()));
616 }
617 TEST_AND_RETURN_FALSE(
618 InitializePartitionInfo(new_rootfs, manifest->mutable_new_rootfs_info()));
619 return true;
620}
621
Andrew de los Reyesef017552010-10-06 17:57:52 -0700622namespace {
623
624// Takes a collection (vector or RepeatedPtrField) of Extent and
625// returns a vector of the blocks referenced, in order.
626template<typename T>
627vector<uint64_t> ExpandExtents(const T& extents) {
628 vector<uint64_t> ret;
629 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
630 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700631 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700632 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700633 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700634 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700635 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700636 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700637 }
638 }
639 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700640 return ret;
641}
642
643// Takes a vector of blocks and returns an equivalent vector of Extent
644// objects.
645vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
646 vector<Extent> new_extents;
647 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
648 it != e; ++it) {
649 graph_utils::AppendBlockToExtents(&new_extents, *it);
650 }
651 return new_extents;
652}
653
654} // namespace {}
655
656void DeltaDiffGenerator::SubstituteBlocks(
657 Vertex* vertex,
658 const vector<Extent>& remove_extents,
659 const vector<Extent>& replace_extents) {
660 // First, expand out the blocks that op reads from
661 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700662 {
663 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700664 vector<uint64_t> remove_extents_expanded =
665 ExpandExtents(remove_extents);
666 vector<uint64_t> replace_extents_expanded =
667 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700668 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700669 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700670 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700671 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700672 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
673 }
674 utils::ApplyMap(&read_blocks, conversion);
675 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
676 e = vertex->out_edges.end(); it != e; ++it) {
677 vector<uint64_t> write_before_deps_expanded =
678 ExpandExtents(it->second.write_extents);
679 utils::ApplyMap(&write_before_deps_expanded, conversion);
680 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700681 }
682 }
683 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700684 vertex->op.clear_src_extents();
685 vector<Extent> new_extents = CompressExtents(read_blocks);
686 DeltaDiffGenerator::StoreExtents(new_extents,
687 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700688}
689
690bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700691 const set<Edge>& edges,
692 vector<CutEdgeVertexes>* out_cuts) {
693 DummyExtentAllocator scratch_allocator;
694 vector<CutEdgeVertexes> cuts;
695 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700696
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700697 uint64_t scratch_blocks_used = 0;
698 for (set<Edge>::const_iterator it = edges.begin();
699 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700700 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700701 vector<Extent> old_extents =
702 (*graph)[it->first].out_edges[it->second].extents;
703 // Choose some scratch space
704 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
705 LOG(INFO) << "using " << graph_utils::EdgeWeight(*graph, *it)
706 << " scratch blocks ("
707 << scratch_blocks_used << ")";
Andrew de los Reyesef017552010-10-06 17:57:52 -0700708 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700709 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
710 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700711 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700712 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700713 cuts.back().old_src = it->first;
714 cuts.back().old_dst = it->second;
Darin Petkov36a58222010-10-07 22:00:09 -0700715
Andrew de los Reyesef017552010-10-06 17:57:52 -0700716 EdgeProperties& cut_edge_properties =
717 (*graph)[it->first].out_edges.find(it->second)->second;
718
719 // This should never happen, as we should only be cutting edges between
720 // real file nodes, and write-before relationships are created from
721 // a real file node to a temp copy node:
722 CHECK(cut_edge_properties.write_extents.empty())
723 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700724
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700725 // make node depend on the copy operation
726 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700727 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700728
729 // Set src/dst extents and other proto variables for copy operation
730 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
731 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700732 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700733 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700734 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700735 graph->back().op.mutable_dst_extents());
736 graph->back().op.set_src_length(
737 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
738 graph->back().op.set_dst_length(graph->back().op.src_length());
739
740 // make the dest node read from the scratch space
741 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700742 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700743 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700744 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700745
746 // delete the old edge
747 CHECK_EQ(1, (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700748
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700749 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700750 EdgeProperties write_before_edge_properties;
751 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
752 (*graph)[it->second].out_edges.insert(
753 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700754 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700755 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700756 return true;
757}
758
759// Stores all Extents in 'extents' into 'out'.
760void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700761 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700762 google::protobuf::RepeatedPtrField<Extent>* out) {
763 for (vector<Extent>::const_iterator it = extents.begin();
764 it != extents.end(); ++it) {
765 Extent* new_extent = out->Add();
766 *new_extent = *it;
767 }
768}
769
770// Creates all the edges for the graph. Writers of a block point to
771// readers of the same block. This is because for an edge A->B, B
772// must complete before A executes.
773void DeltaDiffGenerator::CreateEdges(Graph* graph,
774 const vector<Block>& blocks) {
775 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
776 // Blocks with both a reader and writer get an edge
777 if (blocks[i].reader == Vertex::kInvalidIndex ||
778 blocks[i].writer == Vertex::kInvalidIndex)
779 continue;
780 // Don't have a node depend on itself
781 if (blocks[i].reader == blocks[i].writer)
782 continue;
783 // See if there's already an edge we can add onto
784 Vertex::EdgeMap::iterator edge_it =
785 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
786 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
787 // No existing edge. Create one
788 (*graph)[blocks[i].writer].out_edges.insert(
789 make_pair(blocks[i].reader, EdgeProperties()));
790 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700791 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700792 }
793 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
794 }
795}
796
Andrew de los Reyesef017552010-10-06 17:57:52 -0700797namespace {
798
799class SortCutsByTopoOrderLess {
800 public:
801 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
802 : table_(table) {}
803 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
804 return table_[a.old_dst] < table_[b.old_dst];
805 }
806 private:
807 vector<vector<Vertex::Index>::size_type>& table_;
808};
809
810} // namespace {}
811
812void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
813 vector<Vertex::Index>& op_indexes,
814 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
815 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
816 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
817 i != e; ++i) {
818 Vertex::Index node = op_indexes[i];
819 if (table.size() < (node + 1)) {
820 table.resize(node + 1);
821 }
822 table[node] = i;
823 }
824 reverse_op_indexes->swap(table);
825}
826
827void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
828 vector<CutEdgeVertexes>* cuts) {
829 // first, make a reverse lookup table.
830 vector<vector<Vertex::Index>::size_type> table;
831 GenerateReverseTopoOrderMap(op_indexes, &table);
832 SortCutsByTopoOrderLess less(table);
833 sort(cuts->begin(), cuts->end(), less);
834}
835
836void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
837 vector<Vertex::Index>* op_indexes) {
838 vector<Vertex::Index> ret;
839 vector<Vertex::Index> full_ops;
840 ret.reserve(op_indexes->size());
841 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
842 ++i) {
843 DeltaArchiveManifest_InstallOperation_Type type =
844 (*graph)[(*op_indexes)[i]].op.type();
845 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
846 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
847 full_ops.push_back((*op_indexes)[i]);
848 } else {
849 ret.push_back((*op_indexes)[i]);
850 }
851 }
852 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
853 << (full_ops.size() + ret.size()) << " total ops.";
854 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
855 op_indexes->swap(ret);
856}
857
858namespace {
859
860template<typename T>
861bool TempBlocksExistInExtents(const T& extents) {
862 for (int i = 0, e = extents.size(); i < e; ++i) {
863 Extent extent = graph_utils::GetElement(extents, i);
864 uint64_t start = extent.start_block();
865 uint64_t num = extent.num_blocks();
866 if (start == kSparseHole)
867 continue;
868 if (start >= kTempBlockStart ||
869 (start + num) >= kTempBlockStart) {
870 LOG(ERROR) << "temp block!";
871 LOG(ERROR) << "start: " << start << ", num: " << num;
872 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
873 LOG(ERROR) << "returning true";
874 return true;
875 }
876 // check for wrap-around, which would be a bug:
877 CHECK(start <= (start + num));
878 }
879 return false;
880}
881
882} // namespace {}
883
884bool DeltaDiffGenerator::AssignTempBlocks(
885 Graph* graph,
886 const string& new_root,
887 int data_fd,
888 off_t* data_file_size,
889 vector<Vertex::Index>* op_indexes,
890 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
891 vector<CutEdgeVertexes>& cuts) {
892 CHECK(!cuts.empty());
893 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
894 true ; --i) {
895 LOG(INFO) << "Fixing temp blocks in cut " << i
896 << ": old dst: " << cuts[i].old_dst << " new vertex: "
897 << cuts[i].new_vertex;
898 const uint64_t blocks_needed =
899 graph_utils::BlocksInExtents(cuts[i].tmp_extents);
900 LOG(INFO) << "Scanning for usable blocks (" << blocks_needed << " needed)";
901 // For now, just look for a single op w/ sufficient blocks, not
902 // considering blocks from outgoing read-before deps.
903 Vertex::Index node = cuts[i].old_dst;
904 DeltaArchiveManifest_InstallOperation_Type node_type =
905 (*graph)[node].op.type();
906 if (node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
907 node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
908 LOG(INFO) << "This was already converted to full, so skipping.";
909 // Delete the temp node and pointer to it from old src
910 if (!(*graph)[cuts[i].old_src].out_edges.erase(cuts[i].new_vertex)) {
911 LOG(INFO) << "Odd. node " << cuts[i].old_src << " didn't point to "
912 << cuts[i].new_vertex;
913 }
914 (*graph)[cuts[i].new_vertex].valid = false;
915 vector<Vertex::Index>::size_type new_topo_idx =
916 (*reverse_op_indexes)[cuts[i].new_vertex];
917 op_indexes->erase(op_indexes->begin() + new_topo_idx);
918 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
919 continue;
920 }
921 bool found_node = false;
922 for (vector<Vertex::Index>::size_type j = (*reverse_op_indexes)[node] + 1,
923 je = op_indexes->size(); j < je; ++j) {
924 Vertex::Index test_node = (*op_indexes)[j];
925 // See if this node has sufficient blocks
926 ExtentRanges ranges;
927 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
928 ranges.SubtractExtent(ExtentForRange(
929 kTempBlockStart, kSparseHole - kTempBlockStart));
930 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
931 // For now, for simplicity, subtract out all blocks in read-before
932 // dependencies.
933 for (Vertex::EdgeMap::const_iterator edge_i =
934 (*graph)[test_node].out_edges.begin(),
935 edge_e = (*graph)[test_node].out_edges.end();
936 edge_i != edge_e; ++edge_i) {
937 ranges.SubtractExtents(edge_i->second.extents);
938 }
Darin Petkov36a58222010-10-07 22:00:09 -0700939
Andrew de los Reyesef017552010-10-06 17:57:52 -0700940 uint64_t blocks_found = ranges.blocks();
941 if (blocks_found < blocks_needed) {
942 if (blocks_found > 0)
943 LOG(INFO) << "insufficient blocks found in topo node " << j
944 << " (node " << (*op_indexes)[j] << "). Found only "
945 << blocks_found;
946 continue;
947 }
948 found_node = true;
949 LOG(INFO) << "Found sufficient blocks in topo node " << j
950 << " (node " << (*op_indexes)[j] << ")";
951 // Sub in the blocks, and make the node supplying the blocks
952 // depend on old_dst.
953 vector<Extent> real_extents =
954 ranges.GetExtentsForBlockCount(blocks_needed);
Darin Petkov36a58222010-10-07 22:00:09 -0700955
Andrew de los Reyesef017552010-10-06 17:57:52 -0700956 // Fix the old dest node w/ the real blocks
957 SubstituteBlocks(&(*graph)[node],
958 cuts[i].tmp_extents,
959 real_extents);
Darin Petkov36a58222010-10-07 22:00:09 -0700960
Andrew de los Reyesef017552010-10-06 17:57:52 -0700961 // Fix the new node w/ the real blocks. Since the new node is just a
962 // copy operation, we can replace all the dest extents w/ the real
963 // blocks.
964 DeltaArchiveManifest_InstallOperation *op =
965 &(*graph)[cuts[i].new_vertex].op;
966 op->clear_dst_extents();
967 StoreExtents(real_extents, op->mutable_dst_extents());
Darin Petkov36a58222010-10-07 22:00:09 -0700968
Andrew de los Reyesef017552010-10-06 17:57:52 -0700969 // Add an edge from the real-block supplier to the old dest block.
970 graph_utils::AddReadBeforeDepExtents(&(*graph)[test_node],
971 node,
972 real_extents);
973 break;
974 }
975 if (!found_node) {
976 // convert to full op
977 LOG(WARNING) << "Failed to find enough temp blocks for cut " << i
978 << " with old dest (graph node " << node
979 << "). Converting to a full op, at the expense of a "
980 << "good compression ratio.";
981 TEST_AND_RETURN_FALSE(ConvertCutToFullOp(graph,
982 cuts[i],
983 new_root,
984 data_fd,
985 data_file_size));
986 // move the full op to the back
987 vector<Vertex::Index> new_op_indexes;
988 for (vector<Vertex::Index>::const_iterator iter_i = op_indexes->begin(),
989 iter_e = op_indexes->end(); iter_i != iter_e; ++iter_i) {
990 if ((*iter_i == cuts[i].old_dst) || (*iter_i == cuts[i].new_vertex))
991 continue;
992 new_op_indexes.push_back(*iter_i);
993 }
994 new_op_indexes.push_back(cuts[i].old_dst);
995 op_indexes->swap(new_op_indexes);
Darin Petkov36a58222010-10-07 22:00:09 -0700996
Andrew de los Reyesef017552010-10-06 17:57:52 -0700997 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
998 }
999 if (i == e) {
1000 // break out of for() loop
1001 break;
1002 }
1003 }
1004 return true;
1005}
1006
1007bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1008 size_t idx = 0;
1009 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1010 ++it, ++idx) {
1011 if (!it->valid)
1012 continue;
1013 const DeltaArchiveManifest_InstallOperation& op = it->op;
1014 if (TempBlocksExistInExtents(op.dst_extents()) ||
1015 TempBlocksExistInExtents(op.src_extents())) {
1016 LOG(INFO) << "bad extents in node " << idx;
1017 LOG(INFO) << "so yeah";
1018 return false;
1019 }
1020
1021 // Check out-edges:
1022 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
1023 je = it->out_edges.end(); jt != je; ++jt) {
1024 if (TempBlocksExistInExtents(jt->second.extents) ||
1025 TempBlocksExistInExtents(jt->second.write_extents)) {
1026 LOG(INFO) << "bad out edge in node " << idx;
1027 LOG(INFO) << "so yeah";
1028 return false;
1029 }
1030 }
1031 }
1032 return true;
1033}
1034
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001035bool DeltaDiffGenerator::ReorderDataBlobs(
1036 DeltaArchiveManifest* manifest,
1037 const std::string& data_blobs_path,
1038 const std::string& new_data_blobs_path) {
1039 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1040 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1041 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001042
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001043 DirectFileWriter writer;
1044 TEST_AND_RETURN_FALSE(
1045 writer.Open(new_data_blobs_path.c_str(),
1046 O_WRONLY | O_TRUNC | O_CREAT,
1047 0644) == 0);
1048 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001049 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001050
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001051 for (int i = 0; i < (manifest->install_operations_size() +
1052 manifest->kernel_install_operations_size()); i++) {
1053 DeltaArchiveManifest_InstallOperation* op = NULL;
1054 if (i < manifest->install_operations_size()) {
1055 op = manifest->mutable_install_operations(i);
1056 } else {
1057 op = manifest->mutable_kernel_install_operations(
1058 i - manifest->install_operations_size());
1059 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001060 if (!op->has_data_offset())
1061 continue;
1062 CHECK(op->has_data_length());
1063 vector<char> buf(op->data_length());
1064 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1065 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1066
1067 op->set_data_offset(out_file_size);
1068 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()) ==
1069 static_cast<ssize_t>(buf.size()));
1070 out_file_size += buf.size();
1071 }
1072 return true;
1073}
1074
Andrew de los Reyesef017552010-10-06 17:57:52 -07001075bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1076 const CutEdgeVertexes& cut,
1077 const string& new_root,
1078 int data_fd,
1079 off_t* data_file_size) {
1080 // Drop all incoming edges, keep all outgoing edges
Darin Petkov36a58222010-10-07 22:00:09 -07001081
Andrew de los Reyesef017552010-10-06 17:57:52 -07001082 // Keep all outgoing edges
1083 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1084 graph_utils::DropWriteBeforeDeps(&out_edges);
Darin Petkov36a58222010-10-07 22:00:09 -07001085
Andrew de los Reyesef017552010-10-06 17:57:52 -07001086 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1087 cut.old_dst,
1088 NULL,
1089 "/-!@:&*nonexistent_path",
1090 new_root,
1091 (*graph)[cut.old_dst].file_name,
1092 data_fd,
1093 data_file_size));
Darin Petkov36a58222010-10-07 22:00:09 -07001094
Andrew de los Reyesef017552010-10-06 17:57:52 -07001095 (*graph)[cut.old_dst].out_edges = out_edges;
1096
1097 // Right now we don't have doubly-linked edges, so we have to scan
1098 // the whole graph.
1099 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1100
1101 // Delete temp node
1102 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1103 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1104 (*graph)[cut.old_dst].out_edges.end());
1105 (*graph)[cut.new_vertex].valid = false;
1106 return true;
1107}
1108
1109bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1110 const string& new_root,
1111 int fd,
1112 off_t* data_file_size,
1113 vector<Vertex::Index>* final_order) {
1114 CycleBreaker cycle_breaker;
1115 LOG(INFO) << "Finding cycles...";
1116 set<Edge> cut_edges;
1117 cycle_breaker.BreakCycles(*graph, &cut_edges);
1118 LOG(INFO) << "done finding cycles";
1119 CheckGraph(*graph);
1120
1121 // Calculate number of scratch blocks needed
1122
1123 LOG(INFO) << "Cutting cycles...";
1124 vector<CutEdgeVertexes> cuts;
1125 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1126 LOG(INFO) << "done cutting cycles";
1127 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1128 CheckGraph(*graph);
1129
1130 LOG(INFO) << "Creating initial topological order...";
1131 TopologicalSort(*graph, final_order);
1132 LOG(INFO) << "done with initial topo order";
1133 CheckGraph(*graph);
1134
1135 LOG(INFO) << "Moving full ops to the back";
1136 MoveFullOpsToBack(graph, final_order);
1137 LOG(INFO) << "done moving full ops to back";
1138
1139 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1140 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1141
1142 if (!cuts.empty())
1143 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1144 new_root,
1145 fd,
1146 data_file_size,
1147 final_order,
1148 &inverse_final_order,
1149 cuts));
1150 LOG(INFO) << "Making sure all temp blocks have been allocated";
1151 graph_utils::DumpGraph(*graph);
1152 CHECK(NoTempBlocksRemain(*graph));
1153 LOG(INFO) << "done making sure all temp blocks are allocated";
1154 return true;
1155}
1156
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001157bool DeltaDiffGenerator::ReadFullUpdateFromDisk(
1158 Graph* graph,
1159 const std::string& new_kernel_part,
1160 const std::string& new_image,
1161 int fd,
1162 off_t* data_file_size,
1163 off_t chunk_size,
1164 vector<DeltaArchiveManifest_InstallOperation>* kernel_ops,
1165 std::vector<Vertex::Index>* final_order) {
1166 TEST_AND_RETURN_FALSE(chunk_size > 0);
1167 TEST_AND_RETURN_FALSE((chunk_size % kBlockSize) == 0);
Darin Petkov36a58222010-10-07 22:00:09 -07001168
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001169 // Get the sizes early in the function, so we can fail fast if the user
1170 // passed us bad paths.
1171 const off_t image_size = utils::FileSize(new_image);
1172 TEST_AND_RETURN_FALSE(image_size >= 0);
1173 const off_t kernel_size = utils::FileSize(new_kernel_part);
1174 TEST_AND_RETURN_FALSE(kernel_size >= 0);
1175
1176 off_t part_sizes[] = { image_size, kernel_size };
1177 string paths[] = { new_image, new_kernel_part };
1178
1179 for (int partition = 0; partition < 2; ++partition) {
1180 const string& path = paths[partition];
1181 LOG(INFO) << "compressing " << path;
1182
1183 int in_fd = open(path.c_str(), O_RDONLY, 0);
1184 TEST_AND_RETURN_FALSE(in_fd >= 0);
1185 ScopedFdCloser in_fd_closer(&in_fd);
1186
1187 for (off_t bytes_left = part_sizes[partition], counter = 0, offset = 0;
1188 bytes_left > 0;
1189 bytes_left -= chunk_size, ++counter, offset += chunk_size) {
1190 LOG(INFO) << "offset = " << offset;
1191 DeltaArchiveManifest_InstallOperation* op = NULL;
1192 if (partition == 0) {
1193 graph->resize(graph->size() + 1);
1194 graph->back().file_name = path + StringPrintf("-%" PRIi64, counter);
1195 op = &graph->back().op;
1196 final_order->push_back(graph->size() - 1);
1197 } else {
1198 kernel_ops->resize(kernel_ops->size() + 1);
1199 op = &kernel_ops->back();
1200 }
1201 LOG(INFO) << "have an op";
Darin Petkov36a58222010-10-07 22:00:09 -07001202
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001203 vector<char> buf(min(bytes_left, chunk_size));
1204 LOG(INFO) << "buf size: " << buf.size();
1205 ssize_t bytes_read = -1;
Darin Petkov36a58222010-10-07 22:00:09 -07001206
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001207 TEST_AND_RETURN_FALSE(utils::PReadAll(
1208 in_fd, &buf[0], buf.size(), offset, &bytes_read));
1209 TEST_AND_RETURN_FALSE(bytes_read == static_cast<ssize_t>(buf.size()));
Darin Petkov36a58222010-10-07 22:00:09 -07001210
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001211 vector<char> buf_compressed;
Darin Petkov36a58222010-10-07 22:00:09 -07001212
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001213 TEST_AND_RETURN_FALSE(BzipCompress(buf, &buf_compressed));
1214 const bool compress = buf_compressed.size() < buf.size();
1215 const vector<char>& use_buf = compress ? buf_compressed : buf;
1216 if (compress) {
1217 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1218 } else {
1219 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1220 }
1221 op->set_data_offset(*data_file_size);
1222 *data_file_size += use_buf.size();
1223 op->set_data_length(use_buf.size());
1224 Extent* dst_extent = op->add_dst_extents();
1225 dst_extent->set_start_block(offset / kBlockSize);
1226 dst_extent->set_num_blocks(chunk_size / kBlockSize);
1227 }
1228 }
1229
1230 return true;
1231}
1232
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001233bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1234 const string& old_root,
1235 const string& old_image,
1236 const string& new_root,
1237 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001238 const string& old_kernel_part,
1239 const string& new_kernel_part,
1240 const string& output_path,
1241 const string& private_key_path) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001242 struct stat old_image_stbuf;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001243 struct stat new_image_stbuf;
1244 TEST_AND_RETURN_FALSE_ERRNO(stat(new_image.c_str(), &new_image_stbuf) == 0);
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001245 if (!old_image.empty()) {
1246 TEST_AND_RETURN_FALSE_ERRNO(stat(old_image.c_str(), &old_image_stbuf) == 0);
1247 LOG_IF(WARNING, new_image_stbuf.st_size != old_image_stbuf.st_size)
1248 << "Old and new images are different sizes.";
1249 LOG_IF(FATAL, old_image_stbuf.st_size % kBlockSize)
1250 << "Old image not a multiple of block size " << kBlockSize;
1251 // Sanity check kernel partition arg
1252 TEST_AND_RETURN_FALSE(utils::FileSize(old_kernel_part) >= 0);
1253 } else {
1254 old_image_stbuf.st_size = 0;
1255 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001256 LOG_IF(FATAL, new_image_stbuf.st_size % kBlockSize)
1257 << "New image not a multiple of block size " << kBlockSize;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001258
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001259 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001260 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1261
Andrew de los Reyes3270f742010-07-15 22:28:14 -07001262 vector<Block> blocks(max(old_image_stbuf.st_size / kBlockSize,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001263 new_image_stbuf.st_size / kBlockSize));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001264 LOG(INFO) << "invalid: " << Vertex::kInvalidIndex;
1265 LOG(INFO) << "len: " << blocks.size();
1266 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1267 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1268 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1269 }
1270 Graph graph;
1271 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001272
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001273 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
1274 string temp_file_path;
1275 off_t data_file_size = 0;
1276
1277 LOG(INFO) << "Reading files...";
1278
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001279 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1280
Andrew de los Reyesef017552010-10-06 17:57:52 -07001281 vector<Vertex::Index> final_order;
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001282 if (!old_image.empty()) {
1283 // Delta update
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001284 int fd;
1285 TEST_AND_RETURN_FALSE(
1286 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
1287 TEST_AND_RETURN_FALSE(fd >= 0);
1288 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001289
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001290 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1291 &blocks,
1292 old_root,
1293 new_root,
1294 fd,
1295 &data_file_size));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001296 LOG(INFO) << "done reading normal files";
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001297 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001298
Andrew de los Reyesef017552010-10-06 17:57:52 -07001299 graph.resize(graph.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001300 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1301 fd,
1302 &data_file_size,
1303 new_image,
Andrew de los Reyesef017552010-10-06 17:57:52 -07001304 &graph.back()));
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001305
1306 // Read kernel partition
1307 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1308 new_kernel_part,
1309 &kernel_ops,
1310 fd,
1311 &data_file_size));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001312
1313 LOG(INFO) << "done reading kernel";
1314 CheckGraph(graph);
1315
1316 LOG(INFO) << "Creating edges...";
1317 CreateEdges(&graph, blocks);
1318 LOG(INFO) << "Done creating edges";
1319 CheckGraph(graph);
1320
1321 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1322 new_root,
1323 fd,
1324 &data_file_size,
1325 &final_order));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001326 } else {
1327 // Full update
1328 int fd = 0;
1329 TEST_AND_RETURN_FALSE(ReadFullUpdateFromDisk(&graph,
1330 new_kernel_part,
1331 new_image,
1332 fd,
1333 &data_file_size,
1334 kFullUpdateChunkSize,
1335 &kernel_ops,
1336 &final_order));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001337 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001338
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001339 // Convert to protobuf Manifest object
1340 DeltaArchiveManifest manifest;
1341 CheckGraph(graph);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001342 InstallOperationsToManifest(graph, final_order, kernel_ops, &manifest);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001343
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001344 CheckGraph(graph);
1345 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001346
1347 // Reorder the data blobs with the newly ordered manifest
1348 string ordered_blobs_path;
1349 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1350 "/tmp/CrAU_temp_data.ordered.XXXXXX",
1351 &ordered_blobs_path,
1352 false));
1353 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1354 temp_file_path,
1355 ordered_blobs_path));
1356
1357 // Check that install op blobs are in order and that all blocks are written.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001358 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001359 {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001360 vector<uint32_t> written_count(blocks.size(), 0);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001361 for (int i = 0; i < (manifest.install_operations_size() +
1362 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001363 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001364 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001365 manifest.mutable_install_operations(i) :
1366 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001367 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001368 for (int j = 0; j < op->dst_extents_size(); j++) {
1369 const Extent& extent = op->dst_extents(j);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001370 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001371 block < (extent.start_block() + extent.num_blocks()); block++) {
Darin Petkovc0b7a532010-09-29 15:18:14 -07001372 if (block < blocks.size())
1373 written_count[block]++;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001374 }
1375 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001376 if (op->has_data_offset()) {
1377 if (op->data_offset() != next_blob_offset) {
1378 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001379 << next_blob_offset;
1380 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001381 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001382 }
1383 }
1384 // check all blocks written to
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001385 for (vector<uint32_t>::size_type i = 0; i < written_count.size(); i++) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001386 if (written_count[i] == 0) {
1387 LOG(FATAL) << "block " << i << " not written!";
1388 }
1389 }
1390 }
1391
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001392 // Signatures appear at the end of the blobs. Note the offset in the
1393 // manifest
1394 if (!private_key_path.empty()) {
1395 LOG(INFO) << "Making room for signature in file";
1396 manifest.set_signatures_offset(next_blob_offset);
1397 LOG(INFO) << "set? " << manifest.has_signatures_offset();
1398 // Add a dummy op at the end to appease older clients
1399 DeltaArchiveManifest_InstallOperation* dummy_op =
1400 manifest.add_kernel_install_operations();
1401 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1402 dummy_op->set_data_offset(next_blob_offset);
1403 manifest.set_signatures_offset(next_blob_offset);
1404 uint64_t signature_blob_length = 0;
1405 TEST_AND_RETURN_FALSE(
1406 PayloadSigner::SignatureBlobLength(private_key_path,
1407 &signature_blob_length));
1408 dummy_op->set_data_length(signature_blob_length);
1409 manifest.set_signatures_size(signature_blob_length);
1410 Extent* dummy_extent = dummy_op->add_dst_extents();
1411 // Tell the dummy op to write this data to a big sparse hole
1412 dummy_extent->set_start_block(kSparseHole);
1413 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1414 kBlockSize);
1415 }
1416
Darin Petkov36a58222010-10-07 22:00:09 -07001417 TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1418 new_kernel_part,
1419 old_image,
1420 new_image,
1421 &manifest));
1422
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001423 // Serialize protobuf
1424 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001425
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001426 CheckGraph(graph);
1427 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1428 CheckGraph(graph);
1429
1430 LOG(INFO) << "Writing final delta file header...";
1431 DirectFileWriter writer;
1432 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1433 O_WRONLY | O_CREAT | O_TRUNC,
1434 0644) == 0);
1435 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001436
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001437 // Write header
1438 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)) ==
Andrew de los Reyes08c4e272010-04-15 14:02:17 -07001439 static_cast<ssize_t>(strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001440
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001441 // Write version number
1442 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001443
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001444 // Write protobuf length
1445 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1446 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001447
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001448 // Write protobuf
1449 LOG(INFO) << "Writing final delta file protobuf... "
1450 << serialized_manifest.size();
1451 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
1452 serialized_manifest.size()) ==
1453 static_cast<ssize_t>(serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001454
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001455 // Append the data blobs
1456 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001457 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001458 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1459 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1460 for (;;) {
1461 char buf[kBlockSize];
1462 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1463 if (0 == rc) {
1464 // EOF
1465 break;
1466 }
1467 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
1468 TEST_AND_RETURN_FALSE(writer.Write(buf, rc) == rc);
1469 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001470
1471 // Write signature blob.
1472 if (!private_key_path.empty()) {
1473 LOG(INFO) << "Signing the update...";
1474 vector<char> signature_blob;
1475 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(output_path,
1476 private_key_path,
1477 &signature_blob));
1478 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
1479 signature_blob.size()) ==
1480 static_cast<ssize_t>(signature_blob.size()));
1481 }
1482
Darin Petkov880335c2010-10-01 15:52:53 -07001483 ReportPayloadUsage(graph, manifest);
1484
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001485 LOG(INFO) << "All done. Successfully created delta file.";
1486 return true;
1487}
1488
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001489const char* const kBsdiffPath = "/usr/bin/bsdiff";
1490const char* const kBspatchPath = "/usr/bin/bspatch";
1491const char* const kDeltaMagic = "CrAU";
1492
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001493}; // namespace chromeos_update_engine