gen_esp32part.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 https://docs.espressif.com/projects/esp-idf/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. from __future__ import unicode_literals
  25. import argparse
  26. import os
  27. import re
  28. import struct
  29. import sys
  30. import hashlib
  31. import binascii
  32. import errno
  33. MAX_PARTITION_LENGTH = 0xC00 # 3K for partition data (96 entries) leaves 1K in a 4K sector for signature
  34. MD5_PARTITION_BEGIN = b"\xEB\xEB" + b"\xFF" * 14 # The first 2 bytes are like magic numbers for MD5 sum
  35. PARTITION_TABLE_SIZE = 0x1000 # Size of partition table
  36. MIN_PARTITION_SUBTYPE_APP_OTA = 0x10
  37. NUM_PARTITION_SUBTYPE_APP_OTA = 16
  38. __version__ = '1.2'
  39. APP_TYPE = 0x00
  40. DATA_TYPE = 0x01
  41. TYPES = {
  42. "app": APP_TYPE,
  43. "data": DATA_TYPE,
  44. }
  45. # Keep this map in sync with esp_partition_subtype_t enum in esp_partition.h
  46. SUBTYPES = {
  47. APP_TYPE: {
  48. "factory": 0x00,
  49. "test": 0x20,
  50. },
  51. DATA_TYPE: {
  52. "ota": 0x00,
  53. "phy": 0x01,
  54. "nvs": 0x02,
  55. "coredump": 0x03,
  56. "nvs_keys": 0x04,
  57. "efuse": 0x05,
  58. "esphttpd": 0x80,
  59. "fat": 0x81,
  60. "spiffs": 0x82,
  61. },
  62. }
  63. quiet = False
  64. md5sum = True
  65. secure = False
  66. offset_part_table = 0
  67. def status(msg):
  68. """ Print status message to stderr """
  69. if not quiet:
  70. critical(msg)
  71. def critical(msg):
  72. """ Print critical message to stderr """
  73. sys.stderr.write(msg)
  74. sys.stderr.write('\n')
  75. class PartitionTable(list):
  76. def __init__(self):
  77. super(PartitionTable, self).__init__(self)
  78. @classmethod
  79. def from_csv(cls, csv_contents):
  80. res = PartitionTable()
  81. lines = csv_contents.splitlines()
  82. def expand_vars(f):
  83. f = os.path.expandvars(f)
  84. m = re.match(r'(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)', f)
  85. if m:
  86. raise InputError("unknown variable '%s'" % m.group(1))
  87. return f
  88. for line_no in range(len(lines)):
  89. line = expand_vars(lines[line_no]).strip()
  90. if line.startswith("#") or len(line) == 0:
  91. continue
  92. try:
  93. res.append(PartitionDefinition.from_csv(line, line_no + 1))
  94. except InputError as e:
  95. raise InputError("Error at line %d: %s" % (line_no + 1, e))
  96. except Exception:
  97. critical("Unexpected error parsing CSV line %d: %s" % (line_no + 1, line))
  98. raise
  99. # fix up missing offsets & negative sizes
  100. last_end = offset_part_table + PARTITION_TABLE_SIZE # first offset after partition table
  101. for e in res:
  102. if e.offset is not None and e.offset < last_end:
  103. if e == res[0]:
  104. raise InputError("CSV Error: First partition offset 0x%x overlaps end of partition table 0x%x"
  105. % (e.offset, last_end))
  106. else:
  107. raise InputError("CSV Error: Partitions overlap. Partition at line %d sets offset 0x%x. Previous partition ends 0x%x"
  108. % (e.line_no, e.offset, last_end))
  109. if e.offset is None:
  110. pad_to = 0x10000 if e.type == APP_TYPE else 4
  111. if last_end % pad_to != 0:
  112. last_end += pad_to - (last_end % pad_to)
  113. e.offset = last_end
  114. if e.size < 0:
  115. e.size = -e.size - e.offset
  116. last_end = e.offset + e.size
  117. return res
  118. def __getitem__(self, item):
  119. """ Allow partition table access via name as well as by
  120. numeric index. """
  121. if isinstance(item, str):
  122. for x in self:
  123. if x.name == item:
  124. return x
  125. raise ValueError("No partition entry named '%s'" % item)
  126. else:
  127. return super(PartitionTable, self).__getitem__(item)
  128. def find_by_type(self, ptype, subtype):
  129. """ Return a partition by type & subtype, returns
  130. None if not found """
  131. # convert ptype & subtypes names (if supplied this way) to integer values
  132. try:
  133. ptype = TYPES[ptype]
  134. except KeyError:
  135. try:
  136. ptype = int(ptype, 0)
  137. except TypeError:
  138. pass
  139. try:
  140. subtype = SUBTYPES[int(ptype)][subtype]
  141. except KeyError:
  142. try:
  143. subtype = int(subtype, 0)
  144. except TypeError:
  145. pass
  146. for p in self:
  147. if p.type == ptype and p.subtype == subtype:
  148. return p
  149. return None
  150. def find_by_name(self, name):
  151. for p in self:
  152. if p.name == name:
  153. return p
  154. return None
  155. def verify(self):
  156. # verify each partition individually
  157. for p in self:
  158. p.verify()
  159. # check on duplicate name
  160. names = [p.name for p in self]
  161. duplicates = set(n for n in names if names.count(n) > 1)
  162. # print sorted duplicate partitions by name
  163. if len(duplicates) != 0:
  164. print("A list of partitions that have the same name:")
  165. for p in sorted(self, key=lambda x:x.name):
  166. if len(duplicates.intersection([p.name])) != 0:
  167. print("%s" % (p.to_csv()))
  168. raise InputError("Partition names must be unique")
  169. # check for overlaps
  170. last = None
  171. for p in sorted(self, key=lambda x:x.offset):
  172. if p.offset < offset_part_table + PARTITION_TABLE_SIZE:
  173. raise InputError("Partition offset 0x%x is below 0x%x" % (p.offset, offset_part_table + PARTITION_TABLE_SIZE))
  174. if last is not None and p.offset < last.offset + last.size:
  175. raise InputError("Partition at 0x%x overlaps 0x%x-0x%x" % (p.offset, last.offset, last.offset + last.size - 1))
  176. last = p
  177. def flash_size(self):
  178. """ Return the size that partitions will occupy in flash
  179. (ie the offset the last partition ends at)
  180. """
  181. try:
  182. last = sorted(self, reverse=True)[0]
  183. except IndexError:
  184. return 0 # empty table!
  185. return last.offset + last.size
  186. @classmethod
  187. def from_binary(cls, b):
  188. md5 = hashlib.md5()
  189. result = cls()
  190. for o in range(0,len(b),32):
  191. data = b[o:o + 32]
  192. if len(data) != 32:
  193. raise InputError("Partition table length must be a multiple of 32 bytes")
  194. if data == b'\xFF' * 32:
  195. return result # got end marker
  196. if md5sum and data[:2] == MD5_PARTITION_BEGIN[:2]: # check only the magic number part
  197. if data[16:] == md5.digest():
  198. continue # the next iteration will check for the end marker
  199. else:
  200. raise InputError("MD5 checksums don't match! (computed: 0x%s, parsed: 0x%s)" % (md5.hexdigest(), binascii.hexlify(data[16:])))
  201. else:
  202. md5.update(data)
  203. result.append(PartitionDefinition.from_binary(data))
  204. raise InputError("Partition table is missing an end-of-table marker")
  205. def to_binary(self):
  206. result = b"".join(e.to_binary() for e in self)
  207. if md5sum:
  208. result += MD5_PARTITION_BEGIN + hashlib.md5(result).digest()
  209. if len(result) >= MAX_PARTITION_LENGTH:
  210. raise InputError("Binary partition table length (%d) longer than max" % len(result))
  211. result += b"\xFF" * (MAX_PARTITION_LENGTH - len(result)) # pad the sector, for signing
  212. return result
  213. def to_csv(self, simple_formatting=False):
  214. rows = ["# ESP-IDF Partition Table",
  215. "# Name, Type, SubType, Offset, Size, Flags"]
  216. rows += [x.to_csv(simple_formatting) for x in self]
  217. return "\n".join(rows) + "\n"
  218. class PartitionDefinition(object):
  219. MAGIC_BYTES = b"\xAA\x50"
  220. ALIGNMENT = {
  221. APP_TYPE: 0x10000,
  222. DATA_TYPE: 0x04,
  223. }
  224. # dictionary maps flag name (as used in CSV flags list, property name)
  225. # to bit set in flags words in binary format
  226. FLAGS = {
  227. "encrypted": 0
  228. }
  229. # add subtypes for the 16 OTA slot values ("ota_XX, etc.")
  230. for ota_slot in range(NUM_PARTITION_SUBTYPE_APP_OTA):
  231. SUBTYPES[TYPES["app"]]["ota_%d" % ota_slot] = MIN_PARTITION_SUBTYPE_APP_OTA + ota_slot
  232. def __init__(self):
  233. self.name = ""
  234. self.type = None
  235. self.subtype = None
  236. self.offset = None
  237. self.size = None
  238. self.encrypted = False
  239. @classmethod
  240. def from_csv(cls, line, line_no):
  241. """ Parse a line from the CSV """
  242. line_w_defaults = line + ",,,," # lazy way to support default fields
  243. fields = [f.strip() for f in line_w_defaults.split(",")]
  244. res = PartitionDefinition()
  245. res.line_no = line_no
  246. res.name = fields[0]
  247. res.type = res.parse_type(fields[1])
  248. res.subtype = res.parse_subtype(fields[2])
  249. res.offset = res.parse_address(fields[3])
  250. res.size = res.parse_address(fields[4])
  251. if res.size is None:
  252. raise InputError("Size field can't be empty")
  253. flags = fields[5].split(":")
  254. for flag in flags:
  255. if flag in cls.FLAGS:
  256. setattr(res, flag, True)
  257. elif len(flag) > 0:
  258. raise InputError("CSV flag column contains unknown flag '%s'" % (flag))
  259. return res
  260. def __eq__(self, other):
  261. return self.name == other.name and self.type == other.type \
  262. and self.subtype == other.subtype and self.offset == other.offset \
  263. and self.size == other.size
  264. def __repr__(self):
  265. def maybe_hex(x):
  266. return "0x%x" % x if x is not None else "None"
  267. return "PartitionDefinition('%s', 0x%x, 0x%x, %s, %s)" % (self.name, self.type, self.subtype or 0,
  268. maybe_hex(self.offset), maybe_hex(self.size))
  269. def __str__(self):
  270. return "Part '%s' %d/%d @ 0x%x size 0x%x" % (self.name, self.type, self.subtype, self.offset or -1, self.size or -1)
  271. def __cmp__(self, other):
  272. return self.offset - other.offset
  273. def __lt__(self, other):
  274. return self.offset < other.offset
  275. def __gt__(self, other):
  276. return self.offset > other.offset
  277. def __le__(self, other):
  278. return self.offset <= other.offset
  279. def __ge__(self, other):
  280. return self.offset >= other.offset
  281. def parse_type(self, strval):
  282. if strval == "":
  283. raise InputError("Field 'type' can't be left empty.")
  284. return parse_int(strval, TYPES)
  285. def parse_subtype(self, strval):
  286. if strval == "":
  287. return 0 # default
  288. return parse_int(strval, SUBTYPES.get(self.type, {}))
  289. def parse_address(self, strval):
  290. if strval == "":
  291. return None # PartitionTable will fill in default
  292. return parse_int(strval)
  293. def verify(self):
  294. if self.type is None:
  295. raise ValidationError(self, "Type field is not set")
  296. if self.subtype is None:
  297. raise ValidationError(self, "Subtype field is not set")
  298. if self.offset is None:
  299. raise ValidationError(self, "Offset field is not set")
  300. align = self.ALIGNMENT.get(self.type, 4)
  301. if self.offset % align:
  302. raise ValidationError(self, "Offset 0x%x is not aligned to 0x%x" % (self.offset, align))
  303. if self.size % align and secure:
  304. raise ValidationError(self, "Size 0x%x is not aligned to 0x%x" % (self.size, align))
  305. if self.size is None:
  306. raise ValidationError(self, "Size field is not set")
  307. if self.name in TYPES and TYPES.get(self.name, "") != self.type:
  308. critical("WARNING: Partition has name '%s' which is a partition type, but does not match this partition's "
  309. "type (0x%x). Mistake in partition table?" % (self.name, self.type))
  310. all_subtype_names = []
  311. for names in (t.keys() for t in SUBTYPES.values()):
  312. all_subtype_names += names
  313. if self.name in all_subtype_names and SUBTYPES.get(self.type, {}).get(self.name, "") != self.subtype:
  314. critical("WARNING: Partition has name '%s' which is a partition subtype, but this partition has "
  315. "non-matching type 0x%x and subtype 0x%x. Mistake in partition table?" % (self.name, self.type, self.subtype))
  316. STRUCT_FORMAT = b"<2sBBLL16sL"
  317. @classmethod
  318. def from_binary(cls, b):
  319. if len(b) != 32:
  320. raise InputError("Partition definition length must be exactly 32 bytes. Got %d bytes." % len(b))
  321. res = cls()
  322. (magic, res.type, res.subtype, res.offset,
  323. res.size, res.name, flags) = struct.unpack(cls.STRUCT_FORMAT, b)
  324. if b"\x00" in res.name: # strip null byte padding from name string
  325. res.name = res.name[:res.name.index(b"\x00")]
  326. res.name = res.name.decode()
  327. if magic != cls.MAGIC_BYTES:
  328. raise InputError("Invalid magic bytes (%r) for partition definition" % magic)
  329. for flag,bit in cls.FLAGS.items():
  330. if flags & (1 << bit):
  331. setattr(res, flag, True)
  332. flags &= ~(1 << bit)
  333. if flags != 0:
  334. critical("WARNING: Partition definition had unknown flag(s) 0x%08x. Newer binary format?" % flags)
  335. return res
  336. def get_flags_list(self):
  337. return [flag for flag in self.FLAGS.keys() if getattr(self, flag)]
  338. def to_binary(self):
  339. flags = sum((1 << self.FLAGS[flag]) for flag in self.get_flags_list())
  340. return struct.pack(self.STRUCT_FORMAT,
  341. self.MAGIC_BYTES,
  342. self.type, self.subtype,
  343. self.offset, self.size,
  344. self.name.encode(),
  345. flags)
  346. def to_csv(self, simple_formatting=False):
  347. def addr_format(a, include_sizes):
  348. if not simple_formatting and include_sizes:
  349. for (val, suffix) in [(0x100000, "M"), (0x400, "K")]:
  350. if a % val == 0:
  351. return "%d%s" % (a // val, suffix)
  352. return "0x%x" % a
  353. def lookup_keyword(t, keywords):
  354. for k,v in keywords.items():
  355. if simple_formatting is False and t == v:
  356. return k
  357. return "%d" % t
  358. def generate_text_flags():
  359. """ colon-delimited list of flags """
  360. return ":".join(self.get_flags_list())
  361. return ",".join([self.name,
  362. lookup_keyword(self.type, TYPES),
  363. lookup_keyword(self.subtype, SUBTYPES.get(self.type, {})),
  364. addr_format(self.offset, False),
  365. addr_format(self.size, True),
  366. generate_text_flags()])
  367. def parse_int(v, keywords={}):
  368. """Generic parser for integer fields - int(x,0) with provision for
  369. k/m/K/M suffixes and 'keyword' value lookup.
  370. """
  371. try:
  372. for letter, multiplier in [("k", 1024), ("m", 1024 * 1024)]:
  373. if v.lower().endswith(letter):
  374. return parse_int(v[:-1], keywords) * multiplier
  375. return int(v, 0)
  376. except ValueError:
  377. if len(keywords) == 0:
  378. raise InputError("Invalid field value %s" % v)
  379. try:
  380. return keywords[v.lower()]
  381. except KeyError:
  382. raise InputError("Value '%s' is not valid. Known keywords: %s" % (v, ", ".join(keywords)))
  383. def main():
  384. global quiet
  385. global md5sum
  386. global offset_part_table
  387. global secure
  388. parser = argparse.ArgumentParser(description='ESP32 partition table utility')
  389. parser.add_argument('--flash-size', help='Optional flash size limit, checks partition table fits in flash',
  390. nargs='?', choices=['1MB', '2MB', '4MB', '8MB', '16MB'])
  391. parser.add_argument('--disable-md5sum', help='Disable md5 checksum for the partition table', default=False, action='store_true')
  392. parser.add_argument('--no-verify', help="Don't verify partition table fields", action='store_true')
  393. parser.add_argument('--verify', '-v', help="Verify partition table fields (deprecated, this behaviour is "
  394. "enabled by default and this flag does nothing.", action='store_true')
  395. parser.add_argument('--quiet', '-q', help="Don't print non-critical status messages to stderr", action='store_true')
  396. parser.add_argument('--offset', '-o', help='Set offset partition table', default='0x8000')
  397. parser.add_argument('--secure', help="Require app partitions to be suitable for secure boot", action='store_true')
  398. parser.add_argument('input', help='Path to CSV or binary file to parse.', type=argparse.FileType('rb'))
  399. parser.add_argument('output', help='Path to output converted binary or CSV file. Will use stdout if omitted.',
  400. nargs='?', default='-')
  401. args = parser.parse_args()
  402. quiet = args.quiet
  403. md5sum = not args.disable_md5sum
  404. secure = args.secure
  405. offset_part_table = int(args.offset, 0)
  406. input = args.input.read()
  407. input_is_binary = input[0:2] == PartitionDefinition.MAGIC_BYTES
  408. if input_is_binary:
  409. status("Parsing binary partition input...")
  410. table = PartitionTable.from_binary(input)
  411. else:
  412. input = input.decode()
  413. status("Parsing CSV input...")
  414. table = PartitionTable.from_csv(input)
  415. if not args.no_verify:
  416. status("Verifying table...")
  417. table.verify()
  418. if args.flash_size:
  419. size_mb = int(args.flash_size.replace("MB", ""))
  420. size = size_mb * 1024 * 1024 # flash memory uses honest megabytes!
  421. table_size = table.flash_size()
  422. if size < table_size:
  423. raise InputError("Partitions defined in '%s' occupy %.1fMB of flash (%d bytes) which does not fit in configured "
  424. "flash size %dMB. Change the flash size in menuconfig under the 'Serial Flasher Config' menu." %
  425. (args.input.name, table_size / 1024.0 / 1024.0, table_size, size_mb))
  426. # Make sure that the output directory is created
  427. output_dir = os.path.abspath(os.path.dirname(args.output))
  428. if not os.path.exists(output_dir):
  429. try:
  430. os.makedirs(output_dir)
  431. except OSError as exc:
  432. if exc.errno != errno.EEXIST:
  433. raise
  434. if input_is_binary:
  435. output = table.to_csv()
  436. with sys.stdout if args.output == '-' else open(args.output, 'w') as f:
  437. f.write(output)
  438. else:
  439. output = table.to_binary()
  440. try:
  441. stdout_binary = sys.stdout.buffer # Python 3
  442. except AttributeError:
  443. stdout_binary = sys.stdout
  444. with stdout_binary if args.output == '-' else open(args.output, 'wb') as f:
  445. f.write(output)
  446. class InputError(RuntimeError):
  447. def __init__(self, e):
  448. super(InputError, self).__init__(e)
  449. class ValidationError(InputError):
  450. def __init__(self, partition, message):
  451. super(ValidationError, self).__init__(
  452. "Partition %s invalid: %s" % (partition.name, message))
  453. if __name__ == '__main__':
  454. try:
  455. main()
  456. except InputError as e:
  457. print(e, file=sys.stderr)
  458. sys.exit(2)