blob: bb9cdb317611ca6258329f44a29fc7ffef0cc5fd [file] [log] [blame]
Doug Zongker424296a2014-09-02 08:53:09 -07001# Copyright (C) 2014 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Doug Zongkerfc44a512014-08-26 13:10:25 -070015from __future__ import print_function
16
17from collections import deque, OrderedDict
18from hashlib import sha1
Doug Zongker62338182014-09-08 08:29:55 -070019import heapq
Doug Zongkerfc44a512014-08-26 13:10:25 -070020import itertools
21import multiprocessing
22import os
Doug Zongkerfc44a512014-08-26 13:10:25 -070023import re
24import subprocess
Doug Zongkerfc44a512014-08-26 13:10:25 -070025import threading
26import tempfile
27
Dan Albert8b72aef2015-03-23 19:13:21 -070028from rangelib import RangeSet
29
Doug Zongkerfc44a512014-08-26 13:10:25 -070030
Doug Zongkerab7ca1d2014-08-26 10:40:28 -070031__all__ = ["EmptyImage", "DataImage", "BlockImageDiff"]
32
Dan Albert8b72aef2015-03-23 19:13:21 -070033
Doug Zongkerfc44a512014-08-26 13:10:25 -070034def compute_patch(src, tgt, imgdiff=False):
35 srcfd, srcfile = tempfile.mkstemp(prefix="src-")
36 tgtfd, tgtfile = tempfile.mkstemp(prefix="tgt-")
37 patchfd, patchfile = tempfile.mkstemp(prefix="patch-")
38 os.close(patchfd)
39
40 try:
41 with os.fdopen(srcfd, "wb") as f_src:
42 for p in src:
43 f_src.write(p)
44
45 with os.fdopen(tgtfd, "wb") as f_tgt:
46 for p in tgt:
47 f_tgt.write(p)
48 try:
49 os.unlink(patchfile)
50 except OSError:
51 pass
52 if imgdiff:
53 p = subprocess.call(["imgdiff", "-z", srcfile, tgtfile, patchfile],
54 stdout=open("/dev/null", "a"),
55 stderr=subprocess.STDOUT)
56 else:
57 p = subprocess.call(["bsdiff", srcfile, tgtfile, patchfile])
58
59 if p:
60 raise ValueError("diff failed: " + str(p))
61
62 with open(patchfile, "rb") as f:
63 return f.read()
64 finally:
65 try:
66 os.unlink(srcfile)
67 os.unlink(tgtfile)
68 os.unlink(patchfile)
69 except OSError:
70 pass
71
Dan Albert8b72aef2015-03-23 19:13:21 -070072
73class Image(object):
74 def ReadRangeSet(self, ranges):
75 raise NotImplementedError
76
77 def TotalSha1(self):
78 raise NotImplementedError
79
80
81class EmptyImage(Image):
Doug Zongkerfc44a512014-08-26 13:10:25 -070082 """A zero-length image."""
83 blocksize = 4096
84 care_map = RangeSet()
85 total_blocks = 0
86 file_map = {}
87 def ReadRangeSet(self, ranges):
88 return ()
Doug Zongkerab7ca1d2014-08-26 10:40:28 -070089 def TotalSha1(self):
90 return sha1().hexdigest()
91
92
Dan Albert8b72aef2015-03-23 19:13:21 -070093class DataImage(Image):
Doug Zongkerab7ca1d2014-08-26 10:40:28 -070094 """An image wrapped around a single string of data."""
95
96 def __init__(self, data, trim=False, pad=False):
97 self.data = data
98 self.blocksize = 4096
99
100 assert not (trim and pad)
101
102 partial = len(self.data) % self.blocksize
103 if partial > 0:
104 if trim:
105 self.data = self.data[:-partial]
106 elif pad:
107 self.data += '\0' * (self.blocksize - partial)
108 else:
109 raise ValueError(("data for DataImage must be multiple of %d bytes "
110 "unless trim or pad is specified") %
111 (self.blocksize,))
112
113 assert len(self.data) % self.blocksize == 0
114
115 self.total_blocks = len(self.data) / self.blocksize
116 self.care_map = RangeSet(data=(0, self.total_blocks))
117
118 zero_blocks = []
119 nonzero_blocks = []
120 reference = '\0' * self.blocksize
121
122 for i in range(self.total_blocks):
123 d = self.data[i*self.blocksize : (i+1)*self.blocksize]
124 if d == reference:
125 zero_blocks.append(i)
126 zero_blocks.append(i+1)
127 else:
128 nonzero_blocks.append(i)
129 nonzero_blocks.append(i+1)
130
131 self.file_map = {"__ZERO": RangeSet(zero_blocks),
132 "__NONZERO": RangeSet(nonzero_blocks)}
133
134 def ReadRangeSet(self, ranges):
135 return [self.data[s*self.blocksize:e*self.blocksize] for (s, e) in ranges]
136
137 def TotalSha1(self):
Dan Albert8b72aef2015-03-23 19:13:21 -0700138 return sha1(self.data).hexdigest()
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700139
Doug Zongkerfc44a512014-08-26 13:10:25 -0700140
141class Transfer(object):
142 def __init__(self, tgt_name, src_name, tgt_ranges, src_ranges, style, by_id):
143 self.tgt_name = tgt_name
144 self.src_name = src_name
145 self.tgt_ranges = tgt_ranges
146 self.src_ranges = src_ranges
147 self.style = style
148 self.intact = (getattr(tgt_ranges, "monotonic", False) and
149 getattr(src_ranges, "monotonic", False))
Tao Baob8c87172015-03-19 19:42:12 -0700150
151 # We use OrderedDict rather than dict so that the output is repeatable;
152 # otherwise it would depend on the hash values of the Transfer objects.
153 self.goes_before = OrderedDict()
154 self.goes_after = OrderedDict()
Doug Zongkerfc44a512014-08-26 13:10:25 -0700155
Doug Zongker62338182014-09-08 08:29:55 -0700156 self.stash_before = []
157 self.use_stash = []
158
Doug Zongkerfc44a512014-08-26 13:10:25 -0700159 self.id = len(by_id)
160 by_id.append(self)
161
Doug Zongker62338182014-09-08 08:29:55 -0700162 def NetStashChange(self):
163 return (sum(sr.size() for (_, sr) in self.stash_before) -
164 sum(sr.size() for (_, sr) in self.use_stash))
165
Doug Zongkerfc44a512014-08-26 13:10:25 -0700166 def __str__(self):
167 return (str(self.id) + ": <" + str(self.src_ranges) + " " + self.style +
168 " to " + str(self.tgt_ranges) + ">")
169
170
171# BlockImageDiff works on two image objects. An image object is
172# anything that provides the following attributes:
173#
174# blocksize: the size in bytes of a block, currently must be 4096.
175#
176# total_blocks: the total size of the partition/image, in blocks.
177#
178# care_map: a RangeSet containing which blocks (in the range [0,
179# total_blocks) we actually care about; i.e. which blocks contain
180# data.
181#
182# file_map: a dict that partitions the blocks contained in care_map
183# into smaller domains that are useful for doing diffs on.
184# (Typically a domain is a file, and the key in file_map is the
185# pathname.)
186#
187# ReadRangeSet(): a function that takes a RangeSet and returns the
188# data contained in the image blocks of that RangeSet. The data
189# is returned as a list or tuple of strings; concatenating the
190# elements together should produce the requested data.
191# Implementations are free to break up the data into list/tuple
192# elements in any way that is convenient.
193#
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700194# TotalSha1(): a function that returns (as a hex string) the SHA-1
195# hash of all the data in the image (ie, all the blocks in the
196# care_map)
197#
Doug Zongkerfc44a512014-08-26 13:10:25 -0700198# When creating a BlockImageDiff, the src image may be None, in which
199# case the list of transfers produced will never read from the
200# original image.
201
202class BlockImageDiff(object):
Doug Zongker62338182014-09-08 08:29:55 -0700203 def __init__(self, tgt, src=None, threads=None, version=2):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700204 if threads is None:
205 threads = multiprocessing.cpu_count() // 2
Dan Albert8b72aef2015-03-23 19:13:21 -0700206 if threads == 0:
207 threads = 1
Doug Zongkerfc44a512014-08-26 13:10:25 -0700208 self.threads = threads
Doug Zongker62338182014-09-08 08:29:55 -0700209 self.version = version
Dan Albert8b72aef2015-03-23 19:13:21 -0700210 self.transfers = []
211 self.src_basenames = {}
212 self.src_numpatterns = {}
Doug Zongker62338182014-09-08 08:29:55 -0700213
214 assert version in (1, 2)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700215
216 self.tgt = tgt
217 if src is None:
218 src = EmptyImage()
219 self.src = src
220
221 # The updater code that installs the patch always uses 4k blocks.
222 assert tgt.blocksize == 4096
223 assert src.blocksize == 4096
224
225 # The range sets in each filemap should comprise a partition of
226 # the care map.
227 self.AssertPartition(src.care_map, src.file_map.values())
228 self.AssertPartition(tgt.care_map, tgt.file_map.values())
229
230 def Compute(self, prefix):
231 # When looking for a source file to use as the diff input for a
232 # target file, we try:
233 # 1) an exact path match if available, otherwise
234 # 2) a exact basename match if available, otherwise
235 # 3) a basename match after all runs of digits are replaced by
236 # "#" if available, otherwise
237 # 4) we have no source for this target.
238 self.AbbreviateSourceNames()
239 self.FindTransfers()
240
241 # Find the ordering dependencies among transfers (this is O(n^2)
242 # in the number of transfers).
243 self.GenerateDigraph()
244 # Find a sequence of transfers that satisfies as many ordering
245 # dependencies as possible (heuristically).
246 self.FindVertexSequence()
247 # Fix up the ordering dependencies that the sequence didn't
248 # satisfy.
Doug Zongker62338182014-09-08 08:29:55 -0700249 if self.version == 1:
250 self.RemoveBackwardEdges()
251 else:
252 self.ReverseBackwardEdges()
253 self.ImproveVertexSequence()
254
Doug Zongkerfc44a512014-08-26 13:10:25 -0700255 # Double-check our work.
256 self.AssertSequenceGood()
257
258 self.ComputePatches(prefix)
259 self.WriteTransfers(prefix)
260
Dan Albert8b72aef2015-03-23 19:13:21 -0700261 def HashBlocks(self, source, ranges): # pylint: disable=no-self-use
Sami Tolvanendd67a292014-12-09 16:40:34 +0000262 data = source.ReadRangeSet(ranges)
263 ctx = sha1()
264
265 for p in data:
266 ctx.update(p)
267
268 return ctx.hexdigest()
269
Doug Zongkerfc44a512014-08-26 13:10:25 -0700270 def WriteTransfers(self, prefix):
271 out = []
272
Doug Zongkerfc44a512014-08-26 13:10:25 -0700273 total = 0
274 performs_read = False
275
Doug Zongker62338182014-09-08 08:29:55 -0700276 stashes = {}
277 stashed_blocks = 0
278 max_stashed_blocks = 0
279
280 free_stash_ids = []
281 next_stash_id = 0
282
Doug Zongkerfc44a512014-08-26 13:10:25 -0700283 for xf in self.transfers:
284
Doug Zongker62338182014-09-08 08:29:55 -0700285 if self.version < 2:
286 assert not xf.stash_before
287 assert not xf.use_stash
288
289 for s, sr in xf.stash_before:
290 assert s not in stashes
291 if free_stash_ids:
292 sid = heapq.heappop(free_stash_ids)
293 else:
294 sid = next_stash_id
295 next_stash_id += 1
296 stashes[s] = sid
297 stashed_blocks += sr.size()
298 out.append("stash %d %s\n" % (sid, sr.to_string_raw()))
299
300 if stashed_blocks > max_stashed_blocks:
301 max_stashed_blocks = stashed_blocks
302
Jesse Zhao7b985f62015-03-02 16:53:08 -0800303 free_string = []
304
Doug Zongker62338182014-09-08 08:29:55 -0700305 if self.version == 1:
Dan Albert8b72aef2015-03-23 19:13:21 -0700306 src_str = xf.src_ranges.to_string_raw()
Sami Tolvanendd67a292014-12-09 16:40:34 +0000307 elif self.version >= 2:
Doug Zongker62338182014-09-08 08:29:55 -0700308
309 # <# blocks> <src ranges>
310 # OR
311 # <# blocks> <src ranges> <src locs> <stash refs...>
312 # OR
313 # <# blocks> - <stash refs...>
314
315 size = xf.src_ranges.size()
Dan Albert8b72aef2015-03-23 19:13:21 -0700316 src_str = [str(size)]
Doug Zongker62338182014-09-08 08:29:55 -0700317
318 unstashed_src_ranges = xf.src_ranges
319 mapped_stashes = []
320 for s, sr in xf.use_stash:
321 sid = stashes.pop(s)
322 stashed_blocks -= sr.size()
323 unstashed_src_ranges = unstashed_src_ranges.subtract(sr)
324 sr = xf.src_ranges.map_within(sr)
325 mapped_stashes.append(sr)
Sami Tolvanendd67a292014-12-09 16:40:34 +0000326 if self.version == 2:
Dan Albert8b72aef2015-03-23 19:13:21 -0700327 src_str.append("%d:%s" % (sid, sr.to_string_raw()))
Sami Tolvanendd67a292014-12-09 16:40:34 +0000328 else:
329 assert sh in stashes
Dan Albert8b72aef2015-03-23 19:13:21 -0700330 src_str.append("%s:%s" % (sh, sr.to_string_raw()))
Sami Tolvanendd67a292014-12-09 16:40:34 +0000331 stashes[sh] -= 1
332 if stashes[sh] == 0:
333 free_string.append("free %s\n" % (sh))
334 stashes.pop(sh)
Doug Zongker62338182014-09-08 08:29:55 -0700335 heapq.heappush(free_stash_ids, sid)
336
337 if unstashed_src_ranges:
Dan Albert8b72aef2015-03-23 19:13:21 -0700338 src_str.insert(1, unstashed_src_ranges.to_string_raw())
Doug Zongker62338182014-09-08 08:29:55 -0700339 if xf.use_stash:
340 mapped_unstashed = xf.src_ranges.map_within(unstashed_src_ranges)
Dan Albert8b72aef2015-03-23 19:13:21 -0700341 src_str.insert(2, mapped_unstashed.to_string_raw())
Doug Zongker62338182014-09-08 08:29:55 -0700342 mapped_stashes.append(mapped_unstashed)
343 self.AssertPartition(RangeSet(data=(0, size)), mapped_stashes)
344 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700345 src_str.insert(1, "-")
Doug Zongker62338182014-09-08 08:29:55 -0700346 self.AssertPartition(RangeSet(data=(0, size)), mapped_stashes)
347
Dan Albert8b72aef2015-03-23 19:13:21 -0700348 src_str = " ".join(src_str)
Doug Zongker62338182014-09-08 08:29:55 -0700349
350 # both versions:
351 # zero <rangeset>
352 # new <rangeset>
353 # erase <rangeset>
354 #
355 # version 1:
356 # bsdiff patchstart patchlen <src rangeset> <tgt rangeset>
357 # imgdiff patchstart patchlen <src rangeset> <tgt rangeset>
358 # move <src rangeset> <tgt rangeset>
359 #
360 # version 2:
Dan Albert8b72aef2015-03-23 19:13:21 -0700361 # bsdiff patchstart patchlen <tgt rangeset> <src_str>
362 # imgdiff patchstart patchlen <tgt rangeset> <src_str>
363 # move <tgt rangeset> <src_str>
Sami Tolvanendd67a292014-12-09 16:40:34 +0000364 #
365 # version 3:
Dan Albert8b72aef2015-03-23 19:13:21 -0700366 # bsdiff patchstart patchlen srchash tgthash <tgt rangeset> <src_str>
367 # imgdiff patchstart patchlen srchash tgthash <tgt rangeset> <src_str>
368 # move hash <tgt rangeset> <src_str>
Doug Zongkerfc44a512014-08-26 13:10:25 -0700369
370 tgt_size = xf.tgt_ranges.size()
371
372 if xf.style == "new":
373 assert xf.tgt_ranges
374 out.append("%s %s\n" % (xf.style, xf.tgt_ranges.to_string_raw()))
375 total += tgt_size
376 elif xf.style == "move":
377 performs_read = True
378 assert xf.tgt_ranges
379 assert xf.src_ranges.size() == tgt_size
380 if xf.src_ranges != xf.tgt_ranges:
Doug Zongker62338182014-09-08 08:29:55 -0700381 if self.version == 1:
382 out.append("%s %s %s\n" % (
383 xf.style,
384 xf.src_ranges.to_string_raw(), xf.tgt_ranges.to_string_raw()))
385 elif self.version == 2:
386 out.append("%s %s %s\n" % (
387 xf.style,
Dan Albert8b72aef2015-03-23 19:13:21 -0700388 xf.tgt_ranges.to_string_raw(), src_str))
Sami Tolvanendd67a292014-12-09 16:40:34 +0000389 elif self.version >= 3:
390 out.append("%s %s %s %s\n" % (
391 xf.style,
392 self.HashBlocks(self.tgt, xf.tgt_ranges),
Dan Albert8b72aef2015-03-23 19:13:21 -0700393 xf.tgt_ranges.to_string_raw(), src_str))
Doug Zongkerfc44a512014-08-26 13:10:25 -0700394 total += tgt_size
395 elif xf.style in ("bsdiff", "imgdiff"):
396 performs_read = True
397 assert xf.tgt_ranges
398 assert xf.src_ranges
Doug Zongker62338182014-09-08 08:29:55 -0700399 if self.version == 1:
400 out.append("%s %d %d %s %s\n" % (
401 xf.style, xf.patch_start, xf.patch_len,
402 xf.src_ranges.to_string_raw(), xf.tgt_ranges.to_string_raw()))
403 elif self.version == 2:
404 out.append("%s %d %d %s %s\n" % (
405 xf.style, xf.patch_start, xf.patch_len,
Dan Albert8b72aef2015-03-23 19:13:21 -0700406 xf.tgt_ranges.to_string_raw(), src_str))
Sami Tolvanendd67a292014-12-09 16:40:34 +0000407 elif self.version >= 3:
408 out.append("%s %d %d %s %s %s %s\n" % (
409 xf.style,
410 xf.patch_start, xf.patch_len,
411 self.HashBlocks(self.src, xf.src_ranges),
412 self.HashBlocks(self.tgt, xf.tgt_ranges),
Dan Albert8b72aef2015-03-23 19:13:21 -0700413 xf.tgt_ranges.to_string_raw(), src_str))
Doug Zongkerfc44a512014-08-26 13:10:25 -0700414 total += tgt_size
415 elif xf.style == "zero":
416 assert xf.tgt_ranges
417 to_zero = xf.tgt_ranges.subtract(xf.src_ranges)
418 if to_zero:
419 out.append("%s %s\n" % (xf.style, to_zero.to_string_raw()))
420 total += to_zero.size()
421 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700422 raise ValueError("unknown transfer style '%s'\n" % xf.style)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700423
Dan Albertee8323b2015-03-27 16:49:01 -0700424 if free_string:
425 out.append("".join(free_string))
Doug Zongker62338182014-09-08 08:29:55 -0700426
427 # sanity check: abort if we're going to need more than 512 MB if
428 # stash space
429 assert max_stashed_blocks * self.tgt.blocksize < (512 << 20)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700430
431 all_tgt = RangeSet(data=(0, self.tgt.total_blocks))
432 if performs_read:
433 # if some of the original data is used, then at the end we'll
434 # erase all the blocks on the partition that don't contain data
435 # in the new image.
436 new_dontcare = all_tgt.subtract(self.tgt.care_map)
437 if new_dontcare:
438 out.append("erase %s\n" % (new_dontcare.to_string_raw(),))
439 else:
440 # if nothing is read (ie, this is a full OTA), then we can start
441 # by erasing the entire partition.
Doug Zongkere985f6f2014-09-09 12:38:47 -0700442 out.insert(0, "erase %s\n" % (all_tgt.to_string_raw(),))
443
444 out.insert(0, "%d\n" % (self.version,)) # format version number
445 out.insert(1, str(total) + "\n")
446 if self.version >= 2:
447 # version 2 only: after the total block count, we give the number
448 # of stash slots needed, and the maximum size needed (in blocks)
449 out.insert(2, str(next_stash_id) + "\n")
450 out.insert(3, str(max_stashed_blocks) + "\n")
Doug Zongkerfc44a512014-08-26 13:10:25 -0700451
452 with open(prefix + ".transfer.list", "wb") as f:
453 for i in out:
454 f.write(i)
455
Doug Zongker62338182014-09-08 08:29:55 -0700456 if self.version >= 2:
457 print("max stashed blocks: %d (%d bytes)\n" % (
458 max_stashed_blocks, max_stashed_blocks * self.tgt.blocksize))
459
Doug Zongkerfc44a512014-08-26 13:10:25 -0700460 def ComputePatches(self, prefix):
461 print("Reticulating splines...")
462 diff_q = []
463 patch_num = 0
464 with open(prefix + ".new.dat", "wb") as new_f:
465 for xf in self.transfers:
466 if xf.style == "zero":
467 pass
468 elif xf.style == "new":
469 for piece in self.tgt.ReadRangeSet(xf.tgt_ranges):
470 new_f.write(piece)
471 elif xf.style == "diff":
472 src = self.src.ReadRangeSet(xf.src_ranges)
473 tgt = self.tgt.ReadRangeSet(xf.tgt_ranges)
474
475 # We can't compare src and tgt directly because they may have
476 # the same content but be broken up into blocks differently, eg:
477 #
478 # ["he", "llo"] vs ["h", "ello"]
479 #
480 # We want those to compare equal, ideally without having to
481 # actually concatenate the strings (these may be tens of
482 # megabytes).
483
484 src_sha1 = sha1()
485 for p in src:
486 src_sha1.update(p)
487 tgt_sha1 = sha1()
488 tgt_size = 0
489 for p in tgt:
490 tgt_sha1.update(p)
491 tgt_size += len(p)
492
493 if src_sha1.digest() == tgt_sha1.digest():
494 # These are identical; we don't need to generate a patch,
495 # just issue copy commands on the device.
496 xf.style = "move"
497 else:
498 # For files in zip format (eg, APKs, JARs, etc.) we would
499 # like to use imgdiff -z if possible (because it usually
500 # produces significantly smaller patches than bsdiff).
501 # This is permissible if:
502 #
503 # - the source and target files are monotonic (ie, the
504 # data is stored with blocks in increasing order), and
505 # - we haven't removed any blocks from the source set.
506 #
507 # If these conditions are satisfied then appending all the
508 # blocks in the set together in order will produce a valid
509 # zip file (plus possibly extra zeros in the last block),
510 # which is what imgdiff needs to operate. (imgdiff is
511 # fine with extra zeros at the end of the file.)
512 imgdiff = (xf.intact and
513 xf.tgt_name.split(".")[-1].lower()
514 in ("apk", "jar", "zip"))
515 xf.style = "imgdiff" if imgdiff else "bsdiff"
516 diff_q.append((tgt_size, src, tgt, xf, patch_num))
517 patch_num += 1
518
519 else:
520 assert False, "unknown style " + xf.style
521
522 if diff_q:
523 if self.threads > 1:
524 print("Computing patches (using %d threads)..." % (self.threads,))
525 else:
526 print("Computing patches...")
527 diff_q.sort()
528
529 patches = [None] * patch_num
530
Dan Albert8b72aef2015-03-23 19:13:21 -0700531 # TODO: Rewrite with multiprocessing.ThreadPool?
Doug Zongkerfc44a512014-08-26 13:10:25 -0700532 lock = threading.Lock()
533 def diff_worker():
534 while True:
535 with lock:
Dan Albert8b72aef2015-03-23 19:13:21 -0700536 if not diff_q:
537 return
Doug Zongkerfc44a512014-08-26 13:10:25 -0700538 tgt_size, src, tgt, xf, patchnum = diff_q.pop()
539 patch = compute_patch(src, tgt, imgdiff=(xf.style == "imgdiff"))
540 size = len(patch)
541 with lock:
542 patches[patchnum] = (patch, xf)
543 print("%10d %10d (%6.2f%%) %7s %s" % (
544 size, tgt_size, size * 100.0 / tgt_size, xf.style,
545 xf.tgt_name if xf.tgt_name == xf.src_name else (
546 xf.tgt_name + " (from " + xf.src_name + ")")))
547
548 threads = [threading.Thread(target=diff_worker)
Dan Albert8b72aef2015-03-23 19:13:21 -0700549 for _ in range(self.threads)]
Doug Zongkerfc44a512014-08-26 13:10:25 -0700550 for th in threads:
551 th.start()
552 while threads:
553 threads.pop().join()
554 else:
555 patches = []
556
557 p = 0
558 with open(prefix + ".patch.dat", "wb") as patch_f:
559 for patch, xf in patches:
560 xf.patch_start = p
561 xf.patch_len = len(patch)
562 patch_f.write(patch)
563 p += len(patch)
564
565 def AssertSequenceGood(self):
566 # Simulate the sequences of transfers we will output, and check that:
567 # - we never read a block after writing it, and
568 # - we write every block we care about exactly once.
569
570 # Start with no blocks having been touched yet.
571 touched = RangeSet()
572
573 # Imagine processing the transfers in order.
574 for xf in self.transfers:
575 # Check that the input blocks for this transfer haven't yet been touched.
Doug Zongker62338182014-09-08 08:29:55 -0700576
577 x = xf.src_ranges
578 if self.version >= 2:
579 for _, sr in xf.use_stash:
580 x = x.subtract(sr)
581
582 assert not touched.overlaps(x)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700583 # Check that the output blocks for this transfer haven't yet been touched.
584 assert not touched.overlaps(xf.tgt_ranges)
585 # Touch all the blocks written by this transfer.
586 touched = touched.union(xf.tgt_ranges)
587
588 # Check that we've written every target block.
589 assert touched == self.tgt.care_map
590
Doug Zongker62338182014-09-08 08:29:55 -0700591 def ImproveVertexSequence(self):
592 print("Improving vertex order...")
593
594 # At this point our digraph is acyclic; we reversed any edges that
595 # were backwards in the heuristically-generated sequence. The
596 # previously-generated order is still acceptable, but we hope to
597 # find a better order that needs less memory for stashed data.
598 # Now we do a topological sort to generate a new vertex order,
599 # using a greedy algorithm to choose which vertex goes next
600 # whenever we have a choice.
601
602 # Make a copy of the edge set; this copy will get destroyed by the
603 # algorithm.
604 for xf in self.transfers:
605 xf.incoming = xf.goes_after.copy()
606 xf.outgoing = xf.goes_before.copy()
607
608 L = [] # the new vertex order
609
610 # S is the set of sources in the remaining graph; we always choose
611 # the one that leaves the least amount of stashed data after it's
612 # executed.
613 S = [(u.NetStashChange(), u.order, u) for u in self.transfers
614 if not u.incoming]
615 heapq.heapify(S)
616
617 while S:
618 _, _, xf = heapq.heappop(S)
619 L.append(xf)
620 for u in xf.outgoing:
621 del u.incoming[xf]
622 if not u.incoming:
623 heapq.heappush(S, (u.NetStashChange(), u.order, u))
624
625 # if this fails then our graph had a cycle.
626 assert len(L) == len(self.transfers)
627
628 self.transfers = L
629 for i, xf in enumerate(L):
630 xf.order = i
631
Doug Zongkerfc44a512014-08-26 13:10:25 -0700632 def RemoveBackwardEdges(self):
633 print("Removing backward edges...")
634 in_order = 0
635 out_of_order = 0
636 lost_source = 0
637
638 for xf in self.transfers:
Doug Zongkerfc44a512014-08-26 13:10:25 -0700639 lost = 0
640 size = xf.src_ranges.size()
641 for u in xf.goes_before:
642 # xf should go before u
643 if xf.order < u.order:
644 # it does, hurray!
Doug Zongker62338182014-09-08 08:29:55 -0700645 in_order += 1
Doug Zongkerfc44a512014-08-26 13:10:25 -0700646 else:
647 # it doesn't, boo. trim the blocks that u writes from xf's
648 # source, so that xf can go after u.
Doug Zongker62338182014-09-08 08:29:55 -0700649 out_of_order += 1
Doug Zongkerfc44a512014-08-26 13:10:25 -0700650 assert xf.src_ranges.overlaps(u.tgt_ranges)
651 xf.src_ranges = xf.src_ranges.subtract(u.tgt_ranges)
652 xf.intact = False
653
654 if xf.style == "diff" and not xf.src_ranges:
655 # nothing left to diff from; treat as new data
656 xf.style = "new"
657
658 lost = size - xf.src_ranges.size()
659 lost_source += lost
Doug Zongkerfc44a512014-08-26 13:10:25 -0700660
661 print((" %d/%d dependencies (%.2f%%) were violated; "
662 "%d source blocks removed.") %
663 (out_of_order, in_order + out_of_order,
664 (out_of_order * 100.0 / (in_order + out_of_order))
665 if (in_order + out_of_order) else 0.0,
666 lost_source))
667
Doug Zongker62338182014-09-08 08:29:55 -0700668 def ReverseBackwardEdges(self):
669 print("Reversing backward edges...")
670 in_order = 0
671 out_of_order = 0
672 stashes = 0
673 stash_size = 0
674
675 for xf in self.transfers:
Doug Zongker62338182014-09-08 08:29:55 -0700676 for u in xf.goes_before.copy():
677 # xf should go before u
678 if xf.order < u.order:
679 # it does, hurray!
680 in_order += 1
681 else:
682 # it doesn't, boo. modify u to stash the blocks that it
683 # writes that xf wants to read, and then require u to go
684 # before xf.
685 out_of_order += 1
686
687 overlap = xf.src_ranges.intersect(u.tgt_ranges)
688 assert overlap
689
690 u.stash_before.append((stashes, overlap))
691 xf.use_stash.append((stashes, overlap))
692 stashes += 1
693 stash_size += overlap.size()
694
695 # reverse the edge direction; now xf must go after u
696 del xf.goes_before[u]
697 del u.goes_after[xf]
698 xf.goes_after[u] = None # value doesn't matter
699 u.goes_before[xf] = None
700
701 print((" %d/%d dependencies (%.2f%%) were violated; "
702 "%d source blocks stashed.") %
703 (out_of_order, in_order + out_of_order,
704 (out_of_order * 100.0 / (in_order + out_of_order))
705 if (in_order + out_of_order) else 0.0,
706 stash_size))
707
Doug Zongkerfc44a512014-08-26 13:10:25 -0700708 def FindVertexSequence(self):
709 print("Finding vertex sequence...")
710
711 # This is based on "A Fast & Effective Heuristic for the Feedback
712 # Arc Set Problem" by P. Eades, X. Lin, and W.F. Smyth. Think of
713 # it as starting with the digraph G and moving all the vertices to
714 # be on a horizontal line in some order, trying to minimize the
715 # number of edges that end up pointing to the left. Left-pointing
716 # edges will get removed to turn the digraph into a DAG. In this
717 # case each edge has a weight which is the number of source blocks
718 # we'll lose if that edge is removed; we try to minimize the total
719 # weight rather than just the number of edges.
720
721 # Make a copy of the edge set; this copy will get destroyed by the
722 # algorithm.
723 for xf in self.transfers:
724 xf.incoming = xf.goes_after.copy()
725 xf.outgoing = xf.goes_before.copy()
726
727 # We use an OrderedDict instead of just a set so that the output
728 # is repeatable; otherwise it would depend on the hash values of
729 # the transfer objects.
730 G = OrderedDict()
731 for xf in self.transfers:
732 G[xf] = None
733 s1 = deque() # the left side of the sequence, built from left to right
734 s2 = deque() # the right side of the sequence, built from right to left
735
736 while G:
737
738 # Put all sinks at the end of the sequence.
739 while True:
740 sinks = [u for u in G if not u.outgoing]
Dan Albert8b72aef2015-03-23 19:13:21 -0700741 if not sinks:
742 break
Doug Zongkerfc44a512014-08-26 13:10:25 -0700743 for u in sinks:
744 s2.appendleft(u)
745 del G[u]
746 for iu in u.incoming:
747 del iu.outgoing[u]
748
749 # Put all the sources at the beginning of the sequence.
750 while True:
751 sources = [u for u in G if not u.incoming]
Dan Albert8b72aef2015-03-23 19:13:21 -0700752 if not sources:
753 break
Doug Zongkerfc44a512014-08-26 13:10:25 -0700754 for u in sources:
755 s1.append(u)
756 del G[u]
757 for iu in u.outgoing:
758 del iu.incoming[u]
759
Dan Albert8b72aef2015-03-23 19:13:21 -0700760 if not G:
761 break
Doug Zongkerfc44a512014-08-26 13:10:25 -0700762
763 # Find the "best" vertex to put next. "Best" is the one that
764 # maximizes the net difference in source blocks saved we get by
765 # pretending it's a source rather than a sink.
766
767 max_d = None
768 best_u = None
769 for u in G:
770 d = sum(u.outgoing.values()) - sum(u.incoming.values())
771 if best_u is None or d > max_d:
772 max_d = d
773 best_u = u
774
775 u = best_u
776 s1.append(u)
777 del G[u]
778 for iu in u.outgoing:
779 del iu.incoming[u]
780 for iu in u.incoming:
781 del iu.outgoing[u]
782
783 # Now record the sequence in the 'order' field of each transfer,
784 # and by rearranging self.transfers to be in the chosen sequence.
785
786 new_transfers = []
787 for x in itertools.chain(s1, s2):
788 x.order = len(new_transfers)
789 new_transfers.append(x)
790 del x.incoming
791 del x.outgoing
792
793 self.transfers = new_transfers
794
795 def GenerateDigraph(self):
796 print("Generating digraph...")
797 for a in self.transfers:
798 for b in self.transfers:
Dan Albert8b72aef2015-03-23 19:13:21 -0700799 if a is b:
800 continue
Doug Zongkerfc44a512014-08-26 13:10:25 -0700801
802 # If the blocks written by A are read by B, then B needs to go before A.
803 i = a.tgt_ranges.intersect(b.src_ranges)
804 if i:
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700805 if b.src_name == "__ZERO":
806 # the cost of removing source blocks for the __ZERO domain
807 # is (nearly) zero.
808 size = 0
809 else:
810 size = i.size()
Doug Zongkerfc44a512014-08-26 13:10:25 -0700811 b.goes_before[a] = size
812 a.goes_after[b] = size
813
814 def FindTransfers(self):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700815 empty = RangeSet()
816 for tgt_fn, tgt_ranges in self.tgt.file_map.items():
817 if tgt_fn == "__ZERO":
818 # the special "__ZERO" domain is all the blocks not contained
819 # in any file and that are filled with zeros. We have a
820 # special transfer style for zero blocks.
821 src_ranges = self.src.file_map.get("__ZERO", empty)
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700822 Transfer(tgt_fn, "__ZERO", tgt_ranges, src_ranges,
823 "zero", self.transfers)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700824 continue
825
826 elif tgt_fn in self.src.file_map:
827 # Look for an exact pathname match in the source.
828 Transfer(tgt_fn, tgt_fn, tgt_ranges, self.src.file_map[tgt_fn],
829 "diff", self.transfers)
830 continue
831
832 b = os.path.basename(tgt_fn)
833 if b in self.src_basenames:
834 # Look for an exact basename match in the source.
835 src_fn = self.src_basenames[b]
836 Transfer(tgt_fn, src_fn, tgt_ranges, self.src.file_map[src_fn],
837 "diff", self.transfers)
838 continue
839
840 b = re.sub("[0-9]+", "#", b)
841 if b in self.src_numpatterns:
842 # Look for a 'number pattern' match (a basename match after
843 # all runs of digits are replaced by "#"). (This is useful
844 # for .so files that contain version numbers in the filename
845 # that get bumped.)
846 src_fn = self.src_numpatterns[b]
847 Transfer(tgt_fn, src_fn, tgt_ranges, self.src.file_map[src_fn],
848 "diff", self.transfers)
849 continue
850
851 Transfer(tgt_fn, None, tgt_ranges, empty, "new", self.transfers)
852
853 def AbbreviateSourceNames(self):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700854 for k in self.src.file_map.keys():
855 b = os.path.basename(k)
856 self.src_basenames[b] = k
857 b = re.sub("[0-9]+", "#", b)
858 self.src_numpatterns[b] = k
859
860 @staticmethod
861 def AssertPartition(total, seq):
862 """Assert that all the RangeSets in 'seq' form a partition of the
863 'total' RangeSet (ie, they are nonintersecting and their union
864 equals 'total')."""
865 so_far = RangeSet()
866 for i in seq:
867 assert not so_far.overlaps(i)
868 so_far = so_far.union(i)
869 assert so_far == total