commit a2745278eb03d63f4df8da4367f27ec8cab7deb9
parent 4988174f7eecc6da544ebf23156ce638cecf0f3f
Author: jvoisin <julien.voisin@dustri.org>
Date: Sat, 30 Sep 2023 00:15:26 +0200
Add `strlen`
Diffstat:
4 files changed, 41 insertions(+), 0 deletions(-)
diff --git 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
@@ -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
@@ -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
@@ -0,0 +1,22 @@
+#define _GNU_SOURCE
+#define _BSD_SOURCE
+
+#include "common.h"
+
+#include <string.h>
+
+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;
+}