1717 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
1818 * Portions Copyright (c) 1994, Regents of the University of California
1919 *
20- * $PostgreSQL: pgsql/src/interfaces/libpq/pqexpbuffer.c,v 1.16 2003/11/29 19:52:12 pgsql Exp $
20+ * $PostgreSQL: pgsql/src/interfaces/libpq/pqexpbuffer.c,v 1.17 2004/05/14 00:20:38 tgl Exp $
2121 *
2222 *-------------------------------------------------------------------------
2323 */
2424
2525#include "postgres_fe.h"
2626
27+ #include <limits.h>
28+
2729#include "pqexpbuffer.h"
2830
2931#ifdef WIN32
@@ -132,7 +134,18 @@ enlargePQExpBuffer(PQExpBuffer str, size_t needed)
132134size_t newlen ;
133135char * newdata ;
134136
137+ /*
138+ * Guard against ridiculous "needed" values, which can occur if we're
139+ * fed bogus data. Without this, we can get an overflow or infinite
140+ * loop in the following.
141+ */
142+ if (needed >= ((size_t )INT_MAX - str -> len ))
143+ return 0 ;
144+
135145needed += str -> len + 1 ;/* total space required now */
146+
147+ /* Because of the above test, we now have needed <= INT_MAX */
148+
136149if (needed <=str -> maxlen )
137150return 1 ;/* got enough space already */
138151
@@ -146,6 +159,14 @@ enlargePQExpBuffer(PQExpBuffer str, size_t needed)
146159while (needed > newlen )
147160newlen = 2 * newlen ;
148161
162+ /*
163+ * Clamp to INT_MAX in case we went past it. Note we are assuming
164+ * here that INT_MAX <= UINT_MAX/2, else the above loop could
165+ * overflow. We will still have newlen >= needed.
166+ */
167+ if (newlen > (size_t )INT_MAX )
168+ newlen = (size_t )INT_MAX ;
169+
149170newdata = (char * )realloc (str -> data ,newlen );
150171if (newdata != NULL )
151172{