blob: 50db931761101cc238f15b426f46cc3af5ed5deb [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"
Darin Petkov7a22d792010-11-08 14:10:00 -080030#include "update_engine/full_update_generator.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070031#include "update_engine/graph_types.h"
32#include "update_engine/graph_utils.h"
Darin Petkov36a58222010-10-07 22:00:09 -070033#include "update_engine/omaha_hash_calculator.h"
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -070034#include "update_engine/payload_signer.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070035#include "update_engine/subprocess.h"
36#include "update_engine/topological_sort.h"
37#include "update_engine/update_metadata.pb.h"
38#include "update_engine/utils.h"
39
40using std::make_pair;
Andrew de los Reyesef017552010-10-06 17:57:52 -070041using std::map;
Andrew de los Reyes3270f742010-07-15 22:28:14 -070042using std::max;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070043using std::min;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -070044using std::pair;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070045using std::set;
46using std::string;
47using std::vector;
48
49namespace chromeos_update_engine {
50
51typedef DeltaDiffGenerator::Block Block;
Darin Petkov9fa7ec52010-10-18 11:45:23 -070052typedef map<const DeltaArchiveManifest_InstallOperation*,
53 const string*> OperationNameMap;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070054
55namespace {
Andrew de los Reyes27f7d372010-10-07 11:26:07 -070056const size_t kBlockSize = 4096; // bytes
Darin Petkov9eadd642010-10-14 15:20:57 -070057const size_t kRootFSPartitionSize = 1 * 1024 * 1024 * 1024; // bytes
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070058const uint64_t kVersionNumber = 1;
Darin Petkov9eadd642010-10-14 15:20:57 -070059const uint64_t kFullUpdateChunkSize = 1024 * 1024; // bytes
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070060
Darin Petkov68c10d12010-10-14 09:24:37 -070061static const char* kInstallOperationTypes[] = {
62 "REPLACE",
63 "REPLACE_BZ",
64 "MOVE",
65 "BSDIFF"
66};
67
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070068// Stores all Extents for a file into 'out'. Returns true on success.
69bool GatherExtents(const string& path,
70 google::protobuf::RepeatedPtrField<Extent>* out) {
71 vector<Extent> extents;
72 TEST_AND_RETURN_FALSE(extent_mapper::ExtentsForFileFibmap(path, &extents));
73 DeltaDiffGenerator::StoreExtents(extents, out);
74 return true;
75}
76
77// Runs the bsdiff tool on two files and returns the resulting delta in
78// 'out'. Returns true on success.
79bool BsdiffFiles(const string& old_file,
80 const string& new_file,
81 vector<char>* out) {
82 const string kPatchFile = "/tmp/delta.patchXXXXXX";
83 string patch_file_path;
84
85 TEST_AND_RETURN_FALSE(
86 utils::MakeTempFile(kPatchFile, &patch_file_path, NULL));
87
88 vector<string> cmd;
89 cmd.push_back(kBsdiffPath);
90 cmd.push_back(old_file);
91 cmd.push_back(new_file);
92 cmd.push_back(patch_file_path);
93
94 int rc = 1;
95 vector<char> patch_file;
96 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc));
97 TEST_AND_RETURN_FALSE(rc == 0);
98 TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
99 unlink(patch_file_path.c_str());
100 return true;
101}
102
103// The blocks vector contains a reader and writer for each block on the
104// filesystem that's being in-place updated. We populate the reader/writer
105// fields of blocks by calling this function.
106// For each block in 'operation' that is read or written, find that block
107// in 'blocks' and set the reader/writer field to the vertex passed.
108// 'graph' is not strictly necessary, but useful for printing out
109// error messages.
110bool AddInstallOpToBlocksVector(
111 const DeltaArchiveManifest_InstallOperation& operation,
112 vector<Block>* blocks,
113 const Graph& graph,
114 Vertex::Index vertex) {
115 LOG(INFO) << "AddInstallOpToBlocksVector(" << vertex << "), "
116 << graph[vertex].file_name;
117 // See if this is already present.
118 TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700119
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700120 enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
121 for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
122 const int extents_size =
123 (field == READER) ? operation.src_extents_size() :
124 operation.dst_extents_size();
125 const char* past_participle = (field == READER) ? "read" : "written";
126 const google::protobuf::RepeatedPtrField<Extent>& extents =
127 (field == READER) ? operation.src_extents() : operation.dst_extents();
128 Vertex::Index Block::*access_type =
129 (field == READER) ? &Block::reader : &Block::writer;
130
131 for (int i = 0; i < extents_size; i++) {
132 const Extent& extent = extents.Get(i);
133 if (extent.start_block() == kSparseHole) {
134 // Hole in sparse file. skip
135 continue;
136 }
137 for (uint64_t block = extent.start_block();
138 block < (extent.start_block() + extent.num_blocks()); block++) {
139 LOG(INFO) << "ext: " << i << " block: " << block;
140 if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
141 LOG(FATAL) << "Block " << block << " is already "
142 << past_participle << " by "
143 << (*blocks)[block].*access_type << "("
144 << graph[(*blocks)[block].*access_type].file_name
145 << ") and also " << vertex << "("
146 << graph[vertex].file_name << ")";
147 }
148 (*blocks)[block].*access_type = vertex;
149 }
150 }
151 }
152 return true;
153}
154
Andrew de los Reyesef017552010-10-06 17:57:52 -0700155// For a given regular file which must exist at new_root + path, and
156// may exist at old_root + path, creates a new InstallOperation and
157// adds it to the graph. Also, populates the |blocks| array as
158// necessary, if |blocks| is non-NULL. Also, writes the data
159// necessary to send the file down to the client into data_fd, which
160// has length *data_file_size. *data_file_size is updated
161// appropriately. If |existing_vertex| is no kInvalidIndex, use that
162// rather than allocating a new vertex. Returns true on success.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700163bool DeltaReadFile(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700164 Vertex::Index existing_vertex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700165 vector<Block>* blocks,
166 const string& old_root,
167 const string& new_root,
168 const string& path, // within new_root
169 int data_fd,
170 off_t* data_file_size) {
171 vector<char> data;
172 DeltaArchiveManifest_InstallOperation operation;
173
174 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_root + path,
175 new_root + path,
176 &data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700177 &operation,
178 true));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700179
180 // Write the data
181 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
182 operation.set_data_offset(*data_file_size);
183 operation.set_data_length(data.size());
184 }
185
186 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
187 *data_file_size += data.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700188
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700189 // Now, insert into graph and blocks vector
Andrew de los Reyesef017552010-10-06 17:57:52 -0700190 Vertex::Index vertex = existing_vertex;
191 if (vertex == Vertex::kInvalidIndex) {
192 graph->resize(graph->size() + 1);
193 vertex = graph->size() - 1;
194 }
195 (*graph)[vertex].op = operation;
196 CHECK((*graph)[vertex].op.has_type());
197 (*graph)[vertex].file_name = path;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700198
Andrew de los Reyesef017552010-10-06 17:57:52 -0700199 if (blocks)
200 TEST_AND_RETURN_FALSE(AddInstallOpToBlocksVector((*graph)[vertex].op,
201 blocks,
202 *graph,
203 vertex));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700204 return true;
205}
206
207// For each regular file within new_root, creates a node in the graph,
208// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
209// and writes any necessary data to the end of data_fd.
210bool DeltaReadFiles(Graph* graph,
211 vector<Block>* blocks,
212 const string& old_root,
213 const string& new_root,
214 int data_fd,
215 off_t* data_file_size) {
216 set<ino_t> visited_inodes;
217 for (FilesystemIterator fs_iter(new_root,
218 utils::SetWithValue<string>("/lost+found"));
219 !fs_iter.IsEnd(); fs_iter.Increment()) {
220 if (!S_ISREG(fs_iter.GetStat().st_mode))
221 continue;
222
223 // Make sure we visit each inode only once.
224 if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
225 continue;
226 visited_inodes.insert(fs_iter.GetStat().st_ino);
227 if (fs_iter.GetStat().st_size == 0)
228 continue;
229
230 LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700231
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700232 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700233 Vertex::kInvalidIndex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700234 blocks,
235 old_root,
236 new_root,
237 fs_iter.GetPartialPath(),
238 data_fd,
239 data_file_size));
240 }
241 return true;
242}
243
Andrew de los Reyesef017552010-10-06 17:57:52 -0700244// This class allocates non-existent temp blocks, starting from
245// kTempBlockStart. Other code is responsible for converting these
246// temp blocks into real blocks, as the client can't read or write to
247// these blocks.
248class DummyExtentAllocator {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700249 public:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700250 explicit DummyExtentAllocator()
251 : next_block_(kTempBlockStart) {}
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700252 vector<Extent> Allocate(const uint64_t block_count) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700253 vector<Extent> ret(1);
254 ret[0].set_start_block(next_block_);
255 ret[0].set_num_blocks(block_count);
256 next_block_ += block_count;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700257 return ret;
258 }
259 private:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700260 uint64_t next_block_;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700261};
262
263// Reads blocks from image_path that are not yet marked as being written
264// in the blocks array. These blocks that remain are non-file-data blocks.
265// In the future we might consider intelligent diffing between this data
266// and data in the previous image, but for now we just bzip2 compress it
267// and include it in the update.
268// Creates a new node in the graph to write these blocks and writes the
269// appropriate blob to blobs_fd. Reads and updates blobs_length;
270bool ReadUnwrittenBlocks(const vector<Block>& blocks,
271 int blobs_fd,
272 off_t* blobs_length,
273 const string& image_path,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700274 Vertex* vertex) {
Darin Petkovabe7cc92010-10-08 12:29:32 -0700275 vertex->file_name = "<rootfs-non-file-data>";
276
Andrew de los Reyesef017552010-10-06 17:57:52 -0700277 DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700278 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
279 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
280 ScopedFdCloser image_fd_closer(&image_fd);
281
282 string temp_file_path;
283 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
284 &temp_file_path,
285 NULL));
286
287 FILE* file = fopen(temp_file_path.c_str(), "w");
288 TEST_AND_RETURN_FALSE(file);
289 int err = BZ_OK;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700290
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700291 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
292 file,
293 9, // max compression
294 0, // verbosity
295 0); // default work factor
296 TEST_AND_RETURN_FALSE(err == BZ_OK);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700297
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700298 vector<Extent> extents;
299 vector<Block>::size_type block_count = 0;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700300
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700301 LOG(INFO) << "Appending left over blocks to extents";
302 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
303 if (blocks[i].writer != Vertex::kInvalidIndex)
304 continue;
Andrew de los Reyesef017552010-10-06 17:57:52 -0700305 if (blocks[i].reader != Vertex::kInvalidIndex) {
306 graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
307 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700308 graph_utils::AppendBlockToExtents(&extents, i);
309 block_count++;
310 }
311
312 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
313 // so we arbitrarily set it to 1024 * kBlockSize.
314 vector<char> buf(1024 * kBlockSize);
315
316 LOG(INFO) << "Reading left over blocks";
317 vector<Block>::size_type blocks_copied_count = 0;
318
319 // For each extent in extents, write the data into BZ2_bzWrite which
320 // sends it to an output file.
321 // We use the temporary buffer 'buf' to hold the data, which may be
322 // smaller than the extent, so in that case we have to loop to get
323 // the extent's data (that's the inner while loop).
324 for (vector<Extent>::const_iterator it = extents.begin();
325 it != extents.end(); ++it) {
326 vector<Block>::size_type blocks_read = 0;
327 while (blocks_read < it->num_blocks()) {
328 const int copy_block_cnt =
329 min(buf.size() / kBlockSize,
330 static_cast<vector<char>::size_type>(
331 it->num_blocks() - blocks_read));
332 ssize_t rc = pread(image_fd,
333 &buf[0],
334 copy_block_cnt * kBlockSize,
335 (it->start_block() + blocks_read) * kBlockSize);
336 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
337 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
338 copy_block_cnt * kBlockSize);
339 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
340 TEST_AND_RETURN_FALSE(err == BZ_OK);
341 blocks_read += copy_block_cnt;
342 blocks_copied_count += copy_block_cnt;
343 LOG(INFO) << "progress: " << ((float)blocks_copied_count)/block_count;
344 }
345 }
346 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
347 TEST_AND_RETURN_FALSE(err == BZ_OK);
348 bz_file = NULL;
349 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
350 file = NULL;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700351
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700352 vector<char> compressed_data;
353 LOG(INFO) << "Reading compressed data off disk";
354 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
355 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700356
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700357 // Add node to graph to write these blocks
358 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
359 out_op->set_data_offset(*blobs_length);
360 out_op->set_data_length(compressed_data.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700361 LOG(INFO) << "Rootfs non-data blocks compressed take up "
362 << compressed_data.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700363 *blobs_length += compressed_data.size();
364 out_op->set_dst_length(kBlockSize * block_count);
365 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700366
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700367 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
368 &compressed_data[0],
369 compressed_data.size()));
370 LOG(INFO) << "done with extra blocks";
371 return true;
372}
373
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700374// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700375// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700376bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
377 uint64_t value_be = htobe64(value);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700378 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)) ==
379 sizeof(value_be));
380 return true;
381}
382
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700383// Adds each operation from |graph| to |out_manifest| in the order specified by
384// |order| while building |out_op_name_map| with operation to name
385// mappings. Adds all |kernel_ops| to |out_manifest|. Filters out no-op
386// operations.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700387void InstallOperationsToManifest(
388 const Graph& graph,
389 const vector<Vertex::Index>& order,
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700390 const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700391 DeltaArchiveManifest* out_manifest,
392 OperationNameMap* out_op_name_map) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700393 for (vector<Vertex::Index>::const_iterator it = order.begin();
394 it != order.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700395 const Vertex& vertex = graph[*it];
396 const DeltaArchiveManifest_InstallOperation& add_op = vertex.op;
397 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
398 continue;
399 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700400 DeltaArchiveManifest_InstallOperation* op =
401 out_manifest->add_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700402 *op = add_op;
403 (*out_op_name_map)[op] = &vertex.file_name;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700404 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700405 for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
406 kernel_ops.begin(); it != kernel_ops.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700407 const DeltaArchiveManifest_InstallOperation& add_op = *it;
408 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
409 continue;
410 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700411 DeltaArchiveManifest_InstallOperation* op =
412 out_manifest->add_kernel_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700413 *op = add_op;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700414 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700415}
416
417void CheckGraph(const Graph& graph) {
418 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
419 CHECK(it->op.has_type());
420 }
421}
422
Darin Petkov68c10d12010-10-14 09:24:37 -0700423// Delta compresses a kernel partition |new_kernel_part| with knowledge of the
424// old kernel partition |old_kernel_part|. If |old_kernel_part| is an empty
425// string, generates a full update of the partition.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700426bool DeltaCompressKernelPartition(
427 const string& old_kernel_part,
428 const string& new_kernel_part,
429 vector<DeltaArchiveManifest_InstallOperation>* ops,
430 int blobs_fd,
431 off_t* blobs_length) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700432 LOG(INFO) << "Delta compressing kernel partition...";
Darin Petkov68c10d12010-10-14 09:24:37 -0700433 LOG_IF(INFO, old_kernel_part.empty()) << "Generating full kernel update...";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700434
435 // Add a new install operation
436 ops->resize(1);
437 DeltaArchiveManifest_InstallOperation* op = &(*ops)[0];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700438
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700439 vector<char> data;
Darin Petkov68c10d12010-10-14 09:24:37 -0700440 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_kernel_part,
441 new_kernel_part,
442 &data,
443 op,
444 false));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700445
Darin Petkov68c10d12010-10-14 09:24:37 -0700446 // Write the data
447 if (op->type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
448 op->set_data_offset(*blobs_length);
449 op->set_data_length(data.size());
450 }
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700451
Darin Petkov68c10d12010-10-14 09:24:37 -0700452 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data[0], data.size()));
453 *blobs_length += data.size();
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700454
Darin Petkov68c10d12010-10-14 09:24:37 -0700455 LOG(INFO) << "Done delta compressing kernel partition: "
456 << kInstallOperationTypes[op->type()];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700457 return true;
458}
459
Darin Petkov880335c2010-10-01 15:52:53 -0700460struct DeltaObject {
461 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
462 : name(in_name),
463 type(in_type),
464 size(in_size) {}
465 bool operator <(const DeltaObject& object) const {
Darin Petkovd43d6902010-10-14 11:17:50 -0700466 return (size != object.size) ? (size < object.size) : (name < object.name);
Darin Petkov880335c2010-10-01 15:52:53 -0700467 }
468 string name;
469 int type;
470 off_t size;
471};
472
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700473void ReportPayloadUsage(const DeltaArchiveManifest& manifest,
474 const int64_t manifest_metadata_size,
475 const OperationNameMap& op_name_map) {
Darin Petkov880335c2010-10-01 15:52:53 -0700476 vector<DeltaObject> objects;
477 off_t total_size = 0;
478
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700479 // Rootfs install operations.
480 for (int i = 0; i < manifest.install_operations_size(); ++i) {
481 const DeltaArchiveManifest_InstallOperation& op =
482 manifest.install_operations(i);
483 objects.push_back(DeltaObject(*op_name_map.find(&op)->second,
484 op.type(),
485 op.data_length()));
486 total_size += op.data_length();
Darin Petkov880335c2010-10-01 15:52:53 -0700487 }
488
Darin Petkov880335c2010-10-01 15:52:53 -0700489 // Kernel install operations.
490 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
491 const DeltaArchiveManifest_InstallOperation& op =
492 manifest.kernel_install_operations(i);
493 objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
494 op.type(),
495 op.data_length()));
496 total_size += op.data_length();
497 }
498
Darin Petkov95cf01f2010-10-12 14:59:13 -0700499 objects.push_back(DeltaObject("<manifest-metadata>",
500 -1,
501 manifest_metadata_size));
502 total_size += manifest_metadata_size;
503
Darin Petkov880335c2010-10-01 15:52:53 -0700504 std::sort(objects.begin(), objects.end());
505
506 static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
507 for (vector<DeltaObject>::const_iterator it = objects.begin();
508 it != objects.end(); ++it) {
509 const DeltaObject& object = *it;
510 fprintf(stderr, kFormatString,
511 object.size * 100.0 / total_size,
512 object.size,
Darin Petkov95cf01f2010-10-12 14:59:13 -0700513 object.type >= 0 ? kInstallOperationTypes[object.type] : "-",
Darin Petkov880335c2010-10-01 15:52:53 -0700514 object.name.c_str());
515 }
516 fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
517}
518
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700519} // namespace {}
520
521bool DeltaDiffGenerator::ReadFileToDiff(
522 const string& old_filename,
523 const string& new_filename,
524 vector<char>* out_data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700525 DeltaArchiveManifest_InstallOperation* out_op,
526 bool gather_extents) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700527 // Read new data in
528 vector<char> new_data;
529 TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700530
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700531 TEST_AND_RETURN_FALSE(!new_data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700532
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700533 vector<char> new_data_bz;
534 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
535 CHECK(!new_data_bz.empty());
536
537 vector<char> data; // Data blob that will be written to delta file.
538
539 DeltaArchiveManifest_InstallOperation operation;
540 size_t current_best_size = 0;
541 if (new_data.size() <= new_data_bz.size()) {
542 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
543 current_best_size = new_data.size();
544 data = new_data;
545 } else {
546 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
547 current_best_size = new_data_bz.size();
548 data = new_data_bz;
549 }
550
551 // Do we have an original file to consider?
552 struct stat old_stbuf;
Darin Petkov68c10d12010-10-14 09:24:37 -0700553 bool no_original = old_filename.empty();
554 if (!no_original && 0 != stat(old_filename.c_str(), &old_stbuf)) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700555 // If stat-ing the old file fails, it should be because it doesn't exist.
556 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
Darin Petkov68c10d12010-10-14 09:24:37 -0700557 no_original = true;
558 }
559 if (!no_original) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700560 // Read old data
561 vector<char> old_data;
562 TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
563 if (old_data == new_data) {
564 // No change in data.
565 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
566 current_best_size = 0;
567 data.clear();
568 } else {
569 // Try bsdiff of old to new data
570 vector<char> bsdiff_delta;
571 TEST_AND_RETURN_FALSE(
572 BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
573 CHECK_GT(bsdiff_delta.size(), 0);
574 if (bsdiff_delta.size() < current_best_size) {
575 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
576 current_best_size = bsdiff_delta.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700577
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700578 data = bsdiff_delta;
579 }
580 }
581 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700582
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700583 // Set parameters of the operations
584 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700585
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700586 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
587 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Darin Petkov68c10d12010-10-14 09:24:37 -0700588 if (gather_extents) {
589 TEST_AND_RETURN_FALSE(
590 GatherExtents(old_filename, operation.mutable_src_extents()));
591 } else {
592 Extent* src_extent = operation.add_src_extents();
593 src_extent->set_start_block(0);
594 src_extent->set_num_blocks(
595 (old_stbuf.st_size + kBlockSize - 1) / kBlockSize);
596 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700597 operation.set_src_length(old_stbuf.st_size);
598 }
599
Darin Petkov68c10d12010-10-14 09:24:37 -0700600 if (gather_extents) {
601 TEST_AND_RETURN_FALSE(
602 GatherExtents(new_filename, operation.mutable_dst_extents()));
603 } else {
604 Extent* dst_extent = operation.add_dst_extents();
605 dst_extent->set_start_block(0);
606 dst_extent->set_num_blocks((new_data.size() + kBlockSize - 1) / kBlockSize);
607 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700608 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700609
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700610 out_data->swap(data);
611 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700612
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700613 return true;
614}
615
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700616bool DeltaDiffGenerator::InitializePartitionInfo(bool is_kernel,
617 const string& partition,
618 PartitionInfo* info) {
Darin Petkov7ea32332010-10-13 10:46:11 -0700619 int64_t size = 0;
620 if (is_kernel) {
621 size = utils::FileSize(partition);
622 } else {
623 int block_count = 0, block_size = 0;
624 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(partition,
625 &block_count,
626 &block_size));
627 size = static_cast<int64_t>(block_count) * block_size;
628 }
629 TEST_AND_RETURN_FALSE(size > 0);
Darin Petkov36a58222010-10-07 22:00:09 -0700630 info->set_size(size);
631 OmahaHashCalculator hasher;
Darin Petkov7ea32332010-10-13 10:46:11 -0700632 TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, size) == size);
Darin Petkov36a58222010-10-07 22:00:09 -0700633 TEST_AND_RETURN_FALSE(hasher.Finalize());
634 const vector<char>& hash = hasher.raw_hash();
635 info->set_hash(hash.data(), hash.size());
Darin Petkovd43d6902010-10-14 11:17:50 -0700636 LOG(INFO) << partition << ": size=" << size << " hash=" << hasher.hash();
Darin Petkov36a58222010-10-07 22:00:09 -0700637 return true;
638}
639
640bool InitializePartitionInfos(const string& old_kernel,
641 const string& new_kernel,
642 const string& old_rootfs,
643 const string& new_rootfs,
644 DeltaArchiveManifest* manifest) {
Darin Petkovd43d6902010-10-14 11:17:50 -0700645 if (!old_kernel.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700646 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
647 true,
648 old_kernel,
649 manifest->mutable_old_kernel_info()));
Darin Petkovd43d6902010-10-14 11:17:50 -0700650 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700651 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
652 true,
653 new_kernel,
654 manifest->mutable_new_kernel_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700655 if (!old_rootfs.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700656 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
657 false,
658 old_rootfs,
659 manifest->mutable_old_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700660 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700661 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
662 false,
663 new_rootfs,
664 manifest->mutable_new_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700665 return true;
666}
667
Andrew de los Reyesef017552010-10-06 17:57:52 -0700668namespace {
669
670// Takes a collection (vector or RepeatedPtrField) of Extent and
671// returns a vector of the blocks referenced, in order.
672template<typename T>
673vector<uint64_t> ExpandExtents(const T& extents) {
674 vector<uint64_t> ret;
675 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
676 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700677 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700678 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700679 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700680 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700681 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700682 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700683 }
684 }
685 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700686 return ret;
687}
688
689// Takes a vector of blocks and returns an equivalent vector of Extent
690// objects.
691vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
692 vector<Extent> new_extents;
693 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
694 it != e; ++it) {
695 graph_utils::AppendBlockToExtents(&new_extents, *it);
696 }
697 return new_extents;
698}
699
700} // namespace {}
701
702void DeltaDiffGenerator::SubstituteBlocks(
703 Vertex* vertex,
704 const vector<Extent>& remove_extents,
705 const vector<Extent>& replace_extents) {
706 // First, expand out the blocks that op reads from
707 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700708 {
709 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700710 vector<uint64_t> remove_extents_expanded =
711 ExpandExtents(remove_extents);
712 vector<uint64_t> replace_extents_expanded =
713 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700714 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700715 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700716 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700717 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700718 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
719 }
720 utils::ApplyMap(&read_blocks, conversion);
721 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
722 e = vertex->out_edges.end(); it != e; ++it) {
723 vector<uint64_t> write_before_deps_expanded =
724 ExpandExtents(it->second.write_extents);
725 utils::ApplyMap(&write_before_deps_expanded, conversion);
726 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700727 }
728 }
729 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700730 vertex->op.clear_src_extents();
731 vector<Extent> new_extents = CompressExtents(read_blocks);
732 DeltaDiffGenerator::StoreExtents(new_extents,
733 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700734}
735
736bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700737 const set<Edge>& edges,
738 vector<CutEdgeVertexes>* out_cuts) {
739 DummyExtentAllocator scratch_allocator;
740 vector<CutEdgeVertexes> cuts;
741 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700742
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700743 uint64_t scratch_blocks_used = 0;
744 for (set<Edge>::const_iterator it = edges.begin();
745 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700746 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700747 vector<Extent> old_extents =
748 (*graph)[it->first].out_edges[it->second].extents;
749 // Choose some scratch space
750 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
751 LOG(INFO) << "using " << graph_utils::EdgeWeight(*graph, *it)
752 << " scratch blocks ("
753 << scratch_blocks_used << ")";
Andrew de los Reyesef017552010-10-06 17:57:52 -0700754 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700755 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
756 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700757 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700758 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700759 cuts.back().old_src = it->first;
760 cuts.back().old_dst = it->second;
Darin Petkov36a58222010-10-07 22:00:09 -0700761
Andrew de los Reyesef017552010-10-06 17:57:52 -0700762 EdgeProperties& cut_edge_properties =
763 (*graph)[it->first].out_edges.find(it->second)->second;
764
765 // This should never happen, as we should only be cutting edges between
766 // real file nodes, and write-before relationships are created from
767 // a real file node to a temp copy node:
768 CHECK(cut_edge_properties.write_extents.empty())
769 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700770
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700771 // make node depend on the copy operation
772 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700773 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700774
775 // Set src/dst extents and other proto variables for copy operation
776 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
777 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700778 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700779 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700780 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700781 graph->back().op.mutable_dst_extents());
782 graph->back().op.set_src_length(
783 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
784 graph->back().op.set_dst_length(graph->back().op.src_length());
785
786 // make the dest node read from the scratch space
787 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700788 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700789 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700790 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700791
792 // delete the old edge
793 CHECK_EQ(1, (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700794
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700795 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700796 EdgeProperties write_before_edge_properties;
797 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
798 (*graph)[it->second].out_edges.insert(
799 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700800 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700801 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700802 return true;
803}
804
805// Stores all Extents in 'extents' into 'out'.
806void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700807 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700808 google::protobuf::RepeatedPtrField<Extent>* out) {
809 for (vector<Extent>::const_iterator it = extents.begin();
810 it != extents.end(); ++it) {
811 Extent* new_extent = out->Add();
812 *new_extent = *it;
813 }
814}
815
816// Creates all the edges for the graph. Writers of a block point to
817// readers of the same block. This is because for an edge A->B, B
818// must complete before A executes.
819void DeltaDiffGenerator::CreateEdges(Graph* graph,
820 const vector<Block>& blocks) {
821 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
822 // Blocks with both a reader and writer get an edge
823 if (blocks[i].reader == Vertex::kInvalidIndex ||
824 blocks[i].writer == Vertex::kInvalidIndex)
825 continue;
826 // Don't have a node depend on itself
827 if (blocks[i].reader == blocks[i].writer)
828 continue;
829 // See if there's already an edge we can add onto
830 Vertex::EdgeMap::iterator edge_it =
831 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
832 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
833 // No existing edge. Create one
834 (*graph)[blocks[i].writer].out_edges.insert(
835 make_pair(blocks[i].reader, EdgeProperties()));
836 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700837 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700838 }
839 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
840 }
841}
842
Andrew de los Reyesef017552010-10-06 17:57:52 -0700843namespace {
844
845class SortCutsByTopoOrderLess {
846 public:
847 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
848 : table_(table) {}
849 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
850 return table_[a.old_dst] < table_[b.old_dst];
851 }
852 private:
853 vector<vector<Vertex::Index>::size_type>& table_;
854};
855
856} // namespace {}
857
858void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
859 vector<Vertex::Index>& op_indexes,
860 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
861 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
862 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
863 i != e; ++i) {
864 Vertex::Index node = op_indexes[i];
865 if (table.size() < (node + 1)) {
866 table.resize(node + 1);
867 }
868 table[node] = i;
869 }
870 reverse_op_indexes->swap(table);
871}
872
873void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
874 vector<CutEdgeVertexes>* cuts) {
875 // first, make a reverse lookup table.
876 vector<vector<Vertex::Index>::size_type> table;
877 GenerateReverseTopoOrderMap(op_indexes, &table);
878 SortCutsByTopoOrderLess less(table);
879 sort(cuts->begin(), cuts->end(), less);
880}
881
882void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
883 vector<Vertex::Index>* op_indexes) {
884 vector<Vertex::Index> ret;
885 vector<Vertex::Index> full_ops;
886 ret.reserve(op_indexes->size());
887 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
888 ++i) {
889 DeltaArchiveManifest_InstallOperation_Type type =
890 (*graph)[(*op_indexes)[i]].op.type();
891 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
892 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
893 full_ops.push_back((*op_indexes)[i]);
894 } else {
895 ret.push_back((*op_indexes)[i]);
896 }
897 }
898 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
899 << (full_ops.size() + ret.size()) << " total ops.";
900 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
901 op_indexes->swap(ret);
902}
903
904namespace {
905
906template<typename T>
907bool TempBlocksExistInExtents(const T& extents) {
908 for (int i = 0, e = extents.size(); i < e; ++i) {
909 Extent extent = graph_utils::GetElement(extents, i);
910 uint64_t start = extent.start_block();
911 uint64_t num = extent.num_blocks();
912 if (start == kSparseHole)
913 continue;
914 if (start >= kTempBlockStart ||
915 (start + num) >= kTempBlockStart) {
916 LOG(ERROR) << "temp block!";
917 LOG(ERROR) << "start: " << start << ", num: " << num;
918 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
919 LOG(ERROR) << "returning true";
920 return true;
921 }
922 // check for wrap-around, which would be a bug:
923 CHECK(start <= (start + num));
924 }
925 return false;
926}
927
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700928// Convertes the cuts, which must all have the same |old_dst| member,
929// to full. It does this by converting the |old_dst| to REPLACE or
930// REPLACE_BZ, dropping all incoming edges to |old_dst|, and marking
931// all temp nodes invalid.
932bool ConvertCutsToFull(
933 Graph* graph,
934 const string& new_root,
935 int data_fd,
936 off_t* data_file_size,
937 vector<Vertex::Index>* op_indexes,
938 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
939 const vector<CutEdgeVertexes>& cuts) {
940 CHECK(!cuts.empty());
941 set<Vertex::Index> deleted_nodes;
942 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
943 e = cuts.end(); it != e; ++it) {
944 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ConvertCutToFullOp(
945 graph,
946 *it,
947 new_root,
948 data_fd,
949 data_file_size));
950 deleted_nodes.insert(it->new_vertex);
951 }
952 deleted_nodes.insert(cuts[0].old_dst);
Darin Petkovbc58a7b2010-11-03 11:52:53 -0700953
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700954 vector<Vertex::Index> new_op_indexes;
955 new_op_indexes.reserve(op_indexes->size());
956 for (vector<Vertex::Index>::iterator it = op_indexes->begin(),
957 e = op_indexes->end(); it != e; ++it) {
958 if (utils::SetContainsKey(deleted_nodes, *it))
959 continue;
960 new_op_indexes.push_back(*it);
961 }
962 new_op_indexes.push_back(cuts[0].old_dst);
963 op_indexes->swap(new_op_indexes);
964 DeltaDiffGenerator::GenerateReverseTopoOrderMap(*op_indexes,
965 reverse_op_indexes);
966 return true;
967}
968
969// Tries to assign temp blocks for a collection of cuts, all of which share
970// the same old_dst member. If temp blocks can't be found, old_dst will be
971// converted to a REPLACE or REPLACE_BZ operation. Returns true on success,
972// which can happen even if blocks are converted to full. Returns false
973// on exceptional error cases.
974bool AssignBlockForAdjoiningCuts(
975 Graph* graph,
976 const string& new_root,
977 int data_fd,
978 off_t* data_file_size,
979 vector<Vertex::Index>* op_indexes,
980 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
981 const vector<CutEdgeVertexes>& cuts) {
982 CHECK(!cuts.empty());
983 const Vertex::Index old_dst = cuts[0].old_dst;
984 // Calculate # of blocks needed
985 uint64_t blocks_needed = 0;
986 map<const CutEdgeVertexes*, uint64_t> cuts_blocks_needed;
987 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
988 e = cuts.end(); it != e; ++it) {
989 uint64_t cut_blocks_needed = 0;
990 for (vector<Extent>::const_iterator jt = it->tmp_extents.begin(),
991 je = it->tmp_extents.end(); jt != je; ++jt) {
992 cut_blocks_needed += jt->num_blocks();
993 }
994 blocks_needed += cut_blocks_needed;
995 cuts_blocks_needed[&*it] = cut_blocks_needed;
996 }
997 LOG(INFO) << "Need to find " << blocks_needed << " blocks for "
998 << cuts.size() << " cuts";
Darin Petkovbc58a7b2010-11-03 11:52:53 -0700999
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001000 // Find enough blocks
1001 ExtentRanges scratch_ranges;
1002 // Each block that's supplying temp blocks and the corresponding blocks:
1003 typedef vector<pair<Vertex::Index, ExtentRanges> > SupplierVector;
1004 SupplierVector block_suppliers;
1005 uint64_t scratch_blocks_found = 0;
1006 LOG(INFO) << "scan from " << (*reverse_op_indexes)[old_dst] + 1
1007 << " to " << op_indexes->size();
1008 for (vector<Vertex::Index>::size_type i = (*reverse_op_indexes)[old_dst] + 1,
1009 e = op_indexes->size(); i < e; ++i) {
1010 Vertex::Index test_node = (*op_indexes)[i];
1011 if (!(*graph)[test_node].valid)
1012 continue;
1013 // See if this node has sufficient blocks
1014 ExtentRanges ranges;
1015 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
1016 ranges.SubtractExtent(ExtentForRange(
1017 kTempBlockStart, kSparseHole - kTempBlockStart));
1018 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
1019 // For now, for simplicity, subtract out all blocks in read-before
1020 // dependencies.
1021 for (Vertex::EdgeMap::const_iterator edge_i =
1022 (*graph)[test_node].out_edges.begin(),
1023 edge_e = (*graph)[test_node].out_edges.end();
1024 edge_i != edge_e; ++edge_i) {
1025 ranges.SubtractExtents(edge_i->second.extents);
1026 }
1027 if (ranges.blocks() == 0)
1028 continue;
1029
1030 if (ranges.blocks() + scratch_blocks_found > blocks_needed) {
1031 // trim down ranges
1032 vector<Extent> new_ranges = ranges.GetExtentsForBlockCount(
1033 blocks_needed - scratch_blocks_found);
1034 ranges = ExtentRanges();
1035 ranges.AddExtents(new_ranges);
1036 }
1037 scratch_ranges.AddRanges(ranges);
1038 block_suppliers.push_back(make_pair(test_node, ranges));
1039 scratch_blocks_found += ranges.blocks();
1040 LOG(INFO) << "Adding " << ranges.blocks() << " blocks. Now have "
1041 << scratch_ranges.blocks();
1042 if (scratch_ranges.blocks() >= blocks_needed)
1043 break;
1044 }
1045 if (scratch_ranges.blocks() < blocks_needed) {
1046 LOG(INFO) << "Unable to find sufficient scratch";
1047 TEST_AND_RETURN_FALSE(ConvertCutsToFull(graph,
1048 new_root,
1049 data_fd,
1050 data_file_size,
1051 op_indexes,
1052 reverse_op_indexes,
1053 cuts));
1054 return true;
1055 }
1056 // Use the scratch we found
1057 TEST_AND_RETURN_FALSE(scratch_ranges.blocks() == scratch_blocks_found);
1058
1059 // Make all the suppliers depend on this node
1060 for (SupplierVector::iterator it = block_suppliers.begin(),
1061 e = block_suppliers.end(); it != e; ++it) {
1062 graph_utils::AddReadBeforeDepExtents(
1063 &(*graph)[it->first],
1064 old_dst,
1065 it->second.GetExtentsForBlockCount(it->second.blocks()));
1066 }
Darin Petkovbc58a7b2010-11-03 11:52:53 -07001067
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001068 // Replace temp blocks in each cut
1069 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
1070 e = cuts.end(); it != e; ++it) {
1071 vector<Extent> real_extents =
1072 scratch_ranges.GetExtentsForBlockCount(cuts_blocks_needed[&*it]);
1073 scratch_ranges.SubtractExtents(real_extents);
1074
1075 // Fix the old dest node w/ the real blocks
1076 DeltaDiffGenerator::SubstituteBlocks(&(*graph)[old_dst],
1077 it->tmp_extents,
1078 real_extents);
1079
1080 // Fix the new node w/ the real blocks. Since the new node is just a
1081 // copy operation, we can replace all the dest extents w/ the real
1082 // blocks.
1083 DeltaArchiveManifest_InstallOperation *op =
1084 &(*graph)[it->new_vertex].op;
1085 op->clear_dst_extents();
1086 DeltaDiffGenerator::StoreExtents(real_extents, op->mutable_dst_extents());
1087 }
1088 LOG(INFO) << "Done subbing in for cut set";
1089 return true;
1090}
1091
Andrew de los Reyesef017552010-10-06 17:57:52 -07001092} // namespace {}
1093
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001094// Returns true if |op| is a no-op operation that doesn't do any useful work
1095// (e.g., a move operation that copies blocks onto themselves).
1096bool DeltaDiffGenerator::IsNoopOperation(
1097 const DeltaArchiveManifest_InstallOperation& op) {
1098 return (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE &&
1099 ExpandExtents(op.src_extents()) == ExpandExtents(op.dst_extents()));
1100}
1101
Andrew de los Reyesef017552010-10-06 17:57:52 -07001102bool DeltaDiffGenerator::AssignTempBlocks(
1103 Graph* graph,
1104 const string& new_root,
1105 int data_fd,
1106 off_t* data_file_size,
1107 vector<Vertex::Index>* op_indexes,
1108 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001109 const vector<CutEdgeVertexes>& cuts) {
Andrew de los Reyesef017552010-10-06 17:57:52 -07001110 CHECK(!cuts.empty());
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001111
1112 // group of cuts w/ the same old_dst:
1113 vector<CutEdgeVertexes> cuts_group;
1114
Andrew de los Reyesef017552010-10-06 17:57:52 -07001115 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
1116 true ; --i) {
1117 LOG(INFO) << "Fixing temp blocks in cut " << i
1118 << ": old dst: " << cuts[i].old_dst << " new vertex: "
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001119 << cuts[i].new_vertex << " path: "
1120 << (*graph)[cuts[i].old_dst].file_name;
1121
1122 if (cuts_group.empty() || (cuts_group[0].old_dst == cuts[i].old_dst)) {
1123 cuts_group.push_back(cuts[i]);
1124 } else {
1125 CHECK(!cuts_group.empty());
1126 TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1127 new_root,
1128 data_fd,
1129 data_file_size,
1130 op_indexes,
1131 reverse_op_indexes,
1132 cuts_group));
1133 cuts_group.clear();
1134 cuts_group.push_back(cuts[i]);
Andrew de los Reyesef017552010-10-06 17:57:52 -07001135 }
Darin Petkov36a58222010-10-07 22:00:09 -07001136
Andrew de los Reyesef017552010-10-06 17:57:52 -07001137 if (i == e) {
1138 // break out of for() loop
1139 break;
1140 }
1141 }
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001142 CHECK(!cuts_group.empty());
1143 TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1144 new_root,
1145 data_fd,
1146 data_file_size,
1147 op_indexes,
1148 reverse_op_indexes,
1149 cuts_group));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001150 return true;
1151}
1152
1153bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1154 size_t idx = 0;
1155 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1156 ++it, ++idx) {
1157 if (!it->valid)
1158 continue;
1159 const DeltaArchiveManifest_InstallOperation& op = it->op;
1160 if (TempBlocksExistInExtents(op.dst_extents()) ||
1161 TempBlocksExistInExtents(op.src_extents())) {
1162 LOG(INFO) << "bad extents in node " << idx;
1163 LOG(INFO) << "so yeah";
1164 return false;
1165 }
1166
1167 // Check out-edges:
1168 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
1169 je = it->out_edges.end(); jt != je; ++jt) {
1170 if (TempBlocksExistInExtents(jt->second.extents) ||
1171 TempBlocksExistInExtents(jt->second.write_extents)) {
1172 LOG(INFO) << "bad out edge in node " << idx;
1173 LOG(INFO) << "so yeah";
1174 return false;
1175 }
1176 }
1177 }
1178 return true;
1179}
1180
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001181bool DeltaDiffGenerator::ReorderDataBlobs(
1182 DeltaArchiveManifest* manifest,
1183 const std::string& data_blobs_path,
1184 const std::string& new_data_blobs_path) {
1185 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1186 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1187 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001188
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001189 DirectFileWriter writer;
1190 TEST_AND_RETURN_FALSE(
1191 writer.Open(new_data_blobs_path.c_str(),
1192 O_WRONLY | O_TRUNC | O_CREAT,
1193 0644) == 0);
1194 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001195 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001196
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001197 for (int i = 0; i < (manifest->install_operations_size() +
1198 manifest->kernel_install_operations_size()); i++) {
1199 DeltaArchiveManifest_InstallOperation* op = NULL;
1200 if (i < manifest->install_operations_size()) {
1201 op = manifest->mutable_install_operations(i);
1202 } else {
1203 op = manifest->mutable_kernel_install_operations(
1204 i - manifest->install_operations_size());
1205 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001206 if (!op->has_data_offset())
1207 continue;
1208 CHECK(op->has_data_length());
1209 vector<char> buf(op->data_length());
1210 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1211 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1212
1213 op->set_data_offset(out_file_size);
1214 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()) ==
1215 static_cast<ssize_t>(buf.size()));
1216 out_file_size += buf.size();
1217 }
1218 return true;
1219}
1220
Andrew de los Reyesef017552010-10-06 17:57:52 -07001221bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1222 const CutEdgeVertexes& cut,
1223 const string& new_root,
1224 int data_fd,
1225 off_t* data_file_size) {
1226 // Drop all incoming edges, keep all outgoing edges
Darin Petkov36a58222010-10-07 22:00:09 -07001227
Andrew de los Reyesef017552010-10-06 17:57:52 -07001228 // Keep all outgoing edges
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001229 if ((*graph)[cut.old_dst].op.type() !=
1230 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ &&
1231 (*graph)[cut.old_dst].op.type() !=
1232 DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
1233 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1234 graph_utils::DropWriteBeforeDeps(&out_edges);
Darin Petkov36a58222010-10-07 22:00:09 -07001235
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001236 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1237 cut.old_dst,
1238 NULL,
1239 "/-!@:&*nonexistent_path",
1240 new_root,
1241 (*graph)[cut.old_dst].file_name,
1242 data_fd,
1243 data_file_size));
Darin Petkov36a58222010-10-07 22:00:09 -07001244
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001245 (*graph)[cut.old_dst].out_edges = out_edges;
Andrew de los Reyesef017552010-10-06 17:57:52 -07001246
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001247 // Right now we don't have doubly-linked edges, so we have to scan
1248 // the whole graph.
1249 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1250 }
Andrew de los Reyesef017552010-10-06 17:57:52 -07001251
1252 // Delete temp node
1253 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1254 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1255 (*graph)[cut.old_dst].out_edges.end());
1256 (*graph)[cut.new_vertex].valid = false;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001257 LOG(INFO) << "marked node invalid: " << cut.new_vertex;
Andrew de los Reyesef017552010-10-06 17:57:52 -07001258 return true;
1259}
1260
1261bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1262 const string& new_root,
1263 int fd,
1264 off_t* data_file_size,
1265 vector<Vertex::Index>* final_order) {
1266 CycleBreaker cycle_breaker;
1267 LOG(INFO) << "Finding cycles...";
1268 set<Edge> cut_edges;
1269 cycle_breaker.BreakCycles(*graph, &cut_edges);
1270 LOG(INFO) << "done finding cycles";
1271 CheckGraph(*graph);
1272
1273 // Calculate number of scratch blocks needed
1274
1275 LOG(INFO) << "Cutting cycles...";
1276 vector<CutEdgeVertexes> cuts;
1277 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1278 LOG(INFO) << "done cutting cycles";
1279 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1280 CheckGraph(*graph);
1281
1282 LOG(INFO) << "Creating initial topological order...";
1283 TopologicalSort(*graph, final_order);
1284 LOG(INFO) << "done with initial topo order";
1285 CheckGraph(*graph);
1286
1287 LOG(INFO) << "Moving full ops to the back";
1288 MoveFullOpsToBack(graph, final_order);
1289 LOG(INFO) << "done moving full ops to back";
1290
1291 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1292 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1293
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001294 SortCutsByTopoOrder(*final_order, &cuts);
1295
Andrew de los Reyesef017552010-10-06 17:57:52 -07001296 if (!cuts.empty())
1297 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1298 new_root,
1299 fd,
1300 data_file_size,
1301 final_order,
1302 &inverse_final_order,
1303 cuts));
1304 LOG(INFO) << "Making sure all temp blocks have been allocated";
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001305
Andrew de los Reyesef017552010-10-06 17:57:52 -07001306 graph_utils::DumpGraph(*graph);
1307 CHECK(NoTempBlocksRemain(*graph));
1308 LOG(INFO) << "done making sure all temp blocks are allocated";
1309 return true;
1310}
1311
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001312bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1313 const string& old_root,
1314 const string& old_image,
1315 const string& new_root,
1316 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001317 const string& old_kernel_part,
1318 const string& new_kernel_part,
1319 const string& output_path,
1320 const string& private_key_path) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001321 int old_image_block_count = 0, old_image_block_size = 0;
1322 int new_image_block_count = 0, new_image_block_size = 0;
1323 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(new_image,
1324 &new_image_block_count,
1325 &new_image_block_size));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001326 if (!old_image.empty()) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001327 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(old_image,
1328 &old_image_block_count,
1329 &old_image_block_size));
1330 TEST_AND_RETURN_FALSE(old_image_block_size == new_image_block_size);
1331 LOG_IF(WARNING, old_image_block_count != new_image_block_count)
1332 << "Old and new images have different block counts.";
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001333 }
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001334 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001335 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1336
Darin Petkov7ea32332010-10-13 10:46:11 -07001337 vector<Block> blocks(max(old_image_block_count, new_image_block_count));
1338 LOG(INFO) << "Invalid block index: " << Vertex::kInvalidIndex;
1339 LOG(INFO) << "Block count: " << blocks.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001340 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1341 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1342 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1343 }
1344 Graph graph;
1345 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001346
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001347 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
1348 string temp_file_path;
1349 off_t data_file_size = 0;
1350
1351 LOG(INFO) << "Reading files...";
1352
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001353 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1354
Andrew de los Reyesef017552010-10-06 17:57:52 -07001355 vector<Vertex::Index> final_order;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001356 {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001357 int fd;
1358 TEST_AND_RETURN_FALSE(
1359 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
1360 TEST_AND_RETURN_FALSE(fd >= 0);
1361 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001362 if (!old_image.empty()) {
1363 // Delta update
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001364
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001365 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1366 &blocks,
1367 old_root,
1368 new_root,
1369 fd,
1370 &data_file_size));
1371 LOG(INFO) << "done reading normal files";
1372 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001373
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001374 graph.resize(graph.size() + 1);
1375 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1376 fd,
1377 &data_file_size,
1378 new_image,
1379 &graph.back()));
1380
1381 // Read kernel partition
1382 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1383 new_kernel_part,
1384 &kernel_ops,
1385 fd,
1386 &data_file_size));
1387
1388 LOG(INFO) << "done reading kernel";
1389 CheckGraph(graph);
1390
1391 LOG(INFO) << "Creating edges...";
1392 CreateEdges(&graph, blocks);
1393 LOG(INFO) << "Done creating edges";
1394 CheckGraph(graph);
1395
1396 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1397 new_root,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001398 fd,
1399 &data_file_size,
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001400 &final_order));
1401 } else {
1402 // Full update
Darin Petkov7ea32332010-10-13 10:46:11 -07001403 off_t new_image_size =
1404 static_cast<off_t>(new_image_block_count) * new_image_block_size;
Darin Petkov7a22d792010-11-08 14:10:00 -08001405 TEST_AND_RETURN_FALSE(FullUpdateGenerator::Run(&graph,
1406 new_kernel_part,
1407 new_image,
1408 new_image_size,
1409 fd,
1410 &data_file_size,
1411 kFullUpdateChunkSize,
1412 kBlockSize,
1413 &kernel_ops,
1414 &final_order));
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001415 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001416 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001417
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001418 // Convert to protobuf Manifest object
1419 DeltaArchiveManifest manifest;
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001420 OperationNameMap op_name_map;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001421 CheckGraph(graph);
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001422 InstallOperationsToManifest(graph,
1423 final_order,
1424 kernel_ops,
1425 &manifest,
1426 &op_name_map);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001427 CheckGraph(graph);
1428 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001429
1430 // Reorder the data blobs with the newly ordered manifest
1431 string ordered_blobs_path;
1432 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1433 "/tmp/CrAU_temp_data.ordered.XXXXXX",
1434 &ordered_blobs_path,
1435 false));
1436 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1437 temp_file_path,
1438 ordered_blobs_path));
1439
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001440 // Check that install op blobs are in order.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001441 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001442 {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001443 for (int i = 0; i < (manifest.install_operations_size() +
1444 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001445 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001446 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001447 manifest.mutable_install_operations(i) :
1448 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001449 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001450 if (op->has_data_offset()) {
1451 if (op->data_offset() != next_blob_offset) {
1452 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001453 << next_blob_offset;
1454 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001455 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001456 }
1457 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001458 }
1459
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001460 // Signatures appear at the end of the blobs. Note the offset in the
1461 // manifest
1462 if (!private_key_path.empty()) {
1463 LOG(INFO) << "Making room for signature in file";
1464 manifest.set_signatures_offset(next_blob_offset);
1465 LOG(INFO) << "set? " << manifest.has_signatures_offset();
1466 // Add a dummy op at the end to appease older clients
1467 DeltaArchiveManifest_InstallOperation* dummy_op =
1468 manifest.add_kernel_install_operations();
1469 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1470 dummy_op->set_data_offset(next_blob_offset);
1471 manifest.set_signatures_offset(next_blob_offset);
1472 uint64_t signature_blob_length = 0;
1473 TEST_AND_RETURN_FALSE(
1474 PayloadSigner::SignatureBlobLength(private_key_path,
1475 &signature_blob_length));
1476 dummy_op->set_data_length(signature_blob_length);
1477 manifest.set_signatures_size(signature_blob_length);
1478 Extent* dummy_extent = dummy_op->add_dst_extents();
1479 // Tell the dummy op to write this data to a big sparse hole
1480 dummy_extent->set_start_block(kSparseHole);
1481 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1482 kBlockSize);
1483 }
1484
Darin Petkov36a58222010-10-07 22:00:09 -07001485 TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1486 new_kernel_part,
1487 old_image,
1488 new_image,
1489 &manifest));
1490
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001491 // Serialize protobuf
1492 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001493
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001494 CheckGraph(graph);
1495 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1496 CheckGraph(graph);
1497
1498 LOG(INFO) << "Writing final delta file header...";
1499 DirectFileWriter writer;
1500 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1501 O_WRONLY | O_CREAT | O_TRUNC,
1502 0644) == 0);
1503 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001504
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001505 // Write header
1506 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)) ==
Andrew de los Reyes08c4e272010-04-15 14:02:17 -07001507 static_cast<ssize_t>(strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001508
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001509 // Write version number
1510 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001511
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001512 // Write protobuf length
1513 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1514 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001515
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001516 // Write protobuf
1517 LOG(INFO) << "Writing final delta file protobuf... "
1518 << serialized_manifest.size();
1519 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
1520 serialized_manifest.size()) ==
1521 static_cast<ssize_t>(serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001522
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001523 // Append the data blobs
1524 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001525 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001526 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1527 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1528 for (;;) {
1529 char buf[kBlockSize];
1530 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1531 if (0 == rc) {
1532 // EOF
1533 break;
1534 }
1535 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
1536 TEST_AND_RETURN_FALSE(writer.Write(buf, rc) == rc);
1537 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001538
1539 // Write signature blob.
1540 if (!private_key_path.empty()) {
1541 LOG(INFO) << "Signing the update...";
1542 vector<char> signature_blob;
1543 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(output_path,
1544 private_key_path,
1545 &signature_blob));
1546 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
1547 signature_blob.size()) ==
1548 static_cast<ssize_t>(signature_blob.size()));
1549 }
1550
Darin Petkov95cf01f2010-10-12 14:59:13 -07001551 int64_t manifest_metadata_size =
1552 strlen(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001553 ReportPayloadUsage(manifest, manifest_metadata_size, op_name_map);
Darin Petkov880335c2010-10-01 15:52:53 -07001554
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001555 LOG(INFO) << "All done. Successfully created delta file.";
1556 return true;
1557}
1558
Andrew de los Reyes50f36492010-11-01 13:57:12 -07001559const char* const kBsdiffPath = "bsdiff";
1560const char* const kBspatchPath = "bspatch";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001561const char* const kDeltaMagic = "CrAU";
1562
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001563}; // namespace chromeos_update_engine