fortify-headers

standalone fortify-source implementation
git clone git://git.2f30.org/fortify-headers
Log | Files | Refs | README | LICENSE

commit 532f4bfd0ba906e5a1410b9d2a46cf8a4992f062
parent af7480d0190cb5dcf279a7ddfab320ff084a3471
Author: jvoisin <julien.voisin@dustri.org>
Date:   Thu, 22 Jun 2023 18:07:41 +0200

Add tests for stcncpy

Diffstat:
Minclude/string.h | 7++++++-
Mtests/Makefile | 3+++
Atests/test_stpncpy_overwrite_over.c | 15+++++++++++++++
Atests/test_stpncpy_overwrite_under.c | 15+++++++++++++++
Atests/test_stpncpy_static_write.c | 16++++++++++++++++
5 files changed, 55 insertions(+), 1 deletion(-)

diff --git a/include/string.h b/include/string.h @@ -104,8 +104,13 @@ __access(write_only, 1) __access(read_only, 2, 3) _FORTIFY_FN(stpncpy) char *stpncpy(char *__d, const char *__s, size_t __n) { - size_t __b = __bos(__d, 0); + /* trap if pointers are overlapping but not if dst == src. + * gcc seems to like to generate code that relies on dst == src */ + if ((__d < __s && __d + __n > __s) || + (__s < __d && __s + __n > __d)) + __builtin_trap(); + size_t __b = __bos(__d, 0); if (__n > __b && strlen(__s) + 1 > __b) __builtin_trap(); return __orig_stpncpy(__d, __s, __n); diff --git a/tests/Makefile b/tests/Makefile @@ -22,6 +22,9 @@ TARGETS=test_memcpy_static_write \ test_strncpy_overwrite_over \ test_strncpy_overwrite_under \ test_strncpy_static_write \ + test_stpncpy_overwrite_over \ + test_stpncpy_overwrite_under \ + test_stpncpy_static_write \ test_getcwd \ .SILENT: diff --git a/tests/test_stpncpy_overwrite_over.c b/tests/test_stpncpy_overwrite_over.c @@ -0,0 +1,15 @@ +#include "common.h" + +#include <string.h> + +int main(int argc, char** argv) { + char buffer[9] = {'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', '\0'}; + puts(buffer); + + CHK_FAIL_START + stpncpy(buffer+1, buffer, 5); + CHK_FAIL_END + + puts(buffer); + return ret; +} diff --git a/tests/test_stpncpy_overwrite_under.c b/tests/test_stpncpy_overwrite_under.c @@ -0,0 +1,15 @@ +#include "common.h" + +#include <string.h> + +int main(int argc, char** argv) { + char buffer[9] = {'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', '\0'}; + puts(buffer); + + CHK_FAIL_START + stpncpy(buffer-1, buffer, 5); + CHK_FAIL_END + + puts(buffer); + return ret; +} diff --git a/tests/test_stpncpy_static_write.c b/tests/test_stpncpy_static_write.c @@ -0,0 +1,16 @@ +#include "common.h" + +#include <string.h> + +int main(int argc, char** argv) { + char buffer[8] = {0}; + stpncpy(buffer, "1234567", 5); + puts(buffer); + + CHK_FAIL_START + stpncpy(buffer, "1234567890", 10); + CHK_FAIL_END + + puts(buffer); + return ret; +}