Skip to content

Commit

Permalink
make bin2c more cautious
Browse files Browse the repository at this point in the history
* check fread for error
* check if the complete file was read (EOF reached)
* exit on writing null character, which would terminate the content prematurely
* check for error after writing file
  • Loading branch information
cgzones committed Nov 15, 2019
1 parent 3f303f3 commit 8ffcc5d
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/bin2c.c
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,27 @@ main (int argc, char *argv[])
return -1;
}

fread (buf, file_size, 1, f_input);
if (fread (buf, file_size, 1, f_input) == 0) {
fprintf (stderr, "%s: can't read from %s\n", argv[0], argv[1]);
free (buf);
fclose (f_input);
return -1;
}

if (fgetc (f_input) != EOF) {
fprintf (stderr, "%s: can't read complete file %s\n", argv[0], argv[1]);
free (buf);
fclose (f_input);
return -1;
}

if (ferror (f_input)) {
fprintf (stderr, "%s: error while reading from %s\n", argv[0], argv[1]);
free (buf);
fclose (f_input);
return -1;
}

fclose (f_input);

#ifdef USE_BZ2
Expand Down Expand Up @@ -93,6 +113,12 @@ main (int argc, char *argv[])

fprintf (f_output, "const char %s[%u] = {", ident, file_size);
for (i = 0; i < file_size; ++i) {
if (buf[i] == '\0') {
fprintf (stderr, "%s: writing a null character terminates the content prematurely\n", argv[0]);
fclose (f_output);
free (buf);
return -1;
}
if (need_comma)
fprintf (f_output, ", ");
else
Expand All @@ -109,6 +135,13 @@ main (int argc, char *argv[])
uncompressed_size);
#endif

if (ferror (f_output)) {
fprintf (stderr, "%s: error while writing to %s\n", argv[0], argv[2]);
fclose (f_output);
free (buf);
return -1;
}

fclose (f_output);
free (buf);

Expand Down

0 comments on commit 8ffcc5d

Please sign in to comment.