From b5447e8e35e42e77539c21710fc26979cf096846 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Dr=C3=B6ge?= Date: Thu, 25 Nov 2021 14:19:53 +0200 Subject: [PATCH] Add overflow protection to g_string_maybe_expand() --- glib/gstring.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/glib/gstring.c b/glib/gstring.c index 05b20b3e3..0a509e5e5 100644 --- a/glib/gstring.c +++ b/glib/gstring.c @@ -76,9 +76,17 @@ static void g_string_maybe_expand (GString *string, gsize len) { + /* Detect potential overflow */ + if G_UNLIKELY ((G_MAXSIZE - string->len - 1) < len) + g_error ("adding %" G_GSIZE_FORMAT " to string would overflow", len); + if (string->len + len >= string->allocated_len) { string->allocated_len = g_nearest_pow (string->len + len + 1); + /* If the new size is bigger than G_MAXSIZE / 2, only allocate enough + * memory for this string and don't over-allocate. */ + if (string->allocated_len == 0) + string->allocated_len = string->len + len + 1; string->str = g_realloc (string->str, string->allocated_len); } }