Skip to content

Commit 93eb8b6

Browse files
committed
fatfs: Free path copy when f_open fails (FATFS_FSTAT)
When FATFS_FSTAT is enabled, open_r allocates a path copy for fstat/fchmod. If f_open fails, close_r never runs, so the buffer was leaked. Free f->path on the error path and clear the pointer, matching close_r. See PR_DESCRIPTION.md for full description, implementation notes, and testing suggestions.
1 parent b91eeda commit 93eb8b6

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

PR_DESCRIPTION.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# FatFS: free path copy when `f_open` fails (`FATFS_FSTAT`)
2+
3+
## Description
4+
5+
When `FATFS_FSTAT` is enabled, `open_r` allocates a heap copy of the opened path for `fstat`/`fchmod`. If `f_open` failed, that buffer was never freed because `close_r` does not run on a failed open. Each failed open leaked `strlen(path) + 1` bytes until reboot. This change frees the path copy on the `f_open` error path and clears the pointer, matching cleanup in `close_r`.
6+
7+
## Implementation Details
8+
9+
- **`src/buddy/filesystem_fatfs.cpp`**: In `open_r`, inside `if (result != FR_OK)`, add a `FATFS_FSTAT`-guarded block that calls `free(f->path)` when non-null and sets `f->path` to `nullptr` before existing `FR_NO_FILESYSTEM` handling and `return -1`.
10+
11+
## Test/Documentation
12+
13+
- No automated test added; `FATFS_FSTAT` is optional (currently commented out in this file), so default CI builds do not exercise this block.
14+
- To exercise the change: define `FATFS_FSTAT`, build a target that uses the FatFS devoptab, and open a path that makes `f_open` fail (e.g. missing file on USB); confirm heap does not grow on repeated attempts (or use a host-side Memcheck model of the same control flow).

src/buddy/filesystem_fatfs.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,12 @@ static int open_r(struct _reent *r, void *fileStruct, const char *path, int flag
239239
r->_errno = get_errno(result);
240240

241241
if (result != FR_OK) {
242+
#ifdef FATFS_FSTAT
243+
if (f->path) {
244+
free(f->path);
245+
f->path = nullptr;
246+
}
247+
#endif
242248
if (result == FR_NO_FILESYSTEM) {
243249
// Displays exact message that file system on usb disk is not supported
244250
marlin_client::set_warning(WarningType::USBDriveUnsupportedFileSystem);

0 commit comments

Comments
 (0)