} HStore;
 
 /*
- * it's not possible to get more than 2^28 items into an hstore,
- * so we reserve the top few bits of the size field. See hstore_compat.c
- * for one reason why. Some bits are left for future use here.
+ * It's not possible to get more than 2^28 items into an hstore, so we reserve
+ * the top few bits of the size field.  See hstore_compat.c for one reason
+ * why.  Some bits are left for future use here.  MaxAllocSize makes the
+ * practical count limit slightly more than 2^28 / 3, or INT_MAX / 24, the
+ * limit for an hstore full of 4-byte keys and null values.  Therefore, we
+ * don't explicitly check the format-imposed limit.
  */
 #define HS_FLAG_NEWVERSION 0x80000000
 
 #define HS_SETCOUNT(hsp_,c_) ((hsp_)->size_ = (c_) | HS_FLAG_NEWVERSION)
 
 
+/*
+ * "x" comes from an existing HS_COUNT() (as discussed, <= INT_MAX/24) or a
+ * Pairs array length (due to MaxAllocSize, <= INT_MAX/40).  "lenstr" is no
+ * more than INT_MAX, that extreme case arising in hstore_from_arrays().
+ * Therefore, this calculation is limited to about INT_MAX / 5 + INT_MAX.
+ */
 #define HSHRDSIZE      (sizeof(HStore))
 #define CALCDATASIZE(x, lenstr) ( (x) * 2 * sizeof(HEntry) + HSHRDSIZE + (lenstr) )
 
 
 #include "utils/builtins.h"
 #include "utils/json.h"
 #include "utils/lsyscache.h"
+#include "utils/memutils.h"
 #include "utils/typcache.h"
 
 #include "hstore.h"
                PG_RETURN_POINTER(out);
        }
 
+       if (pcount < 0 || pcount > MaxAllocSize / sizeof(Pairs))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                         errmsg("number of pairs (%d) exceeds the maximum allowed (%d)",
+                                        pcount, (int) (MaxAllocSize / sizeof(Pairs)))));
        pairs = palloc(pcount * sizeof(Pairs));
 
        for (i = 0; i < pcount; ++i)
                                          TEXTOID, -1, false, 'i',
                                          &key_datums, &key_nulls, &key_count);
 
+       /* see discussion in hstoreArrayToPairs() */
+       if (key_count > MaxAllocSize / sizeof(Pairs))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                         errmsg("number of pairs (%d) exceeds the maximum allowed (%d)",
+                                        key_count, (int) (MaxAllocSize / sizeof(Pairs)))));
+
        /* value_array might be NULL */
 
        if (PG_ARGISNULL(1))
 
        count = in_count / 2;
 
+       /* see discussion in hstoreArrayToPairs() */
+       if (count > MaxAllocSize / sizeof(Pairs))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                         errmsg("number of pairs (%d) exceeds the maximum allowed (%d)",
+                                        count, (int) (MaxAllocSize / sizeof(Pairs)))));
+
        pairs = palloc(count * sizeof(Pairs));
 
        for (i = 0; i < count; ++i)
                my_extra->ncolumns = ncolumns;
        }
 
+       Assert(ncolumns <= MaxTupleAttributeNumber);            /* thus, no overflow */
        pairs = palloc(ncolumns * sizeof(Pairs));
 
        if (rec)
 
 #include "catalog/pg_type.h"
 #include "funcapi.h"
 #include "utils/builtins.h"
+#include "utils/memutils.h"
 
 #include "hstore.h"
 
                return NULL;
        }
 
+       /*
+        * A text array uses at least eight bytes per element, so any overflow in
+        * "key_count * sizeof(Pairs)" is small enough for palloc() to catch.
+        * However, credible improvements to the array format could invalidate
+        * that assumption.  Therefore, use an explicit check rather than relying
+        * on palloc() to complain.
+        */
+       if (key_count > MaxAllocSize / sizeof(Pairs))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                         errmsg("number of pairs (%d) exceeds the maximum allowed (%d)",
+                                        key_count, (int) (MaxAllocSize / sizeof(Pairs)))));
+
        key_pairs = palloc(sizeof(Pairs) * key_count);
 
        for (i = 0, j = 0; i < key_count; i++)
                PG_RETURN_POINTER(out);
        }
 
