summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSebastian Dröge <sebastian@centricular.com>2021-11-25 14:19:53 +0200
committerSebastian Dröge <sebastian@centricular.com>2021-11-25 14:38:17 +0200
commitb5447e8e35e42e77539c21710fc26979cf096846 (patch)
tree73b0f780a62ea0b34d19ff580cf33bfcb71d1422
parentd01dc6d23a686778d8c0f1df695a3957f363f656 (diff)
downloadglib-b5447e8e35e42e77539c21710fc26979cf096846.tar.gz
Add overflow protection to g_string_maybe_expand()
-rw-r--r--glib/gstring.c8
1 files changed, 8 insertions, 0 deletions
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);
}
}