Skip to content

Commit 0d63064

Browse files
gburgessivNoumanAmir657
authored andcommitted
libc: strlcpy/strlcat shouldn't bzero the rest of buf (llvm#114259)
When running Bionic's testsuite over llvm-libc, tests broke because e.g., ``` const char *str = "abc"; char buf[7]{"111111"}; strlcpy(buf, str, 7); ASSERT_EQ(buf, {'1', '1', '1', '\0', '\0', '\0', '\0'}); ``` On my machine (Debian w/ glibc and clang-16), a `printf` loop over `buf` gets unrolled into a series of const `printf` at compile-time: ``` printf("%d\n", '1'); printf("%d\n", '1'); printf("%d\n", '1'); printf("%d\n", 0); printf("%d\n", '1'); printf("%d\n", '1'); printf("%d\n", 0); ``` Seems best to match existing precedent here.
1 parent 3e69411 commit 0d63064

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

libc/src/string/string_utils.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ LIBC_INLINE size_t strlcpy(char *__restrict dst, const char *__restrict src,
221221
return len;
222222
size_t n = len < size - 1 ? len : size - 1;
223223
inline_memcpy(dst, src, n);
224-
inline_bzero(dst + n, size - n);
224+
dst[n] = '\0';
225225
return len;
226226
}
227227

libc/test/src/string/strlcat_test.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,15 @@ TEST(LlvmLibcStrlcatTest, Smaller) {
2727
EXPECT_STREQ(buf, "abcd");
2828
}
2929

30+
TEST(LlvmLibcStrlcatTest, SmallerNoOverwriteAfter0) {
31+
const char *str = "cd";
32+
char buf[8]{"ab\0\0efg"};
33+
34+
EXPECT_EQ(LIBC_NAMESPACE::strlcat(buf, str, 8), size_t(4));
35+
EXPECT_STREQ(buf, "abcd");
36+
EXPECT_STREQ(buf + 5, "fg");
37+
}
38+
3039
TEST(LlvmLibcStrlcatTest, No0) {
3140
const char *str = "cd";
3241
char buf[7]{"ab"};

libc/test/src/string/strlcpy_test.cpp

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,5 @@ TEST(LlvmLibcStrlcpyTest, Smaller) {
2525

2626
EXPECT_EQ(LIBC_NAMESPACE::strlcpy(buf, str, 7), size_t(3));
2727
EXPECT_STREQ(buf, "abc");
28-
for (const char *p = buf + 3; p < buf + 7; p++)
29-
EXPECT_EQ(*p, '\0');
28+
EXPECT_STREQ(buf + 4, "11");
3029
}

0 commit comments

Comments
 (0)