spiffsgen.py 20 KB

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