From 288465d6e908a4a2b9f8ed27834fc5861bae0ed3 Mon Sep 17 00:00:00 2001 From: Elliott Hughes Date: Tue, 5 Feb 2019 15:00:13 -0800 Subject: [PATCH] Avoid writing to a zero-capacity buffer. Bug: http://b/120752721 Test: ran tests Change-Id: I3f03ae204ab5de40fd4402a5562c50ffe51ef998 --- libc/stdio/fmemopen.cpp | 4 +++- tests/stdio_test.cpp | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/libc/stdio/fmemopen.cpp b/libc/stdio/fmemopen.cpp index 9d8c41f12..6e333ba5f 100644 --- a/libc/stdio/fmemopen.cpp +++ b/libc/stdio/fmemopen.cpp @@ -149,7 +149,9 @@ FILE* fmemopen(void* buf, size_t capacity, const char* mode) { } else if (mode[0] == 'w') { ck->size = 0; ck->offset = 0; - ck->buf[0] = '\0'; + if (capacity > 0) { + ck->buf[0] = '\0'; + } } return fp; diff --git a/tests/stdio_test.cpp b/tests/stdio_test.cpp index 479fd9d62..ad6ed45a9 100644 --- a/tests/stdio_test.cpp +++ b/tests/stdio_test.cpp @@ -1820,6 +1820,14 @@ TEST(STDIO_TEST, fmemopen_zero_length) { ASSERT_EQ(0, fclose(fp)); } +TEST(STDIO_TEST, fmemopen_zero_length_buffer_overrun) { + char buf[2] = "x"; + ASSERT_EQ('x', buf[0]); + FILE* fp = fmemopen(buf, 0, "w"); + ASSERT_EQ('x', buf[0]); + ASSERT_EQ(0, fclose(fp)); +} + TEST(STDIO_TEST, fmemopen_write_only_allocated) { // POSIX says fmemopen "may fail if the mode argument does not include a '+'". // BSD fails, glibc doesn't. We side with the more lenient.