+       /* hstoreArrayToPairs() checked overflow */
        out_pairs = palloc(sizeof(Pairs) * nkeys);
        bufsiz = 0;
 
 
 #define ___INT_H__
 
 #include "utils/array.h"
+#include "utils/memutils.h"
 
 /* number ranges for compression */
 #define MAXNUMRANGE 100
 
 #define HDRSIZEQT      offsetof(QUERYTYPE, items)
 #define COMPUTESIZE(size)      ( HDRSIZEQT + (size) * sizeof(ITEM) )
+#define QUERYTYPEMAXITEMS      ((MaxAllocSize - HDRSIZEQT) / sizeof(ITEM))
 #define GETQUERY(x)  ( (x)->items )
 
 /* "type" codes for ITEM */
 
 static void
 findoprnd(ITEM *ptr, int32 *pos)
 {
+       /* since this function recurses, it could be driven to stack overflow. */
+       check_stack_depth();
+
 #ifdef BS_DEBUG
        elog(DEBUG3, (ptr[*pos].type == OPR) ?
                 "%d  %c" : "%d  %d", *pos, ptr[*pos].val);
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                 errmsg("empty query")));
 
+       if (state.num > QUERYTYPEMAXITEMS)
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+               errmsg("number of query items (%d) exceeds the maximum allowed (%d)",
+                          state.num, (int) QUERYTYPEMAXITEMS)));
        commonlen = COMPUTESIZE(state.num);
+
        query = (QUERYTYPE *) palloc(commonlen);
        SET_VARSIZE(query, commonlen);
        query->size = state.num;
 
 
 #include "fmgr.h"
 #include "tsearch/ts_locale.h"
+#include "utils/memutils.h"
 
 typedef struct
 {
 
 #define HDRSIZEQT              MAXALIGN(VARHDRSZ + sizeof(int32))
 #define COMPUTESIZE(size,lenofoperand) ( HDRSIZEQT + (size) * sizeof(ITEM) + (lenofoperand) )
+#define LTXTQUERY_TOO_BIG(size,lenofoperand) \
+       ((size) > (MaxAllocSize - HDRSIZEQT - (lenofoperand)) / sizeof(ITEM))
 #define GETQUERY(x)  (ITEM*)( (char*)(x)+HDRSIZEQT )
 #define GETOPERAND(x)  ( (char*)GETQUERY(x) + ((ltxtquery*)x)->size * sizeof(ITEM) )
 
 
 #include <ctype.h>
 
 #include "ltree.h"
+#include "utils/memutils.h"
 #include "crc32.h"
 
 PG_FUNCTION_INFO_V1(ltree_in);
                ptr += charlen;
        }
 
+       if (num + 1 > MaxAllocSize / sizeof(nodeitem))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                        errmsg("number of levels (%d) exceeds the maximum allowed (%d)",
+                                       num + 1, (int) (MaxAllocSize / sizeof(nodeitem)))));
        list = lptr = (nodeitem *) palloc(sizeof(nodeitem) * (num + 1));
        ptr = buf;
        while (*ptr)
        }
 
        num++;
+       if (num > MaxAllocSize / ITEMSIZE)
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                        errmsg("number of levels (%d) exceeds the maximum allowed (%d)",
+                                       num, (int) (MaxAllocSize / ITEMSIZE))));
        curqlevel = tmpql = (lquery_level *) palloc0(ITEMSIZE * num);
        ptr = buf;
        while (*ptr)
 
 
 #include "crc32.h"
 #include "ltree.h"
+#include "miscadmin.h"
 
 PG_FUNCTION_INFO_V1(ltxtq_in);
 Datum          ltxtq_in(PG_FUNCTION_ARGS);
        int32           lenstack = 0;
        uint16          flag = 0;
 
+       /* since this function recurses, it could be driven to stack overflow */
+       check_stack_depth();
+
        while ((type = gettoken_query(state, &val, &lenval, &strval, &flag)) != END)
        {
                switch (type)
 static void
 findoprnd(ITEM *ptr, int32 *pos)
 {
+       /* since this function recurses, it could be driven to stack overflow. */
+       check_stack_depth();
+
        if (ptr[*pos].type == VAL || ptr[*pos].type == VALTRUE)
        {
                ptr[*pos].left = 0;
                                 errmsg("syntax error"),
                                 errdetail("Empty query.")));
 
-       /* make finish struct */
+       if (LTXTQUERY_TOO_BIG(state.num, state.sumlen))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                                errmsg("ltxtquery is too large")));
        commonlen = COMPUTESIZE(state.num, state.sumlen);
