gen_esp32part.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #!/usr/bin/env python
  2. #
  3. # ESP32 partition table generation tool
  4. #
  5. # Converts partition tables to/from CSV and binary formats.
  6. #
  7. # See http://esp-idf.readthedocs.io/en/latest/partition-tables.html for explanation of
  8. # partition table structure and uses.
  9. import argparse
  10. import os
  11. import re
  12. import struct
  13. import sys
  14. MAX_PARTITION_LENGTH = 0xC00 # 3K for partition data (96 entries) leaves 1K in a 4K sector for signature
  15. __version__ = '1.0'
  16. quiet = False
  17. def status(msg):
  18. """ Print status message to stderr """
  19. if not quiet:
  20. critical(msg)
  21. def critical(msg):
  22. """ Print critical message to stderr """
  23. if not quiet:
  24. sys.stderr.write(msg)
  25. sys.stderr.write('\n')
  26. class PartitionTable(list):
  27. def __init__(self):
  28. super(PartitionTable, self).__init__(self)
  29. @classmethod
  30. def from_csv(cls, csv_contents):
  31. res = PartitionTable()
  32. lines = csv_contents.split("\n")
  33. for line_no in range(len(lines)):
  34. line = lines[line_no].strip()
  35. if line.startswith("#") or len(line) == 0:
  36. continue
  37. try:
  38. res.append(PartitionDefinition.from_csv(line))
  39. except InputError as e:
  40. raise InputError("Error at line %d: %s" % (line_no+1, e))
  41. except Exception:
  42. critical("Unexpected error parsing line %d: %s" % (line_no+1, line))
  43. raise
  44. # fix up missing offsets & negative sizes
  45. last_end = 0x5000 # first offset after partition table
  46. for e in res:
  47. if e.offset is None:
  48. pad_to = 0x10000 if e.type == PartitionDefinition.APP_TYPE else 4
  49. if last_end % pad_to != 0:
  50. last_end += pad_to - (last_end % pad_to)
  51. e.offset = last_end
  52. if e.size < 0:
  53. e.size = -e.size - e.offset
  54. last_end = e.offset + e.size
  55. return res
  56. def __getitem__(self, item):
  57. """ Allow partition table access via name as well as by
  58. numeric index. """
  59. if isinstance(item, str):
  60. for x in self:
  61. if x.name == item:
  62. return x
  63. raise ValueError("No partition entry named '%s'" % item)
  64. else:
  65. return super(PartitionTable, self).__getitem__(item)
  66. def verify(self):
  67. # verify each partition individually
  68. for p in self:
  69. p.verify()
  70. # check for overlaps
  71. last = None
  72. for p in sorted(self):
  73. if p.offset < 0x5000:
  74. raise InputError("Partition offset 0x%x is below 0x5000" % p.offset)
  75. if last is not None and p.offset < last.offset + last.size:
  76. raise InputError("Partition at 0x%x overlaps 0x%x-0x%x" % (p.offset, last.offset, last.offset+last.size-1))
  77. last = p
  78. @classmethod
  79. def from_binary(cls, b):
  80. result = cls()
  81. for o in range(0,len(b),32):
  82. data = b[o:o+32]
  83. if len(data) != 32:
  84. raise InputError("Partition table length must be a multiple of 32 bytes")
  85. if data == '\xFF'*32:
  86. return result # got end marker
  87. result.append(PartitionDefinition.from_binary(data))
  88. raise InputError("Partition table is missing an end-of-table marker")
  89. def to_binary(self):
  90. result = "".join(e.to_binary() for e in self)
  91. if len(result )>= MAX_PARTITION_LENGTH:
  92. raise InputError("Binary partition table length (%d) longer than max" % len(result))
  93. result += "\xFF" * (MAX_PARTITION_LENGTH - len(result)) # pad the sector, for signing
  94. return result
  95. def to_csv(self, simple_formatting=False):
  96. rows = [ "# Espressif ESP32 Partition Table",
  97. "# Name, Type, SubType, Offset, Size, Flags" ]
  98. rows += [ x.to_csv(simple_formatting) for x in self ]
  99. return "\n".join(rows) + "\n"
  100. class PartitionDefinition(object):
  101. APP_TYPE = 0x00
  102. DATA_TYPE = 0x01
  103. TYPES = {
  104. "app" : APP_TYPE,
  105. "data" : DATA_TYPE,
  106. }
  107. # Keep this map in sync with esp_partition_subtype_t enum in esp_partition.h
  108. SUBTYPES = {
  109. APP_TYPE : {
  110. "factory" : 0x00,
  111. "test" : 0x20,
  112. },
  113. DATA_TYPE : {
  114. "ota" : 0x00,
  115. "phy" : 0x01,
  116. "nvs" : 0x02,
  117. "coredump" : 0x03,
  118. "esphttpd" : 0x80,
  119. "fat" : 0x81,
  120. "spiffs" : 0x82,
  121. },
  122. }
  123. MAGIC_BYTES = "\xAA\x50"
  124. ALIGNMENT = {
  125. APP_TYPE : 0x1000,
  126. DATA_TYPE : 0x04,
  127. }
  128. # dictionary maps flag name (as used in CSV flags list, property name)
  129. # to bit set in flags words in binary format
  130. FLAGS = {
  131. "encrypted" : 0
  132. }
  133. # add subtypes for the 16 OTA slot values ("ota_XXX, etc.")
  134. for ota_slot in range(16):
  135. SUBTYPES[TYPES["app"]]["ota_%d" % ota_slot] = 0x10 + ota_slot
  136. def __init__(self):
  137. self.name = ""
  138. self.type = None
  139. self.subtype = None
  140. self.offset = None
  141. self.size = None
  142. self.encrypted = False
  143. @classmethod
  144. def from_csv(cls, line):
  145. """ Parse a line from the CSV """
  146. line_w_defaults = line + ",,,," # lazy way to support default fields
  147. def expand_vars(f):
  148. f = os.path.expandvars(f)
  149. m = re.match(r'(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)', f)
  150. if m:
  151. raise InputError("unknown variable '%s'" % m.group(1))
  152. return f
  153. fields = [ expand_vars(f.strip()) for f in line_w_defaults.split(",") ]
  154. res = PartitionDefinition()
  155. res.name = fields[0]
  156. res.type = res.parse_type(fields[1])
  157. res.subtype = res.parse_subtype(fields[2])
  158. res.offset = res.parse_address(fields[3])
  159. res.size = res.parse_address(fields[4])
  160. if res.size is None:
  161. raise InputError("Size field can't be empty")
  162. flags = fields[5].split(":")
  163. for flag in flags:
  164. if flag in cls.FLAGS:
  165. setattr(res, flag, True)
  166. elif len(flag) > 0:
  167. raise InputError("CSV flag column contains unknown flag '%s'" % (flag))
  168. return res
  169. def __eq__(self, other):
  170. return self.name == other.name and self.type == other.type \
  171. and self.subtype == other.subtype and self.offset == other.offset \
  172. and self.size == other.size
  173. def __repr__(self):
  174. def maybe_hex(x):
  175. return "0x%x" % x if x is not None else "None"
  176. return "PartitionDefinition('%s', 0x%x, 0x%x, %s, %s)" % (self.name, self.type, self.subtype or 0,
  177. maybe_hex(self.offset), maybe_hex(self.size))
  178. def __str__(self):
  179. return "Part '%s' %d/%d @ 0x%x size 0x%x" % (self.name, self.type, self.subtype, self.offset or -1, self.size or -1)
  180. def __cmp__(self, other):
  181. return self.offset - other.offset
  182. def parse_type(self, strval):
  183. if strval == "":
  184. raise InputError("Field 'type' can't be left empty.")
  185. return parse_int(strval, self.TYPES)
  186. def parse_subtype(self, strval):
  187. if strval == "":
  188. return 0 # default
  189. return parse_int(strval, self.SUBTYPES.get(self.type, {}))
  190. def parse_address(self, strval):
  191. if strval == "":
  192. return None # PartitionTable will fill in default
  193. return parse_int(strval)
  194. def verify(self):
  195. if self.type is None:
  196. raise ValidationError("Type field is not set")
  197. if self.subtype is None:
  198. raise ValidationError("Subtype field is not set")
  199. if self.offset is None:
  200. raise ValidationError("Offset field is not set")
  201. align = self.ALIGNMENT.get(self.type, 4)
  202. if self.offset % align:
  203. raise ValidationError("%s offset 0x%x is not aligned to 0x%x" % (self.name, self.offset, align))
  204. if self.size is None:
  205. raise ValidationError("Size field is not set")
  206. STRUCT_FORMAT = "<2sBBLL16sL"
  207. @classmethod
  208. def from_binary(cls, b):
  209. if len(b) != 32:
  210. raise InputError("Partition definition length must be exactly 32 bytes. Got %d bytes." % len(b))
  211. res = cls()
  212. (magic, res.type, res.subtype, res.offset,
  213. res.size, res.name, flags) = struct.unpack(cls.STRUCT_FORMAT, b)
  214. if "\x00" in res.name: # strip null byte padding from name string
  215. res.name = res.name[:res.name.index("\x00")]
  216. if magic != cls.MAGIC_BYTES:
  217. raise InputError("Invalid magic bytes (%r) for partition definition" % magic)
  218. for flag,bit in cls.FLAGS.items():
  219. if flags & (1<<bit):
  220. setattr(res, flag, True)
  221. flags &= ~(1<<bit)
  222. if flags != 0:
  223. critical("WARNING: Partition definition had unknown flag(s) 0x%08x. Newer binary format?" % flags)
  224. return res
  225. def get_flags_list(self):
  226. return [ flag for flag in self.FLAGS.keys() if getattr(self, flag) ]
  227. def to_binary(self):
  228. flags = sum((1 << self.FLAGS[flag]) for flag in self.get_flags_list())
  229. return struct.pack(self.STRUCT_FORMAT,
  230. self.MAGIC_BYTES,
  231. self.type, self.subtype,
  232. self.offset, self.size,
  233. self.name,
  234. flags)
  235. def to_csv(self, simple_formatting=False):
  236. def addr_format(a, include_sizes):
  237. if not simple_formatting and include_sizes:
  238. for (val, suffix) in [ (0x100000, "M"), (0x400, "K") ]:
  239. if a % val == 0:
  240. return "%d%s" % (a / val, suffix)
  241. return "0x%x" % a
  242. def lookup_keyword(t, keywords):
  243. for k,v in keywords.items():
  244. if simple_formatting == False and t == v:
  245. return k
  246. return "%d" % t
  247. def generate_text_flags():
  248. """ colon-delimited list of flags """
  249. return ":".join(self.get_flags_list())
  250. return ",".join([ self.name,
  251. lookup_keyword(self.type, self.TYPES),
  252. lookup_keyword(self.subtype, self.SUBTYPES.get(self.type, {})),
  253. addr_format(self.offset, False),
  254. addr_format(self.size, True),
  255. generate_text_flags()])
  256. class InputError(RuntimeError):
  257. def __init__(self, e):
  258. super(InputError, self).__init__(e)
  259. def parse_int(v, keywords={}):
  260. """Generic parser for integer fields - int(x,0) with provision for
  261. k/m/K/M suffixes and 'keyword' value lookup.
  262. """
  263. try:
  264. for letter, multiplier in [ ("k",1024), ("m",1024*1024) ]:
  265. if v.lower().endswith(letter):
  266. return parse_int(v[:-1], keywords) * multiplier
  267. return int(v, 0)
  268. except ValueError:
  269. if len(keywords) == 0:
  270. raise InputError("Invalid field value %s" % v)
  271. try:
  272. return keywords[v.lower()]
  273. except KeyError:
  274. raise InputError("Value '%s' is not valid. Known keywords: %s" % (v, ", ".join(keywords)))
  275. def main():
  276. global quiet
  277. parser = argparse.ArgumentParser(description='ESP32 partition table utility')
  278. parser.add_argument('--verify', '-v', help='Verify partition table fields', default=True, action='store_false')
  279. parser.add_argument('--quiet', '-q', help="Don't print status messages to stderr", action='store_true')
  280. parser.add_argument('input', help='Path to CSV or binary file to parse. Will use stdin if omitted.', type=argparse.FileType('r'), default=sys.stdin)
  281. parser.add_argument('output', help='Path to output converted binary or CSV file. Will use stdout if omitted, unless the --display argument is also passed (in which case only the summary is printed.)',
  282. nargs='?',
  283. default='-')
  284. args = parser.parse_args()
  285. quiet = args.quiet
  286. input = args.input.read()
  287. input_is_binary = input[0:2] == PartitionDefinition.MAGIC_BYTES
  288. if input_is_binary:
  289. status("Parsing binary partition input...")
  290. table = PartitionTable.from_binary(input)
  291. else:
  292. status("Parsing CSV input...")
  293. table = PartitionTable.from_csv(input)
  294. if args.verify:
  295. status("Verifying table...")
  296. table.verify()
  297. if input_is_binary:
  298. output = table.to_csv()
  299. else:
  300. output = table.to_binary()
  301. with sys.stdout if args.output == '-' else open(args.output, 'w') as f:
  302. f.write(output)
  303. if __name__ == '__main__':
  304. try:
  305. main()
  306. except InputError as e:
  307. print >>sys.stderr, e
  308. sys.exit(2)