Add strprefix() and fix a bug with it
Subsystems (7)
v8 cover Add strprefix() and fix a bug with it
Hi!
str_has_prefix() is based on sizes and lengths, which means it must overload the valid length 0 to mean not found. This is a typical consequence of choosing to design an API around sizes and lengths, and vanishes when moving to pointer-based similar APIs.
According to its author (Steven R.), str_has_prefix() was never meant to accept an empty prefix, but that's not documented, and there's no obvious reason why that would be acceptable for a generic string function (as opposed to a function very specific to its original use). Anyway, as suggested by Steven, I've added a WARN_ON_ONCE() to catch such uses, and also added documentation stating this limitation.
If the function had been named something like strprefix_len(), that design would have made sense, but being called str_has_prefix(), the obvious way to call it will result in bugs, because the name contradicts its intended use.
Users of strings need a function whose behavior extends naturally to the empty string, and we can do better, by returning a pointer. And indeed, users have ended up using str_has_prefix() with empty prefix, expecting it to work (as is natural of a generic string API with that name).
This patch set adds strprefix(), and uses strprefix() in one place to fix a bug reported by Bartosz.
It also adds streq(3), just because it simplifies the tests, and is also a nice interface.
This patch set doesn't include the sibling strsuffix(), and also doesn't replace any other cases which would benefit from strprefix(), to allow merging it quickly. I'll work on a follow-up patch, including the patches from v6 that have been dropped in this v7, after this has been applied.
Have a lovely day!
Alex
Changes in v8
~~~~~~~~~~~~~
- [*/4]
- Add Tested-by and Reviewed-by tags.
- [4/4]
- Remove Message-ID tags. [Andy, Geert, Bartosz]
See the range-diff and interdiff below.
v1: <https://lore.kernel.org/linux-hardening/[email protected]/>
v2: <https://lore.kernel.org/linux-hardening/[email protected]/>
v3: <https://lore.kernel.org/linux-hardening/[email protected]/>
v4: <https://lore.kernel.org/linux-hardening/[email protected]/>
v5: <https://lore.kernel.org/linux-hardening/[email protected]/>
v6: <https://lore.kernel.org/linux-hardening/[email protected]/>
v7: <https://lore.kernel.org/linux-hardening/[email protected]/>
Testing
~~~~~~~
Since there are no code changes since v7, I haven't tested again. See the link for v7 above to see the testing of v7. Bartosz also tested v7.
Alejandro Colomar (4):
string: Add streq()
string: Add strprefix()
string: Document corner-case misbehavior in str_has_prefix() for empty
prefix
device property: Fix fwnode_name_eq() for empty node names
drivers/base/property.c | 5 +--- drivers/clk/socfpga/clk-gate-a10.c | 2 -- drivers/clk/socfpga/clk.h | 1 - include/linux/string.h | 42 +++++++++++++++++++++++++++--- lib/tests/string_kunit.c | 22 ++++++++++++++++ 5 files changed, 61 insertions(+), 11 deletions(-)
Interdiff against v7:
Range-diff against v7:
1: ad8500a6eb0a ! 1: 8f3840fa232e string: Add streq()
@@ Commit message
This removes some driver-specific definitions of streq(3).
+ Tested-by: Bartosz Golaszewski <[email protected]>
+ Reviewed-by: Bartosz Golaszewski <[email protected]>
## drivers/clk/socfpga/clk-gate-a10.c ##
2: b32d70163fb4 ! 2: a688f0a1c20a string: Add strprefix()
@@ Commit message
+ Tested-by: Bartosz Golaszewski <[email protected]>
+ Reviewed-by: Bartosz Golaszewski <[email protected]>
## include/linux/string.h ##
3: c4131a109098 ! 3: fb24c7a543f8 string: Document corner-case misbehavior in str_has_prefix() for empty prefix
@@ Commit message
+ Tested-by: Bartosz Golaszewski <[email protected]>
+ Reviewed-by: Bartosz Golaszewski <[email protected]>
## include/linux/string.h ##
4: 396395e1d02c ! 4: 5c23d229235a device property: Fix fwnode_name_eq() for empty node names
@@ Commit message
- Message-ID: <[email protected]>
- Message-ID: <nat4ilqmzzpuyrjbuahl367ip22tfnmjorydlppuwqiscxaujo@kf63j4lb3flk>
- Message-ID: <nat4ilqmzzpuyrjbuahl367ip22tfnmjorydlppuwqiscxaujo@kf63j4lb3flk>
## drivers/base/property.c ##
Signature · 1 line
2.55.0
PATCH v8 1/4 string: Add streq()
The return value of strcmp(3) being reversed makes it prone to mistakes. Since most of the time we're only interested in simple equality, add this API for those cases.
This removes some driver-specific definitions of streq(3).
--- drivers/clk/socfpga/clk-gate-a10.c | 2 -- drivers/clk/socfpga/clk.h | 1 - include/linux/string.h | 12 ++++++++++++ lib/tests/string_kunit.c | 13 +++++++++++++ 4 files changed, 25 insertions(+), 3 deletions(-)
drivers/clk/socfpga/clk-gate-a10.c +0 -2
@@ -11,8 +11,6 @@#include "clk.h" -#define streq (a, b) (strcmp((a), (b)) == 0) -#define to_socfpga_gate_clk (p) container_of(p, struct socfpga_gate_clk, hw.hw)/* SDMMC Group for System Manager defines */
drivers/clk/socfpga/clk.h +0 -1
@@ -19,7 +19,6 @@#define SOCFPGA_MAX_PARENTS 5 -#define streq (a, b) (strcmp((a), (b)) == 0)#define SYSMGR_SDMMC_CTRL_SET (smplsel, drvsel) \ ((((smplsel) & 0x7) << 3) | (((drvsel) & 0x7) << 0))
include/linux/string.h +12 -0
@@ -14,6 +14,18 @@#include <linux/stdarg.h> #include <uapi/linux/string.h> +/** +* streq - strings equal +* +* @s1: string to compare +* @s2: string to compare +* +* Compare two strings for equality. +* +* Return: true iff the strings are equal +*/ +#define streq (s1, s2) (strcmp(s1, s2) == 0) +extern char *strndup_user (const char __user *,long );extern void *memdup_user (const void __user *,size_t )__realloc_size (2 );extern void *vmemdup_user (const void __user *,size_t )__realloc_size (2 );
lib/tests/string_kunit.c +13 -0
@@ -287,6 +287,18 @@ static void string_test_strspn(struct kunit *test) } } +static void string_test_streq (struct kunit *test) +{ +KUNIT_ASSERT_TRUE (test,streq ("foo" ,"foo" )); +KUNIT_ASSERT_TRUE (test,streq ("" ,"" )); + +KUNIT_ASSERT_FALSE (test,streq ("foo" ,"foobar" )); +KUNIT_ASSERT_FALSE (test,streq ("foobar" ,"foo" )); +KUNIT_ASSERT_FALSE (test,streq ("foo" ,"bar" )); +KUNIT_ASSERT_FALSE (test,streq ("foo" ,"" )); +KUNIT_ASSERT_FALSE (test,streq ("" ,"bar" )); +} +static char strcmp_buffer1[STRCMP_LARGE_BUF_LEN ];static char strcmp_buffer2[STRCMP_LARGE_BUF_LEN ];
@@ -891,6 +903,7 @@ static struct kunit_case string_test_cases[] = {KUNIT_CASE (string_test_strnchr),KUNIT_CASE (string_test_strrchr),KUNIT_CASE (string_test_strspn), +KUNIT_CASE (string_test_streq),KUNIT_CASE (string_test_strcmp),KUNIT_CASE (string_test_strcmp_long_strings), KUNIT_CASE(string_test_strncmp),
Signature · 1 line
2.55.0
PATCH v8 2/4 string: Add strprefix()
In reply to Alejandro ColomarAs Bartosz reported, str_has_prefix() has a bug: it can't differentiate between an empty prefix matching an empty string from a non-matching prefix. This is a fundamental design flaw in this API, and not something that can be fixed.
As always, this is a consequence of choosing sizes instead of pointers. Sizes are often the wrong choice. In this specific case, pointers are more capable of differentiating these cases, as NULL is a special sentinel value that doesn't need to overload a valid value.
Let's implement strprefix(), a function that returns a pointer right after the prefix if found, and a null pointer if not found.
We'll slowly migrate existing code from str_has_prefix() to strprefix().
Move the description from str_has_prefix(), and describe str_has_prefix() by comparing it to strprefix().
--- include/linux/string.h | 28 +++++++++++++++++++++++----- lib/tests/string_kunit.c | 9 +++++++++ 2 files changed, 32 insertions(+), 5 deletions(-)
include/linux/string.h +23 -5
@@ -557,16 +557,34 @@ void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count, sizeof(*(obj)) - offsetof(typeof(*(obj)), member)); \ }) +/** +* strprefix - string prefix +* @s: The string to be tested +* @prefix: The string to see if @s starts with +* +* This function determines whether the string pointed to by @s +* starts with the sequence of characters +* (excluding the terminating null character) +* in the string pointed to by @prefix. +* +* Returns: +* * @s + strlen(@prefix) if @s starts with @prefix +* * NULL if @s does not start with @prefix +*/ +__nonnull_args(1, 2) +static inline char *strprefix (const char *s,const char *prefix) +{ +size_t len =strlen (prefix); +return strncmp (s, prefix, len) ==0 ? (char *) s + len :NULL ; +} +/** * str_has_prefix - Test if a string has a given prefix * @str: The string to test * @prefix: The string to see if @str starts with * -* A common way to test a prefix of a string is to do: -* strncmp(str, prefix, sizeof(prefix) - 1) -* -* But this can lead to bugs due to typos, or if prefix is a pointer -* and not a constant. Instead use str_has_prefix(). +* This is similar to strprefix(), but returns an offset instead of +* a pointer. * * Returns: * * strlen(@prefix) if @str starts with @prefix
lib/tests/string_kunit.c +9 -0
@@ -299,6 +299,14 @@ static void string_test_streq(struct kunit *test)KUNIT_ASSERT_FALSE (test,streq ("" ,"bar" )); } +static void string_test_strprefix (struct kunit *test) +{ +KUNIT_ASSERT_TRUE (test,streq (strprefix ("foobar" ,"foo" ),"bar" )); +KUNIT_ASSERT_TRUE (test,streq (strprefix ("foobar" ,"" ),"foobar" )); +KUNIT_ASSERT_TRUE (test,streq (strprefix ("foobar" ,"foobar" ),"" )); +KUNIT_ASSERT_NULL (test,strprefix ("foobar" ,"bar" )); +} +static char strcmp_buffer1[STRCMP_LARGE_BUF_LEN ];static char strcmp_buffer2[STRCMP_LARGE_BUF_LEN ];
@@ -904,6 +912,7 @@ static struct kunit_case string_test_cases[] = {KUNIT_CASE (string_test_strrchr),KUNIT_CASE (string_test_strspn),KUNIT_CASE (string_test_streq), +KUNIT_CASE (string_test_strprefix),KUNIT_CASE (string_test_strcmp),KUNIT_CASE (string_test_strcmp_long_strings), KUNIT_CASE(string_test_strncmp),
Signature · 1 line
2.55.0
PATCH v8 3/4 string: Document corner-case misbehavior in str_has_prefix() for empty prefix
In reply to Alejandro ColomarFor an empty prefix, this function returns a value that can't be distinguished from a non-matching prefix. This is wrong, since an empty prefix is present in every string, and has resulted in bugs in code that called this function without knowing this issue. Let's document it.
--- include/linux/string.h | 4 ++++ 1 file changed, 4 insertions(+)
include/linux/string.h +4 -0
@@ -586,6 +586,10 @@ static inline char *strprefix(const char *s, const char *prefix)* This is similar to strprefix(), but returns an offset instead of * a pointer. * +* Unlike for strprefix(), if the prefix is an empty string, the +* behavior is undefined. If you need to support arbitrary prefixes, +* use strprefix(). +* * Returns: * * strlen(@prefix) if @str starts with @prefix * * 0 if @str does not start with @prefix
Signature · 1 line
2.55.0
PATCH v8 4/4 device property: Fix fwnode_name_eq() for empty node names
In reply to Alejandro Colomarstr_has_prefix() returns the prefix length on match and 0 on mismatch, so the mistmatch case can't be told from "empty prefix matched an empty string".
For instance: the OF root node's name as returned by fwnode_get_name() is "" and will return 0 for any name matched against it and since len is 0 too, fwnode_name_eq() will return true.
Let's use strprefix() instead, which also makes this function simpler.
--- drivers/base/property.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-)
drivers/base/property.c +1 -4
@@ -692,15 +692,12 @@ const char *fwnode_get_name_prefix(const struct fwnode_handle *fwnode)bool fwnode_name_eq (const struct fwnode_handle *fwnode,const char *name) {const char *node_name; -ptrdiff_t len; node_name =fwnode_get_name (fwnode);if (!node_name)return false; - len =strchrnul (node_name,'@' ) - node_name; - -return str_has_prefix (node_name, name) == len; +return strprefix (node_name, name) ==strchrnul (node_name,'@' ); }EXPORT_SYMBOL_GPL (fwnode_name_eq);
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v8 2/4] string: Add strprefix()
In reply to Alejandro ColomarThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] string: kernel-doc parse failure on strprefix() due to __nonnull_args() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] string: kernel-doc parse failure on strprefix() due to __nonnull_args()
--
commit fa176bccb75ab1dcd9cc8e153bcc5112c790bc7c
Author: Alejandro Colomar <[email protected]>
string: Add strprefix()
This commit adds the strprefix() helper to return a pointer after a matched prefix or NULL on mismatch, along with KUnit tests.
Quoted 18 lines
include/linux/string.h +10
-0@@ -557,16 +557,34 @@ void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count, sizeof(*(obj)) - offsetof(typeof(*(obj)), member)); \ }) +/** +* strprefix - string prefix +* @s: The string to be tested +* @prefix: The string to see if @s starts with +* +* This function determines whether the string pointed to by @s +* starts with the sequence of characters +* (excluding the terminating null character) +* in the string pointed to by @prefix. +*
include/linux/string.h void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count, · line 579
Quoted 10 lines
include/linux/string.h +10
-0+* Returns: +* * @s + strlen(@prefix) if @s starts with @prefix +* * NULL if @s does not start with @prefix +*/ +__nonnull_args(1, 2) +static inline char *strprefix (const char *s,const char *prefix) +{ +size_t len =strlen (prefix); +return strncmp (s, prefix, len) ==0 ? (char *) s + len :NULL ; +}
[Severity: Low]
Does __nonnull_args(1, 2) break scripts/kernel-doc parsing for strprefix()?
CTransforms.function_xforms in tools/lib/python/kdoc/xforms_lists.py does not strip __nonnull_args(), so kernel-doc mistakes __nonnull_args for the function identifier when processing include/linux/string.h (included by Documentation/core-api/kernel-api.rst), emitting prototype mismatch warnings and omitting strprefix() from the generated documentation.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Re: [PATCH v8 2/4] string: Add strprefix()
Quoted 49 lines
Date: 2026-11-26 12:27:03+0000
From: [email protected]Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] string: kernel-doc parse failure onstrprefix()due to__nonnull_args()
--commit
fa176bccb75ab1dcd9cc8e153bcc5112c790bc7c
Author: Alejandro Colomar <[email protected]>string: Add
strprefix()This commit adds the
strprefix()helper to return a pointer after a matched prefix or NULL on mismatch, along with KUnit tests.Quoted 18 lines
include/linux/string.h +10
-0@@ -557,16 +557,34 @@ void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count, sizeof(*(obj)) - offsetof(typeof(*(obj)), member)); \ }) +/** +* strprefix - string prefix +* @s: The string to be tested +* @prefix: The string to see if @s starts with +* +* This function determines whether the string pointed to by @s +* starts with the sequence of characters +* (excluding the terminating null character) +* in the string pointed to by @prefix. +* include/linux/string.h void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count, · line 579
Quoted 10 lines
include/linux/string.h +10
-0+* Returns: +* * @s + strlen(@prefix) if @s starts with @prefix +* * NULL if @s does not start with @prefix +*/ +__nonnull_args(1, 2) +static inline char *strprefix (const char *s,const char *prefix) +{ +size_t len =strlen (prefix); +return strncmp (s, prefix, len) ==0 ? (char *) s + len :NULL ; +}[Severity: Low]
Does__nonnull_args(1, 2)breakscripts/kernel-docparsing forstrprefix()?
Quoted 5 lines
CTransforms.function_xforms in
tools/lib/python/kdoc/xforms_lists.pydoes not strip__nonnull_args(), so kernel-doc mistakes__nonnull_argsfor the function identifier when processinginclude/linux/string.h(included byDocumentation/core-api/kernel-api.rst), emitting prototype mismatch warnings and omittingstrprefix()from the generated documentation.
As said in v7, I don't know what to do with this. Any comments?
Signature · 1 line
<https://www.alejandro-colomar.es>