Linux Hardening
 help / color / mirror / Atom feed
* [PATCH] strstarts: avoid calling strlen() if first char does not match
@ 2023-10-22 11:35 James Tirta Halim
  2023-10-22 13:10 ` Greg KH
  0 siblings, 1 reply; 2+ messages in thread
From: James Tirta Halim @ 2023-10-22 11:35 UTC (permalink / raw)
  To: linux-hardening, bpf; +Cc: James Tirta Halim

---
 include/linux/string.h  | 9 ++++++---
 tools/bpf/bpftool/gen.c | 2 +-
 2 files changed, 7 insertions(+), 4 deletions(-)

diff --git a/include/linux/string.h b/include/linux/string.h
index dbfc66400050..1c51039604e7 100644
--- a/include/linux/string.h
+++ b/include/linux/string.h
@@ -214,7 +214,7 @@ int ptr_to_hashval(const void *ptr, unsigned long *hashval_out);
  */
 static inline bool strstarts(const char *str, const char *prefix)
 {
-	return strncmp(str, prefix, strlen(prefix)) == 0;
+	return (*str == *prefix) ? strncmp(str, prefix, strlen(prefix)) == 0 : (*prefix == '\0');
 }
 
 size_t memweight(const void *ptr, size_t bytes);
@@ -356,8 +356,11 @@ void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count,
  */
 static __always_inline size_t str_has_prefix(const char *str, const char *prefix)
 {
-	size_t len = strlen(prefix);
-	return strncmp(str, prefix, len) == 0 ? len : 0;
+	if (*str == *prefix) {
+		size_t len = strlen(prefix);
+		return strncmp(str, prefix, len) == 0 ? len : 0;
+	}
+	return *prefix == '\0';
 }
 
 #endif /* _LINUX_STRING_H_ */
diff --git a/tools/bpf/bpftool/gen.c b/tools/bpf/bpftool/gen.c
index 2883660d6b67..5f8db7e517bc 100644
--- a/tools/bpf/bpftool/gen.c
+++ b/tools/bpf/bpftool/gen.c
@@ -36,7 +36,7 @@ static void sanitize_identifier(char *name)
 
 static bool str_has_prefix(const char *str, const char *prefix)
 {
-	return strncmp(str, prefix, strlen(prefix)) == 0;
+	return (*str == *prefix) ? strncmp(str, prefix, strlen(prefix)) == 0 : (*prefix == '\0');
 }
 
 static bool str_has_suffix(const char *str, const char *suffix)
-- 
2.42.0


^ permalink raw reply related	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2023-10-22 13:10 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2023-10-22 11:35 [PATCH] strstarts: avoid calling strlen() if first char does not match James Tirta Halim
2023-10-22 13:10 ` Greg KH

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox