spiffsgen.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. #!/usr/bin/env python
  2. #
  3. # spiffsgen is a tool used to generate a spiffs image from a directory
  4. #
  5. # Copyright 2019 Espressif Systems (Shanghai) PTE LTD
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http:#www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. from __future__ import division, print_function
  19. import argparse
  20. import io
  21. import math
  22. import os
  23. import struct
  24. try:
  25. import typing
  26. TSP = typing.TypeVar('TSP', bound='SpiffsObjPageWithIdx')
  27. ObjIdsItem = typing.Tuple[int, typing.Type[TSP]]
  28. except ImportError:
  29. pass
  30. SPIFFS_PH_FLAG_USED_FINAL_INDEX = 0xF8
  31. SPIFFS_PH_FLAG_USED_FINAL = 0xFC
  32. SPIFFS_PH_FLAG_LEN = 1
  33. SPIFFS_PH_IX_SIZE_LEN = 4
  34. SPIFFS_PH_IX_OBJ_TYPE_LEN = 1
  35. SPIFFS_TYPE_FILE = 1
  36. # Based on typedefs under spiffs_config.h
  37. SPIFFS_OBJ_ID_LEN = 2 # spiffs_obj_id
  38. SPIFFS_SPAN_IX_LEN = 2 # spiffs_span_ix
  39. SPIFFS_PAGE_IX_LEN = 2 # spiffs_page_ix
  40. SPIFFS_BLOCK_IX_LEN = 2 # spiffs_block_ix
  41. class SpiffsBuildConfig(object):
  42. def __init__(self,
  43. page_size, # type: int
  44. page_ix_len, # type: int
  45. block_size, # type: int
  46. block_ix_len, # type: int
  47. meta_len, # type: int
  48. obj_name_len, # type: int
  49. obj_id_len, # type: int
  50. span_ix_len, # type: int
  51. packed, # type: bool
  52. aligned, # type: bool
  53. endianness, # type: str
  54. use_magic, # type: bool
  55. use_magic_len, # type: bool
  56. aligned_obj_ix_tables # type: bool
  57. ):
  58. if block_size % page_size != 0:
  59. raise RuntimeError('block size should be a multiple of page size')
  60. self.page_size = page_size
  61. self.block_size = block_size
  62. self.obj_id_len = obj_id_len
  63. self.span_ix_len = span_ix_len
  64. self.packed = packed
  65. self.aligned = aligned
  66. self.obj_name_len = obj_name_len
  67. self.meta_len = meta_len
  68. self.page_ix_len = page_ix_len
  69. self.block_ix_len = block_ix_len
  70. self.endianness = endianness
  71. self.use_magic = use_magic
  72. self.use_magic_len = use_magic_len
  73. self.aligned_obj_ix_tables = aligned_obj_ix_tables
  74. self.PAGES_PER_BLOCK = self.block_size // self.page_size
  75. self.OBJ_LU_PAGES_PER_BLOCK = int(math.ceil(self.block_size / self.page_size * self.obj_id_len / self.page_size))
  76. self.OBJ_USABLE_PAGES_PER_BLOCK = self.PAGES_PER_BLOCK - self.OBJ_LU_PAGES_PER_BLOCK
  77. self.OBJ_LU_PAGES_OBJ_IDS_LIM = self.page_size // self.obj_id_len
  78. self.OBJ_DATA_PAGE_HEADER_LEN = self.obj_id_len + self.span_ix_len + SPIFFS_PH_FLAG_LEN
  79. pad = 4 - (4 if self.OBJ_DATA_PAGE_HEADER_LEN % 4 == 0 else self.OBJ_DATA_PAGE_HEADER_LEN % 4)
  80. self.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED = self.OBJ_DATA_PAGE_HEADER_LEN + pad
  81. self.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD = pad
  82. self.OBJ_DATA_PAGE_CONTENT_LEN = self.page_size - self.OBJ_DATA_PAGE_HEADER_LEN
  83. self.OBJ_INDEX_PAGES_HEADER_LEN = (self.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED + SPIFFS_PH_IX_SIZE_LEN +
  84. SPIFFS_PH_IX_OBJ_TYPE_LEN + self.obj_name_len + self.meta_len)
  85. if aligned_obj_ix_tables:
  86. self.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED = (self.OBJ_INDEX_PAGES_HEADER_LEN + SPIFFS_PAGE_IX_LEN - 1) & ~(SPIFFS_PAGE_IX_LEN - 1)
  87. self.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD = self.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED - self.OBJ_INDEX_PAGES_HEADER_LEN
  88. else:
  89. self.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED = self.OBJ_INDEX_PAGES_HEADER_LEN
  90. self.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD = 0
  91. self.OBJ_INDEX_PAGES_OBJ_IDS_HEAD_LIM = (self.page_size - self.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED) // self.block_ix_len
  92. self.OBJ_INDEX_PAGES_OBJ_IDS_LIM = (self.page_size - self.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED) // self.block_ix_len
  93. class SpiffsFullError(RuntimeError):
  94. pass
  95. class SpiffsPage(object):
  96. _endianness_dict = {
  97. 'little': '<',
  98. 'big': '>'
  99. }
  100. _len_dict = {
  101. 1: 'B',
  102. 2: 'H',
  103. 4: 'I',
  104. 8: 'Q'
  105. }
  106. def __init__(self, bix, build_config): # type: (int, SpiffsBuildConfig) -> None
  107. self.build_config = build_config
  108. self.bix = bix
  109. def to_binary(self): # type: () -> bytes
  110. raise NotImplementedError()
  111. class SpiffsObjPageWithIdx(SpiffsPage):
  112. def __init__(self, obj_id, build_config): # type: (int, SpiffsBuildConfig) -> None
  113. super(SpiffsObjPageWithIdx, self).__init__(0, build_config)
  114. self.obj_id = obj_id
  115. def to_binary(self): # type: () -> bytes
  116. raise NotImplementedError()
  117. class SpiffsObjLuPage(SpiffsPage):
  118. def __init__(self, bix, build_config): # type: (int, SpiffsBuildConfig) -> None
  119. SpiffsPage.__init__(self, bix, build_config)
  120. self.obj_ids_limit = self.build_config.OBJ_LU_PAGES_OBJ_IDS_LIM
  121. self.obj_ids = list() # type: typing.List[ObjIdsItem]
  122. def _calc_magic(self, blocks_lim): # type: (int) -> int
  123. # Calculate the magic value mirroring computation done by the macro SPIFFS_MAGIC defined in
  124. # spiffs_nucleus.h
  125. magic = 0x20140529 ^ self.build_config.page_size
  126. if self.build_config.use_magic_len:
  127. magic = magic ^ (blocks_lim - self.bix)
  128. # narrow the result to build_config.obj_id_len bytes
  129. mask = (2 << (8 * self.build_config.obj_id_len)) - 1
  130. return magic & mask
  131. def register_page(self, page): # type: (TSP) -> None
  132. if not self.obj_ids_limit > 0:
  133. raise SpiffsFullError()
  134. obj_id = (page.obj_id, page.__class__)
  135. self.obj_ids.append(obj_id)
  136. self.obj_ids_limit -= 1
  137. def to_binary(self): # type: () -> bytes
  138. img = b''
  139. for (obj_id, page_type) in self.obj_ids:
  140. if page_type == SpiffsObjIndexPage:
  141. obj_id ^= (1 << ((self.build_config.obj_id_len * 8) - 1))
  142. img += struct.pack(SpiffsPage._endianness_dict[self.build_config.endianness] +
  143. SpiffsPage._len_dict[self.build_config.obj_id_len], obj_id)
  144. assert(len(img) <= self.build_config.page_size)
  145. img += b'\xFF' * (self.build_config.page_size - len(img))
  146. return img
  147. def magicfy(self, blocks_lim): # type: (int) -> None
  148. # Only use magic value if no valid obj id has been written to the spot, which is the
  149. # spot taken up by the last obj id on last lookup page. The parent is responsible
  150. # for determining which is the last lookup page and calling this function.
  151. remaining = self.obj_ids_limit
  152. empty_obj_id_dict = {
  153. 1: 0xFF,
  154. 2: 0xFFFF,
  155. 4: 0xFFFFFFFF,
  156. 8: 0xFFFFFFFFFFFFFFFF
  157. }
  158. if remaining >= 2:
  159. for i in range(remaining):
  160. if i == remaining - 2:
  161. self.obj_ids.append((self._calc_magic(blocks_lim), SpiffsObjDataPage))
  162. break
  163. else:
  164. self.obj_ids.append((empty_obj_id_dict[self.build_config.obj_id_len], SpiffsObjDataPage))
  165. self.obj_ids_limit -= 1
  166. class SpiffsObjIndexPage(SpiffsObjPageWithIdx):
  167. def __init__(self, obj_id, span_ix, size, name, build_config
  168. ): # type: (int, int, int, str, SpiffsBuildConfig) -> None
  169. super(SpiffsObjIndexPage, self).__init__(obj_id, build_config)
  170. self.span_ix = span_ix
  171. self.name = name
  172. self.size = size
  173. if self.span_ix == 0:
  174. self.pages_lim = self.build_config.OBJ_INDEX_PAGES_OBJ_IDS_HEAD_LIM
  175. else:
  176. self.pages_lim = self.build_config.OBJ_INDEX_PAGES_OBJ_IDS_LIM
  177. self.pages = list() # type: typing.List[int]
  178. def register_page(self, page): # type: (SpiffsObjDataPage) -> None
  179. if not self.pages_lim > 0:
  180. raise SpiffsFullError
  181. self.pages.append(page.offset)
  182. self.pages_lim -= 1
  183. def to_binary(self): # type: () -> bytes
  184. obj_id = self.obj_id ^ (1 << ((self.build_config.obj_id_len * 8) - 1))
  185. img = struct.pack(SpiffsPage._endianness_dict[self.build_config.endianness] +
  186. SpiffsPage._len_dict[self.build_config.obj_id_len] +
  187. SpiffsPage._len_dict[self.build_config.span_ix_len] +
  188. SpiffsPage._len_dict[SPIFFS_PH_FLAG_LEN],
  189. obj_id,
  190. self.span_ix,
  191. SPIFFS_PH_FLAG_USED_FINAL_INDEX)
  192. # Add padding before the object index page specific information
  193. img += b'\xFF' * self.build_config.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD
  194. # If this is the first object index page for the object, add filname, type
  195. # and size information
  196. if self.span_ix == 0:
  197. img += struct.pack(SpiffsPage._endianness_dict[self.build_config.endianness] +
  198. SpiffsPage._len_dict[SPIFFS_PH_IX_SIZE_LEN] +
  199. SpiffsPage._len_dict[SPIFFS_PH_FLAG_LEN],
  200. self.size,
  201. SPIFFS_TYPE_FILE)
  202. img += self.name.encode() + (b'\x00' * (
  203. (self.build_config.obj_name_len - len(self.name))
  204. + self.build_config.meta_len
  205. + self.build_config.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD))
  206. # Finally, add the page index of daa pages
  207. for page in self.pages:
  208. page = page >> int(math.log(self.build_config.page_size, 2))
  209. img += struct.pack(SpiffsPage._endianness_dict[self.build_config.endianness] +
  210. SpiffsPage._len_dict[self.build_config.page_ix_len], page)
  211. assert(len(img) <= self.build_config.page_size)
  212. img += b'\xFF' * (self.build_config.page_size - len(img))
  213. return img
  214. class SpiffsObjDataPage(SpiffsObjPageWithIdx):
  215. def __init__(self, offset, obj_id, span_ix, contents, build_config
  216. ): # type: (int, int, int, bytes, SpiffsBuildConfig) -> None
  217. super(SpiffsObjDataPage, self).__init__(obj_id, build_config)
  218. self.span_ix = span_ix
  219. self.contents = contents
  220. self.offset = offset
  221. def to_binary(self): # type: () -> bytes
  222. img = struct.pack(SpiffsPage._endianness_dict[self.build_config.endianness] +
  223. SpiffsPage._len_dict[self.build_config.obj_id_len] +
  224. SpiffsPage._len_dict[self.build_config.span_ix_len] +
  225. SpiffsPage._len_dict[SPIFFS_PH_FLAG_LEN],
  226. self.obj_id,
  227. self.span_ix,
  228. SPIFFS_PH_FLAG_USED_FINAL)
  229. img += self.contents
  230. assert(len(img) <= self.build_config.page_size)
  231. img += b'\xFF' * (self.build_config.page_size - len(img))
  232. return img
  233. class SpiffsBlock(object):
  234. def _reset(self): # type: () -> None
  235. self.cur_obj_index_span_ix = 0
  236. self.cur_obj_data_span_ix = 0
  237. self.cur_obj_id = 0
  238. self.cur_obj_idx_page = None # type: typing.Optional[SpiffsObjIndexPage]
  239. def __init__(self, bix, build_config): # type: (int, SpiffsBuildConfig) -> None
  240. self.build_config = build_config
  241. self.offset = bix * self.build_config.block_size
  242. self.remaining_pages = self.build_config.OBJ_USABLE_PAGES_PER_BLOCK
  243. self.pages = list() # type: typing.List[SpiffsPage]
  244. self.bix = bix
  245. lu_pages = list()
  246. for i in range(self.build_config.OBJ_LU_PAGES_PER_BLOCK):
  247. page = SpiffsObjLuPage(self.bix, self.build_config)
  248. lu_pages.append(page)
  249. self.pages.extend(lu_pages)
  250. self.lu_page_iter = iter(lu_pages)
  251. self.lu_page = next(self.lu_page_iter)
  252. self._reset()
  253. def _register_page(self, page): # type: (TSP) -> None
  254. if isinstance(page, SpiffsObjDataPage):
  255. assert self.cur_obj_idx_page is not None
  256. self.cur_obj_idx_page.register_page(page) # can raise SpiffsFullError
  257. try:
  258. self.lu_page.register_page(page)
  259. except SpiffsFullError:
  260. self.lu_page = next(self.lu_page_iter)
  261. try:
  262. self.lu_page.register_page(page)
  263. except AttributeError: # no next lookup page
  264. # Since the amount of lookup pages is pre-computed at every block instance,
  265. # this should never occur
  266. raise RuntimeError('invalid attempt to add page to a block when there is no more space in lookup')
  267. self.pages.append(page)
  268. def begin_obj(self, obj_id, size, name, obj_index_span_ix=0, obj_data_span_ix=0
  269. ): # type: (int, int, str, int, int) -> None
  270. if not self.remaining_pages > 0:
  271. raise SpiffsFullError()
  272. self._reset()
  273. self.cur_obj_id = obj_id
  274. self.cur_obj_index_span_ix = obj_index_span_ix
  275. self.cur_obj_data_span_ix = obj_data_span_ix
  276. page = SpiffsObjIndexPage(obj_id, self.cur_obj_index_span_ix, size, name, self.build_config)
  277. self._register_page(page)
  278. self.cur_obj_idx_page = page
  279. self.remaining_pages -= 1
  280. self.cur_obj_index_span_ix += 1
  281. def update_obj(self, contents): # type: (bytes) -> None
  282. if not self.remaining_pages > 0:
  283. raise SpiffsFullError()
  284. page = SpiffsObjDataPage(self.offset + (len(self.pages) * self.build_config.page_size),
  285. self.cur_obj_id, self.cur_obj_data_span_ix, contents, self.build_config)
  286. self._register_page(page)
  287. self.cur_obj_data_span_ix += 1
  288. self.remaining_pages -= 1
  289. def end_obj(self): # type: () -> None
  290. self._reset()
  291. def is_full(self): # type: () -> bool
  292. return self.remaining_pages <= 0
  293. def to_binary(self, blocks_lim): # type: (int) -> bytes
  294. img = b''
  295. if self.build_config.use_magic:
  296. for (idx, page) in enumerate(self.pages):
  297. if idx == self.build_config.OBJ_LU_PAGES_PER_BLOCK - 1:
  298. assert isinstance(page, SpiffsObjLuPage)
  299. page.magicfy(blocks_lim)
  300. img += page.to_binary()
  301. else:
  302. for page in self.pages:
  303. img += page.to_binary()
  304. assert(len(img) <= self.build_config.block_size)
  305. img += b'\xFF' * (self.build_config.block_size - len(img))
  306. return img
  307. class SpiffsFS(object):
  308. def __init__(self, img_size, build_config): # type: (int, SpiffsBuildConfig) -> None
  309. if img_size % build_config.block_size != 0:
  310. raise RuntimeError('image size should be a multiple of block size')
  311. self.img_size = img_size
  312. self.build_config = build_config
  313. self.blocks = list() # type: typing.List[SpiffsBlock]
  314. self.blocks_lim = self.img_size // self.build_config.block_size
  315. self.remaining_blocks = self.blocks_lim
  316. self.cur_obj_id = 1 # starting object id
  317. def _create_block(self): # type: () -> SpiffsBlock
  318. if self.is_full():
  319. raise SpiffsFullError('the image size has been exceeded')
  320. block = SpiffsBlock(len(self.blocks), self.build_config)
  321. self.blocks.append(block)
  322. self.remaining_blocks -= 1
  323. return block
  324. def is_full(self): # type: () -> bool
  325. return self.remaining_blocks <= 0
  326. def create_file(self, img_path, file_path): # type: (str, str) -> None
  327. if len(img_path) > self.build_config.obj_name_len:
  328. raise RuntimeError("object name '%s' too long" % img_path)
  329. name = img_path
  330. with open(file_path, 'rb') as obj:
  331. contents = obj.read()
  332. stream = io.BytesIO(contents)
  333. try:
  334. block = self.blocks[-1]
  335. block.begin_obj(self.cur_obj_id, len(contents), name)
  336. except (IndexError, SpiffsFullError):
  337. block = self._create_block()
  338. block.begin_obj(self.cur_obj_id, len(contents), name)
  339. contents_chunk = stream.read(self.build_config.OBJ_DATA_PAGE_CONTENT_LEN)
  340. while contents_chunk:
  341. try:
  342. block = self.blocks[-1]
  343. try:
  344. # This can fail because either (1) all the pages in block have been
  345. # used or (2) object index has been exhausted.
  346. block.update_obj(contents_chunk)
  347. except SpiffsFullError:
  348. # If its (1), use the outer exception handler
  349. if block.is_full():
  350. raise SpiffsFullError
  351. # If its (2), write another object index page
  352. block.begin_obj(self.cur_obj_id, len(contents), name,
  353. obj_index_span_ix=block.cur_obj_index_span_ix,
  354. obj_data_span_ix=block.cur_obj_data_span_ix)
  355. continue
  356. except (IndexError, SpiffsFullError):
  357. # All pages in the block have been exhausted. Create a new block, copying
  358. # the previous state of the block to a new one for the continuation of the
  359. # current object
  360. prev_block = block
  361. block = self._create_block()
  362. block.cur_obj_id = prev_block.cur_obj_id
  363. block.cur_obj_idx_page = prev_block.cur_obj_idx_page
  364. block.cur_obj_data_span_ix = prev_block.cur_obj_data_span_ix
  365. block.cur_obj_index_span_ix = prev_block.cur_obj_index_span_ix
  366. continue
  367. contents_chunk = stream.read(self.build_config.OBJ_DATA_PAGE_CONTENT_LEN)
  368. block.end_obj()
  369. self.cur_obj_id += 1
  370. def to_binary(self): # type: () -> bytes
  371. img = b''
  372. all_blocks = []
  373. for block in self.blocks:
  374. all_blocks.append(block.to_binary(self.blocks_lim))
  375. bix = len(self.blocks)
  376. if self.build_config.use_magic:
  377. # Create empty blocks with magic numbers
  378. while self.remaining_blocks > 0:
  379. block = SpiffsBlock(bix, self.build_config)
  380. all_blocks.append(block.to_binary(self.blocks_lim))
  381. self.remaining_blocks -= 1
  382. bix += 1
  383. else:
  384. # Just fill remaining spaces FF's
  385. all_blocks.append(b'\xFF' * (self.img_size - len(all_blocks) * self.build_config.block_size))
  386. img += b''.join([blk for blk in all_blocks])
  387. return img
  388. class CustomHelpFormatter(argparse.HelpFormatter):
  389. """
  390. Similar to argparse.ArgumentDefaultsHelpFormatter, except it
  391. doesn't add the default value if "(default:" is already present.
  392. This helps in the case of options with action="store_false", like
  393. --no-magic or --no-magic-len.
  394. """
  395. def _get_help_string(self, action): # type: (argparse.Action) -> str
  396. if action.help is None:
  397. return ''
  398. if '%(default)' not in action.help and '(default:' not in action.help:
  399. if action.default is not argparse.SUPPRESS:
  400. defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
  401. if action.option_strings or action.nargs in defaulting_nargs:
  402. return action.help + ' (default: %(default)s)'
  403. return action.help
  404. def main(): # type: () -> None
  405. parser = argparse.ArgumentParser(description='SPIFFS Image Generator',
  406. formatter_class=CustomHelpFormatter)
  407. parser.add_argument('image_size',
  408. help='Size of the created image')
  409. parser.add_argument('base_dir',
  410. help='Path to directory from which the image will be created')
  411. parser.add_argument('output_file',
  412. help='Created image output file path')
  413. parser.add_argument('--page-size',
  414. help='Logical page size. Set to value same as CONFIG_SPIFFS_PAGE_SIZE.',
  415. type=int,
  416. default=256)
  417. parser.add_argument('--block-size',
  418. help="Logical block size. Set to the same value as the flash chip's sector size (g_rom_flashchip.sector_size).",
  419. type=int,
  420. default=4096)
  421. parser.add_argument('--obj-name-len',
  422. help='File full path maximum length. Set to value same as CONFIG_SPIFFS_OBJ_NAME_LEN.',
  423. type=int,
  424. default=32)
  425. parser.add_argument('--meta-len',
  426. help='File metadata length. Set to value same as CONFIG_SPIFFS_META_LENGTH.',
  427. type=int,
  428. default=4)
  429. parser.add_argument('--use-magic',
  430. dest='use_magic',
  431. help='Use magic number to create an identifiable SPIFFS image. Specify if CONFIG_SPIFFS_USE_MAGIC.',
  432. action='store_true')
  433. parser.add_argument('--no-magic',
  434. dest='use_magic',
  435. help='Inverse of --use-magic (default: --use-magic is enabled)',
  436. action='store_false')
  437. parser.add_argument('--use-magic-len',
  438. dest='use_magic_len',
  439. help='Use position in memory to create different magic numbers for each block. Specify if CONFIG_SPIFFS_USE_MAGIC_LENGTH.',
  440. action='store_true')
  441. parser.add_argument('--no-magic-len',
  442. dest='use_magic_len',
  443. help='Inverse of --use-magic-len (default: --use-magic-len is enabled)',
  444. action='store_false')
  445. parser.add_argument('--follow-symlinks',
  446. help='Take into account symbolic links during partition image creation.',
  447. action='store_true')
  448. parser.add_argument('--big-endian',
  449. help='Specify if the target architecture is big-endian. If not specified, little-endian is assumed.',
  450. action='store_true')
  451. parser.add_argument('--aligned-obj-ix-tables',
  452. action='store_true',
  453. help='Use aligned object index tables. Specify if SPIFFS_ALIGNED_OBJECT_INDEX_TABLES is set.')
  454. parser.set_defaults(use_magic=True, use_magic_len=True)
  455. args = parser.parse_args()
  456. if not os.path.exists(args.base_dir):
  457. raise RuntimeError('given base directory %s does not exist' % args.base_dir)
  458. with open(args.output_file, 'wb') as image_file:
  459. image_size = int(args.image_size, 0)
  460. spiffs_build_default = SpiffsBuildConfig(args.page_size, SPIFFS_PAGE_IX_LEN,
  461. args.block_size, SPIFFS_BLOCK_IX_LEN, args.meta_len,
  462. args.obj_name_len, SPIFFS_OBJ_ID_LEN, SPIFFS_SPAN_IX_LEN,
  463. True, True, 'big' if args.big_endian else 'little',
  464. args.use_magic, args.use_magic_len, args.aligned_obj_ix_tables)
  465. spiffs = SpiffsFS(image_size, spiffs_build_default)
  466. for root, dirs, files in os.walk(args.base_dir, followlinks=args.follow_symlinks):
  467. for f in files:
  468. full_path = os.path.join(root, f)
  469. spiffs.create_file('/' + os.path.relpath(full_path, args.base_dir).replace('\\', '/'), full_path)
  470. image = spiffs.to_binary()
  471. image_file.write(image)
  472. if __name__ == '__main__':
  473. main()