From 5111a778cd1ef73b85caef42c5d96a59956a35c8 Mon Sep 17 00:00:00 2001 From: Enjia Mai Date: Sat, 24 Apr 2021 01:15:40 +0800 Subject: [PATCH] lib: c_lib: add a check logic to verify overflow in fwrite Add a simple logic to validate parameters of fwrite(). If the result of size times nitems greater than the string length, return zero. Fixes #33491. Signed-off-by: Enjia Mai --- lib/libc/minimal/source/stdout/stdout_console.c | 4 ++++ tests/lib/sprintf/src/main.c | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/libc/minimal/source/stdout/stdout_console.c b/lib/libc/minimal/source/stdout/stdout_console.c index 92f094c78771..015b07681361 100644 --- a/lib/libc/minimal/source/stdout/stdout_console.c +++ b/lib/libc/minimal/source/stdout/stdout_console.c @@ -65,6 +65,10 @@ size_t z_impl_zephyr_fwrite(const void *_MLIBC_RESTRICT ptr, size_t size, return 0; } + if ((strlen(ptr) + 1) < (size * nitems)) { + return 0; + } + p = ptr; i = nitems; do { diff --git a/tests/lib/sprintf/src/main.c b/tests/lib/sprintf/src/main.c index 7c8913548e01..dfe7317d58b5 100644 --- a/tests/lib/sprintf/src/main.c +++ b/tests/lib/sprintf/src/main.c @@ -914,7 +914,7 @@ void test_fwrite(void) zassert_equal(ret, 0, "fwrite failed!"); ret = fwrite("This 3", 4, 4, stdout); - zassert_not_equal(ret, 0, "fwrite failed!"); + zassert_equal(ret, 0, "fwrite failed!"); ret = fwrite("This 3", 4, 4, stdin); zassert_equal(ret, 0, "fwrite failed!");