From a2745278eb03d63f4df8da4367f27ec8cab7deb9 Mon Sep 17 00:00:00 2001 From: jvoisin Date: Sat, 30 Sep 2023 00:15:26 +0200 Subject: Add `strlen` --- README.md | 1 + include/string.h | 17 +++++++++++++++++ tests/Makefile | 1 + tests/test_strlen_static_read.c | 22 ++++++++++++++++++++++ 4 files changed, 41 insertions(+) create mode 100644 tests/test_strlen_static_read.c diff --git a/README.md b/README.md index 9d4dacf..5ec6c5a 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,7 @@ At this point, the program will safely crash. - `strcpy` - `strlcat` - `strlcpy` +- `strlen` - `strncat` - `strncpy` - `strrchr` diff --git a/include/string.h b/include/string.h index e681181..ab7ac43 100644 --- a/include/string.h +++ b/include/string.h @@ -35,6 +35,7 @@ extern "C" { #undef memset #undef strcat #undef strcpy +#undef strlen #undef strncat #undef strncpy @@ -237,6 +238,22 @@ _FORTIFY_FN(strcpy) char *strcpy(char * _FORTIFY_POS0 __d, const char *__s) #endif } +__access (read_only, 1) +#if __has_builtin(__builtin_strlen) +__diagnose_as_builtin(__builtin_strlen, 1) +#endif +_FORTIFY_FN(strlen) size_t strlen(const char * _FORTIFY_POS0 __s) +{ +#if __has_builtin(__builtin___strlen_chk) && USE_NATIVE_CHK + return __builtin___strlen_chk(__s, __bos(__s, 0)); +#else + size_t ret = __orig_strlen(__s); + if (ret > __bos(__s, 0) - 1) + __builtin_trap(); + return ret; +#endif +} + __access (read_write, 1) __access (read_only, 2, 3) #if __has_builtin(__builtin_strncat) diff --git a/tests/Makefile b/tests/Makefile index 81593cf..c862c52 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -87,6 +87,7 @@ RUNTIME_TARGETS= \ test_stpncpy_overwrite_over \ test_stpncpy_overwrite_under \ test_stpncpy_static_write \ + test_strlen_static_read \ test_strcat_static_write \ test_strchr_dynamic_read \ test_strchr_static_read \ diff --git a/tests/test_strlen_static_read.c b/tests/test_strlen_static_read.c new file mode 100644 index 0000000..b1f928d --- /dev/null +++ b/tests/test_strlen_static_read.c @@ -0,0 +1,22 @@ +#define _GNU_SOURCE +#define _BSD_SOURCE + +#include "common.h" + +#include + +int main(int argc, char** argv) { + char* canary1 = "ABCDEFGHIJKLMNOPQ"; + char buf[] = {'a', 'b', 'c', 'd', '\0'}; + char* canary2 = "ABCDEF"; + strlen(buf); + puts(buf); + buf[4] = 'e'; + + CHK_FAIL_START + strlen(buf); + CHK_FAIL_END + + puts(argv[1]); + return ret; +} -- cgit v1.3