control.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2016 Google, Inc
  3. # Written by Simon Glass <sjg@chromium.org>
  4. #
  5. # Creates binary images from input files controlled by a description
  6. #
  7. from collections import OrderedDict
  8. import glob
  9. try:
  10. import importlib.resources
  11. except ImportError: # pragma: no cover
  12. # for Python 3.6
  13. import importlib_resources
  14. import os
  15. import pkg_resources
  16. import re
  17. import sys
  18. from binman import bintool
  19. from binman import cbfs_util
  20. from binman import elf
  21. from binman import entry
  22. from dtoc import fdt_util
  23. from u_boot_pylib import command
  24. from u_boot_pylib import tools
  25. from u_boot_pylib import tout
  26. # These are imported if needed since they import libfdt
  27. state = None
  28. Image = None
  29. # List of images we plan to create
  30. # Make this global so that it can be referenced from tests
  31. images = OrderedDict()
  32. # Help text for each type of missing blob, dict:
  33. # key: Value of the entry's 'missing-msg' or entry name
  34. # value: Text for the help
  35. missing_blob_help = {}
  36. def _ReadImageDesc(binman_node, use_expanded):
  37. """Read the image descriptions from the /binman node
  38. This normally produces a single Image object called 'image'. But if
  39. multiple images are present, they will all be returned.
  40. Args:
  41. binman_node: Node object of the /binman node
  42. use_expanded: True if the FDT will be updated with the entry information
  43. Returns:
  44. OrderedDict of Image objects, each of which describes an image
  45. """
  46. # For Image()
  47. # pylint: disable=E1102
  48. images = OrderedDict()
  49. if 'multiple-images' in binman_node.props:
  50. for node in binman_node.subnodes:
  51. if not node.name.startswith('template'):
  52. images[node.name] = Image(node.name, node,
  53. use_expanded=use_expanded)
  54. else:
  55. images['image'] = Image('image', binman_node, use_expanded=use_expanded)
  56. return images
  57. def _FindBinmanNode(dtb):
  58. """Find the 'binman' node in the device tree
  59. Args:
  60. dtb: Fdt object to scan
  61. Returns:
  62. Node object of /binman node, or None if not found
  63. """
  64. for node in dtb.GetRoot().subnodes:
  65. if node.name == 'binman':
  66. return node
  67. return None
  68. def _ReadMissingBlobHelp():
  69. """Read the missing-blob-help file
  70. This file containins help messages explaining what to do when external blobs
  71. are missing.
  72. Returns:
  73. Dict:
  74. key: Message tag (str)
  75. value: Message text (str)
  76. """
  77. def _FinishTag(tag, msg, result):
  78. if tag:
  79. result[tag] = msg.rstrip()
  80. tag = None
  81. msg = ''
  82. return tag, msg
  83. my_data = pkg_resources.resource_string(__name__, 'missing-blob-help')
  84. re_tag = re.compile('^([-a-z0-9]+):$')
  85. result = {}
  86. tag = None
  87. msg = ''
  88. for line in my_data.decode('utf-8').splitlines():
  89. if not line.startswith('#'):
  90. m_tag = re_tag.match(line)
  91. if m_tag:
  92. _, msg = _FinishTag(tag, msg, result)
  93. tag = m_tag.group(1)
  94. elif tag:
  95. msg += line + '\n'
  96. _FinishTag(tag, msg, result)
  97. return result
  98. def _ShowBlobHelp(level, path, text, fname):
  99. tout.do_output(level, '%s (%s):' % (path, fname))
  100. for line in text.splitlines():
  101. tout.do_output(level, ' %s' % line)
  102. tout.do_output(level, '')
  103. def _ShowHelpForMissingBlobs(level, missing_list):
  104. """Show help for each missing blob to help the user take action
  105. Args:
  106. missing_list: List of Entry objects to show help for
  107. """
  108. global missing_blob_help
  109. if not missing_blob_help:
  110. missing_blob_help = _ReadMissingBlobHelp()
  111. for entry in missing_list:
  112. tags = entry.GetHelpTags()
  113. # Show the first match help message
  114. shown_help = False
  115. for tag in tags:
  116. if tag in missing_blob_help:
  117. _ShowBlobHelp(level, entry._node.path, missing_blob_help[tag],
  118. entry.GetDefaultFilename())
  119. shown_help = True
  120. break
  121. # Or a generic help message
  122. if not shown_help:
  123. _ShowBlobHelp(level, entry._node.path, "Missing blob",
  124. entry.GetDefaultFilename())
  125. def GetEntryModules(include_testing=True):
  126. """Get a set of entry class implementations
  127. Returns:
  128. Set of paths to entry class filenames
  129. """
  130. glob_list = pkg_resources.resource_listdir(__name__, 'etype')
  131. glob_list = [fname for fname in glob_list if fname.endswith('.py')]
  132. return set([os.path.splitext(os.path.basename(item))[0]
  133. for item in glob_list
  134. if include_testing or '_testing' not in item])
  135. def WriteEntryDocs(modules, test_missing=None):
  136. """Write out documentation for all entries
  137. Args:
  138. modules: List of Module objects to get docs for
  139. test_missing: Used for testing only, to force an entry's documentation
  140. to show as missing even if it is present. Should be set to None in
  141. normal use.
  142. """
  143. from binman.entry import Entry
  144. Entry.WriteDocs(modules, test_missing)
  145. def write_bintool_docs(modules, test_missing=None):
  146. """Write out documentation for all bintools
  147. Args:
  148. modules: List of Module objects to get docs for
  149. test_missing: Used for testing only, to force an entry's documentation
  150. to show as missing even if it is present. Should be set to None in
  151. normal use.
  152. """
  153. bintool.Bintool.WriteDocs(modules, test_missing)
  154. def ListEntries(image_fname, entry_paths):
  155. """List the entries in an image
  156. This decodes the supplied image and displays a table of entries from that
  157. image, preceded by a header.
  158. Args:
  159. image_fname: Image filename to process
  160. entry_paths: List of wildcarded paths (e.g. ['*dtb*', 'u-boot*',
  161. 'section/u-boot'])
  162. """
  163. image = Image.FromFile(image_fname)
  164. entries, lines, widths = image.GetListEntries(entry_paths)
  165. num_columns = len(widths)
  166. for linenum, line in enumerate(lines):
  167. if linenum == 1:
  168. # Print header line
  169. print('-' * (sum(widths) + num_columns * 2))
  170. out = ''
  171. for i, item in enumerate(line):
  172. width = -widths[i]
  173. if item.startswith('>'):
  174. width = -width
  175. item = item[1:]
  176. txt = '%*s ' % (width, item)
  177. out += txt
  178. print(out.rstrip())
  179. def ReadEntry(image_fname, entry_path, decomp=True):
  180. """Extract an entry from an image
  181. This extracts the data from a particular entry in an image
  182. Args:
  183. image_fname: Image filename to process
  184. entry_path: Path to entry to extract
  185. decomp: True to return uncompressed data, if the data is compress
  186. False to return the raw data
  187. Returns:
  188. data extracted from the entry
  189. """
  190. global Image
  191. from binman.image import Image
  192. image = Image.FromFile(image_fname)
  193. image.CollectBintools()
  194. entry = image.FindEntryPath(entry_path)
  195. return entry.ReadData(decomp)
  196. def ShowAltFormats(image):
  197. """Show alternative formats available for entries in the image
  198. This shows a list of formats available.
  199. Args:
  200. image (Image): Image to check
  201. """
  202. alt_formats = {}
  203. image.CheckAltFormats(alt_formats)
  204. print('%-10s %-20s %s' % ('Flag (-F)', 'Entry type', 'Description'))
  205. for name, val in alt_formats.items():
  206. entry, helptext = val
  207. print('%-10s %-20s %s' % (name, entry.etype, helptext))
  208. def ExtractEntries(image_fname, output_fname, outdir, entry_paths,
  209. decomp=True, alt_format=None):
  210. """Extract the data from one or more entries and write it to files
  211. Args:
  212. image_fname: Image filename to process
  213. output_fname: Single output filename to use if extracting one file, None
  214. otherwise
  215. outdir: Output directory to use (for any number of files), else None
  216. entry_paths: List of entry paths to extract
  217. decomp: True to decompress the entry data
  218. Returns:
  219. List of EntryInfo records that were written
  220. """
  221. image = Image.FromFile(image_fname)
  222. image.CollectBintools()
  223. if alt_format == 'list':
  224. ShowAltFormats(image)
  225. return
  226. # Output an entry to a single file, as a special case
  227. if output_fname:
  228. if not entry_paths:
  229. raise ValueError('Must specify an entry path to write with -f')
  230. if len(entry_paths) != 1:
  231. raise ValueError('Must specify exactly one entry path to write with -f')
  232. entry = image.FindEntryPath(entry_paths[0])
  233. data = entry.ReadData(decomp, alt_format)
  234. tools.write_file(output_fname, data)
  235. tout.notice("Wrote %#x bytes to file '%s'" % (len(data), output_fname))
  236. return
  237. # Otherwise we will output to a path given by the entry path of each entry.
  238. # This means that entries will appear in subdirectories if they are part of
  239. # a sub-section.
  240. einfos = image.GetListEntries(entry_paths)[0]
  241. tout.notice('%d entries match and will be written' % len(einfos))
  242. for einfo in einfos:
  243. entry = einfo.entry
  244. data = entry.ReadData(decomp, alt_format)
  245. path = entry.GetPath()[1:]
  246. fname = os.path.join(outdir, path)
  247. # If this entry has children, create a directory for it and put its
  248. # data in a file called 'root' in that directory
  249. if entry.GetEntries():
  250. if fname and not os.path.exists(fname):
  251. os.makedirs(fname)
  252. fname = os.path.join(fname, 'root')
  253. tout.notice("Write entry '%s' size %x to '%s'" %
  254. (entry.GetPath(), len(data), fname))
  255. tools.write_file(fname, data)
  256. return einfos
  257. def BeforeReplace(image, allow_resize):
  258. """Handle getting an image ready for replacing entries in it
  259. Args:
  260. image: Image to prepare
  261. """
  262. state.PrepareFromLoadedData(image)
  263. image.CollectBintools()
  264. image.LoadData(decomp=False)
  265. # If repacking, drop the old offset/size values except for the original
  266. # ones, so we are only left with the constraints.
  267. if image.allow_repack and allow_resize:
  268. image.ResetForPack()
  269. def ReplaceOneEntry(image, entry, data, do_compress, allow_resize):
  270. """Handle replacing a single entry an an image
  271. Args:
  272. image: Image to update
  273. entry: Entry to write
  274. data: Data to replace with
  275. do_compress: True to compress the data if needed, False if data is
  276. already compressed so should be used as is
  277. allow_resize: True to allow entries to change size (this does a re-pack
  278. of the entries), False to raise an exception
  279. """
  280. if not entry.WriteData(data, do_compress):
  281. if not image.allow_repack:
  282. entry.Raise('Entry data size does not match, but allow-repack is not present for this image')
  283. if not allow_resize:
  284. entry.Raise('Entry data size does not match, but resize is disabled')
  285. def AfterReplace(image, allow_resize, write_map):
  286. """Handle write out an image after replacing entries in it
  287. Args:
  288. image: Image to write
  289. allow_resize: True to allow entries to change size (this does a re-pack
  290. of the entries), False to raise an exception
  291. write_map: True to write a map file
  292. """
  293. tout.info('Processing image')
  294. ProcessImage(image, update_fdt=True, write_map=write_map,
  295. get_contents=False, allow_resize=allow_resize)
  296. def WriteEntryToImage(image, entry, data, do_compress=True, allow_resize=True,
  297. write_map=False):
  298. BeforeReplace(image, allow_resize)
  299. tout.info('Writing data to %s' % entry.GetPath())
  300. ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
  301. AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
  302. def WriteEntry(image_fname, entry_path, data, do_compress=True,
  303. allow_resize=True, write_map=False):
  304. """Replace an entry in an image
  305. This replaces the data in a particular entry in an image. This size of the
  306. new data must match the size of the old data unless allow_resize is True.
  307. Args:
  308. image_fname: Image filename to process
  309. entry_path: Path to entry to extract
  310. data: Data to replace with
  311. do_compress: True to compress the data if needed, False if data is
  312. already compressed so should be used as is
  313. allow_resize: True to allow entries to change size (this does a re-pack
  314. of the entries), False to raise an exception
  315. write_map: True to write a map file
  316. Returns:
  317. Image object that was updated
  318. """
  319. tout.info("Write entry '%s', file '%s'" % (entry_path, image_fname))
  320. image = Image.FromFile(image_fname)
  321. image.CollectBintools()
  322. entry = image.FindEntryPath(entry_path)
  323. WriteEntryToImage(image, entry, data, do_compress=do_compress,
  324. allow_resize=allow_resize, write_map=write_map)
  325. return image
  326. def ReplaceEntries(image_fname, input_fname, indir, entry_paths,
  327. do_compress=True, allow_resize=True, write_map=False):
  328. """Replace the data from one or more entries from input files
  329. Args:
  330. image_fname: Image filename to process
  331. input_fname: Single input filename to use if replacing one file, None
  332. otherwise
  333. indir: Input directory to use (for any number of files), else None
  334. entry_paths: List of entry paths to replace
  335. do_compress: True if the input data is uncompressed and may need to be
  336. compressed if the entry requires it, False if the data is already
  337. compressed.
  338. write_map: True to write a map file
  339. Returns:
  340. List of EntryInfo records that were written
  341. """
  342. image_fname = os.path.abspath(image_fname)
  343. image = Image.FromFile(image_fname)
  344. image.mark_build_done()
  345. # Replace an entry from a single file, as a special case
  346. if input_fname:
  347. if not entry_paths:
  348. raise ValueError('Must specify an entry path to read with -f')
  349. if len(entry_paths) != 1:
  350. raise ValueError('Must specify exactly one entry path to write with -f')
  351. entry = image.FindEntryPath(entry_paths[0])
  352. data = tools.read_file(input_fname)
  353. tout.notice("Read %#x bytes from file '%s'" % (len(data), input_fname))
  354. WriteEntryToImage(image, entry, data, do_compress=do_compress,
  355. allow_resize=allow_resize, write_map=write_map)
  356. return
  357. # Otherwise we will input from a path given by the entry path of each entry.
  358. # This means that files must appear in subdirectories if they are part of
  359. # a sub-section.
  360. einfos = image.GetListEntries(entry_paths)[0]
  361. tout.notice("Replacing %d matching entries in image '%s'" %
  362. (len(einfos), image_fname))
  363. BeforeReplace(image, allow_resize)
  364. for einfo in einfos:
  365. entry = einfo.entry
  366. if entry.GetEntries():
  367. tout.info("Skipping section entry '%s'" % entry.GetPath())
  368. continue
  369. path = entry.GetPath()[1:]
  370. fname = os.path.join(indir, path)
  371. if os.path.exists(fname):
  372. tout.notice("Write entry '%s' from file '%s'" %
  373. (entry.GetPath(), fname))
  374. data = tools.read_file(fname)
  375. ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
  376. else:
  377. tout.warning("Skipping entry '%s' from missing file '%s'" %
  378. (entry.GetPath(), fname))
  379. AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
  380. return image
  381. def SignEntries(image_fname, input_fname, privatekey_fname, algo, entry_paths,
  382. write_map=False):
  383. """Sign and replace the data from one or more entries from input files
  384. Args:
  385. image_fname: Image filename to process
  386. input_fname: Single input filename to use if replacing one file, None
  387. otherwise
  388. algo: Hashing algorithm
  389. entry_paths: List of entry paths to sign
  390. privatekey_fname: Private key filename
  391. write_map (bool): True to write the map file
  392. """
  393. image_fname = os.path.abspath(image_fname)
  394. image = Image.FromFile(image_fname)
  395. image.mark_build_done()
  396. BeforeReplace(image, allow_resize=True)
  397. for entry_path in entry_paths:
  398. entry = image.FindEntryPath(entry_path)
  399. entry.UpdateSignatures(privatekey_fname, algo, input_fname)
  400. AfterReplace(image, allow_resize=True, write_map=write_map)
  401. def _ProcessTemplates(parent):
  402. """Handle any templates in the binman description
  403. Args:
  404. parent: Binman node to process (typically /binman)
  405. Returns:
  406. bool: True if any templates were processed
  407. Search though each target node looking for those with an 'insert-template'
  408. property. Use that as a list of references to template nodes to use to
  409. adjust the target node.
  410. Processing involves copying each subnode of the template node into the
  411. target node.
  412. This is done recursively, so templates can be at any level of the binman
  413. image, e.g. inside a section.
  414. See 'Templates' in the Binman documnentation for details.
  415. """
  416. found = False
  417. for node in parent.subnodes:
  418. tmpl = fdt_util.GetPhandleList(node, 'insert-template')
  419. if tmpl:
  420. node.copy_subnodes_from_phandles(tmpl)
  421. found = True
  422. found |= _ProcessTemplates(node)
  423. return found
  424. def _RemoveTemplates(parent):
  425. """Remove any templates in the binman description
  426. """
  427. for node in parent.subnodes:
  428. if node.name.startswith('template'):
  429. node.Delete()
  430. def PrepareImagesAndDtbs(dtb_fname, select_images, update_fdt, use_expanded):
  431. """Prepare the images to be processed and select the device tree
  432. This function:
  433. - reads in the device tree
  434. - finds and scans the binman node to create all entries
  435. - selects which images to build
  436. - Updates the device tress with placeholder properties for offset,
  437. image-pos, etc.
  438. Args:
  439. dtb_fname: Filename of the device tree file to use (.dts or .dtb)
  440. selected_images: List of images to output, or None for all
  441. update_fdt: True to update the FDT wth entry offsets, etc.
  442. use_expanded: True to use expanded versions of entries, if available.
  443. So if 'u-boot' is called for, we use 'u-boot-expanded' instead. This
  444. is needed if update_fdt is True (although tests may disable it)
  445. Returns:
  446. OrderedDict of images:
  447. key: Image name (str)
  448. value: Image object
  449. """
  450. # Import these here in case libfdt.py is not available, in which case
  451. # the above help option still works.
  452. from dtoc import fdt
  453. from dtoc import fdt_util
  454. global images
  455. # Get the device tree ready by compiling it and copying the compiled
  456. # output into a file in our output directly. Then scan it for use
  457. # in binman.
  458. dtb_fname = fdt_util.EnsureCompiled(dtb_fname)
  459. fname = tools.get_output_filename('u-boot.dtb.out')
  460. tools.write_file(fname, tools.read_file(dtb_fname))
  461. dtb = fdt.FdtScan(fname)
  462. node = _FindBinmanNode(dtb)
  463. if not node:
  464. raise ValueError("Device tree '%s' does not have a 'binman' "
  465. "node" % dtb_fname)
  466. if _ProcessTemplates(node):
  467. dtb.Sync(True)
  468. fname = tools.get_output_filename('u-boot.dtb.tmpl1')
  469. tools.write_file(fname, dtb.GetContents())
  470. _RemoveTemplates(node)
  471. dtb.Sync(True)
  472. # Rescan the dtb to pick up the new phandles
  473. dtb.Scan()
  474. node = _FindBinmanNode(dtb)
  475. fname = tools.get_output_filename('u-boot.dtb.tmpl2')
  476. tools.write_file(fname, dtb.GetContents())
  477. images = _ReadImageDesc(node, use_expanded)
  478. if select_images:
  479. skip = []
  480. new_images = OrderedDict()
  481. for name, image in images.items():
  482. if name in select_images:
  483. new_images[name] = image
  484. else:
  485. skip.append(name)
  486. images = new_images
  487. tout.notice('Skipping images: %s' % ', '.join(skip))
  488. state.Prepare(images, dtb)
  489. # Prepare the device tree by making sure that any missing
  490. # properties are added (e.g. 'pos' and 'size'). The values of these
  491. # may not be correct yet, but we add placeholders so that the
  492. # size of the device tree is correct. Later, in
  493. # SetCalculatedProperties() we will insert the correct values
  494. # without changing the device-tree size, thus ensuring that our
  495. # entry offsets remain the same.
  496. for image in images.values():
  497. image.gen_entries()
  498. image.CollectBintools()
  499. if update_fdt:
  500. image.AddMissingProperties(True)
  501. image.ProcessFdt(dtb)
  502. for dtb_item in state.GetAllFdts():
  503. dtb_item.Sync(auto_resize=True)
  504. dtb_item.Pack()
  505. dtb_item.Flush()
  506. return images
  507. def ProcessImage(image, update_fdt, write_map, get_contents=True,
  508. allow_resize=True, allow_missing=False,
  509. allow_fake_blobs=False):
  510. """Perform all steps for this image, including checking and # writing it.
  511. This means that errors found with a later image will be reported after
  512. earlier images are already completed and written, but that does not seem
  513. important.
  514. Args:
  515. image: Image to process
  516. update_fdt: True to update the FDT wth entry offsets, etc.
  517. write_map: True to write a map file
  518. get_contents: True to get the image contents from files, etc., False if
  519. the contents is already present
  520. allow_resize: True to allow entries to change size (this does a re-pack
  521. of the entries), False to raise an exception
  522. allow_missing: Allow blob_ext objects to be missing
  523. allow_fake_blobs: Allow blob_ext objects to be faked with dummy files
  524. Returns:
  525. True if one or more external blobs are missing or faked,
  526. False if all are present
  527. """
  528. if get_contents:
  529. image.SetAllowMissing(allow_missing)
  530. image.SetAllowFakeBlob(allow_fake_blobs)
  531. image.GetEntryContents()
  532. image.drop_absent()
  533. image.GetEntryOffsets()
  534. # We need to pack the entries to figure out where everything
  535. # should be placed. This sets the offset/size of each entry.
  536. # However, after packing we call ProcessEntryContents() which
  537. # may result in an entry changing size. In that case we need to
  538. # do another pass. Since the device tree often contains the
  539. # final offset/size information we try to make space for this in
  540. # AddMissingProperties() above. However, if the device is
  541. # compressed we cannot know this compressed size in advance,
  542. # since changing an offset from 0x100 to 0x104 (for example) can
  543. # alter the compressed size of the device tree. So we need a
  544. # third pass for this.
  545. passes = 5
  546. for pack_pass in range(passes):
  547. try:
  548. image.PackEntries()
  549. except Exception as e:
  550. if write_map:
  551. fname = image.WriteMap()
  552. print("Wrote map file '%s' to show errors" % fname)
  553. raise
  554. image.SetImagePos()
  555. if update_fdt:
  556. image.SetCalculatedProperties()
  557. for dtb_item in state.GetAllFdts():
  558. dtb_item.Sync()
  559. dtb_item.Flush()
  560. image.WriteSymbols()
  561. sizes_ok = image.ProcessEntryContents()
  562. if sizes_ok:
  563. break
  564. image.ResetForPack()
  565. tout.info('Pack completed after %d pass(es)' % (pack_pass + 1))
  566. if not sizes_ok:
  567. image.Raise('Entries changed size after packing (tried %s passes)' %
  568. passes)
  569. image.BuildImage()
  570. if write_map:
  571. image.WriteMap()
  572. missing_list = []
  573. image.CheckMissing(missing_list)
  574. if missing_list:
  575. tout.error("Image '%s' is missing external blobs and is non-functional: %s\n" %
  576. (image.name, ' '.join([e.name for e in missing_list])))
  577. _ShowHelpForMissingBlobs(tout.ERROR, missing_list)
  578. faked_list = []
  579. image.CheckFakedBlobs(faked_list)
  580. if faked_list:
  581. tout.warning(
  582. "Image '%s' has faked external blobs and is non-functional: %s\n" %
  583. (image.name, ' '.join([os.path.basename(e.GetDefaultFilename())
  584. for e in faked_list])))
  585. optional_list = []
  586. image.CheckOptional(optional_list)
  587. if optional_list:
  588. tout.warning(
  589. "Image '%s' is missing optional external blobs but is still functional: %s\n" %
  590. (image.name, ' '.join([e.name for e in optional_list])))
  591. _ShowHelpForMissingBlobs(tout.WARNING, optional_list)
  592. missing_bintool_list = []
  593. image.check_missing_bintools(missing_bintool_list)
  594. if missing_bintool_list:
  595. tout.warning(
  596. "Image '%s' has missing bintools and is non-functional: %s\n" %
  597. (image.name, ' '.join([os.path.basename(bintool.name)
  598. for bintool in missing_bintool_list])))
  599. return any([missing_list, faked_list, missing_bintool_list])
  600. def Binman(args):
  601. """The main control code for binman
  602. This assumes that help and test options have already been dealt with. It
  603. deals with the core task of building images.
  604. Args:
  605. args: Command line arguments Namespace object
  606. """
  607. global Image
  608. global state
  609. if args.full_help:
  610. with importlib.resources.path('binman', 'README.rst') as readme:
  611. tools.print_full_help(str(readme))
  612. return 0
  613. # Put these here so that we can import this module without libfdt
  614. from binman.image import Image
  615. from binman import state
  616. tool_paths = []
  617. if args.toolpath:
  618. tool_paths += args.toolpath
  619. if args.tooldir:
  620. tool_paths.append(args.tooldir)
  621. tools.set_tool_paths(tool_paths or None)
  622. bintool.Bintool.set_tool_dir(args.tooldir)
  623. if args.cmd in ['ls', 'extract', 'replace', 'tool', 'sign']:
  624. try:
  625. tout.init(args.verbosity)
  626. if args.cmd == 'replace':
  627. tools.prepare_output_dir(args.outdir, args.preserve)
  628. else:
  629. tools.prepare_output_dir(None)
  630. if args.cmd == 'ls':
  631. ListEntries(args.image, args.paths)
  632. if args.cmd == 'extract':
  633. ExtractEntries(args.image, args.filename, args.outdir, args.paths,
  634. not args.uncompressed, args.format)
  635. if args.cmd == 'replace':
  636. ReplaceEntries(args.image, args.filename, args.indir, args.paths,
  637. do_compress=not args.compressed,
  638. allow_resize=not args.fix_size, write_map=args.map)
  639. if args.cmd == 'sign':
  640. SignEntries(args.image, args.file, args.key, args.algo, args.paths)
  641. if args.cmd == 'tool':
  642. if args.list:
  643. bintool.Bintool.list_all()
  644. elif args.fetch:
  645. if not args.bintools:
  646. raise ValueError(
  647. "Please specify bintools to fetch or 'all' or 'missing'")
  648. bintool.Bintool.fetch_tools(bintool.FETCH_ANY,
  649. args.bintools)
  650. else:
  651. raise ValueError("Invalid arguments to 'tool' subcommand")
  652. except:
  653. raise
  654. finally:
  655. tools.finalise_output_dir()
  656. return 0
  657. elf_params = None
  658. if args.update_fdt_in_elf:
  659. elf_params = args.update_fdt_in_elf.split(',')
  660. if len(elf_params) != 4:
  661. raise ValueError('Invalid args %s to --update-fdt-in-elf: expected infile,outfile,begin_sym,end_sym' %
  662. elf_params)
  663. # Try to figure out which device tree contains our image description
  664. if args.dt:
  665. dtb_fname = args.dt
  666. else:
  667. board = args.board
  668. if not board:
  669. raise ValueError('Must provide a board to process (use -b <board>)')
  670. board_pathname = os.path.join(args.build_dir, board)
  671. dtb_fname = os.path.join(board_pathname, 'u-boot.dtb')
  672. if not args.indir:
  673. args.indir = ['.']
  674. args.indir.append(board_pathname)
  675. try:
  676. tout.init(args.verbosity)
  677. elf.debug = args.debug
  678. cbfs_util.VERBOSE = args.verbosity > 2
  679. state.use_fake_dtb = args.fake_dtb
  680. # Normally we replace the 'u-boot' etype with 'u-boot-expanded', etc.
  681. # When running tests this can be disabled using this flag. When not
  682. # updating the FDT in image, it is not needed by binman, but we use it
  683. # for consistency, so that the images look the same to U-Boot at
  684. # runtime.
  685. use_expanded = not args.no_expanded
  686. try:
  687. tools.set_input_dirs(args.indir)
  688. tools.prepare_output_dir(args.outdir, args.preserve)
  689. state.SetEntryArgs(args.entry_arg)
  690. state.SetThreads(args.threads)
  691. images = PrepareImagesAndDtbs(dtb_fname, args.image,
  692. args.update_fdt, use_expanded)
  693. if args.test_section_timeout:
  694. # Set the first image to timeout, used in testThreadTimeout()
  695. images[list(images.keys())[0]].test_section_timeout = True
  696. invalid = False
  697. bintool.Bintool.set_missing_list(
  698. args.force_missing_bintools.split(',') if
  699. args.force_missing_bintools else None)
  700. # Create the directory here instead of Entry.check_fake_fname()
  701. # since that is called from a threaded context so different threads
  702. # may race to create the directory
  703. if args.fake_ext_blobs:
  704. entry.Entry.create_fake_dir()
  705. for image in images.values():
  706. invalid |= ProcessImage(image, args.update_fdt, args.map,
  707. allow_missing=args.allow_missing,
  708. allow_fake_blobs=args.fake_ext_blobs)
  709. # Write the updated FDTs to our output files
  710. for dtb_item in state.GetAllFdts():
  711. tools.write_file(dtb_item._fname, dtb_item.GetContents())
  712. if elf_params:
  713. data = state.GetFdtForEtype('u-boot-dtb').GetContents()
  714. elf.UpdateFile(*elf_params, data)
  715. # This can only be True if -M is provided, since otherwise binman
  716. # would have raised an error already
  717. if invalid:
  718. msg = 'Some images are invalid'
  719. if args.ignore_missing:
  720. tout.warning(msg)
  721. else:
  722. tout.error(msg)
  723. return 103
  724. # Use this to debug the time take to pack the image
  725. #state.TimingShow()
  726. finally:
  727. tools.finalise_output_dir()
  728. finally:
  729. tout.uninit()
  730. return 0