Skip to content

Commit

Permalink
Custom strndupa: Convert it to a macro instead of a function (#385)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
Cropi authored and stevegrubb committed Jul 25, 2024
1 parent a5f87a5 commit 6947d6b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
17 changes: 9 additions & 8 deletions auparse/auparse.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 */
Expand Down
17 changes: 9 additions & 8 deletions src/ausearch-lol.c
Original file line number Diff line number Diff line change
Expand Up @@ -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

/*
Expand Down Expand Up @@ -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)
{
Expand Down

0 comments on commit 6947d6b

Please sign in to comment.