gen_esp32part.py 20 KB

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