spiffsgen.py 20 KB

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