Skip to content

Commit

Permalink
Merge pull request #17895 from victoryforce/safer-dt_copy_file
Browse files Browse the repository at this point in the history
Safer malloc in `dt_copy_file` - logging an error instead of terminating
  • Loading branch information
TurboGit authored Nov 27, 2024
2 parents b3e52a1 + fe99016 commit b4e550a
Showing 1 changed file with 30 additions and 9 deletions.
39 changes: 30 additions & 9 deletions src/common/utility.c
Original file line number Diff line number Diff line change
Expand Up @@ -920,26 +920,47 @@ char *dt_read_file(const char *const filename, size_t *filesize)
return NULL;
}

void dt_copy_file(const char *const sourcefile, const char *dst)
void dt_copy_file(const char *const sourcefile, const char *destination)
{
char *content = NULL;
FILE *fin = g_fopen(sourcefile, "rb");
FILE *fout = g_fopen(dst, "wb");
FILE *fout = g_fopen(destination, "wb");

if(fin && fout)
{
fseek(fin, 0, SEEK_END);
const size_t end = ftell(fin);
const size_t filesize = ftell(fin);
rewind(fin);
content = (char *)g_malloc_n(end, sizeof(char));
if(content == NULL) goto END;
if(fread(content, sizeof(char), end, fin) != end) goto END;
if(fwrite(content, sizeof(char), end, fout) != end) goto END;

content = (char *)g_try_malloc_n(filesize, sizeof(char));
if(content == NULL)
{
dt_print(DT_DEBUG_ALWAYS,
"[dt_copy_file] failure to allocate memory for copying file '%s'",
sourcefile);
goto END;
}
if(fread(content, sizeof(char), filesize, fin) != filesize)
{
dt_print(DT_DEBUG_ALWAYS,
"[dt_copy_file] error reading file '%s' for copying",
sourcefile);
goto END;
}
if(fwrite(content, sizeof(char), filesize, fout) != filesize)
{
dt_print(DT_DEBUG_ALWAYS,
"[dt_copy_file] error writing file '%s' during copying",
destination);
goto END;
}
}

END:
if(fout != NULL) fclose(fout);
if(fin != NULL) fclose(fin);
if(fout != NULL)
fclose(fout);
if(fin != NULL)
fclose(fin);

g_free(content);
}
Expand Down

0 comments on commit b4e550a

Please sign in to comment.