From 31cfc2e0d46b33ac7f3a8de86096e28b5929e9f6 Mon Sep 17 00:00:00 2001 From: David Malcolm Date: Mon, 17 Jul 2017 21:23:51 -0400 Subject: [PATCH 20/27] Fix selftest::read_file for empty file selftest::read_file currently assumes it has a non-empty file; when loading an empty file it dies with an assertion failure, or a write through NULL if assertions are disabled. This patch fixes this case, removing this limitation. gcc/ChangeLog: * selftest.c (selftest::read_file): Handle 0-length files. (selftest::test_read_empty_file): New function. (selftest::selftest_c_tests): Call it. --- gcc/selftest.c | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/gcc/selftest.c b/gcc/selftest.c index b41b9f5..026a35f 100644 --- a/gcc/selftest.c +++ b/gcc/selftest.c @@ -192,7 +192,14 @@ read_file (const location &loc, const char *path) fclose (f_in); /* 0-terminate the buffer. */ + if (total_sz == 0) + { + size_t new_alloc_sz = alloc_sz ? alloc_sz * 2: total_sz + 1; + result = (char *)xrealloc (result, new_alloc_sz); + alloc_sz = new_alloc_sz; + } gcc_assert (total_sz < alloc_sz); + gcc_assert (result); result[total_sz] = '\0'; return result; @@ -296,6 +303,17 @@ test_read_file () free (buf); } +/* Verify that read_file can cope with an empty file. */ + +static void +test_read_empty_file () +{ + temp_source_file t (SELFTEST_LOCATION, "empty.txt", ""); + char *buf = read_file (SELFTEST_LOCATION, t.get_filename ()); + ASSERT_STREQ ("", buf); + free (buf); +} + /* Verify locate_file (and read_file). */ static void @@ -317,6 +335,7 @@ selftest_c_tests () test_assertions (); test_named_temp_file (); test_read_file (); + test_read_empty_file (); test_locate_file (); } -- 1.8.5.3