mkdfu.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2020 Espressif Systems (Shanghai) PTE LTD
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # This program creates archives compatible with ESP32-S* ROM DFU implementation.
  18. #
  19. # The archives are in CPIO format. Each file which needs to be flashed is added to the archive
  20. # as a separate file. In addition to that, a special index file, 'dfuinfo0.dat', is created.
  21. # This file must be the first one in the archive. It contains binary structures describing each
  22. # subsequent file (for example, where the file needs to be flashed/loaded).
  23. from collections import namedtuple
  24. from future.utils import iteritems
  25. import argparse
  26. import hashlib
  27. import json
  28. import os
  29. import struct
  30. import zlib
  31. try:
  32. import typing
  33. except ImportError:
  34. # Only used for type annotations
  35. pass
  36. try:
  37. from itertools import izip as zip
  38. except ImportError:
  39. # Python 3
  40. pass
  41. # CPIO ("new ASCII") format related things
  42. CPIO_MAGIC = b"070701"
  43. CPIO_STRUCT = b"=6s" + b"8s" * 13
  44. CPIOHeader = namedtuple(
  45. "CPIOHeader",
  46. [
  47. "magic",
  48. "ino",
  49. "mode",
  50. "uid",
  51. "gid",
  52. "nlink",
  53. "mtime",
  54. "filesize",
  55. "devmajor",
  56. "devminor",
  57. "rdevmajor",
  58. "rdevminor",
  59. "namesize",
  60. "check",
  61. ],
  62. )
  63. CPIO_TRAILER = "TRAILER!!!"
  64. def make_cpio_header(
  65. filename_len, file_len, is_trailer=False
  66. ): # type: (int, int, bool) -> CPIOHeader
  67. """ Returns CPIOHeader for the given file name and file size """
  68. def as_hex(val): # type: (int) -> bytes
  69. return "{:08x}".format(val).encode("ascii")
  70. hex_0 = as_hex(0)
  71. mode = hex_0 if is_trailer else as_hex(0o0100644)
  72. nlink = as_hex(1) if is_trailer else hex_0
  73. return CPIOHeader(
  74. magic=CPIO_MAGIC,
  75. ino=hex_0,
  76. mode=mode,
  77. uid=hex_0,
  78. gid=hex_0,
  79. nlink=nlink,
  80. mtime=hex_0,
  81. filesize=as_hex(file_len),
  82. devmajor=hex_0,
  83. devminor=hex_0,
  84. rdevmajor=hex_0,
  85. rdevminor=hex_0,
  86. namesize=as_hex(filename_len),
  87. check=hex_0,
  88. )
  89. # DFU format related things
  90. # Structure of one entry in dfuinfo0.dat
  91. DFUINFO_STRUCT = b"<I I 64s 16s"
  92. DFUInfo = namedtuple("DFUInfo", ["address", "flags", "name", "md5"])
  93. DFUINFO_FILE = "dfuinfo0.dat"
  94. # Structure which gets added at the end of the entire DFU file
  95. DFUSUFFIX_STRUCT = b"<H H H H 3s B"
  96. DFUSuffix = namedtuple(
  97. "DFUSuffix", ["bcd_device", "pid", "vid", "bcd_dfu", "sig", "len"]
  98. )
  99. ESPRESSIF_VID = 12346
  100. # TODO: set PID based on the chip type (add a command line argument)
  101. DFUSUFFIX_DEFAULT = DFUSuffix(0xFFFF, 0xFFFF, ESPRESSIF_VID, 0x0100, b"UFD", 16)
  102. # This CRC32 gets added after DFUSUFFIX_STRUCT
  103. DFUCRC_STRUCT = b"<I"
  104. def dfu_crc(data, crc=0): # type: (bytes, int) -> int
  105. """ Calculate CRC32/JAMCRC of data, with an optional initial value """
  106. uint32_max = 0xFFFFFFFF
  107. return uint32_max - (zlib.crc32(data, crc) & uint32_max)
  108. def pad_bytes(b, multiple, padding=b"\x00"): # type: (bytes, int, bytes) -> bytes
  109. """ Pad 'b' to a length divisible by 'multiple' """
  110. padded_len = (len(b) + multiple - 1) // multiple * multiple
  111. return b + padding * (padded_len - len(b))
  112. class EspDfuWriter(object):
  113. def __init__(self, dest_file): # type: (typing.BinaryIO) -> None
  114. self.dest = dest_file
  115. self.entries = [] # type: typing.List[bytes]
  116. self.index = [] # type: typing.List[DFUInfo]
  117. def add_file(self, flash_addr, path): # type: (int, str) -> None
  118. """ Add file to be written into flash at given address """
  119. with open(path, "rb") as f:
  120. self._add_cpio_flash_entry(os.path.basename(path), flash_addr, f.read())
  121. def finish(self): # type: () -> None
  122. """ Write DFU file """
  123. # Prepare and add dfuinfo0.dat file
  124. dfuinfo = b"".join([struct.pack(DFUINFO_STRUCT, *item) for item in self.index])
  125. self._add_cpio_entry(DFUINFO_FILE, dfuinfo, first=True)
  126. # Add CPIO archive trailer
  127. self._add_cpio_entry(CPIO_TRAILER, b"", trailer=True)
  128. # Combine all the entries and pad the file
  129. out_data = b"".join(self.entries)
  130. cpio_block_size = 10240
  131. out_data = pad_bytes(out_data, cpio_block_size)
  132. # Add DFU suffix and CRC
  133. out_data += struct.pack(DFUSUFFIX_STRUCT, *DFUSUFFIX_DEFAULT)
  134. out_data += struct.pack(DFUCRC_STRUCT, dfu_crc(out_data))
  135. # Finally write the entire binary
  136. self.dest.write(out_data)
  137. def _add_cpio_flash_entry(
  138. self, filename, flash_addr, data
  139. ): # type: (str, int, bytes) -> None
  140. md5 = hashlib.md5()
  141. md5.update(data)
  142. self.index.append(
  143. DFUInfo(
  144. address=flash_addr,
  145. flags=0,
  146. name=filename.encode("utf-8"),
  147. md5=md5.digest(),
  148. )
  149. )
  150. self._add_cpio_entry(filename, data)
  151. def _add_cpio_entry(
  152. self, filename, data, first=False, trailer=False
  153. ): # type: (str, bytes, bool, bool) -> None
  154. filename_b = filename.encode("utf-8") + b"\x00"
  155. cpio_header = make_cpio_header(len(filename_b), len(data), is_trailer=trailer)
  156. entry = pad_bytes(
  157. struct.pack(CPIO_STRUCT, *cpio_header) + filename_b, 4
  158. ) + pad_bytes(data, 4)
  159. if not first:
  160. self.entries.append(entry)
  161. else:
  162. self.entries.insert(0, entry)
  163. def action_write(args):
  164. writer = EspDfuWriter(args['output_file'])
  165. for addr, f in args['files']:
  166. print('Adding {} at {:#x}'.format(f, addr))
  167. writer.add_file(addr, f)
  168. writer.finish()
  169. print('"{}" has been written. You may proceed with DFU flashing.'.format(args['output_file'].name))
  170. def main():
  171. parser = argparse.ArgumentParser()
  172. # Provision to add "info" command
  173. subparsers = parser.add_subparsers(dest="command")
  174. write_parser = subparsers.add_parser("write")
  175. write_parser.add_argument("-o", "--output-file",
  176. help='Filename for storing the output DFU image',
  177. required=True,
  178. type=argparse.FileType("wb"))
  179. write_parser.add_argument("--json",
  180. help='Optional file for loading "flash_files" dictionary with <address> <file> items')
  181. write_parser.add_argument("files",
  182. metavar="<address> <file>", help='Add <file> at <address>',
  183. nargs="*")
  184. args = parser.parse_args()
  185. def check_file(file_name):
  186. if not os.path.isfile(file_name):
  187. raise RuntimeError('{} is not a regular file!'.format(file_name))
  188. return file_name
  189. files = []
  190. if args.files:
  191. files += [(int(addr, 0), check_file(f_name)) for addr, f_name in zip(args.files[::2], args.files[1::2])]
  192. if args.json:
  193. json_dir = os.path.dirname(os.path.abspath(args.json))
  194. def process_json_file(path):
  195. '''
  196. The input path is relative to json_dir. This function makes it relative to the current working
  197. directory.
  198. '''
  199. return check_file(os.path.relpath(os.path.join(json_dir, path), start=os.curdir))
  200. with open(args.json) as f:
  201. files += [(int(addr, 0),
  202. process_json_file(f_name)) for addr, f_name in iteritems(json.load(f)['flash_files'])]
  203. files = sorted([(addr, f_name) for addr, f_name in iteritems(dict(files))],
  204. key=lambda x: x[0]) # remove possible duplicates and sort based on the address
  205. cmd_args = {'output_file': args.output_file,
  206. 'files': files,
  207. }
  208. {'write': action_write
  209. }[args.command](cmd_args)
  210. if __name__ == "__main__":
  211. main()