main: Fix race condition between calling stat and rename

This commit is contained in:
Pali Rohár committed 2017-06-17 23:10:36 +02:00
1 parent 76b18b9d39
commit 897919a70f
1 file changed
+11 -5
+11 -5
View File
@@ -1319,14 +1319,12 @@ int main(int argc, char **argv) {
for ( i = 0; i < IMAGE_COUNT; ++i ) { for ( i = 0; i < IMAGE_COUNT; ++i ) {
struct stat st; int rename_ret;
int rename_errno;
if ( ! image_tmp_name(i) ) if ( ! image_tmp_name(i) )
continue; continue;
if ( stat(image_tmp_name(i), &st) != 0 )
continue;
switch ( i ) { switch ( i ) {
case IMAGE_2ND: case IMAGE_2ND:
case IMAGE_XLOADER: case IMAGE_XLOADER:
@@ -1357,10 +1355,18 @@ int main(int argc, char **argv) {
buf[0] = 0; buf[0] = 0;
snprintf(buf, sizeof(buf), "%s-%s:%hd_%s", image_type_to_string(i), device_to_string(dev->detected_device), dev->detected_hwrev, ptr); snprintf(buf, sizeof(buf), "%s-%s:%hd_%s", image_type_to_string(i), device_to_string(dev->detected_device), dev->detected_hwrev, ptr);
rename_ret = rename(image_tmp_name(i), buf);
rename_errno = errno;
if ( rename_ret < 0 && rename_errno == ENOENT )
continue;
printf("Renaming %s image file to %s...\n", image_type_to_string(i), buf); printf("Renaming %s image file to %s...\n", image_type_to_string(i), buf);
if ( rename(image_tmp_name(i), buf) < 0 ) { if ( rename_ret < 0 ) {
errno = rename_errno;
ERROR_INFO("Renaming failed"); ERROR_INFO("Renaming failed");
buf[0] = 0; buf[0] = 0;