From 0dcdc0347c8d0405c1c6b444d23483dd9bf31d34 Mon Sep 17 00:00:00 2001 From: Yu-Ping Wu Date: Thu, 8 Aug 2024 17:20:05 +0800 Subject: commonlib/bsd: Add strlen() and strnlen() functions Add strlen() and strnlen() to commonlib/bsd by rewriting them from scratch, and remove the same functions from coreboot and libpayload. Note that in the existing libpayload implementation, these functions return 0 for NULL strings. Given that POSIX doesn't require the NULL check and that other major libc implementations (e.g. glibc [1]) don't seem to do that, the new functions also don't perform the NULL check. [1] https://github.com/bminor/glibc/blob/master/sysdeps/i386/strlen.c Change-Id: I1203ec9affabe493bd14b46662d212b08240cced Signed-off-by: Yu-Ping Wu Reviewed-on: https://review.coreboot.org/c/coreboot/+/83830 Reviewed-by: Maximilian Brune Tested-by: build bot (Jenkins) Reviewed-by: Julius Werner --- src/commonlib/bsd/include/commonlib/bsd/string.h | 4 ++++ src/commonlib/bsd/string.c | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+) (limited to 'src/commonlib/bsd') diff --git a/src/commonlib/bsd/include/commonlib/bsd/string.h b/src/commonlib/bsd/include/commonlib/bsd/string.h index bbd4754800..8e8b896e7e 100644 --- a/src/commonlib/bsd/include/commonlib/bsd/string.h +++ b/src/commonlib/bsd/include/commonlib/bsd/string.h @@ -3,8 +3,12 @@ #ifndef _COMMONLIB_BSD_STRING_H_ #define _COMMONLIB_BSD_STRING_H_ +#include #include +size_t strlen(const char *src); +size_t strnlen(const char *str, size_t maxlen); + unsigned int skip_atoi(char **ptr); #endif /* _COMMONLIB_BSD_STRING_H_ */ diff --git a/src/commonlib/bsd/string.c b/src/commonlib/bsd/string.c index 3286d41b1c..a9dce39e8d 100644 --- a/src/commonlib/bsd/string.c +++ b/src/commonlib/bsd/string.c @@ -2,6 +2,26 @@ #include #include +#include + +size_t strlen(const char *str) +{ + const char *ptr = str; + + while (*ptr++) + ; + return ptr - str - 1; +} + +size_t strnlen(const char *str, size_t maxlen) +{ + const char *ptr = str; + const char *end = str + maxlen + 1; + + while (*ptr++ && ptr < end) + ; + return ptr - str - 1; +} unsigned int skip_atoi(char **ptr) { -- cgit v1.2.3