@@ -90,6 +90,24 @@ void fat16_unmount(fat16_fs_t* fs)
9090 */
9191}
9292
93+ static int fat16_next_cluster_safe (fat16_fs_t * fs ,
94+ uint16_t current ,
95+ uint16_t * next ,
96+ uint32_t * depth )
97+ {
98+ if (current < 2 || current >= FAT16_EOC )
99+ return FAT_ERR_NOT_FOUND ;
100+
101+ if ((* depth )++ > FAT16_MAX_CLUSTERS ) {
102+ printf ("fat16: FAT loop detected\n" );
103+ return FAT_ERR_CORRUPT ;
104+ }
105+
106+ * next = fat16_read_fat_fs (fs , current );
107+ return FAT_OK ;
108+ }
109+
110+
93111uint16_t fat16_read_fat_fs (fat16_fs_t * fs , uint16_t cluster ) {
94112 uint8_t buf [512 ];
95113 uint32_t offset = cluster * 2 ;
@@ -673,16 +691,24 @@ void fat16_update_root_entry(
673691 }
674692}
675693
676- void fat16_free_chain (fat16_fs_t * fs , uint16_t start_cluster ) {
694+ void fat16_free_chain (fat16_fs_t * fs , uint16_t start_cluster )
695+ {
677696 uint16_t cluster = start_cluster ;
678- while (cluster < FAT16_EOC ) {
679- uint16_t next = fat16_read_fat_fs (fs , cluster );
680- fat16_write_fat_entry (fs , cluster , 0x0000 ); // mark as free
697+ uint32_t depth = 0 ;
698+
699+ while (cluster >= 2 && cluster < FAT16_EOC ) {
700+ uint16_t next ;
701+
702+ if (fat16_next_cluster_safe (fs , cluster , & next , & depth ) != FAT_OK )
703+ break ;
704+
705+ fat16_write_fat_entry (fs , cluster , 0x0000 );
681706 cluster = next ;
682707 }
683708}
684709
685710
711+
686712int fat16_update_dir_entry (
687713 fat16_fs_t * fs ,
688714 uint16_t dir_cluster ,
@@ -832,6 +858,9 @@ int fat16_unlink(fat16_fs_t* fs, uint16_t parent_cluster, const char* name) {
832858 char fatname [11 ];
833859 fat16_format_name (name , fatname );
834860
861+ if (fat16_is_reserved_name (name ))
862+ return FAT_ERR_NOT_FOUND ;
863+
835864 if (fat16_find_in_dir (fs , parent_cluster , name , & e ) != 0 ) {
836865 printf ("unlink: '%s' not found" , name );
837866 return FAT_ERR_NOT_FOUND ;
@@ -1135,6 +1164,9 @@ int fat16_delete_entry(fat16_fs_t* fs, uint16_t parent_cluster, const char* name
11351164 char fatname [11 ];
11361165 fat16_format_name (name , fatname );
11371166
1167+ if (fat16_is_reserved_name (name ))
1168+ return FAT_ERR_NOT_FOUND ;
1169+
11381170 // Root directory
11391171 if (parent_cluster == 0 ) {
11401172 for (uint32_t i = 0 ; i < fs -> root_dir_sectors ; i ++ ) {
0 commit comments