spiffsgen.py 24 KB

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