From bd1ad65704d44e3e06a587a890e8087bfd9abe3b Mon Sep 17 00:00:00 2001 From: Marvin Borner Date: Sat, 3 Apr 2021 18:32:07 +0200 Subject: Added strnlen for buffer overflow prevention --- libs/libc/inc/str.h | 2 ++ libs/libc/str.c | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) (limited to 'libs') diff --git a/libs/libc/inc/str.h b/libs/libc/inc/str.h index b00750b..542e586 100644 --- a/libs/libc/inc/str.h +++ b/libs/libc/inc/str.h @@ -6,6 +6,7 @@ #include u32 strlen(const char *s) NONNULL; +u32 strnlen(const char *s, u32 max) NONNULL; u32 strlcpy(char *dst, const char *src, u32 size) NONNULL; char *strchr(char *s, char c) NONNULL; char *strrchr(char *s, char c) NONNULL; @@ -18,6 +19,7 @@ char *strdup(const char *s) NONNULL; #ifdef KERNEL u32 strlen_user(const char *s) NONNULL; +u32 strnlen_user(const char *s, u32 max) NONNULL; u32 strlcpy_user(char *dst, const char *src, u32 size) NONNULL; char *strchr_user(char *s, char c) NONNULL; char *strrchr_user(char *s, char c) NONNULL; diff --git a/libs/libc/str.c b/libs/libc/str.c index 52af5c4..9a30e92 100644 --- a/libs/libc/str.c +++ b/libs/libc/str.c @@ -13,6 +13,16 @@ u32 strlen(const char *str) return s - str; } +u32 strnlen(const char *str, u32 max) +{ + const char *s = str; + while (max && *s) { + s++; + max--; + } + return s - str; +} + u32 strlcpy(char *dst, const char *src, u32 size) { const char *orig = src; @@ -231,6 +241,14 @@ u32 strlen_user(const char *str) return ret; } +u32 strnlen_user(const char *str, u32 max) +{ + stac(); + u32 ret = strnlen(str, max); + clac(); + return ret; +} + u32 strlcpy_user(char *dst, const char *src, u32 size) { stac(); -- cgit v1.2.3