libc: add const-correct string.h overloads
libcxx provides const-correct overloads for a few string.h functions.
These overloads use clang's enable_if attribute, so they're preferred
over our FORTIFY'ed equivalents.
This weakens _FORTIFY_SOURCE=2 when used with some of these functions,
since clang needs to see __pass_object_size in order to pass an accurate
result for __builtin_object_size(s, 1) at a callsite. Since those
functions don't have __pass_object_size on their params, clang can't do
that. This makes LLVM lower the __builtin_object_size calls, which means
we get the same result as __builtin_object_size(s, 0).
We have to provide all of the overloads in Bionic, since enable_if is
only used to disambiguate overloads with (otherwise) the same type. In
other words:
// overload 1
char *strchr(const char *, int s) __attribute__((enable_if(1, "")));
// overload 2
char *strchr(char *, int s);
void foo() {
char cs[1] = {};
strchr(static_cast<const char *>(cs), '\0'); // calls overload #1.
strchr(cs, '\0'); // calls overload #2.
}
Bug: 34747525
Test: m checkbuild on bullhead internal master + AOSP. vts -m
BionicUnitTests passes on both. Surprisingly, the only code that this
seems to break is contained in Bionic.
Change-Id: Ie406f42fb3d1c5bf940dc857889876fc39b57c90
diff --git a/libc/bionic/fortify.cpp b/libc/bionic/fortify.cpp
index cf2d1c2..cfbfbc5 100644
--- a/libc/bionic/fortify.cpp
+++ b/libc/bionic/fortify.cpp
@@ -133,7 +133,7 @@
void* __memchr_chk(const void* s, int c, size_t n, size_t actual_size) {
__check_buffer_access("memchr", "read from", n, actual_size);
- return memchr(s, c, n);
+ return const_cast<void*>(memchr(s, c, n));
}
// Runtime implementation of __builtin____memmove_chk (used directly by compiler, not in headers).
diff --git a/libc/bionic/memmem.cpp b/libc/bionic/memmem.cpp
index 61d681f..019e772 100644
--- a/libc/bionic/memmem.cpp
+++ b/libc/bionic/memmem.cpp
@@ -35,7 +35,7 @@
if (n < m) return nullptr;
if (m == 0) return const_cast<void*>(void_haystack);
- if (m == 1) return memchr(haystack, needle[0], n);
+ if (m == 1) return const_cast<void*>(memchr(haystack, needle[0], n));
// This uses the "Not So Naive" algorithm, a very simple but usually effective algorithm.
// http://www-igm.univ-mlv.fr/~lecroq/string/
diff --git a/libc/bionic/ndk_cruft.cpp b/libc/bionic/ndk_cruft.cpp
index c042f9f..29565a2 100644
--- a/libc/bionic/ndk_cruft.cpp
+++ b/libc/bionic/ndk_cruft.cpp
@@ -322,7 +322,7 @@
// This was removed from POSIX 2008.
char* index(const char* str, int ch) {
- return strchr(str, ch);
+ return const_cast<char*>(strchr(str, ch));
}
// This was removed from BSD.