lkml.org 
[lkml]   [2022]   [Jan]   [30]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
Patch in this message
/
From
Subject[PATCH] lib/test_string.c: Add test for strlen()
Date
Add a simple test for strlen() functionality, including using it as a
constant expression.

Cc: Geert Uytterhoeven <geert@linux-m68k.org>
Cc: Peter Rosin <peda@axentia.se>
Signed-off-by: Kees Cook <keescook@chromium.org>
---
I'll be taking this as part of my Clang FORTIFY_SOURCE series.
---
lib/test_string.c | 37 +++++++++++++++++++++++++++++++++++++
1 file changed, 37 insertions(+)

diff --git a/lib/test_string.c b/lib/test_string.c
index 9dfd6f52de92..59994f552c48 100644
--- a/lib/test_string.c
+++ b/lib/test_string.c
@@ -179,6 +179,38 @@ static __init int strnchr_selftest(void)
return 0;
}

+/*
+ * Unlike many other string functions, strlen() can be used in
+ * static initializers when string lengths are known at compile
+ * time. (i.e. Under these conditions, strlen() is a constant
+ * expression.) Make sure it can be used this way.
+ */
+static const int strlen_ce = strlen("tada, a constant expression");
+
+static __init int strlen_selftest(void)
+{
+ /* String length ruler: 123456789012345 */
+ static const char normal[] = "I am normal";
+ static const char *ptr = "where do I go?";
+ static const char trailing[] = "hidden NULLs\0\0\0";
+ static const char leading[] = "\0\0hidden text";
+
+ if (strlen(normal) != 11)
+ return 0x100001;
+ if (strlen(ptr++) != 14)
+ return 0x100002;
+ if (strlen(ptr++) != 13)
+ return 0x100003;
+ if (strlen(trailing) != 12)
+ return 0x100004;
+ if (strlen(leading) != 0)
+ return 0x100005;
+ if (strlen_ce != 27)
+ return 0x100006;
+
+ return 0;
+}
+
static __exit void string_selftest_remove(void)
{
}
@@ -212,6 +244,11 @@ static __init int string_selftest_init(void)
if (subtest)
goto fail;

+ test = 5;
+ subtest = strlen_selftest();
+ if (subtest)
+ goto fail;
+
pr_info("String selftests succeeded\n");
return 0;
fail:
--
2.30.2
\
 
 \ /
  Last update: 2022-01-30 19:37    [W:0.092 / U:0.100 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site