From d84885cfef71248629eb87d4556fde8c48c520ea Mon Sep 17 00:00:00 2001 From: Rong Tao Date: Thu, 28 Aug 2025 10:53:13 +0800 Subject: [PATCH 1/2] bpf/helpers: bpf_strnstr: Exact match length strnstr should not treat the ending '\0' of s2 as a matching character, otherwise the parameter 'len' will be meaningless, for example: 1. bpf_strnstr("openat", "open", 4) = -ENOENT 2. bpf_strnstr("openat", "open", 5) = 0 This patch makes (1) return 0, indicating a successful match. Signed-off-by: Rong Tao --- kernel/bpf/helpers.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 401b4932cc49f..ced7132980fe6 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -3672,10 +3672,12 @@ __bpf_kfunc int bpf_strnstr(const char *s1__ign, const char *s2__ign, size_t len guard(pagefault)(); for (i = 0; i < XATTR_SIZE_MAX; i++) { - for (j = 0; i + j < len && j < XATTR_SIZE_MAX; j++) { + for (j = 0; i + j <= len && j < XATTR_SIZE_MAX; j++) { __get_kernel_nofault(&c2, s2__ign + j, char, err_out); if (c2 == '\0') return i; + if (i + j == len) + break; __get_kernel_nofault(&c1, s1__ign + j, char, err_out); if (c1 == '\0') return -ENOENT; From 818b8cff5b92fb186e98030ca90435d7b94f32dd Mon Sep 17 00:00:00 2001 From: Rong Tao Date: Thu, 28 Aug 2025 10:53:41 +0800 Subject: [PATCH 2/2] selftests/bpf: Add tests for bpf_strnstr Add two tests for bpf_strnstr(): bpf_strnstr("", "", 0) = 0 bpf_strnstr("hello world", "hello", 5) = 0 Signed-off-by: Rong Tao --- tools/testing/selftests/bpf/progs/string_kfuncs_success.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/testing/selftests/bpf/progs/string_kfuncs_success.c b/tools/testing/selftests/bpf/progs/string_kfuncs_success.c index 46697f3818789..f8fe14787b2ea 100644 --- a/tools/testing/selftests/bpf/progs/string_kfuncs_success.c +++ b/tools/testing/selftests/bpf/progs/string_kfuncs_success.c @@ -30,6 +30,8 @@ __test(2) int test_strcspn(void *ctx) { return bpf_strcspn(str, "lo"); } __test(6) int test_strstr_found(void *ctx) { return bpf_strstr(str, "world"); } __test(-ENOENT) int test_strstr_notfound(void *ctx) { return bpf_strstr(str, "hi"); } __test(0) int test_strstr_empty(void *ctx) { return bpf_strstr(str, ""); } +__test(0) int test_strnstr_found(void *ctx) { return bpf_strnstr("", "", 0); } +__test(0) int test_strnstr_found(void *ctx) { return bpf_strnstr(str, "hello", 5); } __test(0) int test_strnstr_found(void *ctx) { return bpf_strnstr(str, "hello", 6); } __test(-ENOENT) int test_strnstr_notfound(void *ctx) { return bpf_strnstr(str, "hi", 10); } __test(0) int test_strnstr_empty(void *ctx) { return bpf_strnstr(str, "", 1); }