Skip to content

Commit 3fed8c2

Browse files
authored
Truncate the file before a StorageOperation write (#3523)
***NO_CI***
1 parent 5644d8f commit 3fed8c2

1 file changed

Lines changed: 12 additions & 0 deletions

File tree

src/HAL/nanoHAL_StorageOperation.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ uint32_t HAL_StorageOperation(uint8_t operation, uint32_t dataLength, uint32_t o
5353
char dirPath[FS_MAX_DIRECTORY_LENGTH];
5454
char *lastSeparator;
5555
int bytesWritten = 0;
56+
HRESULT deleteResult;
5657

5758
// extract parent directory from relative path and create it if needed
5859
snprintf(dirPath, sizeof(dirPath), "%s", relativePath);
@@ -74,6 +75,17 @@ uint32_t HAL_StorageOperation(uint8_t operation, uint32_t dataLength, uint32_t o
7475
}
7576
}
7677

78+
// Open() below doesn't truncate, so remove an existing file to start the write from an empty one
79+
deleteResult = volume->Delete(relativePath, false);
80+
81+
// a missing file, or a volume without Delete, is the normal case; any other failure would leave
82+
// the previous content in place and the write would produce a file with a stale tail
83+
if (FAILED(deleteResult) && deleteResult != CLR_E_FILE_NOT_FOUND && deleteResult != CLR_E_NOT_SUPPORTED)
84+
{
85+
errorCode = StorageOperationErrorCode::WriteError;
86+
goto done;
87+
}
88+
7789
// open the file (creates it, if it doesn't exist)
7890
if (FAILED(volume->Open(relativePath, fileHandle)))
7991
{

0 commit comments

Comments
 (0)