(string_list_join_concat) Prevent undefined behaviour if input string buffer is unterminated

This commit is contained in:
jdgleaver 2020-08-25 15:51:15 +01:00
parent 915bbc9bcc
commit 179e77c8b0
2 changed files with 24 additions and 2 deletions

View File

@ -70,7 +70,18 @@ static INLINE bool string_ends_with(const char *str, const char *suffix)
return string_ends_with_size(str, suffix, strlen(str), strlen(suffix));
}
/* Returns the length of 'str' (c.f. strlen()), but only
* checks the first 'size' characters
* - If 'str' is NULL, returns 0
* - If 'str' is not NULL and no '\0' character is found
* in the first 'size' characters, returns 'size' */
static INLINE size_t strlen_size(const char *str, size_t size)
{
size_t i = 0;
if (str)
for(; (i < size) && str[i]; ++i);
return i;
}
#define STRLEN_CONST(x) ((sizeof((x))-1))

View File

@ -245,7 +245,18 @@ void string_list_set(struct string_list *list,
void string_list_join_concat(char *buffer, size_t size,
const struct string_list *list, const char *delim)
{
size_t i, len = strlen(buffer);
size_t i;
size_t len = strlen_size(buffer, size);
/* If buffer is already 'full', nothing
* further can be added
* > This condition will also be triggered
* if buffer is not NUL-terminated,
* in which case any attempt to increment
* buffer or decrement size would lead to
* undefined behaviour */
if (len >= size)
return;
buffer += len;
size -= len;