Skip to content

Commit 24e6f37

Browse files
authored
Add NULL checks to fix possible undefined behavior (netty#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
1 parent 7269441 commit 24e6f37

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

transport-native-unix-common/src/main/c/netty_unix_util.c

+13
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ static const uint64_t NETTY_BILLION = 1000000000L;
2929
#endif /* NETTY_USE_MACH_INSTEAD_OF_CLOCK */
3030

3131
char* netty_unix_util_prepend(const char* prefix, const char* str) {
32+
if (str == NULL) {
33+
// If str is NULL we should just return NULL as passing NULL to strlen is undefined behavior.
34+
return NULL;
35+
}
3236
char* result = NULL;
3337
if (prefix == NULL) {
3438
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) {
4650
}
4751

4852
char* netty_unix_util_rstrstr(char* s1rbegin, const char* s1rend, const char* s2) {
53+
if (s1rbegin == NULL || s1rend == NULL || s2 == NULL) {
54+
// Return NULL if any of the parameters is NULL to not risk a segfault
55+
return NULL;
56+
}
4957
size_t s2len = strlen(s2);
5058
char *s = s1rbegin - s2len;
5159

@@ -58,6 +66,11 @@ char* netty_unix_util_rstrstr(char* s1rbegin, const char* s1rend, const char* s2
5866
}
5967

6068
static char* netty_unix_util_strstr_last(const char* haystack, const char* needle) {
69+
if (haystack == NULL || needle == NULL) {
70+
// calling strstr with NULL is undefined behavior. Better just return NULL and not risk a crash.
71+
return NULL;
72+
}
73+
6174
char* prevptr = NULL;
6275
char* ptr = (char*) haystack;
6376

0 commit comments

Comments
 (0)