add check for overflow while doubling (very unlikely in practice, but still
authorespie <espie@openbsd.org>
Sat, 25 Apr 2015 15:33:47 +0000 (15:33 +0000)
committerespie <espie@openbsd.org>
Sat, 25 Apr 2015 15:33:47 +0000 (15:33 +0000)
better style code). Problem noticed by deraadt@ in m4.

okay doug@ deraadt@

usr.bin/m4/gnum4.c
usr.bin/make/buf.c

index 99d5255..8bc007b 100644 (file)
@@ -1,4 +1,4 @@
-/* $OpenBSD: gnum4.c,v 1.48 2015/03/14 23:00:43 millert Exp $ */
+/* $OpenBSD: gnum4.c,v 1.49 2015/04/25 15:33:47 espie Exp $ */
 
 /*
  * Copyright (c) 1999 Marc Espie
@@ -208,8 +208,11 @@ addchars(const char *c, size_t n)
        while (current + n > bufsize) {
                if (bufsize == 0)
                        bufsize = 1024;
-               else
+               else if (bufsize <= SIZE_MAX/2) {
                        bufsize *= 2;
+               } else {
+                       errx(1, "size overflow");
+               }
                buffer = xrealloc(buffer, bufsize, NULL);
        }
        memcpy(buffer+current, c, n);
index 8aeec06..d7ecf3b 100644 (file)
@@ -1,4 +1,4 @@
-/*     $OpenBSD: buf.c,v 1.25 2012/11/07 14:18:41 espie Exp $  */
+/*     $OpenBSD: buf.c,v 1.26 2015/04/25 15:33:47 espie Exp $  */
 /*     $NetBSD: buf.c,v 1.9 1996/12/31 17:53:21 christos Exp $ */
 
 /*
@@ -67,7 +67,9 @@
  */
 
 #include <ctype.h>
+#include <limits.h>
 #include <stddef.h>
+#include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
 #include <stdarg.h>
 #define DO_STAT_BUF(a, b)
 #endif
 
+static void
+fatal_overflow()
+{
+       fprintf(stderr, "buffer size overflow\n");
+       exit(2);
+}
+
 /* BufExpand(bp, nb)
  *     Expand buffer bp to hold upto nb additional
  *     chars.  Makes sure there's room for an extra '\0' char at
@@ -97,7 +106,11 @@ do {                                                        \
        DO_STAT_BUF(bp, nb);                            \
                                                        \
        do {                                            \
-               size *= 2 ;                             \
+               if (size <= SIZE_MAX/2) {               \
+                       size *= 2 ;                     \
+               } else {                                \
+                       fatal_overflow();               \
+               }                                       \
        } while (size - occupied < (nb)+1+BUF_MARGIN);  \
        (bp)->buffer = (bp)->inPtr = (bp)->endPtr =     \
                erealloc((bp)->buffer, size);           \