blob: d549f70f435459d0d5788949bd5325c0c4d71959 [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:
Sami Tolvanen29f529f2015-04-17 16:28:08 +0100390 # take into account automatic stashing of overlapping blocks
391 if xf.src_ranges.overlaps(xf.tgt_ranges):
392 temp_stash_usage = stashed_blocks + xf.src_ranges.size();
393 if temp_stash_usage > max_stashed_blocks:
394 max_stashed_blocks = temp_stash_usage
395
Sami Tolvanendd67a292014-12-09 16:40:34 +0000396 out.append("%s %s %s %s\n" % (
397 xf.style,
398 self.HashBlocks(self.tgt, xf.tgt_ranges),
Dan Albert8b72aef2015-03-23 19:13:21 -0700399 xf.tgt_ranges.to_string_raw(), src_str))
Doug Zongkerfc44a512014-08-26 13:10:25 -0700400 total += tgt_size
401 elif xf.style in ("bsdiff", "imgdiff"):
402 performs_read = True
403 assert xf.tgt_ranges
404 assert xf.src_ranges
Doug Zongker62338182014-09-08 08:29:55 -0700405 if self.version == 1:
406 out.append("%s %d %d %s %s\n" % (
407 xf.style, xf.patch_start, xf.patch_len,
408 xf.src_ranges.to_string_raw(), xf.tgt_ranges.to_string_raw()))
409 elif self.version == 2:
410 out.append("%s %d %d %s %s\n" % (
411 xf.style, xf.patch_start, xf.patch_len,
Dan Albert8b72aef2015-03-23 19:13:21 -0700412 xf.tgt_ranges.to_string_raw(), src_str))
Sami Tolvanendd67a292014-12-09 16:40:34 +0000413 elif self.version >= 3:
Sami Tolvanen29f529f2015-04-17 16:28:08 +0100414 # take into account automatic stashing of overlapping blocks
415 if xf.src_ranges.overlaps(xf.tgt_ranges):
416 temp_stash_usage = stashed_blocks + xf.src_ranges.size();
417 if temp_stash_usage > max_stashed_blocks:
418 max_stashed_blocks = temp_stash_usage
419
Sami Tolvanendd67a292014-12-09 16:40:34 +0000420 out.append("%s %d %d %s %s %s %s\n" % (
421 xf.style,
422 xf.patch_start, xf.patch_len,
423 self.HashBlocks(self.src, xf.src_ranges),
424 self.HashBlocks(self.tgt, xf.tgt_ranges),
Dan Albert8b72aef2015-03-23 19:13:21 -0700425 xf.tgt_ranges.to_string_raw(), src_str))
Doug Zongkerfc44a512014-08-26 13:10:25 -0700426 total += tgt_size
427 elif xf.style == "zero":
428 assert xf.tgt_ranges
429 to_zero = xf.tgt_ranges.subtract(xf.src_ranges)
430 if to_zero:
431 out.append("%s %s\n" % (xf.style, to_zero.to_string_raw()))
432 total += to_zero.size()
433 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700434 raise ValueError("unknown transfer style '%s'\n" % xf.style)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700435
Dan Albertee8323b2015-03-27 16:49:01 -0700436 if free_string:
437 out.append("".join(free_string))
Doug Zongker62338182014-09-08 08:29:55 -0700438
439 # sanity check: abort if we're going to need more than 512 MB if
440 # stash space
441 assert max_stashed_blocks * self.tgt.blocksize < (512 << 20)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700442
443 all_tgt = RangeSet(data=(0, self.tgt.total_blocks))
444 if performs_read:
445 # if some of the original data is used, then at the end we'll
446 # erase all the blocks on the partition that don't contain data
447 # in the new image.
448 new_dontcare = all_tgt.subtract(self.tgt.care_map)
449 if new_dontcare:
450 out.append("erase %s\n" % (new_dontcare.to_string_raw(),))
451 else:
452 # if nothing is read (ie, this is a full OTA), then we can start
453 # by erasing the entire partition.
Doug Zongkere985f6f2014-09-09 12:38:47 -0700454 out.insert(0, "erase %s\n" % (all_tgt.to_string_raw(),))
455
456 out.insert(0, "%d\n" % (self.version,)) # format version number
457 out.insert(1, str(total) + "\n")
458 if self.version >= 2:
459 # version 2 only: after the total block count, we give the number
460 # of stash slots needed, and the maximum size needed (in blocks)
461 out.insert(2, str(next_stash_id) + "\n")
462 out.insert(3, str(max_stashed_blocks) + "\n")
Doug Zongkerfc44a512014-08-26 13:10:25 -0700463
464 with open(prefix + ".transfer.list", "wb") as f:
465 for i in out:
466 f.write(i)
467
Doug Zongker62338182014-09-08 08:29:55 -0700468 if self.version >= 2:
469 print("max stashed blocks: %d (%d bytes)\n" % (
470 max_stashed_blocks, max_stashed_blocks * self.tgt.blocksize))
471
Doug Zongkerfc44a512014-08-26 13:10:25 -0700472 def ComputePatches(self, prefix):
473 print("Reticulating splines...")
474 diff_q = []
475 patch_num = 0
476 with open(prefix + ".new.dat", "wb") as new_f:
477 for xf in self.transfers:
478 if xf.style == "zero":
479 pass
480 elif xf.style == "new":
481 for piece in self.tgt.ReadRangeSet(xf.tgt_ranges):
482 new_f.write(piece)
483 elif xf.style == "diff":
484 src = self.src.ReadRangeSet(xf.src_ranges)
485 tgt = self.tgt.ReadRangeSet(xf.tgt_ranges)
486
487 # We can't compare src and tgt directly because they may have
488 # the same content but be broken up into blocks differently, eg:
489 #
490 # ["he", "llo"] vs ["h", "ello"]
491 #
492 # We want those to compare equal, ideally without having to
493 # actually concatenate the strings (these may be tens of
494 # megabytes).
495
496 src_sha1 = sha1()
497 for p in src:
498 src_sha1.update(p)
499 tgt_sha1 = sha1()
500 tgt_size = 0
501 for p in tgt:
502 tgt_sha1.update(p)
503 tgt_size += len(p)
504
505 if src_sha1.digest() == tgt_sha1.digest():
506 # These are identical; we don't need to generate a patch,
507 # just issue copy commands on the device.
508 xf.style = "move"
509 else:
510 # For files in zip format (eg, APKs, JARs, etc.) we would
511 # like to use imgdiff -z if possible (because it usually
512 # produces significantly smaller patches than bsdiff).
513 # This is permissible if:
514 #
515 # - the source and target files are monotonic (ie, the
516 # data is stored with blocks in increasing order), and
517 # - we haven't removed any blocks from the source set.
518 #
519 # If these conditions are satisfied then appending all the
520 # blocks in the set together in order will produce a valid
521 # zip file (plus possibly extra zeros in the last block),
522 # which is what imgdiff needs to operate. (imgdiff is
523 # fine with extra zeros at the end of the file.)
524 imgdiff = (xf.intact and
525 xf.tgt_name.split(".")[-1].lower()
526 in ("apk", "jar", "zip"))
527 xf.style = "imgdiff" if imgdiff else "bsdiff"
528 diff_q.append((tgt_size, src, tgt, xf, patch_num))
529 patch_num += 1
530
531 else:
532 assert False, "unknown style " + xf.style
533
534 if diff_q:
535 if self.threads > 1:
536 print("Computing patches (using %d threads)..." % (self.threads,))
537 else:
538 print("Computing patches...")
539 diff_q.sort()
540
541 patches = [None] * patch_num
542
Dan Albert8b72aef2015-03-23 19:13:21 -0700543 # TODO: Rewrite with multiprocessing.ThreadPool?
Doug Zongkerfc44a512014-08-26 13:10:25 -0700544 lock = threading.Lock()
545 def diff_worker():
546 while True:
547 with lock:
Dan Albert8b72aef2015-03-23 19:13:21 -0700548 if not diff_q:
549 return
Doug Zongkerfc44a512014-08-26 13:10:25 -0700550 tgt_size, src, tgt, xf, patchnum = diff_q.pop()
551 patch = compute_patch(src, tgt, imgdiff=(xf.style == "imgdiff"))
552 size = len(patch)
553 with lock:
554 patches[patchnum] = (patch, xf)
555 print("%10d %10d (%6.2f%%) %7s %s" % (
556 size, tgt_size, size * 100.0 / tgt_size, xf.style,
557 xf.tgt_name if xf.tgt_name == xf.src_name else (
558 xf.tgt_name + " (from " + xf.src_name + ")")))
559
560 threads = [threading.Thread(target=diff_worker)
Dan Albert8b72aef2015-03-23 19:13:21 -0700561 for _ in range(self.threads)]
Doug Zongkerfc44a512014-08-26 13:10:25 -0700562 for th in threads:
563 th.start()
564 while threads:
565 threads.pop().join()
566 else:
567 patches = []
568
569 p = 0
570 with open(prefix + ".patch.dat", "wb") as patch_f:
571 for patch, xf in patches:
572 xf.patch_start = p
573 xf.patch_len = len(patch)
574 patch_f.write(patch)
575 p += len(patch)
576
577 def AssertSequenceGood(self):
578 # Simulate the sequences of transfers we will output, and check that:
579 # - we never read a block after writing it, and
580 # - we write every block we care about exactly once.
581
582 # Start with no blocks having been touched yet.
583 touched = RangeSet()
584
585 # Imagine processing the transfers in order.
586 for xf in self.transfers:
587 # Check that the input blocks for this transfer haven't yet been touched.
Doug Zongker62338182014-09-08 08:29:55 -0700588
589 x = xf.src_ranges
590 if self.version >= 2:
591 for _, sr in xf.use_stash:
592 x = x.subtract(sr)
593
594 assert not touched.overlaps(x)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700595 # Check that the output blocks for this transfer haven't yet been touched.
596 assert not touched.overlaps(xf.tgt_ranges)
597 # Touch all the blocks written by this transfer.
598 touched = touched.union(xf.tgt_ranges)
599
600 # Check that we've written every target block.
601 assert touched == self.tgt.care_map
602
Doug Zongker62338182014-09-08 08:29:55 -0700603 def ImproveVertexSequence(self):
604 print("Improving vertex order...")
605
606 # At this point our digraph is acyclic; we reversed any edges that
607 # were backwards in the heuristically-generated sequence. The
608 # previously-generated order is still acceptable, but we hope to
609 # find a better order that needs less memory for stashed data.
610 # Now we do a topological sort to generate a new vertex order,
611 # using a greedy algorithm to choose which vertex goes next
612 # whenever we have a choice.
613
614 # Make a copy of the edge set; this copy will get destroyed by the
615 # algorithm.
616 for xf in self.transfers:
617 xf.incoming = xf.goes_after.copy()
618 xf.outgoing = xf.goes_before.copy()
619
620 L = [] # the new vertex order
621
622 # S is the set of sources in the remaining graph; we always choose
623 # the one that leaves the least amount of stashed data after it's
624 # executed.
625 S = [(u.NetStashChange(), u.order, u) for u in self.transfers
626 if not u.incoming]
627 heapq.heapify(S)
628
629 while S:
630 _, _, xf = heapq.heappop(S)
631 L.append(xf)
632 for u in xf.outgoing:
633 del u.incoming[xf]
634 if not u.incoming:
635 heapq.heappush(S, (u.NetStashChange(), u.order, u))
636
637 # if this fails then our graph had a cycle.
638 assert len(L) == len(self.transfers)
639
640 self.transfers = L
641 for i, xf in enumerate(L):
642 xf.order = i
643
Doug Zongkerfc44a512014-08-26 13:10:25 -0700644 def RemoveBackwardEdges(self):
645 print("Removing backward edges...")
646 in_order = 0
647 out_of_order = 0
648 lost_source = 0
649
650 for xf in self.transfers:
Doug Zongkerfc44a512014-08-26 13:10:25 -0700651 lost = 0
652 size = xf.src_ranges.size()
653 for u in xf.goes_before:
654 # xf should go before u
655 if xf.order < u.order:
656 # it does, hurray!
Doug Zongker62338182014-09-08 08:29:55 -0700657 in_order += 1
Doug Zongkerfc44a512014-08-26 13:10:25 -0700658 else:
659 # it doesn't, boo. trim the blocks that u writes from xf's
660 # source, so that xf can go after u.
Doug Zongker62338182014-09-08 08:29:55 -0700661 out_of_order += 1
Doug Zongkerfc44a512014-08-26 13:10:25 -0700662 assert xf.src_ranges.overlaps(u.tgt_ranges)
663 xf.src_ranges = xf.src_ranges.subtract(u.tgt_ranges)
664 xf.intact = False
665
666 if xf.style == "diff" and not xf.src_ranges:
667 # nothing left to diff from; treat as new data
668 xf.style = "new"
669
670 lost = size - xf.src_ranges.size()
671 lost_source += lost
Doug Zongkerfc44a512014-08-26 13:10:25 -0700672
673 print((" %d/%d dependencies (%.2f%%) were violated; "
674 "%d source blocks removed.") %
675 (out_of_order, in_order + out_of_order,
676 (out_of_order * 100.0 / (in_order + out_of_order))
677 if (in_order + out_of_order) else 0.0,
678 lost_source))
679
Doug Zongker62338182014-09-08 08:29:55 -0700680 def ReverseBackwardEdges(self):
681 print("Reversing backward edges...")
682 in_order = 0
683 out_of_order = 0
684 stashes = 0
685 stash_size = 0
686
687 for xf in self.transfers:
Doug Zongker62338182014-09-08 08:29:55 -0700688 for u in xf.goes_before.copy():
689 # xf should go before u
690 if xf.order < u.order:
691 # it does, hurray!
692 in_order += 1
693 else:
694 # it doesn't, boo. modify u to stash the blocks that it
695 # writes that xf wants to read, and then require u to go
696 # before xf.
697 out_of_order += 1
698
699 overlap = xf.src_ranges.intersect(u.tgt_ranges)
700 assert overlap
701
702 u.stash_before.append((stashes, overlap))
703 xf.use_stash.append((stashes, overlap))
704 stashes += 1
705 stash_size += overlap.size()
706
707 # reverse the edge direction; now xf must go after u
708 del xf.goes_before[u]
709 del u.goes_after[xf]
710 xf.goes_after[u] = None # value doesn't matter
711 u.goes_before[xf] = None
712
713 print((" %d/%d dependencies (%.2f%%) were violated; "
714 "%d source blocks stashed.") %
715 (out_of_order, in_order + out_of_order,
716 (out_of_order * 100.0 / (in_order + out_of_order))
717 if (in_order + out_of_order) else 0.0,
718 stash_size))
719
Doug Zongkerfc44a512014-08-26 13:10:25 -0700720 def FindVertexSequence(self):
721 print("Finding vertex sequence...")
722
723 # This is based on "A Fast & Effective Heuristic for the Feedback
724 # Arc Set Problem" by P. Eades, X. Lin, and W.F. Smyth. Think of
725 # it as starting with the digraph G and moving all the vertices to
726 # be on a horizontal line in some order, trying to minimize the
727 # number of edges that end up pointing to the left. Left-pointing
728 # edges will get removed to turn the digraph into a DAG. In this
729 # case each edge has a weight which is the number of source blocks
730 # we'll lose if that edge is removed; we try to minimize the total
731 # weight rather than just the number of edges.
732
733 # Make a copy of the edge set; this copy will get destroyed by the
734 # algorithm.
735 for xf in self.transfers:
736 xf.incoming = xf.goes_after.copy()
737 xf.outgoing = xf.goes_before.copy()
738
739 # We use an OrderedDict instead of just a set so that the output
740 # is repeatable; otherwise it would depend on the hash values of
741 # the transfer objects.
742 G = OrderedDict()
743 for xf in self.transfers:
744 G[xf] = None
745 s1 = deque() # the left side of the sequence, built from left to right
746 s2 = deque() # the right side of the sequence, built from right to left
747
748 while G:
749
750 # Put all sinks at the end of the sequence.
751 while True:
752 sinks = [u for u in G if not u.outgoing]
Dan Albert8b72aef2015-03-23 19:13:21 -0700753 if not sinks:
754 break
Doug Zongkerfc44a512014-08-26 13:10:25 -0700755 for u in sinks:
756 s2.appendleft(u)
757 del G[u]
758 for iu in u.incoming:
759 del iu.outgoing[u]
760
761 # Put all the sources at the beginning of the sequence.
762 while True:
763 sources = [u for u in G if not u.incoming]
Dan Albert8b72aef2015-03-23 19:13:21 -0700764 if not sources:
765 break
Doug Zongkerfc44a512014-08-26 13:10:25 -0700766 for u in sources:
767 s1.append(u)
768 del G[u]
769 for iu in u.outgoing:
770 del iu.incoming[u]
771
Dan Albert8b72aef2015-03-23 19:13:21 -0700772 if not G:
773 break
Doug Zongkerfc44a512014-08-26 13:10:25 -0700774
775 # Find the "best" vertex to put next. "Best" is the one that
776 # maximizes the net difference in source blocks saved we get by
777 # pretending it's a source rather than a sink.
778
779 max_d = None
780 best_u = None
781 for u in G:
782 d = sum(u.outgoing.values()) - sum(u.incoming.values())
783 if best_u is None or d > max_d:
784 max_d = d
785 best_u = u
786
787 u = best_u
788 s1.append(u)
789 del G[u]
790 for iu in u.outgoing:
791 del iu.incoming[u]
792 for iu in u.incoming:
793 del iu.outgoing[u]
794
795 # Now record the sequence in the 'order' field of each transfer,
796 # and by rearranging self.transfers to be in the chosen sequence.
797
798 new_transfers = []
799 for x in itertools.chain(s1, s2):
800 x.order = len(new_transfers)
801 new_transfers.append(x)
802 del x.incoming
803 del x.outgoing
804
805 self.transfers = new_transfers
806
807 def GenerateDigraph(self):
808 print("Generating digraph...")
809 for a in self.transfers:
810 for b in self.transfers:
Dan Albert8b72aef2015-03-23 19:13:21 -0700811 if a is b:
812 continue
Doug Zongkerfc44a512014-08-26 13:10:25 -0700813
814 # If the blocks written by A are read by B, then B needs to go before A.
815 i = a.tgt_ranges.intersect(b.src_ranges)
816 if i:
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700817 if b.src_name == "__ZERO":
818 # the cost of removing source blocks for the __ZERO domain
819 # is (nearly) zero.
820 size = 0
821 else:
822 size = i.size()
Doug Zongkerfc44a512014-08-26 13:10:25 -0700823 b.goes_before[a] = size
824 a.goes_after[b] = size
825
826 def FindTransfers(self):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700827 empty = RangeSet()
828 for tgt_fn, tgt_ranges in self.tgt.file_map.items():
829 if tgt_fn == "__ZERO":
830 # the special "__ZERO" domain is all the blocks not contained
831 # in any file and that are filled with zeros. We have a
832 # special transfer style for zero blocks.
833 src_ranges = self.src.file_map.get("__ZERO", empty)
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700834 Transfer(tgt_fn, "__ZERO", tgt_ranges, src_ranges,
835 "zero", self.transfers)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700836 continue
837
838 elif tgt_fn in self.src.file_map:
839 # Look for an exact pathname match in the source.
840 Transfer(tgt_fn, tgt_fn, tgt_ranges, self.src.file_map[tgt_fn],
841 "diff", self.transfers)
842 continue
843
844 b = os.path.basename(tgt_fn)
845 if b in self.src_basenames:
846 # Look for an exact basename match in the source.
847 src_fn = self.src_basenames[b]
848 Transfer(tgt_fn, src_fn, tgt_ranges, self.src.file_map[src_fn],
849 "diff", self.transfers)
850 continue
851
852 b = re.sub("[0-9]+", "#", b)
853 if b in self.src_numpatterns:
854 # Look for a 'number pattern' match (a basename match after
855 # all runs of digits are replaced by "#"). (This is useful
856 # for .so files that contain version numbers in the filename
857 # that get bumped.)
858 src_fn = self.src_numpatterns[b]
859 Transfer(tgt_fn, src_fn, tgt_ranges, self.src.file_map[src_fn],
860 "diff", self.transfers)
861 continue
862
863 Transfer(tgt_fn, None, tgt_ranges, empty, "new", self.transfers)
864
865 def AbbreviateSourceNames(self):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700866 for k in self.src.file_map.keys():
867 b = os.path.basename(k)
868 self.src_basenames[b] = k
869 b = re.sub("[0-9]+", "#", b)
870 self.src_numpatterns[b] = k
871
872 @staticmethod
873 def AssertPartition(total, seq):
874 """Assert that all the RangeSets in 'seq' form a partition of the
875 'total' RangeSet (ie, they are nonintersecting and their union
876 equals 'total')."""
877 so_far = RangeSet()
878 for i in seq:
879 assert not so_far.overlaps(i)
880 so_far = so_far.union(i)
881 assert so_far == total