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