gen_esp32part.py 21 KB

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