applier.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. #
  2. # Copyright (C) 2013 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. """Applying a Chrome OS update payload.
  17. This module is used internally by the main Payload class for applying an update
  18. payload. The interface for invoking the applier is as follows:
  19. applier = PayloadApplier(payload)
  20. applier.Run(...)
  21. """
  22. from __future__ import print_function
  23. import array
  24. import bz2
  25. import hashlib
  26. import itertools
  27. # Not everywhere we can have the lzma library so we ignore it if we didn't have
  28. # it because it is not going to be used. For example, 'cros flash' uses
  29. # devserver code which eventually loads this file, but the lzma library is not
  30. # included in the client test devices, and it is not necessary to do so. But
  31. # lzma is not used in 'cros flash' so it should be fine. Python 3.x include
  32. # lzma, but for backward compatibility with Python 2.7, backports-lzma is
  33. # needed.
  34. try:
  35. import lzma
  36. except ImportError:
  37. try:
  38. from backports import lzma
  39. except ImportError:
  40. pass
  41. import os
  42. import shutil
  43. import subprocess
  44. import sys
  45. import tempfile
  46. from update_payload import common
  47. from update_payload.error import PayloadError
  48. #
  49. # Helper functions.
  50. #
  51. def _VerifySha256(file_obj, expected_hash, name, length=-1):
  52. """Verifies the SHA256 hash of a file.
  53. Args:
  54. file_obj: file object to read
  55. expected_hash: the hash digest we expect to be getting
  56. name: name string of this hash, for error reporting
  57. length: precise length of data to verify (optional)
  58. Raises:
  59. PayloadError if computed hash doesn't match expected one, or if fails to
  60. read the specified length of data.
  61. """
  62. hasher = hashlib.sha256()
  63. block_length = 1024 * 1024
  64. max_length = length if length >= 0 else sys.maxint
  65. while max_length > 0:
  66. read_length = min(max_length, block_length)
  67. data = file_obj.read(read_length)
  68. if not data:
  69. break
  70. max_length -= len(data)
  71. hasher.update(data)
  72. if length >= 0 and max_length > 0:
  73. raise PayloadError(
  74. 'insufficient data (%d instead of %d) when verifying %s' %
  75. (length - max_length, length, name))
  76. actual_hash = hasher.digest()
  77. if actual_hash != expected_hash:
  78. raise PayloadError('%s hash (%s) not as expected (%s)' %
  79. (name, common.FormatSha256(actual_hash),
  80. common.FormatSha256(expected_hash)))
  81. def _ReadExtents(file_obj, extents, block_size, max_length=-1):
  82. """Reads data from file as defined by extent sequence.
  83. This tries to be efficient by not copying data as it is read in chunks.
  84. Args:
  85. file_obj: file object
  86. extents: sequence of block extents (offset and length)
  87. block_size: size of each block
  88. max_length: maximum length to read (optional)
  89. Returns:
  90. A character array containing the concatenated read data.
  91. """
  92. data = array.array('c')
  93. if max_length < 0:
  94. max_length = sys.maxint
  95. for ex in extents:
  96. if max_length == 0:
  97. break
  98. read_length = min(max_length, ex.num_blocks * block_size)
  99. # Fill with zeros or read from file, depending on the type of extent.
  100. if ex.start_block == common.PSEUDO_EXTENT_MARKER:
  101. data.extend(itertools.repeat('\0', read_length))
  102. else:
  103. file_obj.seek(ex.start_block * block_size)
  104. data.fromfile(file_obj, read_length)
  105. max_length -= read_length
  106. return data
  107. def _WriteExtents(file_obj, data, extents, block_size, base_name):
  108. """Writes data to file as defined by extent sequence.
  109. This tries to be efficient by not copy data as it is written in chunks.
  110. Args:
  111. file_obj: file object
  112. data: data to write
  113. extents: sequence of block extents (offset and length)
  114. block_size: size of each block
  115. base_name: name string of extent sequence for error reporting
  116. Raises:
  117. PayloadError when things don't add up.
  118. """
  119. data_offset = 0
  120. data_length = len(data)
  121. for ex, ex_name in common.ExtentIter(extents, base_name):
  122. if not data_length:
  123. raise PayloadError('%s: more write extents than data' % ex_name)
  124. write_length = min(data_length, ex.num_blocks * block_size)
  125. # Only do actual writing if this is not a pseudo-extent.
  126. if ex.start_block != common.PSEUDO_EXTENT_MARKER:
  127. file_obj.seek(ex.start_block * block_size)
  128. data_view = buffer(data, data_offset, write_length)
  129. file_obj.write(data_view)
  130. data_offset += write_length
  131. data_length -= write_length
  132. if data_length:
  133. raise PayloadError('%s: more data than write extents' % base_name)
  134. def _ExtentsToBspatchArg(extents, block_size, base_name, data_length=-1):
  135. """Translates an extent sequence into a bspatch-compatible string argument.
  136. Args:
  137. extents: sequence of block extents (offset and length)
  138. block_size: size of each block
  139. base_name: name string of extent sequence for error reporting
  140. data_length: the actual total length of the data in bytes (optional)
  141. Returns:
  142. A tuple consisting of (i) a string of the form
  143. "off_1:len_1,...,off_n:len_n", (ii) an offset where zero padding is needed
  144. for filling the last extent, (iii) the length of the padding (zero means no
  145. padding is needed and the extents cover the full length of data).
  146. Raises:
  147. PayloadError if data_length is too short or too long.
  148. """
  149. arg = ''
  150. pad_off = pad_len = 0
  151. if data_length < 0:
  152. data_length = sys.maxint
  153. for ex, ex_name in common.ExtentIter(extents, base_name):
  154. if not data_length:
  155. raise PayloadError('%s: more extents than total data length' % ex_name)
  156. is_pseudo = ex.start_block == common.PSEUDO_EXTENT_MARKER
  157. start_byte = -1 if is_pseudo else ex.start_block * block_size
  158. num_bytes = ex.num_blocks * block_size
  159. if data_length < num_bytes:
  160. # We're only padding a real extent.
  161. if not is_pseudo:
  162. pad_off = start_byte + data_length
  163. pad_len = num_bytes - data_length
  164. num_bytes = data_length
  165. arg += '%s%d:%d' % (arg and ',', start_byte, num_bytes)
  166. data_length -= num_bytes
  167. if data_length:
  168. raise PayloadError('%s: extents not covering full data length' % base_name)
  169. return arg, pad_off, pad_len
  170. #
  171. # Payload application.
  172. #
  173. class PayloadApplier(object):
  174. """Applying an update payload.
  175. This is a short-lived object whose purpose is to isolate the logic used for
  176. applying an update payload.
  177. """
  178. def __init__(self, payload, bsdiff_in_place=True, bspatch_path=None,
  179. puffpatch_path=None, truncate_to_expected_size=True):
  180. """Initialize the applier.
  181. Args:
  182. payload: the payload object to check
  183. bsdiff_in_place: whether to perform BSDIFF operation in-place (optional)
  184. bspatch_path: path to the bspatch binary (optional)
  185. puffpatch_path: path to the puffpatch binary (optional)
  186. truncate_to_expected_size: whether to truncate the resulting partitions
  187. to their expected sizes, as specified in the
  188. payload (optional)
  189. """
  190. assert payload.is_init, 'uninitialized update payload'
  191. self.payload = payload
  192. self.block_size = payload.manifest.block_size
  193. self.minor_version = payload.manifest.minor_version
  194. self.bsdiff_in_place = bsdiff_in_place
  195. self.bspatch_path = bspatch_path or 'bspatch'
  196. self.puffpatch_path = puffpatch_path or 'puffin'
  197. self.truncate_to_expected_size = truncate_to_expected_size
  198. def _ApplyReplaceOperation(self, op, op_name, out_data, part_file, part_size):
  199. """Applies a REPLACE{,_BZ,_XZ} operation.
  200. Args:
  201. op: the operation object
  202. op_name: name string for error reporting
  203. out_data: the data to be written
  204. part_file: the partition file object
  205. part_size: the size of the partition
  206. Raises:
  207. PayloadError if something goes wrong.
  208. """
  209. block_size = self.block_size
  210. data_length = len(out_data)
  211. # Decompress data if needed.
  212. if op.type == common.OpType.REPLACE_BZ:
  213. out_data = bz2.decompress(out_data)
  214. data_length = len(out_data)
  215. elif op.type == common.OpType.REPLACE_XZ:
  216. # pylint: disable=no-member
  217. out_data = lzma.decompress(out_data)
  218. data_length = len(out_data)
  219. # Write data to blocks specified in dst extents.
  220. data_start = 0
  221. for ex, ex_name in common.ExtentIter(op.dst_extents,
  222. '%s.dst_extents' % op_name):
  223. start_block = ex.start_block
  224. num_blocks = ex.num_blocks
  225. count = num_blocks * block_size
  226. # Make sure it's not a fake (signature) operation.
  227. if start_block != common.PSEUDO_EXTENT_MARKER:
  228. data_end = data_start + count
  229. # Make sure we're not running past partition boundary.
  230. if (start_block + num_blocks) * block_size > part_size:
  231. raise PayloadError(
  232. '%s: extent (%s) exceeds partition size (%d)' %
  233. (ex_name, common.FormatExtent(ex, block_size),
  234. part_size))
  235. # Make sure that we have enough data to write.
  236. if data_end >= data_length + block_size:
  237. raise PayloadError(
  238. '%s: more dst blocks than data (even with padding)')
  239. # Pad with zeros if necessary.
  240. if data_end > data_length:
  241. padding = data_end - data_length
  242. out_data += '\0' * padding
  243. self.payload.payload_file.seek(start_block * block_size)
  244. part_file.seek(start_block * block_size)
  245. part_file.write(out_data[data_start:data_end])
  246. data_start += count
  247. # Make sure we wrote all data.
  248. if data_start < data_length:
  249. raise PayloadError('%s: wrote fewer bytes (%d) than expected (%d)' %
  250. (op_name, data_start, data_length))
  251. def _ApplyMoveOperation(self, op, op_name, part_file):
  252. """Applies a MOVE operation.
  253. Note that this operation must read the whole block data from the input and
  254. only then dump it, due to our in-place update semantics; otherwise, it
  255. might clobber data midway through.
  256. Args:
  257. op: the operation object
  258. op_name: name string for error reporting
  259. part_file: the partition file object
  260. Raises:
  261. PayloadError if something goes wrong.
  262. """
  263. block_size = self.block_size
  264. # Gather input raw data from src extents.
  265. in_data = _ReadExtents(part_file, op.src_extents, block_size)
  266. # Dump extracted data to dst extents.
  267. _WriteExtents(part_file, in_data, op.dst_extents, block_size,
  268. '%s.dst_extents' % op_name)
  269. def _ApplyZeroOperation(self, op, op_name, part_file):
  270. """Applies a ZERO operation.
  271. Args:
  272. op: the operation object
  273. op_name: name string for error reporting
  274. part_file: the partition file object
  275. Raises:
  276. PayloadError if something goes wrong.
  277. """
  278. block_size = self.block_size
  279. base_name = '%s.dst_extents' % op_name
  280. # Iterate over the extents and write zero.
  281. # pylint: disable=unused-variable
  282. for ex, ex_name in common.ExtentIter(op.dst_extents, base_name):
  283. # Only do actual writing if this is not a pseudo-extent.
  284. if ex.start_block != common.PSEUDO_EXTENT_MARKER:
  285. part_file.seek(ex.start_block * block_size)
  286. part_file.write('\0' * (ex.num_blocks * block_size))
  287. def _ApplySourceCopyOperation(self, op, op_name, old_part_file,
  288. new_part_file):
  289. """Applies a SOURCE_COPY operation.
  290. Args:
  291. op: the operation object
  292. op_name: name string for error reporting
  293. old_part_file: the old partition file object
  294. new_part_file: the new partition file object
  295. Raises:
  296. PayloadError if something goes wrong.
  297. """
  298. if not old_part_file:
  299. raise PayloadError(
  300. '%s: no source partition file provided for operation type (%d)' %
  301. (op_name, op.type))
  302. block_size = self.block_size
  303. # Gather input raw data from src extents.
  304. in_data = _ReadExtents(old_part_file, op.src_extents, block_size)
  305. # Dump extracted data to dst extents.
  306. _WriteExtents(new_part_file, in_data, op.dst_extents, block_size,
  307. '%s.dst_extents' % op_name)
  308. def _BytesInExtents(self, extents, base_name):
  309. """Counts the length of extents in bytes.
  310. Args:
  311. extents: The list of Extents.
  312. base_name: For error reporting.
  313. Returns:
  314. The number of bytes in extents.
  315. """
  316. length = 0
  317. # pylint: disable=unused-variable
  318. for ex, ex_name in common.ExtentIter(extents, base_name):
  319. length += ex.num_blocks * self.block_size
  320. return length
  321. def _ApplyDiffOperation(self, op, op_name, patch_data, old_part_file,
  322. new_part_file):
  323. """Applies a SOURCE_BSDIFF, BROTLI_BSDIFF or PUFFDIFF operation.
  324. Args:
  325. op: the operation object
  326. op_name: name string for error reporting
  327. patch_data: the binary patch content
  328. old_part_file: the source partition file object
  329. new_part_file: the target partition file object
  330. Raises:
  331. PayloadError if something goes wrong.
  332. """
  333. if not old_part_file:
  334. raise PayloadError(
  335. '%s: no source partition file provided for operation type (%d)' %
  336. (op_name, op.type))
  337. block_size = self.block_size
  338. # Dump patch data to file.
  339. with tempfile.NamedTemporaryFile(delete=False) as patch_file:
  340. patch_file_name = patch_file.name
  341. patch_file.write(patch_data)
  342. if (hasattr(new_part_file, 'fileno') and
  343. ((not old_part_file) or hasattr(old_part_file, 'fileno'))):
  344. # Construct input and output extents argument for bspatch.
  345. in_extents_arg, _, _ = _ExtentsToBspatchArg(
  346. op.src_extents, block_size, '%s.src_extents' % op_name,
  347. data_length=op.src_length if op.src_length else
  348. self._BytesInExtents(op.src_extents, "%s.src_extents"))
  349. out_extents_arg, pad_off, pad_len = _ExtentsToBspatchArg(
  350. op.dst_extents, block_size, '%s.dst_extents' % op_name,
  351. data_length=op.dst_length if op.dst_length else
  352. self._BytesInExtents(op.dst_extents, "%s.dst_extents"))
  353. new_file_name = '/dev/fd/%d' % new_part_file.fileno()
  354. # Diff from source partition.
  355. old_file_name = '/dev/fd/%d' % old_part_file.fileno()
  356. if op.type in (common.OpType.BSDIFF, common.OpType.SOURCE_BSDIFF,
  357. common.OpType.BROTLI_BSDIFF):
  358. # Invoke bspatch on partition file with extents args.
  359. bspatch_cmd = [self.bspatch_path, old_file_name, new_file_name,
  360. patch_file_name, in_extents_arg, out_extents_arg]
  361. subprocess.check_call(bspatch_cmd)
  362. elif op.type == common.OpType.PUFFDIFF:
  363. # Invoke puffpatch on partition file with extents args.
  364. puffpatch_cmd = [self.puffpatch_path,
  365. "--operation=puffpatch",
  366. "--src_file=%s" % old_file_name,
  367. "--dst_file=%s" % new_file_name,
  368. "--patch_file=%s" % patch_file_name,
  369. "--src_extents=%s" % in_extents_arg,
  370. "--dst_extents=%s" % out_extents_arg]
  371. subprocess.check_call(puffpatch_cmd)
  372. else:
  373. raise PayloadError("Unknown operation %s", op.type)
  374. # Pad with zeros past the total output length.
  375. if pad_len:
  376. new_part_file.seek(pad_off)
  377. new_part_file.write('\0' * pad_len)
  378. else:
  379. # Gather input raw data and write to a temp file.
  380. input_part_file = old_part_file if old_part_file else new_part_file
  381. in_data = _ReadExtents(input_part_file, op.src_extents, block_size,
  382. max_length=op.src_length if op.src_length else
  383. self._BytesInExtents(op.src_extents,
  384. "%s.src_extents"))
  385. with tempfile.NamedTemporaryFile(delete=False) as in_file:
  386. in_file_name = in_file.name
  387. in_file.write(in_data)
  388. # Allocate temporary output file.
  389. with tempfile.NamedTemporaryFile(delete=False) as out_file:
  390. out_file_name = out_file.name
  391. if op.type in (common.OpType.BSDIFF, common.OpType.SOURCE_BSDIFF,
  392. common.OpType.BROTLI_BSDIFF):
  393. # Invoke bspatch.
  394. bspatch_cmd = [self.bspatch_path, in_file_name, out_file_name,
  395. patch_file_name]
  396. subprocess.check_call(bspatch_cmd)
  397. elif op.type == common.OpType.PUFFDIFF:
  398. # Invoke puffpatch.
  399. puffpatch_cmd = [self.puffpatch_path,
  400. "--operation=puffpatch",
  401. "--src_file=%s" % in_file_name,
  402. "--dst_file=%s" % out_file_name,
  403. "--patch_file=%s" % patch_file_name]
  404. subprocess.check_call(puffpatch_cmd)
  405. else:
  406. raise PayloadError("Unknown operation %s", op.type)
  407. # Read output.
  408. with open(out_file_name, 'rb') as out_file:
  409. out_data = out_file.read()
  410. if len(out_data) != op.dst_length:
  411. raise PayloadError(
  412. '%s: actual patched data length (%d) not as expected (%d)' %
  413. (op_name, len(out_data), op.dst_length))
  414. # Write output back to partition, with padding.
  415. unaligned_out_len = len(out_data) % block_size
  416. if unaligned_out_len:
  417. out_data += '\0' * (block_size - unaligned_out_len)
  418. _WriteExtents(new_part_file, out_data, op.dst_extents, block_size,
  419. '%s.dst_extents' % op_name)
  420. # Delete input/output files.
  421. os.remove(in_file_name)
  422. os.remove(out_file_name)
  423. # Delete patch file.
  424. os.remove(patch_file_name)
  425. def _ApplyOperations(self, operations, base_name, old_part_file,
  426. new_part_file, part_size):
  427. """Applies a sequence of update operations to a partition.
  428. This assumes an in-place update semantics for MOVE and BSDIFF, namely all
  429. reads are performed first, then the data is processed and written back to
  430. the same file.
  431. Args:
  432. operations: the sequence of operations
  433. base_name: the name of the operation sequence
  434. old_part_file: the old partition file object, open for reading/writing
  435. new_part_file: the new partition file object, open for reading/writing
  436. part_size: the partition size
  437. Raises:
  438. PayloadError if anything goes wrong while processing the payload.
  439. """
  440. for op, op_name in common.OperationIter(operations, base_name):
  441. # Read data blob.
  442. data = self.payload.ReadDataBlob(op.data_offset, op.data_length)
  443. if op.type in (common.OpType.REPLACE, common.OpType.REPLACE_BZ,
  444. common.OpType.REPLACE_XZ):
  445. self._ApplyReplaceOperation(op, op_name, data, new_part_file, part_size)
  446. elif op.type == common.OpType.MOVE:
  447. self._ApplyMoveOperation(op, op_name, new_part_file)
  448. elif op.type == common.OpType.ZERO:
  449. self._ApplyZeroOperation(op, op_name, new_part_file)
  450. elif op.type == common.OpType.BSDIFF:
  451. self._ApplyDiffOperation(op, op_name, data, new_part_file,
  452. new_part_file)
  453. elif op.type == common.OpType.SOURCE_COPY:
  454. self._ApplySourceCopyOperation(op, op_name, old_part_file,
  455. new_part_file)
  456. elif op.type in (common.OpType.SOURCE_BSDIFF, common.OpType.PUFFDIFF,
  457. common.OpType.BROTLI_BSDIFF):
  458. self._ApplyDiffOperation(op, op_name, data, old_part_file,
  459. new_part_file)
  460. else:
  461. raise PayloadError('%s: unknown operation type (%d)' %
  462. (op_name, op.type))
  463. def _ApplyToPartition(self, operations, part_name, base_name,
  464. new_part_file_name, new_part_info,
  465. old_part_file_name=None, old_part_info=None):
  466. """Applies an update to a partition.
  467. Args:
  468. operations: the sequence of update operations to apply
  469. part_name: the name of the partition, for error reporting
  470. base_name: the name of the operation sequence
  471. new_part_file_name: file name to write partition data to
  472. new_part_info: size and expected hash of dest partition
  473. old_part_file_name: file name of source partition (optional)
  474. old_part_info: size and expected hash of source partition (optional)
  475. Raises:
  476. PayloadError if anything goes wrong with the update.
  477. """
  478. # Do we have a source partition?
  479. if old_part_file_name:
  480. # Verify the source partition.
  481. with open(old_part_file_name, 'rb') as old_part_file:
  482. _VerifySha256(old_part_file, old_part_info.hash,
  483. 'old ' + part_name, length=old_part_info.size)
  484. new_part_file_mode = 'r+b'
  485. if self.minor_version == common.INPLACE_MINOR_PAYLOAD_VERSION:
  486. # Copy the src partition to the dst one; make sure we don't truncate it.
  487. shutil.copyfile(old_part_file_name, new_part_file_name)
  488. elif self.minor_version >= common.SOURCE_MINOR_PAYLOAD_VERSION:
  489. # In minor version >= 2, we don't want to copy the partitions, so
  490. # instead just make the new partition file.
  491. open(new_part_file_name, 'w').close()
  492. else:
  493. raise PayloadError("Unknown minor version: %d" % self.minor_version)
  494. else:
  495. # We need to create/truncate the dst partition file.
  496. new_part_file_mode = 'w+b'
  497. # Apply operations.
  498. with open(new_part_file_name, new_part_file_mode) as new_part_file:
  499. old_part_file = (open(old_part_file_name, 'r+b')
  500. if old_part_file_name else None)
  501. try:
  502. self._ApplyOperations(operations, base_name, old_part_file,
  503. new_part_file, new_part_info.size)
  504. finally:
  505. if old_part_file:
  506. old_part_file.close()
  507. # Truncate the result, if so instructed.
  508. if self.truncate_to_expected_size:
  509. new_part_file.seek(0, 2)
  510. if new_part_file.tell() > new_part_info.size:
  511. new_part_file.seek(new_part_info.size)
  512. new_part_file.truncate()
  513. # Verify the resulting partition.
  514. with open(new_part_file_name, 'rb') as new_part_file:
  515. _VerifySha256(new_part_file, new_part_info.hash,
  516. 'new ' + part_name, length=new_part_info.size)
  517. def Run(self, new_parts, old_parts=None):
  518. """Applier entry point, invoking all update operations.
  519. Args:
  520. new_parts: map of partition name to dest partition file
  521. old_parts: map of partition name to source partition file (optional)
  522. Raises:
  523. PayloadError if payload application failed.
  524. """
  525. if old_parts is None:
  526. old_parts = {}
  527. self.payload.ResetFile()
  528. new_part_info = {}
  529. old_part_info = {}
  530. install_operations = []
  531. manifest = self.payload.manifest
  532. if self.payload.header.version == 1:
  533. for real_name, proto_name in common.CROS_PARTITIONS:
  534. new_part_info[real_name] = getattr(manifest, 'new_%s_info' % proto_name)
  535. old_part_info[real_name] = getattr(manifest, 'old_%s_info' % proto_name)
  536. install_operations.append((common.ROOTFS, manifest.install_operations))
  537. install_operations.append((common.KERNEL,
  538. manifest.kernel_install_operations))
  539. else:
  540. for part in manifest.partitions:
  541. name = part.partition_name
  542. new_part_info[name] = part.new_partition_info
  543. old_part_info[name] = part.old_partition_info
  544. install_operations.append((name, part.operations))
  545. part_names = set(new_part_info.keys()) # Equivalently, old_part_info.keys()
  546. # Make sure the arguments are sane and match the payload.
  547. new_part_names = set(new_parts.keys())
  548. if new_part_names != part_names:
  549. raise PayloadError('missing dst partition(s) %s' %
  550. ', '.join(part_names - new_part_names))
  551. old_part_names = set(old_parts.keys())
  552. if part_names - old_part_names:
  553. if self.payload.IsDelta():
  554. raise PayloadError('trying to apply a delta update without src '
  555. 'partition(s) %s' %
  556. ', '.join(part_names - old_part_names))
  557. elif old_part_names == part_names:
  558. if self.payload.IsFull():
  559. raise PayloadError('trying to apply a full update onto src partitions')
  560. else:
  561. raise PayloadError('not all src partitions provided')
  562. for name, operations in install_operations:
  563. # Apply update to partition.
  564. self._ApplyToPartition(
  565. operations, name, '%s_install_operations' % name, new_parts[name],
  566. new_part_info[name], old_parts.get(name, None), old_part_info[name])