blob: 9659ad206834aae15cdc8ede66b6f232d25a17c0 [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,
Darin Petkov95cf01f2010-10-12 14:59:13 -0700467 const DeltaArchiveManifest& manifest,
468 const int64_t manifest_metadata_size) {
Darin Petkov880335c2010-10-01 15:52:53 -0700469 vector<DeltaObject> objects;
470 off_t total_size = 0;
471
472 // Graph nodes with information about file names.
473 for (Vertex::Index node = 0; node < graph.size(); node++) {
Darin Petkovabe7cc92010-10-08 12:29:32 -0700474 const Vertex& vertex = graph[node];
475 if (!vertex.valid) {
476 continue;
477 }
478 objects.push_back(DeltaObject(vertex.file_name,
479 vertex.op.type(),
480 vertex.op.data_length()));
481 total_size += vertex.op.data_length();
Darin Petkov880335c2010-10-01 15:52:53 -0700482 }
483
Darin Petkov880335c2010-10-01 15:52:53 -0700484 // Kernel install operations.
485 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
486 const DeltaArchiveManifest_InstallOperation& op =
487 manifest.kernel_install_operations(i);
488 objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
489 op.type(),
490 op.data_length()));
491 total_size += op.data_length();
492 }
493
Darin Petkov95cf01f2010-10-12 14:59:13 -0700494 objects.push_back(DeltaObject("<manifest-metadata>",
495 -1,
496 manifest_metadata_size));
497 total_size += manifest_metadata_size;
498
Darin Petkov880335c2010-10-01 15:52:53 -0700499 std::sort(objects.begin(), objects.end());
500
501 static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
502 for (vector<DeltaObject>::const_iterator it = objects.begin();
503 it != objects.end(); ++it) {
504 const DeltaObject& object = *it;
505 fprintf(stderr, kFormatString,
506 object.size * 100.0 / total_size,
507 object.size,
Darin Petkov95cf01f2010-10-12 14:59:13 -0700508 object.type >= 0 ? kInstallOperationTypes[object.type] : "-",
Darin Petkov880335c2010-10-01 15:52:53 -0700509 object.name.c_str());
510 }
511 fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
512}
513
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700514} // namespace {}
515
516bool DeltaDiffGenerator::ReadFileToDiff(
517 const string& old_filename,
518 const string& new_filename,
519 vector<char>* out_data,
520 DeltaArchiveManifest_InstallOperation* out_op) {
521 // Read new data in
522 vector<char> new_data;
523 TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700524
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700525 TEST_AND_RETURN_FALSE(!new_data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700526
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700527 vector<char> new_data_bz;
528 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
529 CHECK(!new_data_bz.empty());
530
531 vector<char> data; // Data blob that will be written to delta file.
532
533 DeltaArchiveManifest_InstallOperation operation;
534 size_t current_best_size = 0;
535 if (new_data.size() <= new_data_bz.size()) {
536 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
537 current_best_size = new_data.size();
538 data = new_data;
539 } else {
540 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
541 current_best_size = new_data_bz.size();
542 data = new_data_bz;
543 }
544
545 // Do we have an original file to consider?
546 struct stat old_stbuf;
547 if (0 != stat(old_filename.c_str(), &old_stbuf)) {
548 // If stat-ing the old file fails, it should be because it doesn't exist.
549 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
550 } else {
551 // Read old data
552 vector<char> old_data;
553 TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
554 if (old_data == new_data) {
555 // No change in data.
556 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
557 current_best_size = 0;
558 data.clear();
559 } else {
560 // Try bsdiff of old to new data
561 vector<char> bsdiff_delta;
562 TEST_AND_RETURN_FALSE(
563 BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
564 CHECK_GT(bsdiff_delta.size(), 0);
565 if (bsdiff_delta.size() < current_best_size) {
566 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
567 current_best_size = bsdiff_delta.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700568
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700569 data = bsdiff_delta;
570 }
571 }
572 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700573
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700574 // Set parameters of the operations
575 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700576
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700577 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
578 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
579 TEST_AND_RETURN_FALSE(
580 GatherExtents(old_filename, operation.mutable_src_extents()));
581 operation.set_src_length(old_stbuf.st_size);
582 }
583
584 TEST_AND_RETURN_FALSE(
585 GatherExtents(new_filename, operation.mutable_dst_extents()));
586 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700587
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700588 out_data->swap(data);
589 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700590
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700591 return true;
592}
593
Darin Petkov7ea32332010-10-13 10:46:11 -0700594bool InitializePartitionInfo(bool is_kernel,
595 const string& partition,
596 PartitionInfo* info) {
597 int64_t size = 0;
598 if (is_kernel) {
599 size = utils::FileSize(partition);
600 } else {
601 int block_count = 0, block_size = 0;
602 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(partition,
603 &block_count,
604 &block_size));
605 size = static_cast<int64_t>(block_count) * block_size;
606 }
607 TEST_AND_RETURN_FALSE(size > 0);
Darin Petkov36a58222010-10-07 22:00:09 -0700608 info->set_size(size);
609 OmahaHashCalculator hasher;
Darin Petkov7ea32332010-10-13 10:46:11 -0700610 TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, size) == size);
Darin Petkov36a58222010-10-07 22:00:09 -0700611 TEST_AND_RETURN_FALSE(hasher.Finalize());
612 const vector<char>& hash = hasher.raw_hash();
613 info->set_hash(hash.data(), hash.size());
614 return true;
615}
616
617bool InitializePartitionInfos(const string& old_kernel,
618 const string& new_kernel,
619 const string& old_rootfs,
620 const string& new_rootfs,
621 DeltaArchiveManifest* manifest) {
622 if (!old_kernel.empty()) {
623 TEST_AND_RETURN_FALSE(
Darin Petkov7ea32332010-10-13 10:46:11 -0700624 InitializePartitionInfo(true,
625 old_kernel,
Darin Petkov36a58222010-10-07 22:00:09 -0700626 manifest->mutable_old_kernel_info()));
627 }
628 TEST_AND_RETURN_FALSE(
Darin Petkov7ea32332010-10-13 10:46:11 -0700629 InitializePartitionInfo(true,
630 new_kernel,
631 manifest->mutable_new_kernel_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700632 if (!old_rootfs.empty()) {
633 TEST_AND_RETURN_FALSE(
Darin Petkov7ea32332010-10-13 10:46:11 -0700634 InitializePartitionInfo(false,
635 old_rootfs,
Darin Petkov36a58222010-10-07 22:00:09 -0700636 manifest->mutable_old_rootfs_info()));
637 }
638 TEST_AND_RETURN_FALSE(
Darin Petkov7ea32332010-10-13 10:46:11 -0700639 InitializePartitionInfo(false,
640 new_rootfs,
641 manifest->mutable_new_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700642 return true;
643}
644
Andrew de los Reyesef017552010-10-06 17:57:52 -0700645namespace {
646
647// Takes a collection (vector or RepeatedPtrField) of Extent and
648// returns a vector of the blocks referenced, in order.
649template<typename T>
650vector<uint64_t> ExpandExtents(const T& extents) {
651 vector<uint64_t> ret;
652 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
653 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700654 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700655 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700656 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700657 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700658 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700659 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700660 }
661 }
662 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700663 return ret;
664}
665
666// Takes a vector of blocks and returns an equivalent vector of Extent
667// objects.
668vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
669 vector<Extent> new_extents;
670 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
671 it != e; ++it) {
672 graph_utils::AppendBlockToExtents(&new_extents, *it);
673 }
674 return new_extents;
675}
676
677} // namespace {}
678
679void DeltaDiffGenerator::SubstituteBlocks(
680 Vertex* vertex,
681 const vector<Extent>& remove_extents,
682 const vector<Extent>& replace_extents) {
683 // First, expand out the blocks that op reads from
684 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700685 {
686 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700687 vector<uint64_t> remove_extents_expanded =
688 ExpandExtents(remove_extents);
689 vector<uint64_t> replace_extents_expanded =
690 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700691 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700692 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700693 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700694 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700695 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
696 }
697 utils::ApplyMap(&read_blocks, conversion);
698 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
699 e = vertex->out_edges.end(); it != e; ++it) {
700 vector<uint64_t> write_before_deps_expanded =
701 ExpandExtents(it->second.write_extents);
702 utils::ApplyMap(&write_before_deps_expanded, conversion);
703 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700704 }
705 }
706 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700707 vertex->op.clear_src_extents();
708 vector<Extent> new_extents = CompressExtents(read_blocks);
709 DeltaDiffGenerator::StoreExtents(new_extents,
710 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700711}
712
713bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700714 const set<Edge>& edges,
715 vector<CutEdgeVertexes>* out_cuts) {
716 DummyExtentAllocator scratch_allocator;
717 vector<CutEdgeVertexes> cuts;
718 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700719
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700720 uint64_t scratch_blocks_used = 0;
721 for (set<Edge>::const_iterator it = edges.begin();
722 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700723 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700724 vector<Extent> old_extents =
725 (*graph)[it->first].out_edges[it->second].extents;
726 // Choose some scratch space
727 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
728 LOG(INFO) << "using " << graph_utils::EdgeWeight(*graph, *it)
729 << " scratch blocks ("
730 << scratch_blocks_used << ")";
Andrew de los Reyesef017552010-10-06 17:57:52 -0700731 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700732 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
733 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700734 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700735 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700736 cuts.back().old_src = it->first;
737 cuts.back().old_dst = it->second;
Darin Petkov36a58222010-10-07 22:00:09 -0700738
Andrew de los Reyesef017552010-10-06 17:57:52 -0700739 EdgeProperties& cut_edge_properties =
740 (*graph)[it->first].out_edges.find(it->second)->second;
741
742 // This should never happen, as we should only be cutting edges between
743 // real file nodes, and write-before relationships are created from
744 // a real file node to a temp copy node:
745 CHECK(cut_edge_properties.write_extents.empty())
746 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700747
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700748 // make node depend on the copy operation
749 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700750 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700751
752 // Set src/dst extents and other proto variables for copy operation
753 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
754 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700755 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700756 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700757 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700758 graph->back().op.mutable_dst_extents());
759 graph->back().op.set_src_length(
760 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
761 graph->back().op.set_dst_length(graph->back().op.src_length());
762
763 // make the dest node read from the scratch space
764 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700765 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700766 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700767 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700768
769 // delete the old edge
770 CHECK_EQ(1, (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700771
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700772 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700773 EdgeProperties write_before_edge_properties;
774 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
775 (*graph)[it->second].out_edges.insert(
776 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700777 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700778 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700779 return true;
780}
781
782// Stores all Extents in 'extents' into 'out'.
783void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700784 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700785 google::protobuf::RepeatedPtrField<Extent>* out) {
786 for (vector<Extent>::const_iterator it = extents.begin();
787 it != extents.end(); ++it) {
788 Extent* new_extent = out->Add();
789 *new_extent = *it;
790 }
791}
792
793// Creates all the edges for the graph. Writers of a block point to
794// readers of the same block. This is because for an edge A->B, B
795// must complete before A executes.
796void DeltaDiffGenerator::CreateEdges(Graph* graph,
797 const vector<Block>& blocks) {
798 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
799 // Blocks with both a reader and writer get an edge
800 if (blocks[i].reader == Vertex::kInvalidIndex ||
801 blocks[i].writer == Vertex::kInvalidIndex)
802 continue;
803 // Don't have a node depend on itself
804 if (blocks[i].reader == blocks[i].writer)
805 continue;
806 // See if there's already an edge we can add onto
807 Vertex::EdgeMap::iterator edge_it =
808 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
809 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
810 // No existing edge. Create one
811 (*graph)[blocks[i].writer].out_edges.insert(
812 make_pair(blocks[i].reader, EdgeProperties()));
813 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700814 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700815 }
816 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
817 }
818}
819
Andrew de los Reyesef017552010-10-06 17:57:52 -0700820namespace {
821
822class SortCutsByTopoOrderLess {
823 public:
824 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
825 : table_(table) {}
826 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
827 return table_[a.old_dst] < table_[b.old_dst];
828 }
829 private:
830 vector<vector<Vertex::Index>::size_type>& table_;
831};
832
833} // namespace {}
834
835void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
836 vector<Vertex::Index>& op_indexes,
837 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
838 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
839 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
840 i != e; ++i) {
841 Vertex::Index node = op_indexes[i];
842 if (table.size() < (node + 1)) {
843 table.resize(node + 1);
844 }
845 table[node] = i;
846 }
847 reverse_op_indexes->swap(table);
848}
849
850void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
851 vector<CutEdgeVertexes>* cuts) {
852 // first, make a reverse lookup table.
853 vector<vector<Vertex::Index>::size_type> table;
854 GenerateReverseTopoOrderMap(op_indexes, &table);
855 SortCutsByTopoOrderLess less(table);
856 sort(cuts->begin(), cuts->end(), less);
857}
858
859void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
860 vector<Vertex::Index>* op_indexes) {
861 vector<Vertex::Index> ret;
862 vector<Vertex::Index> full_ops;
863 ret.reserve(op_indexes->size());
864 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
865 ++i) {
866 DeltaArchiveManifest_InstallOperation_Type type =
867 (*graph)[(*op_indexes)[i]].op.type();
868 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
869 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
870 full_ops.push_back((*op_indexes)[i]);
871 } else {
872 ret.push_back((*op_indexes)[i]);
873 }
874 }
875 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
876 << (full_ops.size() + ret.size()) << " total ops.";
877 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
878 op_indexes->swap(ret);
879}
880
881namespace {
882
883template<typename T>
884bool TempBlocksExistInExtents(const T& extents) {
885 for (int i = 0, e = extents.size(); i < e; ++i) {
886 Extent extent = graph_utils::GetElement(extents, i);
887 uint64_t start = extent.start_block();
888 uint64_t num = extent.num_blocks();
889 if (start == kSparseHole)
890 continue;
891 if (start >= kTempBlockStart ||
892 (start + num) >= kTempBlockStart) {
893 LOG(ERROR) << "temp block!";
894 LOG(ERROR) << "start: " << start << ", num: " << num;
895 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
896 LOG(ERROR) << "returning true";
897 return true;
898 }
899 // check for wrap-around, which would be a bug:
900 CHECK(start <= (start + num));
901 }
902 return false;
903}
904
905} // namespace {}
906
907bool DeltaDiffGenerator::AssignTempBlocks(
908 Graph* graph,
909 const string& new_root,
910 int data_fd,
911 off_t* data_file_size,
912 vector<Vertex::Index>* op_indexes,
913 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
914 vector<CutEdgeVertexes>& cuts) {
915 CHECK(!cuts.empty());
916 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
917 true ; --i) {
918 LOG(INFO) << "Fixing temp blocks in cut " << i
919 << ": old dst: " << cuts[i].old_dst << " new vertex: "
920 << cuts[i].new_vertex;
921 const uint64_t blocks_needed =
922 graph_utils::BlocksInExtents(cuts[i].tmp_extents);
923 LOG(INFO) << "Scanning for usable blocks (" << blocks_needed << " needed)";
924 // For now, just look for a single op w/ sufficient blocks, not
925 // considering blocks from outgoing read-before deps.
926 Vertex::Index node = cuts[i].old_dst;
927 DeltaArchiveManifest_InstallOperation_Type node_type =
928 (*graph)[node].op.type();
929 if (node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
930 node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
931 LOG(INFO) << "This was already converted to full, so skipping.";
932 // Delete the temp node and pointer to it from old src
933 if (!(*graph)[cuts[i].old_src].out_edges.erase(cuts[i].new_vertex)) {
934 LOG(INFO) << "Odd. node " << cuts[i].old_src << " didn't point to "
935 << cuts[i].new_vertex;
936 }
937 (*graph)[cuts[i].new_vertex].valid = false;
938 vector<Vertex::Index>::size_type new_topo_idx =
939 (*reverse_op_indexes)[cuts[i].new_vertex];
940 op_indexes->erase(op_indexes->begin() + new_topo_idx);
941 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
942 continue;
943 }
944 bool found_node = false;
945 for (vector<Vertex::Index>::size_type j = (*reverse_op_indexes)[node] + 1,
946 je = op_indexes->size(); j < je; ++j) {
947 Vertex::Index test_node = (*op_indexes)[j];
948 // See if this node has sufficient blocks
949 ExtentRanges ranges;
950 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
951 ranges.SubtractExtent(ExtentForRange(
952 kTempBlockStart, kSparseHole - kTempBlockStart));
953 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
954 // For now, for simplicity, subtract out all blocks in read-before
955 // dependencies.
956 for (Vertex::EdgeMap::const_iterator edge_i =
957 (*graph)[test_node].out_edges.begin(),
958 edge_e = (*graph)[test_node].out_edges.end();
959 edge_i != edge_e; ++edge_i) {
960 ranges.SubtractExtents(edge_i->second.extents);
961 }
Darin Petkov36a58222010-10-07 22:00:09 -0700962
Andrew de los Reyesef017552010-10-06 17:57:52 -0700963 uint64_t blocks_found = ranges.blocks();
964 if (blocks_found < blocks_needed) {
965 if (blocks_found > 0)
966 LOG(INFO) << "insufficient blocks found in topo node " << j
967 << " (node " << (*op_indexes)[j] << "). Found only "
968 << blocks_found;
969 continue;
970 }
971 found_node = true;
972 LOG(INFO) << "Found sufficient blocks in topo node " << j
973 << " (node " << (*op_indexes)[j] << ")";
974 // Sub in the blocks, and make the node supplying the blocks
975 // depend on old_dst.
976 vector<Extent> real_extents =
977 ranges.GetExtentsForBlockCount(blocks_needed);
Darin Petkov36a58222010-10-07 22:00:09 -0700978
Andrew de los Reyesef017552010-10-06 17:57:52 -0700979 // Fix the old dest node w/ the real blocks
980 SubstituteBlocks(&(*graph)[node],
981 cuts[i].tmp_extents,
982 real_extents);
Darin Petkov36a58222010-10-07 22:00:09 -0700983
Andrew de los Reyesef017552010-10-06 17:57:52 -0700984 // Fix the new node w/ the real blocks. Since the new node is just a
985 // copy operation, we can replace all the dest extents w/ the real
986 // blocks.
987 DeltaArchiveManifest_InstallOperation *op =
988 &(*graph)[cuts[i].new_vertex].op;
989 op->clear_dst_extents();
990 StoreExtents(real_extents, op->mutable_dst_extents());
Darin Petkov36a58222010-10-07 22:00:09 -0700991
Andrew de los Reyesef017552010-10-06 17:57:52 -0700992 // Add an edge from the real-block supplier to the old dest block.
993 graph_utils::AddReadBeforeDepExtents(&(*graph)[test_node],
994 node,
995 real_extents);
996 break;
997 }
998 if (!found_node) {
999 // convert to full op
1000 LOG(WARNING) << "Failed to find enough temp blocks for cut " << i
1001 << " with old dest (graph node " << node
1002 << "). Converting to a full op, at the expense of a "
1003 << "good compression ratio.";
1004 TEST_AND_RETURN_FALSE(ConvertCutToFullOp(graph,
1005 cuts[i],
1006 new_root,
1007 data_fd,
1008 data_file_size));
1009 // move the full op to the back
1010 vector<Vertex::Index> new_op_indexes;
1011 for (vector<Vertex::Index>::const_iterator iter_i = op_indexes->begin(),
1012 iter_e = op_indexes->end(); iter_i != iter_e; ++iter_i) {
1013 if ((*iter_i == cuts[i].old_dst) || (*iter_i == cuts[i].new_vertex))
1014 continue;
1015 new_op_indexes.push_back(*iter_i);
1016 }
1017 new_op_indexes.push_back(cuts[i].old_dst);
1018 op_indexes->swap(new_op_indexes);
Darin Petkov36a58222010-10-07 22:00:09 -07001019
Andrew de los Reyesef017552010-10-06 17:57:52 -07001020 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
1021 }
1022 if (i == e) {
1023 // break out of for() loop
1024 break;
1025 }
1026 }
1027 return true;
1028}
1029
1030bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1031 size_t idx = 0;
1032 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1033 ++it, ++idx) {
1034 if (!it->valid)
1035 continue;
1036 const DeltaArchiveManifest_InstallOperation& op = it->op;
1037 if (TempBlocksExistInExtents(op.dst_extents()) ||
1038 TempBlocksExistInExtents(op.src_extents())) {
1039 LOG(INFO) << "bad extents in node " << idx;
1040 LOG(INFO) << "so yeah";
1041 return false;
1042 }
1043
1044 // Check out-edges:
1045 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
1046 je = it->out_edges.end(); jt != je; ++jt) {
1047 if (TempBlocksExistInExtents(jt->second.extents) ||
1048 TempBlocksExistInExtents(jt->second.write_extents)) {
1049 LOG(INFO) << "bad out edge in node " << idx;
1050 LOG(INFO) << "so yeah";
1051 return false;
1052 }
1053 }
1054 }
1055 return true;
1056}
1057
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001058bool DeltaDiffGenerator::ReorderDataBlobs(
1059 DeltaArchiveManifest* manifest,
1060 const std::string& data_blobs_path,
1061 const std::string& new_data_blobs_path) {
1062 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1063 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1064 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001065
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001066 DirectFileWriter writer;
1067 TEST_AND_RETURN_FALSE(
1068 writer.Open(new_data_blobs_path.c_str(),
1069 O_WRONLY | O_TRUNC | O_CREAT,
1070 0644) == 0);
1071 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001072 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001073
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001074 for (int i = 0; i < (manifest->install_operations_size() +
1075 manifest->kernel_install_operations_size()); i++) {
1076 DeltaArchiveManifest_InstallOperation* op = NULL;
1077 if (i < manifest->install_operations_size()) {
1078 op = manifest->mutable_install_operations(i);
1079 } else {
1080 op = manifest->mutable_kernel_install_operations(
1081 i - manifest->install_operations_size());
1082 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001083 if (!op->has_data_offset())
1084 continue;
1085 CHECK(op->has_data_length());
1086 vector<char> buf(op->data_length());
1087 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1088 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1089
1090 op->set_data_offset(out_file_size);
1091 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()) ==
1092 static_cast<ssize_t>(buf.size()));
1093 out_file_size += buf.size();
1094 }
1095 return true;
1096}
1097
Andrew de los Reyesef017552010-10-06 17:57:52 -07001098bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1099 const CutEdgeVertexes& cut,
1100 const string& new_root,
1101 int data_fd,
1102 off_t* data_file_size) {
1103 // Drop all incoming edges, keep all outgoing edges
Darin Petkov36a58222010-10-07 22:00:09 -07001104
Andrew de los Reyesef017552010-10-06 17:57:52 -07001105 // Keep all outgoing edges
1106 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1107 graph_utils::DropWriteBeforeDeps(&out_edges);
Darin Petkov36a58222010-10-07 22:00:09 -07001108
Andrew de los Reyesef017552010-10-06 17:57:52 -07001109 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1110 cut.old_dst,
1111 NULL,
1112 "/-!@:&*nonexistent_path",
1113 new_root,
1114 (*graph)[cut.old_dst].file_name,
1115 data_fd,
1116 data_file_size));
Darin Petkov36a58222010-10-07 22:00:09 -07001117
Andrew de los Reyesef017552010-10-06 17:57:52 -07001118 (*graph)[cut.old_dst].out_edges = out_edges;
1119
1120 // Right now we don't have doubly-linked edges, so we have to scan
1121 // the whole graph.
1122 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1123
1124 // Delete temp node
1125 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1126 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1127 (*graph)[cut.old_dst].out_edges.end());
1128 (*graph)[cut.new_vertex].valid = false;
1129 return true;
1130}
1131
1132bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1133 const string& new_root,
1134 int fd,
1135 off_t* data_file_size,
1136 vector<Vertex::Index>* final_order) {
1137 CycleBreaker cycle_breaker;
1138 LOG(INFO) << "Finding cycles...";
1139 set<Edge> cut_edges;
1140 cycle_breaker.BreakCycles(*graph, &cut_edges);
1141 LOG(INFO) << "done finding cycles";
1142 CheckGraph(*graph);
1143
1144 // Calculate number of scratch blocks needed
1145
1146 LOG(INFO) << "Cutting cycles...";
1147 vector<CutEdgeVertexes> cuts;
1148 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1149 LOG(INFO) << "done cutting cycles";
1150 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1151 CheckGraph(*graph);
1152
1153 LOG(INFO) << "Creating initial topological order...";
1154 TopologicalSort(*graph, final_order);
1155 LOG(INFO) << "done with initial topo order";
1156 CheckGraph(*graph);
1157
1158 LOG(INFO) << "Moving full ops to the back";
1159 MoveFullOpsToBack(graph, final_order);
1160 LOG(INFO) << "done moving full ops to back";
1161
1162 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1163 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1164
1165 if (!cuts.empty())
1166 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1167 new_root,
1168 fd,
1169 data_file_size,
1170 final_order,
1171 &inverse_final_order,
1172 cuts));
1173 LOG(INFO) << "Making sure all temp blocks have been allocated";
1174 graph_utils::DumpGraph(*graph);
1175 CHECK(NoTempBlocksRemain(*graph));
1176 LOG(INFO) << "done making sure all temp blocks are allocated";
1177 return true;
1178}
1179
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001180bool DeltaDiffGenerator::ReadFullUpdateFromDisk(
1181 Graph* graph,
1182 const std::string& new_kernel_part,
1183 const std::string& new_image,
Darin Petkov7ea32332010-10-13 10:46:11 -07001184 off_t image_size,
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001185 int fd,
1186 off_t* data_file_size,
1187 off_t chunk_size,
1188 vector<DeltaArchiveManifest_InstallOperation>* kernel_ops,
1189 std::vector<Vertex::Index>* final_order) {
1190 TEST_AND_RETURN_FALSE(chunk_size > 0);
1191 TEST_AND_RETURN_FALSE((chunk_size % kBlockSize) == 0);
Darin Petkov36a58222010-10-07 22:00:09 -07001192
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001193 // Get the sizes early in the function, so we can fail fast if the user
1194 // passed us bad paths.
Darin Petkov7ea32332010-10-13 10:46:11 -07001195 TEST_AND_RETURN_FALSE(image_size >= 0 &&
1196 image_size <= utils::FileSize(new_image));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001197 const off_t kernel_size = utils::FileSize(new_kernel_part);
1198 TEST_AND_RETURN_FALSE(kernel_size >= 0);
1199
1200 off_t part_sizes[] = { image_size, kernel_size };
1201 string paths[] = { new_image, new_kernel_part };
1202
1203 for (int partition = 0; partition < 2; ++partition) {
1204 const string& path = paths[partition];
1205 LOG(INFO) << "compressing " << path;
1206
1207 int in_fd = open(path.c_str(), O_RDONLY, 0);
1208 TEST_AND_RETURN_FALSE(in_fd >= 0);
1209 ScopedFdCloser in_fd_closer(&in_fd);
1210
1211 for (off_t bytes_left = part_sizes[partition], counter = 0, offset = 0;
1212 bytes_left > 0;
1213 bytes_left -= chunk_size, ++counter, offset += chunk_size) {
1214 LOG(INFO) << "offset = " << offset;
1215 DeltaArchiveManifest_InstallOperation* op = NULL;
1216 if (partition == 0) {
1217 graph->resize(graph->size() + 1);
1218 graph->back().file_name = path + StringPrintf("-%" PRIi64, counter);
1219 op = &graph->back().op;
1220 final_order->push_back(graph->size() - 1);
1221 } else {
1222 kernel_ops->resize(kernel_ops->size() + 1);
1223 op = &kernel_ops->back();
1224 }
1225 LOG(INFO) << "have an op";
Darin Petkov36a58222010-10-07 22:00:09 -07001226
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001227 vector<char> buf(min(bytes_left, chunk_size));
1228 LOG(INFO) << "buf size: " << buf.size();
1229 ssize_t bytes_read = -1;
Darin Petkov36a58222010-10-07 22:00:09 -07001230
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001231 TEST_AND_RETURN_FALSE(utils::PReadAll(
1232 in_fd, &buf[0], buf.size(), offset, &bytes_read));
1233 TEST_AND_RETURN_FALSE(bytes_read == static_cast<ssize_t>(buf.size()));
Darin Petkov36a58222010-10-07 22:00:09 -07001234
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001235 vector<char> buf_compressed;
Darin Petkov36a58222010-10-07 22:00:09 -07001236
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001237 TEST_AND_RETURN_FALSE(BzipCompress(buf, &buf_compressed));
1238 const bool compress = buf_compressed.size() < buf.size();
1239 const vector<char>& use_buf = compress ? buf_compressed : buf;
1240 if (compress) {
1241 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1242 } else {
1243 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1244 }
1245 op->set_data_offset(*data_file_size);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001246 TEST_AND_RETURN_FALSE(utils::WriteAll(fd, &use_buf[0], use_buf.size()));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001247 *data_file_size += use_buf.size();
1248 op->set_data_length(use_buf.size());
1249 Extent* dst_extent = op->add_dst_extents();
1250 dst_extent->set_start_block(offset / kBlockSize);
1251 dst_extent->set_num_blocks(chunk_size / kBlockSize);
1252 }
1253 }
1254
1255 return true;
1256}
1257
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001258bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1259 const string& old_root,
1260 const string& old_image,
1261 const string& new_root,
1262 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001263 const string& old_kernel_part,
1264 const string& new_kernel_part,
1265 const string& output_path,
1266 const string& private_key_path) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001267 int old_image_block_count = 0, old_image_block_size = 0;
1268 int new_image_block_count = 0, new_image_block_size = 0;
1269 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(new_image,
1270 &new_image_block_count,
1271 &new_image_block_size));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001272 if (!old_image.empty()) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001273 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(old_image,
1274 &old_image_block_count,
1275 &old_image_block_size));
1276 TEST_AND_RETURN_FALSE(old_image_block_size == new_image_block_size);
1277 LOG_IF(WARNING, old_image_block_count != new_image_block_count)
1278 << "Old and new images have different block counts.";
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001279 // Sanity check kernel partition arg
1280 TEST_AND_RETURN_FALSE(utils::FileSize(old_kernel_part) >= 0);
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001281 }
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001282 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001283 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1284
Darin Petkov7ea32332010-10-13 10:46:11 -07001285 vector<Block> blocks(max(old_image_block_count, new_image_block_count));
1286 LOG(INFO) << "Invalid block index: " << Vertex::kInvalidIndex;
1287 LOG(INFO) << "Block count: " << blocks.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001288 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1289 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1290 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1291 }
1292 Graph graph;
1293 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001294
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001295 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
1296 string temp_file_path;
1297 off_t data_file_size = 0;
1298
1299 LOG(INFO) << "Reading files...";
1300
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001301 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1302
Andrew de los Reyesef017552010-10-06 17:57:52 -07001303 vector<Vertex::Index> final_order;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001304 {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001305 int fd;
1306 TEST_AND_RETURN_FALSE(
1307 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
1308 TEST_AND_RETURN_FALSE(fd >= 0);
1309 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001310 if (!old_image.empty()) {
1311 // Delta update
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001312
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001313 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1314 &blocks,
1315 old_root,
1316 new_root,
1317 fd,
1318 &data_file_size));
1319 LOG(INFO) << "done reading normal files";
1320 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001321
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001322 graph.resize(graph.size() + 1);
1323 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1324 fd,
1325 &data_file_size,
1326 new_image,
1327 &graph.back()));
1328
1329 // Read kernel partition
1330 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1331 new_kernel_part,
1332 &kernel_ops,
1333 fd,
1334 &data_file_size));
1335
1336 LOG(INFO) << "done reading kernel";
1337 CheckGraph(graph);
1338
1339 LOG(INFO) << "Creating edges...";
1340 CreateEdges(&graph, blocks);
1341 LOG(INFO) << "Done creating edges";
1342 CheckGraph(graph);
1343
1344 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1345 new_root,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001346 fd,
1347 &data_file_size,
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001348 &final_order));
1349 } else {
1350 // Full update
Darin Petkov7ea32332010-10-13 10:46:11 -07001351 off_t new_image_size =
1352 static_cast<off_t>(new_image_block_count) * new_image_block_size;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001353 TEST_AND_RETURN_FALSE(ReadFullUpdateFromDisk(&graph,
1354 new_kernel_part,
1355 new_image,
Darin Petkov7ea32332010-10-13 10:46:11 -07001356 new_image_size,
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001357 fd,
1358 &data_file_size,
1359 kFullUpdateChunkSize,
1360 &kernel_ops,
1361 &final_order));
1362 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001363 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001364
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001365 // Convert to protobuf Manifest object
1366 DeltaArchiveManifest manifest;
1367 CheckGraph(graph);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001368 InstallOperationsToManifest(graph, final_order, kernel_ops, &manifest);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001369
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001370 CheckGraph(graph);
1371 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001372
1373 // Reorder the data blobs with the newly ordered manifest
1374 string ordered_blobs_path;
1375 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1376 "/tmp/CrAU_temp_data.ordered.XXXXXX",
1377 &ordered_blobs_path,
1378 false));
1379 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1380 temp_file_path,
1381 ordered_blobs_path));
1382
1383 // Check that install op blobs are in order and that all blocks are written.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001384 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001385 {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001386 vector<uint32_t> written_count(blocks.size(), 0);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001387 for (int i = 0; i < (manifest.install_operations_size() +
1388 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001389 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001390 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001391 manifest.mutable_install_operations(i) :
1392 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001393 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001394 for (int j = 0; j < op->dst_extents_size(); j++) {
1395 const Extent& extent = op->dst_extents(j);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001396 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001397 block < (extent.start_block() + extent.num_blocks()); block++) {
Darin Petkovc0b7a532010-09-29 15:18:14 -07001398 if (block < blocks.size())
1399 written_count[block]++;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001400 }
1401 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001402 if (op->has_data_offset()) {
1403 if (op->data_offset() != next_blob_offset) {
1404 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001405 << next_blob_offset;
1406 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001407 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001408 }
1409 }
1410 // check all blocks written to
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001411 for (vector<uint32_t>::size_type i = 0; i < written_count.size(); i++) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001412 if (written_count[i] == 0) {
1413 LOG(FATAL) << "block " << i << " not written!";
1414 }
1415 }
1416 }
1417
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001418 // Signatures appear at the end of the blobs. Note the offset in the
1419 // manifest
1420 if (!private_key_path.empty()) {
1421 LOG(INFO) << "Making room for signature in file";
1422 manifest.set_signatures_offset(next_blob_offset);
1423 LOG(INFO) << "set? " << manifest.has_signatures_offset();
1424 // Add a dummy op at the end to appease older clients
1425 DeltaArchiveManifest_InstallOperation* dummy_op =
1426 manifest.add_kernel_install_operations();
1427 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1428 dummy_op->set_data_offset(next_blob_offset);
1429 manifest.set_signatures_offset(next_blob_offset);
1430 uint64_t signature_blob_length = 0;
1431 TEST_AND_RETURN_FALSE(
1432 PayloadSigner::SignatureBlobLength(private_key_path,
1433 &signature_blob_length));
1434 dummy_op->set_data_length(signature_blob_length);
1435 manifest.set_signatures_size(signature_blob_length);
1436 Extent* dummy_extent = dummy_op->add_dst_extents();
1437 // Tell the dummy op to write this data to a big sparse hole
1438 dummy_extent->set_start_block(kSparseHole);
1439 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1440 kBlockSize);
1441 }
1442
Darin Petkov36a58222010-10-07 22:00:09 -07001443 TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1444 new_kernel_part,
1445 old_image,
1446 new_image,
1447 &manifest));
1448
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001449 // Serialize protobuf
1450 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001451
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001452 CheckGraph(graph);
1453 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1454 CheckGraph(graph);
1455
1456 LOG(INFO) << "Writing final delta file header...";
1457 DirectFileWriter writer;
1458 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1459 O_WRONLY | O_CREAT | O_TRUNC,
1460 0644) == 0);
1461 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001462
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001463 // Write header
1464 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)) ==
Andrew de los Reyes08c4e272010-04-15 14:02:17 -07001465 static_cast<ssize_t>(strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001466
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001467 // Write version number
1468 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001469
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001470 // Write protobuf length
1471 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1472 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001473
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001474 // Write protobuf
1475 LOG(INFO) << "Writing final delta file protobuf... "
1476 << serialized_manifest.size();
1477 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
1478 serialized_manifest.size()) ==
1479 static_cast<ssize_t>(serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001480
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001481 // Append the data blobs
1482 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001483 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001484 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1485 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1486 for (;;) {
1487 char buf[kBlockSize];
1488 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1489 if (0 == rc) {
1490 // EOF
1491 break;
1492 }
1493 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
1494 TEST_AND_RETURN_FALSE(writer.Write(buf, rc) == rc);
1495 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001496
1497 // Write signature blob.
1498 if (!private_key_path.empty()) {
1499 LOG(INFO) << "Signing the update...";
1500 vector<char> signature_blob;
1501 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(output_path,
1502 private_key_path,
1503 &signature_blob));
1504 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
1505 signature_blob.size()) ==
1506 static_cast<ssize_t>(signature_blob.size()));
1507 }
1508
Darin Petkov95cf01f2010-10-12 14:59:13 -07001509 int64_t manifest_metadata_size =
1510 strlen(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
1511 ReportPayloadUsage(graph, manifest, manifest_metadata_size);
Darin Petkov880335c2010-10-01 15:52:53 -07001512
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001513 LOG(INFO) << "All done. Successfully created delta file.";
1514 return true;
1515}
1516
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001517const char* const kBsdiffPath = "/usr/bin/bsdiff";
1518const char* const kBspatchPath = "/usr/bin/bspatch";
1519const char* const kDeltaMagic = "CrAU";
1520
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001521}; // namespace chromeos_update_engine