--- xpdf-3.02/fofi/FoFiTrueType.cc
+++ xpdf-3.02/fofi/FoFiTrueType.cc
@@ -396,7 +396,7 @@
   return nameToGID->lookupInt(name);
 }
 
-Gushort *FoFiTrueType::getCIDToGIDMap(int *nCIDs) {
+Gushort *FoFiTrueType::getCIDToGIDMap(SafeInt *nCIDs) {
   FoFiType1C *ff;
   Gushort *map;
   int i;
@@ -504,7 +504,7 @@
 }
 
 void FoFiTrueType::convertToCIDType2(char *psName,
-				     Gushort *cidMap, int nCIDs,
+				     Gushort *cidMap, SafeInt nCIDs,
 				     GBool needVerticalMetrics,
 				     FoFiOutputFunc outputFunc,
 				     void *outputStream) {
@@ -538,7 +538,7 @@
   (*outputFunc)(outputStream, "  end def\n", 10);
   (*outputFunc)(outputStream, "/GDBytes 2 def\n", 15);
   if (cidMap) {
-    buf = GString::format("/CIDCount {0:d} def\n", nCIDs);
+    buf = GString::format("/CIDCount {0:d} def\n", nCIDs.Int());
     (*outputFunc)(outputStream, buf->getCString(), buf->getLength());
     delete buf;
     if (nCIDs > 32767) {
@@ -577,13 +577,13 @@
     }
   } else {
     // direct mapping - just fill the string(s) with s[i]=i
-    buf = GString::format("/CIDCount {0:d} def\n", nGlyphs);
+    buf = GString::format("/CIDCount {0:d} def\n", nGlyphs.Int());
     (*outputFunc)(outputStream, buf->getCString(), buf->getLength());
     delete buf;
     if (nGlyphs > 32767) {
       (*outputFunc)(outputStream, "/CIDMap [\n", 10);
       for (i = 0; i < nGlyphs; i += 32767) {
-	j = nGlyphs - i < 32767 ? nGlyphs - i : 32767;
+	j = nGlyphs.Int() - i < 32767 ? nGlyphs.Int() - i : 32767;
 	buf = GString::format("  {0:d} string 0 1 {1:d} {{\n", 2 * j, j - 1);
 	(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
 	delete buf;
@@ -599,10 +599,10 @@
       }
       (*outputFunc)(outputStream, "] def\n", 6);
     } else {
-      buf = GString::format("/CIDMap {0:d} string\n", 2 * nGlyphs);
+      buf = GString::format("/CIDMap {0:d} string\n", 2 * nGlyphs.Int());
       (*outputFunc)(outputStream, buf->getCString(), buf->getLength());
       delete buf;
-      buf = GString::format("  0 1 {0:d} {{\n", nGlyphs - 1);
+      buf = GString::format("  0 1 {0:d} {{\n", nGlyphs.Int() - 1);
       (*outputFunc)(outputStream, buf->getCString(), buf->getLength());
       delete buf;
       (*outputFunc)(outputStream,
@@ -654,7 +654,7 @@
   delete ff;
 }
 
-void FoFiTrueType::convertToType0(char *psName, Gushort *cidMap, int nCIDs,
+void FoFiTrueType::convertToType0(char *psName, Gushort *cidMap, SafeInt nCIDs,
 				  GBool needVerticalMetrics,
 				  FoFiOutputFunc outputFunc,
 				  void *outputStream) {
@@ -672,7 +672,7 @@
   delete sfntsName;
 
   // write the descendant Type 42 fonts
-  n = cidMap ? nCIDs : nGlyphs;
+  n = cidMap ? nCIDs.Int() : nGlyphs.Int();
   for (i = 0; i < n; i += 256) {
     (*outputFunc)(outputStream, "10 dict begin\n", 14);
     (*outputFunc)(outputStream, "/FontName /", 11);
@@ -836,12 +836,13 @@
   };
   GBool missingCmap, missingName, missingPost, missingOS2;
   GBool unsortedLoca, badCmapLen, abbrevHMTX;
-  int nZeroLengthTables;
+  SafeInt nZeroLengthTables;
   int nHMetrics, advWidth, lsb;
   TrueTypeLoca *locaTable;
   TrueTypeTable *newTables;
   char *newNameTab, *newCmapTab, *newHHEATab, *newHMTXTab;
-  int nNewTables, cmapIdx, cmapLen, glyfLen, newNameLen, newCmapLen, next;
+  SafeInt nNewTables;
+  int cmapIdx, cmapLen, glyfLen, newNameLen, newCmapLen, next;
   int newHHEALen, newHMTXLen;
   Guint locaChecksum, glyfChecksum, fileChecksum;
   char *tableDir;
@@ -866,7 +867,7 @@
   missingOS2 = seekTable("OS/2") < 0;
 
   // read the loca table, check to see if it's sorted
-  locaTable = (TrueTypeLoca *)gmallocn(nGlyphs + 1, sizeof(TrueTypeLoca));
+  locaTable = (TrueTypeLoca *)gmallocn(nGlyphs + SafeInt(1), sizeof(TrueTypeLoca));
   unsortedLoca = gFalse;
   i = seekTable("loca");
   pos = tables[i].offset;
@@ -943,13 +944,13 @@
   // the same pos value remain in the same order)
   glyfLen = 0; // make gcc happy
   if (unsortedLoca) {
-    qsort(locaTable, nGlyphs + 1, sizeof(TrueTypeLoca),
+    qsort(locaTable, nGlyphs.Int() + 1, sizeof(TrueTypeLoca),
 	  &cmpTrueTypeLocaOffset);
     for (i = 0; i < nGlyphs; ++i) {
       locaTable[i].len = locaTable[i+1].origOffset - locaTable[i].origOffset;
     }
-    locaTable[nGlyphs].len = 0;
-    qsort(locaTable, nGlyphs + 1, sizeof(TrueTypeLoca),
+    locaTable[nGlyphs.Int()].len = 0;
+    qsort(locaTable, nGlyphs.Int() + 1, sizeof(TrueTypeLoca),
 	  &cmpTrueTypeLocaIdx);
     pos = 0;
     for (i = 0; i <= nGlyphs; ++i) {
@@ -992,7 +993,7 @@
   // construct the new name table
   if (name) {
     n = strlen(name);
-    newNameLen = (6 + 4*12 + 2 * (3*n + 7) + 3) & ~3;
+    newNameLen = (6 + 4*12 + 2 * (3*SafeInt(n) + 7) + 3).Int() & ~3;
     newNameTab = (char *)gmalloc(newNameLen);
     memset(newNameTab, 0, newNameLen);
     newNameTab[0] = 0;		// format selector
@@ -1097,11 +1098,11 @@
     for (i = 0; i < newHHEALen; ++i) {
       newHHEATab[i] = getU8(pos++, &ok);
     }
-    newHHEATab[34] = nGlyphs >> 8;
-    newHHEATab[35] = nGlyphs & 0xff;
+    newHHEATab[34] = nGlyphs.Int() >> 8;
+    newHHEATab[35] = nGlyphs.Int() & 0xff;
     i = seekTable("hmtx");
     pos = tables[i].offset;
-    newHMTXLen = 4 * nGlyphs;
+    newHMTXLen = (4 * nGlyphs).Int();
     newHMTXTab = (char *)gmalloc(newHMTXLen);
     advWidth = 0;
     for (i = 0; i < nHMetrics; ++i) {
@@ -1157,7 +1158,7 @@
       } else if (newTables[j].tag == cmapTag && badCmapLen) {
 	newTables[j].len = cmapLen;
       } else if (newTables[j].tag == locaTag && unsortedLoca) {
-	newTables[j].len = (nGlyphs + 1) * (locaFmt ? 4 : 2);
+	newTables[j].len = (nGlyphs.Int() + 1) * (locaFmt ? 4 : 2);
 	newTables[j].checksum = locaChecksum;
       } else if (newTables[j].tag == glyfTag && unsortedLoca) {
 	newTables[j].len = glyfLen;
@@ -1218,9 +1219,9 @@
     newTables[j].len = sizeof(os2Tab);
     ++j;
   }
-  qsort(newTables, nNewTables, sizeof(TrueTypeTable),
+  qsort(newTables, nNewTables.Int(), sizeof(TrueTypeTable),
 	&cmpTrueTypeTableTag);
-  pos = 12 + nNewTables * 16;
+  pos = 12 + nNewTables.Int() * 16;
   for (i = 0; i < nNewTables; ++i) {
     newTables[i].offset = pos;
     pos += newTables[i].len;
@@ -1230,20 +1231,20 @@
   }
 
   // write the table directory
-  tableDir = (char *)gmalloc(12 + nNewTables * 16);
+  tableDir = (char *)gmalloc((SafeInt(12) + nNewTables * SafeInt(16)).Int());
   tableDir[0] = 0x00;					// sfnt version
   tableDir[1] = 0x01;
   tableDir[2] = 0x00;
   tableDir[3] = 0x00;
-  tableDir[4] = (char)((nNewTables >> 8) & 0xff);	// numTables
-  tableDir[5] = (char)(nNewTables & 0xff);
-  for (i = -1, t = (Guint)nNewTables; t; ++i, t >>= 1) ;
+  tableDir[4] = (char)((nNewTables.Int() >> 8) & 0xff);	// numTables
+  tableDir[5] = (char)(nNewTables.Int() & 0xff);
+  for (i = -1, t = (Guint)nNewTables.Int(); t; ++i, t >>= 1) ;
   t = 1 << (4 + i);
   tableDir[6] = (char)((t >> 8) & 0xff);		// searchRange
   tableDir[7] = (char)(t & 0xff);
   tableDir[8] = (char)((i >> 8) & 0xff);		// entrySelector
   tableDir[9] = (char)(i & 0xff);
-  t = nNewTables * 16 - t;
+  t = nNewTables.Int() * 16 - t;
   tableDir[10] = (char)((t >> 8) & 0xff);		// rangeShift
   tableDir[11] = (char)(t & 0xff);
   pos = 12;
@@ -1266,11 +1267,11 @@
     tableDir[pos+15] = (char) newTables[i].len;
     pos += 16;
   }
-  (*outputFunc)(outputStream, tableDir, 12 + nNewTables * 16);
+  (*outputFunc)(outputStream, tableDir, 12 + nNewTables.Int() * 16);
 
   // compute the file checksum
   fileChecksum = computeTableChecksum((Guchar *)tableDir,
-				      12 + nNewTables * 16);
+				      12 + nNewTables.Int() * 16);
   for (i = 0; i < nNewTables; ++i) {
     fileChecksum += newTables[i].checksum;
   }
@@ -1458,7 +1459,7 @@
   Guchar tableDir[12 + nT42Tables*16];
   GBool ok;
   Guint checksum;
-  int nNewTables;
+  SafeInt nNewTables;
   int length, pos, glyfPos, i, j, k;
   Guchar vheaTab[36] = {
     0, 1, 0, 0,			// table version number
@@ -1499,7 +1500,7 @@
   // table, cmpTrueTypeLocaPos uses offset as its primary sort key,
   // and idx as its secondary key (ensuring that adjacent entries with
   // the same pos value remain in the same order)
-  locaTable = (TrueTypeLoca *)gmallocn(nGlyphs + 1, sizeof(TrueTypeLoca));
+  locaTable = (TrueTypeLoca *)gmallocn(nGlyphs + SafeInt(1), sizeof(TrueTypeLoca));
   i = seekTable("loca");
   pos = tables[i].offset;
   ok = gTrue;
@@ -1511,13 +1512,13 @@
       locaTable[i].origOffset = 2 * getU16BE(pos + i*2, &ok);
     }
   }
-  qsort(locaTable, nGlyphs + 1, sizeof(TrueTypeLoca),
+  qsort(locaTable, nGlyphs.Int() + 1, sizeof(TrueTypeLoca),
 	&cmpTrueTypeLocaOffset);
   for (i = 0; i < nGlyphs; ++i) {
     locaTable[i].len = locaTable[i+1].origOffset - locaTable[i].origOffset;
   }
-  locaTable[nGlyphs].len = 0;
-  qsort(locaTable, nGlyphs + 1, sizeof(TrueTypeLoca),
+  locaTable[nGlyphs.Int()].len = 0;
+  qsort(locaTable, nGlyphs.Int() + 1, sizeof(TrueTypeLoca),
 	&cmpTrueTypeLocaIdx);
   pos = 0;
   for (i = 0; i <= nGlyphs; ++i) {
@@ -1529,7 +1530,7 @@
   }
 
   // construct the new 'loca' table
-  locaData = (Guchar *)gmallocn(nGlyphs + 1, (locaFmt ? 4 : 2));
+  locaData = (Guchar *)gmallocn(nGlyphs + SafeInt(1), (locaFmt ? 4 : 2));
   for (i = 0; i <= nGlyphs; ++i) {
     pos = locaTable[i].newOffset;
     if (locaFmt) {
@@ -1570,7 +1571,7 @@
 
   // construct the new table headers, including table checksums
   // (pad each table out to a multiple of 4 bytes)
-  pos = 12 + nNewTables*16;
+  pos = 12 + nNewTables.Int()*16;
   k = 0;
   for (i = 0; i < nT42Tables; ++i) {
     length = -1;
@@ -1579,7 +1580,7 @@
       length = 54;
       checksum = computeTableChecksum(headData, 54);
     } else if (i == t42LocaTable) {
-      length = (nGlyphs + 1) * (locaFmt ? 4 : 2);
+      length = (nGlyphs.Int() + 1) * (locaFmt ? 4 : 2);
       checksum = computeTableChecksum(locaData, length);
     } else if (i == t42GlyfTable) {
       length = 0;
@@ -1608,7 +1609,7 @@
 	length = sizeof(vheaTab);
 	checksum = computeTableChecksum(vheaTab, length);
       } else if (needVerticalMetrics && i == t42VmtxTable) {
-	length = 4 + (nGlyphs - 1) * 4;
+	length = (4 + (nGlyphs - 1) * 4).Int();
 	vmtxTab = (Guchar *)gmalloc(length);
 	vmtxTab[0] = advance / 256;
 	vmtxTab[1] = advance % 256;
@@ -1646,13 +1647,13 @@
   tableDir[2] = 0x00;
   tableDir[3] = 0x00;
   tableDir[4] = 0;		// numTables
-  tableDir[5] = nNewTables;
+  tableDir[5] = nNewTables.Int();
   tableDir[6] = 0;		// searchRange
   tableDir[7] = (Guchar)128;
   tableDir[8] = 0;		// entrySelector
   tableDir[9] = 3;
   tableDir[10] = 0;		// rangeShift
-  tableDir[11] = (Guchar)(16 * nNewTables - 128);
+  tableDir[11] = (Guchar)(16 * nNewTables.Int() - 128);
   pos = 12;
   for (i = 0; i < nNewTables; ++i) {
     tableDir[pos   ] = (Guchar)(newTables[i].tag >> 24);
@@ -1675,7 +1676,7 @@
   }
 
   // compute the font checksum and store it in the head table
-  checksum = computeTableChecksum(tableDir, 12 + nNewTables*16);
+  checksum = computeTableChecksum(tableDir, 12 + nNewTables.Int()*16);
   for (i = 0; i < nNewTables; ++i) {
     checksum += newTables[i].checksum;
   }
@@ -1695,14 +1696,14 @@
   }
 
   // write the table directory
-  dumpString(tableDir, 12 + nNewTables*16, outputFunc, outputStream);
+  dumpString(tableDir, 12 + nNewTables.Int()*16, outputFunc, outputStream);
 
   // write the tables
   for (i = 0; i < nNewTables; ++i) {
     if (i == t42HeadTable) {
       dumpString(headData, 54, outputFunc, outputStream);
     } else if (i == t42LocaTable) {
-      length = (nGlyphs + 1) * (locaFmt ? 4 : 2);
+      length = (nGlyphs.Int() + 1) * (locaFmt ? 4 : 2);
       dumpString(locaData, length, outputFunc, outputStream);
     } else if (i == t42GlyfTable) {
       glyfPos = tables[seekTable("glyf")].offset;
@@ -1909,7 +1910,7 @@
       parsedOk = gFalse;
       return;
     }
-    if (tables[i].len < (nGlyphs + 1) * (locaFmt ? 4 : 2)) {
+    if (tables[i].len < (nGlyphs.Int() + 1) * (locaFmt ? 4 : 2)) {
       nGlyphs = tables[i].len / (locaFmt ? 4 : 2) - 1;
     }
     for (j = 0; j <= nGlyphs; ++j) {
@@ -1958,7 +1959,7 @@
       goto err;
     }
     if (n > nGlyphs) {
-      n = nGlyphs;
+      n = nGlyphs.Int();
     }
     stringIdx = 0;
     stringPos = tablePos + 34 + 2*n;
--- xpdf-3.02/fofi/FoFiTrueType.h
+++ xpdf-3.02/fofi/FoFiTrueType.h
@@ -66,7 +66,7 @@
   // Return the mapping from CIDs to GIDs, and return the number of
   // CIDs in *<nCIDs>.  This is only useful for CID fonts.  (Only
   // useful for OpenType CFF fonts.)
-  Gushort *getCIDToGIDMap(int *nCIDs);
+  Gushort *getCIDToGIDMap(SafeInt *nCIDs);
 
   // Returns the least restrictive embedding licensing right (as
   // defined by the TrueType spec):
@@ -103,7 +103,7 @@
   // name (so we don't need to depend on the 'name' table in the
   // font).  The <cidMap> array maps CIDs to GIDs; it has <nCIDs>
   // entries.  (Not useful for OpenType CFF fonts.)
-  void convertToCIDType2(char *psName, Gushort *cidMap, int nCIDs,
+  void convertToCIDType2(char *psName, Gushort *cidMap, SafeInt nCIDs,
 			 GBool needVerticalMetrics,
 			 FoFiOutputFunc outputFunc, void *outputStream);
 
@@ -118,7 +118,7 @@
   // PostScript font name (so we don't need to depend on the 'name'
   // table in the font).  The <cidMap> array maps CIDs to GIDs; it has
   // <nCIDs> entries.  (Not useful for OpenType CFF fonts.)
-  void convertToType0(char *psName, Gushort *cidMap, int nCIDs,
+  void convertToType0(char *psName, Gushort *cidMap, SafeInt nCIDs,
 		      GBool needVerticalMetrics,
 		      FoFiOutputFunc outputFunc, void *outputStream);
 
@@ -159,10 +159,10 @@
   int seekTable(char *tag);
 
   TrueTypeTable *tables;
-  int nTables;
+  SafeInt nTables;
   TrueTypeCmap *cmaps;
   int nCmaps;
-  int nGlyphs;
+  SafeInt nGlyphs;
   int locaFmt;
   int bbox[4];
   GHash *nameToGID;
--- xpdf-3.02/fofi/FoFiType1C.cc
+++ xpdf-3.02/fofi/FoFiType1C.cc
@@ -101,9 +101,10 @@
   return encoding;
 }
 
-Gushort *FoFiType1C::getCIDToGIDMap(int *nCIDs) {
+Gushort *FoFiType1C::getCIDToGIDMap(SafeInt *nCIDs) {
   Gushort *map;
-  int n, i;
+  SafeInt n;
+  int i;
 
   // a CID font's top dict has ROS as the first operator
   if (topDict.firstOp != 0x0c1e) {
@@ -121,7 +122,7 @@
   }
   ++n;
   map = (Gushort *)gmallocn(n, sizeof(Gushort));
-  memset(map, 0, n * sizeof(Gushort));
+  memset(map, 0, n.Int() * sizeof(Gushort));
   for (i = 0; i < nGlyphs; ++i) {
     map[charset[i]] = i;
   }
@@ -437,7 +438,8 @@
   int *charStringOffsets;
   Type1CIndex subrIdx;
   Type1CIndexVal val;
-  int nCIDs, gdBytes;
+  SafeInt nCIDs;
+  int gdBytes;
   GString *buf;
   char buf2[256];
   GBool ok;
@@ -460,7 +462,7 @@
 
   // build the charstrings
   charStrings = new GString();
-  charStringOffsets = (int *)gmallocn(nCIDs + 1, sizeof(int));
+  charStringOffsets = (int *)gmallocn(nCIDs + SafeInt(1), sizeof(int));
   for (i = 0; i < nCIDs; ++i) {
     charStringOffsets[i] = charStrings->getLength();
     if ((gid = cidMap[i]) >= 0) {
@@ -476,13 +478,13 @@
       }
     }
   }
-  charStringOffsets[nCIDs] = charStrings->getLength();
+  charStringOffsets[nCIDs.Int()] = charStrings->getLength();
 
   // compute gdBytes = number of bytes needed for charstring offsets
   // (offset size needs to account for the charstring offset table,
   // with a worst case of five bytes per entry, plus the charstrings
   // themselves)
-  i = (nCIDs + 1) * 5 + charStrings->getLength();
+  i = (nCIDs.Int() + 1) * 5 + charStrings->getLength();
   if (i < 0x100) {
     gdBytes = 1;
   } else if (i < 0x10000) {
@@ -547,7 +549,7 @@
   (*outputFunc)(outputStream, "end def\n", 8);
 
   // CIDFont-specific entries
-  buf = GString::format("/CIDCount {0:d} def\n", nCIDs);
+  buf = GString::format("/CIDCount {0:d} def\n", nCIDs.Int());
   (*outputFunc)(outputStream, buf->getCString(), buf->getLength());
   delete buf;
   (*outputFunc)(outputStream, "/FDBytes 1 def\n", 15);
@@ -565,7 +567,7 @@
   }
 
   // FDArray entry
-  buf = GString::format("/FDArray {0:d} array\n", nFDs);
+  buf = GString::format("/FDArray {0:d} array\n", nFDs.Int());
   (*outputFunc)(outputStream, buf->getCString(), buf->getLength());
   delete buf;
   for (i = 0; i < nFDs; ++i) {
@@ -708,7 +710,7 @@
   (*outputFunc)(outputStream, "def\n", 4);
 
   // start the binary section
-  offset = (nCIDs + 1) * (1 + gdBytes);
+  offset = (nCIDs.Int() + 1) * (1 + gdBytes);
   buf = GString::format("(Hex) {0:d} StartData\n",
 			offset + charStrings->getLength());
   (*outputFunc)(outputStream, buf->getCString(), buf->getLength());
@@ -761,7 +763,7 @@
   int *cidMap;
   Type1CIndex subrIdx;
   Type1CIndexVal val;
-  int nCIDs;
+  SafeInt nCIDs;
   GString *buf;
   Type1CEexecBuf eb;
   GBool ok;
--- xpdf-3.02/fofi/FoFiType1C.h
+++ xpdf-3.02/fofi/FoFiType1C.h
@@ -151,7 +151,7 @@
 
   // Return the mapping from CIDs to GIDs, and return the number of
   // CIDs in *<nCIDs>.  This is only useful for CID fonts.
-  Gushort *getCIDToGIDMap(int *nCIDs);
+  Gushort *getCIDToGIDMap(SafeInt *nCIDs);
 
   // Convert to a Type 1 font, suitable for embedding in a PostScript
   // file.  This is only useful with 8-bit fonts.  If <newEncoding> is
@@ -216,7 +216,7 @@
   Type1CPrivateDict *privateDicts;
 
   int nGlyphs;
-  int nFDs;
+  SafeInt nFDs;
   Guchar *fdSelect;
   Gushort *charset;
   int gsubrBias;
--- xpdf-3.02/goo/GHash.cc
+++ xpdf-3.02/goo/GHash.cc
@@ -311,7 +311,8 @@
 void GHash::expand() {
   GHashBucket **oldTab;
   GHashBucket *p;
-  int oldSize, h, i;
+  int h, i;
+  SafeInt oldSize;
 
   oldSize = size;
   oldTab = tab;
@@ -365,7 +366,7 @@
   for (p = key->getCString(), i = 0; i < key->getLength(); ++p, ++i) {
     h = 17 * h + (int)(*p & 0xff);
   }
-  return (int)(h % size);
+  return (int)(h % size.Int());
 }
 
 int GHash::hash(char *key) {
@@ -376,5 +377,5 @@
   for (p = key; *p; ++p) {
     h = 17 * h + (int)(*p & 0xff);
   }
-  return (int)(h % size);
+  return (int)(h % size.Int());
 }
--- xpdf-3.02/goo/GHash.h
+++ xpdf-3.02/goo/GHash.h
@@ -55,7 +55,7 @@
   int hash(char *key);
 
   GBool deleteKeys;		// set if key strings should be deleted
-  int size;			// number of buckets
+  SafeInt size;			// number of buckets
   int len;			// number of entries
   GHashBucket **tab;
 };
--- xpdf-3.02/goo/GList.cc
+++ xpdf-3.02/goo/GList.cc
@@ -43,7 +43,7 @@
   if (length >= size) {
     expand();
   }
-  data[length++] = p;
+  data[(length++).Int()] = p;
 }
 
 void GList::append(GList *list) {
@@ -53,7 +53,7 @@
     expand();
   }
   for (i = 0; i < list->length; ++i) {
-    data[length++] = list->data[i];
+    data[(length++).Int()] = list->data[i];
   }
 }
 
@@ -62,7 +62,7 @@
     expand();
   }
   if (i < length) {
-    memmove(data+i+1, data+i, (length - i) * sizeof(void *));
+    memmove(data+i+1, data+i, (length.Int() - i) * sizeof(void *));
   }
   data[i] = p;
   ++length;
@@ -73,7 +73,7 @@
 
   p = data[i];
   if (i < length - 1) {
-    memmove(data+i, data+i+1, (length - i - 1) * sizeof(void *));
+    memmove(data+i, data+i+1, (length.Int() - i - 1) * sizeof(void *));
   }
   --length;
   if (size - length >= ((inc > 0) ? inc : size/2)) {
@@ -83,7 +83,7 @@
 }
 
 void GList::sort(int (*cmp)(const void *obj1, const void *obj2)) {
-  qsort(data, length, sizeof(void *), cmp);
+  qsort(data, length.Int(), sizeof(void *), cmp);
 }
 
 void GList::expand() {
--- xpdf-3.02/goo/GList.h
+++ xpdf-3.02/goo/GList.h
@@ -16,6 +16,7 @@
 #endif
 
 #include "gtypes.h"
+#include "gmem.h"
 
 //------------------------------------------------------------------------
 // GList
@@ -36,7 +37,7 @@
   //----- general
 
   // Get the number of elements.
-  int getLength() { return length; }
+  int getLength() { return length.Int(); }
 
   //----- ordered list support
 
@@ -76,9 +77,9 @@
   void shrink();
 
   void **data;			// the list elements
-  int size;			// size of data array
-  int length;			// number of elements on list
-  int inc;			// allocation increment
+  SafeInt size;			// size of data array
+  SafeInt length;		// number of elements on list
+  SafeInt inc;			// allocation increment
 };
 
 #define deleteGList(list, T)                        \
--- xpdf-3.02/goo/GString.cc
+++ xpdf-3.02/goo/GString.cc
@@ -224,7 +224,8 @@
 
 GString *GString::appendfv(char *fmt, va_list argList) {
   GStringFormatArg *args;
-  int argsLen, argsSize;
+  int argsLen; 
+  SafeInt argsSize;
   GStringFormatArg arg;
   int idx, width, prec;
   GBool reverseAlign, zeroFill;
--- xpdf-3.02/goo/gmem.cc
+++ xpdf-3.02/goo/gmem.cc
@@ -186,14 +186,335 @@
 #endif
 }
 
-void *gmallocn(int nObjs, int objSize) GMEM_EXCEP {
-  int n;
+SafeInt::SafeInt(const long long int cA) 
+{  
+  if (cA < -INT_MAX || INT_MAX < cA) 
+    integer_overflow("SafeInt::SafeInt(long long): "); 
+  c = cA;
+}
+ 
+SafeInt::SafeInt()
+{  }
+  
+SafeInt::SafeInt(const SafeInt& copy): c(copy.c) 
+{  }
+
+SafeInt SafeInt::create(const long long int cA) 
+{ 
+  return SafeInt(cA);
+}
+
+int SafeInt::Int(void) const
+{
+  return c;
+}
+
+void SafeInt::integer_overflow(const char * prefix)
+{ 
+  fprintf(stderr, "error: %sinteger overflow", prefix);  
+  exit (1); 
+}
+
+void SafeInt::division_by_zero(const char * prefix)
+{
+  fprintf(stderr, "error: %sdivide by zero", prefix);
+  exit(1);
+}
+
+void SafeInt::shift_is_negative(const char * prefix)
+{
+  fprintf(stderr, "warning: %sbitwise shift amount is negative", prefix);
+}
+
+SafeInt& SafeInt::operator=(const int& cA)
+{
+  *this = SafeInt(cA);
+  return *this;
+}
+
+bool SafeInt::operator==(const SafeInt& right) const
+{
+  return c == right.c;
+}
+
+bool SafeInt::operator!=(const SafeInt& right) const
+{
+  return c != right.c;
+}
+
+bool SafeInt::operator<(const SafeInt& right) const
+{ 
+  return c < right.c; 
+}
+
+bool SafeInt::operator<=(const SafeInt& right) const
+{ 
+  return c <= right.c; 
+}
+
+bool SafeInt::operator>(const SafeInt& right) const
+{ 
+  return c > right.c; 
+}
+
+bool SafeInt::operator>=(const SafeInt& right) const
+{ 
+  return c >= right.c; 
+}
+
+bool SafeInt::operator==(const int& right) const
+{
+  return c == right;
+}
+
+bool SafeInt::operator!=(const int& right) const
+{
+  return c != right;
+}
+
+bool SafeInt::operator<(const int& right) const
+{
+  return c < right;
+}
+
+bool SafeInt::operator<=(const int& right) const
+{
+  return c <= right;
+}
+
+bool SafeInt::operator>(const int& right) const
+{
+  return c > right;
+}
+
+bool SafeInt::operator>=(const int& right) const
+{
+  return c >= right;
+}
+
+bool operator==(const int& left, const SafeInt& right)
+{ 
+  return left == right.c; 
+}
+
+bool operator!=(const int& left, const SafeInt& right)
+{
+  return left != right.c;
+}
+
+bool operator<(const int& left, const SafeInt& right)
+{
+  return left < right.c;
+}
+
+bool operator<=(const int& left, const SafeInt& right)
+{
+  return left <= right.c;
+}
+
+bool operator>(const int& left, const SafeInt& right)
+{
+  return left > right.c;
+}
+
+bool operator>=(const int& left, const SafeInt& right)
+{
+  return left >= right.c;
+}
+
+SafeInt SafeInt::operator+() const 
+{ 
+  return SafeInt(*this); 
+}
+
+SafeInt SafeInt::operator+(const SafeInt& right) const
+{ 
+  if (c*right.c > 0 &&
+      ((c > 0 && c > INT_MAX - right.c) || 
+       (c < 0 && c < -INT_MAX - right.c))) 
+    integer_overflow("SafeInt::operator+(): ");
+  return SafeInt(c + right.c); 
+}
+
+SafeInt SafeInt::operator-() const
+{ 
+  return SafeInt(-c); 
+}
+
+SafeInt SafeInt::operator-(const SafeInt& right) const
+{ 
+  return *this + (-right); 
+}
+
+SafeInt SafeInt::operator*(const SafeInt& right) const
+{ 
+  if (right.c != 0 && c*right.c/right.c != c) 
+    integer_overflow("SafeInt::operator*(): ");
+  return SafeInt(c * right.c); 
+}
+
+SafeInt SafeInt::operator/(const SafeInt& right) const
+{ 
+  return SafeInt(c / right.c); 
+}
+
+SafeInt SafeInt::operator%(const SafeInt& right) const
+{
+  return SafeInt(c % right.c);
+}
+
+SafeInt SafeInt::operator/(const int& right) const
+{
+  if (right == 0)
+    division_by_zero("SafeInt::operator/(): ");
+  return SafeInt(c / right);
+}
+
+SafeInt SafeInt::operator%(const int& right) const
+{
+  return SafeInt(c % right);
+}
+
+SafeInt& SafeInt::operator+=(const SafeInt& right) 
+{ 
+  *this = *this + right; 
+  return *this; 
+}
+
+SafeInt& SafeInt::operator-=(const SafeInt& right) 
+{ 
+  *this = *this - right; 
+  return *this; 
+}
+
+SafeInt& SafeInt::operator*=(const SafeInt& right)
+{ 
+  *this = *this * right; 
+  return *this; 
+}
+
+SafeInt& SafeInt::operator/=(const SafeInt& right)
+{ 
+  *this = *this / right; 
+  return *this; 
+}
+
+SafeInt& SafeInt::operator%=(const SafeInt& right)
+{
+  *this = *this % right;
+  return *this;
+}
+
+SafeInt& SafeInt::operator/=(const int& right)
+{
+  *this = *this / right;
+  return *this;
+}
+
+SafeInt& SafeInt::operator%=(const int& right)
+{
+  *this = *this % right;
+  return *this;
+}
+
+SafeInt& SafeInt::operator++()
+{ 
+  *this += one; 
+  return *this; 
+}
+
+SafeInt SafeInt::operator++(int)
+{ 
+  SafeInt res(*this); 
+  *this += one; 
+  return res; 
+}
+
+SafeInt& SafeInt::operator--()
+{ 
+  *this -= one; 
+  return *this; 
+}
+
+SafeInt SafeInt::operator--(int)
+{ 
+  SafeInt res(*this); 
+  *this -= one; 
+  return res; 
+}
+
+SafeInt operator+(const int& left, const SafeInt& right)
+{
+  return SafeInt(left) + right;
+}
+
+SafeInt operator-(const int& left, const SafeInt& right)
+{
+  return SafeInt(left) - right;
+}
+
+SafeInt operator*(const int& left, const SafeInt& right)
+{
+  return SafeInt(left) * right;
+}
+
+SafeInt operator/(const int& left, const SafeInt& right)
+{
+  return SafeInt(left) / right;
+}
+
+SafeInt operator%(const int& left, const SafeInt& right)
+{
+  return SafeInt(left) % right;
+}
+
+SafeInt SafeInt::operator<<(const int offset)
+{
+  if (offset < 0)
+  {
+    shift_is_negative("SafeInt::operator<<(): ");
+    return *this >> -offset;
+  }
+
+  if ((c & (-1 << (sizeof(c)*8 - offset))) != 0)
+    integer_overflow("SafeInt::operator<<(): ");
+ return SafeInt(c << offset);
+}
+
+SafeInt SafeInt::operator>>(const int offset)
+{
+  if (offset < 0)
+  {
+    shift_is_negative("SafeInt::operator>>(): ");
+    return *this << -offset;
+  }
+
+  return SafeInt(c >> offset);
+}
+
+SafeInt& SafeInt::operator<<=(const int offset)
+{
+  *this = *this << offset;
+  return *this; 
+}
+
+SafeInt& SafeInt::operator>>=(const int offset)
+{
+  *this = *this >> offset;
+  return *this;
+}
+
+const SafeInt SafeInt::zero = SafeInt(0);
+const SafeInt SafeInt::one = SafeInt(1);
+
+void *gmallocn(SafeInt nObjs, SafeInt objSize) GMEM_EXCEP {
+  SafeInt n;
 
-  if (nObjs == 0) {
+  if (nObjs == SafeInt::create(0)) {
     return NULL;
   }
   n = nObjs * objSize;
-  if (objSize <= 0 || nObjs < 0 || nObjs >= INT_MAX / objSize) {
+  if (objSize <= SafeInt::create(0) || nObjs < SafeInt::create(0)) {
 #if USE_EXCEPTIONS
     throw GMemException();
 #else
@@ -201,20 +522,20 @@
     exit(1);
 #endif
   }
-  return gmalloc(n);
+  return gmalloc(n.Int());
 }
 
-void *greallocn(void *p, int nObjs, int objSize) GMEM_EXCEP {
-  int n;
+void *greallocn(void *p, SafeInt nObjs, SafeInt objSize) GMEM_EXCEP {
+  SafeInt n;
 
-  if (nObjs == 0) {
+  if (nObjs == SafeInt::create(0)) {
     if (p) {
       gfree(p);
     }
     return NULL;
   }
   n = nObjs * objSize;
-  if (objSize <= 0 || nObjs < 0 || nObjs >= INT_MAX / objSize) {
+  if (objSize <= SafeInt::create(0) || nObjs < SafeInt::create(0)) {
 #if USE_EXCEPTIONS
     throw GMemException();
 #else
@@ -222,7 +543,7 @@
     exit(1);
 #endif
   }
-  return grealloc(p, n);
+  return grealloc(p, n.Int());
 }
 
 void gfree(void *p) {
--- xpdf-3.02/goo/gmem.h
+++ xpdf-3.02/goo/gmem.h
@@ -28,6 +28,98 @@
 
 #endif // USE_EXCEPTIONS
 
+class SafeInt
+{
+  int c;
+ 
+public:
+  SafeInt();
+  SafeInt(const SafeInt& copy);
+  SafeInt(const long long int cA);
+  static SafeInt create(const long long int cA);
+  int Int(void) const;
+
+  const static SafeInt zero;
+  const static SafeInt one;
+  
+  static void integer_overflow(const char * prefix = NULL);
+  static void division_by_zero(const char * prefix = NULL);
+  static void shift_is_negative(const char * prefix = NULL);
+
+  SafeInt& operator=(const int& cA);
+
+  bool operator==(const SafeInt& right) const;
+  bool operator!=(const SafeInt& right) const;
+  bool operator<(const SafeInt& right) const;
+  bool operator<=(const SafeInt& right) const;
+  bool operator >(const SafeInt& right) const;
+  bool operator >=(const SafeInt& right) const;
+
+  bool operator==(const int& right) const;
+  bool operator!=(const int& right) const;
+  bool operator<(const int& right) const;
+  bool operator<=(const int& right) const;
+  bool operator >(const int& right) const;
+  bool operator >=(const int& right) const;
+
+  friend bool operator ==(const int &left, const SafeInt& right);
+  friend bool operator !=(const int &left, const SafeInt& right);
+  friend bool operator <(const int &left, const SafeInt& right);
+  friend bool operator <=(const int &left, const SafeInt& right);
+  friend bool operator >(const int &left, const SafeInt& right);
+  friend bool operator >=(const int &left, const SafeInt& right);
+
+  SafeInt operator+() const; 
+  SafeInt operator+(const SafeInt& right) const;
+  SafeInt operator-() const;
+  SafeInt operator-(const SafeInt& right) const;
+  SafeInt operator*(const SafeInt& right) const;
+  SafeInt operator/(const SafeInt& right) const;
+  SafeInt operator%(const SafeInt& right) const;
+
+  SafeInt operator/(const int& right) const;
+  SafeInt operator%(const int& right) const;
+
+  SafeInt& operator+=(const SafeInt& right); 
+  SafeInt& operator-=(const SafeInt& right); 
+  SafeInt& operator*=(const SafeInt& right);
+  SafeInt& operator/=(const SafeInt& right);
+  SafeInt& operator%=(const SafeInt& right);
+
+  SafeInt& operator/=(const int& right);
+  SafeInt& operator%=(const int& right);
+
+  friend SafeInt operator+(const int& left, const SafeInt& right);
+  friend SafeInt operator-(const int& left, const SafeInt& right);
+  friend SafeInt operator*(const int& left, const SafeInt& right);
+  friend SafeInt operator/(const int& left, const SafeInt& right);
+  friend SafeInt operator%(const int& left, const SafeInt& right);
+
+  SafeInt& operator++();
+  SafeInt operator++(int);
+  SafeInt& operator--();
+  SafeInt operator--(int);
+
+  SafeInt operator<<(const int offset);
+  SafeInt operator>>(const int offset);
+
+  SafeInt& operator<<=(const int offset);
+  SafeInt& operator>>=(const int offset);
+};
+
+bool operator==(const int& left, const SafeInt& right);
+bool operator!=(const int& left, const SafeInt& right);
+bool operator<(const int& left, const SafeInt& right);
+bool operator<=(const int& left, const SafeInt& right);
+bool operator>(const int& left, const SafeInt& right);
+bool operator>=(const int& left, const SafeInt& right);
+
+SafeInt operator+(const int& left, const SafeInt& right);
+SafeInt operator-(const int& left, const SafeInt& right);
+SafeInt operator*(const int& left, const SafeInt& right);
+SafeInt operator/(const int& left, const SafeInt& right);
+SafeInt operator%(const int& left, const SafeInt& right);
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -50,8 +142,8 @@
  * bytes, but there is an additional error check that the total size
  * doesn't overflow an int.
  */
-extern void *gmallocn(int nObjs, int objSize) GMEM_EXCEP;
-extern void *greallocn(void *p, int nObjs, int objSize) GMEM_EXCEP;
+extern void *gmallocn(SafeInt nObjs, SafeInt objSize) GMEM_EXCEP;
+extern void *greallocn(void *p, SafeInt nObjs, SafeInt objSize) GMEM_EXCEP;
 
 /*
  * Same as free, but checks for and ignores NULL pointers.
--- xpdf-3.02/splash/Splash.cc
+++ xpdf-3.02/splash/Splash.cc
@@ -1912,7 +1912,7 @@
   xq = w % scaledWidth;
 
   // allocate pixel buffer
-  pixBuf = (SplashColorPtr)gmalloc((yp + 1) * w);
+  pixBuf = (SplashColorPtr)gmalloc(((SafeInt(yp) + SafeInt(1)) * SafeInt(w)).Int());
 
   // initialize the pixel pipe
   pipeInit(&pipe, 0, 0, state->fillPattern, NULL, state->fillAlpha,
@@ -2208,9 +2208,9 @@
   xq = w % scaledWidth;
 
   // allocate pixel buffers
-  colorBuf = (SplashColorPtr)gmalloc((yp + 1) * w * nComps);
+  colorBuf = (SplashColorPtr)gmalloc(((SafeInt(yp) + SafeInt(1)) * SafeInt(w) * SafeInt(nComps)).Int());
   if (srcAlpha) {
-    alphaBuf = (Guchar *)gmalloc((yp + 1) * w);
+    alphaBuf = (Guchar *)gmalloc(((SafeInt(yp) + SafeInt(1)) * SafeInt(w)).Int());
   } else {
     alphaBuf = NULL;
   }
@@ -3064,7 +3064,7 @@
     // draw the start cap
     pathOut->moveTo(pathIn->pts[i].x - wdy, pathIn->pts[i].y + wdx);
     if (i == subpathStart) {
-      firstPt = pathOut->length - 1;
+      firstPt = pathOut->length.Int() - 1;
     }
     if (first && !closed) {
       switch (state->lineCap) {
@@ -3099,7 +3099,7 @@
     }
 
     // draw the left side of the segment rectangle
-    left2 = pathOut->length - 1;
+    left2 = pathOut->length.Int() - 1;
     pathOut->lineTo(pathIn->pts[i+1].x + wdy, pathIn->pts[i+1].y - wdx);
 
     // draw the end cap
@@ -3136,11 +3136,11 @@
     }
 
     // draw the right side of the segment rectangle
-    right2 = pathOut->length - 1;
+    right2 = pathOut->length.Int() - 1;
     pathOut->close();
 
     // draw the join
-    join2 = pathOut->length;
+    join2 = pathOut->length.Int();
     if (!last || closed) {
       crossprod = dx * dyNext - dy * dxNext;
       dotprod = -(dx * dxNext + dy * dyNext);
@@ -3254,10 +3254,10 @@
 	if (i >= subpathStart + 2) {
 	  pathOut->addStrokeAdjustHint(left1, right1, left0 + 1, right0);
 	  pathOut->addStrokeAdjustHint(left1, right1,
-				       join0, pathOut->length - 1);
+				       join0, pathOut->length.Int() - 1);
 	} else {
 	  pathOut->addStrokeAdjustHint(left1, right1,
-				       firstPt, pathOut->length - 1);
+				       firstPt, pathOut->length.Int() - 1);
 	}
 	if (closed) {
 	  pathOut->addStrokeAdjustHint(left1, right1, firstPt, leftFirst);
@@ -3266,7 +3266,7 @@
 	  pathOut->addStrokeAdjustHint(leftFirst, rightFirst,
 				       left1 + 1, right1);
 	  pathOut->addStrokeAdjustHint(leftFirst, rightFirst,
-				       join1, pathOut->length - 1);
+				       join1, pathOut->length.Int() - 1);
 	}
       }
     }
--- xpdf-3.02/splash/SplashBitmap.cc
+++ xpdf-3.02/splash/SplashBitmap.cc
@@ -44,13 +44,13 @@
   }
   rowSize += rowPad - 1;
   rowSize -= rowSize % rowPad;
-  data = (SplashColorPtr)gmalloc(rowSize * height);
+  data = (SplashColorPtr)gmallocn(rowSize, height);
   if (!topDown) {
     data += (height - 1) * rowSize;
     rowSize = -rowSize;
   }
   if (alphaA) {
-    alpha = (Guchar *)gmalloc(width * height);
+    alpha = (Guchar *)gmallocn(width, height);
   } else {
     alpha = NULL;
   }
--- xpdf-3.02/splash/SplashClip.cc
+++ xpdf-3.02/splash/SplashClip.cc
@@ -55,7 +55,8 @@
   paths = NULL;
   flags = NULL;
   scanners = NULL;
-  length = size = 0;
+  length = 0;
+  size = 0;
 }
 
 SplashClip::SplashClip(SplashClip *clip) {
@@ -124,7 +125,8 @@
   paths = NULL;
   flags = NULL;
   scanners = NULL;
-  length = size = 0;
+  length = 0;
+  size = 0;
 
   if (x0 < x1) {
     xMin = x0;
--- xpdf-3.02/splash/SplashClip.h
+++ xpdf-3.02/splash/SplashClip.h
@@ -101,7 +101,8 @@
   SplashXPath **paths;
   Guchar *flags;
   SplashXPathScanner **scanners;
-  int length, size;
+  int length;
+  SafeInt size;
 };
 
 #endif
--- xpdf-3.02/splash/SplashFTFont.cc
+++ xpdf-3.02/splash/SplashFTFont.cc
@@ -157,7 +157,7 @@
   FT_Vector offset;
   FT_GlyphSlot slot;
   FT_UInt gid;
-  int rowSize;
+  SafeInt rowSize;
   Guchar *p, *q;
   int i;
 
@@ -210,14 +210,14 @@
   if (aa) {
     rowSize = bitmap->w;
   } else {
-    rowSize = (bitmap->w + 7) >> 3;
+    rowSize = (SafeInt(bitmap->w) + SafeInt(7)) >> 3;
   }
-  bitmap->data = (Guchar *)gmalloc(rowSize * bitmap->h);
+  bitmap->data = (Guchar *)gmallocn(rowSize, bitmap->h);
   bitmap->freeData = gTrue;
   for (i = 0, p = bitmap->data, q = slot->bitmap.buffer;
        i < bitmap->h;
-       ++i, p += rowSize, q += slot->bitmap.pitch) {
-    memcpy(p, q, rowSize);
+       ++i, p += rowSize.Int(), q += slot->bitmap.pitch) {
+    memcpy(p, q, rowSize.Int());
   }
 
   return gTrue;
--- xpdf-3.02/splash/SplashFTFontEngine.cc
+++ xpdf-3.02/splash/SplashFTFontEngine.cc
@@ -91,7 +91,7 @@
 						GBool deleteFile) {
   FoFiType1C *ff;
   Gushort *cidToGIDMap;
-  int nCIDs;
+  SafeInt nCIDs;
   SplashFontFile *ret;
 
   // check for a CFF font
@@ -106,7 +106,7 @@
     nCIDs = 0;
   }
   ret = SplashFTFontFile::loadCIDFont(this, idA, fileName, deleteFile,
-				      cidToGIDMap, nCIDs);
+				      cidToGIDMap, nCIDs.Int());
   if (!ret) {
     gfree(cidToGIDMap);
   }
@@ -119,7 +119,7 @@
   FoFiTrueType *ff;
   GBool isCID;
   Gushort *cidToGIDMap;
-  int nCIDs;
+  SafeInt nCIDs;
   SplashFontFile *ret;
 
   cidToGIDMap = NULL;
@@ -134,7 +134,7 @@
     }
   }
   ret = SplashFTFontFile::loadCIDFont(this, idA, fileName, deleteFile,
-				      cidToGIDMap, nCIDs);
+				      cidToGIDMap, nCIDs.Int());
   if (!ret) {
     gfree(cidToGIDMap);
   }
--- xpdf-3.02/splash/SplashFont.cc
+++ xpdf-3.02/splash/SplashFont.cc
@@ -78,7 +78,7 @@
   cacheTags = (SplashFontCacheTag *)gmallocn(cacheSets * cacheAssoc,
 					     sizeof(SplashFontCacheTag));
   for (i = 0; i < cacheSets * cacheAssoc; ++i) {
-    cacheTags[i].mru = i & (cacheAssoc - 1);
+    cacheTags[i].mru = i & (cacheAssoc.Int() - 1);
   }
 }
 
@@ -106,7 +106,7 @@
   }
 
   // check the cache
-  i = (c & (cacheSets - 1)) * cacheAssoc;
+  i = (c & (cacheSets.Int() - 1)) * cacheAssoc.Int();
   for (j = 0; j < cacheAssoc; ++j) {
     if ((cacheTags[i+j].mru & 0x80000000) &&
 	cacheTags[i+j].c == c &&
@@ -151,7 +151,7 @@
   }
   p = NULL; // make gcc happy
   for (j = 0; j < cacheAssoc; ++j) {
-    if ((cacheTags[i+j].mru & 0x7fffffff) == cacheAssoc - 1) {
+    if ((cacheTags[i+j].mru & 0x7fffffff) == cacheAssoc.Int() - 1) {
       cacheTags[i+j].mru = 0x80000000;
       cacheTags[i+j].c = c;
       cacheTags[i+j].xFrac = (short)xFrac;
--- xpdf-3.02/splash/SplashFont.h
+++ xpdf-3.02/splash/SplashFont.h
@@ -97,8 +97,8 @@
     cacheTags;
   int glyphW, glyphH;		// size of glyph bitmaps
   int glyphSize;		// size of glyph bitmaps, in bytes
-  int cacheSets;		// number of sets in cache
-  int cacheAssoc;		// cache associativity (glyphs per set)
+  SafeInt cacheSets;		// number of sets in cache
+  SafeInt cacheAssoc;		// cache associativity (glyphs per set)
 };
 
 #endif
--- xpdf-3.02/splash/SplashPath.cc
+++ xpdf-3.02/splash/SplashPath.cc
@@ -44,13 +44,13 @@
   size = path->size;
   pts = (SplashPathPoint *)gmallocn(size, sizeof(SplashPathPoint));
   flags = (Guchar *)gmallocn(size, sizeof(Guchar));
-  memcpy(pts, path->pts, length * sizeof(SplashPathPoint));
-  memcpy(flags, path->flags, length * sizeof(Guchar));
+  memcpy(pts, path->pts, length.Int() * sizeof(SplashPathPoint));
+  memcpy(flags, path->flags, length.Int() * sizeof(Guchar));
   curSubpath = path->curSubpath;
   if (path->hints) {
     hintsLength = hintsSize = path->hintsLength;
     hints = (SplashPathHint *)gmallocn(hintsSize, sizeof(SplashPathHint));
-    memcpy(hints, path->hints, hintsLength * sizeof(SplashPathHint));
+    memcpy(hints, path->hints, hintsLength.Int() * sizeof(SplashPathHint));
   } else {
     hints = NULL;
   }
@@ -79,11 +79,11 @@
 void SplashPath::append(SplashPath *path) {
   int i;
 
-  curSubpath = length + path->curSubpath;
-  grow(path->length);
+  curSubpath = length.Int() + path->curSubpath;
+  grow(path->length.Int());
   for (i = 0; i < path->length; ++i) {
-    pts[length] = path->pts[i];
-    flags[length] = path->flags[i];
+    pts[length.Int()] = path->pts[i];
+    flags[length.Int()] = path->flags[i];
     ++length;
   }
 }
@@ -93,10 +93,10 @@
     return splashErrBogusPath;
   }
   grow(1);
-  pts[length].x = x;
-  pts[length].y = y;
-  flags[length] = splashPathFirst | splashPathLast;
-  curSubpath = length++;
+  pts[length.Int()].x = x;
+  pts[length.Int()].y = y;
+  flags[length.Int()] = splashPathFirst | splashPathLast;
+  curSubpath = (length++).Int();
   return splashOk;
 }
 
@@ -104,11 +104,11 @@
   if (noCurrentPoint()) {
     return splashErrNoCurPt;
   }
-  flags[length-1] &= ~splashPathLast;
+  flags[(length-1).Int()] &= ~splashPathLast;
   grow(1);
-  pts[length].x = x;
-  pts[length].y = y;
-  flags[length] = splashPathLast;
+  pts[length.Int()].x = x;
+  pts[length.Int()].y = y;
+  flags[length.Int()] = splashPathLast;
   ++length;
   return splashOk;
 }
@@ -119,19 +119,19 @@
   if (noCurrentPoint()) {
     return splashErrNoCurPt;
   }
-  flags[length-1] &= ~splashPathLast;
+  flags[(length-1).Int()] &= ~splashPathLast;
   grow(3);
-  pts[length].x = x1;
-  pts[length].y = y1;
-  flags[length] = splashPathCurve;
+  pts[length.Int()].x = x1;
+  pts[length.Int()].y = y1;
+  flags[length.Int()] = splashPathCurve;
   ++length;
-  pts[length].x = x2;
-  pts[length].y = y2;
-  flags[length] = splashPathCurve;
+  pts[length.Int()].x = x2;
+  pts[length.Int()].y = y2;
+  flags[length.Int()] = splashPathCurve;
   ++length;
-  pts[length].x = x3;
-  pts[length].y = y3;
-  flags[length] = splashPathLast;
+  pts[length.Int()].x = x3;
+  pts[length.Int()].y = y3;
+  flags[length.Int()] = splashPathLast;
   ++length;
   return splashOk;
 }
@@ -140,28 +140,28 @@
   if (noCurrentPoint()) {
     return splashErrNoCurPt;
   }
-  if (curSubpath == length - 1 ||
-      pts[length - 1].x != pts[curSubpath].x ||
-      pts[length - 1].y != pts[curSubpath].y) {
+  if (curSubpath == length.Int() - 1 ||
+      pts[length.Int() - 1].x != pts[curSubpath].x ||
+      pts[length.Int() - 1].y != pts[curSubpath].y) {
     lineTo(pts[curSubpath].x, pts[curSubpath].y);
   }
   flags[curSubpath] |= splashPathClosed;
-  flags[length - 1] |= splashPathClosed;
-  curSubpath = length;
+  flags[length.Int() - 1] |= splashPathClosed;
+  curSubpath = length.Int();
   return splashOk;
 }
 
 void SplashPath::addStrokeAdjustHint(int ctrl0, int ctrl1,
 				     int firstPt, int lastPt) {
   if (hintsLength == hintsSize) {
-    hintsSize = hintsLength ? 2 * hintsLength : 8;
+    hintsSize = hintsLength.Int() ? 2 * hintsLength : 8;
     hints = (SplashPathHint *)greallocn(hints, hintsSize,
 					sizeof(SplashPathHint));
   }
-  hints[hintsLength].ctrl0 = ctrl0;
-  hints[hintsLength].ctrl1 = ctrl1;
-  hints[hintsLength].firstPt = firstPt;
-  hints[hintsLength].lastPt = lastPt;
+  hints[hintsLength.Int()].ctrl0 = ctrl0;
+  hints[hintsLength.Int()].ctrl1 = ctrl1;
+  hints[hintsLength.Int()].firstPt = firstPt;
+  hints[hintsLength.Int()].lastPt = lastPt;
   ++hintsLength;
 }
 
@@ -178,7 +178,7 @@
   if (noCurrentPoint()) {
     return gFalse;
   }
-  *x = pts[length - 1].x;
-  *y = pts[length - 1].y;
+  *x = pts[length.Int() - 1].x;
+  *y = pts[length.Int() - 1].y;
   return gTrue;
 }
--- xpdf-3.02/splash/SplashPath.h
+++ xpdf-3.02/splash/SplashPath.h
@@ -91,7 +91,7 @@
   void offset(SplashCoord dx, SplashCoord dy);
 
   // Get the points on the path.
-  int getLength() { return length; }
+  int getLength() { return length.Int(); }
   void getPoint(int i, double *x, double *y, Guchar *f)
     { *x = pts[i].x; *y = pts[i].y; *f = flags[i]; }
 
@@ -108,11 +108,11 @@
 
   SplashPathPoint *pts;		// array of points
   Guchar *flags;		// array of flags
-  int length, size;		// length/size of the pts and flags arrays
+  SafeInt length, size;		// length/size of the pts and flags arrays
   int curSubpath;		// index of first point in last subpath
 
   SplashPathHint *hints;	// list of hints
-  int hintsLength, hintsSize;
+  SafeInt hintsLength, hintsSize;
 
   friend class SplashXPath;
   friend class Splash;
--- xpdf-3.02/splash/SplashScreen.cc
+++ xpdf-3.02/splash/SplashScreen.cc
@@ -12,7 +12,6 @@
 
 #include <stdlib.h>
 #include <string.h>
-#include "gmem.h"
 #include "SplashMath.h"
 #include "SplashScreen.h"
 
@@ -61,7 +60,7 @@
     // size must be a power of 2
     for (size = 1; size < params->size; size <<= 1) ;
     mat = (Guchar *)gmallocn(size * size, sizeof(Guchar));
-    buildDispersedMatrix(size/2, size/2, 1, size/2, 1);
+    buildDispersedMatrix((size/2).Int(), (size/2).Int(), 1, (size/2).Int(), 1);
     break;
 
   case splashScreenClustered:
@@ -76,8 +75,8 @@
 
   case splashScreenStochasticClustered:
     // size must be at least 2*r
-    if (params->size < 2 * params->dotRadius) {
-      size = 2 * params->dotRadius;
+    if (SafeInt(params->size) < 2 * SafeInt(params->dotRadius)) {
+      size = 2 * SafeInt(params->dotRadius);
     } else {
       size = params->size;
     }
@@ -118,15 +117,15 @@
 					int delta, int offset) {
   if (delta == 0) {
     // map values in [1, size^2] --> [1, 255]
-    mat[i * size + j] = 1 + (254 * (val - 1)) / (size * size - 1);
+    mat[i * size.Int() + j] = 1 + (254 * (val - 1)) / (size.Int() * size.Int() - 1);
   } else {
     buildDispersedMatrix(i, j,
 			 val, delta / 2, 4*offset);
-    buildDispersedMatrix((i + delta) % size, (j + delta) % size,
+    buildDispersedMatrix((i + delta) % size.Int(), (j + delta) % size.Int(),
 			 val + offset, delta / 2, 4*offset);
-    buildDispersedMatrix((i + delta) % size, j,
+    buildDispersedMatrix((i + delta) % size.Int(), j,
 			 val + 2*offset, delta / 2, 4*offset);
-    buildDispersedMatrix((i + 2*delta) % size, (j + delta) % size,
+    buildDispersedMatrix((i + 2*delta) % size.Int(), (j + delta) % size.Int(),
 			 val + 3*offset, delta / 2, 4*offset);
   }
 }
@@ -135,14 +134,15 @@
   SplashCoord *dist;
   SplashCoord u, v, d;
   Guchar val;
-  int size2, x, y, x1, y1, i;
+  SafeInt size2;
+  int x, y, x1, y1, i;
 
   size2 = size >> 1;
 
   // initialize the threshold matrix
   for (y = 0; y < size; ++y) {
     for (x = 0; x < size; ++x) {
-      mat[y * size + x] = 0;
+      mat[y * size.Int() + x] = 0;
     }
   }
 
@@ -154,22 +154,22 @@
 	u = (SplashCoord)x + 0.5 - 0;
 	v = (SplashCoord)y + 0.5 - 0;
       } else {
-	u = (SplashCoord)x + 0.5 - (SplashCoord)size2;
-	v = (SplashCoord)y + 0.5 - (SplashCoord)size2;
+	u = (SplashCoord)x + 0.5 - (SplashCoord)size2.Int();
+	v = (SplashCoord)y + 0.5 - (SplashCoord)size2.Int();
       }
-      dist[y * size2 + x] = u*u + v*v;
+      dist[y * size2.Int() + x] = u*u + v*v;
     }
   }
   for (y = 0; y < size2; ++y) {
     for (x = 0; x < size2; ++x) {
       if (x < y) {
 	u = (SplashCoord)x + 0.5 - 0;
-	v = (SplashCoord)y + 0.5 - (SplashCoord)size2;
+	v = (SplashCoord)y + 0.5 - (SplashCoord)size2.Int();
       } else {
-	u = (SplashCoord)x + 0.5 - (SplashCoord)size2;
+	u = (SplashCoord)x + 0.5 - (SplashCoord)size2.Int();
 	v = (SplashCoord)y + 0.5 - 0;
       }
-      dist[(size2 + y) * size2 + x] = u*u + v*v;
+      dist[(size2.Int() + y) * size2.Int() + x] = u*u + v*v;
     }
   }
 
@@ -181,22 +181,22 @@
     d = -1;
     for (y = 0; y < size; ++y) {
       for (x = 0; x < size2; ++x) {
-	if (mat[y * size + x] == 0 &&
-	    dist[y * size2 + x] > d) {
+	if (mat[y * size.Int() + x] == 0 &&
+	    dist[y * size2.Int() + x] > d) {
 	  x1 = x;
 	  y1 = y;
-	  d = dist[y1 * size2 + x1];
+	  d = dist[y1 * size2.Int() + x1];
 	}
       }
     }
     // map values in [0, 2*size*size2-1] --> [1, 255]
-    val = 1 + (254 * (2*i)) / (2*size*size2 - 1);
-    mat[y1 * size + x1] = val;
-    val = 1 + (254 * (2*i+1)) / (2*size*size2 - 1);
-    if (y1 < size2) {
-      mat[(y1 + size2) * size + x1 + size2] = val;
+    val = 1 + (254 * (2*i)) / (2*size.Int()*size2.Int() - 1);
+    mat[y1 * size.Int() + x1] = val;
+    val = 1 + (254 * (2*i+1)) / (2*size.Int()*size2.Int() - 1);
+    if (y1 < size2.Int()) {
+      mat[(y1 + size2.Int()) * size.Int() + x1 + size2.Int()] = val;
     } else {
-      mat[(y1 - size2) * size + x1 + size2] = val;
+      mat[(y1 - size2.Int()) * size.Int() + x1 + size2.Int()] = val;
     }
   }
 
@@ -208,10 +208,10 @@
   int dx0, dx1, dx, dy0, dy1, dy;
 
   dx0 = abs(x0 - x1);
-  dx1 = size - dx0;
+  dx1 = size.Int() - dx0;
   dx = dx0 < dx1 ? dx0 : dx1;
   dy0 = abs(y0 - y1);
-  dy1 = size - dy0;
+  dy1 = size.Int() - dy0;
   dy = dy0 < dy1 ? dy0 : dy1;
   return dx * dx + dy * dy;
 }
@@ -222,7 +222,7 @@
 // Hardcopy, and Graphic Arts IV, SPIE Vol. 3648, pp. 496-505, 1999.
 void SplashScreen::buildSCDMatrix(int r) {
   SplashScreenPoint *dots, *pts;
-  int dotsLen, dotsSize;
+  SafeInt dotsLen, dotsSize;
   char *tmpl;
   char *grid;
   int *region, *dist;
@@ -242,7 +242,7 @@
     }
   }
   for (i = 0; i < size * size; ++i) {
-    j = i + (int)((double)(size * size - i) *
+    j = i + (int)((double)(size.Int() * size.Int() - i) *
 		  (double)rand() / ((double)RAND_MAX + 1.0));
     x = pts[i].x;
     y = pts[i].y;
@@ -253,7 +253,7 @@
   }
 
   // construct the circle template
-  tmpl = (char *)gmallocn((r+1)*(r+1), sizeof(char));
+  tmpl = (char *)gmallocn((SafeInt(r)+SafeInt(1))*(SafeInt(r)+SafeInt(1)), sizeof(char));
   for (y = 0; y <= r; ++y) {
     for (x = 0; x <= r; ++x) {
       tmpl[y*(r+1) + x] = (x * y <= r * r) ? 1 : 0;
@@ -264,7 +264,7 @@
   grid = (char *)gmallocn(size * size, sizeof(char));
   for (y = 0; y < size; ++y) {
     for (x = 0; x < size; ++x) {
-      grid[y*size + x] = 0;
+      grid[y*size.Int() + x] = 0;
     }
   }
 
@@ -272,27 +272,27 @@
   dotsLen = 0;
   dotsSize = 32;
   dots = (SplashScreenPoint *)gmallocn(dotsSize, sizeof(SplashScreenPoint));
-  for (i = 0; i < size * size; ++i) {
+  for (i = 0; i < size.Int() * size.Int(); ++i) {
     x = pts[i].x;
     y = pts[i].y;
-    if (!grid[y*size + x]) {
+    if (!grid[y*size.Int() + x]) {
       if (dotsLen == dotsSize) {
 	dotsSize *= 2;
 	dots = (SplashScreenPoint *)greallocn(dots, dotsSize,
 					      sizeof(SplashScreenPoint));
       }
-      dots[dotsLen++] = pts[i];
+      dots[(dotsLen++).Int()] = pts[i];
       for (yy = 0; yy <= r; ++yy) {
-	y0 = (y + yy) % size;
-	y1 = (y - yy + size) % size;
+	y0 = (y + yy) % size.Int();
+	y1 = (y - yy + size.Int()) % size.Int();
 	for (xx = 0; xx <= r; ++xx) {
 	  if (tmpl[yy*(r+1) + xx]) {
-	    x0 = (x + xx) % size;
-	    x1 = (x - xx + size) % size;
-	    grid[y0*size + x0] = 1;
-	    grid[y0*size + x1] = 1;
-	    grid[y1*size + x0] = 1;
-	    grid[y1*size + x1] = 1;
+	    x0 = (x + xx) % size.Int();
+	    x1 = (x - xx + size.Int()) % size.Int();
+	    grid[y0*size.Int() + x0] = 1;
+	    grid[y0*size.Int() + x1] = 1;
+	    grid[y1*size.Int() + x0] = 1;
+	    grid[y1*size.Int() + x1] = 1;
 	  }
 	}
       }
@@ -316,17 +316,17 @@
 	  dMin = d;
 	}
       }
-      region[y*size + x] = iMin;
-      dist[y*size + x] = dMin;
+      region[y*size.Int() + x] = iMin;
+      dist[y*size.Int() + x] = dMin;
     }
   }
 
   // compute threshold values
   for (i = 0; i < dotsLen; ++i) {
     n = 0;
-    for (y = 0; y < size; ++y) {
-      for (x = 0; x < size; ++x) {
-	if (region[y*size + x] == i) {
+    for (y = 0; y < size.Int(); ++y) {
+      for (x = 0; x < size.Int(); ++x) {
+	if (region[y*size.Int() + x] == i) {
 	  pts[n].x = x;
 	  pts[n].y = y;
 	  pts[n].dist = distance(dots[i].x, dots[i].y, x, y);
@@ -337,7 +337,7 @@
     qsort(pts, n, sizeof(SplashScreenPoint), &cmpDistances);
     for (j = 0; j < n; ++j) {
       // map values in [0 .. n-1] --> [255 .. 1]
-      mat[pts[j].y * size + pts[j].x] = 255 - (254 * j) / (n - 1);
+      mat[pts[j].y * size.Int() + pts[j].x] = 255 - (254 * j) / (n - 1);
     }
   }
 
@@ -351,7 +351,7 @@
 SplashScreen::SplashScreen(SplashScreen *screen) {
   size = screen->size;
   mat = (Guchar *)gmallocn(size * size, sizeof(Guchar));
-  memcpy(mat, screen->mat, size * size * sizeof(Guchar));
+  memcpy(mat, screen->mat, (size * size).Int() * sizeof(Guchar));
   minVal = screen->minVal;
   maxVal = screen->maxVal;
 }
@@ -369,13 +369,13 @@
   if (value >= maxVal) {
     return 1;
   }
-  if ((xx = x % size) < 0) {
+  if ((xx = x % size.Int()) < 0) {
     xx = -xx;
   }
-  if ((yy = y % size) < 0) {
+  if ((yy = y % size.Int()) < 0) {
     yy = -yy;
   }
-  return value < mat[yy * size + xx] ? 0 : 1;
+  return value < mat[yy * size.Int() + xx] ? 0 : 1;
 }
 
 GBool SplashScreen::isStatic(Guchar value) {
--- xpdf-3.02/splash/SplashScreen.h
+++ xpdf-3.02/splash/SplashScreen.h
@@ -14,11 +14,14 @@
 #endif
 
 #include "SplashTypes.h"
+#include "gmem.h"
 
 //------------------------------------------------------------------------
 // SplashScreen
 //------------------------------------------------------------------------
 
+class SafeInt;
+
 class SplashScreen {
 public:
 
@@ -46,7 +49,7 @@
   void buildSCDMatrix(int r);
 
   Guchar *mat;			// threshold matrix
-  int size;			// size of the threshold matrix
+  SafeInt size;			// size of the threshold matrix
   Guchar minVal;		// any pixel value below minVal generates
 				//   solid black
   Guchar maxVal;		// any pixel value above maxVal generates
--- xpdf-3.02/splash/SplashT1Font.cc
+++ xpdf-3.02/splash/SplashT1Font.cc
@@ -183,7 +183,8 @@
 GBool SplashT1Font::makeGlyph(int c, int xFrac, int yFrac,
 			      SplashGlyphBitmap *bitmap) {
   GLYPH *glyph;
-  int n, i;
+  int i;
+  SafeInt n;
 
   if (aa) {
     glyph = T1_AASetChar(t1libID, c, size, NULL);
@@ -203,7 +204,7 @@
     bitmap->data = (Guchar *)glyph->bits;
     bitmap->freeData = gFalse;
   } else {
-    n = bitmap->h * ((bitmap->w + 7) >> 3);
+    n = SafeInt(bitmap->h) * ((SafeInt(bitmap->w) + SafeInt(7)) >> SafeInt(3));
     bitmap->data = (Guchar *)gmalloc(n);
     for (i = 0; i < n; ++i) {
       bitmap->data[i] = bitReverse[glyph->bits[i] & 0xff];
--- xpdf-3.02/splash/SplashT1FontFile.cc
+++ xpdf-3.02/splash/SplashT1FontFile.cc
@@ -31,7 +31,7 @@
   int t1libIDA;
   char **encTmp;
   char *encStrTmp;
-  int encStrSize;
+  SafeInt encStrSize;
   char *encPtr;
   int i;
 
@@ -45,7 +45,7 @@
   encStrSize = 0;
   for (i = 0; i < 256; ++i) {
     if (encA[i]) {
-      encStrSize += strlen(encA[i]) + 1;
+      encStrSize += SafeInt(strlen(encA[i])) + SafeInt(1);
     }
   }
   encTmp = (char **)gmallocn(257, sizeof(char *));
--- xpdf-3.02/splash/SplashXPath.cc
+++ xpdf-3.02/splash/SplashXPath.cc
@@ -147,7 +147,7 @@
       xsp = x0;
       ysp = y0;
       curSubpath = i;
-      curSubpathX = length;
+      curSubpathX = length.Int();
       ++i;
 
     } else {
@@ -236,7 +236,7 @@
   length = xPath->length;
   size = xPath->size;
   segs = (SplashXPathSeg *)gmallocn(size, sizeof(SplashXPathSeg));
-  memcpy(segs, xPath->segs, length * sizeof(SplashXPathSeg));
+  memcpy(segs, xPath->segs, length.Int() * sizeof(SplashXPathSeg));
 }
 
 SplashXPath::~SplashXPath() {
@@ -344,51 +344,51 @@
 			     SplashCoord x1, SplashCoord y1,
 			     GBool first, GBool last, GBool end0, GBool end1) {
   grow(1);
-  segs[length].x0 = x0;
-  segs[length].y0 = y0;
-  segs[length].x1 = x1;
-  segs[length].y1 = y1;
-  segs[length].flags = 0;
+  segs[length.Int()].x0 = x0;
+  segs[length.Int()].y0 = y0;
+  segs[length.Int()].x1 = x1;
+  segs[length.Int()].y1 = y1;
+  segs[length.Int()].flags = 0;
   if (first) {
-    segs[length].flags |= splashXPathFirst;
+    segs[length.Int()].flags |= splashXPathFirst;
   }
   if (last) {
-    segs[length].flags |= splashXPathLast;
+    segs[length.Int()].flags |= splashXPathLast;
   }
   if (end0) {
-    segs[length].flags |= splashXPathEnd0;
+    segs[length.Int()].flags |= splashXPathEnd0;
   }
   if (end1) {
-    segs[length].flags |= splashXPathEnd1;
+    segs[length.Int()].flags |= splashXPathEnd1;
   }
   if (y1 == y0) {
-    segs[length].dxdy = segs[length].dydx = 0;
-    segs[length].flags |= splashXPathHoriz;
+    segs[length.Int()].dxdy = segs[length.Int()].dydx = 0;
+    segs[length.Int()].flags |= splashXPathHoriz;
     if (x1 == x0) {
-      segs[length].flags |= splashXPathVert;
+      segs[length.Int()].flags |= splashXPathVert;
     }
   } else if (x1 == x0) {
-    segs[length].dxdy = segs[length].dydx = 0;
-    segs[length].flags |= splashXPathVert;
+    segs[length.Int()].dxdy = segs[length.Int()].dydx = 0;
+    segs[length.Int()].flags |= splashXPathVert;
   } else {
 #if USE_FIXEDPOINT
-    if (FixedPoint::divCheck(x1 - x0, y1 - y0, &segs[length].dxdy)) {
-      segs[length].dydx = (SplashCoord)1 / segs[length].dxdy;
+    if (FixedPoint::divCheck(x1 - x0, y1 - y0, &segs[length.Int()].dxdy)) {
+      segs[length.Int()].dydx = (SplashCoord)1 / segs[length.Int()].dxdy;
     } else {
-      segs[length].dxdy = segs[length].dydx = 0;
+      segs[length.Int()].dxdy = segs[length.Int()].dydx = 0;
       if (splashAbs(x1 - x0) > splashAbs(y1 - y0)) {
-	segs[length].flags |= splashXPathHoriz;
+	segs[length.Int()].flags |= splashXPathHoriz;
       } else {
-	segs[length].flags |= splashXPathVert;
+	segs[length.Int()].flags |= splashXPathVert;
       }
     }
 #else
-    segs[length].dxdy = (x1 - x0) / (y1 - y0);
-    segs[length].dydx = (SplashCoord)1 / segs[length].dxdy;
+    segs[length.Int()].dxdy = (x1 - x0) / (y1 - y0);
+    segs[length.Int()].dydx = (SplashCoord)1 / segs[length.Int()].dxdy;
 #endif
   }
   if (y0 > y1) {
-    segs[length].flags |= splashXPathFlip;
+    segs[length.Int()].flags |= splashXPathFlip;
   }
   ++length;
 }
@@ -434,5 +434,5 @@
 }
 
 void SplashXPath::sort() {
-  qsort(segs, length, sizeof(SplashXPathSeg), &cmpXPathSegs);
+  qsort(segs, length.Int(), sizeof(SplashXPathSeg), &cmpXPathSegs);
 }
--- xpdf-3.02/splash/SplashXPath.h
+++ xpdf-3.02/splash/SplashXPath.h
@@ -90,7 +90,7 @@
 		  GBool first, GBool last, GBool end0, GBool end1);
 
   SplashXPathSeg *segs;
-  int length, size;		// length and size of segs array
+  SafeInt length, size;		// length and size of segs array
 
   friend class SplashXPathScanner;
   friend class SplashClip;
--- xpdf-3.02/splash/SplashXPathScanner.cc
+++ xpdf-3.02/splash/SplashXPathScanner.cc
@@ -92,7 +92,8 @@
   interY = yMin - 1;
   xPathIdx = 0;
   inter = NULL;
-  interLen = interSize = 0;
+  interLen = 0;
+  interSize = 0;
 }
 
 SplashXPathScanner::~SplashXPathScanner() {
--- xpdf-3.02/splash/SplashXPathScanner.h
+++ xpdf-3.02/splash/SplashXPathScanner.h
@@ -81,7 +81,7 @@
 				//   computeIntersections
   SplashIntersect *inter;	// intersections array for <interY>
   int interLen;			// number of intersections in <inter>
-  int interSize;		// size of the <inter> array
+  SafeInt interSize;		// size of the <inter> array
 };
 
 #endif
--- xpdf-3.02/xpdf/Annot.cc
+++ xpdf-3.02/xpdf/Annot.cc
@@ -1437,7 +1437,7 @@
   Annot *annot;
   Object obj1;
   Ref ref;
-  int size;
+  SafeInt size;
   int i;
 
   annots = NULL;
--- xpdf-3.02/xpdf/Array.cc
+++ xpdf-3.02/xpdf/Array.cc
@@ -46,7 +46,7 @@
     }
     elems = (Object *)greallocn(elems, size, sizeof(Object));
   }
-  elems[length] = *elem;
+  elems[length.Int()] = *elem;
   ++length;
 }
 
--- xpdf-3.02/xpdf/Array.h
+++ xpdf-3.02/xpdf/Array.h
@@ -37,7 +37,7 @@
   int decRef() { return --ref; }
 
   // Get number of elements.
-  int getLength() { return length; }
+  int getLength() { return length.Int(); }
 
   // Add an element.
   void add(Object *elem);
@@ -50,8 +50,8 @@
 
   XRef *xref;			// the xref table for this PDF file
   Object *elems;		// array of elements
-  int size;			// size of <elems> array
-  int length;			// number of elements in array
+  SafeInt size;			// size of <elems> array
+  SafeInt length;		// number of elements in array
   int ref;			// reference count
 };
 
--- xpdf-3.02/xpdf/Catalog.cc
+++ xpdf-3.02/xpdf/Catalog.cc
@@ -38,7 +38,7 @@
   xref = xrefA;
   pages = NULL;
   pageRefs = NULL;
-  numPages = pagesSize = 0;
+  pagesSize = numPages = 0;
   baseURI = NULL;
 
   xref->getCatalog(&catDict);
@@ -219,7 +219,7 @@
 	pagesSize += 32;
 	pages = (Page **)greallocn(pages, pagesSize, sizeof(Page *));
 	pageRefs = (Ref *)greallocn(pageRefs, pagesSize, sizeof(Ref));
-	for (j = pagesSize - 32; j < pagesSize; ++j) {
+	for (j = (pagesSize - 32).Int(); j < pagesSize; ++j) {
 	  pages[j] = NULL;
 	  pageRefs[j].num = -1;
 	  pageRefs[j].gen = -1;
--- xpdf-3.02/xpdf/Catalog.h
+++ xpdf-3.02/xpdf/Catalog.h
@@ -79,7 +79,7 @@
   Page **pages;			// array of pages
   Ref *pageRefs;		// object ID for each page
   int numPages;			// number of pages
-  int pagesSize;		// size of pages array
+  SafeInt pagesSize;		// size of pages array
   Object dests;			// named destination dictionary
   Object nameTree;		// name tree
   GString *baseURI;		// base URI for URI-type links
--- xpdf-3.02/xpdf/CharCodeToUnicode.cc
+++ xpdf-3.02/xpdf/CharCodeToUnicode.cc
@@ -58,7 +58,8 @@
 							GString *collection) {
   FILE *f;
   Unicode *mapA;
-  CharCode size, mapLenA;
+  CharCode mapLenA;
+  SafeInt size;
   char buf[64];
   Unicode u;
   CharCodeToUnicode *ctu;
@@ -100,7 +101,8 @@
   FILE *f;
   Unicode *mapA;
   CharCodeToUnicodeString *sMapA;
-  CharCode size, oldSize, len, sMapSizeA, sMapLenA;
+  CharCode len, sMapLenA;
+  SafeInt size, oldSize, sMapSizeA;
   char buf[256];
   char *tok;
   Unicode u0;
@@ -116,7 +118,7 @@
 
   size = 4096;
   mapA = (Unicode *)gmallocn(size, sizeof(Unicode));
-  memset(mapA, 0, size * sizeof(Unicode));
+  memset(mapA, 0, size.Int() * sizeof(Unicode));
   len = 0;
   sMapA = NULL;
   sMapSizeA = sMapLenA = 0;
@@ -153,7 +155,7 @@
 	size *= 2;
       }
       mapA = (Unicode *)greallocn(mapA, size, sizeof(Unicode));
-      memset(mapA + oldSize, 0, (size - oldSize) * sizeof(Unicode));
+      memset(mapA + oldSize.Int(), 0, (size - oldSize).Int() * sizeof(Unicode));
     }
     if (n == 1) {
       mapA[u0] = uBuf[0];
@@ -178,7 +180,7 @@
   fclose(f);
 
   ctu = new CharCodeToUnicode(fileName->copy(), mapA, len, gTrue,
-			      sMapA, sMapLenA, sMapSizeA);
+			      sMapA, sMapLenA, sMapSizeA.Int());
   gfree(mapA);
   return ctu;
 }
@@ -319,7 +321,7 @@
 
   if (code >= mapLen) {
     oldLen = mapLen;
-    mapLen = (code + 256) & ~255;
+    mapLen = (SafeInt(code) + 256).Int() & ~255;
     map = (Unicode *)greallocn(map, mapLen, sizeof(Unicode));
     for (i = oldLen; i < mapLen; ++i) {
       map[i] = 0;
@@ -362,7 +364,7 @@
     map[i] = 0;
   }
   sMap = NULL;
-  sMapLen = sMapSize = 0;
+  sMapSize = sMapLen = 0;
   refCnt = 1;
 #if MULTITHREADED
   gInitMutex(&mutex);
--- xpdf-3.02/xpdf/CharCodeToUnicode.h
+++ xpdf-3.02/xpdf/CharCodeToUnicode.h
@@ -87,7 +87,8 @@
   Unicode *map;
   CharCode mapLen;
   CharCodeToUnicodeString *sMap;
-  int sMapLen, sMapSize;
+  int sMapLen;
+  SafeInt sMapSize;
   int refCnt;
 #if MULTITHREADED
   GMutex mutex;
--- xpdf-3.02/xpdf/Decrypt.cc
+++ xpdf-3.02/xpdf/Decrypt.cc
@@ -113,7 +113,7 @@
   GBool ok;
 
   // generate file key
-  buf = (Guchar *)gmalloc(72 + fileID->getLength());
+  buf = (Guchar *)gmalloc((SafeInt(72) + SafeInt(fileID->getLength())).Int());
   if (userPassword) {
     len = userPassword->getLength();
     if (len < 32) {
--- xpdf-3.02/xpdf/Dict.h
+++ xpdf-3.02/xpdf/Dict.h
@@ -67,7 +67,7 @@
 
   XRef *xref;			// the xref table for this PDF file
   DictEntry *entries;		// array of entries
-  int size;			// size of <entries> array
+  SafeInt size;			// size of <entries> array
   int length;			// number of entries in dictionary
   int ref;			// reference count
 
--- xpdf-3.02/xpdf/Function.cc
+++ xpdf-3.02/xpdf/Function.cc
@@ -212,7 +212,7 @@
   }
 
   //----- buffer
-  sBuf = (double *)gmallocn(1 << m, sizeof(double));
+  sBuf = (double *)gmallocn((SafeInt(1) << m).Int(), sizeof(double));
 
   //----- get the stream
   if (!funcObj->isStream()) {
@@ -364,8 +364,8 @@
 SampledFunction::SampledFunction(SampledFunction *func) {
   memcpy(this, func, sizeof(SampledFunction));
   samples = (double *)gmallocn(nSamples, sizeof(double));
-  memcpy(samples, func->samples, nSamples * sizeof(double));
-  sBuf = (double *)gmallocn(1 << m, sizeof(double));
+  memcpy(samples, func->samples, (nSamples * sizeof(double)).Int());
+  sBuf = (double *)gmallocn((SafeInt(1) << m).Int(), sizeof(double));
 }
 
 void SampledFunction::transform(double *in, double *out) {
@@ -570,8 +570,8 @@
   }
   k = obj1.arrayGetLength();
   funcs = (Function **)gmallocn(k, sizeof(Function *));
-  bounds = (double *)gmallocn(k + 1, sizeof(double));
-  encode = (double *)gmallocn(2 * k, sizeof(double));
+  bounds = (double *)gmallocn(k + SafeInt(1), sizeof(double));
+  encode = (double *)gmallocn(SafeInt(2) * k, sizeof(double));
   scale = (double *)gmallocn(k, sizeof(double));
   for (i = 0; i < k; ++i) {
     funcs[i] = NULL;
@@ -604,7 +604,7 @@
     bounds[i] = obj2.getNum();
     obj2.free();
   }
-  bounds[k] = domain[0][1];
+  bounds[k.Int()] = domain[0][1];
   obj1.free();
 
   //----- Encode
@@ -651,12 +651,12 @@
   for (i = 0; i < k; ++i) {
     funcs[i] = func->funcs[i]->copy();
   }
-  bounds = (double *)gmallocn(k + 1, sizeof(double));
-  memcpy(bounds, func->bounds, (k + 1) * sizeof(double));
-  encode = (double *)gmallocn(2 * k, sizeof(double));
-  memcpy(encode, func->encode, 2 * k * sizeof(double));
+  bounds = (double *)gmallocn(k + SafeInt(1), sizeof(double));
+  memcpy(bounds, func->bounds, ((k + 1) * sizeof(double)).Int());
+  encode = (double *)gmallocn(SafeInt(2) * k, sizeof(double));
+  memcpy(encode, func->encode, (2 * k * sizeof(double)).Int());
   scale = (double *)gmallocn(k, sizeof(double));
-  memcpy(scale, func->scale, k * sizeof(double));
+  memcpy(scale, func->scale, (k * sizeof(double)).Int());
   ok = gTrue;
 }
 
@@ -1051,7 +1051,7 @@
 PostScriptFunction::PostScriptFunction(PostScriptFunction *func) {
   memcpy(this, func, sizeof(PostScriptFunction));
   code = (PSObject *)gmallocn(codeSize, sizeof(PSObject));
-  memcpy(code, func->code, codeSize * sizeof(PSObject));
+  memcpy(code, func->code, (codeSize * sizeof(PSObject)).Int());
   codeString = func->codeString->copy();
 }
 
--- xpdf-3.02/xpdf/Function.h
+++ xpdf-3.02/xpdf/Function.h
@@ -131,7 +131,7 @@
     inputMul[funcMaxInputs];
   int idxMul[funcMaxInputs];	// sample array index multipliers
   double *samples;		// the samples
-  int nSamples;			// size of the samples array
+  SafeInt nSamples;		// size of the samples array
   double *sBuf;			// buffer for the transform function
   GBool ok;
 };
@@ -178,7 +178,7 @@
   virtual void transform(double *in, double *out);
   virtual GBool isOk() { return ok; }
 
-  int getNumFuncs() { return k; }
+  int getNumFuncs() { return k.Int(); }
   Function *getFunc(int i) { return funcs[i]; }
   double *getBounds() { return bounds; }
   double *getEncode() { return encode; }
@@ -188,7 +188,7 @@
 
   StitchingFunction(StitchingFunction *func);
 
-  int k;
+  SafeInt k;
   Function **funcs;
   double *bounds;
   double *encode;
@@ -222,7 +222,7 @@
 
   GString *codeString;
   PSObject *code;
-  int codeSize;
+  SafeInt codeSize;
   GBool ok;
 };
 
--- xpdf-3.02/xpdf/GfxFont.cc
+++ xpdf-3.02/xpdf/GfxFont.cc
@@ -368,7 +368,8 @@
   Object obj1, obj2;
   Stream *str;
   int c;
-  int size, i;
+  SafeInt size;
+  int i;
 
   obj1.initRef(embFontID.num, embFontID.gen);
   obj1.fetch(xref, &obj2);
@@ -382,12 +383,12 @@
   str = obj2.getStream();
 
   buf = NULL;
-  i = size = 0;
+  size = i = 0;
   str->reset();
   while ((c = str->getChar()) != EOF) {
     if (i == size) {
       size += 4096;
-      buf = (char *)grealloc(buf, size);
+      buf = (char *)grealloc(buf, size.Int());
     }
     buf[i++] = c;
   }
@@ -1086,7 +1087,8 @@
   CharCode c;
   Unicode uBuf[8];
   int c1, c2;
-  int excepsSize, i, j, k, n;
+  int j, k, n;
+  SafeInt i, excepsSize;
 
   ascent = 0.95;
   descent = -0.35;
@@ -1247,10 +1249,10 @@
     excepsSize = 0;
     i = 0;
     while (i + 1 < obj1.arrayGetLength()) {
-      obj1.arrayGet(i, &obj2);
-      obj1.arrayGet(i + 1, &obj3);
-      if (obj2.isInt() && obj3.isInt() && i + 2 < obj1.arrayGetLength()) {
-	if (obj1.arrayGet(i + 2, &obj4)->isNum()) {
+      obj1.arrayGet(i.Int(), &obj2);
+      obj1.arrayGet((i + 1).Int(), &obj3);
+      if (obj2.isInt() && obj3.isInt() && (i + 2).Int() < obj1.arrayGetLength()) {
+	if (obj1.arrayGet((i + 2).Int(), &obj4)->isNum()) {
 	  if (widths.nExceps == excepsSize) {
 	    excepsSize += 16;
 	    widths.exceps = (GfxFontCIDWidthExcep *)
@@ -1268,7 +1270,7 @@
 	i += 3;
       } else if (obj2.isInt() && obj3.isArray()) {
 	if (widths.nExceps + obj3.arrayGetLength() > excepsSize) {
-	  excepsSize = (widths.nExceps + obj3.arrayGetLength() + 15) & ~15;
+	  excepsSize = (SafeInt(widths.nExceps) + SafeInt(obj3.arrayGetLength()) + 15).Int() & ~15;
 	  widths.exceps = (GfxFontCIDWidthExcep *)
 	    greallocn(widths.exceps,
 		      excepsSize, sizeof(GfxFontCIDWidthExcep));
@@ -1318,12 +1320,12 @@
     excepsSize = 0;
     i = 0;
     while (i + 1 < obj1.arrayGetLength()) {
-      obj1.arrayGet(i, &obj2);
-      obj1.arrayGet(i+ 1, &obj3);
-      if (obj2.isInt() && obj3.isInt() && i + 4 < obj1.arrayGetLength()) {
-	if (obj1.arrayGet(i + 2, &obj4)->isNum() &&
-	    obj1.arrayGet(i + 3, &obj5)->isNum() &&
-	    obj1.arrayGet(i + 4, &obj6)->isNum()) {
+      obj1.arrayGet(i.Int(), &obj2);
+      obj1.arrayGet((i+ 1).Int(), &obj3);
+      if (obj2.isInt() && obj3.isInt() && (i + 4).Int() < obj1.arrayGetLength()) {
+	if (obj1.arrayGet((i + 2).Int(), &obj4)->isNum() &&
+	    obj1.arrayGet((i + 3).Int(), &obj5)->isNum() &&
+	    obj1.arrayGet((i + 4).Int(), &obj6)->isNum()) {
 	  if (widths.nExcepsV == excepsSize) {
 	    excepsSize += 16;
 	    widths.excepsV = (GfxFontCIDWidthExcepV *)
@@ -1511,7 +1513,7 @@
   Unicode u[64];
   const int ulen = sizeof(u) / sizeof(Unicode);
   int code, i;
-  int mapsize;
+  SafeInt mapsize;
   int cidlen;
 
   *mapsizep = 0;
@@ -1529,7 +1531,7 @@
 
   cidlen = 0;
   mapsize = 64;
-  map = (Gushort *)gmalloc(mapsize * sizeof(Gushort));
+  map = (Gushort *)gmallocn(mapsize, sizeof(Gushort));
 
   while (cidlen < ctu->getMapLen()) {
     int n;
@@ -1540,7 +1542,7 @@
     if (cidlen >= mapsize) {
       while (cidlen >= mapsize)
 	mapsize *= 2;
-      map = (Gushort *)grealloc(map, mapsize * sizeof(Gushort));
+      map = (Gushort *)greallocn(map, mapsize, sizeof(Gushort));
     }
     if (n == 1)
       map[cidlen] = ff->mapCodeToGID(cmap, u[0]);
--- xpdf-3.02/xpdf/GfxState.cc
+++ xpdf-3.02/xpdf/GfxState.cc
@@ -925,7 +925,7 @@
 					   int indexHighA) {
   base = baseA;
   indexHigh = indexHighA;
-  lookup = (Guchar *)gmallocn((indexHigh + 1) * base->getNComps(),
+  lookup = (Guchar *)gmallocn((SafeInt(indexHigh) + SafeInt(1)) * SafeInt(base->getNComps()),
 			      sizeof(Guchar));
 }
 
@@ -2337,7 +2337,7 @@
   vertices = (GfxGouraudVertex *)gmallocn(nVertices, sizeof(GfxGouraudVertex));
   memcpy(vertices, shading->vertices, nVertices * sizeof(GfxGouraudVertex));
   nTriangles = shading->nTriangles;
-  triangles = (int (*)[3])gmallocn(nTriangles * 3, sizeof(int));
+  triangles = (int (*)[3])gmallocn(SafeInt(nTriangles) * SafeInt(3), sizeof(int));
   memcpy(triangles, shading->triangles, nTriangles * 3 * sizeof(int));
   nFuncs = shading->nFuncs;
   for (i = 0; i < nFuncs; ++i) {
@@ -2368,7 +2368,8 @@
   double cMul[gfxColorMaxComps];
   GfxGouraudVertex *verticesA;
   int (*trianglesA)[3];
-  int nComps, nVerticesA, nTrianglesA, vertSize, triSize;
+  int nComps, nVerticesA, nTrianglesA;
+  SafeInt vertSize, triSize;
   Guint x, y, flag;
   Guint c[gfxColorMaxComps];
   GfxShadingBitBuf *bitBuf;
@@ -2506,7 +2507,7 @@
 	if (nTrianglesA == triSize) {
 	  triSize = (triSize == 0) ? 16 : 2 * triSize;
 	  trianglesA = (int (*)[3])
-	                   greallocn(trianglesA, triSize * 3, sizeof(int));
+	                   greallocn(trianglesA, SafeInt(triSize) * SafeInt(3), sizeof(int));
 	}
 	if (state == 2) {
 	  trianglesA[nTrianglesA][0] = nVerticesA - 3;
@@ -2531,8 +2532,9 @@
   delete bitBuf;
   if (typeA == 5) {
     nRows = nVerticesA / vertsPerRow;
-    nTrianglesA = (nRows - 1) * 2 * (vertsPerRow - 1);
-    trianglesA = (int (*)[3])gmallocn(nTrianglesA * 3, sizeof(int));
+    nTrianglesA = ((SafeInt(nRows) - SafeInt(1)) * SafeInt(2) 
+                   * (SafeInt(vertsPerRow) - SafeInt(1))).Int();
+    trianglesA = (int (*)[3])gmallocn(SafeInt(nTrianglesA) * SafeInt(3), sizeof(int));
     k = 0;
     for (i = 0; i < nRows - 1; ++i) {
       for (j = 0; j < vertsPerRow - 1; ++j) {
@@ -2673,7 +2675,8 @@
   double xMul, yMul;
   double cMul[gfxColorMaxComps];
   GfxPatch *patchesA, *p;
-  int nComps, nPatchesA, patchesSize, nPts, nColors;
+  int nComps, nPatchesA, nPts, nColors;
+  SafeInt patchesSize;
   Guint flag;
   double x[16], y[16];
   Guint xi, yi;
@@ -3253,7 +3256,7 @@
     lookup2 = indexedCS->getLookup();
     colorSpace2->getDefaultRanges(x, y, indexHigh);
     for (k = 0; k < nComps2; ++k) {
-      lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1,
+      lookup[k] = (GfxColorComp *)gmallocn(SafeInt(maxPixel) + SafeInt(1),
 					   sizeof(GfxColorComp));
       for (i = 0; i <= maxPixel; ++i) {
 	j = (int)(decodeLow[0] + (i * decodeRange[0]) / maxPixel + 0.5);
@@ -3272,7 +3275,7 @@
     nComps2 = colorSpace2->getNComps();
     sepFunc = sepCS->getFunc();
     for (k = 0; k < nComps2; ++k) {
-      lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1,
+      lookup[k] = (GfxColorComp *)gmallocn(SafeInt(maxPixel) + SafeInt(1),
 					   sizeof(GfxColorComp));
       for (i = 0; i <= maxPixel; ++i) {
 	x[0] = decodeLow[0] + (i * decodeRange[0]) / maxPixel;
@@ -3282,7 +3285,7 @@
     }
   } else {
     for (k = 0; k < nComps; ++k) {
-      lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1,
+      lookup[k] = (GfxColorComp *)gmallocn(SafeInt(maxPixel) + SafeInt(1),
 					   sizeof(GfxColorComp));
       for (i = 0; i <= maxPixel; ++i) {
 	lookup[k][i] = dblToCol(decodeLow[k] +
@@ -3300,7 +3303,8 @@
 }
 
 GfxImageColorMap::GfxImageColorMap(GfxImageColorMap *colorMap) {
-  int n, i, k;
+  int i, k;
+  SafeInt n;
 
   colorSpace = colorMap->colorSpace->copy();
   bits = colorMap->bits;
@@ -3310,23 +3314,23 @@
   for (k = 0; k < gfxColorMaxComps; ++k) {
     lookup[k] = NULL;
   }
-  n = 1 << bits;
+  n = SafeInt(1) << bits;
   if (colorSpace->getMode() == csIndexed) {
     colorSpace2 = ((GfxIndexedColorSpace *)colorSpace)->getBase();
     for (k = 0; k < nComps2; ++k) {
       lookup[k] = (GfxColorComp *)gmallocn(n, sizeof(GfxColorComp));
-      memcpy(lookup[k], colorMap->lookup[k], n * sizeof(GfxColorComp));
+      memcpy(lookup[k], colorMap->lookup[k], n.Int() * sizeof(GfxColorComp));
     }
   } else if (colorSpace->getMode() == csSeparation) {
     colorSpace2 = ((GfxSeparationColorSpace *)colorSpace)->getAlt();
     for (k = 0; k < nComps2; ++k) {
       lookup[k] = (GfxColorComp *)gmallocn(n, sizeof(GfxColorComp));
-      memcpy(lookup[k], colorMap->lookup[k], n * sizeof(GfxColorComp));
+      memcpy(lookup[k], colorMap->lookup[k], n.Int() * sizeof(GfxColorComp));
     }
   } else {
     for (k = 0; k < nComps; ++k) {
       lookup[k] = (GfxColorComp *)gmallocn(n, sizeof(GfxColorComp));
-      memcpy(lookup[k], colorMap->lookup[k], n * sizeof(GfxColorComp));
+      memcpy(lookup[k], colorMap->lookup[k], n.Int() * sizeof(GfxColorComp));
     }
   }
   for (i = 0; i < nComps; ++i) {
@@ -3506,7 +3510,7 @@
 
 // Used for copy().
 GfxPath::GfxPath(GBool justMoved1, double firstX1, double firstY1,
-		 GfxSubpath **subpaths1, int n1, int size1) {
+		 GfxSubpath **subpaths1, SafeInt n1, SafeInt size1) {
   int i;
 
   justMoved = justMoved1;
@@ -3532,11 +3536,11 @@
       subpaths = (GfxSubpath **)
 	           greallocn(subpaths, size, sizeof(GfxSubpath *));
     }
-    subpaths[n] = new GfxSubpath(firstX, firstY);
+    subpaths[n.Int()] = new GfxSubpath(firstX, firstY);
     ++n;
     justMoved = gFalse;
   }
-  subpaths[n-1]->lineTo(x, y);
+  subpaths[n.Int()-1]->lineTo(x, y);
 }
 
 void GfxPath::curveTo(double x1, double y1, double x2, double y2,
@@ -3547,11 +3551,11 @@
       subpaths = (GfxSubpath **)
 	           greallocn(subpaths, size, sizeof(GfxSubpath *));
     }
-    subpaths[n] = new GfxSubpath(firstX, firstY);
+    subpaths[n.Int()] = new GfxSubpath(firstX, firstY);
     ++n;
     justMoved = gFalse;
   }
-  subpaths[n-1]->curveTo(x1, y1, x2, y2, x3, y3);
+  subpaths[n.Int()-1]->curveTo(x1, y1, x2, y2, x3, y3);
 }
 
 void GfxPath::close() {
@@ -3563,11 +3567,11 @@
       subpaths = (GfxSubpath **)
 	           greallocn(subpaths, size, sizeof(GfxSubpath *));
     }
-    subpaths[n] = new GfxSubpath(firstX, firstY);
+    subpaths[n.Int()] = new GfxSubpath(firstX, firstY);
     ++n;
     justMoved = gFalse;
   }
-  subpaths[n-1]->close();
+  subpaths[n.Int()-1]->close();
 }
 
 void GfxPath::append(GfxPath *path) {
@@ -3579,7 +3583,7 @@
                  greallocn(subpaths, size, sizeof(GfxSubpath *));
   }
   for (i = 0; i < path->n; ++i) {
-    subpaths[n++] = path->subpaths[i]->copy();
+    subpaths[(n++).Int()] = path->subpaths[i]->copy();
   }
   justMoved = gFalse;
 }
--- xpdf-3.02/xpdf/GfxState.h
+++ xpdf-3.02/xpdf/GfxState.h
@@ -942,7 +942,7 @@
   GBool *curve;			// curve[i] => point i is a control point
 				//   for a Bezier curve
   int n;			// number of points
-  int size;			// size of x/y arrays
+  SafeInt size;			// size of x/y arrays
   GBool closed;			// set if path is closed
 
   GfxSubpath(GfxSubpath *subpath);
@@ -968,12 +968,12 @@
   GBool isPath() { return n > 0; }
 
   // Get subpaths.
-  int getNumSubpaths() { return n; }
+  int getNumSubpaths() { return n.Int(); }
   GfxSubpath *getSubpath(int i) { return subpaths[i]; }
 
   // Get last point on last subpath.
-  double getLastX() { return subpaths[n-1]->getLastX(); }
-  double getLastY() { return subpaths[n-1]->getLastY(); }
+  double getLastX() { return subpaths[n.Int()-1]->getLastX(); }
+  double getLastY() { return subpaths[n.Int()-1]->getLastY(); }
 
   // Move the current point.
   void moveTo(double x, double y);
@@ -999,11 +999,11 @@
   GBool justMoved;		// set if a new subpath was just started
   double firstX, firstY;	// first point in new subpath
   GfxSubpath **subpaths;	// subpaths
-  int n;			// number of subpaths
-  int size;			// size of subpaths array
+  SafeInt n;			// number of subpaths
+  SafeInt size;			// size of subpaths array
 
   GfxPath(GBool justMoved1, double firstX1, double firstY1,
-	  GfxSubpath **subpaths1, int n1, int size1);
+	  GfxSubpath **subpaths1, SafeInt n1, SafeInt size1);
 };
 
 //------------------------------------------------------------------------
--- xpdf-3.02/xpdf/ImageOutputDev.cc
+++ xpdf-3.02/xpdf/ImageOutputDev.cc
@@ -26,7 +26,7 @@
 
 ImageOutputDev::ImageOutputDev(char *fileRootA, GBool dumpJPEGA) {
   fileRoot = copyString(fileRootA);
-  fileName = (char *)gmalloc(strlen(fileRoot) + 20);
+  fileName = (char *)gmalloc((SafeInt(strlen(fileRoot)) + SafeInt(20)).Int());
   dumpJPEG = dumpJPEGA;
   imgNum = 0;
   ok = gTrue;
--- xpdf-3.02/xpdf/JArithmeticDecoder.cc
+++ xpdf-3.02/xpdf/JArithmeticDecoder.cc
@@ -7,6 +7,7 @@
 //========================================================================
 
 #include <aconf.h>
+#include <stdlib.h>
 
 #ifdef USE_GCC_PRAGMAS
 #pragma implementation
@@ -47,6 +48,10 @@
 }
 
 void JArithmeticDecoderStats::setEntry(Guint cx, int i, int mps) {
+  if (cx >= contextSize) {
+    fprintf(stderr, "index out of bounds");
+    exit(1);
+  }
   cxTab[cx] = (i << 1) + mps;
 }
 
--- xpdf-3.02/xpdf/JBIG2Stream.cc
+++ xpdf-3.02/xpdf/JBIG2Stream.cc
@@ -684,7 +684,7 @@
 {
   w = wA;
   h = hA;
-  line = (wA + 7) >> 3;
+  line = (SafeInt(wA) + SafeInt(7) >> 3).Int();
   if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) {
     // force a call to gmalloc(-1), which will throw an exception
     h = -1;
@@ -1522,7 +1522,7 @@
   }
 
   // get the input symbol bitmaps
-  bitmaps = (JBIG2Bitmap **)gmallocn(numInputSyms + numNewSyms,
+  bitmaps = (JBIG2Bitmap **)gmallocn(SafeInt(numInputSyms) + SafeInt(numNewSyms),
 				     sizeof(JBIG2Bitmap *));
   for (i = 0; i < numInputSyms + numNewSyms; ++i) {
     bitmaps[i] = NULL;
@@ -1845,7 +1845,8 @@
   int sOffset;
   Guint huffFlags, huffFS, huffDS, huffDT;
   Guint huffRDW, huffRDH, huffRDX, huffRDY, huffRSize;
-  Guint numInstances, numSyms, symCodeLen;
+  Guint numInstances, symCodeLen;
+  SafeInt numSyms;
   int atx[2], aty[2];
   Guint i, k, kk;
   int j;
@@ -2048,7 +2049,7 @@
     runLengthTab[35].prefixLen = 0;
     runLengthTab[35].rangeLen = jbig2HuffmanEOT;
     huffDecoder->buildTable(runLengthTab, 35);
-    symCodeTab = (JBIG2HuffmanTable *)gmallocn(numSyms + 1,
+    symCodeTab = (JBIG2HuffmanTable *)gmallocn(numSyms + SafeInt(1),
 					       sizeof(JBIG2HuffmanTable));
     for (i = 0; i < numSyms; ++i) {
       symCodeTab[i].val = i;
@@ -2070,9 +2071,9 @@
 	symCodeTab[i++].prefixLen = j;
       }
     }
-    symCodeTab[numSyms].prefixLen = 0;
-    symCodeTab[numSyms].rangeLen = jbig2HuffmanEOT;
-    huffDecoder->buildTable(symCodeTab, numSyms);
+    symCodeTab[numSyms.Int()].prefixLen = 0;
+    symCodeTab[numSyms.Int()].rangeLen = jbig2HuffmanEOT;
+    huffDecoder->buildTable(symCodeTab, numSyms.Int());
     huffDecoder->reset();
 
   // set up the arithmetic decoder
@@ -2086,7 +2087,7 @@
   }
 
   bitmap = readTextRegion(huff, refine, w, h, numInstances,
-			  logStrips, numSyms, symCodeTab, symCodeLen, syms,
+			  logStrips, numSyms.Int(), symCodeTab, symCodeLen, syms,
 			  defPixel, combOp, transposed, refCorner, sOffset,
 			  huffFSTable, huffDSTable, huffDTTable,
 			  huffRDWTable, huffRDHTable,
@@ -2638,6 +2639,7 @@
       error(getPos(), "Bad width in JBIG2 generic bitmap");
       // force a call to gmalloc(-1), which will throw an exception
       w = -3;
+      gmallocn(w + 2, sizeof(int));
     }
     refLine = (int *)gmallocn(w + 2, sizeof(int));
     codingLine = (int *)gmallocn(w + 2, sizeof(int));
@@ -3314,7 +3316,7 @@
   val = lowVal;
   while (val < highVal) {
     if (i == huffTabSize) {
-      huffTabSize *= 2;
+      huffTabSize = (SafeInt(huffTabSize) * 2).Int();
       huffTab = (JBIG2HuffmanTable *)
 	            greallocn(huffTab, huffTabSize, sizeof(JBIG2HuffmanTable));
     }
--- xpdf-3.02/xpdf/JPXStream.cc
+++ xpdf-3.02/xpdf/JPXStream.cc
@@ -652,7 +652,7 @@
       }
       palette.bpc = (Guint *)gmallocn(palette.nComps, sizeof(Guint));
       palette.c =
-          (int *)gmallocn(palette.nEntries * palette.nComps, sizeof(int));
+          (int *)gmallocn(SafeInt(palette.nEntries) * SafeInt(palette.nComps), sizeof(int));
       for (i = 0; i < palette.nComps; ++i) {
 	if (!readUByte(&palette.bpc[i])) {
 	  error(getPos(), "Unexpected EOF in JPX stream");
@@ -910,7 +910,7 @@
 	error(getPos(), "Bad tile count in JPX SIZ marker segment");
 	return gFalse;
       }
-      img.tiles = (JPXTile *)gmallocn(img.nXTiles * img.nYTiles,
+      img.tiles = (JPXTile *)gmallocn(SafeInt(img.nXTiles) * SafeInt(img.nYTiles),
 				      sizeof(JPXTile));
       for (i = 0; i < img.nXTiles * img.nYTiles; ++i) {
 	img.tiles[i].tileComps = (JPXTileComp *)gmallocn(img.nComps,
@@ -978,7 +978,7 @@
 	  }
 	  img.tiles[i].tileComps[comp].resLevels =
 	      (JPXResLevel *)gmallocn(
-		     (img.tiles[i].tileComps[comp].nDecompLevels + 1),
+		     (SafeInt(img.tiles[i].tileComps[comp].nDecompLevels) + SafeInt(1)),
 		     sizeof(JPXResLevel));
 	  for (r = 0; r <= img.tiles[i].tileComps[comp].nDecompLevels; ++r) {
 	    img.tiles[i].tileComps[comp].resLevels[r].precincts = NULL;
@@ -1055,7 +1055,7 @@
 	img.tiles[i].tileComps[comp].resLevels =
 	    (JPXResLevel *)greallocn(
 		     img.tiles[i].tileComps[comp].resLevels,
-		     (img.tiles[i].tileComps[comp].nDecompLevels + 1),
+		     (SafeInt(img.tiles[i].tileComps[comp].nDecompLevels) + SafeInt(1)),
 		     sizeof(JPXResLevel));
 	for (r = 0; r <= img.tiles[i].tileComps[comp].nDecompLevels; ++r) {
 	  img.tiles[i].tileComps[comp].resLevels[r].precincts = NULL;
@@ -1457,7 +1457,7 @@
 	img.tiles[tileIdx].tileComps[comp].resLevels =
 	    (JPXResLevel *)greallocn(
 		     img.tiles[tileIdx].tileComps[comp].resLevels,
-		     (img.tiles[tileIdx].tileComps[comp].nDecompLevels + 1),
+		     (SafeInt(img.tiles[tileIdx].tileComps[comp].nDecompLevels) + SafeInt(1)),
 		     sizeof(JPXResLevel));
 	for (r = 0;
 	     r <= img.tiles[tileIdx].tileComps[comp].nDecompLevels;
@@ -1512,7 +1512,7 @@
       img.tiles[tileIdx].tileComps[comp].resLevels =
 	  (JPXResLevel *)greallocn(
 		     img.tiles[tileIdx].tileComps[comp].resLevels,
-		     (img.tiles[tileIdx].tileComps[comp].nDecompLevels + 1),
+		     (SafeInt(img.tiles[tileIdx].tileComps[comp].nDecompLevels) + SafeInt(1)),
 		     sizeof(JPXResLevel));
       for (r = 0; r <= img.tiles[tileIdx].tileComps[comp].nDecompLevels; ++r) {
 	img.tiles[tileIdx].tileComps[comp].resLevels[r].precincts = NULL;
@@ -1775,15 +1775,15 @@
       tileComp->y1 = jpxCeilDiv(tile->y1, tileComp->hSep);
       tileComp->cbW = 1 << tileComp->codeBlockW;
       tileComp->cbH = 1 << tileComp->codeBlockH;
-      tileComp->data = (int *)gmallocn((tileComp->x1 - tileComp->x0) *
-				       (tileComp->y1 - tileComp->y0),
+      tileComp->data = (int *)gmallocn((SafeInt(tileComp->x1) - SafeInt(tileComp->x0)) *
+				       (SafeInt(tileComp->y1) - SafeInt(tileComp->y0)),
 				       sizeof(int));
       if (tileComp->x1 - tileComp->x0 > tileComp->y1 - tileComp->y0) {
 	n = tileComp->x1 - tileComp->x0;
       } else {
 	n = tileComp->y1 - tileComp->y0;
       }
-      tileComp->buf = (int *)gmallocn(n + 8, sizeof(int));
+      tileComp->buf = (int *)gmallocn(SafeInt(n) + SafeInt(8), sizeof(int));
       for (r = 0; r <= tileComp->nDecompLevels; ++r) {
 	resLevel = &tileComp->resLevels[r];
 	k = r == 0 ? tileComp->nDecompLevels
@@ -1844,7 +1844,7 @@
 	    for (level = subband->maxTTLevel; level >= 0; --level) {
 	      nx = jpxCeilDivPow2(subband->nXCBs, level);
 	      ny = jpxCeilDivPow2(subband->nYCBs, level);
-	      n += nx * ny;
+	      n += (SafeInt(nx) * SafeInt(ny)).Int();
 	    }
 	    subband->inclusion =
 	        (JPXTagTreeNode *)gmallocn(n, sizeof(JPXTagTreeNode));
@@ -1856,8 +1856,8 @@
 	      subband->zeroBitPlane[k].finished = gFalse;
 	      subband->zeroBitPlane[k].val = 0;
 	    }
-	    subband->cbs = (JPXCodeBlock *)gmallocn(subband->nXCBs *
-						      subband->nYCBs,
+	    subband->cbs = (JPXCodeBlock *)gmallocn(SafeInt(subband->nXCBs) *
+						      SafeInt(subband->nYCBs),
 						    sizeof(JPXCodeBlock));
 	    sbx0 = jpxFloorDivPow2(subband->x0, tileComp->codeBlockW);
 	    sby0 = jpxFloorDivPow2(subband->y0, tileComp->codeBlockH);
@@ -1885,8 +1885,8 @@
 		cb->nextPass = jpxPassCleanup;
 		cb->nZeroBitPlanes = 0;
 		cb->coeffs =
-		    (JPXCoeff *)gmallocn((1 << (tileComp->codeBlockW
-						+ tileComp->codeBlockH)),
+		    (JPXCoeff *)gmallocn((SafeInt(1) << (SafeInt(tileComp->codeBlockW)
+						+ SafeInt(tileComp->codeBlockH)).Int()),
 					 sizeof(JPXCoeff));
 		for (cbi = 0;
 		     cbi < (Guint)(1 << (tileComp->codeBlockW
--- xpdf-3.02/xpdf/Link.cc
+++ xpdf-3.02/xpdf/Link.cc
@@ -725,7 +725,7 @@
 Links::Links(Object *annots, GString *baseURI) {
   Link *link;
   Object obj1, obj2;
-  int size;
+  SafeInt size;
   int i;
 
   links = NULL;
--- xpdf-3.02/xpdf/NameToCharCode.cc
+++ xpdf-3.02/xpdf/NameToCharCode.cc
@@ -49,7 +49,8 @@
 
 void NameToCharCode::add(char *name, CharCode c) {
   NameToCharCodeEntry *oldTab;
-  int h, i, oldSize;
+  int h, i;
+  SafeInt oldSize;
 
   // expand the table if necessary
   if (len >= size / 2) {
@@ -112,5 +113,5 @@
   for (p = name; *p; ++p) {
     h = 17 * h + (int)(*p & 0xff);
   }
-  return (int)(h % size);
+  return (int)(h % size.Int());
 }
--- xpdf-3.02/xpdf/NameToCharCode.h
+++ xpdf-3.02/xpdf/NameToCharCode.h
@@ -35,7 +35,7 @@
   int hash(char *name);
 
   NameToCharCodeEntry *tab;
-  int size;
+  SafeInt size;
   int len;
 };
 
--- xpdf-3.02/xpdf/PSOutputDev.cc
+++ xpdf-3.02/xpdf/PSOutputDev.cc
@@ -2253,11 +2253,11 @@
     if (fontFileNameLen >= fontFileNameSize) {
       fontFileNameSize += 64;
       fontFileNames =
-	(GString **)grealloc(fontFileNames,
-			     fontFileNameSize * sizeof(GString *));
+	(GString **)greallocn(fontFileNames,
+			      fontFileNameSize, sizeof(GString *));
       psFileNames =
-	(GString **)grealloc(psFileNames,
-			     fontFileNameSize * sizeof(GString *));
+	(GString **)greallocn(psFileNames,
+			      fontFileNameSize, sizeof(GString *));
     }
   }
   fontFileNames[fontFileNameLen] = myFileName;
@@ -2274,7 +2274,7 @@
   if ((ffTT = FoFiTrueType::load(fileName->getCString(), faceIndex))) {
       int n = ((GfxCIDFont *)font)->getCIDToGIDLen();
       if (n) {
-	codeToGID = (Gushort *)gmalloc(n * sizeof(Gushort));
+	codeToGID = (Gushort *)gmallocn(n, sizeof(Gushort));
 	memcpy(codeToGID, ((GfxCIDFont *)font)->getCIDToGID(), n * sizeof(Gushort));
       } else {
 	codeToGID = ((GfxCIDFont *)font)->getCodeToGIDMap(ffTT, &n);
@@ -4412,7 +4412,7 @@
 	     width, -height, height);
 
   // allocate a line buffer
-  lineBuf = (Guchar *)gmalloc(4 * width);
+  lineBuf = (Guchar *)gmallocn(4, width);
 
   // set up to process the data stream
   imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
@@ -4465,7 +4465,8 @@
   ImageStream *imgStr;
   Guchar *line;
   PSOutImgClipRect *rects0, *rects1, *rectsTmp, *rectsOut;
-  int rects0Len, rects1Len, rectsSize, rectsOutLen, rectsOutSize;
+  int rects0Len, rects1Len, rectsOutLen;
+  SafeInt rectsOutSize, rectsSize;
   GBool emitRect, addRect, extendRect;
   GString *s;
   int n, numComps;
--- xpdf-3.02/xpdf/PSOutputDev.h
+++ xpdf-3.02/xpdf/PSOutputDev.h
@@ -328,10 +328,10 @@
 
   Ref *fontIDs;			// list of object IDs of all used fonts
   int fontIDLen;		// number of entries in fontIDs array
-  int fontIDSize;		// size of fontIDs array
+  SafeInt fontIDSize;		// size of fontIDs array
   Ref *fontFileIDs;		// list of object IDs of all embedded fonts
   int fontFileIDLen;		// number of entries in fontFileIDs array
-  int fontFileIDSize;		// size of fontFileIDs array
+  SafeInt fontFileIDSize;	// size of fontFileIDs array
   GString **fontFileNames;	// list of names of all embedded external fonts
   GString **psFileNames;	// list of names of all embedded external ps names
   int fontFileNameLen;		// number of entries in fontFileNames array
@@ -340,16 +340,16 @@
 				//   font name
   PSFont8Info *font8Info;	// info for 8-bit fonts
   int font8InfoLen;		// number of entries in font8Info array
-  int font8InfoSize;		// size of font8Info array
+  SafeInt font8InfoSize;	// size of font8Info array
   PSFont16Enc *font16Enc;	// encodings for substitute 16-bit fonts
   int font16EncLen;		// number of entries in font16Enc array
-  int font16EncSize;		// size of font16Enc array
+  SafeInt font16EncSize;	// size of font16Enc array
   Ref *imgIDs;			// list of image IDs for in-memory images
   int imgIDLen;			// number of entries in imgIDs array
-  int imgIDSize;		// size of imgIDs array
+  SafeInt imgIDSize;		// size of imgIDs array
   Ref *formIDs;			// list of IDs for predefined forms
   int formIDLen;		// number of entries in formIDs array
-  int formIDSize;		// size of formIDs array
+  SafeInt formIDSize;		// size of formIDs array
   GList *xobjStack;		// stack of XObject dicts currently being
 				//   processed
   int numSaves;			// current number of gsaves
--- xpdf-3.02/xpdf/SplashOutputDev.cc
+++ xpdf-3.02/xpdf/SplashOutputDev.cc
@@ -488,8 +488,8 @@
   int glyphW, glyphH;		// size of glyph bitmaps, in pixels
   GBool validBBox;		// false if the bbox was [0 0 0 0]
   int glyphSize;		// size of glyph bitmaps, in bytes
-  int cacheSets;		// number of sets in cache
-  int cacheAssoc;		// cache associativity (glyphs per set)
+  SafeInt cacheSets;		// number of sets in cache
+  SafeInt cacheAssoc;		// cache associativity (glyphs per set)
   Guchar *cacheData;		// glyph pixmap cache
   T3FontCacheTag *cacheTags;	// cache tags, i.e., char codes
 };
@@ -529,7 +529,7 @@
   cacheTags = (T3FontCacheTag *)gmallocn(cacheSets * cacheAssoc,
 					 sizeof(T3FontCacheTag));
   for (i = 0; i < cacheSets * cacheAssoc; ++i) {
-    cacheTags[i].mru = i & (cacheAssoc - 1);
+    cacheTags[i].mru = i & (cacheAssoc.Int() - 1);
   }
 }
 
@@ -1537,7 +1537,7 @@
   t3Font = t3FontCache[0];
 
   // is the glyph in the cache?
-  i = (code & (t3Font->cacheSets - 1)) * t3Font->cacheAssoc;
+  i = (code & (t3Font->cacheSets.Int() - 1)) * t3Font->cacheAssoc.Int();
   for (j = 0; j < t3Font->cacheAssoc; ++j) {
     if ((t3Font->cacheTags[i+j].mru & 0x8000) &&
 	t3Font->cacheTags[i+j].code == code) {
@@ -1644,7 +1644,7 @@
   }
 
   // allocate a cache entry
-  i = (t3GlyphStack->code & (t3Font->cacheSets - 1)) * t3Font->cacheAssoc;
+  i = (t3GlyphStack->code & (t3Font->cacheSets.Int() - 1)) * t3Font->cacheAssoc.Int();
   for (j = 0; j < t3Font->cacheAssoc; ++j) {
     if ((t3Font->cacheTags[i+j].mru & 0x7fff) == t3Font->cacheAssoc - 1) {
       t3Font->cacheTags[i+j].mru = 0x8000;
@@ -2008,7 +2008,7 @@
   // build a lookup table here
   imgData.lookup = NULL;
   if (colorMap->getNumPixelComps() == 1) {
-    n = 1 << colorMap->getBits();
+    n = (SafeInt(1) << colorMap->getBits()).Int();
     switch (colorMode) {
     case splashModeMono1:
     case splashModeMono8:
@@ -2021,7 +2021,7 @@
       break;
     case splashModeRGB8:
     case splashModeBGR8:
-      imgData.lookup = (SplashColorPtr)gmalloc(3 * n);
+      imgData.lookup = (SplashColorPtr)gmallocn(3, n);
       for (i = 0; i < n; ++i) {
 	pix = (Guchar)i;
 	colorMap->getRGB(&pix, &rgb);
@@ -2032,7 +2032,7 @@
       break;
 #if SPLASH_CMYK
     case splashModeCMYK8:
-      imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
+      imgData.lookup = (SplashColorPtr)gmallocn(4, n);
       for (i = 0; i < n; ++i) {
 	pix = (Guchar)i;
 	colorMap->getCMYK(&pix, &cmyk);
@@ -2252,7 +2252,7 @@
     // build a lookup table here
     imgData.lookup = NULL;
     if (colorMap->getNumPixelComps() == 1) {
-      n = 1 << colorMap->getBits();
+      n = (SafeInt(1) << colorMap->getBits()).Int();
       switch (colorMode) {
       case splashModeMono1:
       case splashModeMono8:
@@ -2265,7 +2265,7 @@
 	break;
       case splashModeRGB8:
       case splashModeBGR8:
-	imgData.lookup = (SplashColorPtr)gmalloc(3 * n);
+	imgData.lookup = (SplashColorPtr)gmallocn(3, n);
 	for (i = 0; i < n; ++i) {
 	  pix = (Guchar)i;
 	  colorMap->getRGB(&pix, &rgb);
@@ -2276,7 +2276,7 @@
 	break;
 #if SPLASH_CMYK
       case splashModeCMYK8:
-	imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
+	imgData.lookup = (SplashColorPtr)gmallocn(4, n);
 	for (i = 0; i < n; ++i) {
 	  pix = (Guchar)i;
 	  colorMap->getCMYK(&pix, &cmyk);
@@ -2347,7 +2347,7 @@
   imgMaskData.width = maskWidth;
   imgMaskData.height = maskHeight;
   imgMaskData.y = 0;
-  n = 1 << maskColorMap->getBits();
+  n = (SafeInt(1) << maskColorMap->getBits()).Int();
   imgMaskData.lookup = (SplashColorPtr)gmalloc(n);
   for (i = 0; i < n; ++i) {
     pix = (Guchar)i;
@@ -2384,7 +2384,7 @@
   // build a lookup table here
   imgData.lookup = NULL;
   if (colorMap->getNumPixelComps() == 1) {
-    n = 1 << colorMap->getBits();
+    n = (SafeInt(1) << colorMap->getBits()).Int();
     switch (colorMode) {
     case splashModeMono1:
     case splashModeMono8:
@@ -2397,7 +2397,7 @@
       break;
     case splashModeRGB8:
     case splashModeBGR8:
-      imgData.lookup = (SplashColorPtr)gmalloc(3 * n);
+      imgData.lookup = (SplashColorPtr)gmallocn(3, n);
       for (i = 0; i < n; ++i) {
 	pix = (Guchar)i;
 	colorMap->getRGB(&pix, &rgb);
@@ -2408,7 +2408,7 @@
       break;
 #if SPLASH_CMYK
     case splashModeCMYK8:
-      imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
+      imgData.lookup = (SplashColorPtr)gmallocn(4, n);
       for (i = 0; i < n; ++i) {
 	pix = (Guchar)i;
 	colorMap->getCMYK(&pix, &cmyk);
--- xpdf-3.02/xpdf/Stream.cc
+++ xpdf-3.02/xpdf/Stream.cc
@@ -319,7 +319,7 @@
 
   nVals = width * nComps;
   if (nBits == 1) {
-    imgLineSize = (nVals + 7) & ~7;
+    imgLineSize = (SafeInt(nVals) + SafeInt(7)).Int() & ~7;
   } else {
     imgLineSize = nVals;
   }
@@ -492,7 +492,7 @@
       break;
     case 13:			// PNG average
       predLine[i] = ((predLine[i - pixBytes] + predLine[i]) >> 1) +
-	            (Guchar)c;
+		    (Guchar)c;
       break;
     case 14:			// PNG Paeth
       left = predLine[i - pixBytes];
@@ -1253,8 +1253,8 @@
   // ---> max codingLine size = columns + 1
   // refLine has one extra guard entry at the end
   // ---> max refLine size = columns + 2
-  codingLine = (int *)gmallocn(columns + 1, sizeof(int));
-  refLine = (int *)gmallocn(columns + 2, sizeof(int));
+  codingLine = (int *)gmallocn(SafeInt(columns) + SafeInt(1), sizeof(int));
+  refLine = (int *)gmallocn(SafeInt(columns) + SafeInt(2), sizeof(int));
 
   eof = gFalse;
   row = 0;
@@ -1969,7 +1969,7 @@
   restartInterval = 0;
 
   if (!readHeader()) {
-    y = height;
+    y = height.Int();
     return;
   }
 
@@ -2014,12 +2014,12 @@
     if (bufWidth <= 0 || bufHeight <= 0 ||
 	bufWidth > INT_MAX / bufWidth / (int)sizeof(int)) {
       error(getPos(), "Invalid image size in DCT stream");
-      y = height;
+      y = height.Int();
       return;
     }
     for (i = 0; i < numComps; ++i) {
       frameBuf[i] = (int *)gmallocn(bufWidth * bufHeight, sizeof(int));
-      memset(frameBuf[i], 0, bufWidth * bufHeight * sizeof(int));
+      memset(frameBuf[i], 0, (bufWidth * bufHeight * sizeof(int)).Int());
     }
 
     // read the image data
@@ -2051,7 +2051,7 @@
     comp = 0;
     x = 0;
     y = 0;
-    dy = mcuHeight;
+    dy = mcuHeight.Int();
 
     restartMarker = 0xd0;
     restart();
@@ -2079,7 +2079,7 @@
     return EOF;
   }
   if (progressive || !interleaved) {
-    c = frameBuf[comp][y * bufWidth + x];
+    c = frameBuf[comp][y * bufWidth.Int() + x];
     if (++comp == numComps) {
       comp = 0;
       if (++x == width) {
@@ -2090,7 +2090,7 @@
   } else {
     if (dy >= mcuHeight) {
       if (!readMCURow()) {
-	y = height;
+	y = height.Int();
 	return EOF;
       }
       comp = 0;
@@ -2118,11 +2118,11 @@
     return EOF;
   }
   if (progressive || !interleaved) {
-    return frameBuf[comp][y * bufWidth + x];
+    return frameBuf[comp][y * bufWidth.Int() + x];
   } else {
     if (dy >= mcuHeight) {
       if (!readMCURow()) {
-	y = height;
+	y = height.Int();
 	return EOF;
       }
       comp = 0;
@@ -2154,7 +2154,7 @@
   int x1, x2, y2, x3, y3, x4, y4, x5, y5, cc, i;
   int c;
 
-  for (x1 = 0; x1 < width; x1 += mcuWidth) {
+  for (x1 = 0; x1 < width; x1 += mcuWidth.Int()) {
 
     // deal with restart marker
     if (restartInterval > 0 && restartCtr == 0) {
@@ -2172,8 +2172,8 @@
     for (cc = 0; cc < numComps; ++cc) {
       h = compInfo[cc].hSample;
       v = compInfo[cc].vSample;
-      horiz = mcuWidth / h;
-      vert = mcuHeight / v;
+      horiz = mcuWidth.Int() / h;
+      vert = mcuHeight.Int() / v;
       hSub = horiz / 8;
       vSub = vert / 8;
       for (y2 = 0; y2 < mcuHeight; y2 += vert) {
@@ -2279,11 +2279,11 @@
 	break;
       }
     }
-    dx1 = mcuWidth / compInfo[cc].hSample;
-    dy1 = mcuHeight / compInfo[cc].vSample;
+    dx1 = mcuWidth.Int() / compInfo[cc].hSample;
+    dy1 = mcuHeight.Int() / compInfo[cc].vSample;
   } else {
-    dx1 = mcuWidth;
-    dy1 = mcuHeight;
+    dx1 = mcuWidth.Int();
+    dy1 = mcuHeight.Int();
   }
 
   for (y1 = 0; y1 < height; y1 += dy1) {
@@ -2310,14 +2310,14 @@
 
 	h = compInfo[cc].hSample;
 	v = compInfo[cc].vSample;
-	horiz = mcuWidth / h;
-	vert = mcuHeight / v;
+	horiz = mcuWidth.Int() / h;
+	vert = mcuHeight.Int() / v;
 	vSub = vert / 8;
 	for (y2 = 0; y2 < dy1; y2 += vert) {
 	  for (x2 = 0; x2 < dx1; x2 += horiz) {
 
 	    // pull out the current values
-	    p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
+	    p1 = &frameBuf[cc][(y1+y2) * bufWidth.Int() + (x1+x2)];
 	    for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
 	      data[i] = p1[0];
 	      data[i+1] = p1[1];
@@ -2327,7 +2327,7 @@
 	      data[i+5] = p1[5];
 	      data[i+6] = p1[6];
 	      data[i+7] = p1[7];
-	      p1 += bufWidth * vSub;
+	      p1 += bufWidth.Int() * vSub;
 	    }
 
 	    // read one data unit
@@ -2349,7 +2349,7 @@
 	    }
 
 	    // add the data unit into frameBuf
-	    p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
+	    p1 = &frameBuf[cc][(y1+y2) * bufWidth.Int() + (x1+x2)];
 	    for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
 	      p1[0] = data[i];
 	      p1[1] = data[i+1];
@@ -2359,7 +2359,7 @@
 	      p1[5] = data[i+5];
 	      p1[6] = data[i+6];
 	      p1[7] = data[i+7];
-	      p1 += bufWidth * vSub;
+	      p1 += bufWidth.Int() * vSub;
 	    }
 	  }
 	}
@@ -2556,21 +2556,21 @@
   int h, v, horiz, vert, hSub, vSub;
   int *p0, *p1, *p2;
 
-  for (y1 = 0; y1 < bufHeight; y1 += mcuHeight) {
-    for (x1 = 0; x1 < bufWidth; x1 += mcuWidth) {
+  for (y1 = 0; y1 < bufHeight; y1 += mcuHeight.Int()) {
+    for (x1 = 0; x1 < bufWidth; x1 += mcuWidth.Int()) {
       for (cc = 0; cc < numComps; ++cc) {
 	quantTable = quantTables[compInfo[cc].quantTable];
 	h = compInfo[cc].hSample;
 	v = compInfo[cc].vSample;
-	horiz = mcuWidth / h;
-	vert = mcuHeight / v;
+	horiz = mcuWidth.Int() / h;
+	vert = mcuHeight.Int() / v;
 	hSub = horiz / 8;
 	vSub = vert / 8;
 	for (y2 = 0; y2 < mcuHeight; y2 += vert) {
 	  for (x2 = 0; x2 < mcuWidth; x2 += horiz) {
 
 	    // pull out the coded data unit
-	    p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
+	    p1 = &frameBuf[cc][(y1+y2) * bufWidth.Int() + (x1+x2)];
 	    for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
 	      dataIn[i]   = p1[0];
 	      dataIn[i+1] = p1[1];
@@ -2580,7 +2580,7 @@
 	      dataIn[i+5] = p1[5];
 	      dataIn[i+6] = p1[6];
 	      dataIn[i+7] = p1[7];
-	      p1 += bufWidth * vSub;
+	      p1 += bufWidth.Int() * vSub;
 	    }
 
 	    // transform
@@ -2588,7 +2588,7 @@
 
 	    // store back into frameBuf, doing replication for
 	    // subsampled components
-	    p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
+	    p1 = &frameBuf[cc][(y1+y2) * bufWidth.Int() + (x1+x2)];
 	    if (hSub == 1 && vSub == 1) {
 	      for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
 		p1[0] = dataOut[i] & 0xff;
@@ -2599,10 +2599,10 @@
 		p1[5] = dataOut[i+5] & 0xff;
 		p1[6] = dataOut[i+6] & 0xff;
 		p1[7] = dataOut[i+7] & 0xff;
-		p1 += bufWidth;
+		p1 += bufWidth.Int();
 	      }
 	    } else if (hSub == 2 && vSub == 2) {
-	      p2 = p1 + bufWidth;
+	      p2 = p1 + bufWidth.Int();
 	      for (y3 = 0, i = 0; y3 < 16; y3 += 2, i += 8) {
 		p1[0] = p1[1] = p2[0] = p2[1] = dataOut[i] & 0xff;
 		p1[2] = p1[3] = p2[2] = p2[3] = dataOut[i+1] & 0xff;
@@ -2612,8 +2612,8 @@
 		p1[10] = p1[11] = p2[10] = p2[11] = dataOut[i+5] & 0xff;
 		p1[12] = p1[13] = p2[12] = p2[13] = dataOut[i+6] & 0xff;
 		p1[14] = p1[15] = p2[14] = p2[15] = dataOut[i+7] & 0xff;
-		p1 += bufWidth * 2;
-		p2 += bufWidth * 2;
+		p1 += bufWidth.Int() * 2;
+		p2 += bufWidth.Int() * 2;
 	      }
 	    } else {
 	      i = 0;
@@ -2624,11 +2624,11 @@
 		    for (x5 = 0; x5 < hSub; ++x5) {
 		      p2[x5] = dataOut[i] & 0xff;
 		    }
-		    p2 += bufWidth;
+		    p2 += bufWidth.Int();
 		  }
 		  ++i;
 		}
-		p1 += bufWidth * vSub;
+		p1 += bufWidth.Int() * vSub;
 	      }
 	    }
 	  }
@@ -2640,9 +2640,9 @@
 	// convert YCbCr to RGB
 	if (numComps == 3) {
 	  for (y2 = 0; y2 < mcuHeight; ++y2) {
-	    p0 = &frameBuf[0][(y1+y2) * bufWidth + x1];
-	    p1 = &frameBuf[1][(y1+y2) * bufWidth + x1];
-	    p2 = &frameBuf[2][(y1+y2) * bufWidth + x1];
+	    p0 = &frameBuf[0][(y1+y2) * bufWidth.Int() + x1];
+	    p1 = &frameBuf[1][(y1+y2) * bufWidth.Int() + x1];
+	    p2 = &frameBuf[2][(y1+y2) * bufWidth.Int() + x1];
 	    for (x2 = 0; x2 < mcuWidth; ++x2) {
 	      pY = *p0;
 	      pCb = *p1 - 128;
@@ -2659,9 +2659,9 @@
 	// convert YCbCrK to CMYK (K is passed through unchanged)
 	} else if (numComps == 4) {
 	  for (y2 = 0; y2 < mcuHeight; ++y2) {
-	    p0 = &frameBuf[0][(y1+y2) * bufWidth + x1];
-	    p1 = &frameBuf[1][(y1+y2) * bufWidth + x1];
-	    p2 = &frameBuf[2][(y1+y2) * bufWidth + x1];
+	    p0 = &frameBuf[0][(y1+y2) * bufWidth.Int() + x1];
+	    p1 = &frameBuf[1][(y1+y2) * bufWidth.Int() + x1];
+	    p2 = &frameBuf[2][(y1+y2) * bufWidth.Int() + x1];
 	    for (x2 = 0; x2 < mcuWidth; ++x2) {
 	      pY = *p0;
 	      pCb = *p1 - 128;
@@ -4321,7 +4321,7 @@
   }
 
   // allocate the table
-  tabSize = 1 << tab->maxLen;
+  tabSize = (SafeInt(1) << tab->maxLen).Int();
   tab->codes = (FlateCode *)gmallocn(tabSize, sizeof(FlateCode));
 
   // clear the table
--- xpdf-3.02/xpdf/Stream.h
+++ xpdf-3.02/xpdf/Stream.h
@@ -592,9 +592,9 @@
 
   GBool progressive;		// set if in progressive mode
   GBool interleaved;		// set if in interleaved mode
-  int width, height;		// image size
-  int mcuWidth, mcuHeight;	// size of min coding unit, in data units
-  int bufWidth, bufHeight;	// frameBuf size
+  SafeInt width, height;	// image size
+  SafeInt mcuWidth, mcuHeight;	// size of min coding unit, in data units
+  SafeInt bufWidth, bufHeight;	// frameBuf size
   DCTCompInfo compInfo[4];	// info for each component
   DCTScanInfo scanInfo;		// info for the current scan
   int numComps;			// number of components in image
--- xpdf-3.02/xpdf/TextOutputDev.cc
+++ xpdf-3.02/xpdf/TextOutputDev.cc
@@ -263,7 +263,7 @@
   }
   text = NULL;
   edge = NULL;
-  len = size = 0;
+  size = len = 0;
   spaceAfter = gFalse;
   next = NULL;
 
@@ -346,9 +346,9 @@
     yMax = word->yMax;
   }
   if (len + word->len > size) {
-    size = len + word->len;
+    size = SafeInt(len) + SafeInt(word->len);
     text = (Unicode *)greallocn(text, size, sizeof(Unicode));
-    edge = (double *)greallocn(edge, size + 1, sizeof(double));
+    edge = (double *)greallocn(edge, size + SafeInt(1), sizeof(double));
   }
   for (i = 0; i < word->len; ++i) {
     text[len + i] = word->text[i];
@@ -481,11 +481,11 @@
 }
 
 TextPool::~TextPool() {
-  int baseIdx;
+  SafeInt baseIdx;
   TextWord *word, *word2;
 
   for (baseIdx = minBaseIdx; baseIdx <= maxBaseIdx; ++baseIdx) {
-    for (word = pool[baseIdx - minBaseIdx]; word; word = word2) {
+    for (word = pool[(baseIdx - minBaseIdx).Int()]; word; word = word2) {
       word2 = word->next;
       delete word;
     }
@@ -498,17 +498,17 @@
 
   baseIdx = (int)(base / textPoolStep);
   if (baseIdx < minBaseIdx) {
-    return minBaseIdx;
+    return minBaseIdx.Int();
   }
   if (baseIdx > maxBaseIdx) {
-    return maxBaseIdx;
+    return maxBaseIdx.Int();
   }
   return baseIdx;
 }
 
 void TextPool::addWord(TextWord *word) {
   TextWord **newPool;
-  int wordBaseIdx, newMinBaseIdx, newMaxBaseIdx, baseIdx;
+  SafeInt wordBaseIdx, newMinBaseIdx, newMaxBaseIdx, baseIdx;
   TextWord *w0, *w1;
 
   // expand the array if needed
@@ -516,29 +516,29 @@
   if (minBaseIdx > maxBaseIdx) {
     minBaseIdx = wordBaseIdx - 128;
     maxBaseIdx = wordBaseIdx + 128;
-    pool = (TextWord **)gmallocn(maxBaseIdx - minBaseIdx + 1,
+    pool = (TextWord **)gmallocn(maxBaseIdx - minBaseIdx + SafeInt(1),
 				 sizeof(TextWord *));
     for (baseIdx = minBaseIdx; baseIdx <= maxBaseIdx; ++baseIdx) {
-      pool[baseIdx - minBaseIdx] = NULL;
+      pool[(baseIdx - minBaseIdx).Int()] = NULL;
     }
   } else if (wordBaseIdx < minBaseIdx) {
     newMinBaseIdx = wordBaseIdx - 128;
-    newPool = (TextWord **)gmallocn(maxBaseIdx - newMinBaseIdx + 1,
+    newPool = (TextWord **)gmallocn(maxBaseIdx - newMinBaseIdx + SafeInt(1),
 				    sizeof(TextWord *));
     for (baseIdx = newMinBaseIdx; baseIdx < minBaseIdx; ++baseIdx) {
-      newPool[baseIdx - newMinBaseIdx] = NULL;
+      newPool[(baseIdx - newMinBaseIdx).Int()] = NULL;
     }
-    memcpy(&newPool[minBaseIdx - newMinBaseIdx], pool,
-	   (maxBaseIdx - minBaseIdx + 1) * sizeof(TextWord *));
+    memcpy(&newPool[(minBaseIdx - newMinBaseIdx).Int()], pool,
+	   ((maxBaseIdx - minBaseIdx + 1) * sizeof(TextWord *)).Int());
     gfree(pool);
     pool = newPool;
     minBaseIdx = newMinBaseIdx;
   } else if (wordBaseIdx > maxBaseIdx) {
     newMaxBaseIdx = wordBaseIdx + 128;
-    pool = (TextWord **)greallocn(pool, newMaxBaseIdx - minBaseIdx + 1,
+    pool = (TextWord **)greallocn(pool, newMaxBaseIdx - minBaseIdx + SafeInt(1),
 				  sizeof(TextWord *));
     for (baseIdx = maxBaseIdx + 1; baseIdx <= newMaxBaseIdx; ++baseIdx) {
-      pool[baseIdx - minBaseIdx] = NULL;
+      pool[(baseIdx - minBaseIdx).Int()] = NULL;
     }
     maxBaseIdx = newMaxBaseIdx;
   }
@@ -550,17 +550,17 @@
     w1 = cursor->next;
   } else {
     w0 = NULL;
-    w1 = pool[wordBaseIdx - minBaseIdx];
+    w1 = pool[(wordBaseIdx - minBaseIdx).Int()];
   }
   for (; w1 && word->primaryCmp(w1) > 0; w0 = w1, w1 = w1->next) ;
   word->next = w1;
   if (w0) {
     w0->next = word;
   } else {
-    pool[wordBaseIdx - minBaseIdx] = word;
+    pool[(wordBaseIdx - minBaseIdx).Int()] = word;
   }
   cursor = word;
-  cursorBaseIdx = wordBaseIdx;
+  cursorBaseIdx = wordBaseIdx.Int();
 }
 
 //------------------------------------------------------------------------
@@ -763,7 +763,7 @@
     }
   }
   text = (Unicode *)gmallocn(len, sizeof(Unicode));
-  edge = (double *)gmallocn(len + 1, sizeof(double));
+  edge = (double *)gmallocn(len + SafeInt(1), sizeof(double));
   i = 0;
   for (word1 = words; word1; word1 = word1->next) {
     for (j = 0; j < word1->len; ++j) {
@@ -779,7 +779,7 @@
   }
 
   // compute convertedLen and set up the col array
-  col = (int *)gmallocn(len + 1, sizeof(int));
+  col = (int *)gmallocn(len + SafeInt(1), sizeof(int));
   convertedLen = 0;
   for (i = 0; i < len; ++i) {
     col[i] = convertedLen;
@@ -789,11 +789,11 @@
       convertedLen += uMap->mapUnicode(text[i], buf, sizeof(buf));
     }
   }
-  col[len] = convertedLen;
+  col[len.Int()] = convertedLen;
 
   // check for hyphen at end of line
   //~ need to check for other chars used as hyphens
-  hyphenated = text[len - 1] == (Unicode)'-';
+  hyphenated = text[(len - 1).Int()] == (Unicode)'-';
 }
 
 //------------------------------------------------------------------------
@@ -1163,7 +1163,7 @@
   int i, j, k;
 
   // discard duplicated text (fake boldface, drop shadows)
-  for (idx0 = pool->minBaseIdx; idx0 <= pool->maxBaseIdx; ++idx0) {
+  for (idx0 = pool->minBaseIdx.Int(); idx0 <= pool->maxBaseIdx.Int(); ++idx0) {
     word0 = pool->getPool(idx0);
     while (word0) {
       priDelta = dupMaxPriDelta * word0->fontSize;
@@ -1227,7 +1227,7 @@
 
   // build the lines
   curLine = NULL;
-  poolMinBaseIdx = pool->minBaseIdx;
+  poolMinBaseIdx = pool->minBaseIdx.Int();
   charCount = 0;
   nLines = 0;
   while (1) {
@@ -1329,7 +1329,7 @@
     line->next = line1;
     curLine = line;
     line->coalesce(uMap);
-    charCount += line->len;
+    charCount += line->len.Int();
     ++nLines;
   }
 
@@ -1338,7 +1338,7 @@
   for (line = lines, i = 0; line; line = line->next, ++i) {
     lineArray[i] = line;
   }
-  qsort(lineArray, nLines, sizeof(TextLine *), &TextLine::cmpXY);
+  qsort(lineArray, nLines.Int(), sizeof(TextLine *), &TextLine::cmpXY);
 
   // column assignment
   nColumns = 0;
@@ -1348,7 +1348,7 @@
     for (j = 0; j < i; ++j) {
       line1 = lineArray[j];
       if (line1->primaryDelta(line0) >= 0) {
-	col2 = line1->col[line1->len] + 1;
+	col2 = line1->col[line1->len.Int()] + 1;
       } else {
 	k = 0; // make gcc happy
 	switch (rot) {
@@ -1386,8 +1386,8 @@
     for (k = 0; k <= line0->len; ++k) {
       line0->col[k] += col1;
     }
-    if (line0->col[line0->len] > nColumns) {
-      nColumns = line0->col[line0->len];
+    if (line0->col[line0->len.Int()] > nColumns) {
+      nColumns = line0->col[line0->len.Int()];
     }
   }
   gfree(lineArray);
@@ -1660,7 +1660,8 @@
   TextLine *line;
   TextWord *word;
   TextWord **wordArray;
-  int nWords, i;
+  SafeInt nWords;
+  int i;
 
   words = new GList();
 
@@ -2125,7 +2126,8 @@
   GBool found;
   int count[4];
   int lrCount;
-  int firstBlkIdx, nBlocksLeft;
+  int firstBlkIdx;
+  SafeInt nBlocksLeft;
   int col1, col2;
   int i, j, n;
 
@@ -2311,7 +2313,7 @@
   // build blocks for each rotation value
   for (rot = 0; rot < 4; ++rot) {
     pool = pools[rot];
-    poolMinBaseIdx = pool->minBaseIdx;
+    poolMinBaseIdx = pool->minBaseIdx.Int();
     count[rot] = 0;
 
     // add blocks until no more words are left
@@ -2679,7 +2681,7 @@
   for (blk = blkList, i = 0; blk; blk = blk->next, ++i) {
     blocks[i] = blk;
   }
-  qsort(blocks, nBlocks, sizeof(TextBlock *), &TextBlock::cmpXYPrimaryRot);
+  qsort(blocks, nBlocks.Int(), sizeof(TextBlock *), &TextBlock::cmpXYPrimaryRot);
 
   // column assignment
   for (i = 0; i < nBlocks; ++i) {
@@ -2771,7 +2773,7 @@
   //----- reading order sort
 
   // sort blocks into yx order (in preparation for reading order sort)
-  qsort(blocks, nBlocks, sizeof(TextBlock *), &TextBlock::cmpYXPrimaryRot);
+  qsort(blocks, nBlocks.Int(), sizeof(TextBlock *), &TextBlock::cmpYXPrimaryRot);
 
   // compute space on left and right sides of each block
   for (i = 0; i < nBlocks; ++i) {
@@ -2811,7 +2813,7 @@
   //~ this needs to be adjusted for writing mode (vertical text)
   //~ this also needs to account for right-to-left column ordering
   blkArray = (TextBlock **)gmallocn(nBlocks, sizeof(TextBlock *));
-  memcpy(blkArray, blocks, nBlocks * sizeof(TextBlock *));
+  memcpy(blkArray, blocks, nBlocks.Int() * sizeof(TextBlock *));
   flows = lastFlow = NULL;
   firstBlkIdx = 0;
   nBlocksLeft = nBlocks;
@@ -2983,7 +2985,7 @@
   xMin0 = xMax0 = yMin0 = yMax0 = 0; // make gcc happy
   xMin1 = xMax1 = yMin1 = yMax1 = 0; // make gcc happy
 
-  for (i = backward ? nBlocks - 1 : 0;
+  for (i = backward ? (nBlocks - 1).Int() : 0;
        backward ? i >= 0 : i < nBlocks;
        i += backward ? -1 : 1) {
     blk = blocks[i];
@@ -3013,7 +3015,7 @@
       }
 
       // convert the line to uppercase
-      m = line->len;
+      m = line->len.Int();
       if (!caseSensitive) {
 	if (m > txtSize) {
 	  txt = (Unicode *)greallocn(txt, m, sizeof(Unicode));
@@ -3134,7 +3136,8 @@
   TextBlock *blk;
   TextLine *line;
   TextLineFrag *frags;
-  int nFrags, fragsSize;
+  int nFrags;
+  SafeInt fragsSize;
   TextLineFrag *frag;
   char space[8], eol[16];
   int spaceLen, eolLen;
@@ -3197,7 +3200,7 @@
 		}
 		++j;
 	      }
-	      j = line->len - 1;
+	      j = (line->len - 1).Int();
 	      while (j >= 0) {
 		if (0.5 * (line->edge[j] + line->edge[j+1]) < xMax) {
 		  idx1 = j;
@@ -3218,7 +3221,7 @@
 		}
 		++j;
 	      }
-	      j = line->len - 1;
+	      j = (line->len - 1).Int();
 	      while (j >= 0) {
 		if (0.5 * (line->edge[j] + line->edge[j+1]) < yMax) {
 		  idx1 = j;
@@ -3239,7 +3242,7 @@
 		}
 		++j;
 	      }
-	      j = line->len - 1;
+	      j = (line->len - 1).Int();
 	      while (j >= 0) {
 		if (0.5 * (line->edge[j] + line->edge[j+1]) > xMin) {
 		  idx1 = j;
@@ -3260,7 +3263,7 @@
 		}
 		++j;
 	      }
-	      j = line->len - 1;
+	      j = (line->len - 1).Int();
 	      while (j >= 0) {
 		if (0.5 * (line->edge[j] + line->edge[j+1]) > yMin) {
 		  idx1 = j;
@@ -3449,7 +3452,8 @@
   TextLine *line;
   TextLineFrag *frags;
   TextWord *word;
-  int nFrags, fragsSize;
+  int nFrags;
+  SafeInt fragsSize;
   TextLineFrag *frag;
   char space[8], eol[16], eop[8];
   int spaceLen, eolLen, eopLen;
@@ -3515,7 +3519,7 @@
 	  frags = (TextLineFrag *)greallocn(frags,
 					    fragsSize, sizeof(TextLineFrag));
 	}
-	frags[nFrags].init(line, 0, line->len);
+	frags[nFrags].init(line, 0, line->len.Int());
 	frags[nFrags].computeCoords(gTrue);
 	++nFrags;
       }
@@ -3592,7 +3596,7 @@
     for (flow = flows; flow; flow = flow->next) {
       for (blk = flow->blocks; blk; blk = blk->next) {
 	for (line = blk->lines; line; line = line->next) {
-	  n = line->len;
+	  n = line->len.Int();
 	  if (line->hyphenated && (line->next || blk->next)) {
 	    --n;
 	  }
--- xpdf-3.02/xpdf/TextOutputDev.h
+++ xpdf-3.02/xpdf/TextOutputDev.h
@@ -145,7 +145,7 @@
   double *edge;			// "near" edge x or y coord of each char
 				//   (plus one extra entry for the last char)
   int len;			// length of text and edge arrays
-  int size;			// size of text and edge arrays
+  SafeInt size;			// size of text and edge arrays
   int charPos;                  // character position (within content stream)
   int charLen;                  // number of content stream characters in
                                 //   this word
@@ -182,8 +182,8 @@
   TextPool();
   ~TextPool();
 
-  TextWord *getPool(int baseIdx) { return pool[baseIdx - minBaseIdx]; }
-  void setPool(int baseIdx, TextWord *p) { pool[baseIdx - minBaseIdx] = p; }
+  TextWord *getPool(int baseIdx) { return pool[(baseIdx - minBaseIdx).Int()]; }
+  void setPool(int baseIdx, TextWord *p) { pool[(baseIdx - minBaseIdx).Int()] = p; }
 
   int getBaseIdx(double base);
 
@@ -191,8 +191,8 @@
 
 private:
 
-  int minBaseIdx;		// min baseline bucket index
-  int maxBaseIdx;		// max baseline bucket index
+  SafeInt minBaseIdx;		// min baseline bucket index
+  SafeInt maxBaseIdx;		// max baseline bucket index
   TextWord **pool;		// array of linked lists, one for each
 				//   baseline value (multiple of 4 pts)
   TextWord *cursor;		// pointer to last-accessed word
@@ -256,7 +256,7 @@
   double *edge;			// "near" edge x or y coord of each char
 				//   (plus one extra entry for the last char)
   int *col;			// starting column number of each Unicode char
-  int len;			// number of Unicode chars
+  SafeInt len;			// number of Unicode chars
   int convertedLen;		// total number of converted characters
   GBool hyphenated;		// set if last char is a hyphen
   TextLine *next;		// next line in block
@@ -315,7 +315,7 @@
 				//   are built)
   TextLine *lines;		// linked list of lines
   TextLine *curLine;		// most recently added line
-  int nLines;			// number of lines
+  SafeInt nLines;			// number of lines
   int charCount;		// number of characters in the block
   int col;			// starting column
   int nColumns;			// number of columns in the block
@@ -506,7 +506,7 @@
   TextPool *pools[4];		// a "pool" of TextWords for each rotation
   TextFlow *flows;		// linked list of flows
   TextBlock **blocks;		// array of blocks, in yx order
-  int nBlocks;			// number of blocks
+  SafeInt nBlocks;		// number of blocks
   int primaryRot;		// primary rotation
   GBool primaryLR;		// primary direction (true means L-to-R,
 				//   false means R-to-L)
--- xpdf-3.02/xpdf/UnicodeMap.cc
+++ xpdf-3.02/xpdf/UnicodeMap.cc
@@ -39,7 +39,7 @@
   UnicodeMap *map;
   UnicodeMapRange *range;
   UnicodeMapExt *eMap;
-  int size, eMapsSize;
+  SafeInt size, eMapsSize;
   char buf[256];
   int line, nBytes, i, x;
   char *tok1, *tok2, *tok3;
--- xpdf-3.02/xpdf/XPDFCore.cc
+++ xpdf-3.02/xpdf/XPDFCore.cc
@@ -763,7 +763,8 @@
   int nVisuals;
   XColor xcolor;
   XColor *xcolors;
-  int r, g, b, n, m;
+  int r, g, b, n;
+  SafeInt m;
   GBool ok;
 
   // for some reason, querying XmNvisual doesn't work (even if done
@@ -808,13 +809,13 @@
     // set colors in private colormap
     if (installCmap) {
       for (rgbCubeSize = xMaxRGBCube; rgbCubeSize >= 2; --rgbCubeSize) {
-        m = rgbCubeSize * rgbCubeSize * rgbCubeSize;
-        if (XAllocColorCells(display, colormap, False, NULL, 0, colors, m)) {
+        m = SafeInt(rgbCubeSize) * SafeInt(rgbCubeSize) * SafeInt(rgbCubeSize);
+        if (XAllocColorCells(display, colormap, False, NULL, 0, colors, m.Int())) {
           break;
         }
       }
       if (rgbCubeSize >= 2) {
-        m = rgbCubeSize * rgbCubeSize * rgbCubeSize;
+        m = SafeInt(rgbCubeSize) * SafeInt(rgbCubeSize) * SafeInt(rgbCubeSize);
         xcolors = (XColor *)gmallocn(m, sizeof(XColor));
         n = 0;
         for (r = 0; r < rgbCubeSize; ++r) {
@@ -829,7 +830,7 @@
             }
           }
         }
-        XStoreColors(display, colormap, xcolors, m);
+        XStoreColors(display, colormap, xcolors, m.Int());
         gfree(xcolors);
       } else {
         rgbCubeSize = 1;
@@ -1174,7 +1175,7 @@
     w = tile->xMax - tile->xMin;
     h = tile->yMax - tile->yMin;
     image = XCreateImage(display, visual, depth, ZPixmap, 0, NULL, w, h, 8, 0);
-    image->data = (char *)gmalloc(h * image->bytes_per_line);
+    image->data = (char *)gmalloc((SafeInt(h) * SafeInt(image->bytes_per_line)).Int());
     tile->image = image;
   } else {
     image = (XImage *)tile->image;
@@ -1247,9 +1248,9 @@
     }
   } else {
     // do Floyd-Steinberg dithering on the whole bitmap
-    errDownR = (int *)gmallocn(width + 2, sizeof(int));
-    errDownG = (int *)gmallocn(width + 2, sizeof(int));
-    errDownB = (int *)gmallocn(width + 2, sizeof(int));
+    errDownR = (int *)gmallocn(SafeInt(width) + SafeInt(2), sizeof(int));
+    errDownG = (int *)gmallocn(SafeInt(width) + SafeInt(2), sizeof(int));
+    errDownB = (int *)gmallocn(SafeInt(width) + SafeInt(2), sizeof(int));
     errRightR = errRightG = errRightB = 0;
     errDownRightR = errDownRightG = errDownRightB = 0;
     memset(errDownR, 0, (width + 2) * sizeof(int));
--- xpdf-3.02/xpdf/XPDFViewer.cc
+++ xpdf-3.02/xpdf/XPDFViewer.cc
@@ -262,7 +262,7 @@
   ok = gFalse;
 #ifndef DISABLE_OUTLINE
   outlineLabels = NULL;
-  outlineLabelsLength = outlineLabelsSize = 0;
+  outlineLabelsSize = outlineLabelsLength = 0;
   outlinePaneWidth = 175;
 #endif
   viewerTitle = NULL;
@@ -323,7 +323,7 @@
   ok = gFalse;
 #ifndef DISABLE_OUTLINE
   outlineLabels = NULL;
-  outlineLabelsLength = outlineLabelsSize = 0;
+  outlineLabelsSize = outlineLabelsLength = 0;
   outlinePaneWidth = 175;
 #endif
   viewerTitle = NULL;
@@ -2756,7 +2756,7 @@
     }
     gfree(outlineLabels);
     outlineLabels = NULL;
-    outlineLabelsLength = outlineLabelsSize = 0;
+    outlineLabelsSize = outlineLabelsLength = 0;
   }
 
   if (core->getDoc()) {
--- xpdf-3.02/xpdf/XPDFViewer.h
+++ xpdf-3.02/xpdf/XPDFViewer.h
@@ -305,7 +305,7 @@
   Widget outlineTree;
   Widget *outlineLabels;
   int outlineLabelsLength;
-  int outlineLabelsSize;
+  SafeInt outlineLabelsSize;
   Dimension outlinePaneWidth;
 #endif
   XPDFCore *core;
--- xpdf-3.02/xpdf/XRef.cc
+++ xpdf-3.02/xpdf/XRef.cc
@@ -350,7 +350,8 @@
   GBool more;
   Object obj, obj2;
   Guint pos2;
-  int first, n, newSize, i;
+  int first, n, i;
+  SafeInt newSize;
 
   while (1) {
     parser->getObj(&obj);
@@ -372,7 +373,7 @@
       goto err1;
     }
     if (first + n > size) {
-      for (newSize = size ? 2 * size : 1024;
+      for (newSize = size ? SafeInt(2) * SafeInt(size) : 1024;
 	   first + n > newSize && newSize > 0;
 	   newSize <<= 1) ;
       if (newSize < 0) {
@@ -383,7 +384,7 @@
 	entries[i].offset = 0xffffffff;
 	entries[i].type = xrefEntryFree;
       }
-      size = newSize;
+      size = newSize.Int();
     }
     for (i = first; i < first + n; ++i) {
       if (!parser->getObj(&obj)->isInt()) {
@@ -471,7 +472,7 @@
   int w[3];
   GBool more;
   Object obj, obj2, idx;
-  int newSize, first, n, i;
+  int first, n, i, newSize;
 
   dict = xrefStr->getDict();
 
@@ -562,13 +563,14 @@
 
 GBool XRef::readXRefStreamSection(Stream *xrefStr, int *w, int first, int n) {
   Guint offset;
-  int type, gen, c, newSize, i, j;
+  int type, gen, c, i, j;
+  SafeInt newSize;
 
   if (first + n < 0) {
     return gFalse;
   }
   if (first + n > size) {
-    for (newSize = size ? 2 * size : 1024;
+    for (newSize = size ? SafeInt(2) * SafeInt(size) : 1024;
 	 first + n > newSize && newSize > 0;
 	 newSize <<= 1) ;
     if (newSize < 0) {
@@ -579,7 +581,7 @@
       entries[i].offset = 0xffffffff;
       entries[i].type = xrefEntryFree;
     }
-    size = newSize;
+    size = newSize.Int();
   }
   for (i = first; i < first + n; ++i) {
     if (w[0] == 0) {
@@ -637,8 +639,8 @@
   char buf[256];
   Guint pos;
   int num, gen;
-  int newSize;
-  int streamEndsSize;
+  SafeInt newSize;
+  SafeInt streamEndsSize;
   char *p;
   int i;
   GBool gotRoot;
@@ -649,7 +651,7 @@
 
   error(-1, "PDF file is damaged - attempting to reconstruct xref table...");
   gotRoot = gFalse;
-  streamEndsLen = streamEndsSize = 0;
+  streamEndsSize = streamEndsLen = 0;
 
   str->reset();
   while (1) {
@@ -708,7 +710,7 @@
 	      } while (*p && isspace(*p));
 	      if (!strncmp(p, "obj", 3)) {
 		if (num >= size) {
-		  newSize = (num + 1 + 255) & ~255;
+		  newSize = (SafeInt(num) + 1 + 255).Int() & ~255;
 		  if (newSize < 0) {
 		    error(-1, "Bad object number");
 		    return gFalse;
@@ -719,7 +721,7 @@
 		    entries[i].offset = 0xffffffff;
 		    entries[i].type = xrefEntryFree;
 		  }
-		  size = newSize;
+		  size = newSize.Int();
 		}
 		if (entries[num].type == xrefEntryFree ||
 		    gen >= entries[num].gen) {
--- xpdf-3.02/xpdf/pdffonts.cc
+++ xpdf-3.02/xpdf/pdffonts.cc
@@ -77,7 +77,7 @@
 
 static Ref *fonts;
 static int fontsLen;
-static int fontsSize;
+static SafeInt fontsSize;
 
 int main(int argc, char *argv[]) {
   PDFDoc *doc;
@@ -143,7 +143,7 @@
   printf("name                                 type              emb sub uni object ID\n");
   printf("------------------------------------ ----------------- --- --- --- ---------\n");
   fonts = NULL;
-  fontsLen = fontsSize = 0;
+  fontsSize = fontsLen = 0;
   for (pg = firstPage; pg <= lastPage; ++pg) {
     page = doc->getCatalog()->getPage(pg);
     if ((resDict = page->getResourceDict())) {
