From d13c2b1ba6681fdbee73a044d988c3f9e1172d30 Mon Sep 17 00:00:00 2001 From: Nick Kralevich Date: Fri, 27 Sep 2013 13:21:24 -0700 Subject: [PATCH] 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 --- libc/include/string.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libc/include/string.h b/libc/include/string.h index 10ff72230..37d22c4db 100644 --- a/libc/include/string.h +++ b/libc/include/string.h @@ -135,6 +135,10 @@ char* strncpy(char* __restrict dest, const char* __restrict src, size_t n) { 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);