From 1363c7fe768bdb98b662772f578900d68d4b42d4 Mon Sep 17 00:00:00 2001
From: MCUdude <hansibull@gmail.com>
Date: Sat, 9 Apr 2022 20:08:44 +0200
Subject: [PATCH] Fix buffer overflow issue when in terminal fill mode

---
 src/term.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/term.c b/src/term.c
index 04301304..dc771273 100644
--- a/src/term.c
+++ b/src/term.c
@@ -373,7 +373,8 @@ static int cmd_write(PROGRAMMER * pgm, struct avrpart * p,
     return -1;
   }
 
-  uint8_t * buf = malloc(mem->size + 0x10);
+  // Allocate a buffer guaranteed to be large enough
+  uint8_t * buf = calloc(mem->size + 0x10 + strlen(argv[argc - 2]), sizeof(uint8_t));
   if (buf == NULL) {
     avrdude_message(MSG_INFO, "%s (write): out of memory\n", progname);
     return -1;
@@ -535,6 +536,10 @@ static int cmd_write(PROGRAMMER * pgm, struct avrpart * p,
         buf[i - start_offset + ++data.bytes_grown] = data.a[7];
       }
     }
+
+    // Make sure buf does not overflow
+    if (i - start_offset + data.bytes_grown > maxsize)
+      break;
   }
 
   // When in "fill" mode, the maximum size is already predefined