[glib: 3/5] Add overflow protection to g_string_maybe_expand()




commit b5447e8e35e42e77539c21710fc26979cf096846
Author: Sebastian Dröge <sebastian centricular com>
Date:   Thu Nov 25 14:19:53 2021 +0200

    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);
     }
 }


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]