Skip to content

Commit

Permalink
libc: strlcpy/strlcat shouldn't bzero the rest of buf
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
gburgessiv committed Oct 30, 2024
1 parent 652988b commit 4b32b83
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion libc/src/string/string_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ LIBC_INLINE size_t strlcpy(char *__restrict dst, const char *__restrict src,
return len;
size_t n = len < size - 1 ? len : size - 1;
inline_memcpy(dst, src, n);
inline_bzero(dst + n, size - n);
dst[n] = '\0';
return len;
}

Expand Down
9 changes: 9 additions & 0 deletions libc/test/src/string/strlcat_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ TEST(LlvmLibcStrlcatTest, Smaller) {
EXPECT_STREQ(buf, "abcd");
}

TEST(LlvmLibcStrlcatTest, SmallerNoOverwriteAfter0) {
const char *str = "cd";
char buf[8]{"ab\0\0efg"};

EXPECT_EQ(LIBC_NAMESPACE::strlcat(buf, str, 8), size_t(4));
EXPECT_STREQ(buf, "abcd");
EXPECT_STREQ(buf + 5, "fg");
}

TEST(LlvmLibcStrlcatTest, No0) {
const char *str = "cd";
char buf[7]{"ab"};
Expand Down
3 changes: 1 addition & 2 deletions libc/test/src/string/strlcpy_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,5 @@ TEST(LlvmLibcStrlcpyTest, Smaller) {

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

0 comments on commit 4b32b83

Please sign in to comment.