$OpenBSD: patch-pbm_libpm_c,v 1.1 2003/03/29 04:13:54 brad Exp $
--- pbm/libpm.c.orig	Fri Jan 25 19:18:05 2002
+++ pbm/libpm.c	Fri Mar 28 20:22:07 2003
@@ -14,6 +14,7 @@
 **************************************************************************/
 
 #include <stdio.h>
+#include <limits.h>
 #include "version.h"
 #include "compile.h"
 #include "shhopt.h"
@@ -38,7 +39,7 @@ char*
 pm_allocrow(int const cols, int const size) {
     register char* itrow;
 
-    itrow = (char*) malloc( cols * size );
+    itrow = (char*) malloc2( cols , size );
     if ( itrow == (char*) 0 )
         pm_error( "out of memory allocating a row" );
     return itrow;
@@ -56,10 +57,10 @@ pm_allocarray(int const cols, int const 
     char** its;
     int i;
 
-    its = (char**) malloc( rows * sizeof(char*) );
+    its = (char**) malloc2( rows, sizeof(char*) );
     if ( its == (char**) 0 )
         pm_error( "out of memory allocating an array" );
-    its[0] = (char*) malloc( rows * cols * size );
+    its[0] = (char*) malloc3( rows, cols, size );
     if ( its[0] == (char*) 0 )
         pm_error( "out of memory allocating an array" );
     for ( i = 1; i < rows; ++i )
@@ -77,10 +78,12 @@ char**
 pm_allocarray(int const cols, int const rows, int const size) {
     char** its;
     int i;
-    its = (char**) malloc( (rows + 1) * sizeof(char*) );
+    
+    overflow_add(rows, 1);
+    its = (char**) malloc2( (rows + 1),  sizeof(char*) );
     if ( its == (char**) 0 )
         pm_error( "out of memory allocating an array" );
-    its[rows] = its[0] = (char*) malloc( rows * cols * size );
+    its[rows] = its[0] = (char*) malloc3( rows. cols, size );
     if ( its[0] != (char*) 0 )
         for ( i = 1; i < rows; ++i )
             its[i] = &(its[0][i * cols * size]);
@@ -878,4 +881,52 @@ pm_check(FILE * const file, const enum p
 }
 
 
-
+/*
+ *	Maths wrapping
+ */
+ 
+void overflow2(int a, int b)
+{
+	if(a < 0 || b < 0)
+		pm_error("object too large");
+	if(b == 0)
+		return;
+	if(a > INT_MAX / b)
+		pm_error("object too large");
+}
+
+void overflow3(int a, int b, int c)
+{
+	overflow2(a,b);
+	overflow2(a*b, c);
+}
+
+void overflow_add(int a, int b)
+{
+	if( a > INT_MAX - b)
+		pm_error("object too large");
+}
+
+void *malloc2(int a, int b)
+{
+	overflow2(a, b);
+	if(a*b == 0)
+		pm_error("Zero byte allocation");
+	return malloc(a*b);
+}
+
+void *malloc3(int a, int b, int c)
+{
+	overflow3(a, b, c);
+	if(a*b*c == 0)
+		pm_error("Zero byte allocation");
+	return malloc(a*b*c);
+}
+
+void *realloc2(void * a, int b, int c)
+{
+	overflow2(b, c);
+	if(b*c == 0)
+		pm_error("Zero byte allocation");
+	return realloc(a, b*c);
+}
