mkdfu.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #!/usr/bin/env python
  2. #
  3. # SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD
  4. # SPDX-License-Identifier: Apache-2.0
  5. #
  6. # This program creates archives compatible with ESP32-S* ROM DFU implementation.
  7. #
  8. # The archives are in CPIO format. Each file which needs to be flashed is added to the archive
  9. # as a separate file. In addition to that, a special index file, 'dfuinfo0.dat', is created.
  10. # This file must be the first one in the archive. It contains binary structures describing each
  11. # subsequent file (for example, where the file needs to be flashed/loaded).
  12. from __future__ import print_function, unicode_literals
  13. import argparse
  14. import hashlib
  15. import json
  16. import os
  17. import struct
  18. import zlib
  19. from collections import namedtuple
  20. from functools import partial
  21. from future.utils import iteritems
  22. try:
  23. import typing
  24. except ImportError:
  25. # Only used for type annotations
  26. pass
  27. try:
  28. from itertools import izip as zip # type: ignore
  29. except ImportError:
  30. # Python 3
  31. pass
  32. # CPIO ("new ASCII") format related things
  33. CPIO_MAGIC = b'070701'
  34. CPIO_STRUCT = b'=6s' + b'8s' * 13
  35. CPIOHeader = namedtuple(
  36. 'CPIOHeader',
  37. [
  38. 'magic',
  39. 'ino',
  40. 'mode',
  41. 'uid',
  42. 'gid',
  43. 'nlink',
  44. 'mtime',
  45. 'filesize',
  46. 'devmajor',
  47. 'devminor',
  48. 'rdevmajor',
  49. 'rdevminor',
  50. 'namesize',
  51. 'check',
  52. ],
  53. )
  54. CPIO_TRAILER = 'TRAILER!!!'
  55. def make_cpio_header(
  56. filename_len, file_len, is_trailer=False
  57. ): # type: (int, int, bool) -> CPIOHeader
  58. """ Returns CPIOHeader for the given file name and file size """
  59. def as_hex(val): # type: (int) -> bytes
  60. return '{:08x}'.format(val).encode('ascii')
  61. hex_0 = as_hex(0)
  62. mode = hex_0 if is_trailer else as_hex(0o0100644)
  63. nlink = as_hex(1) if is_trailer else hex_0
  64. return CPIOHeader(
  65. magic=CPIO_MAGIC,
  66. ino=hex_0,
  67. mode=mode,
  68. uid=hex_0,
  69. gid=hex_0,
  70. nlink=nlink,
  71. mtime=hex_0,
  72. filesize=as_hex(file_len),
  73. devmajor=hex_0,
  74. devminor=hex_0,
  75. rdevmajor=hex_0,
  76. rdevminor=hex_0,
  77. namesize=as_hex(filename_len),
  78. check=hex_0,
  79. )
  80. # DFU format related things
  81. # Structure of one entry in dfuinfo0.dat
  82. DFUINFO_STRUCT = b'<I I 64s 16s'
  83. DFUInfo = namedtuple('DFUInfo', ['address', 'flags', 'name', 'md5'])
  84. DFUINFO_FILE = 'dfuinfo0.dat'
  85. # Structure which gets added at the end of the entire DFU file
  86. DFUSUFFIX_STRUCT = b'<H H H H 3s B'
  87. DFUSuffix = namedtuple(
  88. 'DFUSuffix', ['bcd_device', 'pid', 'vid', 'bcd_dfu', 'sig', 'len']
  89. )
  90. ESPRESSIF_VID = 12346
  91. # This CRC32 gets added after DFUSUFFIX_STRUCT
  92. DFUCRC_STRUCT = b'<I'
  93. # Flash chip parameters file related things
  94. FlashParamsData = namedtuple(
  95. 'FlashParamsData',
  96. [
  97. 'ishspi',
  98. 'legacy',
  99. 'deviceId',
  100. 'chip_size',
  101. 'block_size',
  102. 'sector_size',
  103. 'page_size',
  104. 'status_mask',
  105. ],
  106. )
  107. FLASH_PARAMS_STRUCT = b'<IIIIIIII'
  108. FLASH_PARAMS_FILE = 'flash_params.dat'
  109. DFU_INFO_FLAG_PARAM = (1 << 2)
  110. DFU_INFO_FLAG_NOERASE = (1 << 3)
  111. DFU_INFO_FLAG_IGNORE_MD5 = (1 << 4)
  112. def dfu_crc(data, crc=0): # type: (bytes, int) -> int
  113. """ Calculate CRC32/JAMCRC of data, with an optional initial value """
  114. uint32_max = 0xFFFFFFFF
  115. return uint32_max - (zlib.crc32(data, crc) & uint32_max)
  116. def pad_bytes(b, multiple, padding=b'\x00'): # type: (bytes, int, bytes) -> bytes
  117. """ Pad 'b' to a length divisible by 'multiple' """
  118. padded_len = (len(b) + multiple - 1) // multiple * multiple
  119. return b + padding * (padded_len - len(b))
  120. def flash_size_bytes(size): # type: (str) -> int
  121. """
  122. Given a flash size passed in args.flash_size
  123. (ie 4MB), return the size in bytes.
  124. """
  125. try:
  126. return int(size.rstrip('MB'), 10) * 1024 * 1024
  127. except ValueError:
  128. raise argparse.ArgumentTypeError('Unknown size {}'.format(size))
  129. class EspDfuWriter(object):
  130. def __init__(self, dest_file, pid, part_size): # type: (typing.BinaryIO, int, int) -> None
  131. self.dest = dest_file
  132. self.pid = pid
  133. self.part_size = part_size
  134. self.entries = [] # type: typing.List[bytes]
  135. self.index = [] # type: typing.List[DFUInfo]
  136. def add_flash_params_file(self, flash_size): # type: (str) -> None
  137. """
  138. Add a file containing flash chip parameters
  139. Corresponds to the "flashchip" data structure that the ROM
  140. has in RAM.
  141. See flash_set_parameters() in esptool.py for more info
  142. """
  143. flash_params = FlashParamsData(
  144. ishspi=0,
  145. legacy=0,
  146. deviceId=0, # ignored
  147. chip_size=flash_size_bytes(flash_size), # flash size in bytes
  148. block_size=64 * 1024,
  149. sector_size=4 * 1024,
  150. page_size=256,
  151. status_mask=0xffff,
  152. )
  153. data = struct.pack(FLASH_PARAMS_STRUCT, *flash_params)
  154. flags = DFU_INFO_FLAG_PARAM | DFU_INFO_FLAG_NOERASE | DFU_INFO_FLAG_IGNORE_MD5
  155. self._add_cpio_flash_entry(FLASH_PARAMS_FILE, 0, data, flags)
  156. def add_file(self, flash_addr, path): # type: (int, str) -> None
  157. """
  158. Add file to be written into flash at given address
  159. Files are split up into chunks in order avoid timing-out during erasing large regions. Instead of adding
  160. "app.bin" at flash_addr it will add:
  161. 1. app.bin at flash_addr # sizeof(app.bin) == self.part_size
  162. 2. app.bin.1 at flash_addr + self.part_size
  163. 3. app.bin.2 at flash_addr + 2 * self.part_size
  164. ...
  165. """
  166. f_name = os.path.basename(path)
  167. with open(path, 'rb') as f:
  168. for i, chunk in enumerate(iter(partial(f.read, self.part_size), b'')):
  169. n = f_name if i == 0 else '.'.join([f_name, str(i)])
  170. self._add_cpio_flash_entry(n, flash_addr, chunk)
  171. flash_addr += len(chunk)
  172. def finish(self): # type: () -> None
  173. """ Write DFU file """
  174. # Prepare and add dfuinfo0.dat file
  175. dfuinfo = b''.join([struct.pack(DFUINFO_STRUCT, *item) for item in self.index])
  176. self._add_cpio_entry(DFUINFO_FILE, dfuinfo, first=True)
  177. # Add CPIO archive trailer
  178. self._add_cpio_entry(CPIO_TRAILER, b'', trailer=True)
  179. # Combine all the entries and pad the file
  180. out_data = b''.join(self.entries)
  181. cpio_block_size = 10240
  182. out_data = pad_bytes(out_data, cpio_block_size)
  183. # Add DFU suffix and CRC
  184. dfu_suffix = DFUSuffix(0xFFFF, self.pid, ESPRESSIF_VID, 0x0100, b'UFD', 16)
  185. out_data += struct.pack(DFUSUFFIX_STRUCT, *dfu_suffix)
  186. out_data += struct.pack(DFUCRC_STRUCT, dfu_crc(out_data))
  187. # Finally write the entire binary
  188. self.dest.write(out_data)
  189. def _add_cpio_flash_entry(
  190. self, filename, flash_addr, data, flags=0
  191. ): # type: (str, int, bytes, int) -> None
  192. md5 = hashlib.md5()
  193. md5.update(data)
  194. self.index.append(
  195. DFUInfo(
  196. address=flash_addr,
  197. flags=flags,
  198. name=filename.encode('utf-8'),
  199. md5=md5.digest(),
  200. )
  201. )
  202. self._add_cpio_entry(filename, data)
  203. def _add_cpio_entry(
  204. self, filename, data, first=False, trailer=False
  205. ): # type: (str, bytes, bool, bool) -> None
  206. filename_b = filename.encode('utf-8') + b'\x00'
  207. cpio_header = make_cpio_header(len(filename_b), len(data), is_trailer=trailer)
  208. entry = pad_bytes(
  209. struct.pack(CPIO_STRUCT, *cpio_header) + filename_b, 4
  210. ) + pad_bytes(data, 4)
  211. if not first:
  212. self.entries.append(entry)
  213. else:
  214. self.entries.insert(0, entry)
  215. def action_write(args): # type: (typing.Mapping[str, typing.Any]) -> None
  216. writer = EspDfuWriter(args['output_file'], args['pid'], args['part_size'])
  217. print('Adding flash chip parameters file with flash_size = {}'.format(args['flash_size']))
  218. writer.add_flash_params_file(args['flash_size'])
  219. for addr, f in args['files']:
  220. print('Adding {} at {:#x}'.format(f, addr))
  221. writer.add_file(addr, f)
  222. writer.finish()
  223. print('"{}" has been written. You may proceed with DFU flashing.'.format(args['output_file'].name))
  224. if args['part_size'] % (4 * 1024) != 0:
  225. print('WARNING: Partition size of DFU is not multiple of 4k (4096). You might get unexpected behavior.')
  226. def main(): # type: () -> None
  227. parser = argparse.ArgumentParser()
  228. # Provision to add "info" command
  229. subparsers = parser.add_subparsers(dest='command')
  230. write_parser = subparsers.add_parser('write')
  231. write_parser.add_argument('-o', '--output-file',
  232. help='Filename for storing the output DFU image',
  233. required=True,
  234. type=argparse.FileType('wb'))
  235. write_parser.add_argument('--pid',
  236. required=True,
  237. type=lambda h: int(h, 16),
  238. help='Hexa-decimal product indentificator')
  239. write_parser.add_argument('--json',
  240. help='Optional file for loading "flash_files" dictionary with <address> <file> items')
  241. write_parser.add_argument('--part-size',
  242. default=os.environ.get('ESP_DFU_PART_SIZE', 512 * 1024),
  243. type=lambda x: int(x, 0),
  244. help='Larger files are split-up into smaller partitions of this size')
  245. write_parser.add_argument('files',
  246. metavar='<address> <file>', help='Add <file> at <address>',
  247. nargs='*')
  248. write_parser.add_argument('-fs', '--flash-size',
  249. help='SPI Flash size in MegaBytes (1MB, 2MB, 4MB, 8MB, 16MB, 32MB, 64MB, 128MB)',
  250. choices=['1MB', '2MB', '4MB', '8MB', '16MB', '32MB', '64MB', '128MB'],
  251. default='2MB')
  252. args = parser.parse_args()
  253. def check_file(file_name): # type: (str) -> str
  254. if not os.path.isfile(file_name):
  255. raise RuntimeError('{} is not a regular file!'.format(file_name))
  256. return file_name
  257. files = []
  258. if args.files:
  259. files += [(int(addr, 0), check_file(f_name)) for addr, f_name in zip(args.files[::2], args.files[1::2])]
  260. if args.json:
  261. json_dir = os.path.dirname(os.path.abspath(args.json))
  262. def process_json_file(path): # type: (str) -> str
  263. '''
  264. The input path is relative to json_dir. This function makes it relative to the current working
  265. directory.
  266. '''
  267. return check_file(os.path.relpath(os.path.join(json_dir, path), start=os.curdir))
  268. with open(args.json) as f:
  269. files += [(int(addr, 0),
  270. process_json_file(f_name)) for addr, f_name in iteritems(json.load(f)['flash_files'])]
  271. files = sorted([(addr, f_name.decode('utf-8') if isinstance(f_name, type(b'')) else f_name) for addr, f_name in iteritems(dict(files))],
  272. key=lambda x: x[0]) # remove possible duplicates and sort based on the address
  273. cmd_args = {'output_file': args.output_file,
  274. 'files': files,
  275. 'pid': args.pid,
  276. 'part_size': args.part_size,
  277. 'flash_size': args.flash_size,
  278. }
  279. {'write': action_write
  280. }[args.command](cmd_args)
  281. if __name__ == '__main__':
  282. main()