cb0a35
From 49923ccb2143e36850bcdeb781e2bcdf5ce22f15 Mon Sep 17 00:00:00 2001
cb0a35
From: John Hawthorn <john@hawthorn.email>
cb0a35
Date: Wed, 2 Mar 2022 14:17:59 -0800
cb0a35
Subject: [PATCH] Check need < buf->used
cb0a35
cb0a35
We're guaranteed a power of 2 so that this becomes 0, but we might as
cb0a35
well use a check for overflow that works in more cases.
cb0a35
cb0a35
Unsigned integer overflow is defined behaviour, so this should be safe.
cb0a35
cb0a35
(cherry picked from commit 36410d536b676e836637bb20574a56ebc920eb83)
cb0a35
---
cb0a35
 src/yajl_buf.c | 9 +++++++--
cb0a35
 1 file changed, 7 insertions(+), 2 deletions(-)
cb0a35
cb0a35
diff --git a/src/yajl_buf.c b/src/yajl_buf.c
cb0a35
index 1aeafde0..8bd1bea7 100644
cb0a35
--- a/src/yajl_buf.c
cb0a35
+++ b/src/yajl_buf.c
cb0a35
@@ -30,7 +30,7 @@ struct yajl_buf_t {
cb0a35
 };
cb0a35
 
cb0a35
 static
cb0a35
-void yajl_buf_ensure_available(yajl_buf buf, size_t want)
cb0a35
+int yajl_buf_ensure_available(yajl_buf buf, size_t want)
cb0a35
 {
cb0a35
     size_t need;
cb0a35
     
cb0a35
@@ -46,11 +46,15 @@ void yajl_buf_ensure_available(yajl_buf buf, size_t want)
cb0a35
     need = buf->len;
cb0a35
 
cb0a35
     while (want >= (need - buf->used)) need <<= 1;
cb0a35
+    if (need < buf->used) {
cb0a35
+         return -1;
cb0a35
+    }
cb0a35
 
cb0a35
     if (need != buf->len) {
cb0a35
         buf->data = (unsigned char *) YA_REALLOC(buf->alloc, buf->data, need);
cb0a35
         buf->len = need;
cb0a35
     }
cb0a35
+    return 0;
cb0a35
 }
cb0a35
 
cb0a35
 yajl_buf yajl_buf_alloc(yajl_alloc_funcs * alloc)
cb0a35
@@ -70,7 +74,8 @@ void yajl_buf_free(yajl_buf buf)
cb0a35
 
cb0a35
 void yajl_buf_append(yajl_buf buf, const void * data, size_t len)
cb0a35
 {
cb0a35
-    yajl_buf_ensure_available(buf, len);
cb0a35
+    if (yajl_buf_ensure_available(buf, len))
cb0a35
+        return;
cb0a35
     if (len > 0) {
cb0a35
         assert(data != NULL);
cb0a35
         memcpy(buf->data + buf->used, data, len);