Commit f44f2542

f44f2542825aMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

fix(parse): read_file handles ftell error + short read (#768, #763)

Two related I/O paths in the parser's read_file helper:

  • #768: ftell returning -1 on a stream error used to fall through as len = -1, then malloc(len + 1) = malloc(0) returned NULL, and the subsequent fread(NULL, 1, SIZE_MAX, f) tried to read 16 exabytes. Now check fseek/ftell explicitly and bail with NULL.
  • #763: fread's partial-read return wasn't checked, so a disk error / interrupt that produced a truncated source file got silently fed to the parser. Now compare nread == len and bail on short read.

Same call site, same NULL-on-error contract -- existing callers already treat NULL as "file not openable" and log a warning.

Closes #768 Closes #763

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
f44f2542825a
Parent
a97a06c03173

spinel_parse.cmodifiedView file

@@ -1295,11 +1295,19 @@
12951295 static char *read_file(const char *path) {
12961296 FILE *f = fopen(path, "rb");
12971297 if (!f) return NULL;
1298- fseek(f, 0, SEEK_END);
1298+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
12991299 long len = ftell(f);
1300- fseek(f, 0, SEEK_SET);
1301- char *buf = malloc(len + 1);
1302- size_t nread = fread(buf, 1, len, f);
1300+ /* Issue #768: ftell returning -1 (stream error) used to wrap len + 1
1301+ to 0, malloc(0) returns NULL, then fread(NULL, 1, SIZE_MAX, f)
1302+ tried to read 16 exabytes. Bail cleanly. */
1303+ if (len < 0) { fclose(f); return NULL; }
1304+ if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
1305+ char *buf = malloc((size_t)len + 1);
1306+ if (!buf) { fclose(f); return NULL; }
1307+ size_t nread = fread(buf, 1, (size_t)len, f);
1308+ /* Issue #763: detect short read and bail rather than processing
1309+ a truncated source file silently. */
1310+ if (nread != (size_t)len) { free(buf); fclose(f); return NULL; }
13031311 buf[nread] = '\0';
13041312 fclose(f);
13051313 return buf;