blob: 03b59d937bb06608486d2b48bfe1ac1ae9a1ff4f [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;
Darin Petkov9fa7ec52010-10-18 11:45:23 -070050typedef map<const DeltaArchiveManifest_InstallOperation*,
51 const string*> OperationNameMap;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070052
53namespace {
Andrew de los Reyes27f7d372010-10-07 11:26:07 -070054const size_t kBlockSize = 4096; // bytes
Darin Petkov9eadd642010-10-14 15:20:57 -070055const size_t kRootFSPartitionSize = 1 * 1024 * 1024 * 1024; // bytes
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070056const uint64_t kVersionNumber = 1;
Darin Petkov9eadd642010-10-14 15:20:57 -070057const uint64_t kFullUpdateChunkSize = 1024 * 1024; // bytes
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070058
Darin Petkov68c10d12010-10-14 09:24:37 -070059static const char* kInstallOperationTypes[] = {
60 "REPLACE",
61 "REPLACE_BZ",
62 "MOVE",
63 "BSDIFF"
64};
65
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070066// Stores all Extents for a file into 'out'. Returns true on success.
67bool GatherExtents(const string& path,
68 google::protobuf::RepeatedPtrField<Extent>* out) {
69 vector<Extent> extents;
70 TEST_AND_RETURN_FALSE(extent_mapper::ExtentsForFileFibmap(path, &extents));
71 DeltaDiffGenerator::StoreExtents(extents, out);
72 return true;
73}
74
75// Runs the bsdiff tool on two files and returns the resulting delta in
76// 'out'. Returns true on success.
77bool BsdiffFiles(const string& old_file,
78 const string& new_file,
79 vector<char>* out) {
80 const string kPatchFile = "/tmp/delta.patchXXXXXX";
81 string patch_file_path;
82
83 TEST_AND_RETURN_FALSE(
84 utils::MakeTempFile(kPatchFile, &patch_file_path, NULL));
85
86 vector<string> cmd;
87 cmd.push_back(kBsdiffPath);
88 cmd.push_back(old_file);
89 cmd.push_back(new_file);
90 cmd.push_back(patch_file_path);
91
92 int rc = 1;
93 vector<char> patch_file;
94 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc));
95 TEST_AND_RETURN_FALSE(rc == 0);
96 TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
97 unlink(patch_file_path.c_str());
98 return true;
99}
100
101// The blocks vector contains a reader and writer for each block on the
102// filesystem that's being in-place updated. We populate the reader/writer
103// fields of blocks by calling this function.
104// For each block in 'operation' that is read or written, find that block
105// in 'blocks' and set the reader/writer field to the vertex passed.
106// 'graph' is not strictly necessary, but useful for printing out
107// error messages.
108bool AddInstallOpToBlocksVector(
109 const DeltaArchiveManifest_InstallOperation& operation,
110 vector<Block>* blocks,
111 const Graph& graph,
112 Vertex::Index vertex) {
113 LOG(INFO) << "AddInstallOpToBlocksVector(" << vertex << "), "
114 << graph[vertex].file_name;
115 // See if this is already present.
116 TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700117
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700118 enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
119 for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
120 const int extents_size =
121 (field == READER) ? operation.src_extents_size() :
122 operation.dst_extents_size();
123 const char* past_participle = (field == READER) ? "read" : "written";
124 const google::protobuf::RepeatedPtrField<Extent>& extents =
125 (field == READER) ? operation.src_extents() : operation.dst_extents();
126 Vertex::Index Block::*access_type =
127 (field == READER) ? &Block::reader : &Block::writer;
128
129 for (int i = 0; i < extents_size; i++) {
130 const Extent& extent = extents.Get(i);
131 if (extent.start_block() == kSparseHole) {
132 // Hole in sparse file. skip
133 continue;
134 }
135 for (uint64_t block = extent.start_block();
136 block < (extent.start_block() + extent.num_blocks()); block++) {
137 LOG(INFO) << "ext: " << i << " block: " << block;
138 if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
139 LOG(FATAL) << "Block " << block << " is already "
140 << past_participle << " by "
141 << (*blocks)[block].*access_type << "("
142 << graph[(*blocks)[block].*access_type].file_name
143 << ") and also " << vertex << "("
144 << graph[vertex].file_name << ")";
145 }
146 (*blocks)[block].*access_type = vertex;
147 }
148 }
149 }
150 return true;
151}
152
Andrew de los Reyesef017552010-10-06 17:57:52 -0700153// For a given regular file which must exist at new_root + path, and
154// may exist at old_root + path, creates a new InstallOperation and
155// adds it to the graph. Also, populates the |blocks| array as
156// necessary, if |blocks| is non-NULL. Also, writes the data
157// necessary to send the file down to the client into data_fd, which
158// has length *data_file_size. *data_file_size is updated
159// appropriately. If |existing_vertex| is no kInvalidIndex, use that
160// rather than allocating a new vertex. Returns true on success.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700161bool DeltaReadFile(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700162 Vertex::Index existing_vertex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700163 vector<Block>* blocks,
164 const string& old_root,
165 const string& new_root,
166 const string& path, // within new_root
167 int data_fd,
168 off_t* data_file_size) {
169 vector<char> data;
170 DeltaArchiveManifest_InstallOperation operation;
171
172 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_root + path,
173 new_root + path,
174 &data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700175 &operation,
176 true));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700177
178 // Write the data
179 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
180 operation.set_data_offset(*data_file_size);
181 operation.set_data_length(data.size());
182 }
183
184 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
185 *data_file_size += data.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700186
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700187 // Now, insert into graph and blocks vector
Andrew de los Reyesef017552010-10-06 17:57:52 -0700188 Vertex::Index vertex = existing_vertex;
189 if (vertex == Vertex::kInvalidIndex) {
190 graph->resize(graph->size() + 1);
191 vertex = graph->size() - 1;
192 }
193 (*graph)[vertex].op = operation;
194 CHECK((*graph)[vertex].op.has_type());
195 (*graph)[vertex].file_name = path;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700196
Andrew de los Reyesef017552010-10-06 17:57:52 -0700197 if (blocks)
198 TEST_AND_RETURN_FALSE(AddInstallOpToBlocksVector((*graph)[vertex].op,
199 blocks,
200 *graph,
201 vertex));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700202 return true;
203}
204
205// For each regular file within new_root, creates a node in the graph,
206// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
207// and writes any necessary data to the end of data_fd.
208bool DeltaReadFiles(Graph* graph,
209 vector<Block>* blocks,
210 const string& old_root,
211 const string& new_root,
212 int data_fd,
213 off_t* data_file_size) {
214 set<ino_t> visited_inodes;
215 for (FilesystemIterator fs_iter(new_root,
216 utils::SetWithValue<string>("/lost+found"));
217 !fs_iter.IsEnd(); fs_iter.Increment()) {
218 if (!S_ISREG(fs_iter.GetStat().st_mode))
219 continue;
220
221 // Make sure we visit each inode only once.
222 if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
223 continue;
224 visited_inodes.insert(fs_iter.GetStat().st_ino);
225 if (fs_iter.GetStat().st_size == 0)
226 continue;
227
228 LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700229
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700230 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700231 Vertex::kInvalidIndex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700232 blocks,
233 old_root,
234 new_root,
235 fs_iter.GetPartialPath(),
236 data_fd,
237 data_file_size));
238 }
239 return true;
240}
241
Andrew de los Reyesef017552010-10-06 17:57:52 -0700242// This class allocates non-existent temp blocks, starting from
243// kTempBlockStart. Other code is responsible for converting these
244// temp blocks into real blocks, as the client can't read or write to
245// these blocks.
246class DummyExtentAllocator {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700247 public:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700248 explicit DummyExtentAllocator()
249 : next_block_(kTempBlockStart) {}
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700250 vector<Extent> Allocate(const uint64_t block_count) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700251 vector<Extent> ret(1);
252 ret[0].set_start_block(next_block_);
253 ret[0].set_num_blocks(block_count);
254 next_block_ += block_count;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700255 return ret;
256 }
257 private:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700258 uint64_t next_block_;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700259};
260
261// Reads blocks from image_path that are not yet marked as being written
262// in the blocks array. These blocks that remain are non-file-data blocks.
263// In the future we might consider intelligent diffing between this data
264// and data in the previous image, but for now we just bzip2 compress it
265// and include it in the update.
266// Creates a new node in the graph to write these blocks and writes the
267// appropriate blob to blobs_fd. Reads and updates blobs_length;
268bool ReadUnwrittenBlocks(const vector<Block>& blocks,
269 int blobs_fd,
270 off_t* blobs_length,
271 const string& image_path,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700272 Vertex* vertex) {
Darin Petkovabe7cc92010-10-08 12:29:32 -0700273 vertex->file_name = "<rootfs-non-file-data>";
274
Andrew de los Reyesef017552010-10-06 17:57:52 -0700275 DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700276 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
277 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
278 ScopedFdCloser image_fd_closer(&image_fd);
279
280 string temp_file_path;
281 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
282 &temp_file_path,
283 NULL));
284
285 FILE* file = fopen(temp_file_path.c_str(), "w");
286 TEST_AND_RETURN_FALSE(file);
287 int err = BZ_OK;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700288
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700289 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
290 file,
291 9, // max compression
292 0, // verbosity
293 0); // default work factor
294 TEST_AND_RETURN_FALSE(err == BZ_OK);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700295
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700296 vector<Extent> extents;
297 vector<Block>::size_type block_count = 0;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700298
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700299 LOG(INFO) << "Appending left over blocks to extents";
300 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
301 if (blocks[i].writer != Vertex::kInvalidIndex)
302 continue;
Andrew de los Reyesef017552010-10-06 17:57:52 -0700303 if (blocks[i].reader != Vertex::kInvalidIndex) {
304 graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
305 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700306 graph_utils::AppendBlockToExtents(&extents, i);
307 block_count++;
308 }
309
310 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
311 // so we arbitrarily set it to 1024 * kBlockSize.
312 vector<char> buf(1024 * kBlockSize);
313
314 LOG(INFO) << "Reading left over blocks";
315 vector<Block>::size_type blocks_copied_count = 0;
316
317 // For each extent in extents, write the data into BZ2_bzWrite which
318 // sends it to an output file.
319 // We use the temporary buffer 'buf' to hold the data, which may be
320 // smaller than the extent, so in that case we have to loop to get
321 // the extent's data (that's the inner while loop).
322 for (vector<Extent>::const_iterator it = extents.begin();
323 it != extents.end(); ++it) {
324 vector<Block>::size_type blocks_read = 0;
325 while (blocks_read < it->num_blocks()) {
326 const int copy_block_cnt =
327 min(buf.size() / kBlockSize,
328 static_cast<vector<char>::size_type>(
329 it->num_blocks() - blocks_read));
330 ssize_t rc = pread(image_fd,
331 &buf[0],
332 copy_block_cnt * kBlockSize,
333 (it->start_block() + blocks_read) * kBlockSize);
334 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
335 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
336 copy_block_cnt * kBlockSize);
337 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
338 TEST_AND_RETURN_FALSE(err == BZ_OK);
339 blocks_read += copy_block_cnt;
340 blocks_copied_count += copy_block_cnt;
341 LOG(INFO) << "progress: " << ((float)blocks_copied_count)/block_count;
342 }
343 }
344 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
345 TEST_AND_RETURN_FALSE(err == BZ_OK);
346 bz_file = NULL;
347 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
348 file = NULL;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700349
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700350 vector<char> compressed_data;
351 LOG(INFO) << "Reading compressed data off disk";
352 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
353 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700354
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700355 // Add node to graph to write these blocks
356 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
357 out_op->set_data_offset(*blobs_length);
358 out_op->set_data_length(compressed_data.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700359 LOG(INFO) << "Rootfs non-data blocks compressed take up "
360 << compressed_data.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700361 *blobs_length += compressed_data.size();
362 out_op->set_dst_length(kBlockSize * block_count);
363 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700364
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700365 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
366 &compressed_data[0],
367 compressed_data.size()));
368 LOG(INFO) << "done with extra blocks";
369 return true;
370}
371
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700372// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700373// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700374bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
375 uint64_t value_be = htobe64(value);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700376 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)) ==
377 sizeof(value_be));
378 return true;
379}
380
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700381// Adds each operation from |graph| to |out_manifest| in the order specified by
382// |order| while building |out_op_name_map| with operation to name
383// mappings. Adds all |kernel_ops| to |out_manifest|. Filters out no-op
384// operations.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700385void InstallOperationsToManifest(
386 const Graph& graph,
387 const vector<Vertex::Index>& order,
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700388 const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700389 DeltaArchiveManifest* out_manifest,
390 OperationNameMap* out_op_name_map) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700391 for (vector<Vertex::Index>::const_iterator it = order.begin();
392 it != order.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700393 const Vertex& vertex = graph[*it];
394 const DeltaArchiveManifest_InstallOperation& add_op = vertex.op;
395 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
396 continue;
397 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700398 DeltaArchiveManifest_InstallOperation* op =
399 out_manifest->add_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700400 *op = add_op;
401 (*out_op_name_map)[op] = &vertex.file_name;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700402 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700403 for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
404 kernel_ops.begin(); it != kernel_ops.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700405 const DeltaArchiveManifest_InstallOperation& add_op = *it;
406 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
407 continue;
408 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700409 DeltaArchiveManifest_InstallOperation* op =
410 out_manifest->add_kernel_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700411 *op = add_op;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700412 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700413}
414
415void CheckGraph(const Graph& graph) {
416 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
417 CHECK(it->op.has_type());
418 }
419}
420
Darin Petkov68c10d12010-10-14 09:24:37 -0700421// Delta compresses a kernel partition |new_kernel_part| with knowledge of the
422// old kernel partition |old_kernel_part|. If |old_kernel_part| is an empty
423// string, generates a full update of the partition.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700424bool DeltaCompressKernelPartition(
425 const string& old_kernel_part,
426 const string& new_kernel_part,
427 vector<DeltaArchiveManifest_InstallOperation>* ops,
428 int blobs_fd,
429 off_t* blobs_length) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700430 LOG(INFO) << "Delta compressing kernel partition...";
Darin Petkov68c10d12010-10-14 09:24:37 -0700431 LOG_IF(INFO, old_kernel_part.empty()) << "Generating full kernel update...";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700432
433 // Add a new install operation
434 ops->resize(1);
435 DeltaArchiveManifest_InstallOperation* op = &(*ops)[0];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700436
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700437 vector<char> data;
Darin Petkov68c10d12010-10-14 09:24:37 -0700438 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_kernel_part,
439 new_kernel_part,
440 &data,
441 op,
442 false));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700443
Darin Petkov68c10d12010-10-14 09:24:37 -0700444 // Write the data
445 if (op->type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
446 op->set_data_offset(*blobs_length);
447 op->set_data_length(data.size());
448 }
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700449
Darin Petkov68c10d12010-10-14 09:24:37 -0700450 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data[0], data.size()));
451 *blobs_length += data.size();
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700452
Darin Petkov68c10d12010-10-14 09:24:37 -0700453 LOG(INFO) << "Done delta compressing kernel partition: "
454 << kInstallOperationTypes[op->type()];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700455 return true;
456}
457
Darin Petkov880335c2010-10-01 15:52:53 -0700458struct DeltaObject {
459 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
460 : name(in_name),
461 type(in_type),
462 size(in_size) {}
463 bool operator <(const DeltaObject& object) const {
Darin Petkovd43d6902010-10-14 11:17:50 -0700464 return (size != object.size) ? (size < object.size) : (name < object.name);
Darin Petkov880335c2010-10-01 15:52:53 -0700465 }
466 string name;
467 int type;
468 off_t size;
469};
470
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700471void ReportPayloadUsage(const DeltaArchiveManifest& manifest,
472 const int64_t manifest_metadata_size,
473 const OperationNameMap& op_name_map) {
Darin Petkov880335c2010-10-01 15:52:53 -0700474 vector<DeltaObject> objects;
475 off_t total_size = 0;
476
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700477 // Rootfs install operations.
478 for (int i = 0; i < manifest.install_operations_size(); ++i) {
479 const DeltaArchiveManifest_InstallOperation& op =
480 manifest.install_operations(i);
481 objects.push_back(DeltaObject(*op_name_map.find(&op)->second,
482 op.type(),
483 op.data_length()));
484 total_size += op.data_length();
Darin Petkov880335c2010-10-01 15:52:53 -0700485 }
486
Darin Petkov880335c2010-10-01 15:52:53 -0700487 // Kernel install operations.
488 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
489 const DeltaArchiveManifest_InstallOperation& op =
490 manifest.kernel_install_operations(i);
491 objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
492 op.type(),
493 op.data_length()));
494 total_size += op.data_length();
495 }
496
Darin Petkov95cf01f2010-10-12 14:59:13 -0700497 objects.push_back(DeltaObject("<manifest-metadata>",
498 -1,
499 manifest_metadata_size));
500 total_size += manifest_metadata_size;
501
Darin Petkov880335c2010-10-01 15:52:53 -0700502 std::sort(objects.begin(), objects.end());
503
504 static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
505 for (vector<DeltaObject>::const_iterator it = objects.begin();
506 it != objects.end(); ++it) {
507 const DeltaObject& object = *it;
508 fprintf(stderr, kFormatString,
509 object.size * 100.0 / total_size,
510 object.size,
Darin Petkov95cf01f2010-10-12 14:59:13 -0700511 object.type >= 0 ? kInstallOperationTypes[object.type] : "-",
Darin Petkov880335c2010-10-01 15:52:53 -0700512 object.name.c_str());
513 }
514 fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
515}
516
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700517} // namespace {}
518
519bool DeltaDiffGenerator::ReadFileToDiff(
520 const string& old_filename,
521 const string& new_filename,
522 vector<char>* out_data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700523 DeltaArchiveManifest_InstallOperation* out_op,
524 bool gather_extents) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700525 // Read new data in
526 vector<char> new_data;
527 TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700528
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700529 TEST_AND_RETURN_FALSE(!new_data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700530
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700531 vector<char> new_data_bz;
532 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
533 CHECK(!new_data_bz.empty());
534
535 vector<char> data; // Data blob that will be written to delta file.
536
537 DeltaArchiveManifest_InstallOperation operation;
538 size_t current_best_size = 0;
539 if (new_data.size() <= new_data_bz.size()) {
540 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
541 current_best_size = new_data.size();
542 data = new_data;
543 } else {
544 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
545 current_best_size = new_data_bz.size();
546 data = new_data_bz;
547 }
548
549 // Do we have an original file to consider?
550 struct stat old_stbuf;
Darin Petkov68c10d12010-10-14 09:24:37 -0700551 bool no_original = old_filename.empty();
552 if (!no_original && 0 != stat(old_filename.c_str(), &old_stbuf)) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700553 // If stat-ing the old file fails, it should be because it doesn't exist.
554 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
Darin Petkov68c10d12010-10-14 09:24:37 -0700555 no_original = true;
556 }
557 if (!no_original) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700558 // Read old data
559 vector<char> old_data;
560 TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
561 if (old_data == new_data) {
562 // No change in data.
563 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
564 current_best_size = 0;
565 data.clear();
566 } else {
567 // Try bsdiff of old to new data
568 vector<char> bsdiff_delta;
569 TEST_AND_RETURN_FALSE(
570 BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
571 CHECK_GT(bsdiff_delta.size(), 0);
572 if (bsdiff_delta.size() < current_best_size) {
573 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
574 current_best_size = bsdiff_delta.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700575
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700576 data = bsdiff_delta;
577 }
578 }
579 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700580
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700581 // Set parameters of the operations
582 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700583
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700584 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
585 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Darin Petkov68c10d12010-10-14 09:24:37 -0700586 if (gather_extents) {
587 TEST_AND_RETURN_FALSE(
588 GatherExtents(old_filename, operation.mutable_src_extents()));
589 } else {
590 Extent* src_extent = operation.add_src_extents();
591 src_extent->set_start_block(0);
592 src_extent->set_num_blocks(
593 (old_stbuf.st_size + kBlockSize - 1) / kBlockSize);
594 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700595 operation.set_src_length(old_stbuf.st_size);
596 }
597
Darin Petkov68c10d12010-10-14 09:24:37 -0700598 if (gather_extents) {
599 TEST_AND_RETURN_FALSE(
600 GatherExtents(new_filename, operation.mutable_dst_extents()));
601 } else {
602 Extent* dst_extent = operation.add_dst_extents();
603 dst_extent->set_start_block(0);
604 dst_extent->set_num_blocks((new_data.size() + kBlockSize - 1) / kBlockSize);
605 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700606 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700607
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700608 out_data->swap(data);
609 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700610
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700611 return true;
612}
613
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700614bool DeltaDiffGenerator::InitializePartitionInfo(bool is_kernel,
615 const string& partition,
616 PartitionInfo* info) {
Darin Petkov7ea32332010-10-13 10:46:11 -0700617 int64_t size = 0;
618 if (is_kernel) {
619 size = utils::FileSize(partition);
620 } else {
621 int block_count = 0, block_size = 0;
622 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(partition,
623 &block_count,
624 &block_size));
625 size = static_cast<int64_t>(block_count) * block_size;
626 }
627 TEST_AND_RETURN_FALSE(size > 0);
Darin Petkov36a58222010-10-07 22:00:09 -0700628 info->set_size(size);
629 OmahaHashCalculator hasher;
Darin Petkov7ea32332010-10-13 10:46:11 -0700630 TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, size) == size);
Darin Petkov36a58222010-10-07 22:00:09 -0700631 TEST_AND_RETURN_FALSE(hasher.Finalize());
632 const vector<char>& hash = hasher.raw_hash();
633 info->set_hash(hash.data(), hash.size());
Darin Petkovd43d6902010-10-14 11:17:50 -0700634 LOG(INFO) << partition << ": size=" << size << " hash=" << hasher.hash();
Darin Petkov36a58222010-10-07 22:00:09 -0700635 return true;
636}
637
638bool InitializePartitionInfos(const string& old_kernel,
639 const string& new_kernel,
640 const string& old_rootfs,
641 const string& new_rootfs,
642 DeltaArchiveManifest* manifest) {
Darin Petkovd43d6902010-10-14 11:17:50 -0700643 if (!old_kernel.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700644 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
645 true,
646 old_kernel,
647 manifest->mutable_old_kernel_info()));
Darin Petkovd43d6902010-10-14 11:17:50 -0700648 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700649 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
650 true,
651 new_kernel,
652 manifest->mutable_new_kernel_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700653 if (!old_rootfs.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700654 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
655 false,
656 old_rootfs,
657 manifest->mutable_old_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700658 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700659 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
660 false,
661 new_rootfs,
662 manifest->mutable_new_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700663 return true;
664}
665
Andrew de los Reyesef017552010-10-06 17:57:52 -0700666namespace {
667
668// Takes a collection (vector or RepeatedPtrField) of Extent and
669// returns a vector of the blocks referenced, in order.
670template<typename T>
671vector<uint64_t> ExpandExtents(const T& extents) {
672 vector<uint64_t> ret;
673 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
674 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700675 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700676 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700677 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700678 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700679 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700680 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700681 }
682 }
683 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700684 return ret;
685}
686
687// Takes a vector of blocks and returns an equivalent vector of Extent
688// objects.
689vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
690 vector<Extent> new_extents;
691 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
692 it != e; ++it) {
693 graph_utils::AppendBlockToExtents(&new_extents, *it);
694 }
695 return new_extents;
696}
697
698} // namespace {}
699
700void DeltaDiffGenerator::SubstituteBlocks(
701 Vertex* vertex,
702 const vector<Extent>& remove_extents,
703 const vector<Extent>& replace_extents) {
704 // First, expand out the blocks that op reads from
705 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700706 {
707 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700708 vector<uint64_t> remove_extents_expanded =
709 ExpandExtents(remove_extents);
710 vector<uint64_t> replace_extents_expanded =
711 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700712 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700713 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700714 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700715 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700716 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
717 }
718 utils::ApplyMap(&read_blocks, conversion);
719 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
720 e = vertex->out_edges.end(); it != e; ++it) {
721 vector<uint64_t> write_before_deps_expanded =
722 ExpandExtents(it->second.write_extents);
723 utils::ApplyMap(&write_before_deps_expanded, conversion);
724 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700725 }
726 }
727 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700728 vertex->op.clear_src_extents();
729 vector<Extent> new_extents = CompressExtents(read_blocks);
730 DeltaDiffGenerator::StoreExtents(new_extents,
731 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700732}
733
734bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700735 const set<Edge>& edges,
736 vector<CutEdgeVertexes>* out_cuts) {
737 DummyExtentAllocator scratch_allocator;
738 vector<CutEdgeVertexes> cuts;
739 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700740
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700741 uint64_t scratch_blocks_used = 0;
742 for (set<Edge>::const_iterator it = edges.begin();
743 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700744 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700745 vector<Extent> old_extents =
746 (*graph)[it->first].out_edges[it->second].extents;
747 // Choose some scratch space
748 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
749 LOG(INFO) << "using " << graph_utils::EdgeWeight(*graph, *it)
750 << " scratch blocks ("
751 << scratch_blocks_used << ")";
Andrew de los Reyesef017552010-10-06 17:57:52 -0700752 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700753 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
754 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700755 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700756 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700757 cuts.back().old_src = it->first;
758 cuts.back().old_dst = it->second;
Darin Petkov36a58222010-10-07 22:00:09 -0700759
Andrew de los Reyesef017552010-10-06 17:57:52 -0700760 EdgeProperties& cut_edge_properties =
761 (*graph)[it->first].out_edges.find(it->second)->second;
762
763 // This should never happen, as we should only be cutting edges between
764 // real file nodes, and write-before relationships are created from
765 // a real file node to a temp copy node:
766 CHECK(cut_edge_properties.write_extents.empty())
767 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700768
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700769 // make node depend on the copy operation
770 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700771 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700772
773 // Set src/dst extents and other proto variables for copy operation
774 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
775 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700776 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700777 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700778 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700779 graph->back().op.mutable_dst_extents());
780 graph->back().op.set_src_length(
781 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
782 graph->back().op.set_dst_length(graph->back().op.src_length());
783
784 // make the dest node read from the scratch space
785 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700786 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700787 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700788 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700789
790 // delete the old edge
791 CHECK_EQ(1, (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700792
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700793 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700794 EdgeProperties write_before_edge_properties;
795 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
796 (*graph)[it->second].out_edges.insert(
797 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700798 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700799 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700800 return true;
801}
802
803// Stores all Extents in 'extents' into 'out'.
804void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700805 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700806 google::protobuf::RepeatedPtrField<Extent>* out) {
807 for (vector<Extent>::const_iterator it = extents.begin();
808 it != extents.end(); ++it) {
809 Extent* new_extent = out->Add();
810 *new_extent = *it;
811 }
812}
813
814// Creates all the edges for the graph. Writers of a block point to
815// readers of the same block. This is because for an edge A->B, B
816// must complete before A executes.
817void DeltaDiffGenerator::CreateEdges(Graph* graph,
818 const vector<Block>& blocks) {
819 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
820 // Blocks with both a reader and writer get an edge
821 if (blocks[i].reader == Vertex::kInvalidIndex ||
822 blocks[i].writer == Vertex::kInvalidIndex)
823 continue;
824 // Don't have a node depend on itself
825 if (blocks[i].reader == blocks[i].writer)
826 continue;
827 // See if there's already an edge we can add onto
828 Vertex::EdgeMap::iterator edge_it =
829 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
830 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
831 // No existing edge. Create one
832 (*graph)[blocks[i].writer].out_edges.insert(
833 make_pair(blocks[i].reader, EdgeProperties()));
834 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700835 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700836 }
837 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
838 }
839}
840
Andrew de los Reyesef017552010-10-06 17:57:52 -0700841namespace {
842
843class SortCutsByTopoOrderLess {
844 public:
845 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
846 : table_(table) {}
847 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
848 return table_[a.old_dst] < table_[b.old_dst];
849 }
850 private:
851 vector<vector<Vertex::Index>::size_type>& table_;
852};
853
854} // namespace {}
855
856void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
857 vector<Vertex::Index>& op_indexes,
858 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
859 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
860 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
861 i != e; ++i) {
862 Vertex::Index node = op_indexes[i];
863 if (table.size() < (node + 1)) {
864 table.resize(node + 1);
865 }
866 table[node] = i;
867 }
868 reverse_op_indexes->swap(table);
869}
870
871void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
872 vector<CutEdgeVertexes>* cuts) {
873 // first, make a reverse lookup table.
874 vector<vector<Vertex::Index>::size_type> table;
875 GenerateReverseTopoOrderMap(op_indexes, &table);
876 SortCutsByTopoOrderLess less(table);
877 sort(cuts->begin(), cuts->end(), less);
878}
879
880void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
881 vector<Vertex::Index>* op_indexes) {
882 vector<Vertex::Index> ret;
883 vector<Vertex::Index> full_ops;
884 ret.reserve(op_indexes->size());
885 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
886 ++i) {
887 DeltaArchiveManifest_InstallOperation_Type type =
888 (*graph)[(*op_indexes)[i]].op.type();
889 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
890 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
891 full_ops.push_back((*op_indexes)[i]);
892 } else {
893 ret.push_back((*op_indexes)[i]);
894 }
895 }
896 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
897 << (full_ops.size() + ret.size()) << " total ops.";
898 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
899 op_indexes->swap(ret);
900}
901
902namespace {
903
904template<typename T>
905bool TempBlocksExistInExtents(const T& extents) {
906 for (int i = 0, e = extents.size(); i < e; ++i) {
907 Extent extent = graph_utils::GetElement(extents, i);
908 uint64_t start = extent.start_block();
909 uint64_t num = extent.num_blocks();
910 if (start == kSparseHole)
911 continue;
912 if (start >= kTempBlockStart ||
913 (start + num) >= kTempBlockStart) {
914 LOG(ERROR) << "temp block!";
915 LOG(ERROR) << "start: " << start << ", num: " << num;
916 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
917 LOG(ERROR) << "returning true";
918 return true;
919 }
920 // check for wrap-around, which would be a bug:
921 CHECK(start <= (start + num));
922 }
923 return false;
924}
925
926} // namespace {}
927
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700928// Returns true if |op| is a no-op operation that doesn't do any useful work
929// (e.g., a move operation that copies blocks onto themselves).
930bool DeltaDiffGenerator::IsNoopOperation(
931 const DeltaArchiveManifest_InstallOperation& op) {
932 return (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE &&
933 ExpandExtents(op.src_extents()) == ExpandExtents(op.dst_extents()));
934}
935
Andrew de los Reyesef017552010-10-06 17:57:52 -0700936bool DeltaDiffGenerator::AssignTempBlocks(
937 Graph* graph,
938 const string& new_root,
939 int data_fd,
940 off_t* data_file_size,
941 vector<Vertex::Index>* op_indexes,
942 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
943 vector<CutEdgeVertexes>& cuts) {
944 CHECK(!cuts.empty());
945 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
946 true ; --i) {
947 LOG(INFO) << "Fixing temp blocks in cut " << i
948 << ": old dst: " << cuts[i].old_dst << " new vertex: "
949 << cuts[i].new_vertex;
950 const uint64_t blocks_needed =
951 graph_utils::BlocksInExtents(cuts[i].tmp_extents);
952 LOG(INFO) << "Scanning for usable blocks (" << blocks_needed << " needed)";
953 // For now, just look for a single op w/ sufficient blocks, not
954 // considering blocks from outgoing read-before deps.
955 Vertex::Index node = cuts[i].old_dst;
956 DeltaArchiveManifest_InstallOperation_Type node_type =
957 (*graph)[node].op.type();
958 if (node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
959 node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
960 LOG(INFO) << "This was already converted to full, so skipping.";
961 // Delete the temp node and pointer to it from old src
962 if (!(*graph)[cuts[i].old_src].out_edges.erase(cuts[i].new_vertex)) {
963 LOG(INFO) << "Odd. node " << cuts[i].old_src << " didn't point to "
964 << cuts[i].new_vertex;
965 }
966 (*graph)[cuts[i].new_vertex].valid = false;
967 vector<Vertex::Index>::size_type new_topo_idx =
968 (*reverse_op_indexes)[cuts[i].new_vertex];
969 op_indexes->erase(op_indexes->begin() + new_topo_idx);
970 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
971 continue;
972 }
973 bool found_node = false;
974 for (vector<Vertex::Index>::size_type j = (*reverse_op_indexes)[node] + 1,
975 je = op_indexes->size(); j < je; ++j) {
976 Vertex::Index test_node = (*op_indexes)[j];
977 // See if this node has sufficient blocks
978 ExtentRanges ranges;
979 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
980 ranges.SubtractExtent(ExtentForRange(
981 kTempBlockStart, kSparseHole - kTempBlockStart));
982 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
983 // For now, for simplicity, subtract out all blocks in read-before
984 // dependencies.
985 for (Vertex::EdgeMap::const_iterator edge_i =
986 (*graph)[test_node].out_edges.begin(),
987 edge_e = (*graph)[test_node].out_edges.end();
988 edge_i != edge_e; ++edge_i) {
989 ranges.SubtractExtents(edge_i->second.extents);
990 }
Darin Petkov36a58222010-10-07 22:00:09 -0700991
Andrew de los Reyesef017552010-10-06 17:57:52 -0700992 uint64_t blocks_found = ranges.blocks();
993 if (blocks_found < blocks_needed) {
994 if (blocks_found > 0)
995 LOG(INFO) << "insufficient blocks found in topo node " << j
996 << " (node " << (*op_indexes)[j] << "). Found only "
997 << blocks_found;
998 continue;
999 }
1000 found_node = true;
1001 LOG(INFO) << "Found sufficient blocks in topo node " << j
1002 << " (node " << (*op_indexes)[j] << ")";
1003 // Sub in the blocks, and make the node supplying the blocks
1004 // depend on old_dst.
1005 vector<Extent> real_extents =
1006 ranges.GetExtentsForBlockCount(blocks_needed);
Darin Petkov36a58222010-10-07 22:00:09 -07001007
Andrew de los Reyesef017552010-10-06 17:57:52 -07001008 // Fix the old dest node w/ the real blocks
1009 SubstituteBlocks(&(*graph)[node],
1010 cuts[i].tmp_extents,
1011 real_extents);
Darin Petkov36a58222010-10-07 22:00:09 -07001012
Andrew de los Reyesef017552010-10-06 17:57:52 -07001013 // Fix the new node w/ the real blocks. Since the new node is just a
1014 // copy operation, we can replace all the dest extents w/ the real
1015 // blocks.
1016 DeltaArchiveManifest_InstallOperation *op =
1017 &(*graph)[cuts[i].new_vertex].op;
1018 op->clear_dst_extents();
1019 StoreExtents(real_extents, op->mutable_dst_extents());
Darin Petkov36a58222010-10-07 22:00:09 -07001020
Andrew de los Reyesef017552010-10-06 17:57:52 -07001021 // Add an edge from the real-block supplier to the old dest block.
1022 graph_utils::AddReadBeforeDepExtents(&(*graph)[test_node],
1023 node,
1024 real_extents);
1025 break;
1026 }
1027 if (!found_node) {
1028 // convert to full op
1029 LOG(WARNING) << "Failed to find enough temp blocks for cut " << i
1030 << " with old dest (graph node " << node
1031 << "). Converting to a full op, at the expense of a "
1032 << "good compression ratio.";
1033 TEST_AND_RETURN_FALSE(ConvertCutToFullOp(graph,
1034 cuts[i],
1035 new_root,
1036 data_fd,
1037 data_file_size));
1038 // move the full op to the back
1039 vector<Vertex::Index> new_op_indexes;
1040 for (vector<Vertex::Index>::const_iterator iter_i = op_indexes->begin(),
1041 iter_e = op_indexes->end(); iter_i != iter_e; ++iter_i) {
1042 if ((*iter_i == cuts[i].old_dst) || (*iter_i == cuts[i].new_vertex))
1043 continue;
1044 new_op_indexes.push_back(*iter_i);
1045 }
1046 new_op_indexes.push_back(cuts[i].old_dst);
1047 op_indexes->swap(new_op_indexes);
Darin Petkov36a58222010-10-07 22:00:09 -07001048
Andrew de los Reyesef017552010-10-06 17:57:52 -07001049 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
1050 }
1051 if (i == e) {
1052 // break out of for() loop
1053 break;
1054 }
1055 }
1056 return true;
1057}
1058
1059bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1060 size_t idx = 0;
1061 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1062 ++it, ++idx) {
1063 if (!it->valid)
1064 continue;
1065 const DeltaArchiveManifest_InstallOperation& op = it->op;
1066 if (TempBlocksExistInExtents(op.dst_extents()) ||
1067 TempBlocksExistInExtents(op.src_extents())) {
1068 LOG(INFO) << "bad extents in node " << idx;
1069 LOG(INFO) << "so yeah";
1070 return false;
1071 }
1072
1073 // Check out-edges:
1074 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
1075 je = it->out_edges.end(); jt != je; ++jt) {
1076 if (TempBlocksExistInExtents(jt->second.extents) ||
1077 TempBlocksExistInExtents(jt->second.write_extents)) {
1078 LOG(INFO) << "bad out edge in node " << idx;
1079 LOG(INFO) << "so yeah";
1080 return false;
1081 }
1082 }
1083 }
1084 return true;
1085}
1086
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001087bool DeltaDiffGenerator::ReorderDataBlobs(
1088 DeltaArchiveManifest* manifest,
1089 const std::string& data_blobs_path,
1090 const std::string& new_data_blobs_path) {
1091 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1092 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1093 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001094
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001095 DirectFileWriter writer;
1096 TEST_AND_RETURN_FALSE(
1097 writer.Open(new_data_blobs_path.c_str(),
1098 O_WRONLY | O_TRUNC | O_CREAT,
1099 0644) == 0);
1100 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001101 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001102
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001103 for (int i = 0; i < (manifest->install_operations_size() +
1104 manifest->kernel_install_operations_size()); i++) {
1105 DeltaArchiveManifest_InstallOperation* op = NULL;
1106 if (i < manifest->install_operations_size()) {
1107 op = manifest->mutable_install_operations(i);
1108 } else {
1109 op = manifest->mutable_kernel_install_operations(
1110 i - manifest->install_operations_size());
1111 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001112 if (!op->has_data_offset())
1113 continue;
1114 CHECK(op->has_data_length());
1115 vector<char> buf(op->data_length());
1116 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1117 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1118
1119 op->set_data_offset(out_file_size);
1120 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()) ==
1121 static_cast<ssize_t>(buf.size()));
1122 out_file_size += buf.size();
1123 }
1124 return true;
1125}
1126
Andrew de los Reyesef017552010-10-06 17:57:52 -07001127bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1128 const CutEdgeVertexes& cut,
1129 const string& new_root,
1130 int data_fd,
1131 off_t* data_file_size) {
1132 // Drop all incoming edges, keep all outgoing edges
Darin Petkov36a58222010-10-07 22:00:09 -07001133
Andrew de los Reyesef017552010-10-06 17:57:52 -07001134 // Keep all outgoing edges
1135 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1136 graph_utils::DropWriteBeforeDeps(&out_edges);
Darin Petkov36a58222010-10-07 22:00:09 -07001137
Andrew de los Reyesef017552010-10-06 17:57:52 -07001138 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1139 cut.old_dst,
1140 NULL,
1141 "/-!@:&*nonexistent_path",
1142 new_root,
1143 (*graph)[cut.old_dst].file_name,
1144 data_fd,
1145 data_file_size));
Darin Petkov36a58222010-10-07 22:00:09 -07001146
Andrew de los Reyesef017552010-10-06 17:57:52 -07001147 (*graph)[cut.old_dst].out_edges = out_edges;
1148
1149 // Right now we don't have doubly-linked edges, so we have to scan
1150 // the whole graph.
1151 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1152
1153 // Delete temp node
1154 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1155 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1156 (*graph)[cut.old_dst].out_edges.end());
1157 (*graph)[cut.new_vertex].valid = false;
1158 return true;
1159}
1160
1161bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1162 const string& new_root,
1163 int fd,
1164 off_t* data_file_size,
1165 vector<Vertex::Index>* final_order) {
1166 CycleBreaker cycle_breaker;
1167 LOG(INFO) << "Finding cycles...";
1168 set<Edge> cut_edges;
1169 cycle_breaker.BreakCycles(*graph, &cut_edges);
1170 LOG(INFO) << "done finding cycles";
1171 CheckGraph(*graph);
1172
1173 // Calculate number of scratch blocks needed
1174
1175 LOG(INFO) << "Cutting cycles...";
1176 vector<CutEdgeVertexes> cuts;
1177 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1178 LOG(INFO) << "done cutting cycles";
1179 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1180 CheckGraph(*graph);
1181
1182 LOG(INFO) << "Creating initial topological order...";
1183 TopologicalSort(*graph, final_order);
1184 LOG(INFO) << "done with initial topo order";
1185 CheckGraph(*graph);
1186
1187 LOG(INFO) << "Moving full ops to the back";
1188 MoveFullOpsToBack(graph, final_order);
1189 LOG(INFO) << "done moving full ops to back";
1190
1191 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1192 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1193
1194 if (!cuts.empty())
1195 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1196 new_root,
1197 fd,
1198 data_file_size,
1199 final_order,
1200 &inverse_final_order,
1201 cuts));
1202 LOG(INFO) << "Making sure all temp blocks have been allocated";
1203 graph_utils::DumpGraph(*graph);
1204 CHECK(NoTempBlocksRemain(*graph));
1205 LOG(INFO) << "done making sure all temp blocks are allocated";
1206 return true;
1207}
1208
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001209bool DeltaDiffGenerator::ReadFullUpdateFromDisk(
1210 Graph* graph,
1211 const std::string& new_kernel_part,
1212 const std::string& new_image,
Darin Petkov7ea32332010-10-13 10:46:11 -07001213 off_t image_size,
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001214 int fd,
1215 off_t* data_file_size,
1216 off_t chunk_size,
1217 vector<DeltaArchiveManifest_InstallOperation>* kernel_ops,
1218 std::vector<Vertex::Index>* final_order) {
1219 TEST_AND_RETURN_FALSE(chunk_size > 0);
1220 TEST_AND_RETURN_FALSE((chunk_size % kBlockSize) == 0);
Darin Petkov36a58222010-10-07 22:00:09 -07001221
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001222 // Get the sizes early in the function, so we can fail fast if the user
1223 // passed us bad paths.
Darin Petkov7ea32332010-10-13 10:46:11 -07001224 TEST_AND_RETURN_FALSE(image_size >= 0 &&
1225 image_size <= utils::FileSize(new_image));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001226 const off_t kernel_size = utils::FileSize(new_kernel_part);
1227 TEST_AND_RETURN_FALSE(kernel_size >= 0);
1228
1229 off_t part_sizes[] = { image_size, kernel_size };
1230 string paths[] = { new_image, new_kernel_part };
1231
1232 for (int partition = 0; partition < 2; ++partition) {
1233 const string& path = paths[partition];
1234 LOG(INFO) << "compressing " << path;
1235
1236 int in_fd = open(path.c_str(), O_RDONLY, 0);
1237 TEST_AND_RETURN_FALSE(in_fd >= 0);
1238 ScopedFdCloser in_fd_closer(&in_fd);
1239
1240 for (off_t bytes_left = part_sizes[partition], counter = 0, offset = 0;
1241 bytes_left > 0;
1242 bytes_left -= chunk_size, ++counter, offset += chunk_size) {
1243 LOG(INFO) << "offset = " << offset;
1244 DeltaArchiveManifest_InstallOperation* op = NULL;
1245 if (partition == 0) {
1246 graph->resize(graph->size() + 1);
1247 graph->back().file_name = path + StringPrintf("-%" PRIi64, counter);
1248 op = &graph->back().op;
1249 final_order->push_back(graph->size() - 1);
1250 } else {
1251 kernel_ops->resize(kernel_ops->size() + 1);
1252 op = &kernel_ops->back();
1253 }
1254 LOG(INFO) << "have an op";
Darin Petkov36a58222010-10-07 22:00:09 -07001255
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001256 vector<char> buf(min(bytes_left, chunk_size));
1257 LOG(INFO) << "buf size: " << buf.size();
1258 ssize_t bytes_read = -1;
Darin Petkov36a58222010-10-07 22:00:09 -07001259
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001260 TEST_AND_RETURN_FALSE(utils::PReadAll(
1261 in_fd, &buf[0], buf.size(), offset, &bytes_read));
1262 TEST_AND_RETURN_FALSE(bytes_read == static_cast<ssize_t>(buf.size()));
Darin Petkov36a58222010-10-07 22:00:09 -07001263
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001264 vector<char> buf_compressed;
Darin Petkov36a58222010-10-07 22:00:09 -07001265
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001266 TEST_AND_RETURN_FALSE(BzipCompress(buf, &buf_compressed));
1267 const bool compress = buf_compressed.size() < buf.size();
1268 const vector<char>& use_buf = compress ? buf_compressed : buf;
1269 if (compress) {
1270 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1271 } else {
1272 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1273 }
1274 op->set_data_offset(*data_file_size);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001275 TEST_AND_RETURN_FALSE(utils::WriteAll(fd, &use_buf[0], use_buf.size()));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001276 *data_file_size += use_buf.size();
1277 op->set_data_length(use_buf.size());
1278 Extent* dst_extent = op->add_dst_extents();
1279 dst_extent->set_start_block(offset / kBlockSize);
1280 dst_extent->set_num_blocks(chunk_size / kBlockSize);
1281 }
1282 }
1283
1284 return true;
1285}
1286
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001287bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1288 const string& old_root,
1289 const string& old_image,
1290 const string& new_root,
1291 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001292 const string& old_kernel_part,
1293 const string& new_kernel_part,
1294 const string& output_path,
1295 const string& private_key_path) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001296 int old_image_block_count = 0, old_image_block_size = 0;
1297 int new_image_block_count = 0, new_image_block_size = 0;
1298 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(new_image,
1299 &new_image_block_count,
1300 &new_image_block_size));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001301 if (!old_image.empty()) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001302 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(old_image,
1303 &old_image_block_count,
1304 &old_image_block_size));
1305 TEST_AND_RETURN_FALSE(old_image_block_size == new_image_block_size);
1306 LOG_IF(WARNING, old_image_block_count != new_image_block_count)
1307 << "Old and new images have different block counts.";
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001308 }
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001309 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001310 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1311
Darin Petkov7ea32332010-10-13 10:46:11 -07001312 vector<Block> blocks(max(old_image_block_count, new_image_block_count));
1313 LOG(INFO) << "Invalid block index: " << Vertex::kInvalidIndex;
1314 LOG(INFO) << "Block count: " << blocks.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001315 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1316 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1317 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1318 }
1319 Graph graph;
1320 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001321
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001322 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
1323 string temp_file_path;
1324 off_t data_file_size = 0;
1325
1326 LOG(INFO) << "Reading files...";
1327
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001328 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1329
Andrew de los Reyesef017552010-10-06 17:57:52 -07001330 vector<Vertex::Index> final_order;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001331 {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001332 int fd;
1333 TEST_AND_RETURN_FALSE(
1334 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
1335 TEST_AND_RETURN_FALSE(fd >= 0);
1336 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001337 if (!old_image.empty()) {
1338 // Delta update
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001339
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001340 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1341 &blocks,
1342 old_root,
1343 new_root,
1344 fd,
1345 &data_file_size));
1346 LOG(INFO) << "done reading normal files";
1347 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001348
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001349 graph.resize(graph.size() + 1);
1350 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1351 fd,
1352 &data_file_size,
1353 new_image,
1354 &graph.back()));
1355
1356 // Read kernel partition
1357 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1358 new_kernel_part,
1359 &kernel_ops,
1360 fd,
1361 &data_file_size));
1362
1363 LOG(INFO) << "done reading kernel";
1364 CheckGraph(graph);
1365
1366 LOG(INFO) << "Creating edges...";
1367 CreateEdges(&graph, blocks);
1368 LOG(INFO) << "Done creating edges";
1369 CheckGraph(graph);
1370
1371 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1372 new_root,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001373 fd,
1374 &data_file_size,
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001375 &final_order));
1376 } else {
1377 // Full update
Darin Petkov7ea32332010-10-13 10:46:11 -07001378 off_t new_image_size =
1379 static_cast<off_t>(new_image_block_count) * new_image_block_size;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001380 TEST_AND_RETURN_FALSE(ReadFullUpdateFromDisk(&graph,
1381 new_kernel_part,
1382 new_image,
Darin Petkov7ea32332010-10-13 10:46:11 -07001383 new_image_size,
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001384 fd,
1385 &data_file_size,
1386 kFullUpdateChunkSize,
1387 &kernel_ops,
1388 &final_order));
1389 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001390 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001391
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001392 // Convert to protobuf Manifest object
1393 DeltaArchiveManifest manifest;
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001394 OperationNameMap op_name_map;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001395 CheckGraph(graph);
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001396 InstallOperationsToManifest(graph,
1397 final_order,
1398 kernel_ops,
1399 &manifest,
1400 &op_name_map);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001401 CheckGraph(graph);
1402 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001403
1404 // Reorder the data blobs with the newly ordered manifest
1405 string ordered_blobs_path;
1406 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1407 "/tmp/CrAU_temp_data.ordered.XXXXXX",
1408 &ordered_blobs_path,
1409 false));
1410 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1411 temp_file_path,
1412 ordered_blobs_path));
1413
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001414 // Check that install op blobs are in order.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001415 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001416 {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001417 for (int i = 0; i < (manifest.install_operations_size() +
1418 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001419 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001420 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001421 manifest.mutable_install_operations(i) :
1422 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001423 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001424 if (op->has_data_offset()) {
1425 if (op->data_offset() != next_blob_offset) {
1426 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001427 << next_blob_offset;
1428 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001429 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001430 }
1431 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001432 }
1433
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001434 // Signatures appear at the end of the blobs. Note the offset in the
1435 // manifest
1436 if (!private_key_path.empty()) {
1437 LOG(INFO) << "Making room for signature in file";
1438 manifest.set_signatures_offset(next_blob_offset);
1439 LOG(INFO) << "set? " << manifest.has_signatures_offset();
1440 // Add a dummy op at the end to appease older clients
1441 DeltaArchiveManifest_InstallOperation* dummy_op =
1442 manifest.add_kernel_install_operations();
1443 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1444 dummy_op->set_data_offset(next_blob_offset);
1445 manifest.set_signatures_offset(next_blob_offset);
1446 uint64_t signature_blob_length = 0;
1447 TEST_AND_RETURN_FALSE(
1448 PayloadSigner::SignatureBlobLength(private_key_path,
1449 &signature_blob_length));
1450 dummy_op->set_data_length(signature_blob_length);
1451 manifest.set_signatures_size(signature_blob_length);
1452 Extent* dummy_extent = dummy_op->add_dst_extents();
1453 // Tell the dummy op to write this data to a big sparse hole
1454 dummy_extent->set_start_block(kSparseHole);
1455 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1456 kBlockSize);
1457 }
1458
Darin Petkov36a58222010-10-07 22:00:09 -07001459 TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1460 new_kernel_part,
1461 old_image,
1462 new_image,
1463 &manifest));
1464
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001465 // Serialize protobuf
1466 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001467
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001468 CheckGraph(graph);
1469 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1470 CheckGraph(graph);
1471
1472 LOG(INFO) << "Writing final delta file header...";
1473 DirectFileWriter writer;
1474 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1475 O_WRONLY | O_CREAT | O_TRUNC,
1476 0644) == 0);
1477 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001478
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001479 // Write header
1480 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)) ==
Andrew de los Reyes08c4e272010-04-15 14:02:17 -07001481 static_cast<ssize_t>(strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001482
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001483 // Write version number
1484 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001485
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001486 // Write protobuf length
1487 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1488 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001489
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001490 // Write protobuf
1491 LOG(INFO) << "Writing final delta file protobuf... "
1492 << serialized_manifest.size();
1493 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
1494 serialized_manifest.size()) ==
1495 static_cast<ssize_t>(serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001496
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001497 // Append the data blobs
1498 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001499 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001500 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1501 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1502 for (;;) {
1503 char buf[kBlockSize];
1504 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1505 if (0 == rc) {
1506 // EOF
1507 break;
1508 }
1509 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
1510 TEST_AND_RETURN_FALSE(writer.Write(buf, rc) == rc);
1511 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001512
1513 // Write signature blob.
1514 if (!private_key_path.empty()) {
1515 LOG(INFO) << "Signing the update...";
1516 vector<char> signature_blob;
1517 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(output_path,
1518 private_key_path,
1519 &signature_blob));
1520 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
1521 signature_blob.size()) ==
1522 static_cast<ssize_t>(signature_blob.size()));
1523 }
1524
Darin Petkov95cf01f2010-10-12 14:59:13 -07001525 int64_t manifest_metadata_size =
1526 strlen(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001527 ReportPayloadUsage(manifest, manifest_metadata_size, op_name_map);
Darin Petkov880335c2010-10-01 15:52:53 -07001528
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001529 LOG(INFO) << "All done. Successfully created delta file.";
1530 return true;
1531}
1532
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001533const char* const kBsdiffPath = "/usr/bin/bsdiff";
1534const char* const kBspatchPath = "/usr/bin/bspatch";
1535const char* const kDeltaMagic = "CrAU";
1536
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001537}; // namespace chromeos_update_engine