Skip to content

Commit 041defe

Browse files
committed
Statically ensure valid FAT16 cluster count
1 parent 2c9826a commit 041defe

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

src/usb/uf2/ghostfat.c

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,8 @@ struct TextFile {
6868
#define BPB_RESERVED_SECTORS ( 1)
6969
#define BPB_NUMBER_OF_FATS ( 2)
7070
#define BPB_ROOT_DIR_ENTRIES ( 64)
71-
// Static assertions ensure CFG_UF2_NUM_BLOCKS will result in a valid file system.
72-
#define BPB_TOTAL_SECTORS CFG_UF2_NUM_BLOCKS // Configuration ... up to 0x10209 / 0x101e9?
71+
// #define BPB_TOTAL_SECTORS CFG_UF2_NUM_BLOCKS
72+
#define BPB_TOTAL_SECTORS (0x101dd) // 0x101dd is absolute max at current code commit
7373
#define BPB_MEDIA_DESCRIPTOR_BYTE (0xF8)
7474
#define FAT_ENTRY_SIZE (2)
7575
#define FAT_ENTRIES_PER_SECTOR (BPB_SECTOR_SIZE / FAT_ENTRY_SIZE)
@@ -125,6 +125,17 @@ STATIC_ASSERT(NUM_DIRENTRIES < (DIRENTRIES_PER_SECTOR * ROOT_DIR_SECTOR_COUNT));
125125
STATIC_ASSERT(NUM_DIRENTRIES < BPB_ROOT_DIR_ENTRIES); // FAT requirement -- Ensures BPB reserves sufficient entries for all files
126126
STATIC_ASSERT(NUM_DIRENTRIES < DIRENTRIES_PER_SECTOR); // GhostFAT bug workaround -- else, code overflows buffer
127127

128+
#define NUM_SECTORS_IN_DATA_REGION (BPB_TOTAL_SECTORS - BPB_RESERVED_SECTORS - (BPB_NUMBER_OF_FATS * BPB_SECTORS_PER_FAT) - ROOT_DIR_SECTOR_COUNT)
129+
#define CLUSTER_COUNT (NUM_SECTORS_IN_DATA_REGION / BPB_SECTORS_PER_CLUSTER)
130+
131+
// Ensure cluster count results in a valid FAT16 volume!
132+
STATIC_ASSERT( CLUSTER_COUNT >= 0x0FF5 && CLUSTER_COUNT < 0xFFF5 );
133+
134+
// Many existing FAT implementations have small (1-16) off-by-one style errors
135+
// So, avoid being within 32 of those limits for even greater compatibility.
136+
STATIC_ASSERT( CLUSTER_COUNT >= 0x1015 && CLUSTER_COUNT < 0xFFD5 );
137+
138+
128139
#define UF2_FIRMWARE_BYTES_PER_SECTOR 256
129140
#define TRUE_USER_FLASH_SIZE (USER_FLASH_END-USER_FLASH_START)
130141
STATIC_ASSERT(TRUE_USER_FLASH_SIZE % UF2_FIRMWARE_BYTES_PER_SECTOR == 0); // UF2 requirement -- overall size must be integral multiple of per-sector payload?

0 commit comments

Comments
 (0)