From 3d91563c98296ea9947cfab4077f8d8cd1a78835 Mon Sep 17 00:00:00 2001 From: Thomas Heijligen Date: Mon, 21 Nov 2022 17:21:47 +0100 Subject: libpayload/string: add strndup() function Change-Id: Ie509e49f21fb537692704ac6527efa09649164e3 Signed-off-by: Thomas Heijligen Reviewed-on: https://review.coreboot.org/c/coreboot/+/70115 Reviewed-by: Jakub Czapiga Tested-by: build bot (Jenkins) --- payloads/libpayload/include/string.h | 1 + payloads/libpayload/libc/string.c | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) (limited to 'payloads/libpayload') diff --git a/payloads/libpayload/include/string.h b/payloads/libpayload/include/string.h index 393881d9cc..e87dea5def 100644 --- a/payloads/libpayload/include/string.h +++ b/payloads/libpayload/include/string.h @@ -59,6 +59,7 @@ char *strcat(char *d, const char *s); char *strchr(const char *s, int c); char *strrchr(const char *s, int c); char *strdup(const char *s); +char *strndup(const char *s, size_t size); char *strstr(const char *h, const char *n); char *strsep(char **stringp, const char *delim); size_t strspn(const char *s, const char *a); diff --git a/payloads/libpayload/libc/string.c b/payloads/libpayload/libc/string.c index 46c3c019bd..b3e1c8df0d 100644 --- a/payloads/libpayload/libc/string.c +++ b/payloads/libpayload/libc/string.c @@ -321,6 +321,25 @@ char *strdup(const char *s) return p; } +/** + * Duplicate a string with a max length of size + * + * @param s The string to duplicate. + * @param size The max length of the string + * @return A pointer to the copy of the original string. + */ +char *strndup(const char *s, size_t size) +{ + size_t n = strnlen(s, size); + char *p = malloc(n + 1); + + if (p != NULL) { + strncpy(p, s, n); + p[n] = 0; + } + return p; +} + /** * Find a substring within a string. * -- cgit v1.2.3