[PATCH v4 2/6] string: Warn if the prefix is the empty string

From: Alejandro Colomar

Date: Wed Nov 11 2026 - 15:02:51 EST


This corner case is mishandled by this function.
Warn if it happens. Also, document that if such corner case
is needed, strprefix() is preferable.

Reported-by: Bartosz Golaszewski <bartosz.golaszewski@xxxxxxxxxxxxxxxx>
Link: https://lore.kernel.org/linux-hardening/20261104-fwnode-for-each-prop-v1-1-6e28fe1c72c4@xxxxxxxxxxxxxxxx/
Suggested-by: Steven Rostedt <rostedt@xxxxxxxxxxx>
Signed-off-by: Alejandro Colomar <alx@xxxxxxxxxx>
---
include/linux/string.h | 5 +++++
1 file changed, 5 insertions(+)

diff --git a/include/linux/string.h b/include/linux/string.h
index d08ca10c39a2..9444e216ab86 100644
--- a/include/linux/string.h
+++ b/include/linux/string.h
@@ -574,6 +574,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
@@ -581,6 +585,7 @@ static inline char *strprefix(const char *s, const char *prefix)
static __always_inline size_t str_has_prefix(const char *str, const char *prefix)
{
size_t len = strlen(prefix);
+ WARN_ON_ONCE(len == 0);
return strncmp(str, prefix, len) == 0 ? len : 0;
}

--
2.55.0

Attachment: signature.asc
Description: PGP signature