fip_util.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0+
  3. # Copyright 2021 Google LLC
  4. # Written by Simon Glass <sjg@chromium.org>
  5. """Support for ARM's Firmware Image Package (FIP) format
  6. FIP is a format similar to FMAP[1] but with fewer features and an obscure UUID
  7. instead of the region name.
  8. It consists of a header and a table of entries, each pointing to a place in the
  9. firmware image where something can be found.
  10. [1] https://chromium.googlesource.com/chromiumos/third_party/flashmap/+/refs/heads/master/lib/fmap.h
  11. If ATF updates, run this program to update the FIT_TYPE_LIST.
  12. ARM Trusted Firmware is available at:
  13. https://github.com/ARM-software/arm-trusted-firmware.git
  14. """
  15. from argparse import ArgumentParser
  16. import collections
  17. import io
  18. import os
  19. import re
  20. import struct
  21. import sys
  22. from uuid import UUID
  23. OUR_FILE = os.path.realpath(__file__)
  24. OUR_PATH = os.path.dirname(OUR_FILE)
  25. # Bring in the patman and dtoc libraries (but don't override the first path
  26. # in PYTHONPATH)
  27. sys.path.insert(2, os.path.join(OUR_PATH, '..'))
  28. # pylint: disable=C0413
  29. from u_boot_pylib import command
  30. from u_boot_pylib import tools
  31. # The TOC header, at the start of the FIP
  32. HEADER_FORMAT = '<IIQ'
  33. HEADER_LEN = 0x10
  34. HEADER_MAGIC = 0xaA640001
  35. HEADER_SERIAL = 0x12345678
  36. # The entry header (a table of these comes after the TOC header)
  37. UUID_LEN = 16
  38. ENTRY_FORMAT = f'<{UUID_LEN}sQQQ'
  39. ENTRY_SIZE = 0x28
  40. HEADER_NAMES = (
  41. 'name',
  42. 'serial',
  43. 'flags',
  44. )
  45. ENTRY_NAMES = (
  46. 'uuid',
  47. 'offset',
  48. 'size',
  49. 'flags',
  50. )
  51. # Set to True to enable output from running fiptool for debugging
  52. VERBOSE = False
  53. # Use a class so we can convert the bytes, making the table more readable
  54. # pylint: disable=R0903
  55. class FipType:
  56. """A FIP entry type that we understand"""
  57. def __init__(self, name, desc, uuid_bytes):
  58. """Create up a new type
  59. Args:
  60. name (str): Short name for the type
  61. desc (str): Longer description for the type
  62. uuid_bytes (bytes): List of 16 bytes for the UUID
  63. """
  64. self.name = name
  65. self.desc = desc
  66. self.uuid = bytes(uuid_bytes)
  67. # This is taken from tbbr_config.c in ARM Trusted Firmware
  68. FIP_TYPE_LIST = [
  69. # ToC Entry UUIDs
  70. FipType('scp-fwu-cfg', 'SCP Firmware Updater Configuration FWU SCP_BL2U',
  71. [0x65, 0x92, 0x27, 0x03, 0x2f, 0x74, 0xe6, 0x44,
  72. 0x8d, 0xff, 0x57, 0x9a, 0xc1, 0xff, 0x06, 0x10]),
  73. FipType('ap-fwu-cfg', 'AP Firmware Updater Configuration BL2U',
  74. [0x60, 0xb3, 0xeb, 0x37, 0xc1, 0xe5, 0xea, 0x41,
  75. 0x9d, 0xf3, 0x19, 0xed, 0xa1, 0x1f, 0x68, 0x01]),
  76. FipType('fwu', 'Firmware Updater NS_BL2U',
  77. [0x4f, 0x51, 0x1d, 0x11, 0x2b, 0xe5, 0x4e, 0x49,
  78. 0xb4, 0xc5, 0x83, 0xc2, 0xf7, 0x15, 0x84, 0x0a]),
  79. FipType('fwu-cert', 'Non-Trusted Firmware Updater certificate',
  80. [0x71, 0x40, 0x8a, 0xb2, 0x18, 0xd6, 0x87, 0x4c,
  81. 0x8b, 0x2e, 0xc6, 0xdc, 0xcd, 0x50, 0xf0, 0x96]),
  82. FipType('tb-fw', 'Trusted Boot Firmware BL2',
  83. [0x5f, 0xf9, 0xec, 0x0b, 0x4d, 0x22, 0x3e, 0x4d,
  84. 0xa5, 0x44, 0xc3, 0x9d, 0x81, 0xc7, 0x3f, 0x0a]),
  85. FipType('scp-fw', 'SCP Firmware SCP_BL2',
  86. [0x97, 0x66, 0xfd, 0x3d, 0x89, 0xbe, 0xe8, 0x49,
  87. 0xae, 0x5d, 0x78, 0xa1, 0x40, 0x60, 0x82, 0x13]),
  88. FipType('soc-fw', 'EL3 Runtime Firmware BL31',
  89. [0x47, 0xd4, 0x08, 0x6d, 0x4c, 0xfe, 0x98, 0x46,
  90. 0x9b, 0x95, 0x29, 0x50, 0xcb, 0xbd, 0x5a, 0x00]),
  91. FipType('tos-fw', 'Secure Payload BL32 (Trusted OS)',
  92. [0x05, 0xd0, 0xe1, 0x89, 0x53, 0xdc, 0x13, 0x47,
  93. 0x8d, 0x2b, 0x50, 0x0a, 0x4b, 0x7a, 0x3e, 0x38]),
  94. FipType('tos-fw-extra1', 'Secure Payload BL32 Extra1 (Trusted OS Extra1)',
  95. [0x0b, 0x70, 0xc2, 0x9b, 0x2a, 0x5a, 0x78, 0x40,
  96. 0x9f, 0x65, 0x0a, 0x56, 0x82, 0x73, 0x82, 0x88]),
  97. FipType('tos-fw-extra2', 'Secure Payload BL32 Extra2 (Trusted OS Extra2)',
  98. [0x8e, 0xa8, 0x7b, 0xb1, 0xcf, 0xa2, 0x3f, 0x4d,
  99. 0x85, 0xfd, 0xe7, 0xbb, 0xa5, 0x02, 0x20, 0xd9]),
  100. FipType('nt-fw', 'Non-Trusted Firmware BL33',
  101. [0xd6, 0xd0, 0xee, 0xa7, 0xfc, 0xea, 0xd5, 0x4b,
  102. 0x97, 0x82, 0x99, 0x34, 0xf2, 0x34, 0xb6, 0xe4]),
  103. FipType('rmm-fw', 'Realm Monitor Management Firmware',
  104. [0x6c, 0x07, 0x62, 0xa6, 0x12, 0xf2, 0x4b, 0x56,
  105. 0x92, 0xcb, 0xba, 0x8f, 0x63, 0x36, 0x06, 0xd9]),
  106. # Key certificates
  107. FipType('rot-cert', 'Root Of Trust key certificate',
  108. [0x86, 0x2d, 0x1d, 0x72, 0xf8, 0x60, 0xe4, 0x11,
  109. 0x92, 0x0b, 0x8b, 0xe7, 0x62, 0x16, 0x0f, 0x24]),
  110. FipType('trusted-key-cert', 'Trusted key certificate',
  111. [0x82, 0x7e, 0xe8, 0x90, 0xf8, 0x60, 0xe4, 0x11,
  112. 0xa1, 0xb4, 0x77, 0x7a, 0x21, 0xb4, 0xf9, 0x4c]),
  113. FipType('scp-fw-key-cert', 'SCP Firmware key certificate',
  114. [0x02, 0x42, 0x21, 0xa1, 0xf8, 0x60, 0xe4, 0x11,
  115. 0x8d, 0x9b, 0xf3, 0x3c, 0x0e, 0x15, 0xa0, 0x14]),
  116. FipType('soc-fw-key-cert', 'SoC Firmware key certificate',
  117. [0x8a, 0xb8, 0xbe, 0xcc, 0xf9, 0x60, 0xe4, 0x11,
  118. 0x9a, 0xd0, 0xeb, 0x48, 0x22, 0xd8, 0xdc, 0xf8]),
  119. FipType('tos-fw-key-cert', 'Trusted OS Firmware key certificate',
  120. [0x94, 0x77, 0xd6, 0x03, 0xfb, 0x60, 0xe4, 0x11,
  121. 0x85, 0xdd, 0xb7, 0x10, 0x5b, 0x8c, 0xee, 0x04]),
  122. FipType('nt-fw-key-cert', 'Non-Trusted Firmware key certificate',
  123. [0x8a, 0xd5, 0x83, 0x2a, 0xfb, 0x60, 0xe4, 0x11,
  124. 0x8a, 0xaf, 0xdf, 0x30, 0xbb, 0xc4, 0x98, 0x59]),
  125. # Content certificates
  126. FipType('tb-fw-cert', 'Trusted Boot Firmware BL2 certificate',
  127. [0xd6, 0xe2, 0x69, 0xea, 0x5d, 0x63, 0xe4, 0x11,
  128. 0x8d, 0x8c, 0x9f, 0xba, 0xbe, 0x99, 0x56, 0xa5]),
  129. FipType('scp-fw-cert', 'SCP Firmware content certificate',
  130. [0x44, 0xbe, 0x6f, 0x04, 0x5e, 0x63, 0xe4, 0x11,
  131. 0xb2, 0x8b, 0x73, 0xd8, 0xea, 0xae, 0x96, 0x56]),
  132. FipType('soc-fw-cert', 'SoC Firmware content certificate',
  133. [0xe2, 0xb2, 0x0c, 0x20, 0x5e, 0x63, 0xe4, 0x11,
  134. 0x9c, 0xe8, 0xab, 0xcc, 0xf9, 0x2b, 0xb6, 0x66]),
  135. FipType('tos-fw-cert', 'Trusted OS Firmware content certificate',
  136. [0xa4, 0x9f, 0x44, 0x11, 0x5e, 0x63, 0xe4, 0x11,
  137. 0x87, 0x28, 0x3f, 0x05, 0x72, 0x2a, 0xf3, 0x3d]),
  138. FipType('nt-fw-cert', 'Non-Trusted Firmware content certificate',
  139. [0x8e, 0xc4, 0xc1, 0xf3, 0x5d, 0x63, 0xe4, 0x11,
  140. 0xa7, 0xa9, 0x87, 0xee, 0x40, 0xb2, 0x3f, 0xa7]),
  141. FipType('sip-sp-cert', 'SiP owned Secure Partition content certificate',
  142. [0x77, 0x6d, 0xfd, 0x44, 0x86, 0x97, 0x4c, 0x3b,
  143. 0x91, 0xeb, 0xc1, 0x3e, 0x02, 0x5a, 0x2a, 0x6f]),
  144. FipType('plat-sp-cert', 'Platform owned Secure Partition content certificate',
  145. [0xdd, 0xcb, 0xbf, 0x4a, 0xca, 0xd6, 0x11, 0xea,
  146. 0x87, 0xd0, 0x02, 0x42, 0xac, 0x13, 0x00, 0x03]),
  147. # Dynamic configs
  148. FipType('hw-config', 'HW_CONFIG',
  149. [0x08, 0xb8, 0xf1, 0xd9, 0xc9, 0xcf, 0x93, 0x49,
  150. 0xa9, 0x62, 0x6f, 0xbc, 0x6b, 0x72, 0x65, 0xcc]),
  151. FipType('tb-fw-config', 'TB_FW_CONFIG',
  152. [0x6c, 0x04, 0x58, 0xff, 0xaf, 0x6b, 0x7d, 0x4f,
  153. 0x82, 0xed, 0xaa, 0x27, 0xbc, 0x69, 0xbf, 0xd2]),
  154. FipType('soc-fw-config', 'SOC_FW_CONFIG',
  155. [0x99, 0x79, 0x81, 0x4b, 0x03, 0x76, 0xfb, 0x46,
  156. 0x8c, 0x8e, 0x8d, 0x26, 0x7f, 0x78, 0x59, 0xe0]),
  157. FipType('tos-fw-config', 'TOS_FW_CONFIG',
  158. [0x26, 0x25, 0x7c, 0x1a, 0xdb, 0xc6, 0x7f, 0x47,
  159. 0x8d, 0x96, 0xc4, 0xc4, 0xb0, 0x24, 0x80, 0x21]),
  160. FipType('nt-fw-config', 'NT_FW_CONFIG',
  161. [0x28, 0xda, 0x98, 0x15, 0x93, 0xe8, 0x7e, 0x44,
  162. 0xac, 0x66, 0x1a, 0xaf, 0x80, 0x15, 0x50, 0xf9]),
  163. FipType('fw-config', 'FW_CONFIG',
  164. [0x58, 0x07, 0xe1, 0x6a, 0x84, 0x59, 0x47, 0xbe,
  165. 0x8e, 0xd5, 0x64, 0x8e, 0x8d, 0xdd, 0xab, 0x0e]),
  166. ] # end
  167. FIP_TYPES = {ftype.name: ftype for ftype in FIP_TYPE_LIST}
  168. def get_type_uuid(fip_type_or_uuid):
  169. """get_type_uuid() - Convert a type or uuid into both
  170. This always returns a UUID, but may not return a type since it does not do
  171. the reverse lookup.
  172. Args:
  173. fip_type_or_uuid (str or bytes): Either a string containing the name of
  174. an entry (e.g. 'soc-fw') or a bytes(16) containing the UUID
  175. Returns:
  176. tuple:
  177. str: fip type (None if not known)
  178. bytes(16): uuid
  179. Raises:
  180. ValueError: An unknown type was requested
  181. """
  182. if isinstance(fip_type_or_uuid, str):
  183. fip_type = fip_type_or_uuid
  184. lookup = FIP_TYPES.get(fip_type)
  185. if not lookup:
  186. raise ValueError(f"Unknown FIP entry type '{fip_type}'")
  187. uuid = lookup.uuid
  188. else:
  189. fip_type = None
  190. uuid = fip_type_or_uuid
  191. return fip_type, uuid
  192. # pylint: disable=R0903
  193. class FipHeader:
  194. """Class to represent a FIP header"""
  195. def __init__(self, name, serial, flags):
  196. """Set up a new header object
  197. Args:
  198. name (str): Name, i.e. HEADER_MAGIC
  199. serial (str): Serial value, i.e. HEADER_SERIAL
  200. flags (int64): Flags value
  201. """
  202. self.name = name
  203. self.serial = serial
  204. self.flags = flags
  205. # pylint: disable=R0903
  206. class FipEntry:
  207. """Class to represent a single FIP entry
  208. This is used to hold the information about an entry, including its contents.
  209. Use the get_data() method to obtain the raw output for writing to the FIP
  210. file.
  211. """
  212. def __init__(self, uuid, offset, size, flags):
  213. self.uuid = uuid
  214. self.offset = offset
  215. self.size = size
  216. self.flags = flags
  217. self.fip_type = None
  218. self.data = None
  219. self.valid = uuid != tools.get_bytes(0, UUID_LEN)
  220. if self.valid:
  221. # Look up the friendly name
  222. matches = {val for (key, val) in FIP_TYPES.items()
  223. if val.uuid == uuid}
  224. if len(matches) == 1:
  225. self.fip_type = matches.pop().name
  226. @classmethod
  227. def from_type(cls, fip_type_or_uuid, data, flags):
  228. """Create a FipEntry from a type name
  229. Args:
  230. cls (class): This class
  231. fip_type_or_uuid (str or bytes): Name of the type to create, or
  232. bytes(16) uuid
  233. data (bytes): Contents of entry
  234. flags (int64): Flags value
  235. Returns:
  236. FipEntry: Created 241
  237. """
  238. fip_type, uuid = get_type_uuid(fip_type_or_uuid)
  239. fent = FipEntry(uuid, None, len(data), flags)
  240. fent.fip_type = fip_type
  241. fent.data = data
  242. return fent
  243. def decode_fip(data):
  244. """Decode a FIP into a header and list of FIP entries
  245. Args:
  246. data (bytes): Data block containing the FMAP
  247. Returns:
  248. Tuple:
  249. header: FipHeader object
  250. List of FipArea objects
  251. """
  252. fields = list(struct.unpack(HEADER_FORMAT, data[:HEADER_LEN]))
  253. header = FipHeader(*fields)
  254. fents = []
  255. pos = HEADER_LEN
  256. while True:
  257. fields = list(struct.unpack(ENTRY_FORMAT, data[pos:pos + ENTRY_SIZE]))
  258. fent = FipEntry(*fields)
  259. if not fent.valid:
  260. break
  261. fent.data = data[fent.offset:fent.offset + fent.size]
  262. fents.append(fent)
  263. pos += ENTRY_SIZE
  264. return header, fents
  265. class FipWriter:
  266. """Class to handle writing a ARM Trusted Firmware's Firmware Image Package
  267. Usage is something like:
  268. fip = FipWriter(size)
  269. fip.add_entry('scp-fwu-cfg', tools.read_file('something.bin'))
  270. ...
  271. data = cbw.get_data()
  272. Attributes:
  273. """
  274. def __init__(self, flags, align):
  275. self._fip_entries = []
  276. self._flags = flags
  277. self._align = align
  278. def add_entry(self, fip_type, data, flags):
  279. """Add a new entry to the FIP
  280. Args:
  281. fip_type (str): Type to add, e.g. 'tos-fw-config'
  282. data (bytes): Contents of entry
  283. flags (int64): Entry flags
  284. Returns:
  285. FipEntry: entry that was added
  286. """
  287. fent = FipEntry.from_type(fip_type, data, flags)
  288. self._fip_entries.append(fent)
  289. return fent
  290. def get_data(self):
  291. """Obtain the full contents of the FIP
  292. Thhis builds the FIP with headers and all required FIP entries.
  293. Returns:
  294. bytes: data resulting from building the FIP
  295. """
  296. buf = io.BytesIO()
  297. hdr = struct.pack(HEADER_FORMAT, HEADER_MAGIC, HEADER_SERIAL,
  298. self._flags)
  299. buf.write(hdr)
  300. # Calculate the position fo the first entry
  301. offset = len(hdr)
  302. offset += len(self._fip_entries) * ENTRY_SIZE
  303. offset += ENTRY_SIZE # terminating entry
  304. for fent in self._fip_entries:
  305. offset = tools.align(offset, self._align)
  306. fent.offset = offset
  307. offset += fent.size
  308. # Write out the TOC
  309. for fent in self._fip_entries:
  310. hdr = struct.pack(ENTRY_FORMAT, fent.uuid, fent.offset, fent.size,
  311. fent.flags)
  312. buf.write(hdr)
  313. # Write out the entries
  314. for fent in self._fip_entries:
  315. buf.seek(fent.offset)
  316. buf.write(fent.data)
  317. return buf.getvalue()
  318. class FipReader():
  319. """Class to handle reading a Firmware Image Package (FIP)
  320. Usage is something like:
  321. fip = fip_util.FipReader(data)
  322. fent = fip.get_entry('fwu')
  323. self.WriteFile('ufwu.bin', fent.data)
  324. blob = fip.get_entry(
  325. bytes([0xe3, 0xb7, 0x8d, 0x9e, 0x4a, 0x64, 0x11, 0xec,
  326. 0xb4, 0x5c, 0xfb, 0xa2, 0xb9, 0xb4, 0x97, 0x88]))
  327. self.WriteFile('blob.bin', blob.data)
  328. """
  329. def __init__(self, data, read=True):
  330. """Set up a new FitReader
  331. Args:
  332. data (bytes): data to read
  333. read (bool): True to read the data now
  334. """
  335. self.fents = collections.OrderedDict()
  336. self.data = data
  337. if read:
  338. self.read()
  339. def read(self):
  340. """Read all the files in the FIP and add them to self.files"""
  341. self.header, self.fents = decode_fip(self.data)
  342. def get_entry(self, fip_type_or_uuid):
  343. """get_entry() - Find an entry by type or UUID
  344. Args:
  345. fip_type_or_uuid (str or bytes): Name of the type to create, or
  346. bytes(16) uuid
  347. Returns:
  348. FipEntry: if found
  349. Raises:
  350. ValueError: entry type not found
  351. """
  352. fip_type, uuid = get_type_uuid(fip_type_or_uuid)
  353. for fent in self.fents:
  354. if fent.uuid == uuid:
  355. return fent
  356. label = fip_type
  357. if not label:
  358. label = UUID(bytes=uuid)
  359. raise ValueError(f"Cannot find FIP entry '{label}'")
  360. def parse_macros(srcdir):
  361. """parse_macros: Parse the firmware_image_package.h file
  362. Args:
  363. srcdir (str): 'arm-trusted-firmware' source directory
  364. Returns:
  365. dict:
  366. key: UUID macro name, e.g. 'UUID_TRUSTED_FWU_CERT'
  367. value: list:
  368. file comment, e.g. 'ToC Entry UUIDs'
  369. macro name, e.g. 'UUID_TRUSTED_FWU_CERT'
  370. uuid as bytes(16)
  371. Raises:
  372. ValueError: a line cannot be parsed
  373. """
  374. re_uuid = re.compile('0x[0-9a-fA-F]{2}')
  375. re_comment = re.compile(r'^/\* (.*) \*/$')
  376. fname = os.path.join(srcdir, 'include/tools_share/firmware_image_package.h')
  377. data = tools.read_file(fname, binary=False)
  378. macros = collections.OrderedDict()
  379. comment = None
  380. for linenum, line in enumerate(data.splitlines()):
  381. if line.startswith('/*'):
  382. mat = re_comment.match(line)
  383. if mat:
  384. comment = mat.group(1)
  385. else:
  386. # Example: #define UUID_TOS_FW_CONFIG \
  387. if 'UUID' in line:
  388. macro = line.split()[1]
  389. elif '{{' in line:
  390. mat = re_uuid.findall(line)
  391. if not mat or len(mat) != 16:
  392. raise ValueError(
  393. f'{fname}: Cannot parse UUID line {linenum + 1}: Got matches: {mat}')
  394. uuid = bytes([int(val, 16) for val in mat])
  395. macros[macro] = comment, macro, uuid
  396. if not macros:
  397. raise ValueError(f'{fname}: Cannot parse file')
  398. return macros
  399. def parse_names(srcdir):
  400. """parse_names: Parse the tbbr_config.c file
  401. Args:
  402. srcdir (str): 'arm-trusted-firmware' source directory
  403. Returns:
  404. tuple: dict of entries:
  405. key: UUID macro, e.g. 'UUID_NON_TRUSTED_FIRMWARE_BL33'
  406. tuple: entry information
  407. Description of entry, e.g. 'Non-Trusted Firmware BL33'
  408. UUID macro, e.g. 'UUID_NON_TRUSTED_FIRMWARE_BL33'
  409. Name of entry, e.g. 'nt-fw'
  410. Raises:
  411. ValueError: the file cannot be parsed
  412. """
  413. # Extract the .name, .uuid and .cmdline_name values
  414. re_data = re.compile(r'\.name = "([^"]*)",\s*\.uuid = (UUID_\w*),\s*\.cmdline_name = "([^"]+)"',
  415. re.S)
  416. fname = os.path.join(srcdir, 'tools/fiptool/tbbr_config.c')
  417. data = tools.read_file(fname, binary=False)
  418. # Example entry:
  419. # {
  420. # .name = "Secure Payload BL32 Extra2 (Trusted OS Extra2)",
  421. # .uuid = UUID_SECURE_PAYLOAD_BL32_EXTRA2,
  422. # .cmdline_name = "tos-fw-extra2"
  423. # },
  424. mat = re_data.findall(data)
  425. if not mat:
  426. raise ValueError(f'{fname}: Cannot parse file')
  427. names = {uuid: (desc, uuid, name) for desc, uuid, name in mat}
  428. return names
  429. def create_code_output(macros, names):
  430. """create_code_output() - Create the new version of this Python file
  431. Args:
  432. macros (dict):
  433. key (str): UUID macro name, e.g. 'UUID_TRUSTED_FWU_CERT'
  434. value: list:
  435. file comment, e.g. 'ToC Entry UUIDs'
  436. macro name, e.g. 'UUID_TRUSTED_FWU_CERT'
  437. uuid as bytes(16)
  438. names (dict): list of entries, each
  439. tuple: entry information
  440. Description of entry, e.g. 'Non-Trusted Firmware BL33'
  441. UUID macro, e.g. 'UUID_NON_TRUSTED_FIRMWARE_BL33'
  442. Name of entry, e.g. 'nt-fw'
  443. Returns:
  444. str: Table of FipType() entries
  445. """
  446. def _to_hex_list(data):
  447. """Convert bytes into C code
  448. Args:
  449. bytes to convert
  450. Returns:
  451. str: in the format '0x12, 0x34, 0x56...'
  452. """
  453. # Use 0x instead of %# since the latter ignores the 0 modifier in
  454. # Python 3.8.10
  455. return ', '.join(['0x%02x' % byte for byte in data])
  456. out = ''
  457. last_comment = None
  458. for comment, macro, uuid in macros.values():
  459. name_entry = names.get(macro)
  460. if not name_entry:
  461. print(f"Warning: UUID '{macro}' is not mentioned in tbbr_config.c file")
  462. continue
  463. desc, _, name = name_entry
  464. if last_comment != comment:
  465. out += f' # {comment}\n'
  466. last_comment = comment
  467. out += """ FipType('%s', '%s',
  468. [%s,
  469. %s]),
  470. """ % (name, desc, _to_hex_list(uuid[:8]), _to_hex_list(uuid[8:]))
  471. return out
  472. def parse_atf_source(srcdir, dstfile, oldfile):
  473. """parse_atf_source(): Parse the ATF source tree and update this file
  474. Args:
  475. srcdir (str): Path to 'arm-trusted-firmware' directory. Get this from:
  476. https://github.com/ARM-software/arm-trusted-firmware.git
  477. dstfile (str): File to write new code to, if an update is needed
  478. oldfile (str): Python source file to compare against
  479. Raises:
  480. ValueError: srcdir readme.rst is missing or the first line does not
  481. match what is expected
  482. """
  483. # We expect a readme file
  484. readme_fname = os.path.join(srcdir, 'readme.rst')
  485. if not os.path.exists(readme_fname):
  486. raise ValueError(
  487. f"Expected file '{readme_fname}' - try using -s to specify the "
  488. 'arm-trusted-firmware directory')
  489. readme = tools.read_file(readme_fname, binary=False)
  490. first_line = 'Trusted Firmware-A'
  491. if readme.splitlines()[0] != first_line:
  492. raise ValueError(f"'{readme_fname}' does not start with '{first_line}'")
  493. macros = parse_macros(srcdir)
  494. names = parse_names(srcdir)
  495. output = create_code_output(macros, names)
  496. orig = tools.read_file(oldfile, binary=False)
  497. re_fip_list = re.compile(r'(.*FIP_TYPE_LIST = \[).*?( ] # end.*)', re.S)
  498. mat = re_fip_list.match(orig)
  499. new_code = mat.group(1) + '\n' + output + mat.group(2) if mat else output
  500. if new_code == orig:
  501. print(f"Existing code in '{oldfile}' is up-to-date")
  502. else:
  503. tools.write_file(dstfile, new_code, binary=False)
  504. print(f'Needs update, try:\n\tmeld {dstfile} {oldfile}')
  505. def main(argv, oldfile):
  506. """Main program for this tool
  507. Args:
  508. argv (list): List of str command-line arguments
  509. oldfile (str): Python source file to compare against
  510. Returns:
  511. int: 0 (exit code)
  512. """
  513. parser = ArgumentParser(epilog='''Creates an updated version of this code,
  514. with a table of FIP-entry types parsed from the arm-trusted-firmware source
  515. directory''')
  516. parser.add_argument(
  517. '-D', '--debug', action='store_true',
  518. help='Enabling debugging (provides a full traceback on error)')
  519. parser.add_argument(
  520. '-o', '--outfile', type=str, default='fip_util.py.out',
  521. help='Output file to write new fip_util.py file to')
  522. parser.add_argument(
  523. '-s', '--src', type=str, default='.',
  524. help='Directory containing the arm-trusted-firmware source')
  525. args = parser.parse_args(argv)
  526. if not args.debug:
  527. sys.tracebacklimit = 0
  528. parse_atf_source(args.src, args.outfile, oldfile)
  529. return 0
  530. if __name__ == "__main__":
  531. sys.exit(main(sys.argv[1:], OUR_FILE)) # pragma: no cover