Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Failure of rename() may cause delete files. #7306

Closed
fjpanag opened this issue Oct 13, 2022 · 0 comments · Fixed by #7312
Closed

Failure of rename() may cause delete files. #7306

fjpanag opened this issue Oct 13, 2022 · 0 comments · Fixed by #7312

Comments

@fjpanag
Copy link
Contributor

fjpanag commented Oct 13, 2022

There is a case were rename() may fail, but also delete files in the process that it shouldn't.

This can happen when oldpath refers to a non-existent file, while newpath refers to a file that is actually there.
The code will first delete newpath, and then try to rename the first file. If this fails, newpath is lost.

The following snippet demonstrates this:

#define TEST_FILE1 "/mnt/sdcard0/file1"
#define TEST_FILE2 "/mnt/sdcard0/file2"

int fd1 = open(TEST_FILE1, O_WRONLY | O_CREAT, 0666);
write(fd1, "file1", sizeof("file1") - 1);
close(fd1);

int fd2 = open(TEST_FILE2, O_WRONLY | O_CREAT, 0666);
write(fd2, "file2", sizeof("file2") - 1);
close(fd2);

/* Rename file 1 to file 2. File 2 should be deleted
* and file 1 should take its place.
*/

rename(TEST_FILE1, TEST_FILE2);

/* Now only test file 2 should exist. */

/* Since there is no file 1, renaming bellow should fail. */

assert(rename(TEST_FILE1, TEST_FILE2) < 0);

/* ERROR! File 2 has been deleted! */

struct stat f_stat;
assert(stat(TEST_FILE2, &f_stat) == 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant