From df15c97b6e85ab622e21889137184038c0476987 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20K=C4=85dzio=C5=82ka?= Date: Wed, 3 Jul 2019 16:28:51 +0200 Subject: [PATCH] Handle zero-byte files gracefully --- src/asm/lexer.c | 14 ++++++++++++-- test/asm/zero-byte-file.asm | 0 test/asm/zero-byte-file.out | 0 test/asm/zero-byte-file.out.pipe | 0 4 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 test/asm/zero-byte-file.asm create mode 100644 test/asm/zero-byte-file.out create mode 100644 test/asm/zero-byte-file.out.pipe diff --git a/src/asm/lexer.c b/src/asm/lexer.c index ab22fa77..a98fef81 100644 --- a/src/asm/lexer.c +++ b/src/asm/lexer.c @@ -184,10 +184,14 @@ YY_BUFFER_STATE yy_create_buffer(FILE *f) // If ftell errored or the block above wasn't executed if (capacity == -1) capacity = 4096; + // Handle 0-byte files gracefully + else if (capacity == 0) + capacity = 1; while (!feof(f)) { if (buf == NULL || size >= capacity) { - capacity *= 2; + if (buf) + capacity *= 2; /* Give extra room for 2 newlines and terminator */ buf = realloc(buf, capacity + SAFETYMARGIN + 3); @@ -199,7 +203,7 @@ YY_BUFFER_STATE yy_create_buffer(FILE *f) char *bufpos = buf + SAFETYMARGIN + size; size_t read_count = fread(bufpos, 1, capacity - size, f); - if (read_count == 0) + if (read_count == 0 && !feof(f)) fatalerror("%s: fread error", __func__); size += read_count; @@ -211,6 +215,12 @@ YY_BUFFER_STATE yy_create_buffer(FILE *f) pBuffer->pBuffer[size] = 0; pBuffer->nBufferSize = size; + /* This is added here to make the buffer scaling above easy to express, + * while taking the newline space into account + * for the `yy_buffer_append`s below. + */ + capacity += 3; + /* Convert all line endings to LF and spaces */ char *mem = pBuffer->pBuffer; diff --git a/test/asm/zero-byte-file.asm b/test/asm/zero-byte-file.asm new file mode 100644 index 00000000..e69de29b diff --git a/test/asm/zero-byte-file.out b/test/asm/zero-byte-file.out new file mode 100644 index 00000000..e69de29b diff --git a/test/asm/zero-byte-file.out.pipe b/test/asm/zero-byte-file.out.pipe new file mode 100644 index 00000000..e69de29b