Re: [PATCH] lib/test_string.c: Add test for strlen()

From: Kees Cook
Date: Wed Feb 02 2022 - 15:52:07 EST


On Wed, Feb 02, 2022 at 08:01:49AM -0800, Guenter Roeck wrote:
> On Sun, Jan 30, 2022 at 10:36:53AM -0800, Kees Cook wrote:
> > Add a simple test for strlen() functionality, including using it as a
> > constant expression.
> >
> > Cc: Geert Uytterhoeven <geert@xxxxxxxxxxxxxx>
> > Cc: Peter Rosin <peda@xxxxxxxxxx>
> > Signed-off-by: Kees Cook <keescook@xxxxxxxxxxxx>
> > ---
> > 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");
> > +
>
> This results in:
>
> lib/test_string.c:188:30: error: initializer element is not constant
> 188 | static const int strlen_ce = strlen("tada, a constant expression");
>
> for several of my tests. I don't think you can mandate that a compiler
> implements this.

Which tests?

This property of strlen() is already required by our builds (this is how
I tripped over it). For example:

drivers/firmware/xilinx/zynqmp-debug.c:

#define PM_API(id) {id, #id, strlen(#id)}
static struct pm_api_info pm_api_list[] = {
PM_API(PM_GET_API_VERSION),
PM_API(PM_QUERY_DATA),
};



>
> Guenter
>
> > +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
> >

--
Kees Cook