From 5e1c660416f945827d9cd3741ddc20a0b42514b2 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Fri, 23 Oct 2020 14:39:27 +0200 Subject: [PATCH] Add NULL checks to fix possible undefined behavior (#10718) Motivation: In some situations we could have end up calling some functions with NULL parameters which in this case could lead to undefined behavior. All of this would have happened during loading of the native lib. Modifications: Add NULL check as guards and return early Result: Fix some possible undefined behavior --- .../src/main/c/netty_unix_util.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/transport-native-unix-common/src/main/c/netty_unix_util.c b/transport-native-unix-common/src/main/c/netty_unix_util.c index 3d7bda871d..a0362ec525 100644 --- a/transport-native-unix-common/src/main/c/netty_unix_util.c +++ b/transport-native-unix-common/src/main/c/netty_unix_util.c @@ -29,6 +29,10 @@ static const uint64_t NETTY_BILLION = 1000000000L; #endif /* NETTY_USE_MACH_INSTEAD_OF_CLOCK */ char* netty_unix_util_prepend(const char* prefix, const char* str) { + if (str == NULL) { + // If str is NULL we should just return NULL as passing NULL to strlen is undefined behavior. + return NULL; + } char* result = NULL; if (prefix == NULL) { if ((result = (char*) malloc(sizeof(char) * (strlen(str) + 1))) == NULL) { @@ -46,6 +50,10 @@ char* netty_unix_util_prepend(const char* prefix, const char* str) { } char* netty_unix_util_rstrstr(char* s1rbegin, const char* s1rend, const char* s2) { + if (s1rbegin == NULL || s1rend == NULL || s2 == NULL) { + // Return NULL if any of the parameters is NULL to not risk a segfault + return NULL; + } size_t s2len = strlen(s2); char *s = s1rbegin - s2len; @@ -58,6 +66,11 @@ char* netty_unix_util_rstrstr(char* s1rbegin, const char* s1rend, const char* s2 } static char* netty_unix_util_strstr_last(const char* haystack, const char* needle) { + if (haystack == NULL || needle == NULL) { + // calling strstr with NULL is undefined behavior. Better just return NULL and not risk a crash. + return NULL; + } + char* prevptr = NULL; char* ptr = (char*) haystack;