[libc-commits] [PATCH] D106885: [libc] Fix strtok_r crash when src and *saveptr are both nullptr
Alf via Phabricator via libc-commits
libc-commits at lists.llvm.org
Tue Jul 27 08:54:31 PDT 2021
gAlfonso-bit updated this revision to Diff 362050.
gAlfonso-bit added a comment.
Added a new test to catch the bug
CHANGES SINCE LAST ACTION
https://reviews.llvm.org/D106885/new/
https://reviews.llvm.org/D106885
Files:
libc/src/string/string_utils.h
libc/test/src/string/strtok_r_test.cpp
Index: libc/test/src/string/strtok_r_test.cpp
===================================================================
--- libc/test/src/string/strtok_r_test.cpp
+++ libc/test/src/string/strtok_r_test.cpp
@@ -80,6 +80,17 @@
ASSERT_STREQ(__llvm_libc::strtok_r(nullptr, ",", &reserve), nullptr);
}
+TEST(LlvmLibcStrTokReentrantTest,
+ ShouldReturnNullptrWhenBothSrcAndSaveptrAreNull) {
+ char *src = nullptr;
+ char *reserve = nullptr;
+ // Ensure that instead of crashing if src and reserve are null, nullptr is
+ // returned
+ ASSERT_STREQ(__llvm_libc::strtok_r(src, ",", &reserve), nullptr);
+ // And that reserve isn't changed when that happens
+ ASSERT_STREQ(__llvm_libc::strtok_r(src, ",", &reserve), nullptr);
+}
+
TEST(LlvmLibcStrTokReentrantTest,
SubsequentCallsShouldFindFollowingDelimiters) {
char src[] = "12,34.56";
Index: libc/src/string/string_utils.h
===================================================================
--- libc/src/string/string_utils.h
+++ libc/src/string/string_utils.h
@@ -58,23 +58,26 @@
static inline char *string_token(char *__restrict src,
const char *__restrict delimiter_string,
char **__restrict saveptr) {
+ // Check for nullptr in src AND *saveptr first
+ if (src == nullptr && ((src = *saveptr) == nullptr))
+ return nullptr;
+
cpp::Bitset<256> delimiter_set;
- for (; *delimiter_string; ++delimiter_string)
+ for (; *delimiter_string != '\0'; ++delimiter_string)
delimiter_set.set(*delimiter_string);
- src = src ? src : *saveptr;
- for (; *src && delimiter_set.test(*src); ++src)
+ for (; *src != '\0' && delimiter_set.test(*src); ++src)
;
- if (!*src) {
+ if (*src == '\0') {
*saveptr = src;
return nullptr;
}
char *token = src;
- for (; *src && !delimiter_set.test(*src); ++src)
- ;
- if (*src) {
- *src = '\0';
- ++src;
+ for (; *src != '\0'; ++src) {
+ if (delimiter_set.test(*src)) {
+ *src++ = '\0';
+ break;
+ }
}
*saveptr = src;
return token;
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D106885.362050.patch
Type: text/x-patch
Size: 2068 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libc-commits/attachments/20210727/db5002d1/attachment.bin>
More information about the libc-commits
mailing list