utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import argparse
  4. import binascii
  5. import os
  6. import re
  7. import uuid
  8. from datetime import datetime
  9. from typing import List, Optional, Tuple
  10. from construct import BitsInteger, BitStruct, Int16ul
  11. # the regex pattern defines symbols that are allowed by long file names but not by short file names
  12. INVALID_SFN_CHARS_PATTERN = re.compile(r'[.+,;=\[\]]')
  13. FATFS_MIN_ALLOC_UNIT: int = 128
  14. FAT12_MAX_CLUSTERS: int = 4085
  15. FAT16_MAX_CLUSTERS: int = 65525
  16. RESERVED_CLUSTERS_COUNT: int = 2
  17. PAD_CHAR: int = 0x20
  18. FAT12: int = 12
  19. FAT16: int = 16
  20. FAT32: int = 32
  21. FULL_BYTE: bytes = b'\xff'
  22. EMPTY_BYTE: bytes = b'\x00'
  23. # redundant
  24. BYTES_PER_DIRECTORY_ENTRY: int = 32
  25. UINT32_MAX: int = (1 << 32) - 1
  26. MAX_NAME_SIZE: int = 8
  27. MAX_EXT_SIZE: int = 3
  28. DATETIME = Tuple[int, int, int]
  29. FATFS_INCEPTION_YEAR: int = 1980
  30. FATFS_INCEPTION: datetime = datetime(FATFS_INCEPTION_YEAR, 1, 1, 0, 0, 0, 0)
  31. FATFS_MAX_HOURS = 24
  32. FATFS_MAX_MINUTES = 60
  33. FATFS_MAX_SECONDS = 60
  34. FATFS_MAX_DAYS = 31
  35. FATFS_MAX_MONTHS = 12
  36. FATFS_MAX_YEARS = 127
  37. FATFS_SECONDS_GRANULARITY: int = 2
  38. # long names are encoded to two bytes in utf-16
  39. LONG_NAMES_ENCODING: str = 'utf-16'
  40. SHORT_NAMES_ENCODING: str = 'utf-8'
  41. # compatible with WL_SECTOR_SIZE
  42. # choices for WL are WL_SECTOR_SIZE_512 and WL_SECTOR_SIZE_4096
  43. ALLOWED_WL_SECTOR_SIZES: List[int] = [512, 4096]
  44. ALLOWED_SECTOR_SIZES: List[int] = [512, 1024, 2048, 4096]
  45. ALLOWED_SECTORS_PER_CLUSTER: List[int] = [1, 2, 4, 8, 16, 32, 64, 128]
  46. def crc32(input_values: List[int], crc: int) -> int:
  47. """
  48. Name Polynomial Reversed? Init-value XOR-out
  49. crc32 0x104C11DB7 True 4294967295 (UINT32_MAX) 0xFFFFFFFF
  50. """
  51. return binascii.crc32(bytearray(input_values), crc)
  52. def number_of_clusters(number_of_sectors: int, sectors_per_cluster: int) -> int:
  53. return number_of_sectors // sectors_per_cluster
  54. def get_non_data_sectors_cnt(reserved_sectors_cnt: int, sectors_per_fat_cnt: int, root_dir_sectors_cnt: int) -> int:
  55. return reserved_sectors_cnt + sectors_per_fat_cnt + root_dir_sectors_cnt
  56. def get_fatfs_type(clusters_count: int) -> int:
  57. if clusters_count < FAT12_MAX_CLUSTERS:
  58. return FAT12
  59. if clusters_count <= FAT16_MAX_CLUSTERS:
  60. return FAT16
  61. return FAT32
  62. def get_fat_sectors_count(clusters_count: int, sector_size: int) -> int:
  63. fatfs_type_ = get_fatfs_type(clusters_count)
  64. if fatfs_type_ == FAT32:
  65. raise NotImplementedError('FAT32 is not supported!')
  66. # number of byte halves
  67. cluster_s: int = fatfs_type_ // 4
  68. fat_size_bytes: int = (
  69. clusters_count * 2 + cluster_s) if fatfs_type_ == FAT16 else (clusters_count * 3 + 1) // 2 + cluster_s
  70. return (fat_size_bytes + sector_size - 1) // sector_size
  71. def required_clusters_count(cluster_size: int, content: bytes) -> int:
  72. # compute number of required clusters for file text
  73. return (len(content) + cluster_size - 1) // cluster_size
  74. def generate_4bytes_random() -> int:
  75. return uuid.uuid4().int & 0xFFFFFFFF
  76. def pad_string(content: str, size: Optional[int] = None, pad: int = PAD_CHAR) -> str:
  77. # cut string if longer and fill with pad character if shorter than size
  78. return content.ljust(size or len(content), chr(pad))[:size]
  79. def right_strip_string(content: str, pad: int = PAD_CHAR) -> str:
  80. return content.rstrip(chr(pad))
  81. def build_lfn_short_entry_name(name: str, extension: str, order: int) -> str:
  82. return '{}{}'.format(pad_string(content=name[:MAX_NAME_SIZE - 2] + '~' + chr(order), size=MAX_NAME_SIZE),
  83. pad_string(extension[:MAX_EXT_SIZE], size=MAX_EXT_SIZE))
  84. def lfn_checksum(short_entry_name: str) -> int:
  85. """
  86. Function defined by FAT specification. Computes checksum out of name in the short file name entry.
  87. """
  88. checksum_result = 0
  89. for i in range(MAX_NAME_SIZE + MAX_EXT_SIZE):
  90. # operation is a right rotation on 8 bits (Python equivalent for unsigned char in C)
  91. checksum_result = (0x80 if checksum_result & 1 else 0x00) + (checksum_result >> 1) + ord(short_entry_name[i])
  92. checksum_result &= 0xff
  93. return checksum_result
  94. def convert_to_utf16_and_pad(content: str,
  95. expected_size: int,
  96. pad: bytes = FULL_BYTE) -> bytes:
  97. # we need to get rid of the Byte order mark 0xfeff or 0xfffe, fatfs does not use it
  98. bom_utf16: bytes = b'\xfe\xff'
  99. encoded_content_utf16: bytes = content.encode(LONG_NAMES_ENCODING)[len(bom_utf16):]
  100. return encoded_content_utf16.ljust(2 * expected_size, pad)
  101. def split_to_name_and_extension(full_name: str) -> Tuple[str, str]:
  102. name, extension = os.path.splitext(full_name)
  103. return name, extension.replace('.', '')
  104. def is_valid_fatfs_name(string: str) -> bool:
  105. return string == string.upper()
  106. def split_by_half_byte_12_bit_little_endian(value: int) -> Tuple[int, int, int]:
  107. value_as_bytes: bytes = Int16ul.build(value)
  108. return value_as_bytes[0] & 0x0f, value_as_bytes[0] >> 4, value_as_bytes[1] & 0x0f
  109. def merge_by_half_byte_12_bit_little_endian(v1: int, v2: int, v3: int) -> int:
  110. return v1 | v2 << 4 | v3 << 8
  111. def build_byte(first_half: int, second_half: int) -> int:
  112. return (first_half << 4) | second_half
  113. def split_content_into_sectors(content: bytes, sector_size: int) -> List[bytes]:
  114. result = []
  115. clusters_cnt: int = required_clusters_count(cluster_size=sector_size, content=content)
  116. for i in range(clusters_cnt):
  117. result.append(content[sector_size * i:(i + 1) * sector_size])
  118. return result
  119. def get_args_for_partition_generator(desc: str, wl: bool) -> argparse.Namespace:
  120. parser: argparse.ArgumentParser = argparse.ArgumentParser(description=desc)
  121. parser.add_argument('input_directory',
  122. help='Path to the directory that will be encoded into fatfs image')
  123. parser.add_argument('--output_file',
  124. default='fatfs_image.img',
  125. help='Filename of the generated fatfs image')
  126. parser.add_argument('--partition_size',
  127. default=FATDefaults.SIZE,
  128. help='Size of the partition in bytes.' +
  129. ('' if wl else ' Use `--partition_size detect` for detecting the minimal partition size.')
  130. )
  131. parser.add_argument('--sector_size',
  132. default=FATDefaults.SECTOR_SIZE,
  133. type=int,
  134. choices=ALLOWED_WL_SECTOR_SIZES if wl else ALLOWED_SECTOR_SIZES,
  135. help='Size of the partition in bytes')
  136. parser.add_argument('--sectors_per_cluster',
  137. default=1,
  138. type=int,
  139. choices=ALLOWED_SECTORS_PER_CLUSTER,
  140. help='Number of sectors per cluster')
  141. parser.add_argument('--root_entry_count',
  142. default=FATDefaults.ROOT_ENTRIES_COUNT,
  143. help='Number of entries in the root directory')
  144. parser.add_argument('--long_name_support',
  145. action='store_true',
  146. help='Set flag to enable long names support.')
  147. parser.add_argument('--use_default_datetime',
  148. action='store_true',
  149. help='For test purposes. If the flag is set the files are created with '
  150. 'the default timestamp that is the 1st of January 1980')
  151. parser.add_argument('--fat_type',
  152. default=0,
  153. type=int,
  154. choices=[FAT12, FAT16, 0],
  155. help="""
  156. Type of fat. Select 12 for fat12, 16 for fat16. Don't set, or set to 0 for automatic
  157. calculation using cluster size and partition size.
  158. """)
  159. args = parser.parse_args()
  160. if args.fat_type == 0:
  161. args.fat_type = None
  162. if args.partition_size == 'detect' and not wl:
  163. args.partition_size = -1
  164. args.partition_size = int(str(args.partition_size), 0)
  165. if not os.path.isdir(args.input_directory):
  166. raise NotADirectoryError(f'The target directory `{args.input_directory}` does not exist!')
  167. return args
  168. def read_filesystem(path: str) -> bytearray:
  169. with open(path, 'rb') as fs_file:
  170. return bytearray(fs_file.read())
  171. DATE_ENTRY = BitStruct(
  172. 'year' / BitsInteger(7),
  173. 'month' / BitsInteger(4),
  174. 'day' / BitsInteger(5))
  175. TIME_ENTRY = BitStruct(
  176. 'hour' / BitsInteger(5),
  177. 'minute' / BitsInteger(6),
  178. 'second' / BitsInteger(5),
  179. )
  180. def build_name(name: str, extension: str) -> str:
  181. return f'{name}.{extension}' if len(extension) > 0 else name
  182. def build_date_entry(year: int, mon: int, mday: int) -> int:
  183. """
  184. :param year: denotes year starting from 1980 (0 ~ 1980, 1 ~ 1981, etc), valid values are 1980 + 0..127 inclusive
  185. thus theoretically 1980 - 2107
  186. :param mon: denotes number of month of year in common order (1 ~ January, 2 ~ February, etc.),
  187. valid values: 1..12 inclusive
  188. :param mday: denotes number of day in month, valid values are 1..31 inclusive
  189. :returns: 16 bit integer number (7 bits for year, 4 bits for month and 5 bits for day of the month)
  190. """
  191. assert year in range(FATFS_INCEPTION_YEAR, FATFS_INCEPTION_YEAR + FATFS_MAX_YEARS)
  192. assert mon in range(1, FATFS_MAX_MONTHS + 1)
  193. assert mday in range(1, FATFS_MAX_DAYS + 1)
  194. return int.from_bytes(DATE_ENTRY.build(dict(year=year - FATFS_INCEPTION_YEAR, month=mon, day=mday)), 'big')
  195. def build_time_entry(hour: int, minute: int, sec: int) -> int:
  196. """
  197. :param hour: denotes number of hour, valid values are 0..23 inclusive
  198. :param minute: denotes minutes, valid range 0..59 inclusive
  199. :param sec: denotes seconds with granularity 2 seconds (e.g. 1 ~ 2, 29 ~ 58), valid range 0..29 inclusive
  200. :returns: 16 bit integer number (5 bits for hour, 6 bits for minute and 5 bits for second)
  201. """
  202. assert hour in range(FATFS_MAX_HOURS)
  203. assert minute in range(FATFS_MAX_MINUTES)
  204. assert sec in range(FATFS_MAX_SECONDS)
  205. return int.from_bytes(TIME_ENTRY.build(
  206. dict(hour=hour, minute=minute, second=sec // FATFS_SECONDS_GRANULARITY)),
  207. byteorder='big'
  208. )
  209. class FATDefaults:
  210. # FATFS defaults
  211. SIZE: int = 1024 * 1024
  212. RESERVED_SECTORS_COUNT: int = 1
  213. FAT_TABLES_COUNT: int = 1
  214. SECTORS_PER_CLUSTER: int = 1
  215. SECTOR_SIZE: int = 0x1000
  216. HIDDEN_SECTORS: int = 0
  217. ENTRY_SIZE: int = 32
  218. NUM_HEADS: int = 0xff
  219. OEM_NAME: str = 'MSDOS5.0'
  220. SEC_PER_TRACK: int = 0x3f
  221. VOLUME_LABEL: str = 'Espressif'
  222. FILE_SYS_TYPE: str = 'FAT'
  223. ROOT_ENTRIES_COUNT: int = 512 # number of entries in the root directory, recommended 512
  224. MEDIA_TYPE: int = 0xf8
  225. SIGNATURE_WORD: bytes = b'\x55\xAA'
  226. # wear levelling defaults
  227. VERSION: int = 2
  228. TEMP_BUFFER_SIZE: int = 32
  229. UPDATE_RATE: int = 16
  230. WR_SIZE: int = 16
  231. # wear leveling metadata (config sector) contains always sector size 4096
  232. WL_SECTOR_SIZE: int = 4096