gen_esp32part.py 14 KB

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