blob: f024481b048ade7128ce4e672a8f54c1437e16b7 [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());
Darin Petkov698d0412010-10-13 10:59:44 -0700614 LOG(INFO) << "hash: " << hasher.hash();
Darin Petkov36a58222010-10-07 22:00:09 -0700615 return true;
616}
617
618bool InitializePartitionInfos(const string& old_kernel,
619 const string& new_kernel,
620 const string& old_rootfs,
621 const string& new_rootfs,
622 DeltaArchiveManifest* manifest) {
Darin Petkov698d0412010-10-13 10:59:44 -0700623 // TODO(petkov): Generate the old kernel info when we stop generating full
624 // updates for the kernel partition.
Darin Petkov36a58222010-10-07 22:00:09 -0700625 TEST_AND_RETURN_FALSE(
Darin Petkov7ea32332010-10-13 10:46:11 -0700626 InitializePartitionInfo(true,
627 new_kernel,
628 manifest->mutable_new_kernel_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700629 if (!old_rootfs.empty()) {
630 TEST_AND_RETURN_FALSE(
Darin Petkov7ea32332010-10-13 10:46:11 -0700631 InitializePartitionInfo(false,
632 old_rootfs,
Darin Petkov36a58222010-10-07 22:00:09 -0700633 manifest->mutable_old_rootfs_info()));
634 }
635 TEST_AND_RETURN_FALSE(
Darin Petkov7ea32332010-10-13 10:46:11 -0700636 InitializePartitionInfo(false,
637 new_rootfs,
638 manifest->mutable_new_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700639 return true;
640}
641
Andrew de los Reyesef017552010-10-06 17:57:52 -0700642namespace {
643
644// Takes a collection (vector or RepeatedPtrField) of Extent and
645// returns a vector of the blocks referenced, in order.
646template<typename T>
647vector<uint64_t> ExpandExtents(const T& extents) {
648 vector<uint64_t> ret;
649 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
650 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700651 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700652 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700653 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700654 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700655 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700656 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700657 }
658 }
659 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700660 return ret;
661}
662
663// Takes a vector of blocks and returns an equivalent vector of Extent
664// objects.
665vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
666 vector<Extent> new_extents;
667 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
668 it != e; ++it) {
669 graph_utils::AppendBlockToExtents(&new_extents, *it);
670 }
671 return new_extents;
672}
673
674} // namespace {}
675
676void DeltaDiffGenerator::SubstituteBlocks(
677 Vertex* vertex,
678 const vector<Extent>& remove_extents,
679 const vector<Extent>& replace_extents) {
680 // First, expand out the blocks that op reads from
681 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700682 {
683 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700684 vector<uint64_t> remove_extents_expanded =
685 ExpandExtents(remove_extents);
686 vector<uint64_t> replace_extents_expanded =
687 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700688 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700689 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700690 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700691 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700692 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
693 }
694 utils::ApplyMap(&read_blocks, conversion);
695 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
696 e = vertex->out_edges.end(); it != e; ++it) {
697 vector<uint64_t> write_before_deps_expanded =
698 ExpandExtents(it->second.write_extents);
699 utils::ApplyMap(&write_before_deps_expanded, conversion);
700 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700701 }
702 }
703 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700704 vertex->op.clear_src_extents();
705 vector<Extent> new_extents = CompressExtents(read_blocks);
706 DeltaDiffGenerator::StoreExtents(new_extents,
707 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700708}
709
710bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700711 const set<Edge>& edges,
712 vector<CutEdgeVertexes>* out_cuts) {
713 DummyExtentAllocator scratch_allocator;
714 vector<CutEdgeVertexes> cuts;
715 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700716
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700717 uint64_t scratch_blocks_used = 0;
718 for (set<Edge>::const_iterator it = edges.begin();
719 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700720 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700721 vector<Extent> old_extents =
722 (*graph)[it->first].out_edges[it->second].extents;
723 // Choose some scratch space
724 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
725 LOG(INFO) << "using " << graph_utils::EdgeWeight(*graph, *it)
726 << " scratch blocks ("
727 << scratch_blocks_used << ")";
Andrew de los Reyesef017552010-10-06 17:57:52 -0700728 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700729 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
730 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700731 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700732 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700733 cuts.back().old_src = it->first;
734 cuts.back().old_dst = it->second;
Darin Petkov36a58222010-10-07 22:00:09 -0700735
Andrew de los Reyesef017552010-10-06 17:57:52 -0700736 EdgeProperties& cut_edge_properties =
737 (*graph)[it->first].out_edges.find(it->second)->second;
738
739 // This should never happen, as we should only be cutting edges between
740 // real file nodes, and write-before relationships are created from
741 // a real file node to a temp copy node:
742 CHECK(cut_edge_properties.write_extents.empty())
743 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700744
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700745 // make node depend on the copy operation
746 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700747 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700748
749 // Set src/dst extents and other proto variables for copy operation
750 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
751 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700752 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700753 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700754 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700755 graph->back().op.mutable_dst_extents());
756 graph->back().op.set_src_length(
757 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
758 graph->back().op.set_dst_length(graph->back().op.src_length());
759
760 // make the dest node read from the scratch space
761 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700762 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700763 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700764 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700765
766 // delete the old edge
767 CHECK_EQ(1, (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700768
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700769 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700770 EdgeProperties write_before_edge_properties;
771 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
772 (*graph)[it->second].out_edges.insert(
773 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700774 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700775 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700776 return true;
777}
778
779// Stores all Extents in 'extents' into 'out'.
780void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700781 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700782 google::protobuf::RepeatedPtrField<Extent>* out) {
783 for (vector<Extent>::const_iterator it = extents.begin();
784 it != extents.end(); ++it) {
785 Extent* new_extent = out->Add();
786 *new_extent = *it;
787 }
788}
789
790// Creates all the edges for the graph. Writers of a block point to
791// readers of the same block. This is because for an edge A->B, B
792// must complete before A executes.
793void DeltaDiffGenerator::CreateEdges(Graph* graph,
794 const vector<Block>& blocks) {
795 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
796 // Blocks with both a reader and writer get an edge
797 if (blocks[i].reader == Vertex::kInvalidIndex ||
798 blocks[i].writer == Vertex::kInvalidIndex)
799 continue;
800 // Don't have a node depend on itself
801 if (blocks[i].reader == blocks[i].writer)
802 continue;
803 // See if there's already an edge we can add onto
804 Vertex::EdgeMap::iterator edge_it =
805 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
806 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
807 // No existing edge. Create one
808 (*graph)[blocks[i].writer].out_edges.insert(
809 make_pair(blocks[i].reader, EdgeProperties()));
810 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700811 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700812 }
813 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
814 }
815}
816
Andrew de los Reyesef017552010-10-06 17:57:52 -0700817namespace {
818
819class SortCutsByTopoOrderLess {
820 public:
821 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
822 : table_(table) {}
823 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
824 return table_[a.old_dst] < table_[b.old_dst];
825 }
826 private:
827 vector<vector<Vertex::Index>::size_type>& table_;
828};
829
830} // namespace {}
831
832void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
833 vector<Vertex::Index>& op_indexes,
834 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
835 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
836 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
837 i != e; ++i) {
838 Vertex::Index node = op_indexes[i];
839 if (table.size() < (node + 1)) {
840 table.resize(node + 1);
841 }
842 table[node] = i;
843 }
844 reverse_op_indexes->swap(table);
845}
846
847void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
848 vector<CutEdgeVertexes>* cuts) {
849 // first, make a reverse lookup table.
850 vector<vector<Vertex::Index>::size_type> table;
851 GenerateReverseTopoOrderMap(op_indexes, &table);
852 SortCutsByTopoOrderLess less(table);
853 sort(cuts->begin(), cuts->end(), less);
854}
855
856void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
857 vector<Vertex::Index>* op_indexes) {
858 vector<Vertex::Index> ret;
859 vector<Vertex::Index> full_ops;
860 ret.reserve(op_indexes->size());
861 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
862 ++i) {
863 DeltaArchiveManifest_InstallOperation_Type type =
864 (*graph)[(*op_indexes)[i]].op.type();
865 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
866 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
867 full_ops.push_back((*op_indexes)[i]);
868 } else {
869 ret.push_back((*op_indexes)[i]);
870 }
871 }
872 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
873 << (full_ops.size() + ret.size()) << " total ops.";
874 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
875 op_indexes->swap(ret);
876}
877
878namespace {
879
880template<typename T>
881bool TempBlocksExistInExtents(const T& extents) {
882 for (int i = 0, e = extents.size(); i < e; ++i) {
883 Extent extent = graph_utils::GetElement(extents, i);
884 uint64_t start = extent.start_block();
885 uint64_t num = extent.num_blocks();
886 if (start == kSparseHole)
887 continue;
888 if (start >= kTempBlockStart ||
889 (start + num) >= kTempBlockStart) {
890 LOG(ERROR) << "temp block!";
891 LOG(ERROR) << "start: " << start << ", num: " << num;
892 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
893 LOG(ERROR) << "returning true";
894 return true;
895 }
896 // check for wrap-around, which would be a bug:
897 CHECK(start <= (start + num));
898 }
899 return false;
900}
901
902} // namespace {}
903
904bool DeltaDiffGenerator::AssignTempBlocks(
905 Graph* graph,
906 const string& new_root,
907 int data_fd,
908 off_t* data_file_size,
909 vector<Vertex::Index>* op_indexes,
910 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
911 vector<CutEdgeVertexes>& cuts) {
912 CHECK(!cuts.empty());
913 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
914 true ; --i) {
915 LOG(INFO) << "Fixing temp blocks in cut " << i
916 << ": old dst: " << cuts[i].old_dst << " new vertex: "
917 << cuts[i].new_vertex;
918 const uint64_t blocks_needed =
919 graph_utils::BlocksInExtents(cuts[i].tmp_extents);
920 LOG(INFO) << "Scanning for usable blocks (" << blocks_needed << " needed)";
921 // For now, just look for a single op w/ sufficient blocks, not
922 // considering blocks from outgoing read-before deps.
923 Vertex::Index node = cuts[i].old_dst;
924 DeltaArchiveManifest_InstallOperation_Type node_type =
925 (*graph)[node].op.type();
926 if (node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
927 node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
928 LOG(INFO) << "This was already converted to full, so skipping.";
929 // Delete the temp node and pointer to it from old src
930 if (!(*graph)[cuts[i].old_src].out_edges.erase(cuts[i].new_vertex)) {
931 LOG(INFO) << "Odd. node " << cuts[i].old_src << " didn't point to "
932 << cuts[i].new_vertex;
933 }
934 (*graph)[cuts[i].new_vertex].valid = false;
935 vector<Vertex::Index>::size_type new_topo_idx =
936 (*reverse_op_indexes)[cuts[i].new_vertex];
937 op_indexes->erase(op_indexes->begin() + new_topo_idx);
938 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
939 continue;
940 }
941 bool found_node = false;
942 for (vector<Vertex::Index>::size_type j = (*reverse_op_indexes)[node] + 1,
943 je = op_indexes->size(); j < je; ++j) {
944 Vertex::Index test_node = (*op_indexes)[j];
945 // See if this node has sufficient blocks
946 ExtentRanges ranges;
947 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
948 ranges.SubtractExtent(ExtentForRange(
949 kTempBlockStart, kSparseHole - kTempBlockStart));
950 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
951 // For now, for simplicity, subtract out all blocks in read-before
952 // dependencies.
953 for (Vertex::EdgeMap::const_iterator edge_i =
954 (*graph)[test_node].out_edges.begin(),
955 edge_e = (*graph)[test_node].out_edges.end();
956 edge_i != edge_e; ++edge_i) {
957 ranges.SubtractExtents(edge_i->second.extents);
958 }
Darin Petkov36a58222010-10-07 22:00:09 -0700959
Andrew de los Reyesef017552010-10-06 17:57:52 -0700960 uint64_t blocks_found = ranges.blocks();
961 if (blocks_found < blocks_needed) {
962 if (blocks_found > 0)
963 LOG(INFO) << "insufficient blocks found in topo node " << j
964 << " (node " << (*op_indexes)[j] << "). Found only "
965 << blocks_found;
966 continue;
967 }
968 found_node = true;
969 LOG(INFO) << "Found sufficient blocks in topo node " << j
970 << " (node " << (*op_indexes)[j] << ")";
971 // Sub in the blocks, and make the node supplying the blocks
972 // depend on old_dst.
973 vector<Extent> real_extents =
974 ranges.GetExtentsForBlockCount(blocks_needed);
Darin Petkov36a58222010-10-07 22:00:09 -0700975
Andrew de los Reyesef017552010-10-06 17:57:52 -0700976 // Fix the old dest node w/ the real blocks
977 SubstituteBlocks(&(*graph)[node],
978 cuts[i].tmp_extents,
979 real_extents);
Darin Petkov36a58222010-10-07 22:00:09 -0700980
Andrew de los Reyesef017552010-10-06 17:57:52 -0700981 // Fix the new node w/ the real blocks. Since the new node is just a
982 // copy operation, we can replace all the dest extents w/ the real
983 // blocks.
984 DeltaArchiveManifest_InstallOperation *op =
985 &(*graph)[cuts[i].new_vertex].op;
986 op->clear_dst_extents();
987 StoreExtents(real_extents, op->mutable_dst_extents());
Darin Petkov36a58222010-10-07 22:00:09 -0700988
Andrew de los Reyesef017552010-10-06 17:57:52 -0700989 // Add an edge from the real-block supplier to the old dest block.
990 graph_utils::AddReadBeforeDepExtents(&(*graph)[test_node],
991 node,
992 real_extents);
993 break;
994 }
995 if (!found_node) {
996 // convert to full op
997 LOG(WARNING) << "Failed to find enough temp blocks for cut " << i
998 << " with old dest (graph node " << node
999 << "). Converting to a full op, at the expense of a "
1000 << "good compression ratio.";
1001 TEST_AND_RETURN_FALSE(ConvertCutToFullOp(graph,
1002 cuts[i],
1003 new_root,
1004 data_fd,
1005 data_file_size));
1006 // move the full op to the back
1007 vector<Vertex::Index> new_op_indexes;
1008 for (vector<Vertex::Index>::const_iterator iter_i = op_indexes->begin(),
1009 iter_e = op_indexes->end(); iter_i != iter_e; ++iter_i) {
1010 if ((*iter_i == cuts[i].old_dst) || (*iter_i == cuts[i].new_vertex))
1011 continue;
1012 new_op_indexes.push_back(*iter_i);
1013 }
1014 new_op_indexes.push_back(cuts[i].old_dst);
1015 op_indexes->swap(new_op_indexes);
Darin Petkov36a58222010-10-07 22:00:09 -07001016
Andrew de los Reyesef017552010-10-06 17:57:52 -07001017 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
1018 }
1019 if (i == e) {
1020 // break out of for() loop
1021 break;
1022 }
1023 }
1024 return true;
1025}
1026
1027bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1028 size_t idx = 0;
1029 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1030 ++it, ++idx) {
1031 if (!it->valid)
1032 continue;
1033 const DeltaArchiveManifest_InstallOperation& op = it->op;
1034 if (TempBlocksExistInExtents(op.dst_extents()) ||
1035 TempBlocksExistInExtents(op.src_extents())) {
1036 LOG(INFO) << "bad extents in node " << idx;
1037 LOG(INFO) << "so yeah";
1038 return false;
1039 }
1040
1041 // Check out-edges:
1042 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
1043 je = it->out_edges.end(); jt != je; ++jt) {
1044 if (TempBlocksExistInExtents(jt->second.extents) ||
1045 TempBlocksExistInExtents(jt->second.write_extents)) {
1046 LOG(INFO) << "bad out edge in node " << idx;
1047 LOG(INFO) << "so yeah";
1048 return false;
1049 }
1050 }
1051 }
1052 return true;
1053}
1054
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001055bool DeltaDiffGenerator::ReorderDataBlobs(
1056 DeltaArchiveManifest* manifest,
1057 const std::string& data_blobs_path,
1058 const std::string& new_data_blobs_path) {
1059 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1060 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1061 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001062
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001063 DirectFileWriter writer;
1064 TEST_AND_RETURN_FALSE(
1065 writer.Open(new_data_blobs_path.c_str(),
1066 O_WRONLY | O_TRUNC | O_CREAT,
1067 0644) == 0);
1068 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001069 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001070
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001071 for (int i = 0; i < (manifest->install_operations_size() +
1072 manifest->kernel_install_operations_size()); i++) {
1073 DeltaArchiveManifest_InstallOperation* op = NULL;
1074 if (i < manifest->install_operations_size()) {
1075 op = manifest->mutable_install_operations(i);
1076 } else {
1077 op = manifest->mutable_kernel_install_operations(
1078 i - manifest->install_operations_size());
1079 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001080 if (!op->has_data_offset())
1081 continue;
1082 CHECK(op->has_data_length());
1083 vector<char> buf(op->data_length());
1084 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1085 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1086
1087 op->set_data_offset(out_file_size);
1088 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()) ==
1089 static_cast<ssize_t>(buf.size()));
1090 out_file_size += buf.size();
1091 }
1092 return true;
1093}
1094
Andrew de los Reyesef017552010-10-06 17:57:52 -07001095bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1096 const CutEdgeVertexes& cut,
1097 const string& new_root,
1098 int data_fd,
1099 off_t* data_file_size) {
1100 // Drop all incoming edges, keep all outgoing edges
Darin Petkov36a58222010-10-07 22:00:09 -07001101
Andrew de los Reyesef017552010-10-06 17:57:52 -07001102 // Keep all outgoing edges
1103 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1104 graph_utils::DropWriteBeforeDeps(&out_edges);
Darin Petkov36a58222010-10-07 22:00:09 -07001105
Andrew de los Reyesef017552010-10-06 17:57:52 -07001106 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1107 cut.old_dst,
1108 NULL,
1109 "/-!@:&*nonexistent_path",
1110 new_root,
1111 (*graph)[cut.old_dst].file_name,
1112 data_fd,
1113 data_file_size));
Darin Petkov36a58222010-10-07 22:00:09 -07001114
Andrew de los Reyesef017552010-10-06 17:57:52 -07001115 (*graph)[cut.old_dst].out_edges = out_edges;
1116
1117 // Right now we don't have doubly-linked edges, so we have to scan
1118 // the whole graph.
1119 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1120
1121 // Delete temp node
1122 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1123 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1124 (*graph)[cut.old_dst].out_edges.end());
1125 (*graph)[cut.new_vertex].valid = false;
1126 return true;
1127}
1128
1129bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1130 const string& new_root,
1131 int fd,
1132 off_t* data_file_size,
1133 vector<Vertex::Index>* final_order) {
1134 CycleBreaker cycle_breaker;
1135 LOG(INFO) << "Finding cycles...";
1136 set<Edge> cut_edges;
1137 cycle_breaker.BreakCycles(*graph, &cut_edges);
1138 LOG(INFO) << "done finding cycles";
1139 CheckGraph(*graph);
1140
1141 // Calculate number of scratch blocks needed
1142
1143 LOG(INFO) << "Cutting cycles...";
1144 vector<CutEdgeVertexes> cuts;
1145 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1146 LOG(INFO) << "done cutting cycles";
1147 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1148 CheckGraph(*graph);
1149
1150 LOG(INFO) << "Creating initial topological order...";
1151 TopologicalSort(*graph, final_order);
1152 LOG(INFO) << "done with initial topo order";
1153 CheckGraph(*graph);
1154
1155 LOG(INFO) << "Moving full ops to the back";
1156 MoveFullOpsToBack(graph, final_order);
1157 LOG(INFO) << "done moving full ops to back";
1158
1159 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1160 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1161
1162 if (!cuts.empty())
1163 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1164 new_root,
1165 fd,
1166 data_file_size,
1167 final_order,
1168 &inverse_final_order,
1169 cuts));
1170 LOG(INFO) << "Making sure all temp blocks have been allocated";
1171 graph_utils::DumpGraph(*graph);
1172 CHECK(NoTempBlocksRemain(*graph));
1173 LOG(INFO) << "done making sure all temp blocks are allocated";
1174 return true;
1175}
1176
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001177bool DeltaDiffGenerator::ReadFullUpdateFromDisk(
1178 Graph* graph,
1179 const std::string& new_kernel_part,
1180 const std::string& new_image,
Darin Petkov7ea32332010-10-13 10:46:11 -07001181 off_t image_size,
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001182 int fd,
1183 off_t* data_file_size,
1184 off_t chunk_size,
1185 vector<DeltaArchiveManifest_InstallOperation>* kernel_ops,
1186 std::vector<Vertex::Index>* final_order) {
1187 TEST_AND_RETURN_FALSE(chunk_size > 0);
1188 TEST_AND_RETURN_FALSE((chunk_size % kBlockSize) == 0);
Darin Petkov36a58222010-10-07 22:00:09 -07001189
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001190 // Get the sizes early in the function, so we can fail fast if the user
1191 // passed us bad paths.
Darin Petkov7ea32332010-10-13 10:46:11 -07001192 TEST_AND_RETURN_FALSE(image_size >= 0 &&
1193 image_size <= utils::FileSize(new_image));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001194 const off_t kernel_size = utils::FileSize(new_kernel_part);
1195 TEST_AND_RETURN_FALSE(kernel_size >= 0);
1196
1197 off_t part_sizes[] = { image_size, kernel_size };
1198 string paths[] = { new_image, new_kernel_part };
1199
1200 for (int partition = 0; partition < 2; ++partition) {
1201 const string& path = paths[partition];
1202 LOG(INFO) << "compressing " << path;
1203
1204 int in_fd = open(path.c_str(), O_RDONLY, 0);
1205 TEST_AND_RETURN_FALSE(in_fd >= 0);
1206 ScopedFdCloser in_fd_closer(&in_fd);
1207
1208 for (off_t bytes_left = part_sizes[partition], counter = 0, offset = 0;
1209 bytes_left > 0;
1210 bytes_left -= chunk_size, ++counter, offset += chunk_size) {
1211 LOG(INFO) << "offset = " << offset;
1212 DeltaArchiveManifest_InstallOperation* op = NULL;
1213 if (partition == 0) {
1214 graph->resize(graph->size() + 1);
1215 graph->back().file_name = path + StringPrintf("-%" PRIi64, counter);
1216 op = &graph->back().op;
1217 final_order->push_back(graph->size() - 1);
1218 } else {
1219 kernel_ops->resize(kernel_ops->size() + 1);
1220 op = &kernel_ops->back();
1221 }
1222 LOG(INFO) << "have an op";
Darin Petkov36a58222010-10-07 22:00:09 -07001223
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001224 vector<char> buf(min(bytes_left, chunk_size));
1225 LOG(INFO) << "buf size: " << buf.size();
1226 ssize_t bytes_read = -1;
Darin Petkov36a58222010-10-07 22:00:09 -07001227
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001228 TEST_AND_RETURN_FALSE(utils::PReadAll(
1229 in_fd, &buf[0], buf.size(), offset, &bytes_read));
1230 TEST_AND_RETURN_FALSE(bytes_read == static_cast<ssize_t>(buf.size()));
Darin Petkov36a58222010-10-07 22:00:09 -07001231
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001232 vector<char> buf_compressed;
Darin Petkov36a58222010-10-07 22:00:09 -07001233
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001234 TEST_AND_RETURN_FALSE(BzipCompress(buf, &buf_compressed));
1235 const bool compress = buf_compressed.size() < buf.size();
1236 const vector<char>& use_buf = compress ? buf_compressed : buf;
1237 if (compress) {
1238 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1239 } else {
1240 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1241 }
1242 op->set_data_offset(*data_file_size);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001243 TEST_AND_RETURN_FALSE(utils::WriteAll(fd, &use_buf[0], use_buf.size()));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001244 *data_file_size += use_buf.size();
1245 op->set_data_length(use_buf.size());
1246 Extent* dst_extent = op->add_dst_extents();
1247 dst_extent->set_start_block(offset / kBlockSize);
1248 dst_extent->set_num_blocks(chunk_size / kBlockSize);
1249 }
1250 }
1251
1252 return true;
1253}
1254
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001255bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1256 const string& old_root,
1257 const string& old_image,
1258 const string& new_root,
1259 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001260 const string& old_kernel_part,
1261 const string& new_kernel_part,
1262 const string& output_path,
1263 const string& private_key_path) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001264 int old_image_block_count = 0, old_image_block_size = 0;
1265 int new_image_block_count = 0, new_image_block_size = 0;
1266 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(new_image,
1267 &new_image_block_count,
1268 &new_image_block_size));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001269 if (!old_image.empty()) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001270 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(old_image,
1271 &old_image_block_count,
1272 &old_image_block_size));
1273 TEST_AND_RETURN_FALSE(old_image_block_size == new_image_block_size);
1274 LOG_IF(WARNING, old_image_block_count != new_image_block_count)
1275 << "Old and new images have different block counts.";
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001276 // Sanity check kernel partition arg
1277 TEST_AND_RETURN_FALSE(utils::FileSize(old_kernel_part) >= 0);
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001278 }
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001279 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001280 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1281
Darin Petkov7ea32332010-10-13 10:46:11 -07001282 vector<Block> blocks(max(old_image_block_count, new_image_block_count));
1283 LOG(INFO) << "Invalid block index: " << Vertex::kInvalidIndex;
1284 LOG(INFO) << "Block count: " << blocks.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001285 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1286 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1287 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1288 }
1289 Graph graph;
1290 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001291
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001292 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
1293 string temp_file_path;
1294 off_t data_file_size = 0;
1295
1296 LOG(INFO) << "Reading files...";
1297
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001298 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1299
Andrew de los Reyesef017552010-10-06 17:57:52 -07001300 vector<Vertex::Index> final_order;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001301 {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001302 int fd;
1303 TEST_AND_RETURN_FALSE(
1304 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
1305 TEST_AND_RETURN_FALSE(fd >= 0);
1306 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001307 if (!old_image.empty()) {
1308 // Delta update
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001309
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001310 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1311 &blocks,
1312 old_root,
1313 new_root,
1314 fd,
1315 &data_file_size));
1316 LOG(INFO) << "done reading normal files";
1317 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001318
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001319 graph.resize(graph.size() + 1);
1320 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1321 fd,
1322 &data_file_size,
1323 new_image,
1324 &graph.back()));
1325
1326 // Read kernel partition
1327 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1328 new_kernel_part,
1329 &kernel_ops,
1330 fd,
1331 &data_file_size));
1332
1333 LOG(INFO) << "done reading kernel";
1334 CheckGraph(graph);
1335
1336 LOG(INFO) << "Creating edges...";
1337 CreateEdges(&graph, blocks);
1338 LOG(INFO) << "Done creating edges";
1339 CheckGraph(graph);
1340
1341 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1342 new_root,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001343 fd,
1344 &data_file_size,
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001345 &final_order));
1346 } else {
1347 // Full update
Darin Petkov7ea32332010-10-13 10:46:11 -07001348 off_t new_image_size =
1349 static_cast<off_t>(new_image_block_count) * new_image_block_size;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001350 TEST_AND_RETURN_FALSE(ReadFullUpdateFromDisk(&graph,
1351 new_kernel_part,
1352 new_image,
Darin Petkov7ea32332010-10-13 10:46:11 -07001353 new_image_size,
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001354 fd,
1355 &data_file_size,
1356 kFullUpdateChunkSize,
1357 &kernel_ops,
1358 &final_order));
1359 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001360 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001361
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001362 // Convert to protobuf Manifest object
1363 DeltaArchiveManifest manifest;
1364 CheckGraph(graph);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001365 InstallOperationsToManifest(graph, final_order, kernel_ops, &manifest);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001366
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001367 CheckGraph(graph);
1368 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001369
1370 // Reorder the data blobs with the newly ordered manifest
1371 string ordered_blobs_path;
1372 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1373 "/tmp/CrAU_temp_data.ordered.XXXXXX",
1374 &ordered_blobs_path,
1375 false));
1376 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1377 temp_file_path,
1378 ordered_blobs_path));
1379
1380 // Check that install op blobs are in order and that all blocks are written.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001381 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001382 {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001383 vector<uint32_t> written_count(blocks.size(), 0);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001384 for (int i = 0; i < (manifest.install_operations_size() +
1385 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001386 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001387 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001388 manifest.mutable_install_operations(i) :
1389 manifest.mutable_kernel_install_operations(
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 for (int j = 0; j < op->dst_extents_size(); j++) {
1392 const Extent& extent = op->dst_extents(j);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001393 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001394 block < (extent.start_block() + extent.num_blocks()); block++) {
Darin Petkovc0b7a532010-09-29 15:18:14 -07001395 if (block < blocks.size())
1396 written_count[block]++;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001397 }
1398 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001399 if (op->has_data_offset()) {
1400 if (op->data_offset() != next_blob_offset) {
1401 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001402 << next_blob_offset;
1403 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001404 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001405 }
1406 }
1407 // check all blocks written to
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001408 for (vector<uint32_t>::size_type i = 0; i < written_count.size(); i++) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001409 if (written_count[i] == 0) {
1410 LOG(FATAL) << "block " << i << " not written!";
1411 }
1412 }
1413 }
1414
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001415 // Signatures appear at the end of the blobs. Note the offset in the
1416 // manifest
1417 if (!private_key_path.empty()) {
1418 LOG(INFO) << "Making room for signature in file";
1419 manifest.set_signatures_offset(next_blob_offset);
1420 LOG(INFO) << "set? " << manifest.has_signatures_offset();
1421 // Add a dummy op at the end to appease older clients
1422 DeltaArchiveManifest_InstallOperation* dummy_op =
1423 manifest.add_kernel_install_operations();
1424 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1425 dummy_op->set_data_offset(next_blob_offset);
1426 manifest.set_signatures_offset(next_blob_offset);
1427 uint64_t signature_blob_length = 0;
1428 TEST_AND_RETURN_FALSE(
1429 PayloadSigner::SignatureBlobLength(private_key_path,
1430 &signature_blob_length));
1431 dummy_op->set_data_length(signature_blob_length);
1432 manifest.set_signatures_size(signature_blob_length);
1433 Extent* dummy_extent = dummy_op->add_dst_extents();
1434 // Tell the dummy op to write this data to a big sparse hole
1435 dummy_extent->set_start_block(kSparseHole);
1436 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1437 kBlockSize);
1438 }
1439
Darin Petkov36a58222010-10-07 22:00:09 -07001440 TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1441 new_kernel_part,
1442 old_image,
1443 new_image,
1444 &manifest));
1445
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001446 // Serialize protobuf
1447 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001448
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001449 CheckGraph(graph);
1450 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1451 CheckGraph(graph);
1452
1453 LOG(INFO) << "Writing final delta file header...";
1454 DirectFileWriter writer;
1455 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1456 O_WRONLY | O_CREAT | O_TRUNC,
1457 0644) == 0);
1458 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001459
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001460 // Write header
1461 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)) ==
Andrew de los Reyes08c4e272010-04-15 14:02:17 -07001462 static_cast<ssize_t>(strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001463
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001464 // Write version number
1465 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001466
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001467 // Write protobuf length
1468 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1469 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001470
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001471 // Write protobuf
1472 LOG(INFO) << "Writing final delta file protobuf... "
1473 << serialized_manifest.size();
1474 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
1475 serialized_manifest.size()) ==
1476 static_cast<ssize_t>(serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001477
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001478 // Append the data blobs
1479 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001480 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001481 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1482 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1483 for (;;) {
1484 char buf[kBlockSize];
1485 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1486 if (0 == rc) {
1487 // EOF
1488 break;
1489 }
1490 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
1491 TEST_AND_RETURN_FALSE(writer.Write(buf, rc) == rc);
1492 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001493
1494 // Write signature blob.
1495 if (!private_key_path.empty()) {
1496 LOG(INFO) << "Signing the update...";
1497 vector<char> signature_blob;
1498 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(output_path,
1499 private_key_path,
1500 &signature_blob));
1501 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
1502 signature_blob.size()) ==
1503 static_cast<ssize_t>(signature_blob.size()));
1504 }
1505
Darin Petkov95cf01f2010-10-12 14:59:13 -07001506 int64_t manifest_metadata_size =
1507 strlen(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
1508 ReportPayloadUsage(graph, manifest, manifest_metadata_size);
Darin Petkov880335c2010-10-01 15:52:53 -07001509
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001510 LOG(INFO) << "All done. Successfully created delta file.";
1511 return true;
1512}
1513
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001514const char* const kBsdiffPath = "/usr/bin/bsdiff";
1515const char* const kBspatchPath = "/usr/bin/bspatch";
1516const char* const kDeltaMagic = "CrAU";
1517
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001518}; // namespace chromeos_update_engine