+
        query = (ltxtquery *) palloc(commonlen);
        SET_VARSIZE(query, commonlen);
        query->size = state.num;
 
        char       *s;
        int                     npts;
        int                     size;
+       int                     base_size;
        int                     depth = 0;
 
        if ((npts = pair_count(str, ',')) <= 0)
                depth++;
        }
 
-       size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * npts;
+       base_size = sizeof(path->p[0]) * npts;
+       size = offsetof(PATH, p[0]) + base_size;
+
+       /* Check for integer overflow */
+       if (base_size / npts != sizeof(path->p[0]) || size <= base_size)
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                                errmsg("too many points requested")));
+
        path = (PATH *) palloc(size);
 
        SET_VARSIZE(path, size);
        POLYGON    *poly;
        int                     npts;
        int                     size;
+       int                     base_size;
        int                     isopen;
        char       *s;
 
                                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                          errmsg("invalid input syntax for type polygon: \"%s\"", str)));
 
-       size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * npts;
+       base_size = sizeof(poly->p[0]) * npts;
+       size = offsetof(POLYGON, p[0]) + base_size;
+
+       /* Check for integer overflow */
+       if (base_size / npts != sizeof(poly->p[0]) || size <= base_size)
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                                errmsg("too many points requested")));
+
        poly = (POLYGON *) palloc0(size);       /* zero any holes */
 
        SET_VARSIZE(poly, size);
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                 errmsg("open path cannot be converted to polygon")));
 
+       /*
+        * Never overflows: the old size fit in MaxAllocSize, and the new size is
+        * just a small constant larger.
+        */
        size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * path->npts;
        poly = (POLYGON *) palloc(size);
 
        int                     size;
        int                     i;
 
+       /*
+        * Never overflows: the old size fit in MaxAllocSize, and the new size is
+        * smaller by a small constant.
+        */
        size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * poly->npts;
        path = (PATH *) palloc(size);
 
 
                return query;
        }
 
-       /* Pack the QueryItems in the final TSQuery struct to return to caller */
+       if (TSQUERY_TOO_BIG(list_length(state.polstr), state.sumlen))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                                errmsg("tsquery is too large")));
        commonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen);
+
+       /* Pack the QueryItems in the final TSQuery struct to return to caller */
        query = (TSQuery) palloc0(commonlen);
        SET_VARSIZE(query, commonlen);
        query->size = list_length(state.polstr);
 
        QTN2QTState state;
 
        cntsize(in, &sumlen, &nnode);
+
+       if (TSQUERY_TOO_BIG(nnode, sumlen))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                                errmsg("tsquery is too large")));
        len = COMPUTESIZE(nnode, sumlen);
 
        out = (TSQuery) palloc0(len);
 
 #include "funcapi.h"
 #include "miscadmin.h"
 #include "libpq/pqformat.h"
+#include "postmaster/postmaster.h"
 #include "utils/builtins.h"
+#include "utils/memutils.h"
 #include "utils/snapmgr.h"
 
 
 
 #define TXID_SNAPSHOT_SIZE(nxip) \
        (offsetof(TxidSnapshot, xip) + sizeof(txid) * (nxip))
+#define TXID_SNAPSHOT_MAX_NXIP \
+       ((MaxAllocSize - offsetof(TxidSnapshot, xip)) / sizeof(txid))
 
 /*
  * Epoch values from xact.c
 
        load_xid_epoch(&state);
 
+       /*
+        * Compile-time limits on the procarray (MAX_BACKENDS processes plus
+        * MAX_BACKENDS prepared transactions) guarantee nxip won't be too large.
+        */
+       StaticAssertStmt(MAX_BACKENDS * 2 <= TXID_SNAPSHOT_MAX_NXIP,
+                                        "possible overflow in txid_current_snapshot()");
+
        /* allocate */
        nxip = cur->xcnt;
        size = TXID_SNAPSHOT_SIZE(nxip);
        txid            last = 0;
        int                     nxip;
        int                     i;
-       int                     avail;
-       int                     expect;
        txid            xmin,
                                xmax;
 
