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 division, print_function, unicode_literals
  24. import argparse
  25. import binascii
  26. import errno
  27. import hashlib
  28. import os
  29. import re
  30. import struct
  31. import sys
  32. MAX_PARTITION_LENGTH = 0xC00 # 3K for partition data (96 entries) leaves 1K in a 4K sector for signature
  33. MD5_PARTITION_BEGIN = b'\xEB\xEB' + b'\xFF' * 14 # The first 2 bytes are like magic numbers for MD5 sum
  34. PARTITION_TABLE_SIZE = 0x1000 # Size of partition table
  35. MIN_PARTITION_SUBTYPE_APP_OTA = 0x10
  36. NUM_PARTITION_SUBTYPE_APP_OTA = 16
  37. __version__ = '1.2'
  38. APP_TYPE = 0x00
  39. DATA_TYPE = 0x01
  40. TYPES = {
  41. 'app': APP_TYPE,
  42. 'data': DATA_TYPE,
  43. }
  44. # Keep this map in sync with esp_partition_subtype_t enum in esp_partition.h
  45. SUBTYPES = {
  46. APP_TYPE: {
  47. 'factory': 0x00,
  48. 'test': 0x20,
  49. },
  50. DATA_TYPE: {
  51. 'ota': 0x00,
  52. 'phy': 0x01,
  53. 'nvs': 0x02,
  54. 'coredump': 0x03,
  55. 'nvs_keys': 0x04,
  56. 'efuse': 0x05,
  57. 'undefined': 0x06,
  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 err:
  95. raise InputError('Error at line %d: %s' % (line_no + 1, err))
  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. yield p
  149. return
  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. # check that otadata should be unique
  178. otadata_duplicates = [p for p in self if p.type == TYPES['data'] and p.subtype == SUBTYPES[DATA_TYPE]['ota']]
  179. if len(otadata_duplicates) > 1:
  180. for p in otadata_duplicates:
  181. print(p.name, p.type, p.subtype)
  182. raise InputError('Found multiple otadata partitions. Only one partition can be defined with type="data"(1) and subtype="ota"(0).')
  183. if len(otadata_duplicates) == 1 and otadata_duplicates[0].size != 0x2000:
  184. p = otadata_duplicates[0]
  185. print(p.name, p.type, p.subtype, p.offset, p.size)
  186. raise InputError('otadata partition must have size = 0x2000')
  187. def flash_size(self):
  188. """ Return the size that partitions will occupy in flash
  189. (ie the offset the last partition ends at)
  190. """
  191. try:
  192. last = sorted(self, reverse=True)[0]
  193. except IndexError:
  194. return 0 # empty table!
  195. return last.offset + last.size
  196. @classmethod
  197. def from_binary(cls, b):
  198. md5 = hashlib.md5()
  199. result = cls()
  200. for o in range(0,len(b),32):
  201. data = b[o:o + 32]
  202. if len(data) != 32:
  203. raise InputError('Partition table length must be a multiple of 32 bytes')
  204. if data == b'\xFF' * 32:
  205. return result # got end marker
  206. if md5sum and data[:2] == MD5_PARTITION_BEGIN[:2]: # check only the magic number part
  207. if data[16:] == md5.digest():
  208. continue # the next iteration will check for the end marker
  209. else:
  210. raise InputError("MD5 checksums don't match! (computed: 0x%s, parsed: 0x%s)" % (md5.hexdigest(), binascii.hexlify(data[16:])))
  211. else:
  212. md5.update(data)
  213. result.append(PartitionDefinition.from_binary(data))
  214. raise InputError('Partition table is missing an end-of-table marker')
  215. def to_binary(self):
  216. result = b''.join(e.to_binary() for e in self)
  217. if md5sum:
  218. result += MD5_PARTITION_BEGIN + hashlib.md5(result).digest()
  219. if len(result) >= MAX_PARTITION_LENGTH:
  220. raise InputError('Binary partition table length (%d) longer than max' % len(result))
  221. result += b'\xFF' * (MAX_PARTITION_LENGTH - len(result)) # pad the sector, for signing
  222. return result
  223. def to_csv(self, simple_formatting=False):
  224. rows = ['# ESP-IDF Partition Table',
  225. '# Name, Type, SubType, Offset, Size, Flags']
  226. rows += [x.to_csv(simple_formatting) for x in self]
  227. return '\n'.join(rows) + '\n'
  228. class PartitionDefinition(object):
  229. MAGIC_BYTES = b'\xAA\x50'
  230. ALIGNMENT = {
  231. APP_TYPE: 0x10000,
  232. DATA_TYPE: 0x04,
  233. }
  234. # dictionary maps flag name (as used in CSV flags list, property name)
  235. # to bit set in flags words in binary format
  236. FLAGS = {
  237. 'encrypted': 0
  238. }
  239. # add subtypes for the 16 OTA slot values ("ota_XX, etc.")
  240. for ota_slot in range(NUM_PARTITION_SUBTYPE_APP_OTA):
  241. SUBTYPES[TYPES['app']]['ota_%d' % ota_slot] = MIN_PARTITION_SUBTYPE_APP_OTA + ota_slot
  242. def __init__(self):
  243. self.name = ''
  244. self.type = None
  245. self.subtype = None
  246. self.offset = None
  247. self.size = None
  248. self.encrypted = False
  249. @classmethod
  250. def from_csv(cls, line, line_no):
  251. """ Parse a line from the CSV """
  252. line_w_defaults = line + ',,,,' # lazy way to support default fields
  253. fields = [f.strip() for f in line_w_defaults.split(',')]
  254. res = PartitionDefinition()
  255. res.line_no = line_no
  256. res.name = fields[0]
  257. res.type = res.parse_type(fields[1])
  258. res.subtype = res.parse_subtype(fields[2])
  259. res.offset = res.parse_address(fields[3])
  260. res.size = res.parse_address(fields[4])
  261. if res.size is None:
  262. raise InputError("Size field can't be empty")
  263. flags = fields[5].split(':')
  264. for flag in flags:
  265. if flag in cls.FLAGS:
  266. setattr(res, flag, True)
  267. elif len(flag) > 0:
  268. raise InputError("CSV flag column contains unknown flag '%s'" % (flag))
  269. return res
  270. def __eq__(self, other):
  271. return self.name == other.name and self.type == other.type \
  272. and self.subtype == other.subtype and self.offset == other.offset \
  273. and self.size == other.size
  274. def __repr__(self):
  275. def maybe_hex(x):
  276. return '0x%x' % x if x is not None else 'None'
  277. return "PartitionDefinition('%s', 0x%x, 0x%x, %s, %s)" % (self.name, self.type, self.subtype or 0,
  278. maybe_hex(self.offset), maybe_hex(self.size))
  279. def __str__(self):
  280. return "Part '%s' %d/%d @ 0x%x size 0x%x" % (self.name, self.type, self.subtype, self.offset or -1, self.size or -1)
  281. def __cmp__(self, other):
  282. return self.offset - other.offset
  283. def __lt__(self, other):
  284. return self.offset < other.offset
  285. def __gt__(self, other):
  286. return self.offset > other.offset
  287. def __le__(self, other):
  288. return self.offset <= other.offset
  289. def __ge__(self, other):
  290. return self.offset >= other.offset
  291. def parse_type(self, strval):
  292. if strval == '':
  293. raise InputError("Field 'type' can't be left empty.")
  294. return parse_int(strval, TYPES)
  295. def parse_subtype(self, strval):
  296. if strval == '':
  297. if self.type == TYPES['app']:
  298. raise InputError('App partition cannot have an empty subtype')
  299. return SUBTYPES[DATA_TYPE]['undefined']
  300. return parse_int(strval, SUBTYPES.get(self.type, {}))
  301. def parse_address(self, strval):
  302. if strval == '':
  303. return None # PartitionTable will fill in default
  304. return parse_int(strval)
  305. def verify(self):
  306. if self.type is None:
  307. raise ValidationError(self, 'Type field is not set')
  308. if self.subtype is None:
  309. raise ValidationError(self, 'Subtype field is not set')
  310. if self.offset is None:
  311. raise ValidationError(self, 'Offset field is not set')
  312. align = self.ALIGNMENT.get(self.type, 4)
  313. if self.offset % align:
  314. raise ValidationError(self, 'Offset 0x%x is not aligned to 0x%x' % (self.offset, align))
  315. if self.size % align and secure:
  316. raise ValidationError(self, 'Size 0x%x is not aligned to 0x%x' % (self.size, align))
  317. if self.size is None:
  318. raise ValidationError(self, 'Size field is not set')
  319. if self.name in TYPES and TYPES.get(self.name, '') != self.type:
  320. critical("WARNING: Partition has name '%s' which is a partition type, but does not match this partition's "
  321. 'type (0x%x). Mistake in partition table?' % (self.name, self.type))
  322. all_subtype_names = []
  323. for names in (t.keys() for t in SUBTYPES.values()):
  324. all_subtype_names += names
  325. if self.name in all_subtype_names and SUBTYPES.get(self.type, {}).get(self.name, '') != self.subtype:
  326. critical("WARNING: Partition has name '%s' which is a partition subtype, but this partition has "
  327. 'non-matching type 0x%x and subtype 0x%x. Mistake in partition table?' % (self.name, self.type, self.subtype))
  328. STRUCT_FORMAT = b'<2sBBLL16sL'
  329. @classmethod
  330. def from_binary(cls, b):
  331. if len(b) != 32:
  332. raise InputError('Partition definition length must be exactly 32 bytes. Got %d bytes.' % len(b))
  333. res = cls()
  334. (magic, res.type, res.subtype, res.offset,
  335. res.size, res.name, flags) = struct.unpack(cls.STRUCT_FORMAT, b)
  336. if b'\x00' in res.name: # strip null byte padding from name string
  337. res.name = res.name[:res.name.index(b'\x00')]
  338. res.name = res.name.decode()
  339. if magic != cls.MAGIC_BYTES:
  340. raise InputError('Invalid magic bytes (%r) for partition definition' % magic)
  341. for flag,bit in cls.FLAGS.items():
  342. if flags & (1 << bit):
  343. setattr(res, flag, True)
  344. flags &= ~(1 << bit)
  345. if flags != 0:
  346. critical('WARNING: Partition definition had unknown flag(s) 0x%08x. Newer binary format?' % flags)
  347. return res
  348. def get_flags_list(self):
  349. return [flag for flag in self.FLAGS.keys() if getattr(self, flag)]
  350. def to_binary(self):
  351. flags = sum((1 << self.FLAGS[flag]) for flag in self.get_flags_list())
  352. return struct.pack(self.STRUCT_FORMAT,
  353. self.MAGIC_BYTES,
  354. self.type, self.subtype,
  355. self.offset, self.size,
  356. self.name.encode(),
  357. flags)
  358. def to_csv(self, simple_formatting=False):
  359. def addr_format(a, include_sizes):
  360. if not simple_formatting and include_sizes:
  361. for (val, suffix) in [(0x100000, 'M'), (0x400, 'K')]:
  362. if a % val == 0:
  363. return '%d%s' % (a // val, suffix)
  364. return '0x%x' % a
  365. def lookup_keyword(t, keywords):
  366. for k,v in keywords.items():
  367. if simple_formatting is False and t == v:
  368. return k
  369. return '%d' % t
  370. def generate_text_flags():
  371. """ colon-delimited list of flags """
  372. return ':'.join(self.get_flags_list())
  373. return ','.join([self.name,
  374. lookup_keyword(self.type, TYPES),
  375. lookup_keyword(self.subtype, SUBTYPES.get(self.type, {})),
  376. addr_format(self.offset, False),
  377. addr_format(self.size, True),
  378. generate_text_flags()])
  379. def parse_int(v, keywords={}):
  380. """Generic parser for integer fields - int(x,0) with provision for
  381. k/m/K/M suffixes and 'keyword' value lookup.
  382. """
  383. try:
  384. for letter, multiplier in [('k', 1024), ('m', 1024 * 1024)]:
  385. if v.lower().endswith(letter):
  386. return parse_int(v[:-1], keywords) * multiplier
  387. return int(v, 0)
  388. except ValueError:
  389. if len(keywords) == 0:
  390. raise InputError('Invalid field value %s' % v)
  391. try:
  392. return keywords[v.lower()]
  393. except KeyError:
  394. raise InputError("Value '%s' is not valid. Known keywords: %s" % (v, ', '.join(keywords)))
  395. def main():
  396. global quiet
  397. global md5sum
  398. global offset_part_table
  399. global secure
  400. parser = argparse.ArgumentParser(description='ESP32 partition table utility')
  401. parser.add_argument('--flash-size', help='Optional flash size limit, checks partition table fits in flash',
  402. nargs='?', choices=['1MB', '2MB', '4MB', '8MB', '16MB'])
  403. parser.add_argument('--disable-md5sum', help='Disable md5 checksum for the partition table', default=False, action='store_true')
  404. parser.add_argument('--no-verify', help="Don't verify partition table fields", action='store_true')
  405. parser.add_argument('--verify', '-v', help='Verify partition table fields (deprecated, this behaviour is '
  406. 'enabled by default and this flag does nothing.', action='store_true')
  407. parser.add_argument('--quiet', '-q', help="Don't print non-critical status messages to stderr", action='store_true')
  408. parser.add_argument('--offset', '-o', help='Set offset partition table', default='0x8000')
  409. parser.add_argument('--secure', help='Require app partitions to be suitable for secure boot', action='store_true')
  410. parser.add_argument('input', help='Path to CSV or binary file to parse.', type=argparse.FileType('rb'))
  411. parser.add_argument('output', help='Path to output converted binary or CSV file. Will use stdout if omitted.',
  412. nargs='?', default='-')
  413. args = parser.parse_args()
  414. quiet = args.quiet
  415. md5sum = not args.disable_md5sum
  416. secure = args.secure
  417. offset_part_table = int(args.offset, 0)
  418. input = args.input.read()
  419. input_is_binary = input[0:2] == PartitionDefinition.MAGIC_BYTES
  420. if input_is_binary:
  421. status('Parsing binary partition input...')
  422. table = PartitionTable.from_binary(input)
  423. else:
  424. input = input.decode()
  425. status('Parsing CSV input...')
  426. table = PartitionTable.from_csv(input)
  427. if not args.no_verify:
  428. status('Verifying table...')
  429. table.verify()
  430. if args.flash_size:
  431. size_mb = int(args.flash_size.replace('MB', ''))
  432. size = size_mb * 1024 * 1024 # flash memory uses honest megabytes!
  433. table_size = table.flash_size()
  434. if size < table_size:
  435. raise InputError("Partitions defined in '%s' occupy %.1fMB of flash (%d bytes) which does not fit in configured "
  436. "flash size %dMB. Change the flash size in menuconfig under the 'Serial Flasher Config' menu." %
  437. (args.input.name, table_size / 1024.0 / 1024.0, table_size, size_mb))
  438. # Make sure that the output directory is created
  439. output_dir = os.path.abspath(os.path.dirname(args.output))
  440. if not os.path.exists(output_dir):
  441. try:
  442. os.makedirs(output_dir)
  443. except OSError as exc:
  444. if exc.errno != errno.EEXIST:
  445. raise
  446. if input_is_binary:
  447. output = table.to_csv()
  448. with sys.stdout if args.output == '-' else open(args.output, 'w') as f:
  449. f.write(output)
  450. else:
  451. output = table.to_binary()
  452. try:
  453. stdout_binary = sys.stdout.buffer # Python 3
  454. except AttributeError:
  455. stdout_binary = sys.stdout
  456. with stdout_binary if args.output == '-' else open(args.output, 'wb') as f:
  457. f.write(output)
  458. class InputError(RuntimeError):
  459. def __init__(self, e):
  460. super(InputError, self).__init__(e)
  461. class ValidationError(InputError):
  462. def __init__(self, partition, message):
  463. super(ValidationError, self).__init__(
  464. 'Partition %s invalid: %s' % (partition.name, message))
  465. if __name__ == '__main__':
  466. try:
  467. main()
  468. except InputError as e:
  469. print(e, file=sys.stderr)
  470. sys.exit(2)