aboutsummaryrefslogtreecommitdiffstats
path: root/main/libx11/CVE-2013-1981_CVE-2013-1997_CVE-2013-2004.patch
diff options
context:
space:
mode:
authorNatanael Copa <ncopa@alpinelinux.org>2013-05-24 07:54:03 +0000
committerNatanael Copa <ncopa@alpinelinux.org>2013-05-24 07:54:03 +0000
commitdb1e74cf060eb177b9bd1f5ef787b90b19609c5b (patch)
treefef1f9587b38808d25fee2bcc248e4f44b9eb747 /main/libx11/CVE-2013-1981_CVE-2013-1997_CVE-2013-2004.patch
parent1a41cbf7f67c537bc75573199739f92e62ea4be6 (diff)
downloadaports-db1e74cf060eb177b9bd1f5ef787b90b19609c5b.tar.bz2
aports-db1e74cf060eb177b9bd1f5ef787b90b19609c5b.tar.xz
main/libx11: security fix (CVE-2013-1981,CVE-2013-1997,CVE-2013-2004)
ref #1931 fixes #1932
Diffstat (limited to 'main/libx11/CVE-2013-1981_CVE-2013-1997_CVE-2013-2004.patch')
-rw-r--r--main/libx11/CVE-2013-1981_CVE-2013-1997_CVE-2013-2004.patch3852
1 files changed, 3852 insertions, 0 deletions
diff --git a/main/libx11/CVE-2013-1981_CVE-2013-1997_CVE-2013-2004.patch b/main/libx11/CVE-2013-1981_CVE-2013-1997_CVE-2013-2004.patch
new file mode 100644
index 0000000000..c3aa58b9ae
--- /dev/null
+++ b/main/libx11/CVE-2013-1981_CVE-2013-1997_CVE-2013-2004.patch
@@ -0,0 +1,3852 @@
+diff --git a/include/X11/Xlibint.h b/include/X11/Xlibint.h
+index 80edeec..d56482a 100644
+--- a/include/X11/Xlibint.h
++++ b/include/X11/Xlibint.h
+@@ -693,19 +693,10 @@ extern void _XRead32(
+ }
+
+
+-#ifdef MUSTCOPY
+-
+-/* for when 32-bit alignment is not good enough */
+-#define OneDataCard32(dpy,dstaddr,srcvar) \
+- { dpy->bufptr -= 4; Data32 (dpy, (char *) &(srcvar), 4); }
+-
+-#else
+-
+ /* srcvar must be a variable for large architecture version */
+ #define OneDataCard32(dpy,dstaddr,srcvar) \
+ { *(CARD32 *)(dstaddr) = (srcvar); }
+
+-#endif /* MUSTCOPY */
+
+ typedef struct _XInternalAsync {
+ struct _XInternalAsync *next;
+@@ -860,6 +851,15 @@ typedef struct _XExten { /* private to extension mechanism */
+ struct _XExten *next_flush; /* next in list of those with flushes */
+ } _XExtension;
+
++/* Temporary definition until we can depend on an xproto release with it */
++#ifdef _X_COLD
++# define _XLIB_COLD _X_COLD
++#elif defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 403) /* 4.3+ */
++# define _XLIB_COLD __attribute__((__cold__))
++#else
++# define _XLIB_COLD /* nothing */
++#endif
++
+ /* extension hooks */
+
+ #ifdef DataRoutineIsProcedure
+@@ -882,7 +882,14 @@ extern int (*_XErrorFunction)(
+ extern void _XEatData(
+ Display* /* dpy */,
+ unsigned long /* n */
+-);
++) _XLIB_COLD;
++extern void _XEatDataWords(
++ Display* /* dpy */,
++ unsigned long /* n */
++) _XLIB_COLD;
++#if defined(__SUNPRO_C) /* Studio compiler alternative to "cold" attribute */
++# pragma rarely_called(_XEatData, _XEatDataWords)
++#endif
+ extern char *_XAllocScratch(
+ Display* /* dpy */,
+ unsigned long /* nbytes */
+diff --git a/modules/im/ximcp/Makefile.am b/modules/im/ximcp/Makefile.am
+index 16a6ca8..8aae839 100644
+--- a/modules/im/ximcp/Makefile.am
++++ b/modules/im/ximcp/Makefile.am
+@@ -6,6 +6,7 @@ AM_CPPFLAGS= \
+ -I$(top_srcdir)/src/xcms \
+ -I$(top_srcdir)/src/xkb \
+ -I$(top_srcdir)/src/xlibi18n \
++ -I$(top_srcdir)/src \
+ -D_BSD_SOURCE -DXIM_t -DTRANS_CLIENT
+
+ AM_CFLAGS= \
+diff --git a/modules/im/ximcp/imLcPrs.c b/modules/im/ximcp/imLcPrs.c
+index 4e54385..f3627a0 100644
+--- a/modules/im/ximcp/imLcPrs.c
++++ b/modules/im/ximcp/imLcPrs.c
+@@ -41,6 +41,8 @@ OR PERFORMANCE OF THIS SOFTWARE.
+ #include "Ximint.h"
+ #include <sys/stat.h>
+ #include <stdio.h>
++#include <limits.h>
++#include "pathmax.h"
+
+ #define XLC_BUFSIZE 256
+
+@@ -56,6 +58,8 @@ extern int _Xmbstoutf8(
+ int len
+ );
+
++static void parsestringfile(FILE *fp, Xim im, int depth);
++
+ /*
+ * Parsing File Format:
+ *
+@@ -304,9 +308,9 @@ static char*
+ TransFileName(Xim im, char *name)
+ {
+ char *home = NULL, *lcCompose = NULL;
+- char dir[XLC_BUFSIZE];
+- char *i = name, *ret, *j;
+- int l = 0;
++ char dir[XLC_BUFSIZE] = "";
++ char *i = name, *ret = NULL, *j;
++ size_t l = 0;
+
+ while (*i) {
+ if (*i == '%') {
+@@ -316,30 +320,51 @@ TransFileName(Xim im, char *name)
+ l++;
+ break;
+ case 'H':
+- home = getenv("HOME");
+- if (home)
+- l += strlen(home);
++ if (home == NULL)
++ home = getenv("HOME");
++ if (home) {
++ size_t Hsize = strlen(home);
++ if (Hsize > PATH_MAX)
++ /* your home directory length is ridiculous */
++ goto end;
++ l += Hsize;
++ }
+ break;
+ case 'L':
+ if (lcCompose == NULL)
+ lcCompose = _XlcFileName(im->core.lcd, COMPOSE_FILE);
+- if (lcCompose)
+- l += strlen(lcCompose);
++ if (lcCompose) {
++ size_t Lsize = strlen(lcCompose);
++ if (Lsize > PATH_MAX)
++ /* your compose pathname length is ridiculous */
++ goto end;
++ l += Lsize;
++ }
+ break;
+ case 'S':
+- xlocaledir(dir, XLC_BUFSIZE);
+- l += strlen(dir);
++ if (dir[0] == '\0')
++ xlocaledir(dir, XLC_BUFSIZE);
++ if (dir[0]) {
++ size_t Ssize = strlen(dir);
++ if (Ssize > PATH_MAX)
++ /* your locale directory path length is ridiculous */
++ goto end;
++ l += Ssize;
++ }
+ break;
+ }
+ } else {
+ l++;
+ }
+ i++;
++ if (l > PATH_MAX)
++ /* your expanded path length is ridiculous */
++ goto end;
+ }
+
+ j = ret = Xmalloc(l+1);
+ if (ret == NULL)
+- return ret;
++ goto end;
+ i = name;
+ while (*i) {
+ if (*i == '%') {
+@@ -371,6 +396,7 @@ TransFileName(Xim im, char *name)
+ }
+ }
+ *j = '\0';
++end:
+ Xfree(lcCompose);
+ return ret;
+ }
+@@ -423,7 +449,8 @@ static int
+ parseline(
+ FILE *fp,
+ Xim im,
+- char* tokenbuf)
++ char* tokenbuf,
++ int depth)
+ {
+ int token;
+ DTModifier modifier_mask;
+@@ -470,11 +497,13 @@ parseline(
+ goto error;
+ if ((filename = TransFileName(im, tokenbuf)) == NULL)
+ goto error;
++ if (++depth > 100)
++ goto error;
+ infp = _XFopenFile(filename, "r");
+ Xfree(filename);
+ if (infp == NULL)
+ goto error;
+- _XimParseStringFile(infp, im);
++ parsestringfile(infp, im, depth);
+ fclose(infp);
+ return (0);
+ } else if ((token == KEY) && (strcmp("None", tokenbuf) == 0)) {
+@@ -668,17 +697,28 @@ _XimParseStringFile(
+ FILE *fp,
+ Xim im)
+ {
++ parsestringfile(fp, im, 0);
++}
++
++static void
++parsestringfile(
++ FILE *fp,
++ Xim im,
++ int depth)
++{
+ char tb[8192];
+ char* tbp;
+ struct stat st;
+
+ if (fstat (fileno (fp), &st) != -1) {
+ unsigned long size = (unsigned long) st.st_size;
++ if (st.st_size >= INT_MAX)
++ return;
+ if (size <= sizeof tb) tbp = tb;
+ else tbp = malloc (size);
+
+ if (tbp != NULL) {
+- while (parseline(fp, im, tbp) >= 0) {}
++ while (parseline(fp, im, tbp, depth) >= 0) {}
+ if (tbp != tb) free (tbp);
+ }
+ }
+diff --git a/modules/im/ximcp/imTrX.c b/modules/im/ximcp/imTrX.c
+index d85d1d1..d6f4c49 100644
+--- a/modules/im/ximcp/imTrX.c
++++ b/modules/im/ximcp/imTrX.c
+@@ -372,7 +372,7 @@ _XimXGetReadData(
+ XFree(prop_ret);
+ return False;
+ }
+- if (buf_len >= length) {
++ if (buf_len >= (int)nitems) {
+ (void)memcpy(buf, prop_ret, (int)nitems);
+ *ret_len = (int)nitems;
+ if (bytes_after_ret > 0) {
+diff --git a/modules/om/generic/omXChar.c b/modules/om/generic/omXChar.c
+index ff517d5..c9bbb8e 100644
+--- a/modules/om/generic/omXChar.c
++++ b/modules/om/generic/omXChar.c
+@@ -262,47 +262,6 @@ _XomGetFontSetFromCharSet(
+ return (FontSet) NULL;
+ }
+
+-#ifdef MUSTCOPY
+-static void
+-cs_to_xchar2b(
+- register char *from,
+- register XChar2b *to,
+- register length)
+-{
+- while (length-- > 0) {
+- to->byte1 = *from++;
+- to->byte2 = *from++;
+- to++;
+- }
+-}
+-
+-static void
+-cs_to_xchar2b_gl(
+- register char *from,
+- register XChar2b *to,
+- register length)
+-{
+- while (length-- > 0) {
+- to->byte1 = *from++ & 0x7f;
+- to->byte2 = *from++ & 0x7f;
+- to++;
+- }
+-}
+-
+-static void
+-cs_to_xchar2b_gr(
+- register char *from,
+- register XChar2b *to,
+- register length)
+-{
+- while (length-- > 0) {
+- to->byte1 = *from++ | 0x80;
+- to->byte2 = *from++ | 0x80;
+- to++;
+- }
+-}
+-#endif
+-
+ static void
+ shift_to_gl(
+ register char *text,
+@@ -358,10 +317,6 @@ _XomConvert(
+ XlcCharSet charset;
+ int length, cs_left, ret;
+ FontSet font_set;
+-#ifdef MUSTCOPY
+- XChar2b *xchar2b;
+- char *buf, buf_local[BUFSIZ];
+-#endif
+
+ cs = *to;
+ cs_left = *to_left;
+@@ -380,46 +335,18 @@ _XomConvert(
+
+ length = *to_left - cs_left;
+
+-#ifdef MUSTCOPY
+- if (font_set->is_xchar2b) {
+- buf = (length > BUFSIZ) ? Xmalloc(length) : buf_local;
+- if (buf == NULL)
+- return -1;
+- memcpy(buf, (char *) *to, length);
+-
+- xchar2b = (XChar2b *) *to;
+- length >>= 1;
+-
+- if (font_set->side == charset->side)
+- cs_to_xchar2b(buf, xchar2b, length);
+- else if (font_set->side == XlcGL)
+- cs_to_xchar2b_gl(buf, xchar2b, length);
++ if (font_set->side != charset->side) {
++ if (font_set->side == XlcGL)
++ shift_to_gl(*to, length);
+ else if (font_set->side == XlcGR)
+- cs_to_xchar2b_gr(buf, xchar2b, length);
+- else
+- cs_to_xchar2b(buf, xchar2b, length);
+-
+- if (buf != buf_local)
+- Xfree(buf);
+-
+- *to = (XPointer) (xchar2b + length);
+- *to_left -= length;
+- } else
+-#endif
+- {
+- if (font_set->side != charset->side) {
+- if (font_set->side == XlcGL)
+- shift_to_gl(*to, length);
+- else if (font_set->side == XlcGR)
+- shift_to_gr(*to, length);
+- }
+-
+- if (font_set->is_xchar2b)
+- length >>= 1;
+- *to = cs;
+- *to_left -= length;
++ shift_to_gr(*to, length);
+ }
+
++ if (font_set->is_xchar2b)
++ length >>= 1;
++ *to = cs;
++ *to_left -= length;
++
+ *((XFontStruct **) args[0]) = font_set->font;
+ *((Bool *) args[1]) = font_set->is_xchar2b;
+ if(num_args >= 3){
+diff --git a/src/AllCells.c b/src/AllCells.c
+index ddd9c22..6e97e11 100644
+--- a/src/AllCells.c
++++ b/src/AllCells.c
+@@ -53,8 +53,13 @@ Status XAllocColorCells(
+ status = _XReply(dpy, (xReply *)&rep, 0, xFalse);
+
+ if (status) {
+- _XRead32 (dpy, (long *) pixels, 4L * (long) (rep.nPixels));
+- _XRead32 (dpy, (long *) masks, 4L * (long) (rep.nMasks));
++ if ((rep.nPixels > ncolors) || (rep.nMasks > nplanes)) {
++ _XEatDataWords(dpy, rep.length);
++ status = 0; /* Failure */
++ } else {
++ _XRead32 (dpy, (long *) pixels, 4L * (long) (rep.nPixels));
++ _XRead32 (dpy, (long *) masks, 4L * (long) (rep.nMasks));
++ }
+ }
+
+ UnlockDisplay(dpy);
+diff --git a/src/ChWindow.c b/src/ChWindow.c
+index fbd6e88..89a81e1 100644
+--- a/src/ChWindow.c
++++ b/src/ChWindow.c
+@@ -43,20 +43,11 @@ XResizeWindow(
+
+ req->window = w;
+ req->mask = CWWidth | CWHeight;
+-#ifdef MUSTCOPY
+- {
+- unsigned long lwidth = width, lheight = height;
+- dpy->bufptr -= 8;
+- Data32 (dpy, (long *) &lwidth, 4); /* order dictated by values of */
+- Data32 (dpy, (long *) &lheight, 4); /* CWWidth and CWHeight */
+- }
+-#else
+ {
+ CARD32 *valuePtr = (CARD32 *) NEXTPTR(req,xConfigureWindowReq);
+ *valuePtr++ = width;
+ *valuePtr = height;
+ }
+-#endif /* MUSTCOPY */
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return 1;
+diff --git a/src/Cmap.h b/src/Cmap.h
+index 062b538..78cc3ea 100644
+--- a/src/Cmap.h
++++ b/src/Cmap.h
+@@ -2,6 +2,8 @@
+ #ifndef _CMAP_H_
+ #define _CMAP_H_
+
++#include <X11/Xlib.h>
++
+ extern void
+ _XcmsDeleteCmapRec(
+ Display *dpy,
+diff --git a/src/ConfWind.c b/src/ConfWind.c
+index dd55b44..eefce4d 100644
+--- a/src/ConfWind.c
++++ b/src/ConfWind.c
+@@ -44,18 +44,6 @@ XMoveResizeWindow(
+ GetReqExtra(ConfigureWindow, 16, req);
+ req->window = w;
+ req->mask = CWX | CWY | CWWidth | CWHeight;
+-#ifdef MUSTCOPY
+- {
+- long lx = x, ly = y;
+- unsigned long lwidth = width, lheight = height;
+-
+- dpy->bufptr -= 16;
+- Data32 (dpy, (long *) &lx, 4); /* order must match values of */
+- Data32 (dpy, (long *) &ly, 4); /* CWX, CWY, CWWidth, and CWHeight */
+- Data32 (dpy, (long *) &lwidth, 4);
+- Data32 (dpy, (long *) &lheight, 4);
+- }
+-#else
+ {
+ register CARD32 *valuePtr =
+ (CARD32 *) NEXTPTR(req,xConfigureWindowReq);
+@@ -64,7 +52,6 @@ XMoveResizeWindow(
+ *valuePtr++ = width;
+ *valuePtr = height;
+ }
+-#endif /* MUSTCOPY */
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return 1;
+diff --git a/src/Context.c b/src/Context.c
+index 79ae7d6..4bb465b 100644
+--- a/src/Context.c
++++ b/src/Context.c
+@@ -111,7 +111,7 @@ static void ResizeTable(DB db)
+ otable = db->table;
+ for (i = INITHASHMASK+1; (i + i) < db->numentries; )
+ i += i;
+- db->table = (TableEntry *) Xcalloc((unsigned)i, sizeof(TableEntry));
++ db->table = Xcalloc(i, sizeof(TableEntry));
+ if (!db->table) {
+ db->table = otable;
+ return;
+@@ -180,11 +180,11 @@ int XSaveContext(
+ UnlockDisplay(display);
+ }
+ if (!db) {
+- db = (DB) Xmalloc(sizeof(DBRec));
++ db = Xmalloc(sizeof(DBRec));
+ if (!db)
+ return XCNOMEM;
+ db->mask = INITHASHMASK;
+- db->table = (TableEntry *)Xcalloc(db->mask + 1, sizeof(TableEntry));
++ db->table = Xcalloc(db->mask + 1, sizeof(TableEntry));
+ if (!db->table) {
+ Xfree((char *)db);
+ return XCNOMEM;
+@@ -210,7 +210,7 @@ int XSaveContext(
+ return 0;
+ }
+ }
+- entry = (TableEntry) Xmalloc(sizeof(TableEntryRec));
++ entry = Xmalloc(sizeof(TableEntryRec));
+ if (!entry)
+ return XCNOMEM;
+ entry->rid = rid;
+diff --git a/src/Cr.h b/src/Cr.h
+index 800c9ab..635e9e4 100644
+--- a/src/Cr.h
++++ b/src/Cr.h
+@@ -2,6 +2,8 @@
+ #ifndef _CR_H_
+ #define _CR_H_
+
++#include <X11/Xlib.h>
++
+ extern int _XUpdateGCCache(
+ register GC gc,
+ register unsigned long mask,
+diff --git a/src/CrGC.c b/src/CrGC.c
+index 11de94c..2d5f17c 100644
+--- a/src/CrGC.c
++++ b/src/CrGC.c
+@@ -72,7 +72,7 @@ GC XCreateGC (
+ register _XExtension *ext;
+
+ LockDisplay(dpy);
+- if ((gc = (GC)Xmalloc (sizeof(struct _XGC))) == NULL) {
++ if ((gc = Xmalloc (sizeof(struct _XGC))) == NULL) {
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (NULL);
+diff --git a/src/CrWindow.c b/src/CrWindow.c
+index 23f7ddc..7b54601 100644
+--- a/src/CrWindow.c
++++ b/src/CrWindow.c
+@@ -57,20 +57,11 @@ Window XCreateSimpleWindow(
+ wid = req->wid = XAllocID(dpy);
+ req->mask = CWBackPixel | CWBorderPixel;
+
+-#ifdef MUSTCOPY
+- {
+- unsigned long lbackground = background, lborder = border;
+- dpy->bufptr -= 8;
+- Data32 (dpy, (long *) &lbackground, 4);
+- Data32 (dpy, (long *) &lborder, 4);
+- }
+-#else
+ {
+ register CARD32 *valuePtr = (CARD32 *) NEXTPTR(req,xCreateWindowReq);
+ *valuePtr++ = background;
+ *valuePtr = border;
+ }
+-#endif /* MUSTCOPY */
+
+ UnlockDisplay(dpy);
+ SyncHandle();
+diff --git a/src/Depths.c b/src/Depths.c
+index f49655c..a8b719d 100644
+--- a/src/Depths.c
++++ b/src/Depths.c
+@@ -49,7 +49,7 @@ int *XListDepths (
+ register Depth *dp;
+ register int i;
+
+- depths = (int *) Xmalloc (count * sizeof(int));
++ depths = Xmalloc (count * sizeof(int));
+ if (!depths) return NULL;
+ for (i = 0, dp = scr->depths; i < count; i++, dp++)
+ depths[i] = dp->depth;
+diff --git a/src/DrArc.c b/src/DrArc.c
+index 1dc4a07..d72fac9 100644
+--- a/src/DrArc.c
++++ b/src/DrArc.c
+@@ -49,12 +49,6 @@ XDrawArc(
+ {
+ register xPolyArcReq *req;
+ register xArc *arc;
+-#ifdef MUSTCOPY
+- xArc arcdata;
+- long len = SIZEOF(xArc);
+-
+- arc = &arcdata;
+-#endif /* MUSTCOPY */
+
+ LockDisplay(dpy);
+ FlushGC(dpy, gc);
+@@ -63,9 +57,7 @@ XDrawArc(
+ req->drawable = d;
+ req->gc = gc->gid;
+
+-#ifndef MUSTCOPY
+ arc = (xArc *) NEXTPTR(req,xPolyArcReq);
+-#endif /* MUSTCOPY */
+
+ arc->x = x;
+ arc->y = y;
+@@ -74,10 +66,6 @@ XDrawArc(
+ arc->angle1 = angle1;
+ arc->angle2 = angle2;
+
+-#ifdef MUSTCOPY
+- dpy->bufptr -= SIZEOF(xArc);
+- Data (dpy, (char *) arc, len);
+-#endif /* MUSTCOPY */
+
+ UnlockDisplay(dpy);
+ SyncHandle();
+diff --git a/src/DrLine.c b/src/DrLine.c
+index 3786f59..dc82d5a 100644
+--- a/src/DrLine.c
++++ b/src/DrLine.c
+@@ -45,12 +45,6 @@ XDrawLine (
+ int y2)
+ {
+ register xSegment *segment;
+-#ifdef MUSTCOPY
+- xSegment segmentdata;
+- long len = SIZEOF(xSegment);
+-
+- segment = &segmentdata;
+-#endif /* not MUSTCOPY */
+
+ LockDisplay(dpy);
+ FlushGC(dpy, gc);
+@@ -67,21 +61,15 @@ XDrawLine (
+ && (((char *)dpy->bufptr - (char *)req) < (gc->values.line_width ?
+ wsize : zsize)) ) {
+ req->length += SIZEOF(xSegment) >> 2;
+-#ifndef MUSTCOPY
+ segment = (xSegment *) dpy->bufptr;
+ dpy->bufptr += SIZEOF(xSegment);
+-#endif /* not MUSTCOPY */
+ }
+
+ else {
+ GetReqExtra (PolySegment, SIZEOF(xSegment), req);
+ req->drawable = d;
+ req->gc = gc->gid;
+-#ifdef MUSTCOPY
+- dpy->bufptr -= SIZEOF(xSegment);
+-#else
+ segment = (xSegment *) NEXTPTR(req,xPolySegmentReq);
+-#endif /* MUSTCOPY */
+ }
+
+ segment->x1 = x1;
+@@ -89,10 +77,6 @@ XDrawLine (
+ segment->x2 = x2;
+ segment->y2 = y2;
+
+-#ifdef MUSTCOPY
+- Data (dpy, (char *) &segmentdata, len);
+-#endif /* MUSTCOPY */
+-
+ UnlockDisplay(dpy);
+ SyncHandle();
+ }
+diff --git a/src/DrPoint.c b/src/DrPoint.c
+index 5c89b5c..f0332e8 100644
+--- a/src/DrPoint.c
++++ b/src/DrPoint.c
+@@ -42,12 +42,6 @@ XDrawPoint(
+ int y) /* INT16 */
+ {
+ xPoint *point;
+-#ifdef MUSTCOPY
+- xPoint pointdata;
+- long len = SIZEOF(xPoint);
+-
+- point = &pointdata;
+-#endif /* MUSTCOPY */
+
+ LockDisplay(dpy);
+ FlushGC(dpy, gc);
+@@ -65,10 +59,8 @@ XDrawPoint(
+ && ((dpy->bufptr + SIZEOF(xPoint)) <= dpy->bufmax)
+ && (((char *)dpy->bufptr - (char *)req) < size) ) {
+ req->length += SIZEOF(xPoint) >> 2;
+-#ifndef MUSTCOPY
+ point = (xPoint *) dpy->bufptr;
+ dpy->bufptr += SIZEOF(xPoint);
+-#endif /* not MUSTCOPY */
+ }
+
+ else {
+@@ -76,19 +68,12 @@ XDrawPoint(
+ req->drawable = d;
+ req->gc = gc->gid;
+ req->coordMode = CoordModeOrigin;
+-#ifdef MUSTCOPY
+- dpy->bufptr -= SIZEOF(xPoint);
+-#else
+ point = (xPoint *) NEXTPTR(req,xPolyPointReq);
+-#endif /* MUSTCOPY */
+ }
+
+ point->x = x;
+ point->y = y;
+
+-#ifdef MUSTCOPY
+- Data (dpy, (char *) point, len);
+-#endif /* MUSTCOPY */
+ }
+ UnlockDisplay(dpy);
+ SyncHandle();
+diff --git a/src/DrRect.c b/src/DrRect.c
+index dadd55e..d9141ee 100644
+--- a/src/DrRect.c
++++ b/src/DrRect.c
+@@ -45,12 +45,6 @@ XDrawRectangle(
+ unsigned int height) /* CARD16 */
+ {
+ xRectangle *rect;
+-#ifdef MUSTCOPY
+- xRectangle rectdata;
+- long len = SIZEOF(xRectangle);
+-
+- rect = &rectdata;
+-#endif /* MUSTCOPY */
+
+ LockDisplay(dpy);
+ FlushGC(dpy, gc);
+@@ -67,21 +61,15 @@ XDrawRectangle(
+ && (((char *)dpy->bufptr - (char *)req) < (gc->values.line_width ?
+ wsize : zsize)) ) {
+ req->length += SIZEOF(xRectangle) >> 2;
+-#ifndef MUSTCOPY
+ rect = (xRectangle *) dpy->bufptr;
+ dpy->bufptr += SIZEOF(xRectangle);
+-#endif /* not MUSTCOPY */
+ }
+
+ else {
+ GetReqExtra(PolyRectangle, SIZEOF(xRectangle), req);
+ req->drawable = d;
+ req->gc = gc->gid;
+-#ifdef MUSTCOPY
+- dpy->bufptr -= SIZEOF(xRectangle);
+-#else
+ rect = (xRectangle *) NEXTPTR(req,xPolyRectangleReq);
+-#endif /* MUSTCOPY */
+ }
+
+ rect->x = x;
+@@ -89,10 +77,6 @@ XDrawRectangle(
+ rect->width = width;
+ rect->height = height;
+
+-#ifdef MUSTCOPY
+- Data (dpy, (char *) rect, len); /* subtracted bufptr up above */
+-#endif /* MUSTCOPY */
+-
+ }
+ UnlockDisplay(dpy);
+ SyncHandle();
+diff --git a/src/FSWrap.c b/src/FSWrap.c
+index 910e602..12d0406 100644
+--- a/src/FSWrap.c
++++ b/src/FSWrap.c
+@@ -112,7 +112,7 @@ _XParseBaseFontNameList(
+ if (!*ptr)
+ break;
+ }
+- if (!(list = (char **) Xmalloc((unsigned)sizeof(char *) * (*num + 1)))) {
++ if (!(list = Xmalloc(sizeof(char *) * (*num + 1)))) {
+ Xfree(psave);
+ return (char **)NULL;
+ }
+@@ -133,7 +133,7 @@ copy_string_list(
+ if (string_list == NULL || list_count <= 0)
+ return (char **) NULL;
+
+- string_list_ret = (char **) Xmalloc(sizeof(char *) * list_count);
++ string_list_ret = Xmalloc(sizeof(char *) * list_count);
+ if (string_list_ret == NULL)
+ return (char **) NULL;
+
+@@ -142,7 +142,7 @@ copy_string_list(
+ for (length = 0; count-- > 0; list_src++)
+ length += strlen(*list_src) + 1;
+
+- dst = (char *) Xmalloc(length);
++ dst = Xmalloc(length);
+ if (dst == NULL) {
+ Xfree(string_list_ret);
+ return (char **) NULL;
+diff --git a/src/FillArc.c b/src/FillArc.c
+index 0f1ad02..c67f977 100644
+--- a/src/FillArc.c
++++ b/src/FillArc.c
+@@ -46,12 +46,6 @@ XFillArc(
+ int angle2) /* INT16 */
+ {
+ xArc *arc;
+-#ifdef MUSTCOPY
+- xArc arcdata;
+- long len = SIZEOF(xArc);
+-
+- arc = &arcdata;
+-#endif /* MUSTCOPY */
+
+ LockDisplay(dpy);
+ FlushGC(dpy, gc);
+@@ -67,10 +61,8 @@ XFillArc(
+ && ((dpy->bufptr + SIZEOF(xArc)) <= dpy->bufmax)
+ && (((char *)dpy->bufptr - (char *)req) < size) ) {
+ req->length += SIZEOF(xArc) >> 2;
+-#ifndef MUSTCOPY
+ arc = (xArc *) dpy->bufptr;
+ dpy->bufptr += SIZEOF(xArc);
+-#endif /* not MUSTCOPY */
+ }
+
+ else {
+@@ -78,11 +70,7 @@ XFillArc(
+
+ req->drawable = d;
+ req->gc = gc->gid;
+-#ifdef MUSTCOPY
+- dpy->bufptr -= SIZEOF(xArc);
+-#else
+ arc = (xArc *) NEXTPTR(req,xPolyFillArcReq);
+-#endif /* MUSTCOPY */
+ }
+ arc->x = x;
+ arc->y = y;
+@@ -91,10 +79,6 @@ XFillArc(
+ arc->angle1 = angle1;
+ arc->angle2 = angle2;
+
+-#ifdef MUSTCOPY
+- Data (dpy, (char *) arc, len);
+-#endif /* MUSTCOPY */
+-
+ }
+ UnlockDisplay(dpy);
+ SyncHandle();
+diff --git a/src/FillRct.c b/src/FillRct.c
+index 4cd104c..3ca9afe 100644
+--- a/src/FillRct.c
++++ b/src/FillRct.c
+@@ -44,12 +44,6 @@ XFillRectangle(
+ unsigned int height) /* CARD16 */
+ {
+ xRectangle *rect;
+-#ifdef MUSTCOPY
+- xRectangle rectdata;
+- long len = SIZEOF(xRectangle);
+-
+- rect = &rectdata;
+-#endif /* MUSTCOPY */
+
+ LockDisplay(dpy);
+ FlushGC(dpy, gc);
+@@ -66,30 +60,21 @@ XFillRectangle(
+ && ((dpy->bufptr + SIZEOF(xRectangle)) <= dpy->bufmax)
+ && (((char *)dpy->bufptr - (char *)req) < size) ) {
+ req->length += SIZEOF(xRectangle) >> 2;
+-#ifndef MUSTCOPY
+ rect = (xRectangle *) dpy->bufptr;
+ dpy->bufptr += SIZEOF(xRectangle);
+-#endif /* not MUSTCOPY */
+ }
+
+ else {
+ GetReqExtra(PolyFillRectangle, SIZEOF(xRectangle), req);
+ req->drawable = d;
+ req->gc = gc->gid;
+-#ifdef MUSTCOPY
+- dpy->bufptr -= SIZEOF(xRectangle);
+-#else
+ rect = (xRectangle *) NEXTPTR(req,xPolyFillRectangleReq);
+-#endif /* MUSTCOPY */
+ }
+ rect->x = x;
+ rect->y = y;
+ rect->width = width;
+ rect->height = height;
+
+-#ifdef MUSTCOPY
+- Data (dpy, (char *) rect, len);
+-#endif /* MUSTCOPY */
+ }
+ UnlockDisplay(dpy);
+ SyncHandle();
+diff --git a/src/Font.c b/src/Font.c
+index 7f56f68..a32f740 100644
+--- a/src/Font.c
++++ b/src/Font.c
+@@ -31,8 +31,9 @@ authorization from the X Consortium and the XFree86 Project.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
+
+-#if defined(XF86BIGFONT) && !defined(MUSTCOPY)
++#if defined(XF86BIGFONT)
+ #define USE_XF86BIGFONT
+ #endif
+ #ifdef USE_XF86BIGFONT
+@@ -183,7 +184,8 @@ _XQueryFont (
+ unsigned long seq)
+ {
+ register XFontStruct *fs;
+- register long nbytes;
++ unsigned long nbytes;
++ unsigned long reply_left; /* unused data words left in reply buffer */
+ xQueryFontReply reply;
+ register xResourceReq *req;
+ register _XExtension *ext;
+@@ -211,9 +213,10 @@ _XQueryFont (
+ }
+ if (seq)
+ DeqAsyncHandler(dpy, &async);
+- if (! (fs = (XFontStruct *) Xmalloc (sizeof (XFontStruct)))) {
+- _XEatData(dpy, (unsigned long)(reply.nFontProps * SIZEOF(xFontProp) +
+- reply.nCharInfos * SIZEOF(xCharInfo)));
++ reply_left = reply.length -
++ ((SIZEOF(xQueryFontReply) - SIZEOF(xReply)) >> 2);
++ if (! (fs = Xmalloc (sizeof (XFontStruct)))) {
++ _XEatDataWords(dpy, reply_left);
+ return (XFontStruct *)NULL;
+ }
+ fs->ext_data = NULL;
+@@ -228,31 +231,9 @@ _XQueryFont (
+ fs->ascent = cvtINT16toInt (reply.fontAscent);
+ fs->descent = cvtINT16toInt (reply.fontDescent);
+
+-#ifdef MUSTCOPY
+- {
+- xCharInfo *xcip;
+-
+- xcip = (xCharInfo *) &reply.minBounds;
+- fs->min_bounds.lbearing = cvtINT16toShort(xcip->leftSideBearing);
+- fs->min_bounds.rbearing = cvtINT16toShort(xcip->rightSideBearing);
+- fs->min_bounds.width = cvtINT16toShort(xcip->characterWidth);
+- fs->min_bounds.ascent = cvtINT16toShort(xcip->ascent);
+- fs->min_bounds.descent = cvtINT16toShort(xcip->descent);
+- fs->min_bounds.attributes = xcip->attributes;
+-
+- xcip = (xCharInfo *) &reply.maxBounds;
+- fs->max_bounds.lbearing = cvtINT16toShort(xcip->leftSideBearing);
+- fs->max_bounds.rbearing = cvtINT16toShort(xcip->rightSideBearing);
+- fs->max_bounds.width = cvtINT16toShort(xcip->characterWidth);
+- fs->max_bounds.ascent = cvtINT16toShort(xcip->ascent);
+- fs->max_bounds.descent = cvtINT16toShort(xcip->descent);
+- fs->max_bounds.attributes = xcip->attributes;
+- }
+-#else
+ /* XXX the next two statements won't work if short isn't 16 bits */
+ fs->min_bounds = * (XCharStruct *) &reply.minBounds;
+ fs->max_bounds = * (XCharStruct *) &reply.maxBounds;
+-#endif /* MUSTCOPY */
+
+ fs->n_properties = reply.nFontProps;
+ /*
+@@ -261,54 +242,42 @@ _XQueryFont (
+ */
+ fs->properties = NULL;
+ if (fs->n_properties > 0) {
+- nbytes = reply.nFontProps * sizeof(XFontProp);
+- fs->properties = (XFontProp *) Xmalloc ((unsigned) nbytes);
++ /* nFontProps is a CARD16 */
+ nbytes = reply.nFontProps * SIZEOF(xFontProp);
++ if ((nbytes >> 2) <= reply_left) {
++ size_t pbytes = reply.nFontProps * sizeof(XFontProp);
++ fs->properties = Xmalloc (pbytes);
++ }
+ if (! fs->properties) {
+ Xfree((char *) fs);
+- _XEatData(dpy, (unsigned long)
+- (nbytes + reply.nCharInfos * SIZEOF(xCharInfo)));
++ _XEatDataWords(dpy, reply_left);
+ return (XFontStruct *)NULL;
+ }
+ _XRead32 (dpy, (long *)fs->properties, nbytes);
++ reply_left -= (nbytes >> 2);
+ }
+ /*
+ * If no characters in font, then it is a bad font, but
+ * shouldn't try to read nothing.
+ */
+- /* have to unpack charinfos on some machines (CRAY) */
+ fs->per_char = NULL;
+ if (reply.nCharInfos > 0){
+- nbytes = reply.nCharInfos * sizeof(XCharStruct);
+- if (! (fs->per_char = (XCharStruct *) Xmalloc ((unsigned) nbytes))) {
++ /* nCharInfos is a CARD32 */
++ if (reply.nCharInfos < (INT_MAX / sizeof(XCharStruct))) {
++ nbytes = reply.nCharInfos * SIZEOF(xCharInfo);
++ if ((nbytes >> 2) <= reply_left) {
++ size_t cibytes = reply.nCharInfos * sizeof(XCharStruct);
++ fs->per_char = Xmalloc (cibytes);
++ }
++ }
++ if (! fs->per_char) {
+ if (fs->properties) Xfree((char *) fs->properties);
+ Xfree((char *) fs);
+- _XEatData(dpy, (unsigned long)
+- (reply.nCharInfos * SIZEOF(xCharInfo)));
++ _XEatDataWords(dpy, reply_left);
+ return (XFontStruct *)NULL;
+ }
+
+-#ifdef MUSTCOPY
+- {
+- register XCharStruct *cs = fs->per_char;
+- register int i;
+-
+- for (i = 0; i < reply.nCharInfos; i++, cs++) {
+- xCharInfo xcip;
+-
+- _XRead(dpy, (char *)&xcip, SIZEOF(xCharInfo));
+- cs->lbearing = cvtINT16toShort(xcip.leftSideBearing);
+- cs->rbearing = cvtINT16toShort(xcip.rightSideBearing);
+- cs->width = cvtINT16toShort(xcip.characterWidth);
+- cs->ascent = cvtINT16toShort(xcip.ascent);
+- cs->descent = cvtINT16toShort(xcip.descent);
+- cs->attributes = xcip.attributes;
+- }
+- }
+-#else
+- nbytes = reply.nCharInfos * SIZEOF(xCharInfo);
+ _XRead16 (dpy, (char *)fs->per_char, nbytes);
+-#endif
+ }
+
+ /* call out to any extensions interested */
+@@ -354,7 +323,7 @@ _XF86BigfontCodes (
+ if (pData)
+ return (XF86BigfontCodes *) pData->private_data;
+
+- pData = (XExtData *) Xmalloc(sizeof(XExtData) + sizeof(XF86BigfontCodes));
++ pData = Xmalloc(sizeof(XExtData) + sizeof(XF86BigfontCodes));
+ if (!pData) {
+ /* Out of luck. */
+ return (XF86BigfontCodes *) NULL;
+@@ -434,7 +403,8 @@ _XF86BigfontQueryFont (
+ unsigned long seq)
+ {
+ register XFontStruct *fs;
+- register long nbytes;
++ unsigned long nbytes;
++ unsigned long reply_left; /* unused data left in reply buffer */
+ xXF86BigfontQueryFontReply reply;
+ register xXF86BigfontQueryFontReq *req;
+ register _XExtension *ext;
+@@ -487,13 +457,10 @@ _XF86BigfontQueryFont (
+ DeqAsyncHandler(dpy, &async2);
+ if (seq)
+ DeqAsyncHandler(dpy, &async1);
+- if (! (fs = (XFontStruct *) Xmalloc (sizeof (XFontStruct)))) {
+- _XEatData(dpy,
+- reply.nFontProps * SIZEOF(xFontProp)
+- + (reply.nCharInfos > 0 && reply.shmid == (CARD32)(-1)
+- ? reply.nUniqCharInfos * SIZEOF(xCharInfo)
+- + (reply.nCharInfos+1)/2 * 2 * sizeof(CARD16)
+- : 0));
++ reply_left = reply.length -
++ ((SIZEOF(xXF86BigfontQueryFontReply) - SIZEOF(xReply)) >> 2);
++ if (! (fs = Xmalloc (sizeof (XFontStruct)))) {
++ _XEatDataWords(dpy, reply_left);
+ return (XFontStruct *)NULL;
+ }
+ fs->ext_data = NULL;
+@@ -519,23 +486,33 @@ _XF86BigfontQueryFont (
+ */
+ fs->properties = NULL;
+ if (fs->n_properties > 0) {
+- nbytes = reply.nFontProps * sizeof(XFontProp);
+- fs->properties = (XFontProp *) Xmalloc ((unsigned) nbytes);
++ /* nFontProps is a CARD16 */
+ nbytes = reply.nFontProps * SIZEOF(xFontProp);
++ if ((nbytes >> 2) <= reply_left) {
++ size_t pbytes = reply.nFontProps * sizeof(XFontProp);
++ fs->properties = Xmalloc (pbytes);
++ }
+ if (! fs->properties) {
+ Xfree((char *) fs);
+- _XEatData(dpy,
+- nbytes
+- + (reply.nCharInfos > 0 && reply.shmid == (CARD32)(-1)
+- ? reply.nUniqCharInfos * SIZEOF(xCharInfo)
+- + (reply.nCharInfos+1)/2 * 2 * sizeof(CARD16)
+- : 0));
++ _XEatDataWords(dpy, reply_left);
+ return (XFontStruct *)NULL;
+ }
+ _XRead32 (dpy, (long *)fs->properties, nbytes);
++ reply_left -= (nbytes >> 2);
+ }
+
+ fs->per_char = NULL;
++#ifndef LONG64
++ /* compares each part to half the maximum, which should be far more than
++ any real font needs, so the combined total doesn't overflow either */
++ if (reply.nUniqCharInfos > ((ULONG_MAX / 2) / SIZEOF(xCharInfo)) ||
++ reply.nCharInfos > ((ULONG_MAX / 2) / sizeof(CARD16))) {
++ Xfree((char *) fs->properties);
++ Xfree((char *) fs);
++ _XEatDataWords(dpy, reply_left);
++ return (XFontStruct *)NULL;
++ }
++#endif
+ if (reply.nCharInfos > 0) {
+ /* fprintf(stderr, "received font metrics, nCharInfos = %d, nUniqCharInfos = %d, shmid = %d\n", reply.nCharInfos, reply.nUniqCharInfos, reply.shmid); */
+ if (reply.shmid == (CARD32)(-1)) {
+@@ -545,18 +522,18 @@ _XF86BigfontQueryFont (
+
+ nbytes = reply.nUniqCharInfos * SIZEOF(xCharInfo)
+ + (reply.nCharInfos+1)/2 * 2 * sizeof(CARD16);
+- pUniqCI = (xCharInfo *) Xmalloc (nbytes);
++ pUniqCI = Xmalloc (nbytes);
+ if (!pUniqCI) {
+ if (fs->properties) Xfree((char *) fs->properties);
+ Xfree((char *) fs);
+- _XEatData(dpy, nbytes);
++ _XEatDataWords(dpy, reply_left);
+ return (XFontStruct *)NULL;
+ }
+- if (! (fs->per_char = (XCharStruct *) Xmalloc (reply.nCharInfos * sizeof(XCharStruct)))) {
++ if (! (fs->per_char = Xmalloc (reply.nCharInfos * sizeof(XCharStruct)))) {
+ Xfree((char *) pUniqCI);
+ if (fs->properties) Xfree((char *) fs->properties);
+ Xfree((char *) fs);
+- _XEatData(dpy, nbytes);
++ _XEatDataWords(dpy, reply_left);
+ return (XFontStruct *)NULL;
+ }
+ _XRead16 (dpy, (char *) pUniqCI, nbytes);
+@@ -579,7 +556,7 @@ _XF86BigfontQueryFont (
+ XEDataObject fs_union;
+ char *addr;
+
+- pData = (XExtData *) Xmalloc(sizeof(XExtData));
++ pData = Xmalloc(sizeof(XExtData));
+ if (!pData) {
+ if (fs->properties) Xfree((char *) fs->properties);
+ Xfree((char *) fs);
+@@ -611,6 +588,7 @@ _XF86BigfontQueryFont (
+ if (!(extcodes->serverCapabilities & CAP_VerifiedLocal)) {
+ struct shmid_ds buf;
+ if (!(shmctl(reply.shmid, IPC_STAT, &buf) >= 0
++ && reply.nCharInfos < (LONG_MAX / sizeof(XCharStruct))
+ && buf.shm_segsz >= reply.shmsegoffset + reply.nCharInfos * sizeof(XCharStruct) + sizeof(CARD32)
+ && *(CARD32 *)(addr + reply.shmsegoffset + reply.nCharInfos * sizeof(XCharStruct)) == extcodes->serverSignature)) {
+ shmdt(addr);
+diff --git a/src/FontInfo.c b/src/FontInfo.c
+index a3ab65b..0cb5b19 100644
+--- a/src/FontInfo.c
++++ b/src/FontInfo.c
+@@ -28,8 +28,9 @@ in this Software without prior written authorization from The Open Group.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
+
+-#if defined(XF86BIGFONT) && !defined(MUSTCOPY)
++#if defined(XF86BIGFONT)
+ #define USE_XF86BIGFONT
+ #endif
+ #ifdef USE_XF86BIGFONT
+@@ -45,10 +46,11 @@ int maxNames,
+ int *actualCount, /* RETURN */
+ XFontStruct **info) /* RETURN */
+ {
+- register long nbytes;
++ unsigned long nbytes;
++ unsigned long reply_left; /* unused data left in reply buffer */
+ register int i;
+ register XFontStruct *fs;
+- register int size = 0;
++ unsigned int size = 0;
+ XFontStruct *finfo = NULL;
+ char **flist = NULL;
+ xListFontsWithInfoReply reply;
+@@ -67,51 +69,44 @@ XFontStruct **info) /* RETURN */
+ if (!_XReply (dpy, (xReply *) &reply,
+ ((SIZEOF(xListFontsWithInfoReply) -
+ SIZEOF(xGenericReply)) >> 2), xFalse)) {
+- for (j=(i-1); (j >= 0); j--) {
+- Xfree(flist[j]);
+- if (finfo[j].properties) Xfree((char *) finfo[j].properties);
+- }
+- if (flist) Xfree((char *) flist);
+- if (finfo) Xfree((char *) finfo);
+- UnlockDisplay(dpy);
+- SyncHandle();
+- return ((char **) NULL);
++ reply.nameLength = 0; /* avoid trying to read more replies */
++ reply_left = 0;
++ goto badmem;
+ }
+- if (reply.nameLength == 0)
++ reply_left = reply.length -
++ ((SIZEOF(xListFontsWithInfoReply) - SIZEOF(xGenericReply)) >> 2);
++ if (reply.nameLength == 0) {
++ _XEatDataWords(dpy, reply_left);
+ break;
++ }
++ if (reply.nReplies >= (INT_MAX - i)) /* avoid overflowing size */
++ goto badmem;
+ if ((i + reply.nReplies) >= size) {
+ size = i + reply.nReplies + 1;
+
++ if (size >= (INT_MAX / sizeof(XFontStruct)))
++ goto badmem;
++
+ if (finfo) {
+- XFontStruct * tmp_finfo = (XFontStruct *)
+- Xrealloc ((char *) finfo,
+- (unsigned) (sizeof(XFontStruct) * size));
+- char ** tmp_flist = (char **)
+- Xrealloc ((char *) flist,
+- (unsigned) (sizeof(char *) * (size+1)));
+-
+- if ((! tmp_finfo) || (! tmp_flist)) {
+- /* free all the memory that we allocated */
+- for (j=(i-1); (j >= 0); j--) {
+- Xfree(flist[j]);
+- if (finfo[j].properties)
+- Xfree((char *) finfo[j].properties);
+- }
+- if (tmp_flist) Xfree((char *) tmp_flist);
+- else Xfree((char *) flist);
+- if (tmp_finfo) Xfree((char *) tmp_finfo);
+- else Xfree((char *) finfo);
+- goto clearwire;
+- }
+- finfo = tmp_finfo;
+- flist = tmp_flist;
++ XFontStruct * tmp_finfo;
++ char ** tmp_flist;
++
++ tmp_finfo = Xrealloc (finfo, sizeof(XFontStruct) * size);
++ if (tmp_finfo)
++ finfo = tmp_finfo;
++ else
++ goto badmem;
++
++ tmp_flist = Xrealloc (flist, sizeof(char *) * (size+1));
++ if (tmp_flist)
++ flist = tmp_flist;
++ else
++ goto badmem;
+ }
+ else {
+- if (! (finfo = (XFontStruct *)
+- Xmalloc((unsigned) (sizeof(XFontStruct) * size))))
++ if (! (finfo = Xmalloc(sizeof(XFontStruct) * size)))
+ goto clearwire;
+- if (! (flist = (char **)
+- Xmalloc((unsigned) (sizeof(char *) * (size+1))))) {
++ if (! (flist = Xmalloc(sizeof(char *) * (size+1)))) {
+ Xfree((char *) finfo);
+ goto clearwire;
+ }
+@@ -132,51 +127,32 @@ XFontStruct **info) /* RETURN */
+ fs->ascent = cvtINT16toInt (reply.fontAscent);
+ fs->descent = cvtINT16toInt (reply.fontDescent);
+
+-#ifdef MUSTCOPY
+- {
+- xCharInfo *xcip;
+-
+- xcip = (xCharInfo *) &reply.minBounds;
+- fs->min_bounds.lbearing = xcip->leftSideBearing;
+- fs->min_bounds.rbearing = xcip->rightSideBearing;
+- fs->min_bounds.width = xcip->characterWidth;
+- fs->min_bounds.ascent = xcip->ascent;
+- fs->min_bounds.descent = xcip->descent;
+- fs->min_bounds.attributes = xcip->attributes;
+-
+- xcip = (xCharInfo *) &reply.maxBounds;
+- fs->max_bounds.lbearing = xcip->leftSideBearing;
+- fs->max_bounds.rbearing = xcip->rightSideBearing;
+- fs->max_bounds.width = xcip->characterWidth;
+- fs->max_bounds.ascent = xcip->ascent;
+- fs->max_bounds.descent = xcip->descent;
+- fs->max_bounds.attributes = xcip->attributes;
+- }
+-#else
+ /* XXX the next two statements won't work if short isn't 16 bits */
+ fs->min_bounds = * (XCharStruct *) &reply.minBounds;
+ fs->max_bounds = * (XCharStruct *) &reply.maxBounds;
+-#endif /* MUSTCOPY */
+
+ fs->n_properties = reply.nFontProps;
++ fs->properties = NULL;
+ if (fs->n_properties > 0) {
+- nbytes = reply.nFontProps * sizeof(XFontProp);
+- if (! (fs->properties = (XFontProp *) Xmalloc((unsigned) nbytes)))
+- goto badmem;
++ /* nFontProps is a CARD16 */
+ nbytes = reply.nFontProps * SIZEOF(xFontProp);
++ if ((nbytes >> 2) <= reply_left) {
++ size_t pbytes = reply.nFontProps * sizeof(XFontProp);
++ fs->properties = Xmalloc (pbytes);
++ }
++ if (! fs->properties)
++ goto badmem;
+ _XRead32 (dpy, (long *)fs->properties, nbytes);
++ reply_left -= (nbytes >> 2);
++ }
+
+- } else
+- fs->properties = NULL;
+-
+- j = reply.nameLength + 1;
++ /* nameLength is a CARD8 */
++ nbytes = reply.nameLength + 1;
+ if (!i)
+- j++; /* make first string 1 byte longer, to match XListFonts */
+- flist[i] = (char *) Xmalloc ((unsigned int) j);
++ nbytes++; /* make first string 1 byte longer, to match XListFonts */
++ flist[i] = Xmalloc (nbytes);
+ if (! flist[i]) {
+ if (finfo[i].properties) Xfree((char *) finfo[i].properties);
+- nbytes = (reply.nameLength + 3) & ~3;
+- _XEatData(dpy, (unsigned long) nbytes);
+ goto badmem;
+ }
+ if (!i) {
+@@ -198,27 +174,25 @@ XFontStruct **info) /* RETURN */
+ badmem:
+ /* Free all memory allocated by this function. */
+ for (j=(i-1); (j >= 0); j--) {
+- Xfree(flist[j]);
+- if (finfo[j].properties) Xfree((char *) finfo[j].properties);
++ if (j == 0)
++ flist[j]--; /* was incremented above */
++ Xfree(flist[j]);
++ if (finfo[j].properties) Xfree((char *) finfo[j].properties);
+ }
+ if (flist) Xfree((char *) flist);
+ if (finfo) Xfree((char *) finfo);
+
+ clearwire:
+ /* Clear the wire. */
+- do {
+- if (reply.nFontProps)
+- _XEatData(dpy, (unsigned long)
+- (reply.nFontProps * SIZEOF(xFontProp)));
+- nbytes = (reply.nameLength + 3) & ~3;
+- _XEatData(dpy, (unsigned long) nbytes);
+- }
+- while (_XReply(dpy,(xReply *) &reply, ((SIZEOF(xListFontsWithInfoReply) -
+- SIZEOF(xGenericReply)) >> 2),
+- xFalse) && (reply.nameLength != 0));
+-
++ _XEatDataWords(dpy, reply_left);
++ while ((reply.nameLength != 0) &&
++ _XReply(dpy, (xReply *) &reply,
++ ((SIZEOF(xListFontsWithInfoReply) - SIZEOF(xGenericReply))
++ >> 2), xTrue));
+ UnlockDisplay(dpy);
+ SyncHandle();
++ *info = NULL;
++ *actualCount = 0;
+ return (char **) NULL;
+ }
+
+diff --git a/src/FontNames.c b/src/FontNames.c
+index 3018cf2..b5bc7b4 100644
+--- a/src/FontNames.c
++++ b/src/FontNames.c
+@@ -29,6 +29,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
+
+ char **
+ XListFonts(
+@@ -40,11 +41,13 @@ int *actualCount) /* RETURN */
+ register long nbytes;
+ register unsigned i;
+ register int length;
+- char **flist;
+- char *ch;
++ char **flist = NULL;
++ char *ch = NULL;
++ char *chend;
++ int count = 0;
+ xListFontsReply rep;
+ register xListFontsReq *req;
+- register long rlen;
++ unsigned long rlen;
+
+ LockDisplay(dpy);
+ GetReq(ListFonts, req);
+@@ -62,15 +65,17 @@ int *actualCount) /* RETURN */
+ }
+
+ if (rep.nFonts) {
+- flist = (char **)Xmalloc ((unsigned)rep.nFonts * sizeof(char *));
+- rlen = rep.length << 2;
+- ch = (char *) Xmalloc((unsigned) (rlen + 1));
++ flist = Xmalloc (rep.nFonts * sizeof(char *));
++ if (rep.length < (LONG_MAX >> 2)) {
++ rlen = rep.length << 2;
++ ch = Xmalloc(rlen + 1);
+ /* +1 to leave room for last null-terminator */
++ }
+
+ if ((! flist) || (! ch)) {
+ if (flist) Xfree((char *) flist);
+ if (ch) Xfree(ch);
+- _XEatData(dpy, (unsigned long) rlen);
++ _XEatDataWords(dpy, rep.length);
+ *actualCount = 0;
+ UnlockDisplay(dpy);
+ SyncHandle();
+@@ -81,17 +86,21 @@ int *actualCount) /* RETURN */
+ /*
+ * unpack into null terminated strings.
+ */
++ chend = ch + (rlen + 1);
+ length = *(unsigned char *)ch;
+ *ch = 1; /* make sure it is non-zero for XFreeFontNames */
+ for (i = 0; i < rep.nFonts; i++) {
+- flist[i] = ch + 1; /* skip over length */
+- ch += length + 1; /* find next length ... */
+- length = *(unsigned char *)ch;
+- *ch = '\0'; /* and replace with null-termination */
++ if (ch + length < chend) {
++ flist[i] = ch + 1; /* skip over length */
++ ch += length + 1; /* find next length ... */
++ length = *(unsigned char *)ch;
++ *ch = '\0'; /* and replace with null-termination */
++ count++;
++ } else
++ flist[i] = NULL;
+ }
+ }
+- else flist = (char **) NULL;
+- *actualCount = rep.nFonts;
++ *actualCount = count;
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (flist);
+diff --git a/src/GetAtomNm.c b/src/GetAtomNm.c
+index 9823c69..32de50d 100644
+--- a/src/GetAtomNm.c
++++ b/src/GetAtomNm.c
+@@ -46,7 +46,7 @@ char *_XGetAtomName(
+ for (idx = TABLESIZE; --idx >= 0; ) {
+ if ((e = *table++) && (e->atom == atom)) {
+ idx = strlen(EntryName(e)) + 1;
+- if ((name = (char *)Xmalloc(idx)))
++ if ((name = Xmalloc(idx)))
+ strcpy(name, EntryName(e));
+ return name;
+ }
+@@ -73,12 +73,12 @@ char *XGetAtomName(
+ SyncHandle();
+ return(NULL);
+ }
+- if ((name = (char *) Xmalloc(rep.nameLength+1))) {
++ if ((name = Xmalloc(rep.nameLength + 1))) {
+ _XReadPad(dpy, name, (long)rep.nameLength);
+ name[rep.nameLength] = '\0';
+ _XUpdateAtomCache(dpy, name, atom, 0, -1, 0);
+ } else {
+- _XEatData(dpy, (unsigned long) (rep.nameLength + 3) & ~3);
++ _XEatDataWords(dpy, rep.length);
+ name = (char *) NULL;
+ }
+ UnlockDisplay(dpy);
+@@ -124,7 +124,7 @@ Bool _XGetAtomNameHandler(
+ _XGetAsyncReply(dpy, (char *)&replbuf, rep, buf, len,
+ (SIZEOF(xGetAtomNameReply) - SIZEOF(xReply)) >> 2,
+ False);
+- state->names[state->idx] = (char *) Xmalloc(repl->nameLength+1);
++ state->names[state->idx] = Xmalloc(repl->nameLength + 1);
+ _XGetAsyncData(dpy, state->names[state->idx], buf, len,
+ SIZEOF(xGetAtomNameReply), repl->nameLength,
+ repl->length << 2);
+@@ -170,13 +170,13 @@ XGetAtomNames (
+ }
+ if (missed >= 0) {
+ if (_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
+- if ((names_return[missed] = (char *) Xmalloc(rep.nameLength+1))) {
++ if ((names_return[missed] = Xmalloc(rep.nameLength + 1))) {
+ _XReadPad(dpy, names_return[missed], (long)rep.nameLength);
+ names_return[missed][rep.nameLength] = '\0';
+ _XUpdateAtomCache(dpy, names_return[missed], atoms[missed],
+ 0, -1, 0);
+ } else {
+- _XEatData(dpy, (unsigned long) (rep.nameLength + 3) & ~3);
++ _XEatDataWords(dpy, rep.length);
+ async_state.status = 0;
+ }
+ }
+diff --git a/src/GetDflt.c b/src/GetDflt.c
+index dfda1c6..f761ca8 100644
+--- a/src/GetDflt.c
++++ b/src/GetDflt.c
+@@ -52,30 +52,7 @@ SOFTWARE.
+ #include "Xlibint.h"
+ #include <X11/Xos.h>
+ #include <X11/Xresource.h>
+-
+-#ifndef X_NOT_POSIX
+-#ifdef _POSIX_SOURCE
+-#include <limits.h>
+-#else
+-#define _POSIX_SOURCE
+-#include <limits.h>
+-#undef _POSIX_SOURCE
+-#endif
+-#endif
+-#ifndef PATH_MAX
+-#ifdef WIN32
+-#define PATH_MAX 512
+-#else
+-#include <sys/param.h>
+-#endif
+-#ifndef PATH_MAX
+-#ifdef MAXPATHLEN
+-#define PATH_MAX MAXPATHLEN
+-#else
+-#define PATH_MAX 1024
+-#endif
+-#endif
+-#endif
++#include "pathmax.h"
+
+ #ifdef XTHREADS
+ #include <X11/Xthreads.h>
+diff --git a/src/GetFPath.c b/src/GetFPath.c
+index 7d497c9..abd4a5d 100644
+--- a/src/GetFPath.c
++++ b/src/GetFPath.c
+@@ -28,15 +28,18 @@ in this Software without prior written authorization from The Open Group.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
+
+ char **XGetFontPath(
+ register Display *dpy,
+ int *npaths) /* RETURN */
+ {
+ xGetFontPathReply rep;
+- register long nbytes;
+- char **flist;
+- char *ch;
++ unsigned long nbytes;
++ char **flist = NULL;
++ char *ch = NULL;
++ char *chend;
++ int count = 0;
+ register unsigned i;
+ register int length;
+ register xReq *req;
+@@ -46,16 +49,17 @@ char **XGetFontPath(
+ (void) _XReply (dpy, (xReply *) &rep, 0, xFalse);
+
+ if (rep.nPaths) {
+- flist = (char **)
+- Xmalloc((unsigned) rep.nPaths * sizeof (char *));
+- nbytes = (long)rep.length << 2;
+- ch = (char *) Xmalloc ((unsigned) (nbytes + 1));
++ flist = Xmalloc(rep.nPaths * sizeof (char *));
++ if (rep.length < (LONG_MAX >> 2)) {
++ nbytes = (unsigned long) rep.length << 2;
++ ch = Xmalloc (nbytes + 1);
+ /* +1 to leave room for last null-terminator */
++ }
+
+ if ((! flist) || (! ch)) {
+ if (flist) Xfree((char *) flist);
+ if (ch) Xfree(ch);
+- _XEatData(dpy, (unsigned long) nbytes);
++ _XEatDataWords(dpy, rep.length);
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (char **) NULL;
+@@ -65,16 +69,20 @@ char **XGetFontPath(
+ /*
+ * unpack into null terminated strings.
+ */
++ chend = ch + (nbytes + 1);
+ length = *ch;
+ for (i = 0; i < rep.nPaths; i++) {
+- flist[i] = ch+1; /* skip over length */
+- ch += length + 1; /* find next length ... */
+- length = *ch;
+- *ch = '\0'; /* and replace with null-termination */
++ if (ch + length < chend) {
++ flist[i] = ch+1; /* skip over length */
++ ch += length + 1; /* find next length ... */
++ length = *ch;
++ *ch = '\0'; /* and replace with null-termination */
++ count++;
++ } else
++ flist[i] = NULL;
+ }
+ }
+- else flist = NULL;
+- *npaths = rep.nPaths;
++ *npaths = count;
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (flist);
+diff --git a/src/GetHints.c b/src/GetHints.c
+index 4800fe7..3c410d3 100644
+--- a/src/GetHints.c
++++ b/src/GetHints.c
+@@ -128,7 +128,7 @@ XWMHints *XGetWMHints (
+ return(NULL);
+ }
+ /* static copies not allowed in library, due to reentrancy constraint*/
+- if ((hints = (XWMHints *) Xcalloc (1, (unsigned) sizeof(XWMHints)))) {
++ if ((hints = Xcalloc (1, sizeof(XWMHints)))) {
+ hints->flags = prop->flags;
+ hints->input = (prop->input ? True : False);
+ hints->initial_state = cvtINT32toInt (prop->initialState);
+@@ -203,8 +203,7 @@ Status XGetIconSizes (
+ /* static copies not allowed in library, due to reentrancy constraint*/
+
+ nitems /= NumPropIconSizeElements;
+- if (! (hp = hints = (XIconSize *)
+- Xcalloc ((unsigned) nitems, (unsigned) sizeof(XIconSize)))) {
++ if (! (hp = hints = Xcalloc (nitems, sizeof(XIconSize)))) {
+ if (prop) Xfree ((char *) prop);
+ return 0;
+ }
+@@ -317,14 +316,14 @@ XGetClassHint(
+
+ if ( (actual_type == XA_STRING) && (actual_format == 8) ) {
+ len_name = strlen((char *) data);
+- if (! (classhint->res_name = Xmalloc((unsigned) (len_name+1)))) {
++ if (! (classhint->res_name = Xmalloc(len_name + 1))) {
+ Xfree((char *) data);
+ return (0);
+ }
+ strcpy(classhint->res_name, (char *) data);
+ if (len_name == nitems) len_name--;
+ len_class = strlen((char *) (data+len_name+1));
+- if (! (classhint->res_class = Xmalloc((unsigned) (len_class+1)))) {
++ if (! (classhint->res_class = Xmalloc(len_class + 1))) {
+ Xfree(classhint->res_name);
+ classhint->res_name = (char *) NULL;
+ Xfree((char *) data);
+diff --git a/src/GetImage.c b/src/GetImage.c
+index e8f1b03..c461abc 100644
+--- a/src/GetImage.c
++++ b/src/GetImage.c
+@@ -30,6 +30,7 @@ in this Software without prior written authorization from The Open Group.
+ #include "Xlibint.h"
+ #include <X11/Xutil.h> /* for XDestroyImage */
+ #include "ImUtil.h"
++#include <limits.h>
+
+ #define ROUNDUP(nbytes, pad) (((((nbytes) - 1) + (pad)) / (pad)) * (pad))
+
+@@ -56,7 +57,7 @@ XImage *XGetImage (
+ xGetImageReply rep;
+ register xGetImageReq *req;
+ char *data;
+- long nbytes;
++ unsigned long nbytes;
+ XImage *image;
+ LockDisplay(dpy);
+ GetReq (GetImage, req);
+@@ -78,10 +79,13 @@ XImage *XGetImage (
+ return (XImage *)NULL;
+ }
+
+- nbytes = (long)rep.length << 2;
+- data = (char *) Xmalloc((unsigned) nbytes);
++ if (rep.length < (INT_MAX >> 2)) {
++ nbytes = (unsigned long)rep.length << 2;
++ data = Xmalloc(nbytes);
++ } else
++ data = NULL;
+ if (! data) {
+- _XEatData(dpy, (unsigned long) nbytes);
++ _XEatDataWords(dpy, rep.length);
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (XImage *) NULL;
+diff --git a/src/GetMoEv.c b/src/GetMoEv.c
+index 3db176f..ad9c772 100644
+--- a/src/GetMoEv.c
++++ b/src/GetMoEv.c
+@@ -28,6 +28,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
+
+ XTimeCoord *XGetMotionEvents(
+ register Display *dpy,
+@@ -39,7 +40,6 @@ XTimeCoord *XGetMotionEvents(
+ xGetMotionEventsReply rep;
+ register xGetMotionEventsReq *req;
+ XTimeCoord *tc = NULL;
+- long nbytes;
+ LockDisplay(dpy);
+ GetReq(GetMotionEvents, req);
+ req->window = w;
+@@ -52,26 +52,22 @@ XTimeCoord *XGetMotionEvents(
+ return (NULL);
+ }
+
+- if (rep.nEvents) {
+- if (! (tc = (XTimeCoord *)
+- Xmalloc( (unsigned)
+- (nbytes = (long) rep.nEvents * sizeof(XTimeCoord))))) {
+- _XEatData (dpy, (unsigned long) nbytes);
+- UnlockDisplay(dpy);
+- SyncHandle();
+- return (NULL);
+- }
++ if (rep.nEvents && (rep.nEvents < (INT_MAX / sizeof(XTimeCoord))))
++ tc = Xmalloc(rep.nEvents * sizeof(XTimeCoord));
++ if (tc == NULL) {
++ /* server returned either no events or a bad event count */
++ *nEvents = 0;
++ _XEatDataWords (dpy, rep.length);
+ }
+-
+- *nEvents = rep.nEvents;
+- nbytes = SIZEOF (xTimecoord);
++ else
+ {
+ register XTimeCoord *tcptr;
+- register int i;
++ unsigned int i;
+ xTimecoord xtc;
+
++ *nEvents = (int) rep.nEvents;
+ for (i = rep.nEvents, tcptr = tc; i > 0; i--, tcptr++) {
+- _XRead (dpy, (char *) &xtc, nbytes);
++ _XRead (dpy, (char *) &xtc, SIZEOF (xTimecoord));
+ tcptr->time = xtc.time;
+ tcptr->x = cvtINT16toShort (xtc.x);
+ tcptr->y = cvtINT16toShort (xtc.y);
+diff --git a/src/GetPntMap.c b/src/GetPntMap.c
+index 0fcdb66..29fdf21 100644
+--- a/src/GetPntMap.c
++++ b/src/GetPntMap.c
+@@ -29,6 +29,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
+
+ #ifdef MIN /* some systems define this in <sys/param.h> */
+ #undef MIN
+@@ -42,7 +43,7 @@ int XGetPointerMapping (
+
+ {
+ unsigned char mapping[256]; /* known fixed size */
+- long nbytes, remainder = 0;
++ unsigned long nbytes, remainder = 0;
+ xGetPointerMappingReply rep;
+ register xReq *req;
+
+@@ -54,9 +55,15 @@ int XGetPointerMapping (
+ return 0;
+ }
+
+- nbytes = (long)rep.length << 2;
+-
+ /* Don't count on the server returning a valid value */
++ if (rep.length >= (INT_MAX >> 2)) {
++ _XEatDataWords(dpy, rep.length);
++ UnlockDisplay(dpy);
++ SyncHandle();
++ return 0;
++ }
++
++ nbytes = (unsigned long) rep.length << 2;
+ if (nbytes > sizeof mapping) {
+ remainder = nbytes - sizeof mapping;
+ nbytes = sizeof mapping;
+@@ -69,7 +76,7 @@ int XGetPointerMapping (
+ }
+
+ if (remainder)
+- _XEatData(dpy, (unsigned long)remainder);
++ _XEatData(dpy, remainder);
+
+ UnlockDisplay(dpy);
+ SyncHandle();
+@@ -86,8 +93,8 @@ XGetKeyboardMapping (Display *dpy,
+ int count,
+ int *keysyms_per_keycode)
+ {
+- long nbytes;
+- unsigned long nkeysyms;
++ unsigned long nbytes;
++ CARD32 nkeysyms;
+ register KeySym *mapping = NULL;
+ xGetKeyboardMappingReply rep;
+ register xGetKeyboardMappingReq *req;
+@@ -102,17 +109,19 @@ XGetKeyboardMapping (Display *dpy,
+ return (KeySym *) NULL;
+ }
+
+- nkeysyms = (unsigned long) rep.length;
++ nkeysyms = rep.length;
+ if (nkeysyms > 0) {
+- nbytes = nkeysyms * sizeof (KeySym);
+- mapping = (KeySym *) Xmalloc ((unsigned) nbytes);
+- nbytes = nkeysyms << 2;
++ if (nkeysyms < (INT_MAX / sizeof (KeySym))) {
++ nbytes = nkeysyms * sizeof (KeySym);
++ mapping = Xmalloc (nbytes);
++ }
+ if (! mapping) {
+- _XEatData(dpy, (unsigned long) nbytes);
++ _XEatDataWords(dpy, rep.length);
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (KeySym *) NULL;
+ }
++ nbytes = nkeysyms << 2;
+ _XRead32 (dpy, (long *) mapping, nbytes);
+ }
+ *keysyms_per_keycode = rep.keySymsPerKeyCode;
+diff --git a/src/GetProp.c b/src/GetProp.c
+index 5d6e0b8..9eb422e 100644
+--- a/src/GetProp.c
++++ b/src/GetProp.c
+@@ -28,6 +28,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
+
+ int
+ XGetWindowProperty(
+@@ -48,6 +49,13 @@ XGetWindowProperty(
+ register xGetPropertyReq *req;
+ xError error = {0};
+
++ /* Always initialize return values, in case callers fail to initialize
++ them and fail to check the return code for an error. */
++ *actual_type = None;
++ *actual_format = 0;
++ *nitems = *bytesafter = 0L;
++ *prop = (unsigned char *) NULL;
++
+ LockDisplay(dpy);
+ GetReq (GetProperty, req);
+ req->window = w;
+@@ -64,10 +72,18 @@ XGetWindowProperty(
+ return (1); /* not Success */
+ }
+
+- *prop = (unsigned char *) NULL;
+ if (reply.propertyType != None) {
+- long nbytes, netbytes;
+- switch (reply.format) {
++ unsigned long nbytes, netbytes;
++ int format = reply.format;
++
++ /*
++ * Protect against both integer overflow and just plain oversized
++ * memory allocation - no server should ever return this many props.
++ */
++ if (reply.nItems >= (INT_MAX >> 4))
++ format = -1; /* fall through to default error case */
++
++ switch (format) {
+ /*
+ * One extra byte is malloced than is needed to contain the property
+ * data, but this last byte is null terminated and convenient for
+@@ -76,24 +92,21 @@ XGetWindowProperty(
+ */
+ case 8:
+ nbytes = netbytes = reply.nItems;
+- if (nbytes + 1 > 0 &&
+- (*prop = (unsigned char *) Xmalloc ((unsigned)nbytes + 1)))
++ if (nbytes + 1 > 0 && (*prop = Xmalloc (nbytes + 1)))
+ _XReadPad (dpy, (char *) *prop, netbytes);
+ break;
+
+ case 16:
+ nbytes = reply.nItems * sizeof (short);
+ netbytes = reply.nItems << 1;
+- if (nbytes + 1 > 0 &&
+- (*prop = (unsigned char *) Xmalloc ((unsigned)nbytes + 1)))
++ if (nbytes + 1 > 0 && (*prop = Xmalloc (nbytes + 1)))
+ _XRead16Pad (dpy, (short *) *prop, netbytes);
+ break;
+
+ case 32:
+ nbytes = reply.nItems * sizeof (long);
+ netbytes = reply.nItems << 2;
+- if (nbytes + 1 > 0 &&
+- (*prop = (unsigned char *) Xmalloc ((unsigned)nbytes + 1)))
++ if (nbytes + 1 > 0 && (*prop = Xmalloc (nbytes + 1)))
+ _XRead32 (dpy, (long *) *prop, netbytes);
+ break;
+
+@@ -115,7 +128,7 @@ XGetWindowProperty(
+ break;
+ }
+ if (! *prop) {
+- _XEatData(dpy, (unsigned long) netbytes);
++ _XEatDataWords(dpy, reply.length);
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return(BadAlloc); /* not Success */
+diff --git a/src/GetRGBCMap.c b/src/GetRGBCMap.c
+index 9e227a2..2f0b752 100644
+--- a/src/GetRGBCMap.c
++++ b/src/GetRGBCMap.c
+@@ -99,8 +99,7 @@ Status XGetRGBColormaps (
+ /*
+ * allocate array
+ */
+- cmaps = (XStandardColormap *) Xmalloc (ncmaps *
+- sizeof (XStandardColormap));
++ cmaps = Xmalloc (ncmaps * sizeof (XStandardColormap));
+ if (!cmaps) {
+ if (data) Xfree ((char *) data);
+ return False;
+diff --git a/src/ImUtil.c b/src/ImUtil.c
+index 3164d43..39beb4d 100644
+--- a/src/ImUtil.c
++++ b/src/ImUtil.c
+@@ -332,7 +332,7 @@ XImage *XCreateImage (
+ (xpad != 8 && xpad != 16 && xpad != 32) ||
+ offset < 0)
+ return (XImage *) NULL;
+- if ((image = (XImage *) Xcalloc(1, (unsigned) sizeof(XImage))) == NULL)
++ if ((image = Xcalloc(1, sizeof(XImage))) == NULL)
+ return (XImage *) NULL;
+
+ image->width = width;
+@@ -850,7 +850,7 @@ static XImage *_XSubImage (
+ register unsigned long pixel;
+ char *data;
+
+- if ((subimage = (XImage *) Xcalloc (1, sizeof (XImage))) == NULL)
++ if ((subimage = Xcalloc (1, sizeof (XImage))) == NULL)
+ return (XImage *) NULL;
+ subimage->width = width;
+ subimage->height = height;
+@@ -876,7 +876,7 @@ static XImage *_XSubImage (
+ _XInitImageFuncPtrs (subimage);
+ dsize = subimage->bytes_per_line * height;
+ if (subimage->format == XYPixmap) dsize = dsize * subimage->depth;
+- if (((data = Xcalloc (1, (unsigned) dsize)) == NULL) && (dsize > 0)) {
++ if (((data = Xcalloc (1, dsize)) == NULL) && (dsize > 0)) {
+ Xfree((char *) subimage);
+ return (XImage *) NULL;
+ }
+diff --git a/src/InitExt.c b/src/InitExt.c
+index 19515cc..75991bd 100644
+--- a/src/InitExt.c
++++ b/src/InitExt.c
+@@ -49,7 +49,7 @@ XExtCodes *XInitExtension (
+ &codes.first_error)) return (NULL);
+
+ LockDisplay (dpy);
+- if (! (ext = (_XExtension *) Xcalloc (1, sizeof (_XExtension))) ||
++ if (! (ext = Xcalloc (1, sizeof (_XExtension))) ||
+ ! (ext->name = strdup(name))) {
+ if (ext) Xfree((char *) ext);
+ UnlockDisplay(dpy);
+@@ -71,7 +71,7 @@ XExtCodes *XAddExtension (Display *dpy)
+ register _XExtension *ext;
+
+ LockDisplay (dpy);
+- if (! (ext = (_XExtension *) Xcalloc (1, sizeof (_XExtension)))) {
++ if (! (ext = Xcalloc (1, sizeof (_XExtension)))) {
+ UnlockDisplay(dpy);
+ return (XExtCodes *) NULL;
+ }
+diff --git a/src/IntAtom.c b/src/IntAtom.c
+index 7a56258..25466ca 100644
+--- a/src/IntAtom.c
++++ b/src/IntAtom.c
+@@ -72,7 +72,7 @@ Atom _XInternAtom(
+
+ /* look in the cache first */
+ if (!(atoms = dpy->atoms)) {
+- dpy->atoms = atoms = (AtomTable *)Xcalloc(1, sizeof(AtomTable));
++ dpy->atoms = atoms = Xcalloc(1, sizeof(AtomTable));
+ dpy->free_funcs->atoms = _XFreeAtomTable;
+ }
+ sig = 0;
+@@ -127,7 +127,7 @@ _XUpdateAtomCache(
+
+ if (!dpy->atoms) {
+ if (idx < 0) {
+- dpy->atoms = (AtomTable *)Xcalloc(1, sizeof(AtomTable));
++ dpy->atoms = Xcalloc(1, sizeof(AtomTable));
+ dpy->free_funcs->atoms = _XFreeAtomTable;
+ }
+ if (!dpy->atoms)
+@@ -147,7 +147,7 @@ _XUpdateAtomCache(
+ }
+ }
+ }
+- e = (Entry)Xmalloc(sizeof(EntryRec) + n + 1);
++ e = Xmalloc(sizeof(EntryRec) + n + 1);
+ if (e) {
+ e->sig = sig;
+ e->atom = atom;
+diff --git a/src/Key.h b/src/Key.h
+index 0fe89ba..bb25439 100644
+--- a/src/Key.h
++++ b/src/Key.h
+@@ -2,6 +2,9 @@
+ #ifndef _KEY_H_
+ #define _KEY_H_
+
++#include <X11/Xlib.h>
++#include <X11/Xresource.h>
++
+ #ifndef NEEDKTABLE
+ extern const unsigned char _XkeyTable[];
+ #endif
+diff --git a/src/KeyBind.c b/src/KeyBind.c
+index 221cedd..efd21ba 100644
+--- a/src/KeyBind.c
++++ b/src/KeyBind.c
+@@ -997,11 +997,9 @@ XRebindKeysym (
+ tmp = dpy->key_bindings;
+ nb = sizeof(KeySym) * nm;
+
+- if ((! (p = (struct _XKeytrans *) Xcalloc( 1, sizeof(struct _XKeytrans)))) ||
+- ((! (p->string = (char *) Xmalloc( (unsigned) nbytes))) &&
+- (nbytes > 0)) ||
+- ((! (p->modifiers = (KeySym *) Xmalloc( (unsigned) nb))) &&
+- (nb > 0))) {
++ if ((! (p = Xcalloc( 1, sizeof(struct _XKeytrans)))) ||
++ ((! (p->string = Xmalloc(nbytes))) && (nbytes > 0)) ||
++ ((! (p->modifiers = Xmalloc(nb))) && (nb > 0))) {
+ if (p) {
+ if (p->string) Xfree(p->string);
+ if (p->modifiers) Xfree((char *) p->modifiers);
+diff --git a/src/LiHosts.c b/src/LiHosts.c
+index 5ae70d5..c6d82fa 100644
+--- a/src/LiHosts.c
++++ b/src/LiHosts.c
+@@ -62,6 +62,8 @@ X Window System is a trademark of The Open Group.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
++
+ /*
+ * can be freed using XFree.
+ */
+@@ -73,7 +75,6 @@ XHostAddress *XListHosts (
+ {
+ register XHostAddress *outbuf = NULL, *op;
+ xListHostsReply reply;
+- long nbytes;
+ unsigned char *buf, *bp;
+ register unsigned i;
+ register xListHostsReq *req;
+@@ -90,19 +91,26 @@ XHostAddress *XListHosts (
+ }
+
+ if (reply.nHosts) {
+- nbytes = reply.length << 2; /* compute number of bytes in reply */
++ unsigned long nbytes = reply.length << 2; /* number of bytes in reply */
++ const unsigned long max_hosts = INT_MAX /
++ (sizeof(XHostAddress) + sizeof(XServerInterpretedAddress));
++
++ if (reply.nHosts < max_hosts) {
++ unsigned long hostbytes = reply.nHosts *
++ (sizeof(XHostAddress) + sizeof(XServerInterpretedAddress));
+
+- op = outbuf = (XHostAddress *)
+- Xmalloc((unsigned) (nbytes +
+- (reply.nHosts * sizeof(XHostAddress)) +
+- (reply.nHosts * sizeof(XServerInterpretedAddress))));
++ if (reply.length < (INT_MAX >> 2) &&
++ (hostbytes >> 2) < ((INT_MAX >> 2) - reply.length))
++ outbuf = Xmalloc(nbytes + hostbytes);
++ }
+
+ if (! outbuf) {
+- _XEatData(dpy, (unsigned long) nbytes);
++ _XEatDataWords(dpy, reply.length);
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (XHostAddress *) NULL;
+ }
++ op = outbuf;
+ sip = (XServerInterpretedAddress *)
+ (((unsigned char *) outbuf) + (reply.nHosts * sizeof(XHostAddress)));
+ bp = buf = ((unsigned char *) sip)
+diff --git a/src/LiICmaps.c b/src/LiICmaps.c
+index e981619..45a2f2f 100644
+--- a/src/LiICmaps.c
++++ b/src/LiICmaps.c
+@@ -34,7 +34,7 @@ Colormap *XListInstalledColormaps(
+ Window win,
+ int *n) /* RETURN */
+ {
+- long nbytes;
++ unsigned long nbytes;
+ Colormap *cmaps;
+ xListInstalledColormapsReply rep;
+ register xResourceReq *req;
+@@ -51,14 +51,14 @@ Colormap *XListInstalledColormaps(
+
+ if (rep.nColormaps) {
+ nbytes = rep.nColormaps * sizeof(Colormap);
+- cmaps = (Colormap *) Xmalloc((unsigned) nbytes);
+- nbytes = rep.nColormaps << 2;
++ cmaps = Xmalloc(nbytes);
+ if (! cmaps) {
+- _XEatData(dpy, (unsigned long) nbytes);
++ _XEatDataWords(dpy, rep.length);
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return((Colormap *) NULL);
+ }
++ nbytes = rep.nColormaps << 2;
+ _XRead32 (dpy, (long *) cmaps, nbytes);
+ }
+ else cmaps = (Colormap *) NULL;
+diff --git a/src/LiProps.c b/src/LiProps.c
+index 72560ab..d9c7465 100644
+--- a/src/LiProps.c
++++ b/src/LiProps.c
+@@ -34,7 +34,7 @@ Atom *XListProperties(
+ Window window,
+ int *n_props) /* RETURN */
+ {
+- long nbytes;
++ unsigned long nbytes;
+ xListPropertiesReply rep;
+ Atom *properties;
+ register xResourceReq *req;
+@@ -50,14 +50,14 @@ Atom *XListProperties(
+
+ if (rep.nProperties) {
+ nbytes = rep.nProperties * sizeof(Atom);
+- properties = (Atom *) Xmalloc ((unsigned) nbytes);
+- nbytes = rep.nProperties << 2;
++ properties = Xmalloc (nbytes);
+ if (! properties) {
+- _XEatData(dpy, (unsigned long) nbytes);
++ _XEatDataWords(dpy, rep.length);
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (Atom *) NULL;
+ }
++ nbytes = rep.nProperties << 2;
+ _XRead32 (dpy, (long *) properties, nbytes);
+ }
+ else properties = (Atom *) NULL;
+diff --git a/src/ListExt.c b/src/ListExt.c
+index 16b522e..e925c47 100644
+--- a/src/ListExt.c
++++ b/src/ListExt.c
+@@ -28,18 +28,21 @@ in this Software without prior written authorization from The Open Group.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
+
+ char **XListExtensions(
+ register Display *dpy,
+ int *nextensions) /* RETURN */
+ {
+ xListExtensionsReply rep;
+- char **list;
+- char *ch;
++ char **list = NULL;
++ char *ch = NULL;
++ char *chend;
++ int count = 0;
+ register unsigned i;
+ register int length;
+ register xReq *req;
+- register long rlen;
++ unsigned long rlen;
+
+ LockDisplay(dpy);
+ GetEmptyReq (ListExtensions, req);
+@@ -51,16 +54,17 @@ char **XListExtensions(
+ }
+
+ if (rep.nExtensions) {
+- list = (char **) Xmalloc (
+- (unsigned)(rep.nExtensions * sizeof (char *)));
+- rlen = rep.length << 2;
+- ch = (char *) Xmalloc ((unsigned) rlen + 1);
++ list = Xmalloc (rep.nExtensions * sizeof (char *));
++ if (rep.length < (LONG_MAX >> 2)) {
++ rlen = rep.length << 2;
++ ch = Xmalloc (rlen + 1);
+ /* +1 to leave room for last null-terminator */
++ }
+
+ if ((!list) || (!ch)) {
+ if (list) Xfree((char *) list);
+ if (ch) Xfree((char *) ch);
+- _XEatData(dpy, (unsigned long) rlen);
++ _XEatDataWords(dpy, rep.length);
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (char **) NULL;
+@@ -70,17 +74,21 @@ char **XListExtensions(
+ /*
+ * unpack into null terminated strings.
+ */
++ chend = ch + (rlen + 1);
+ length = *ch;
+ for (i = 0; i < rep.nExtensions; i++) {
+- list[i] = ch+1; /* skip over length */
+- ch += length + 1; /* find next length ... */
+- length = *ch;
+- *ch = '\0'; /* and replace with null-termination */
++ if (ch + length < chend) {
++ list[i] = ch+1; /* skip over length */
++ ch += length + 1; /* find next length ... */
++ length = *ch;
++ *ch = '\0'; /* and replace with null-termination */
++ count++;
++ } else
++ list[i] = NULL;
+ }
+ }
+- else list = (char **) NULL;
+
+- *nextensions = rep.nExtensions;
++ *nextensions = count;
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (list);
+diff --git a/src/Makefile.am b/src/Makefile.am
+index 71e02e7..27b74b0 100644
+--- a/src/Makefile.am
++++ b/src/Makefile.am
+@@ -210,6 +210,7 @@ libX11_la_SOURCES = \
+ ParseCmd.c \
+ ParseCol.c \
+ ParseGeom.c \
++ pathmax.h \
+ PeekEvent.c \
+ PeekIfEv.c \
+ Pending.c \
+diff --git a/src/ModMap.c b/src/ModMap.c
+index c99bfdd..5c5b426 100644
+--- a/src/ModMap.c
++++ b/src/ModMap.c
+@@ -28,6 +28,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
+
+ XModifierKeymap *
+ XGetModifierMapping(register Display *dpy)
+@@ -41,13 +42,17 @@ XGetModifierMapping(register Display *dpy)
+ GetEmptyReq(GetModifierMapping, req);
+ (void) _XReply (dpy, (xReply *)&rep, 0, xFalse);
+
+- nbytes = (unsigned long)rep.length << 2;
+- res = (XModifierKeymap *) Xmalloc(sizeof (XModifierKeymap));
+- if (res) res->modifiermap = (KeyCode *) Xmalloc ((unsigned) nbytes);
++ if (rep.length < (LONG_MAX >> 2)) {
++ nbytes = (unsigned long)rep.length << 2;
++ res = Xmalloc(sizeof (XModifierKeymap));
++ if (res)
++ res->modifiermap = Xmalloc (nbytes);
++ } else
++ res = NULL;
+ if ((! res) || (! res->modifiermap)) {
+ if (res) Xfree((char *) res);
+ res = (XModifierKeymap *) NULL;
+- _XEatData(dpy, nbytes);
++ _XEatDataWords(dpy, rep.length);
+ } else {
+ _XReadPad(dpy, (char *) res->modifiermap, (long) nbytes);
+ res->max_keypermod = rep.numKeyPerModifier;
+@@ -92,11 +97,11 @@ XSetModifierMapping(
+ XModifierKeymap *
+ XNewModifiermap(int keyspermodifier)
+ {
+- XModifierKeymap *res = (XModifierKeymap *) Xmalloc((sizeof (XModifierKeymap)));
++ XModifierKeymap *res = Xmalloc((sizeof (XModifierKeymap)));
+ if (res) {
+ res->max_keypermod = keyspermodifier;
+ res->modifiermap = (keyspermodifier > 0 ?
+- (KeyCode *) Xmalloc((unsigned) (8 * keyspermodifier))
++ Xmalloc(8 * keyspermodifier)
+ : (KeyCode *) NULL);
+ if (keyspermodifier && (res->modifiermap == NULL)) {
+ Xfree((char *) res);
+diff --git a/src/MoveWin.c b/src/MoveWin.c
+index 3cd75e1..2eb2283 100644
+--- a/src/MoveWin.c
++++ b/src/MoveWin.c
+@@ -44,20 +44,11 @@ XMoveWindow (
+ req->window = w;
+ req->mask = CWX | CWY;
+
+-#ifdef MUSTCOPY
+- {
+- long lx = (long) x, ly = (long) y;
+- dpy->bufptr -= 8;
+- Data32 (dpy, (long *) &lx, 4); /* order dictated by CWX and CWY */
+- Data32 (dpy, (long *) &ly, 4);
+- }
+-#else
+ {
+ CARD32 *valuePtr = (CARD32 *) NEXTPTR(req,xConfigureWindowReq);
+ *valuePtr++ = x;
+ *valuePtr = y;
+ }
+-#endif /* MUSTCOPY */
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return 1;
+diff --git a/src/OpenDis.c b/src/OpenDis.c
+index 9379fec..f9231d8 100644
+--- a/src/OpenDis.c
++++ b/src/OpenDis.c
+@@ -112,7 +112,7 @@ XOpenDisplay (
+ /*
+ * Attempt to allocate a display structure. Return NULL if allocation fails.
+ */
+- if ((dpy = (Display *)Xcalloc(1, sizeof(Display))) == NULL) {
++ if ((dpy = Xcalloc(1, sizeof(Display))) == NULL) {
+ return(NULL);
+ }
+
+@@ -246,9 +246,7 @@ XOpenDisplay (
+ dpy->qlen = 0;
+
+ /* Set up free-function record */
+- if ((dpy->free_funcs = (_XFreeFuncRec *)Xcalloc(1,
+- sizeof(_XFreeFuncRec)))
+- == NULL) {
++ if ((dpy->free_funcs = Xcalloc(1, sizeof(_XFreeFuncRec))) == NULL) {
+ OutOfMemory (dpy);
+ return(NULL);
+ }
+@@ -316,7 +314,7 @@ XOpenDisplay (
+ return (NULL);
+ }
+
+- dpy->vendor = (char *) Xmalloc((unsigned) (u.setup->nbytesVendor + 1));
++ dpy->vendor = Xmalloc(u.setup->nbytesVendor + 1);
+ if (dpy->vendor == NULL) {
+ OutOfMemory(dpy);
+ return (NULL);
+@@ -342,9 +340,7 @@ XOpenDisplay (
+ /*
+ * Now iterate down setup information.....
+ */
+- dpy->pixmap_format =
+- (ScreenFormat *)Xmalloc(
+- (unsigned) (dpy->nformats *sizeof(ScreenFormat)));
++ dpy->pixmap_format = Xcalloc(dpy->nformats, sizeof(ScreenFormat));
+ if (dpy->pixmap_format == NULL) {
+ OutOfMemory (dpy);
+ return(NULL);
+@@ -372,8 +368,7 @@ XOpenDisplay (
+ /*
+ * next the Screen structures.
+ */
+- dpy->screens =
+- (Screen *)Xmalloc((unsigned) dpy->nscreens*sizeof(Screen));
++ dpy->screens = Xcalloc(dpy->nscreens, sizeof(Screen));
+ if (dpy->screens == NULL) {
+ OutOfMemory (dpy);
+ return(NULL);
+@@ -415,8 +410,7 @@ XOpenDisplay (
+ /*
+ * lets set up the depth structures.
+ */
+- sp->depths = (Depth *)Xmalloc(
+- (unsigned)sp->ndepths*sizeof(Depth));
++ sp->depths = Xcalloc(sp->ndepths, sizeof(Depth));
+ if (sp->depths == NULL) {
+ OutOfMemory (dpy);
+ return(NULL);
+@@ -438,8 +432,7 @@ XOpenDisplay (
+ dp->nvisuals = u.dp->nVisuals;
+ u.dp = (xDepth *) (((char *) u.dp) + sz_xDepth);
+ if (dp->nvisuals > 0) {
+- dp->visuals =
+- (Visual *)Xmalloc((unsigned)dp->nvisuals*sizeof(Visual));
++ dp->visuals = Xcalloc(dp->nvisuals, sizeof(Visual));
+ if (dp->visuals == NULL) {
+ OutOfMemory (dpy);
+ return(NULL);
+@@ -550,7 +543,7 @@ XOpenDisplay (
+ dpy->xdefaults[reply.nItems] = '\0';
+ }
+ else if (reply.propertyType != None)
+- _XEatData(dpy, reply.nItems * (reply.format >> 3));
++ _XEatDataWords(dpy, reply.length);
+ }
+ }
+ UnlockDisplay(dpy);
+diff --git a/src/PixFormats.c b/src/PixFormats.c
+index 8e4a100..6d9f64d 100644
+--- a/src/PixFormats.c
++++ b/src/PixFormats.c
+@@ -38,8 +38,8 @@ XPixmapFormatValues *XListPixmapFormats (
+ Display *dpy,
+ int *count) /* RETURN */
+ {
+- XPixmapFormatValues *formats = (XPixmapFormatValues *)
+- Xmalloc((unsigned) (dpy->nformats * sizeof (XPixmapFormatValues)));
++ XPixmapFormatValues *formats =
++ Xmalloc(dpy->nformats * sizeof (XPixmapFormatValues));
+
+ if (formats) {
+ register int i;
+diff --git a/src/PolyReg.c b/src/PolyReg.c
+index 74c8765..6d02773 100644
+--- a/src/PolyReg.c
++++ b/src/PolyReg.c
+@@ -95,8 +95,7 @@ InsertEdgeInET(
+ {
+ if (*iSLLBlock > SLLSPERBLOCK-1)
+ {
+- tmpSLLBlock =
+- (ScanLineListBlock *)Xmalloc(sizeof(ScanLineListBlock));
++ tmpSLLBlock = Xmalloc(sizeof(ScanLineListBlock));
+ (*SLLBlock)->next = tmpSLLBlock;
+ tmpSLLBlock->next = (ScanLineListBlock *)NULL;
+ *SLLBlock = tmpSLLBlock;
+@@ -410,8 +409,7 @@ static int PtsToRegion(
+
+ numRects = ((numFullPtBlocks * NUMPTSTOBUFFER) + iCurPtBlock) >> 1;
+
+- if (!(reg->rects = (BOX *)Xrealloc((char *)reg->rects,
+- (unsigned) (sizeof(BOX) * numRects)))) {
++ if (!(reg->rects = Xrealloc(reg->rects, sizeof(BOX) * numRects))) {
+ Xfree(prevRects);
+ return(0);
+ }
+@@ -521,8 +519,7 @@ XPolygonRegion(
+
+ if (Count < 2) return region;
+
+- if (! (pETEs = (EdgeTableEntry *)
+- Xmalloc((unsigned) (sizeof(EdgeTableEntry) * Count)))) {
++ if (! (pETEs = Xmalloc(sizeof(EdgeTableEntry) * Count))) {
+ XDestroyRegion(region);
+ return (Region) NULL;
+ }
+@@ -559,7 +556,7 @@ XPolygonRegion(
+ * send out the buffer
+ */
+ if (iPts == NUMPTSTOBUFFER) {
+- tmpPtBlock = (POINTBLOCK *)Xmalloc(sizeof(POINTBLOCK));
++ tmpPtBlock = Xmalloc(sizeof(POINTBLOCK));
+ curPtBlock->next = tmpPtBlock;
+ curPtBlock = tmpPtBlock;
+ pts = curPtBlock->pts;
+@@ -605,7 +602,7 @@ XPolygonRegion(
+ * send out the buffer
+ */
+ if (iPts == NUMPTSTOBUFFER) {
+- tmpPtBlock = (POINTBLOCK *)Xmalloc(sizeof(POINTBLOCK));
++ tmpPtBlock = Xmalloc(sizeof(POINTBLOCK));
+ curPtBlock->next = tmpPtBlock;
+ curPtBlock = tmpPtBlock;
+ pts = curPtBlock->pts;
+diff --git a/src/PolyTxt16.c b/src/PolyTxt16.c
+index dd65818..2e4be16 100644
+--- a/src/PolyTxt16.c
++++ b/src/PolyTxt16.c
+@@ -168,18 +168,7 @@ XDrawText16(
+ }
+ elt->len = 254;
+
+-#if defined(MUSTCOPY) || defined(MUSTCOPY2B)
+- {
+- register int i;
+- register unsigned char *cp;
+- for (i = 0, cp = ((unsigned char *)elt) + 2; i < 254; i++) {
+- *cp++ = CharacterOffset[i].byte1;
+- *cp++ = CharacterOffset[i].byte2;
+- }
+- }
+-#else
+ memcpy ((char *) (elt + 1), (char *)CharacterOffset, 254 * 2);
+-#endif
+ PartialNChars = PartialNChars - 254;
+ CharacterOffset += 254;
+
+@@ -213,21 +202,9 @@ XDrawText16(
+ }
+ elt->len = PartialNChars;
+
+-#if defined(MUSTCOPY) || defined(MUSTCOPY2B)
+- {
+- register int i;
+- register unsigned char *cp;
+- for (i = 0, cp = ((unsigned char *)elt) + 2; i < PartialNChars;
+- i++) {
+- *cp++ = CharacterOffset[i].byte1;
+- *cp++ = CharacterOffset[i].byte2;
+- }
+- }
+-#else
+ memcpy ((char *) (elt + 1), (char *)CharacterOffset,
+ PartialNChars *
+ 2);
+-#endif
+ }
+ }
+ item++;
+diff --git a/src/PropAlloc.c b/src/PropAlloc.c
+index bad7681..2f3ab17 100644
+--- a/src/PropAlloc.c
++++ b/src/PropAlloc.c
+@@ -39,20 +39,19 @@ in this Software without prior written authorization from The Open Group.
+
+ XSizeHints *XAllocSizeHints (void)
+ {
+- return ((XSizeHints *) Xcalloc (1, (unsigned) sizeof (XSizeHints)));
++ return Xcalloc (1, sizeof (XSizeHints));
+ }
+
+
+ XStandardColormap *XAllocStandardColormap (void)
+ {
+- return ((XStandardColormap *)
+- Xcalloc (1, (unsigned) sizeof (XStandardColormap)));
++ return Xcalloc (1, sizeof (XStandardColormap));
+ }
+
+
+ XWMHints *XAllocWMHints (void)
+ {
+- return ((XWMHints *) Xcalloc (1, (unsigned) sizeof (XWMHints)));
++ return Xcalloc (1, sizeof (XWMHints));
+ }
+
+
+@@ -69,7 +68,7 @@ XClassHint *XAllocClassHint (void)
+
+ XIconSize *XAllocIconSize (void)
+ {
+- return ((XIconSize *) Xcalloc (1, (unsigned) sizeof (XIconSize)));
++ return Xcalloc (1, sizeof (XIconSize));
+ }
+
+
+diff --git a/src/PutBEvent.c b/src/PutBEvent.c
+index f9d4c29..1768e03 100644
+--- a/src/PutBEvent.c
++++ b/src/PutBEvent.c
+@@ -41,7 +41,7 @@ _XPutBackEvent (
+ XEvent store = *event;
+
+ if (!dpy->qfree) {
+- if ((dpy->qfree = (_XQEvent *) Xmalloc (sizeof (_XQEvent))) == NULL) {
++ if ((dpy->qfree = Xmalloc (sizeof (_XQEvent))) == NULL) {
+ return 0;
+ }
+ dpy->qfree->next = NULL;
+diff --git a/src/PutImage.c b/src/PutImage.c
+index 6dad4f1..2a694f0 100644
+--- a/src/PutImage.c
++++ b/src/PutImage.c
+@@ -680,7 +680,7 @@ SendXYImage(
+
+ length = ROUNDUP(length, 4);
+ if ((dpy->bufptr + length) > dpy->bufmax) {
+- if ((buf = _XAllocScratch(dpy, (unsigned long) (length))) == NULL) {
++ if ((buf = _XAllocScratch(dpy, length)) == NULL) {
+ UnGetReq(PutImage);
+ return;
+ }
+@@ -703,13 +703,13 @@ SendXYImage(
+ bytes_per_temp_plane = bytes_per_line * req->height;
+ temp_length = ROUNDUP(bytes_per_temp_plane * image->depth, 4);
+ if (buf == dpy->bufptr) {
+- if (! (temp = _XAllocScratch(dpy, (unsigned long) temp_length))) {
++ if (! (temp = _XAllocScratch(dpy, temp_length))) {
+ UnGetReq(PutImage);
+ return;
+ }
+ }
+ else
+- if ((extra = temp = Xmalloc((unsigned) temp_length)) == NULL) {
++ if ((extra = temp = Xmalloc(temp_length)) == NULL) {
+ UnGetReq(PutImage);
+ return;
+ }
+@@ -778,8 +778,7 @@ SendZImage(
+ (req_yoffset * image->bytes_per_line) +
+ ((req_xoffset * image->bits_per_pixel) >> 3);
+ if ((image->bits_per_pixel == 4) && ((unsigned int) req_xoffset & 0x01)) {
+- if (! (shifted_src = (unsigned char *)
+- Xmalloc((unsigned) (req->height * image->bytes_per_line)))) {
++ if (! (shifted_src = Xmalloc(req->height * image->bytes_per_line))) {
+ UnGetReq(PutImage);
+ return;
+ }
+@@ -810,7 +809,7 @@ SendZImage(
+ dest = (unsigned char *)dpy->bufptr;
+ else
+ if ((dest = (unsigned char *)
+- _XAllocScratch(dpy, (unsigned long)(length))) == NULL) {
++ _XAllocScratch(dpy, length)) == NULL) {
+ if (shifted_src) Xfree((char *) shifted_src);
+ UnGetReq(PutImage);
+ return;
+@@ -1001,7 +1000,7 @@ XPutImage (
+ img.bits_per_pixel = dest_bits_per_pixel;
+ img.bytes_per_line = ROUNDUP((dest_bits_per_pixel * width),
+ dest_scanline_pad) >> 3;
+- img.data = Xmalloc((unsigned) (img.bytes_per_line * height));
++ img.data = Xmalloc(img.bytes_per_line * height);
+ if (img.data == NULL)
+ return 0;
+ _XInitImageFuncPtrs(&img);
+diff --git a/src/QuColors.c b/src/QuColors.c
+index 237b8bf..13a63eb 100644
+--- a/src/QuColors.c
++++ b/src/QuColors.c
+@@ -37,9 +37,7 @@ _XQueryColors(
+ int ncolors)
+ {
+ register int i;
+- xrgb *color;
+ xQueryColorsReply rep;
+- long nbytes;
+ register xQueryColorsReq *req;
+
+ GetReq(QueryColors, req);
+@@ -52,8 +50,9 @@ _XQueryColors(
+ /* XXX this isn't very efficient */
+
+ if (_XReply(dpy, (xReply *) &rep, 0, xFalse) != 0) {
+- if ((color = (xrgb *)
+- Xmalloc((unsigned) (nbytes = (long) ncolors * SIZEOF(xrgb))))) {
++ unsigned long nbytes = (long) ncolors * SIZEOF(xrgb);
++ xrgb *color = Xmalloc(nbytes);
++ if (color != NULL) {
+
+ _XRead(dpy, (char *) color, nbytes);
+
+@@ -67,7 +66,8 @@ _XQueryColors(
+ }
+ Xfree((char *)color);
+ }
+- else _XEatData(dpy, (unsigned long) nbytes);
++ else
++ _XEatDataWords(dpy, rep.length);
+ }
+ }
+
+diff --git a/src/QuTree.c b/src/QuTree.c
+index 3cea282..8da2ae2 100644
+--- a/src/QuTree.c
++++ b/src/QuTree.c
+@@ -37,7 +37,7 @@ Status XQueryTree (
+ Window **children, /* RETURN */
+ unsigned int *nchildren) /* RETURN */
+ {
+- long nbytes;
++ unsigned long nbytes;
+ xQueryTreeReply rep;
+ register xResourceReq *req;
+
+@@ -52,14 +52,14 @@ Status XQueryTree (
+ *children = (Window *) NULL;
+ if (rep.nChildren != 0) {
+ nbytes = rep.nChildren * sizeof(Window);
+- *children = (Window *) Xmalloc((unsigned) nbytes);
+- nbytes = rep.nChildren << 2;
++ *children = Xmalloc(nbytes);
+ if (! *children) {
+- _XEatData(dpy, (unsigned long) nbytes);
++ _XEatDataWords(dpy, rep.length);
+ UnlockDisplay(dpy);
+ SyncHandle();
+ return (0);
+ }
++ nbytes = rep.nChildren << 2;
+ _XRead32 (dpy, (long *) *children, nbytes);
+ }
+ *parent = rep.parent;
+diff --git a/src/Quarks.c b/src/Quarks.c
+index 7a704b1..9ee787b 100644
+--- a/src/Quarks.c
++++ b/src/Quarks.c
+@@ -190,15 +190,14 @@ ExpandQuarkTable(void)
+ newmask = (oldmask << 1) + 1;
+ else {
+ if (!stringTable) {
+- stringTable = (XrmString **)Xmalloc(sizeof(XrmString *) *
+- CHUNKPER);
++ stringTable = Xmalloc(sizeof(XrmString *) * CHUNKPER);
+ if (!stringTable)
+ return False;
+ stringTable[0] = (XrmString *)NULL;
+ }
+ #ifdef PERMQ
+ if (!permTable)
+- permTable = (Bits **)Xmalloc(sizeof(Bits *) * CHUNKPER);
++ permTable = Xmalloc(sizeof(Bits *) * CHUNKPER);
+ if (!permTable)
+ return False;
+ #endif
+@@ -293,13 +292,13 @@ nomatch: if (!rehash)
+ q = nextQuark;
+ if (!(q & QUANTUMMASK)) {
+ if (!(q & CHUNKMASK)) {
+- if (!(new = Xrealloc((char *)stringTable,
++ if (!(new = Xrealloc(stringTable,
+ sizeof(XrmString *) *
+ ((q >> QUANTUMSHIFT) + CHUNKPER))))
+ goto fail;
+ stringTable = (XrmString **)new;
+ #ifdef PERMQ
+- if (!(new = Xrealloc((char *)permTable,
++ if (!(new = Xrealloc(permTable,
+ sizeof(Bits *) *
+ ((q >> QUANTUMSHIFT) + CHUNKPER))))
+ goto fail;
+diff --git a/src/RdBitF.c b/src/RdBitF.c
+index ab7d800..727204f 100644
+--- a/src/RdBitF.c
++++ b/src/RdBitF.c
+@@ -191,7 +191,7 @@ XReadBitmapFileData (
+ bytes_per_line = (ww+7)/8 + padding;
+
+ size = bytes_per_line * hh;
+- bits = (unsigned char *) Xmalloc ((unsigned int) size);
++ bits = Xmalloc (size);
+ if (!bits)
+ RETURN (BitmapNoMemory);
+
+diff --git a/src/Region.c b/src/Region.c
+index 41047b2..d3d431a 100644
+--- a/src/Region.c
++++ b/src/Region.c
+@@ -139,9 +139,9 @@ XCreateRegion(void)
+ {
+ Region temp;
+
+- if (! (temp = ( Region )Xmalloc( (unsigned) sizeof( REGION ))))
++ if (! (temp = Xmalloc(sizeof( REGION ))))
+ return (Region) NULL;
+- if (! (temp->rects = ( BOX * )Xmalloc( (unsigned) sizeof( BOX )))) {
++ if (! (temp->rects = Xmalloc(sizeof( BOX )))) {
+ Xfree((char *) temp);
+ return (Region) NULL;
+ }
+@@ -521,9 +521,9 @@ miRegionCopy(
+ {
+ BOX *prevRects = dstrgn->rects;
+
+- if (! (dstrgn->rects = (BOX *)
+- Xrealloc((char *) dstrgn->rects,
+- (unsigned) rgn->numRects * (sizeof(BOX))))) {
++ dstrgn->rects = Xrealloc(dstrgn->rects,
++ rgn->numRects * (sizeof(BOX)));
++ if (! dstrgn->rects) {
+ Xfree(prevRects);
+ return;
+ }
+@@ -788,8 +788,7 @@ miRegionOp(
+ */
+ newReg->size = max(reg1->numRects,reg2->numRects) * 2;
+
+- if (! (newReg->rects = (BoxPtr)
+- Xmalloc ((unsigned) (sizeof(BoxRec) * newReg->size)))) {
++ if (! (newReg->rects = Xmalloc (sizeof(BoxRec) * newReg->size))) {
+ newReg->size = 0;
+ return;
+ }
+@@ -980,8 +979,8 @@ miRegionOp(
+ {
+ BoxPtr prev_rects = newReg->rects;
+ newReg->size = newReg->numRects;
+- newReg->rects = (BoxPtr) Xrealloc ((char *) newReg->rects,
+- (unsigned) (sizeof(BoxRec) * newReg->size));
++ newReg->rects = Xrealloc (newReg->rects,
++ sizeof(BoxRec) * newReg->size);
+ if (! newReg->rects)
+ newReg->rects = prev_rects;
+ }
+@@ -993,7 +992,7 @@ miRegionOp(
+ */
+ newReg->size = 1;
+ Xfree((char *) newReg->rects);
+- newReg->rects = (BoxPtr) Xmalloc(sizeof(BoxRec));
++ newReg->rects = Xmalloc(sizeof(BoxRec));
+ }
+ }
+ Xfree ((char *) oldRects);
+diff --git a/src/RegstFlt.c b/src/RegstFlt.c
+index 9a560e7..5a1faa7 100644
+--- a/src/RegstFlt.c
++++ b/src/RegstFlt.c
+@@ -85,7 +85,7 @@ _XRegisterFilterByMask(
+ {
+ XFilterEventRec *rec;
+
+- rec = (XFilterEventList)Xmalloc(sizeof(XFilterEventRec));
++ rec = Xmalloc(sizeof(XFilterEventRec));
+ if (!rec)
+ return;
+ rec->window = window;
+@@ -117,7 +117,7 @@ _XRegisterFilterByType(
+ {
+ XFilterEventRec *rec;
+
+- rec = (XFilterEventList)Xmalloc(sizeof(XFilterEventRec));
++ rec = Xmalloc(sizeof(XFilterEventRec));
+ if (!rec)
+ return;
+ rec->window = window;
+diff --git a/src/RestackWs.c b/src/RestackWs.c
+index 1dba3c8..52391ec 100644
+--- a/src/RestackWs.c
++++ b/src/RestackWs.c
+@@ -36,9 +36,6 @@ XRestackWindows (
+ int n)
+ {
+ int i = 0;
+-#ifdef MUSTCOPY
+- unsigned long val = Below; /* needed for macro below */
+-#endif
+
+ LockDisplay(dpy);
+ while (windows++, ++i < n) {
+@@ -47,18 +44,12 @@ XRestackWindows (
+ GetReqExtra (ConfigureWindow, 8, req);
+ req->window = *windows;
+ req->mask = CWSibling | CWStackMode;
+-#ifdef MUSTCOPY
+- dpy->bufptr -= 8;
+- Data32 (dpy, (long *)(windows-1), 4);
+- Data32 (dpy, (long *)&val, 4);
+-#else
+ {
+ register CARD32 *values = (CARD32 *)
+ NEXTPTR(req,xConfigureWindowReq);
+ *values++ = *(windows-1);
+ *values = Below;
+ }
+-#endif /* MUSTCOPY */
+ }
+ UnlockDisplay(dpy);
+ SyncHandle();
+diff --git a/src/SetFPath.c b/src/SetFPath.c
+index 89955c2..b1afd82 100644
+--- a/src/SetFPath.c
++++ b/src/SetFPath.c
+@@ -52,7 +52,7 @@ XSetFontPath (
+ }
+ nbytes = (n + 3) & ~3;
+ req->length += nbytes >> 2;
+- if ((p = (char *) Xmalloc ((unsigned) nbytes))) {
++ if ((p = Xmalloc (nbytes))) {
+ /*
+ * pack into counted strings.
+ */
+diff --git a/src/SetHints.c b/src/SetHints.c
+index 0c33f59..a35ad88 100644
+--- a/src/SetHints.c
++++ b/src/SetHints.c
+@@ -184,7 +184,7 @@ XSetIconSizes (
+ #define size_of_the_real_thing sizeof /* avoid grepping screwups */
+ unsigned nbytes = count * size_of_the_real_thing(xPropIconSize);
+ #undef size_of_the_real_thing
+- if ((prop = pp = (xPropIconSize *) Xmalloc (nbytes))) {
++ if ((prop = pp = Xmalloc (nbytes))) {
+ for (i = 0; i < count; i++) {
+ pp->minWidth = list->min_width;
+ pp->minHeight = list->min_height;
+@@ -216,7 +216,7 @@ XSetCommand (
+ for (i = 0, nbytes = 0; i < argc; i++) {
+ nbytes += safestrlen(argv[i]) + 1;
+ }
+- if ((bp = buf = Xmalloc((unsigned) nbytes))) {
++ if ((bp = buf = Xmalloc(nbytes))) {
+ /* copy arguments into single buffer */
+ for (i = 0; i < argc; i++) {
+ if (argv[i]) {
+@@ -297,7 +297,7 @@ XSetClassHint(
+
+ len_nm = safestrlen(classhint->res_name);
+ len_cl = safestrlen(classhint->res_class);
+- if ((class_string = s = Xmalloc((unsigned) (len_nm + len_cl + 2)))) {
++ if ((class_string = s = Xmalloc(len_nm + len_cl + 2))) {
+ if (len_nm) {
+ strcpy(s, classhint->res_name);
+ s += len_nm + 1;
+diff --git a/src/StColor.c b/src/StColor.c
+index 19f2a4b..d5a217f 100644
+--- a/src/StColor.c
++++ b/src/StColor.c
+@@ -37,21 +37,13 @@ XStoreColor(
+ {
+ xColorItem *citem;
+ register xStoreColorsReq *req;
+-#ifdef MUSTCOPY
+- xColorItem citemdata;
+- long len = SIZEOF(xColorItem);
+-
+- citem = &citemdata;
+-#endif /* MUSTCOPY */
+
+ LockDisplay(dpy);
+ GetReqExtra(StoreColors, SIZEOF(xColorItem), req); /* assume size is 4*n */
+
+ req->cmap = cmap;
+
+-#ifndef MUSTCOPY
+ citem = (xColorItem *) NEXTPTR(req,xStoreColorsReq);
+-#endif /* not MUSTCOPY */
+
+ citem->pixel = def->pixel;
+ citem->red = def->red;
+@@ -59,10 +51,6 @@ XStoreColor(
+ citem->blue = def->blue;
+ citem->flags = def->flags; /* do_red, do_green, do_blue */
+
+-#ifdef MUSTCOPY
+- dpy->bufptr -= SIZEOF(xColorItem); /* adjust for GetReqExtra */
+- Data (dpy, (char *) citem, len);
+-#endif /* MUSTCOPY */
+
+ UnlockDisplay(dpy);
+ SyncHandle();
+diff --git a/src/StrToText.c b/src/StrToText.c
+index b5327e8..ef927f3 100644
+--- a/src/StrToText.c
++++ b/src/StrToText.c
+@@ -78,7 +78,7 @@ Status XStringListToTextProperty (
+ }
+ }
+ } else {
+- proto.value = (unsigned char *) Xmalloc (1); /* easier for client */
++ proto.value = Xmalloc (1); /* easier for client */
+ if (!proto.value) return False;
+
+ proto.value[0] = '\0';
+diff --git a/src/Text16.c b/src/Text16.c
+index 5a66a2b..008a3f7 100644
+--- a/src/Text16.c
++++ b/src/Text16.c
+@@ -82,18 +82,7 @@ XDrawString16(
+ BufAlloc (xTextElt *, elt, nbytes);
+ elt->delta = 0;
+ elt->len = 254;
+-#if defined(MUSTCOPY) || defined(MUSTCOPY2B)
+- {
+- register int i;
+- register unsigned char *cp;
+- for (i = 0, cp = ((unsigned char *)elt) + 2; i < 254; i++) {
+- *cp++ = CharacterOffset[i].byte1;
+- *cp++ = CharacterOffset[i].byte2;
+- }
+- }
+-#else
+ memcpy (((char *) elt) + 2, (char *)CharacterOffset, 254 * 2);
+-#endif
+ PartialNChars = PartialNChars - 254;
+ CharacterOffset += 254;
+ }
+@@ -104,19 +93,7 @@ XDrawString16(
+ BufAlloc (xTextElt *, elt, nbytes);
+ elt->delta = 0;
+ elt->len = PartialNChars;
+-#if defined(MUSTCOPY) || defined(MUSTCOPY2B)
+- {
+- register int i;
+- register unsigned char *cp;
+- for (i = 0, cp = ((unsigned char *)elt) + 2; i < PartialNChars;
+- i++) {
+- *cp++ = CharacterOffset[i].byte1;
+- *cp++ = CharacterOffset[i].byte2;
+- }
+- }
+-#else
+ memcpy(((char *)elt) + 2, (char *)CharacterOffset, PartialNChars * 2);
+-#endif
+ }
+ }
+
+diff --git a/src/TextToStr.c b/src/TextToStr.c
+index 216391c..36d9f07 100644
+--- a/src/TextToStr.c
++++ b/src/TextToStr.c
+@@ -72,10 +72,10 @@ Status XTextPropertyToStringList (
+ /*
+ * allocate list and duplicate
+ */
+- list = (char **) Xmalloc (nelements * sizeof (char *));
++ list = Xmalloc (nelements * sizeof (char *));
+ if (!list) return False;
+
+- start = (char *) Xmalloc ((datalen + 1) * sizeof (char)); /* for <NUL> */
++ start = Xmalloc ((datalen + 1) * sizeof (char)); /* for <NUL> */
+ if (!start) {
+ Xfree ((char *) list);
+ return False;
+diff --git a/src/VisUtil.c b/src/VisUtil.c
+index 3434c01..aa67992 100644
+--- a/src/VisUtil.c
++++ b/src/VisUtil.c
+@@ -75,8 +75,7 @@ XVisualInfo *XGetVisualInfo(
+
+ count = 0;
+ total = 10;
+- if (! (vip_base = vip = (XVisualInfo *)
+- Xmalloc((unsigned) (sizeof(XVisualInfo) * total)))) {
++ if (! (vip_base = vip = Xmalloc(sizeof(XVisualInfo) * total))) {
+ UnlockDisplay(dpy);
+ return (XVisualInfo *) NULL;
+ }
+@@ -132,9 +131,8 @@ XVisualInfo *XGetVisualInfo(
+ {
+ XVisualInfo *old_vip_base = vip_base;
+ total += 10;
+- if (! (vip_base = (XVisualInfo *)
+- Xrealloc((char *) vip_base,
+- (unsigned) (sizeof(XVisualInfo) * total)))) {
++ if (! (vip_base = Xrealloc(vip_base,
++ sizeof(XVisualInfo) * total))) {
+ Xfree((char *) old_vip_base);
+ UnlockDisplay(dpy);
+ return (XVisualInfo *) NULL;
+diff --git a/src/WrBitF.c b/src/WrBitF.c
+index 1ec6280..75a93a7 100644
+--- a/src/WrBitF.c
++++ b/src/WrBitF.c
+@@ -53,7 +53,7 @@ static char *Format_Image(
+ bytes_per_line = (width+7)/8;
+ *resultsize = bytes_per_line * height; /* Calculate size of data */
+
+- data = (char *) Xmalloc( *resultsize ); /* Get space for data */
++ data = Xmalloc( *resultsize ); /* Get space for data */
+ if (!data)
+ return(ERR_RETURN);
+
+diff --git a/src/Xintatom.h b/src/Xintatom.h
+index 82dba36..516a72b 100644
+--- a/src/Xintatom.h
++++ b/src/Xintatom.h
+@@ -2,6 +2,7 @@
+ #ifndef _XINTATOM_H_
+ #define _XINTATOM_H_ 1
+
++#include <X11/Xlib.h>
+ #include <X11/Xfuncproto.h>
+
+ /* IntAtom.c */
+diff --git a/src/Xintconn.h b/src/Xintconn.h
+index db59061..cd9aee3 100644
+--- a/src/Xintconn.h
++++ b/src/Xintconn.h
+@@ -3,6 +3,7 @@
+ #define _XINTCONN_H_ 1
+
+ #include <X11/Xfuncproto.h>
++#include <X11/Xlib.h>
+
+ _XFUNCPROTOBEGIN
+
+diff --git a/src/XlibAsync.c b/src/XlibAsync.c
+index b17135c..eb2b819 100644
+--- a/src/XlibAsync.c
++++ b/src/XlibAsync.c
+@@ -100,11 +100,6 @@ _XGetAsyncReply(
+ _XRead(dpy, replbuf + len, size - len);
+ buf = replbuf;
+ len = size;
+-#ifdef MUSTCOPY
+- } else {
+- memcpy(replbuf, buf, size);
+- buf = replbuf;
+-#endif
+ }
+
+ if (discard && rep->generic.length > extra &&
+diff --git a/src/XlibInt.c b/src/XlibInt.c
+index 2827c10..ee90510 100644
+--- a/src/XlibInt.c
++++ b/src/XlibInt.c
+@@ -152,7 +152,7 @@ Bool _XPollfdCacheInit(
+ #ifdef USE_POLL
+ struct pollfd *pfp;
+
+- pfp = (struct pollfd *)Xmalloc(POLLFD_CACHE_SIZE * sizeof(struct pollfd));
++ pfp = Xmalloc(POLLFD_CACHE_SIZE * sizeof(struct pollfd));
+ if (!pfp)
+ return False;
+ pfp[0].fd = dpy->fd;
+@@ -492,10 +492,10 @@ _XRegisterInternalConnection(
+ struct _XConnWatchInfo *watchers;
+ XPointer *wd;
+
+- new_conni = (struct _XConnectionInfo*)Xmalloc(sizeof(struct _XConnectionInfo));
++ new_conni = Xmalloc(sizeof(struct _XConnectionInfo));
+ if (!new_conni)
+ return 0;
+- new_conni->watch_data = (XPointer *)Xmalloc(dpy->watcher_count * sizeof(XPointer));
++ new_conni->watch_data = Xmalloc(dpy->watcher_count * sizeof(XPointer));
+ if (!new_conni->watch_data) {
+ Xfree(new_conni);
+ return 0;
+@@ -582,7 +582,7 @@ XInternalConnectionNumbers(
+ count = 0;
+ for (info_list=dpy->im_fd_info; info_list; info_list=info_list->next)
+ count++;
+- fd_list = (int*) Xmalloc (count * sizeof(int));
++ fd_list = Xmalloc (count * sizeof(int));
+ if (!fd_list) {
+ UnlockDisplay(dpy);
+ return 0;
+@@ -655,9 +655,8 @@ XAddConnectionWatch(
+
+ /* allocate new watch data */
+ for (info_list=dpy->im_fd_info; info_list; info_list=info_list->next) {
+- wd_array = (XPointer *)Xrealloc((char *)info_list->watch_data,
+- (dpy->watcher_count + 1) *
+- sizeof(XPointer));
++ wd_array = Xrealloc(info_list->watch_data,
++ (dpy->watcher_count + 1) * sizeof(XPointer));
+ if (!wd_array) {
+ UnlockDisplay(dpy);
+ return 0;
+@@ -666,7 +665,7 @@ XAddConnectionWatch(
+ wd_array[dpy->watcher_count] = NULL; /* for cleanliness */
+ }
+
+- new_watcher = (struct _XConnWatchInfo*)Xmalloc(sizeof(struct _XConnWatchInfo));
++ new_watcher = Xmalloc(sizeof(struct _XConnWatchInfo));
+ if (!new_watcher) {
+ UnlockDisplay(dpy);
+ return 0;
+@@ -874,8 +873,7 @@ void _XEnq(
+ /* If dpy->qfree is non-NULL do this, else malloc a new one. */
+ dpy->qfree = qelt->next;
+ }
+- else if ((qelt =
+- (_XQEvent *) Xmalloc((unsigned)sizeof(_XQEvent))) == NULL) {
++ else if ((qelt = Xmalloc(sizeof(_XQEvent))) == NULL) {
+ /* Malloc call failed! */
+ ESET(ENOMEM);
+ _XIOError(dpy);
+@@ -1636,7 +1634,7 @@ char *_XAllocScratch(
+ {
+ if (nbytes > dpy->scratch_length) {
+ if (dpy->scratch_buffer) Xfree (dpy->scratch_buffer);
+- if ((dpy->scratch_buffer = Xmalloc((unsigned) nbytes)))
++ if ((dpy->scratch_buffer = Xmalloc(nbytes)))
+ dpy->scratch_length = nbytes;
+ else dpy->scratch_length = 0;
+ }
+diff --git a/src/Xprivate.h b/src/Xprivate.h
+index 006b170..6bfe70b 100644
+--- a/src/Xprivate.h
++++ b/src/Xprivate.h
+@@ -8,6 +8,8 @@
+ #ifndef XPRIVATE_H
+ #define XPRIVATE_H
+
++#include <X11/Xlib.h>
++
+ extern _X_HIDDEN void _XIDHandler(Display *dpy);
+ extern _X_HIDDEN void _XSeqSyncFunction(Display *dpy);
+ extern _X_HIDDEN void _XSetPrivSyncFunction(Display *dpy);
+diff --git a/src/Xresinternal.h b/src/Xresinternal.h
+index c2f355f..b5cc7ff 100644
+--- a/src/Xresinternal.h
++++ b/src/Xresinternal.h
+@@ -2,6 +2,8 @@
+ #ifndef _XRESINTERNAL_H_
+ #define _XRESINTERNAL_H_
+
++#include <X11/Xlib.h>
++#include <X11/Xresource.h>
+ #include <inttypes.h>
+
+ /* type defines */
+diff --git a/src/Xrm.c b/src/Xrm.c
+index d6899d9..d8272ee 100644
+--- a/src/Xrm.c
++++ b/src/Xrm.c
+@@ -62,6 +62,7 @@ from The Open Group.
+ #endif
+ #include <X11/Xos.h>
+ #include <sys/stat.h>
++#include <limits.h>
+ #include "Xresinternal.h"
+ #include "Xresource.h"
+
+@@ -494,7 +495,7 @@ static XrmDatabase NewDatabase(void)
+ {
+ register XrmDatabase db;
+
+- db = (XrmDatabase) Xmalloc(sizeof(XrmHashBucketRec));
++ db = Xmalloc(sizeof(XrmHashBucketRec));
+ if (db) {
+ _XCreateMutex(&db->linfo);
+ db->table = (NTable)NULL;
+@@ -827,7 +828,7 @@ static void PutEntry(
+ NTable *nprev, *firstpprev;
+
+ #define NEWTABLE(q,i) \
+- table = (NTable)Xmalloc(sizeof(LTableRec)); \
++ table = Xmalloc(sizeof(LTableRec)); \
+ if (!table) \
+ return; \
+ table->name = q; \
+@@ -840,7 +841,7 @@ static void PutEntry(
+ nprev = NodeBuckets(table); \
+ } else { \
+ table->leaf = 1; \
+- if (!(nprev = (NTable *)Xmalloc(sizeof(VEntry *)))) {\
++ if (!(nprev = Xmalloc(sizeof(VEntry *)))) {\
+ Xfree(table); \
+ return; \
+ } \
+@@ -954,9 +955,8 @@ static void PutEntry(
+ prev = nprev;
+ }
+ /* now allocate the value entry */
+- entry = (VEntry)Xmalloc(((type == XrmQString) ?
+- sizeof(VEntryRec) : sizeof(DEntryRec)) +
+- value->size);
++ entry = Xmalloc(((type == XrmQString) ?
++ sizeof(VEntryRec) : sizeof(DEntryRec)) + value->size);
+ if (!entry)
+ return;
+ entry->name = q = *quarks;
+@@ -986,13 +986,12 @@ static void PutEntry(
+ if (resourceQuarks) {
+ unsigned char *prevQuarks = resourceQuarks;
+
+- resourceQuarks = (unsigned char *)Xrealloc((char *)resourceQuarks,
+- size);
++ resourceQuarks = Xrealloc(resourceQuarks, size);
+ if (!resourceQuarks) {
+ Xfree(prevQuarks);
+ }
+ } else
+- resourceQuarks = (unsigned char *)Xmalloc(size);
++ resourceQuarks = Xmalloc(size);
+ if (resourceQuarks) {
+ bzero((char *)&resourceQuarks[oldsize], size - oldsize);
+ maxResourceQuark = (size << 3) - 1;
+@@ -1087,13 +1086,15 @@ static void GetIncludeFile(
+ XrmDatabase db,
+ _Xconst char *base,
+ _Xconst char *fname,
+- int fnamelen);
++ int fnamelen,
++ int depth);
+
+ static void GetDatabase(
+ XrmDatabase db,
+ _Xconst char *str,
+ _Xconst char *filename,
+- Bool doall)
++ Bool doall,
++ int depth)
+ {
+ char *rhs;
+ char *lhs, lhs_s[DEF_BUFF_SIZE];
+@@ -1135,11 +1136,11 @@ static void GetDatabase(
+
+ str_len = strlen (str);
+ if (DEF_BUFF_SIZE > str_len) lhs = lhs_s;
+- else if ((lhs = (char*) Xmalloc (str_len)) == NULL)
++ else if ((lhs = Xmalloc (str_len)) == NULL)
+ return;
+
+ alloc_chars = DEF_BUFF_SIZE < str_len ? str_len : DEF_BUFF_SIZE;
+- if ((rhs = (char*) Xmalloc (alloc_chars)) == NULL) {
++ if ((rhs = Xmalloc (alloc_chars)) == NULL) {
+ if (lhs != lhs_s) Xfree (lhs);
+ return;
+ }
+@@ -1203,7 +1204,8 @@ static void GetDatabase(
+ } while (c != '"' && !is_EOL(bits));
+ /* must have an ending " */
+ if (c == '"')
+- GetIncludeFile(db, filename, fname, str - len - fname);
++ GetIncludeFile(db, filename, fname, str - len - fname,
++ depth);
+ }
+ }
+ /* spin to next newline */
+@@ -1544,7 +1546,7 @@ XrmPutLineResource(
+ {
+ if (!*pdb) *pdb = NewDatabase();
+ _XLockMutex(&(*pdb)->linfo);
+- GetDatabase(*pdb, line, (char *)NULL, False);
++ GetDatabase(*pdb, line, (char *)NULL, False, 0);
+ _XUnlockMutex(&(*pdb)->linfo);
+ }
+
+@@ -1556,7 +1558,7 @@ XrmGetStringDatabase(
+
+ db = NewDatabase();
+ _XLockMutex(&db->linfo);
+- GetDatabase(db, data, (char *)NULL, True);
++ GetDatabase(db, data, (char *)NULL, True, 0);
+ _XUnlockMutex(&db->linfo);
+ return db;
+ }
+@@ -1594,11 +1596,12 @@ ReadInFile(_Xconst char *filename)
+ */
+ {
+ struct stat status_buffer;
+- if ( (fstat(fd, &status_buffer)) == -1 ) {
++ if ( ((fstat(fd, &status_buffer)) == -1 ) ||
++ (status_buffer.st_size >= INT_MAX) ) {
+ close (fd);
+ return (char *)NULL;
+ } else
+- size = status_buffer.st_size;
++ size = (int) status_buffer.st_size;
+ }
+
+ if (!(filebuf = Xmalloc(size + 1))) { /* leave room for '\0' */
+@@ -1634,7 +1637,8 @@ GetIncludeFile(
+ XrmDatabase db,
+ _Xconst char *base,
+ _Xconst char *fname,
+- int fnamelen)
++ int fnamelen,
++ int depth)
+ {
+ int len;
+ char *str;
+@@ -1642,6 +1646,8 @@ GetIncludeFile(
+
+ if (fnamelen <= 0 || fnamelen >= BUFSIZ)
+ return;
++ if (depth >= MAXDBDEPTH)
++ return;
+ if (*fname != '/' && base && (str = strrchr(base, '/'))) {
+ len = str - base + 1;
+ if (len + fnamelen >= BUFSIZ)
+@@ -1655,7 +1661,7 @@ GetIncludeFile(
+ }
+ if (!(str = ReadInFile(realfname)))
+ return;
+- GetDatabase(db, str, realfname, True);
++ GetDatabase(db, str, realfname, True, depth + 1);
+ Xfree(str);
+ }
+
+@@ -1671,7 +1677,7 @@ XrmGetFileDatabase(
+
+ db = NewDatabase();
+ _XLockMutex(&db->linfo);
+- GetDatabase(db, str, filename, True);
++ GetDatabase(db, str, filename, True, 0);
+ _XUnlockMutex(&db->linfo);
+ Xfree(str);
+ return db;
+@@ -1695,7 +1701,7 @@ XrmCombineFileDatabase(
+ } else
+ db = NewDatabase();
+ _XLockMutex(&db->linfo);
+- GetDatabase(db, str, filename, True);
++ GetDatabase(db, str, filename, True, 0);
+ _XUnlockMutex(&db->linfo);
+ Xfree(str);
+ if (!override)
+diff --git a/src/locking.c b/src/locking.c
+index b3dfb3b..7c09c44 100644
+--- a/src/locking.c
++++ b/src/locking.c
+@@ -82,7 +82,7 @@ _Xthread_waiter(void)
+ struct _xthread_waiter *me;
+
+ if (!(me = TlsGetValue(_X_TlsIndex))) {
+- me = (struct _xthread_waiter *)xmalloc(sizeof(struct _xthread_waiter));
++ me = xmalloc(sizeof(struct _xthread_waiter));
+ me->sem = CreateSemaphore(NULL, 0, 1, NULL);
+ me->next = NULL;
+ TlsSetValue(_X_TlsIndex, me);
+@@ -249,7 +249,7 @@ static struct _XCVList *_XCreateCVL(
+ dpy->lock->free_cvls = cvl->next;
+ dpy->lock->num_free_cvls--;
+ } else {
+- cvl = (struct _XCVList *)Xmalloc(sizeof(struct _XCVList));
++ cvl = Xmalloc(sizeof(struct _XCVList));
+ if (!cvl)
+ return NULL;
+ cvl->cv = xcondition_malloc();
+@@ -512,10 +512,10 @@ void _XUserUnlockDisplay(
+ static int _XInitDisplayLock(
+ Display *dpy)
+ {
+- dpy->lock_fns = (struct _XLockPtrs*)Xmalloc(sizeof(struct _XLockPtrs));
++ dpy->lock_fns = Xmalloc(sizeof(struct _XLockPtrs));
+ if (dpy->lock_fns == NULL)
+ return -1;
+- dpy->lock = (struct _XLockInfo *)Xmalloc(sizeof(struct _XLockInfo));
++ dpy->lock = Xmalloc(sizeof(struct _XLockInfo));
+ if (dpy->lock == NULL) {
+ _XFreeDisplayLock(dpy);
+ return -1;
+diff --git a/src/locking.h b/src/locking.h
+index 96019fc..5251a60 100644
+--- a/src/locking.h
++++ b/src/locking.h
+@@ -36,6 +36,8 @@ in this Software without prior written authorization from The Open Group.
+
+ #define xmalloc(s) Xmalloc(s)
+ #define xfree(s) Xfree(s)
++#include <X11/Xlib.h>
++#include <X11/Xlibint.h>
+ #include <X11/Xthreads.h>
+
+ struct _XCVList {
+diff --git a/src/pathmax.h b/src/pathmax.h
+new file mode 100644
+index 0000000..3aa3d50
+--- /dev/null
++++ b/src/pathmax.h
+@@ -0,0 +1,81 @@
++
++/***********************************************************
++
++Copyright 1987, 1988, 1998 The Open Group
++
++Permission to use, copy, modify, distribute, and sell this software and its
++documentation for any purpose is hereby granted without fee, provided that
++the above copyright notice appear in all copies and that both that
++copyright notice and this permission notice appear in supporting
++documentation.
++
++The above copyright notice and this permission notice shall be included in
++all copies or substantial portions of the Software.
++
++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
++AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
++CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
++
++Except as contained in this notice, the name of The Open Group shall not be
++used in advertising or otherwise to promote the sale, use or other dealings
++in this Software without prior written authorization from The Open Group.
++
++
++Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts.
++
++ All Rights Reserved
++
++Permission to use, copy, modify, and distribute this software and its
++documentation for any purpose and without fee is hereby granted,
++provided that the above copyright notice appear in all copies and that
++both that copyright notice and this permission notice appear in
++supporting documentation, and that the name of Digital not be
++used in advertising or publicity pertaining to distribution of the
++software without specific, written prior permission.
++
++DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
++ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
++DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
++ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
++WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
++ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
++SOFTWARE.
++
++******************************************************************/
++
++/*
++ * Provides a single definition of PATH_MAX instead of replicating this mess
++ * in multiple files
++ */
++
++#ifdef HAVE_CONFIG_H
++#include <config.h>
++#endif
++#include <X11/Xos.h>
++
++#ifndef X_NOT_POSIX
++#ifdef _POSIX_SOURCE
++#include <limits.h>
++#else
++#define _POSIX_SOURCE
++#include <limits.h>
++#undef _POSIX_SOURCE
++#endif
++#endif
++#ifndef PATH_MAX
++#ifdef WIN32
++#define PATH_MAX 512
++#else
++#include <sys/param.h>
++#endif
++#ifndef PATH_MAX
++#ifdef MAXPATHLEN
++#define PATH_MAX MAXPATHLEN
++#else
++#define PATH_MAX 1024
++#endif
++#endif
++#endif
+diff --git a/src/udcInf.c b/src/udcInf.c
+index db7ad10..a692a31 100644
+--- a/src/udcInf.c
++++ b/src/udcInf.c
+@@ -145,12 +145,11 @@ int *num_codeset;
+ if(!_XlcCompareISOLatin1(charset_str,buf)){
+ num_ret += 1;
+ if(num_ret == 1){
+- ret = (int *)Xmalloc(sizeof(int));
++ ret = Xmalloc(sizeof(int));
+ } else {
+ int *prev_ret = ret;
+
+- ret =
+- (int *)Xrealloc(ret,num_ret*sizeof(int));
++ ret = Xrealloc(ret, num_ret * sizeof(int));
+ if (ret == NULL){
+ Xfree(prev_ret);
+ }
+@@ -272,7 +271,7 @@ int *num_gr;
+ sprintf(buf, "fs%d.charset.udc_area", codeset-1);
+ _XlcGetLocaleDataBase(lcd, "XLC_FONTSET", buf, &value, &count);
+ if(count > 0){
+- udc = (_XUDCGlyphRegion *)Xmalloc(count * sizeof(_XUDCGlyphRegion));
++ udc = Xmalloc(count * sizeof(_XUDCGlyphRegion));
+ if(udc == NULL){
+ _xudc_utyerrno = 0x03 ;
+ _xudc_utyerrno |= (0x0b<<8) ;
+@@ -524,7 +523,7 @@ int *num_cr;
+ return(ret);
+ }
+
+- crr = (_XUDCCodeRegion *)Xmalloc(num_gr*sizeof(_XUDCCodeRegion));
++ crr = Xmalloc(num_gr * sizeof(_XUDCCodeRegion));
+ if(crr == NULL){
+ Xfree(gr);
+ _xudc_utyerrno = 0x03 ;
+diff --git a/src/xcb_io.c b/src/xcb_io.c
+index 300ef57..727c6c7 100644
+--- a/src/xcb_io.c
++++ b/src/xcb_io.c
+@@ -19,6 +19,7 @@
+ #include <stdint.h>
+ #include <stdlib.h>
+ #include <string.h>
++#include <limits.h>
+ #ifdef HAVE_SYS_SELECT_H
+ #include <sys/select.h>
+ #endif
+@@ -757,3 +758,19 @@ void _XEatData(Display *dpy, unsigned long n)
+ dpy->xcb->reply_consumed += n;
+ _XFreeReplyData(dpy, False);
+ }
++
++/*
++ * Read and discard "n" 32-bit words of data
++ * Matches the units of the length field in X protocol replies, and provides
++ * a single implementation of overflow checking to avoid having to replicate
++ * those checks in every caller.
++ */
++void _XEatDataWords(Display *dpy, unsigned long n)
++{
++ if (n < ((INT_MAX - dpy->xcb->reply_consumed) >> 2))
++ dpy->xcb->reply_consumed += (n << 2);
++ else
++ /* Overflow would happen, so just eat the rest of the reply */
++ dpy->xcb->reply_consumed = dpy->xcb->reply_length;
++ _XFreeReplyData(dpy, False);
++}
+diff --git a/src/xcms/cmsColNm.c b/src/xcms/cmsColNm.c
+index 8518adf..86b7110 100644
+--- a/src/xcms/cmsColNm.c
++++ b/src/xcms/cmsColNm.c
+@@ -40,6 +40,7 @@
+ #include <sys/stat.h>
+ #include <stdio.h>
+ #include <ctype.h>
++#include <limits.h>
+ #define XK_LATIN1
+ #include <X11/keysymdef.h>
+ #include "Cv.h"
+@@ -542,7 +543,10 @@ stringSectionSize(
+ char *pBuf;
+ char *f1;
+ char *f2;
+- int i;
++ size_t i;
++
++ unsigned int numEntries = 0;
++ unsigned int sectionSize = 0;
+
+ *pNumEntries = 0;
+ *pSectionSize = 0;
+@@ -576,26 +580,37 @@ stringSectionSize(
+ return(XcmsFailure);
+ }
+
+- (*pNumEntries)++;
++ numEntries++;
++ if (numEntries >= INT_MAX)
++ return(XcmsFailure);
+
+- (*pSectionSize) += (i = strlen(f1)) + 1;
++ i = strlen(f1);
++ if (i >= INT_MAX - sectionSize)
++ return(XcmsFailure);
++ sectionSize += i + 1;
+ for (; i; i--, f1++) {
+ /* REMOVE SPACES FROM COUNT */
+ if (isspace(*f1)) {
+- (*pSectionSize)--;
++ sectionSize--;
+ }
+ }
+
+- (*pSectionSize) += (i = strlen(f2)) + 1;
++ i = strlen(f2);
++ if (i >= INT_MAX - sectionSize)
++ return(XcmsFailure);
++ sectionSize += i + 1;
+ for (; i; i--, f2++) {
+ /* REMOVE SPACES FROM COUNT */
+ if (isspace(*f2)) {
+- (*pSectionSize)--;
++ sectionSize--;
+ }
+ }
+
+ }
+
++ *pNumEntries = (int) numEntries;
++ *pSectionSize = (int) sectionSize;
++
+ return(XcmsSuccess);
+ }
+
+diff --git a/src/xkb/XKBExtDev.c b/src/xkb/XKBExtDev.c
+index 353e769..dd383bc 100644
+--- a/src/xkb/XKBExtDev.c
++++ b/src/xkb/XKBExtDev.c
+@@ -181,6 +181,9 @@ int tmp;
+ return tmp;
+ }
+ if (rep->nBtnsWanted>0) {
++ if (((unsigned short) rep->firstBtnWanted + rep->nBtnsWanted)
++ >= devi->num_btns)
++ goto BAILOUT;
+ act= &devi->btn_acts[rep->firstBtnWanted];
+ bzero((char *)act,(rep->nBtnsWanted*sizeof(XkbAction)));
+ }
+@@ -190,6 +193,9 @@ int tmp;
+ goto BAILOUT;
+ if (rep->nBtnsRtrn>0) {
+ int size;
++ if (((unsigned short) rep->firstBtnRtrn + rep->nBtnsRtrn)
++ >= devi->num_btns)
++ goto BAILOUT;
+ act= &devi->btn_acts[rep->firstBtnRtrn];
+ size= rep->nBtnsRtrn*SIZEOF(xkbActionWireDesc);
+ if (!_XkbCopyFromReadBuffer(&buf,(char *)act,size))
+diff --git a/src/xkb/XKBGeom.c b/src/xkb/XKBGeom.c
+index 7594a3d..7140a72 100644
+--- a/src/xkb/XKBGeom.c
++++ b/src/xkb/XKBGeom.c
+@@ -364,12 +364,16 @@ Status rtrn;
+ }
+ ol->num_points= olWire->nPoints;
+ }
+- if (shapeWire->primaryNdx!=XkbNoShape)
++ if ((shapeWire->primaryNdx!=XkbNoShape) &&
++ (shapeWire->primaryNdx < shapeWire->nOutlines))
+ shape->primary= &shape->outlines[shapeWire->primaryNdx];
+- else shape->primary= NULL;
+- if (shapeWire->approxNdx!=XkbNoShape)
++ else
++ shape->primary= NULL;
++ if ((shapeWire->approxNdx!=XkbNoShape) &&
++ (shapeWire->approxNdx < shapeWire->nOutlines))
+ shape->approx= &shape->outlines[shapeWire->approxNdx];
+- else shape->approx= NULL;
++ else
++ shape->approx= NULL;
+ XkbComputeShapeBounds(shape);
+ }
+ return Success;
+@@ -615,6 +619,9 @@ XkbGeometryPtr geom;
+ if (status==Success)
+ status= _XkbReadGeomKeyAliases(&buf,geom,rep);
+ left= _XkbFreeReadBuffer(&buf);
++ if ((rep->baseColorNdx > geom->num_colors) ||
++ (rep->labelColorNdx > geom->num_colors))
++ status = BadLength;
+ if ((status!=Success) || left || buf.error) {
+ if (status==Success)
+ status= BadLength;
+diff --git a/src/xkb/XKBGetMap.c b/src/xkb/XKBGetMap.c
+index 30fb629..c73e655 100644
+--- a/src/xkb/XKBGetMap.c
++++ b/src/xkb/XKBGetMap.c
+@@ -151,9 +151,12 @@ XkbClientMapPtr map;
+ map= xkb->map;
+ if (map->key_sym_map==NULL) {
+ register int offset;
++ int size = xkb->max_key_code + 1;
+ XkbSymMapPtr oldMap;
+ xkbSymMapWireDesc *newMap;
+- map->key_sym_map= _XkbTypedCalloc((xkb->max_key_code+1),XkbSymMapRec);
++ if (((unsigned short)rep->firstKeySym + rep->nKeySyms) > size)
++ return BadLength;
++ map->key_sym_map= _XkbTypedCalloc(size,XkbSymMapRec);
+ if (map->key_sym_map==NULL)
+ return BadAlloc;
+ if (map->syms==NULL) {
+@@ -209,6 +212,8 @@ XkbClientMapPtr map;
+ KeySym * newSyms;
+ int tmp;
+
++ if (((unsigned short)rep->firstKeySym + rep->nKeySyms) > map->num_syms)
++ return BadLength;
+ oldMap = &map->key_sym_map[rep->firstKeySym];
+ for (i=0;i<(int)rep->nKeySyms;i++,oldMap++) {
+ newMap= (xkbSymMapWireDesc *)
+@@ -264,6 +269,10 @@ Status ret = Success;
+ symMap = &info->map->key_sym_map[rep->firstKeyAct];
+ for (i=0;i<(int)rep->nKeyActs;i++,symMap++) {
+ if (numDesc[i]==0) {
++ if ((i + rep->firstKeyAct) > (info->max_key_code + 1)) {
++ ret = BadLength;
++ goto done;
++ }
+ info->server->key_acts[i+rep->firstKeyAct]= 0;
+ }
+ else {
+@@ -296,8 +305,10 @@ register int i;
+ xkbBehaviorWireDesc *wire;
+
+ if ( rep->totalKeyBehaviors>0 ) {
++ int size = xkb->max_key_code + 1;
++ if ( ((int) rep->firstKeyBehavior + rep->nKeyBehaviors) > size)
++ return BadLength;
+ if ( xkb->server->behaviors == NULL ) {
+- int size = xkb->max_key_code+1;
+ xkb->server->behaviors = _XkbTypedCalloc(size,XkbBehavior);
+ if (xkb->server->behaviors==NULL)
+ return BadAlloc;
+@@ -309,7 +320,7 @@ xkbBehaviorWireDesc *wire;
+ for (i=0;i<rep->totalKeyBehaviors;i++) {
+ wire= (xkbBehaviorWireDesc *)_XkbGetReadBufferPtr(buf,
+ SIZEOF(xkbBehaviorWireDesc));
+- if (wire==NULL)
++ if (wire==NULL || wire->key >= size)
+ return BadLength;
+ xkb->server->behaviors[wire->key].type= wire->type;
+ xkb->server->behaviors[wire->key].data= wire->data;
+@@ -351,8 +362,10 @@ register int i;
+ unsigned char *wire;
+
+ if ( rep->totalKeyExplicit>0 ) {
++ int size = xkb->max_key_code + 1;
++ if ( ((int) rep->firstKeyExplicit + rep->nKeyExplicit) > size)
++ return BadLength;
+ if ( xkb->server->explicit == NULL ) {
+- int size = xkb->max_key_code+1;
+ xkb->server->explicit = _XkbTypedCalloc(size,unsigned char);
+ if (xkb->server->explicit==NULL)
+ return BadAlloc;
+@@ -366,6 +379,8 @@ unsigned char *wire;
+ if (!wire)
+ return BadLength;
+ for (i=0;i<rep->totalKeyExplicit;i++,wire+=2) {
++ if (wire[0] > xkb->max_key_code || wire[1] > xkb->max_key_code)
++ return BadLength;
+ xkb->server->explicit[wire[0]]= wire[1];
+ }
+ }
+@@ -379,6 +394,9 @@ register int i;
+ unsigned char *wire;
+
+ if ( rep->totalModMapKeys>0 ) {
++ if ( ((int)rep->firstModMapKey + rep->nModMapKeys) >
++ (xkb->max_key_code + 1))
++ return BadLength;
+ if ((xkb->map->modmap==NULL)&&
+ (XkbAllocClientMap(xkb,XkbModifierMapMask,0)!=Success)) {
+ return BadAlloc;
+@@ -391,6 +409,8 @@ unsigned char *wire;
+ if (!wire)
+ return BadLength;
+ for (i=0;i<rep->totalModMapKeys;i++,wire+=2) {
++ if (wire[0] > xkb->max_key_code || wire[1] > xkb->max_key_code)
++ return BadLength;
+ xkb->map->modmap[wire[0]]= wire[1];
+ }
+ }
+@@ -405,6 +425,9 @@ xkbVModMapWireDesc * wire;
+ XkbServerMapPtr srv;
+
+ if ( rep->totalVModMapKeys>0 ) {
++ if (((int) rep->firstVModMapKey + rep->nVModMapKeys)
++ > xkb->max_key_code + 1)
++ return BadLength;
+ if (((xkb->server==NULL)||(xkb->server->vmodmap==NULL))&&
+ (XkbAllocServerMap(xkb,XkbVirtualModMapMask,0)!=Success)) {
+ return BadAlloc;
+@@ -461,6 +484,8 @@ unsigned mask;
+
+ if ( xkb->device_spec == XkbUseCoreKbd )
+ xkb->device_spec= rep->deviceID;
++ if ( rep->maxKeyCode < rep->minKeyCode )
++ return BadImplementation;
+ xkb->min_key_code = rep->minKeyCode;
+ xkb->max_key_code = rep->maxKeyCode;
+
+diff --git a/src/xkb/XKBNames.c b/src/xkb/XKBNames.c
+index cf2382c..6df7406 100644
+--- a/src/xkb/XKBNames.c
++++ b/src/xkb/XKBNames.c
+@@ -180,6 +180,8 @@ _XkbReadGetNamesReply( Display * dpy,
+ nKeys= xkb->max_key_code+1;
+ names->keys= _XkbTypedCalloc(nKeys,XkbKeyNameRec);
+ }
++ if ( ((int)rep->firstKey + rep->nKeys) > xkb->max_key_code + 1)
++ goto BAILOUT;
+ if (names->keys!=NULL) {
+ if (!_XkbCopyFromReadBuffer(&buf,
+ (char *)&names->keys[rep->firstKey],
+diff --git a/src/xlibi18n/lcFile.c b/src/xlibi18n/lcFile.c
+index 2c06fa2..61a14e7 100644
+--- a/src/xlibi18n/lcFile.c
++++ b/src/xlibi18n/lcFile.c
+@@ -54,29 +54,7 @@
+
+ #define XLC_BUFSIZE 256
+
+-#ifndef X_NOT_POSIX
+-#ifdef _POSIX_SOURCE
+-#include <limits.h>
+-#else
+-#define _POSIX_SOURCE
+-#include <limits.h>
+-#undef _POSIX_SOURCE
+-#endif
+-#endif
+-#ifndef PATH_MAX
+-#ifdef WIN32
+-#define PATH_MAX 512
+-#else
+-#include <sys/param.h>
+-#endif
+-#ifndef PATH_MAX
+-#ifdef MAXPATHLEN
+-#define PATH_MAX MAXPATHLEN
+-#else
+-#define PATH_MAX 1024
+-#endif
+-#endif
+-#endif
++#include "pathmax.h"
+
+ #define NUM_LOCALEDIR 64
+