-       /*
-        * load nxip and check for nonsense.
-        *
-        * (nxip > avail) check is against int overflows in 'expect'.
-        */
+       /* load and validate nxip */
        nxip = pq_getmsgint(buf, 4);
-       avail = buf->len - buf->cursor;
-       expect = 8 + 8 + nxip * 8;
-       if (nxip < 0 || nxip > avail || expect > avail)
+       if (nxip < 0 || nxip > TXID_SNAPSHOT_MAX_NXIP)
                goto bad_format;
 
        xmin = pq_getmsgint64(buf);
 
                sp = input_string;
        }
 
+       /*
+        * Determine bitlength from input string.  MaxAllocSize ensures a regular
+        * input is small enough, but we must check hex input.
+        */
        slen = strlen(sp);
-       /* Determine bitlength from input string */
        if (bit_not_hex)
                bitlen = slen;
        else
+       {
+               if (slen > VARBITMAXLEN / 4)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                                errmsg("bit string length exceeds the maximum allowed (%d)",
+                                               VARBITMAXLEN)));
                bitlen = slen * 4;
+       }
 
        /*
         * Sometimes atttypmod is not supplied. If it is supplied we need to make
                sp = input_string;
        }
 
+       /*
+        * Determine bitlength from input string.  MaxAllocSize ensures a regular
+        * input is small enough, but we must check hex input.
+        */
        slen = strlen(sp);
-       /* Determine bitlength from input string */
        if (bit_not_hex)
                bitlen = slen;
        else
+       {
+               if (slen > VARBITMAXLEN / 4)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                                errmsg("bit string length exceeds the maximum allowed (%d)",
+                                               VARBITMAXLEN)));
                bitlen = slen * 4;
+       }
 
        /*
         * Sometimes atttypmod is not supplied. If it is supplied we need to make
 /*
  * varbit_out -
  *       Prints the string as bits to preserve length accurately
+ *
+ * XXX varbit_recv() and hex input to varbit_in() can load a value that this
+ * cannot emit.  Consider using hex output for such values.
  */
 Datum
 varbit_out(PG_FUNCTION_ARGS)
        bitlen1 = VARBITLEN(arg1);
        bitlen2 = VARBITLEN(arg2);
 
+       if (bitlen1 > VARBITMAXLEN - bitlen2)
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                                errmsg("bit string length exceeds the maximum allowed (%d)",
+                                               VARBITMAXLEN)));
        bytelen = VARBITTOTALLEN(bitlen1 + bitlen2);
 
        result = (VarBit *) palloc(bytelen);
 
 #define _PG_TSTYPE_H_
 
 #include "fmgr.h"
+#include "utils/memutils.h"
 #include "utils/pg_crc.h"
 
 
  * QueryItems, and lenofoperand is the total length of all operands
  */
 #define COMPUTESIZE(size, lenofoperand) ( HDRSIZETQ + (size) * sizeof(QueryItem) + (lenofoperand) )
+#define TSQUERY_TOO_BIG(size, lenofoperand) \
+       ((size) > (MaxAllocSize - HDRSIZETQ - (lenofoperand)) / sizeof(QueryItem))
 
 /* Returns a pointer to the first QueryItem in a TSQuery */
 #define GETQUERY(x)  ((QueryItem*)( (char*)(x)+HDRSIZETQ ))
 
 #ifndef VARBIT_H
 #define VARBIT_H
 
+#include <limits.h>
+
 #include "fmgr.h"
 
 /*
 /* Number of bytes needed to store a bit string of a given length */
 #define VARBITTOTALLEN(BITLEN) (((BITLEN) + BITS_PER_BYTE-1)/BITS_PER_BYTE + \
                                                                 VARHDRSZ + VARBITHDRSZ)
+/*
+ * Maximum number of bits.  Several code sites assume no overflow from
+ * computing bitlen + X; VARBITTOTALLEN() has the largest such X.
+ */
+#define VARBITMAXLEN           (INT_MAX - BITS_PER_BYTE + 1)
 /* pointer beyond the end of the bit string (like end() in STL containers) */
 #define VARBITEND(PTR)         (((bits8 *) (PTR)) + VARSIZE(PTR))
 /* Mask that will cover exactly one byte, i.e. BITS_PER_BYTE bits */