Fix unnecessary call to __strncpy_chk2
If "n" is smaller than the size of "src", then we'll
never read off the end of src. It makes no sense to call
__strncpy_chk2 in those circumstances.
For example, consider the following code:
int main() {
char src[10];
char dst[5];
memcpy(src, "0123456789", sizeof(src));
strncpy(dst, src, sizeof(dst));
dst[4] = '\0';
printf("%s\n", dst);
return 0;
}
In this code, it's clear that the strncpy will never read off
the end of src.
Change-Id: I9cf58857a0c5216b4576d21d3c1625e2913ccc03
diff --git a/libc/include/string.h b/libc/include/string.h
index 10ff722..37d22c4 100644
--- a/libc/include/string.h
+++ b/libc/include/string.h
@@ -135,6 +135,10 @@
return __builtin___strncpy_chk(dest, src, n, bos_dest);
}
+ if (__builtin_constant_p(n) && (n <= bos_src)) {
+ return __builtin___strncpy_chk(dest, src, n, bos_dest);
+ }
+
size_t slen = __builtin_strlen(src);
if (__builtin_constant_p(slen)) {
return __builtin___strncpy_chk(dest, src, n, bos_dest);