Skip to content

Commit e2ce959

Browse files
committed
Added more safety checks.
1 parent 58a74d5 commit e2ce959

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

source/format.cpp

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,27 +110,43 @@ static bool getFormatParams(const u64 totSec, const ArgFlags flags, FormatParams
110110

111111
if(fatBits <= 32)
112112
{
113-
// TODO: More sanity checks.
114113
if(params.rsvdSecCnt > 0xFFFF)
115114
{
116115
fputs("Error: Reserved sector count overflowed. Can't format the SD card with these parameters.\n", stderr);
117116
return false;
118117
}
119-
if(params.secPerFat * bytesPerSec / (fatBits / 8) < params.maxClus)
118+
119+
const u32 maxClus = params.maxClus;
120+
if(params.secPerFat * bytesPerSec / (fatBits / 8) < maxClus)
120121
{
121122
fputs("Error: FAT doesn't contain enough entries to allocate all clusters.\n", stderr);
122123
return false;
123124
}
125+
124126
const u32 calcFsArea = params.rsvdSecCnt + (2 * params.secPerFat) +
125127
((32 * (fatBits < 32 ? 512 : 0) + bytesPerSec - 1) / bytesPerSec);
126128
if(params.fsAreaSize != calcFsArea)
127129
{
128130
fputs("Error: Filesystem area smaller than reserved sectors + FATs.\n", stderr);
129131
return false;
130132
}
133+
131134
/*if(params.fsAreaSize > params.alignment)
132135
fputs("Warning: Filesystem area overlaps with data area. May reduce performance and lifetime.\n", stderr);*/
136+
137+
// fatgen103.doc: Less than 4085 is FAT12. Less than 65525 is FAT16. Otherwise FAT32.
138+
// mkfs.fat: Up to 4084 is FAT12. 4087-65524 is FAT16. 65525-268435444 is FAT32.
139+
// (Win) fastfat.sys, (Linux) msdos.ko/vfat.ko detect FAT32 when fatSz16 is set to zero.
140+
// Note: mkfs uses different values because of many FAT drivers with off by X bugs.
141+
const u32 upperBound = 0x0FFFFFF4u & (0xFFFFFFFFu>>(32 - fatBits)); // 0xFF4, 0xFFF4 and 0x0FFFFFF4.
142+
if((fatBits == 12 && maxClus > 4084u) || (fatBits == 16 && maxClus < 4087u) ||
143+
(fatBits == 32 && maxClus < 65525u) || maxClus > upperBound)
144+
{
145+
fputs("Error: Too few/many clusters for FAT variant.\n", stderr);
146+
return false;
147+
}
133148
}
149+
// TODO: exFAT checks.
134150

135151
return true;
136152
}

0 commit comments

Comments
 (0)