control.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. import os
  10. import sys
  11. from patman import tools
  12. from binman import cbfs_util
  13. from binman import elf
  14. from patman import command
  15. from patman import tout
  16. # List of images we plan to create
  17. # Make this global so that it can be referenced from tests
  18. images = OrderedDict()
  19. def _ReadImageDesc(binman_node):
  20. """Read the image descriptions from the /binman node
  21. This normally produces a single Image object called 'image'. But if
  22. multiple images are present, they will all be returned.
  23. Args:
  24. binman_node: Node object of the /binman node
  25. Returns:
  26. OrderedDict of Image objects, each of which describes an image
  27. """
  28. images = OrderedDict()
  29. if 'multiple-images' in binman_node.props:
  30. for node in binman_node.subnodes:
  31. images[node.name] = Image(node.name, node)
  32. else:
  33. images['image'] = Image('image', binman_node)
  34. return images
  35. def _FindBinmanNode(dtb):
  36. """Find the 'binman' node in the device tree
  37. Args:
  38. dtb: Fdt object to scan
  39. Returns:
  40. Node object of /binman node, or None if not found
  41. """
  42. for node in dtb.GetRoot().subnodes:
  43. if node.name == 'binman':
  44. return node
  45. return None
  46. def GetEntryModules(include_testing=True):
  47. """Get a set of entry class implementations
  48. Returns:
  49. Set of paths to entry class filenames
  50. """
  51. our_path = os.path.dirname(os.path.realpath(__file__))
  52. glob_list = glob.glob(os.path.join(our_path, 'etype/*.py'))
  53. return set([os.path.splitext(os.path.basename(item))[0]
  54. for item in glob_list
  55. if include_testing or '_testing' not in item])
  56. def WriteEntryDocs(modules, test_missing=None):
  57. """Write out documentation for all entries
  58. Args:
  59. modules: List of Module objects to get docs for
  60. test_missing: Used for testing only, to force an entry's documeentation
  61. to show as missing even if it is present. Should be set to None in
  62. normal use.
  63. """
  64. from binman.entry import Entry
  65. Entry.WriteDocs(modules, test_missing)
  66. def ListEntries(image_fname, entry_paths):
  67. """List the entries in an image
  68. This decodes the supplied image and displays a table of entries from that
  69. image, preceded by a header.
  70. Args:
  71. image_fname: Image filename to process
  72. entry_paths: List of wildcarded paths (e.g. ['*dtb*', 'u-boot*',
  73. 'section/u-boot'])
  74. """
  75. image = Image.FromFile(image_fname)
  76. entries, lines, widths = image.GetListEntries(entry_paths)
  77. num_columns = len(widths)
  78. for linenum, line in enumerate(lines):
  79. if linenum == 1:
  80. # Print header line
  81. print('-' * (sum(widths) + num_columns * 2))
  82. out = ''
  83. for i, item in enumerate(line):
  84. width = -widths[i]
  85. if item.startswith('>'):
  86. width = -width
  87. item = item[1:]
  88. txt = '%*s ' % (width, item)
  89. out += txt
  90. print(out.rstrip())
  91. def ReadEntry(image_fname, entry_path, decomp=True):
  92. """Extract an entry from an image
  93. This extracts the data from a particular entry in an image
  94. Args:
  95. image_fname: Image filename to process
  96. entry_path: Path to entry to extract
  97. decomp: True to return uncompressed data, if the data is compress
  98. False to return the raw data
  99. Returns:
  100. data extracted from the entry
  101. """
  102. global Image
  103. from binman.image import Image
  104. image = Image.FromFile(image_fname)
  105. entry = image.FindEntryPath(entry_path)
  106. return entry.ReadData(decomp)
  107. def ExtractEntries(image_fname, output_fname, outdir, entry_paths,
  108. decomp=True):
  109. """Extract the data from one or more entries and write it to files
  110. Args:
  111. image_fname: Image filename to process
  112. output_fname: Single output filename to use if extracting one file, None
  113. otherwise
  114. outdir: Output directory to use (for any number of files), else None
  115. entry_paths: List of entry paths to extract
  116. decomp: True to decompress the entry data
  117. Returns:
  118. List of EntryInfo records that were written
  119. """
  120. image = Image.FromFile(image_fname)
  121. # Output an entry to a single file, as a special case
  122. if output_fname:
  123. if not entry_paths:
  124. raise ValueError('Must specify an entry path to write with -f')
  125. if len(entry_paths) != 1:
  126. raise ValueError('Must specify exactly one entry path to write with -f')
  127. entry = image.FindEntryPath(entry_paths[0])
  128. data = entry.ReadData(decomp)
  129. tools.WriteFile(output_fname, data)
  130. tout.Notice("Wrote %#x bytes to file '%s'" % (len(data), output_fname))
  131. return
  132. # Otherwise we will output to a path given by the entry path of each entry.
  133. # This means that entries will appear in subdirectories if they are part of
  134. # a sub-section.
  135. einfos = image.GetListEntries(entry_paths)[0]
  136. tout.Notice('%d entries match and will be written' % len(einfos))
  137. for einfo in einfos:
  138. entry = einfo.entry
  139. data = entry.ReadData(decomp)
  140. path = entry.GetPath()[1:]
  141. fname = os.path.join(outdir, path)
  142. # If this entry has children, create a directory for it and put its
  143. # data in a file called 'root' in that directory
  144. if entry.GetEntries():
  145. if not os.path.exists(fname):
  146. os.makedirs(fname)
  147. fname = os.path.join(fname, 'root')
  148. tout.Notice("Write entry '%s' to '%s'" % (entry.GetPath(), fname))
  149. tools.WriteFile(fname, data)
  150. return einfos
  151. def BeforeReplace(image, allow_resize):
  152. """Handle getting an image ready for replacing entries in it
  153. Args:
  154. image: Image to prepare
  155. """
  156. state.PrepareFromLoadedData(image)
  157. image.LoadData()
  158. # If repacking, drop the old offset/size values except for the original
  159. # ones, so we are only left with the constraints.
  160. if allow_resize:
  161. image.ResetForPack()
  162. def ReplaceOneEntry(image, entry, data, do_compress, allow_resize):
  163. """Handle replacing a single entry an an image
  164. Args:
  165. image: Image to update
  166. entry: Entry to write
  167. data: Data to replace with
  168. do_compress: True to compress the data if needed, False if data is
  169. already compressed so should be used as is
  170. allow_resize: True to allow entries to change size (this does a re-pack
  171. of the entries), False to raise an exception
  172. """
  173. if not entry.WriteData(data, do_compress):
  174. if not image.allow_repack:
  175. entry.Raise('Entry data size does not match, but allow-repack is not present for this image')
  176. if not allow_resize:
  177. entry.Raise('Entry data size does not match, but resize is disabled')
  178. def AfterReplace(image, allow_resize, write_map):
  179. """Handle write out an image after replacing entries in it
  180. Args:
  181. image: Image to write
  182. allow_resize: True to allow entries to change size (this does a re-pack
  183. of the entries), False to raise an exception
  184. write_map: True to write a map file
  185. """
  186. tout.Info('Processing image')
  187. ProcessImage(image, update_fdt=True, write_map=write_map,
  188. get_contents=False, allow_resize=allow_resize)
  189. def WriteEntryToImage(image, entry, data, do_compress=True, allow_resize=True,
  190. write_map=False):
  191. BeforeReplace(image, allow_resize)
  192. tout.Info('Writing data to %s' % entry.GetPath())
  193. ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
  194. AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
  195. def WriteEntry(image_fname, entry_path, data, do_compress=True,
  196. allow_resize=True, write_map=False):
  197. """Replace an entry in an image
  198. This replaces the data in a particular entry in an image. This size of the
  199. new data must match the size of the old data unless allow_resize is True.
  200. Args:
  201. image_fname: Image filename to process
  202. entry_path: Path to entry to extract
  203. data: Data to replace with
  204. do_compress: True to compress the data if needed, False if data is
  205. already compressed so should be used as is
  206. allow_resize: True to allow entries to change size (this does a re-pack
  207. of the entries), False to raise an exception
  208. write_map: True to write a map file
  209. Returns:
  210. Image object that was updated
  211. """
  212. tout.Info("Write entry '%s', file '%s'" % (entry_path, image_fname))
  213. image = Image.FromFile(image_fname)
  214. entry = image.FindEntryPath(entry_path)
  215. WriteEntryToImage(image, entry, data, do_compress=do_compress,
  216. allow_resize=allow_resize, write_map=write_map)
  217. return image
  218. def ReplaceEntries(image_fname, input_fname, indir, entry_paths,
  219. do_compress=True, allow_resize=True, write_map=False):
  220. """Replace the data from one or more entries from input files
  221. Args:
  222. image_fname: Image filename to process
  223. input_fname: Single input ilename to use if replacing one file, None
  224. otherwise
  225. indir: Input directory to use (for any number of files), else None
  226. entry_paths: List of entry paths to extract
  227. do_compress: True if the input data is uncompressed and may need to be
  228. compressed if the entry requires it, False if the data is already
  229. compressed.
  230. write_map: True to write a map file
  231. Returns:
  232. List of EntryInfo records that were written
  233. """
  234. image = Image.FromFile(image_fname)
  235. # Replace an entry from a single file, as a special case
  236. if input_fname:
  237. if not entry_paths:
  238. raise ValueError('Must specify an entry path to read with -f')
  239. if len(entry_paths) != 1:
  240. raise ValueError('Must specify exactly one entry path to write with -f')
  241. entry = image.FindEntryPath(entry_paths[0])
  242. data = tools.ReadFile(input_fname)
  243. tout.Notice("Read %#x bytes from file '%s'" % (len(data), input_fname))
  244. WriteEntryToImage(image, entry, data, do_compress=do_compress,
  245. allow_resize=allow_resize, write_map=write_map)
  246. return
  247. # Otherwise we will input from a path given by the entry path of each entry.
  248. # This means that files must appear in subdirectories if they are part of
  249. # a sub-section.
  250. einfos = image.GetListEntries(entry_paths)[0]
  251. tout.Notice("Replacing %d matching entries in image '%s'" %
  252. (len(einfos), image_fname))
  253. BeforeReplace(image, allow_resize)
  254. for einfo in einfos:
  255. entry = einfo.entry
  256. if entry.GetEntries():
  257. tout.Info("Skipping section entry '%s'" % entry.GetPath())
  258. continue
  259. path = entry.GetPath()[1:]
  260. fname = os.path.join(indir, path)
  261. if os.path.exists(fname):
  262. tout.Notice("Write entry '%s' from file '%s'" %
  263. (entry.GetPath(), fname))
  264. data = tools.ReadFile(fname)
  265. ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
  266. else:
  267. tout.Warning("Skipping entry '%s' from missing file '%s'" %
  268. (entry.GetPath(), fname))
  269. AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
  270. return image
  271. def PrepareImagesAndDtbs(dtb_fname, select_images, update_fdt):
  272. """Prepare the images to be processed and select the device tree
  273. This function:
  274. - reads in the device tree
  275. - finds and scans the binman node to create all entries
  276. - selects which images to build
  277. - Updates the device tress with placeholder properties for offset,
  278. image-pos, etc.
  279. Args:
  280. dtb_fname: Filename of the device tree file to use (.dts or .dtb)
  281. selected_images: List of images to output, or None for all
  282. update_fdt: True to update the FDT wth entry offsets, etc.
  283. """
  284. # Import these here in case libfdt.py is not available, in which case
  285. # the above help option still works.
  286. from dtoc import fdt
  287. from dtoc import fdt_util
  288. global images
  289. # Get the device tree ready by compiling it and copying the compiled
  290. # output into a file in our output directly. Then scan it for use
  291. # in binman.
  292. dtb_fname = fdt_util.EnsureCompiled(dtb_fname)
  293. fname = tools.GetOutputFilename('u-boot.dtb.out')
  294. tools.WriteFile(fname, tools.ReadFile(dtb_fname))
  295. dtb = fdt.FdtScan(fname)
  296. node = _FindBinmanNode(dtb)
  297. if not node:
  298. raise ValueError("Device tree '%s' does not have a 'binman' "
  299. "node" % dtb_fname)
  300. images = _ReadImageDesc(node)
  301. if select_images:
  302. skip = []
  303. new_images = OrderedDict()
  304. for name, image in images.items():
  305. if name in select_images:
  306. new_images[name] = image
  307. else:
  308. skip.append(name)
  309. images = new_images
  310. tout.Notice('Skipping images: %s' % ', '.join(skip))
  311. state.Prepare(images, dtb)
  312. # Prepare the device tree by making sure that any missing
  313. # properties are added (e.g. 'pos' and 'size'). The values of these
  314. # may not be correct yet, but we add placeholders so that the
  315. # size of the device tree is correct. Later, in
  316. # SetCalculatedProperties() we will insert the correct values
  317. # without changing the device-tree size, thus ensuring that our
  318. # entry offsets remain the same.
  319. for image in images.values():
  320. image.ExpandEntries()
  321. if update_fdt:
  322. image.AddMissingProperties()
  323. image.ProcessFdt(dtb)
  324. for dtb_item in state.GetAllFdts():
  325. dtb_item.Sync(auto_resize=True)
  326. dtb_item.Pack()
  327. dtb_item.Flush()
  328. return images
  329. def ProcessImage(image, update_fdt, write_map, get_contents=True,
  330. allow_resize=True, allow_missing=False):
  331. """Perform all steps for this image, including checking and # writing it.
  332. This means that errors found with a later image will be reported after
  333. earlier images are already completed and written, but that does not seem
  334. important.
  335. Args:
  336. image: Image to process
  337. update_fdt: True to update the FDT wth entry offsets, etc.
  338. write_map: True to write a map file
  339. get_contents: True to get the image contents from files, etc., False if
  340. the contents is already present
  341. allow_resize: True to allow entries to change size (this does a re-pack
  342. of the entries), False to raise an exception
  343. allow_missing: Allow blob_ext objects to be missing
  344. Returns:
  345. True if one or more external blobs are missing, False if all are present
  346. """
  347. if get_contents:
  348. image.SetAllowMissing(allow_missing)
  349. image.GetEntryContents()
  350. image.GetEntryOffsets()
  351. # We need to pack the entries to figure out where everything
  352. # should be placed. This sets the offset/size of each entry.
  353. # However, after packing we call ProcessEntryContents() which
  354. # may result in an entry changing size. In that case we need to
  355. # do another pass. Since the device tree often contains the
  356. # final offset/size information we try to make space for this in
  357. # AddMissingProperties() above. However, if the device is
  358. # compressed we cannot know this compressed size in advance,
  359. # since changing an offset from 0x100 to 0x104 (for example) can
  360. # alter the compressed size of the device tree. So we need a
  361. # third pass for this.
  362. passes = 5
  363. for pack_pass in range(passes):
  364. try:
  365. image.PackEntries()
  366. image.CheckSize()
  367. image.CheckEntries()
  368. except Exception as e:
  369. if write_map:
  370. fname = image.WriteMap()
  371. print("Wrote map file '%s' to show errors" % fname)
  372. raise
  373. image.SetImagePos()
  374. if update_fdt:
  375. image.SetCalculatedProperties()
  376. for dtb_item in state.GetAllFdts():
  377. dtb_item.Sync()
  378. dtb_item.Flush()
  379. image.WriteSymbols()
  380. sizes_ok = image.ProcessEntryContents()
  381. if sizes_ok:
  382. break
  383. image.ResetForPack()
  384. tout.Info('Pack completed after %d pass(es)' % (pack_pass + 1))
  385. if not sizes_ok:
  386. image.Raise('Entries changed size after packing (tried %s passes)' %
  387. passes)
  388. image.BuildImage()
  389. if write_map:
  390. image.WriteMap()
  391. missing_list = []
  392. image.CheckMissing(missing_list)
  393. if missing_list:
  394. tout.Warning("Image '%s' is missing external blobs and is non-functional: %s" %
  395. (image.name, ' '.join([e.name for e in missing_list])))
  396. return bool(missing_list)
  397. def Binman(args):
  398. """The main control code for binman
  399. This assumes that help and test options have already been dealt with. It
  400. deals with the core task of building images.
  401. Args:
  402. args: Command line arguments Namespace object
  403. """
  404. global Image
  405. global state
  406. if args.full_help:
  407. pager = os.getenv('PAGER')
  408. if not pager:
  409. pager = 'more'
  410. fname = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])),
  411. 'README')
  412. command.Run(pager, fname)
  413. return 0
  414. # Put these here so that we can import this module without libfdt
  415. from binman.image import Image
  416. from binman import state
  417. if args.cmd in ['ls', 'extract', 'replace']:
  418. try:
  419. tout.Init(args.verbosity)
  420. tools.PrepareOutputDir(None)
  421. if args.cmd == 'ls':
  422. ListEntries(args.image, args.paths)
  423. if args.cmd == 'extract':
  424. ExtractEntries(args.image, args.filename, args.outdir, args.paths,
  425. not args.uncompressed)
  426. if args.cmd == 'replace':
  427. ReplaceEntries(args.image, args.filename, args.indir, args.paths,
  428. do_compress=not args.compressed,
  429. allow_resize=not args.fix_size, write_map=args.map)
  430. except:
  431. raise
  432. finally:
  433. tools.FinaliseOutputDir()
  434. return 0
  435. # Try to figure out which device tree contains our image description
  436. if args.dt:
  437. dtb_fname = args.dt
  438. else:
  439. board = args.board
  440. if not board:
  441. raise ValueError('Must provide a board to process (use -b <board>)')
  442. board_pathname = os.path.join(args.build_dir, board)
  443. dtb_fname = os.path.join(board_pathname, 'u-boot.dtb')
  444. if not args.indir:
  445. args.indir = ['.']
  446. args.indir.append(board_pathname)
  447. try:
  448. tout.Init(args.verbosity)
  449. elf.debug = args.debug
  450. cbfs_util.VERBOSE = args.verbosity > 2
  451. state.use_fake_dtb = args.fake_dtb
  452. try:
  453. tools.SetInputDirs(args.indir)
  454. tools.PrepareOutputDir(args.outdir, args.preserve)
  455. tools.SetToolPaths(args.toolpath)
  456. state.SetEntryArgs(args.entry_arg)
  457. images = PrepareImagesAndDtbs(dtb_fname, args.image,
  458. args.update_fdt)
  459. missing = False
  460. for image in images.values():
  461. missing |= ProcessImage(image, args.update_fdt, args.map,
  462. allow_missing=args.allow_missing)
  463. # Write the updated FDTs to our output files
  464. for dtb_item in state.GetAllFdts():
  465. tools.WriteFile(dtb_item._fname, dtb_item.GetContents())
  466. if missing:
  467. tout.Warning("Some images are invalid")
  468. finally:
  469. tools.FinaliseOutputDir()
  470. finally:
  471. tout.Uninit()
  472. return 0