From 6947d6b23919ebc01edad6c31451345830669df7 Mon Sep 17 00:00:00 2001 From: Attila Lakatos Date: Thu, 25 Jul 2024 21:19:11 +0200 Subject: [PATCH] Custom strndupa: Convert it to a macro instead of a function (#385) * Custom strndupa: Convert it to a macro instead of a function Looking at https://www.gnu.org/software/libc/manual/html_node/Truncating-Strings.html , strndupa is implemented as a macro. It uses malloca, which allocates space in the stack frame of the caller. The temporary space is automatically freed when the function that called alloca returns. * Remove extra () from strndupa macro --- auparse/auparse.c | 17 +++++++++-------- src/ausearch-lol.c | 17 +++++++++-------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/auparse/auparse.c b/auparse/auparse.c index e16586343..c3e1fb9ed 100644 --- a/auparse/auparse.c +++ b/auparse/auparse.c @@ -502,7 +502,7 @@ auparse_state_t *auparse_init(ausource_t source, const void *b) if (access_ok(b)) goto bad_exit; tmp = malloc(2*sizeof(char *)); - if (tmp == NULL) + if (tmp == NULL) goto bad_exit; tmp[0] = strdup(b); tmp[1] = NULL; @@ -1215,13 +1215,14 @@ static int str2event(char *s, au_event_t *e) } #ifndef HAVE_STRNDUPA -static inline char *strndupa(const char *old, size_t n) -{ - size_t len = strnlen(old, n); - char *tmp = alloca(len + 1); - tmp[len] = 0; - return memcpy(tmp, old, len); -} +#define strndupa(s, n) \ + ({ \ + const char *__old = (s); \ + size_t __len = strnlen (__old, (n)); \ + char *__new = (char *) alloca(__len + 1); \ + __new[__len] = '\0'; \ + (char *) memcpy (__new, __old, __len); \ + }) #endif /* Returns 0 on success and 1 on error */ diff --git a/src/ausearch-lol.c b/src/ausearch-lol.c index 476723dfb..31c5ff2e3 100644 --- a/src/ausearch-lol.c +++ b/src/ausearch-lol.c @@ -163,13 +163,14 @@ static int compare_event_time(event *e1, event *e2) } #ifndef HAVE_STRNDUPA -static inline char *strndupa(const char *old, size_t n) -{ - size_t len = strnlen(old, n); - char *tmp = alloca(len + 1); - tmp[len] = 0; - return memcpy(tmp, old, len); -} +#define strndupa(s, n) \ + ({ \ + const char *__old = (s); \ + size_t __len = strnlen (__old, (n)); \ + char *__new = (char *) alloca(__len + 1); \ + __new[__len] = '\0'; \ + (char *) memcpy (__new, __old, __len); \ + }) #endif /* @@ -244,7 +245,7 @@ static int extract_timestamp(const char *b, event *e) return 0; } -// This function will check events to see if they are complete +// This function will check events to see if they are complete // FIXME: Can we think of other ways to determine if the event is done? static void check_events(lol *lo, time_t sec) {