16673783 problem in X11/LIBRARIES s12_22
authorAlan Coopersmith <Alan.Coopersmith@Oracle.COM>
Wed, 08 May 2013 18:06:35 -0700
changeset 1377 74e8a5844513
parent 1376 d4184aec09c6
child 1378 baafc0f40acc
16673783 problem in X11/LIBRARIES 16674478 problem in X11/LIBRARIES
open-src/driver/xf86-video-openchrome/CVE-2013-1994.patch
open-src/driver/xf86-video-openchrome/Makefile
open-src/lib/libFS/CVE-2013-1996.patch
open-src/lib/libFS/Makefile
open-src/lib/libX11/CVE-2013-1981.patch
open-src/lib/libX11/CVE-2013-1997.patch
open-src/lib/libX11/CVE-2013-2004.patch
open-src/lib/libX11/Makefile
open-src/lib/libX11/XEatDataWords.patch
open-src/lib/libX11/alloc-cleanup.patch
open-src/lib/libX11/mapfile-vers
open-src/lib/libX11/upstream-cleanup.patch
open-src/lib/libXcursor/CVE-2013-2003.patch
open-src/lib/libXcursor/Makefile
open-src/lib/libXext/CVE-2013-1982.patch
open-src/lib/libXext/Makefile
open-src/lib/libXext/sun-src/src/TransOvl.c
open-src/lib/libXext/sun-src/src/XPanoramiX.c
open-src/lib/libXfixes/CVE-2013-1983.patch
open-src/lib/libXfixes/Makefile
open-src/lib/libXi/CVE-2013-19XX.patch
open-src/lib/libXi/Makefile
open-src/lib/libXinerama/CVE-2013-1985.patch
open-src/lib/libXinerama/Makefile
open-src/lib/libXp/CVE-2013-2062.patch
open-src/lib/libXp/Makefile
open-src/lib/libXrandr/CVE-2013-1986.patch
open-src/lib/libXrandr/Makefile
open-src/lib/libXrender/CVE-2013-1987.patch
open-src/lib/libXrender/Makefile
open-src/lib/libXres/CVE-2013-1988.patch
open-src/lib/libXres/Makefile
open-src/lib/libXt/CVE-2013-2002.patch
open-src/lib/libXt/CVE-2013-2005.patch
open-src/lib/libXt/Makefile
open-src/lib/libXtst/CVE-2013-2063.patch
open-src/lib/libXtst/Makefile
open-src/lib/libXv/CVE-2013-1989.patch
open-src/lib/libXv/Makefile
open-src/lib/libXvMC/CVE-2013-1990.patch
open-src/lib/libXvMC/Makefile
open-src/lib/libXxf86vm/CVE-2013-2001.patch
open-src/lib/libXxf86vm/Makefile
open-src/lib/libXxf86vm/upstream-error-fixes.patch
open-src/lib/libdmx/CVE-2013-1992.patch
open-src/lib/libdmx/Makefile
open-src/lib/libxcb/CVE-2013-2064.patch
open-src/lib/libxcb/Makefile
open-src/lib/mesa/CVE-2013-1993.patch
open-src/lib/mesa/Makefile
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/driver/xf86-video-openchrome/CVE-2013-1994.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,87 @@
+From a886e8bcfe8ec9d1843bcb85fdb76176dc0f2a0c Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 20:49:43 -0700
+Subject: [PATCH:xf86-video-openchrome 1/2] integer overflow in
+ uniDRIOpenConnection() in
+ libchromeXvMC* [CVE-2013-1994
+ 1/2]
+
+busIdStringLength is a CARD32 and needs to be bounds checked before adding
+one to it to come up with the total size to allocate, to avoid integer
+overflow leading to underallocation and writing data from the network past
+the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/xvmc/xf86dri.c |    7 ++++++-
+ 1 file changed, 6 insertions(+), 1 deletion(-)
+
+diff --git a/src/xvmc/xf86dri.c b/src/xvmc/xf86dri.c
+index 1feb232..fba7583 100644
+--- a/src/xvmc/xf86dri.c
++++ b/src/xvmc/xf86dri.c
+@@ -42,6 +42,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ #include <X11/extensions/Xext.h>
+ #include <X11/extensions/extutil.h>
+ #include "xf86dristr.h"
++#include <limits.h>
+ 
+ static XExtensionInfo _xf86dri_info_data;
+ static XExtensionInfo *xf86dri_info = &_xf86dri_info_data;
+@@ -203,7 +204,11 @@ uniDRIOpenConnection(dpy, screen, hSAREA, busIdString)
+     }
+ #endif
+     if (rep.length) {
+-	if (!(*busIdString = (char *)Xcalloc(rep.busIdStringLength + 1, 1))) {
++	if (rep.busIdStringLength < INT_MAX)
++	    *busIdString = Xcalloc(rep.busIdStringLength + 1, 1);
++	else
++	    *busIdString = NULL;
++	if (*busIdString == NULL) {
+ 	    _XEatData(dpy, ((rep.busIdStringLength + 3) & ~3));
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+-- 
+1.7.9.2
+
+From 70fdbc0eeb99273d282c62d45f29b5f044bec08e Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 20:57:07 -0700
+Subject: [PATCH:xf86-video-openchrome 2/2] integer overflow in
+ uniDRIGetClientDriverName() in
+ libchromeXvMC* [CVE-2013-1994
+ 2/2]
+
+clientDriverNameLength is a CARD32 and needs to be bounds checked before
+adding one to it to come up with the total size to allocate, to avoid
+integer overflow leading to underallocation and writing data from the
+network past the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/xvmc/xf86dri.c |    7 +++++--
+ 1 file changed, 5 insertions(+), 2 deletions(-)
+
+diff --git a/src/xvmc/xf86dri.c b/src/xvmc/xf86dri.c
+index fba7583..c5702ec 100644
+--- a/src/xvmc/xf86dri.c
++++ b/src/xvmc/xf86dri.c
+@@ -314,8 +314,11 @@ uniDRIGetClientDriverName(dpy, screen, ddxDriverMajorVersion,
+     *ddxDriverPatchVersion = rep.ddxDriverPatchVersion;
+ 
+     if (rep.length) {
+-	if (!(*clientDriverName =
+-		(char *)Xcalloc(rep.clientDriverNameLength + 1, 1))) {
++	if (rep.clientDriverNameLength < INT_MAX)
++	    *clientDriverName = Xcalloc(rep.clientDriverNameLength + 1, 1);
++	else
++	    *clientDriverName = NULL;
++	if (*clientDriverName == NULL) {
+ 	    _XEatData(dpy, ((rep.clientDriverNameLength + 3) & ~3));
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+-- 
+1.7.9.2
+
--- a/open-src/driver/xf86-video-openchrome/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/driver/xf86-video-openchrome/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -41,6 +41,7 @@
 
 # Patches to apply to source after unpacking, in order
 SOURCE_PATCHES = manpage-sections.patch,-p1
+SOURCE_PATCHES += CVE-2013-1994.patch,-p1
 
 # Extra rules to run when unpacking upstream source
 CLEAN_LINEFEED_TARGET = $(SOURCE_DIR)/.source.clean.done
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libFS/CVE-2013-1996.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,56 @@
+From 26dc23446c2e7818fdebfb46e101bac4883df07e Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sun, 14 Apr 2013 09:07:32 -0700
+Subject: [PATCH:libFS] Sign extension issue and integer overflow in
+ FSOpenServer() [CVE-2013-1996]
+
+>       altlen = (int) *ad++; <-- if char is 0xff, will sign extend to int (0xffffffff == -1)
+>       alts[i].name = (char *) FSmalloc(altlen + 1); <-- -1 + 1 == 0
+> ...
+>       memmove(alts[i].name, ad, altlen); <-- memory corruption
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/FSOpenServ.c |    8 ++++----
+ 1 file changed, 4 insertions(+), 4 deletions(-)
+
+diff --git a/src/FSOpenServ.c b/src/FSOpenServ.c
+index 32f7d25..58c611b 100644
+--- a/src/FSOpenServ.c
++++ b/src/FSOpenServ.c
+@@ -111,10 +111,10 @@ FSOpenServer(const char *server)
+     char       *setup = NULL;
+     fsConnSetupAccept conn;
+     char       *auth_data = NULL;
+-    char       *alt_data = NULL,
++    unsigned char *alt_data = NULL,
+                *ad;
+     AlternateServer *alts = NULL;
+-    int         altlen;
++    unsigned int altlen;
+     char       *vendor_string;
+     unsigned long        setuplength;
+ 
+@@ -158,8 +158,8 @@ FSOpenServer(const char *server)
+ 
+     setuplength = prefix.alternate_len << 2;
+     if (setuplength > (SIZE_MAX>>2)
+-	|| (alt_data = (char *)
+-	 (setup = FSmalloc((unsigned) setuplength))) == NULL) {
++	|| (alt_data = (unsigned char *)
++	 (setup = FSmalloc(setuplength))) == NULL) {
+ 	goto fail;
+     }
+     _FSRead(svr, (char *) alt_data, setuplength);
+@@ -178,8 +178,8 @@ FSOpenServer(const char *server)
+     }
+     for (i = 0; i < prefix.num_alternates; i++) {
+ 	alts[i].subset = (Bool) *ad++;
+-	altlen = (int) *ad++;
+-	alts[i].name = (char *) FSmalloc(altlen + 1);
++	altlen = (unsigned int) *ad++;
++	alts[i].name = FSmalloc(altlen + 1);
+ 	if (!alts[i].name) {
+ 	    while (--i) {
+ 		FSfree((char *) alts[i].name);
--- a/open-src/lib/libFS/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libFS/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # libFS - client library to connect to xfs font servers
 #
-# Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -39,6 +39,7 @@
 # Patches to apply to source after unpacking, in order
 SOURCE_PATCHES += solaris-abi.patch,-p1
 SOURCE_PATCHES += lint.patch,-p1
+SOURCE_PATCHES += CVE-2013-1996.patch,-p1
 
 # Regenerate Makefile.in's from Makefile.am's after patching them
 AUTORECONF=yes
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libX11/CVE-2013-1981.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,1442 @@
+From 4ccc31a3b1decfdec554db5204cd138d32566ed3 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 13:03:55 -0800
+Subject: [PATCH:libX11 01/38] Move repeated #ifdef magic to find PATH_MAX
+ into a common header
+
+Lets stop duplicating the mess all over
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/GetDflt.c         |   25 +--------------
+ src/Makefile.am       |    1 +
+ src/pathmax.h         |   82 +++++++++++++++++++++++++++++++++++++++++++++++++
+ src/xlibi18n/lcFile.c |   24 +--------------
+ 4 files changed, 85 insertions(+), 47 deletions(-)
+ create mode 100644 src/pathmax.h
+
+diff --git a/src/GetDflt.c b/src/GetDflt.c
+index 6f62cd8..4962530 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/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/pathmax.h b/src/pathmax.h
+new file mode 100644
+index 0000000..a8aaaa5
+--- /dev/null
++++ b/src/pathmax.h
+@@ -0,0 +1,82 @@
++
++/***********************************************************
++
++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/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
+ 
+-- 
+1.7.9.2
+
+From bee46fae41c84f42cb025811ec767c9c8cfcb32c Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 21:05:27 -0800
+Subject: [PATCH:libX11 03/38] integer overflow in _XQueryFont() on 32-bit
+ platforms [CVE-2013-1981 1/13]
+
+If the CARD32 reply.nCharInfos * sizeof(XCharStruct) overflows an
+unsigned long, then too small of a buffer will be allocated for the
+data copied in from the reply.
+
+v2: Fix reply_left calculations, check calculated sizes fit in reply_left
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Font.c |   35 +++++++++++++++++++++++------------
+ 1 file changed, 23 insertions(+), 12 deletions(-)
+
+diff --git a/src/Font.c b/src/Font.c
+index 25e1790..9ee127c 100644
+--- a/src/Font.c
++++ b/src/Font.c
+@@ -31,6 +31,7 @@ authorization from the X Consortium and the XFree86 Project.
+ #include <config.h>
+ #endif
+ #include "Xlibint.h"
++#include <limits.h>
+ 
+ #if defined(XF86BIGFONT)
+ #define 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);
++    reply_left = reply.length -
++	((SIZEOF(xQueryFontReply) - SIZEOF(xReply)) >> 2);
+     if (! (fs = (XFontStruct *) Xmalloc (sizeof (XFontStruct)))) {
+-	_XEatData(dpy, (unsigned long)(reply.nFontProps * SIZEOF(xFontProp) +
+-				       reply.nCharInfos * SIZEOF(xCharInfo)));
++	_XEatDataWords(dpy, reply_left);
+ 	return (XFontStruct *)NULL;
+     }
+     fs->ext_data 		= NULL;
+@@ -239,16 +242,19 @@ _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
+@@ -256,16 +262,21 @@ _XQueryFont (
+      */
+     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;
+ 	}
+ 
+-	nbytes = reply.nCharInfos * SIZEOF(xCharInfo);
+ 	_XRead16 (dpy, (char *)fs->per_char, nbytes);
+     }
+ 
+-- 
+1.7.9.2
+
+From ed74729326d04eb736dd2cdffa394c9638a28ab2 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 21:05:27 -0800
+Subject: [PATCH:libX11 04/38] integer overflow in _XF86BigfontQueryFont()
+ [CVE-2013-1981 2/13]
+
+Similar to _XQueryFont, but with more ways to go wrong and overflow.
+Only compiled if libX11 is built with XF86BigFont support.
+
+v2: Fix reply_left calculations, check calculated sizes fit in reply_left
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Font.c |   42 +++++++++++++++++++++++++-----------------
+ 1 file changed, 25 insertions(+), 17 deletions(-)
+
+diff --git a/src/Font.c b/src/Font.c
+index 9ee127c..5dbdb29 100644
+--- a/src/Font.c
++++ b/src/Font.c
+@@ -403,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;
+@@ -456,13 +457,10 @@ _XF86BigfontQueryFont (
+     DeqAsyncHandler(dpy, &async2);
+     if (seq)
+ 	DeqAsyncHandler(dpy, &async1);
++    reply_left = reply.length -
++	((SIZEOF(xXF86BigfontQueryFontReply) - SIZEOF(xReply)) >> 2);
+     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));
++	_XEatDataWords(dpy, reply_left);
+ 	return (XFontStruct *)NULL;
+     }
+     fs->ext_data 		= NULL;
+@@ -488,23 +486,32 @@ _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);
++	_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)) {
+@@ -518,14 +525,14 @@ _XF86BigfontQueryFont (
+ 	    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)))) {
+ 		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);
+@@ -580,6 +587,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);
+-- 
+1.7.9.2
+
+From ce805b2d94edf8109ed8b7f53d440b012b350326 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 22:49:01 -0800
+Subject: [PATCH:libX11 05/38] integer overflow in XListFontsWithInfo()
+ [CVE-2013-1981 3/13]
+
+If the reported number of remaining fonts is too large, the calculations
+to allocate memory for them may overflow, leaving us writing beyond the
+bounds of the allocation.
+
+v2: Fix reply_left calculations, check calculated sizes fit in reply_left
+v3: On error cases, also set values to be returned in pointer args to 0/NULL
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/FontInfo.c |  105 ++++++++++++++++++++++++++------------------------------
+ 1 file changed, 49 insertions(+), 56 deletions(-)
+
+diff --git a/src/FontInfo.c b/src/FontInfo.c
+index fb296b8..4b295a5 100644
+--- a/src/FontInfo.c
++++ b/src/FontInfo.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>
+ 
+ #if defined(XF86BIGFONT)
+ #define 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,52 +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)));
++		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;
+-
+-		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);
+-		    }
+-		    Xfree((char *) flist);
+-		    Xfree((char *) finfo);
+-		    goto clearwire;
+-		}
++		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;
+ 		}
+@@ -138,24 +132,27 @@ XFontStruct **info)	/* RETURN */
+ 	fs->max_bounds = * (XCharStruct *) &reply.maxBounds;
+ 
+ 	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) {
+@@ -185,19 +182,15 @@ XFontStruct **info)	/* RETURN */
+ 
+   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;
+ }
+ 
+-- 
+1.7.9.2
+
+From 3eaf200b6d60de2284c6d7e0180ddf9cabf25a64 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 22:49:01 -0800
+Subject: [PATCH:libX11 06/38] integer overflow in XGetMotionEvents()
+ [CVE-2013-1981 4/13]
+
+If the reported number of motion events is too large, the calculations
+to allocate memory for them may overflow, leaving us writing beyond the
+bounds of the allocation.
+
+v2: Ensure nEvents is set to 0 when returning NULL events pointer
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/GetMoEv.c |   26 +++++++++++---------------
+ 1 file changed, 11 insertions(+), 15 deletions(-)
+
+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);
+-- 
+1.7.9.2
+
+From b0528a42d6728c119af2fcb28407efa7b0b9fe54 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 22:49:01 -0800
+Subject: [PATCH:libX11 07/38] integer overflow in XListHosts() [CVE-2013-1981
+ 5/13]
+
+If the reported number of host entries is too large, the calculations
+to allocate memory for them may overflow, leaving us writing beyond the
+bounds of the allocation.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/LiHosts.c |   22 +++++++++++++++-------
+ 1 file changed, 15 insertions(+), 7 deletions(-)
+
+diff --git a/src/LiHosts.c b/src/LiHosts.c
+index 0f5e837..83cf3c7 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)
+-- 
+1.7.9.2
+
+From fa0ab9b0a1e2dae89895919a9dcdff5f6851ee64 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 11:44:19 -0800
+Subject: [PATCH:libX11 20/38] Integer overflows in stringSectionSize() cause
+ buffer overflow in ReadColornameDB()
+ [CVE-2013-1981 6/13]
+
+LoadColornameDB() calls stringSectionSize() to do a first pass over the
+file (which may be provided by the user via XCMSDB environment variable)
+to determine how much memory needs to be allocated to read in the file,
+then allocates the returned sizes and calls ReadColornameDB() to load the
+data from the file into that newly allocated memory.
+
+If stringSectionSize() overflows the signed ints used to calculate the
+file size (say if you have an xcmsdb with ~4 billion lines in or a
+combined string length of ~4 gig - which while it may have been
+inconceivable when Xlib was written, is quite possible today), then
+LoadColornameDB() may allocate a memory buffer much smaller than the
+amount of data ReadColornameDB() will write to it.
+
+The total size is left limited to an int, because if your xcmsdb file
+is larger than 2gb, you're doing it wrong.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xcms/cmsColNm.c |   27 +++++++++++++++++++++------
+ 1 file changed, 21 insertions(+), 6 deletions(-)
+
+diff --git a/src/xcms/cmsColNm.c b/src/xcms/cmsColNm.c
+index a6749c0..8d0d4a7 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);
+ }
+ 
+-- 
+1.7.9.2
+
+From de8462f73c41b2253d920a713725c96591ab5690 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 18:37:37 -0800
+Subject: [PATCH:libX11 21/38] integer overflow in ReadInFile() in Xrm.c
+ [CVE-2013-1981 7/13]
+
+Called from XrmGetFileDatabase() which gets called from InitDefaults()
+which gets the filename from getenv ("XENVIRONMENT")
+
+If file is exactly 0xffffffff bytes long (or longer and truncates to
+0xffffffff, on implementations where off_t is larger than an int),
+then size may be set to a value which overflows causing less memory
+to be allocated than is written to by the following read() call.
+
+size is left limited to an int, because if your Xresources file is
+larger than 2gb, you're very definitely doing it wrong.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/Xrm.c |    6 ++++--
+ 1 file changed, 4 insertions(+), 2 deletions(-)
+
+diff --git a/src/Xrm.c b/src/Xrm.c
+index d6899d9..3e29ab0 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"
+ 
+@@ -1594,11 +1595,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' */
+-- 
+1.7.9.2
+
+From 9a8117101fe3c6c615fbce34eca244f149bb2766 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 18:37:37 -0800
+Subject: [PATCH:libX11 24/38] integer truncation in _XimParseStringFile()
+ [CVE-2013-1981 8/13]
+
+Called from _XimCreateDefaultTree() which uses getenv("XCOMPOSEFILE")
+to specify filename.
+
+If the size of off_t is larger than the size of unsigned long (as in
+32-bit builds with large file flags), a file larger than 4 gigs could
+have its size truncated, leading to data from that file being written
+past the end of the undersized buffer allocated for it.
+
+While configure.ac does not use AC_SYS_LARGEFILE to set large file mode,
+builders may have added the large file compilation flags to CFLAGS on
+their own.
+
+size is left limited to an int, because if your Xim file is
+larger than 2gb, you're doing it wrong.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ modules/im/ximcp/imLcPrs.c |    3 +++
+ 1 file changed, 3 insertions(+)
+
+diff --git a/modules/im/ximcp/imLcPrs.c b/modules/im/ximcp/imLcPrs.c
+index 4c7d6f0..bcf4579 100644
+--- a/modules/im/ximcp/imLcPrs.c
++++ b/modules/im/ximcp/imLcPrs.c
+@@ -41,6 +41,7 @@ OR PERFORMANCE OF THIS SOFTWARE.
+ #include "Ximint.h"
+ #include <sys/stat.h>
+ #include <stdio.h>
++#include <limits.h>
+ 
+ #define XLC_BUFSIZE 256
+ 
+@@ -688,6 +689,8 @@ parsestringfile(
+ 
+     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);
+ 
+-- 
+1.7.9.2
+
+From 692e43c2d5fbc56f38371f3f44a1d339595f0056 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 13:18:48 -0800
+Subject: [PATCH:libX11 25/38] integer overflows in TransFileName()
+ [CVE-2013-1981 9/13]
+
+When trying to process file paths the tokens %H, %L, & %S are expanded
+to $HOME, the standard compose file path & the xlocaledir path.
+If enough of these tokens are repeated and values like $HOME are set to
+very large values, the calculation of the total string size required to
+hold the expanded path can overflow, resulting in allocating a smaller
+string than the amount of data we'll write to it.
+
+Simply restrict all of these values, and the total path size to PATH_MAX,
+because really, that's all you should need for a filename path.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ modules/im/ximcp/Makefile.am |    1 +
+ modules/im/ximcp/imLcPrs.c   |   45 +++++++++++++++++++++++++++++++-----------
+ 2 files changed, 35 insertions(+), 11 deletions(-)
+
+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 bcf4579..f3627a0 100644
+--- a/modules/im/ximcp/imLcPrs.c
++++ b/modules/im/ximcp/imLcPrs.c
+@@ -42,6 +42,7 @@ OR PERFORMANCE OF THIS SOFTWARE.
+ #include <sys/stat.h>
+ #include <stdio.h>
+ #include <limits.h>
++#include "pathmax.h"
+ 
+ #define XLC_BUFSIZE 256
+ 
+@@ -307,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 == '%') {
+@@ -319,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 == '%') {
+@@ -374,6 +396,7 @@ TransFileName(Xim im, char *name)
+       }
+    }
+    *j = '\0';
++end:
+    Xfree(lcCompose);
+    return ret;
+ }
+-- 
+1.7.9.2
+
+From ea8bc513f6849cadc93dd68de8a562d6e63b19d5 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 8 Mar 2013 22:25:35 -0800
+Subject: [PATCH:libX11 26/38] integer overflow in XGetWindowProperty()
+ [CVE-2013-1981 10/13]
+
+If the reported number of properties is too large, the calculations
+to allocate memory for them may overflow, leaving us returning less
+memory to the caller than implied by the value written to *nitems.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/GetProp.c |   25 ++++++++++++++++---------
+ 1 file changed, 16 insertions(+), 9 deletions(-)
+
+diff --git a/src/GetProp.c b/src/GetProp.c
+index 5d6e0b8..ae14edc 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(
+@@ -66,8 +67,17 @@ XGetWindowProperty(
+ 
+     *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 +86,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 +122,7 @@ XGetWindowProperty(
+ 	    break;
+ 	}
+ 	if (! *prop) {
+-	    _XEatData(dpy, (unsigned long) netbytes);
++	    _XEatDataWords(dpy, reply.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return(BadAlloc);	/* not Success */
+-- 
+1.7.9.2
+
+From 0febed454ee211deb6ae56d4febf71393e0aff2b Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 15:08:21 -0800
+Subject: [PATCH:libX11 27/38] integer overflow in XGetImage() [CVE-2013-1981
+ 11/13]
+
+Ensure that we don't underallocate when the server claims to have sent a
+very large reply.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/GetImage.c |   12 ++++++++----
+ 1 file changed, 8 insertions(+), 4 deletions(-)
+
+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;
+-- 
+1.7.9.2
+
+From 83f1fc4205d2c9c886bdc4bdab2a27cb0e280110 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 15:08:21 -0800
+Subject: [PATCH:libX11 28/38] integer overflow in XGetPointerMapping() &
+ XGetKeyboardMapping() [CVE-2013-1981 12/13]
+
+Ensure that we don't underallocate when the server claims a very large reply
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/GetPntMap.c |   31 ++++++++++++++++++++-----------
+ 1 file changed, 20 insertions(+), 11 deletions(-)
+
+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;
+-- 
+1.7.9.2
+
+From b2e9b2585a4528e23df9f9067c6c6c91115ae55b Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 15:08:21 -0800
+Subject: [PATCH:libX11 29/38] integer overflow in XGetModifierMapping()
+ [CVE-2013-1981 13/13]
+
+Ensure that we don't underallocate when the server claims a very large reply
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/ModMap.c |   13 +++++++++----
+ 1 file changed, 9 insertions(+), 4 deletions(-)
+
+diff --git a/src/ModMap.c b/src/ModMap.c
+index c99bfdd..122ca80 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;
+-- 
+1.7.9.2
+
+From 3fb82a4726114c1e9916658dad659a4dbfb050c8 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 11:04:37 -0800
+Subject: [PATCH:libX11 33/38] Make XGetWindowProperty() always initialize
+ returned values
+
+Avoids memory corruption and other errors when callers access them
+without checking to see if XGetWindowProperty() returned an error value.
+
+Callers are still required to check for errors, this just reduces the
+damage when they don't.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/GetProp.c |    8 +++++++-
+ 1 file changed, 7 insertions(+), 1 deletion(-)
+
+diff --git a/src/GetProp.c b/src/GetProp.c
+index ae14edc..9eb422e 100644
+--- a/src/GetProp.c
++++ b/src/GetProp.c
+@@ -49,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;
+@@ -65,7 +72,6 @@ XGetWindowProperty(
+ 	return (1);	/* not Success */
+ 	}
+ 
+-    *prop = (unsigned char *) NULL;
+     if (reply.propertyType != None) {
+ 	unsigned long nbytes, netbytes;
+ 	int format = reply.format;
+-- 
+1.7.9.2
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libX11/CVE-2013-1997.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,789 @@
+From b68b8dcddbb517cee2fe370ffd3bacae99c75299 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 19:30:09 -0800
+Subject: [PATCH:libX11 08/38] unvalidated lengths in XAllocColorCells()
+ [CVE-2013-1997 1/15]
+
+If a broken server returned larger than requested values for nPixels or
+nMasks, XAllocColorCells would happily overflow the buffers provided by
+the caller to write the results into.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/AllCells.c |    9 +++++++--
+ 1 file changed, 7 insertions(+), 2 deletions(-)
+
+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);
+-- 
+1.7.9.2
+
+From 638d668a99734cf68bea1b799aece5706fb18b08 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 22:49:01 -0800
+Subject: [PATCH:libX11 09/38] unvalidated index in
+ _XkbReadGetDeviceInfoReply() [CVE-2013-1997
+ 2/15]
+
+If the X server returns more buttons than are allocated in the XKB
+device info structures, out of bounds writes could occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xkb/XKBExtDev.c |    6 ++++++
+ 1 file changed, 6 insertions(+)
+
+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))
+-- 
+1.7.9.2
+
+From 1807e71a8a30aa2cff099708c508a25a9b6ba9da Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 09:12:47 -0800
+Subject: [PATCH:libX11 10/38] unvalidated indexes in _XkbReadGeomShapes()
+ [CVE-2013-1997 3/15]
+
+If the X server returns shape indexes outside the range of the number
+of shapes it told us to allocate, out of bounds memory access could occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xkb/XKBGeom.c |   12 ++++++++----
+ 1 file changed, 8 insertions(+), 4 deletions(-)
+
+diff --git a/src/xkb/XKBGeom.c b/src/xkb/XKBGeom.c
+index 7594a3d..4ad21f8 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;
+-- 
+1.7.9.2
+
+From 8215ec8bcad57c9707353626d782ff66ebe13b06 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 09:18:26 -0800
+Subject: [PATCH:libX11 11/38] unvalidated indexes in
+ _XkbReadGetGeometryReply() [CVE-2013-1997
+ 4/15]
+
+If the X server returns color indexes outside the range of the number of
+colors it told us to allocate, out of bounds memory access could occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xkb/XKBGeom.c |    3 +++
+ 1 file changed, 3 insertions(+)
+
+diff --git a/src/xkb/XKBGeom.c b/src/xkb/XKBGeom.c
+index 4ad21f8..7140a72 100644
+--- a/src/xkb/XKBGeom.c
++++ b/src/xkb/XKBGeom.c
+@@ -619,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;
+-- 
+1.7.9.2
+
+From 77009b1f37ec583ef5ff17834c8a5cf2413f9ba6 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 09:28:33 -0800
+Subject: [PATCH:libX11 12/38] unvalidated index in _XkbReadKeySyms()
+ [CVE-2013-1997 5/15]
+
+If the X server returns keymap indexes outside the range of the number of
+keys it told us to allocate, out of bounds memory access could occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xkb/XKBGetMap.c |    7 ++++++-
+ 1 file changed, 6 insertions(+), 1 deletion(-)
+
+diff --git a/src/xkb/XKBGetMap.c b/src/xkb/XKBGetMap.c
+index 30fb629..4a428d3 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 *)
+-- 
+1.7.9.2
+
+From ffc188aa4cbc0b0d0c612b62e45c29d485f86402 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 09:40:22 -0800
+Subject: [PATCH:libX11 13/38] unvalidated index in _XkbReadKeyActions()
+ [CVE-2013-1997 6/15]
+
+If the X server returns key action indexes outside the range of the number
+of keys it told us to allocate, out of bounds memory access could occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xkb/XKBGetMap.c |    4 ++++
+ 1 file changed, 4 insertions(+)
+
+diff --git a/src/xkb/XKBGetMap.c b/src/xkb/XKBGetMap.c
+index 4a428d3..86ecf9d 100644
+--- a/src/xkb/XKBGetMap.c
++++ b/src/xkb/XKBGetMap.c
+@@ -269,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 {
+-- 
+1.7.9.2
+
+From 9f3d45b62875e7861deeecf849f90520395ee655 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 10:39:21 -0800
+Subject: [PATCH:libX11 14/38] unvalidated index in _XkbReadKeyBehaviors()
+ [CVE-2013-1997 7/15]
+
+If the X server returns key behavior indexes outside the range of the number
+of keys it told us to allocate, out of bounds memory writes could occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xkb/XKBGetMap.c |    6 ++++--
+ 1 file changed, 4 insertions(+), 2 deletions(-)
+
+diff --git a/src/xkb/XKBGetMap.c b/src/xkb/XKBGetMap.c
+index 86ecf9d..af93a5c 100644
+--- a/src/xkb/XKBGetMap.c
++++ b/src/xkb/XKBGetMap.c
+@@ -305,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;
+@@ -318,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;
+-- 
+1.7.9.2
+
+From b837305efa896d4bab4932faffb30d53cec546a3 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 10:51:51 -0800
+Subject: [PATCH:libX11 15/38] unvalidated index in _XkbReadModifierMap()
+ [CVE-2013-1997 8/15]
+
+If the X server returns modifier map indexes outside the range of the number
+of keys it told us to allocate, out of bounds memory writes could occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xkb/XKBGetMap.c |    5 +++++
+ 1 file changed, 5 insertions(+)
+
+diff --git a/src/xkb/XKBGetMap.c b/src/xkb/XKBGetMap.c
+index af93a5c..a68455b 100644
+--- a/src/xkb/XKBGetMap.c
++++ b/src/xkb/XKBGetMap.c
+@@ -390,6 +390,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;
+@@ -402,6 +405,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];
+ 	}
+     }
+-- 
+1.7.9.2
+
+From d71c0d7d138f8d15e7f4cfe747329405f0644423 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 11:04:44 -0800
+Subject: [PATCH:libX11 16/38] unvalidated index in
+ _XkbReadExplicitComponents() [CVE-2013-1997
+ 9/15]
+
+If the X server returns key indexes outside the range of the number of
+keys it told us to allocate, out of bounds memory writes could occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xkb/XKBGetMap.c |    6 +++++-
+ 1 file changed, 5 insertions(+), 1 deletion(-)
+
+diff --git a/src/xkb/XKBGetMap.c b/src/xkb/XKBGetMap.c
+index a68455b..ea77f2a 100644
+--- a/src/xkb/XKBGetMap.c
++++ b/src/xkb/XKBGetMap.c
+@@ -362,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;
+@@ -377,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];
+ 	}
+     }
+-- 
+1.7.9.2
+
+From fb927b6dbc0172c2ca63b5ad243bfb98bb61fc4c Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 11:01:04 -0800
+Subject: [PATCH:libX11 17/38] unvalidated index in _XkbReadVirtualModMap()
+ [CVE-2013-1997 10/15]
+
+If the X server returns modifier map indexes outside the range of the number
+of keys it told us to allocate, out of bounds memory writes could occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xkb/XKBGetMap.c |    3 +++
+ 1 file changed, 3 insertions(+)
+
+diff --git a/src/xkb/XKBGetMap.c b/src/xkb/XKBGetMap.c
+index ea77f2a..5551298 100644
+--- a/src/xkb/XKBGetMap.c
++++ b/src/xkb/XKBGetMap.c
+@@ -425,6 +425,9 @@ xkbVModMapWireDesc *	wire;
+ XkbServerMapPtr		srv;
+ 
+     if ( rep->totalVModMapKeys>0 ) {
++	if (((int) rep->firstVModMapKey + rep->nVModMapKeys)
++	     > xkb->max_key_code)
++	    return BadLength;
+ 	if (((xkb->server==NULL)||(xkb->server->vmodmap==NULL))&&
+ 	    (XkbAllocServerMap(xkb,XkbVirtualModMapMask,0)!=Success)) {
+ 	    return BadAlloc;
+-- 
+1.7.9.2
+
+From f06f3cdc343fd6d42021dba055f080b617432301 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 11:11:08 -0800
+Subject: [PATCH:libX11 18/38] unvalidated index/length in
+ _XkbReadGetNamesReply() [CVE-2013-1997 11/15]
+
+If the X server returns key name indexes outside the range of the number
+of keys it told us to allocate, out of bounds memory writes could occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/xkb/XKBNames.c |    2 ++
+ 1 file changed, 2 insertions(+)
+
+diff --git a/src/xkb/XKBNames.c b/src/xkb/XKBNames.c
+index 0276c05..0f1e48e 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);
+ 	}
++	else if ( ((int)rep->firstKey + rep->nKeys) > xkb->max_key_code)
++	    goto BAILOUT;
+ 	if (names->keys!=NULL) {
+ 	    if (!_XkbCopyFromReadBuffer(&buf,
+ 					(char *)&names->keys[rep->firstKey],
+-- 
+1.7.9.2
+
+From d851a64b0704f79550a9507a34d057c7415f6516 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 11:25:25 -0800
+Subject: [PATCH:libX11 19/38] unvalidated length in _XimXGetReadData()
+ [CVE-2013-1997 12/15]
+
+Check the provided buffer size against the amount of data we're going to
+write into it, not against the reported length from the ClientMessage.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ modules/im/ximcp/imTrX.c |    2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/modules/im/ximcp/imTrX.c b/modules/im/ximcp/imTrX.c
+index 1412d70..76ff20e 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) {
+-- 
+1.7.9.2
+
+From 59ba5744cdb8831e53f6340279d9841a037c48bc Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 15:08:21 -0800
+Subject: [PATCH:libX11 30/38] Avoid overflows in XListFonts() [CVE-2013-1997
+ 13/15]
+
+Ensure that when breaking the returned list into individual strings,
+we don't walk past the end of allocated memory to write the '\0' bytes
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/FontNames.c |   35 ++++++++++++++++++++++-------------
+ 1 file changed, 22 insertions(+), 13 deletions(-)
+
+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);
+-- 
+1.7.9.2
+
+From b5686ac6ad36e7742f8bba5b906bf2c57ba18955 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 15:08:21 -0800
+Subject: [PATCH:libX11 31/38] Avoid overflows in XGetFontPath()
+ [CVE-2013-1997 14/15]
+
+Ensure that when breaking the returned list into individual strings,
+we don't walk past the end of allocated memory to write the '\0' bytes
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/GetFPath.c |   36 ++++++++++++++++++++++--------------
+ 1 file changed, 22 insertions(+), 14 deletions(-)
+
+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);
+-- 
+1.7.9.2
+
+From 910875c83c9e6741aba258f44f94b3d69f804d00 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 15:08:21 -0800
+Subject: [PATCH:libX11 32/38] Avoid overflows in XListExtensions()
+ [CVE-2013-1997 15/15]
+
+Ensure that when breaking the returned list into individual strings,
+we don't walk past the end of allocated memory to write the '\0' bytes
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/ListExt.c |   36 ++++++++++++++++++++++--------------
+ 1 file changed, 22 insertions(+), 14 deletions(-)
+
+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);
+-- 
+1.7.9.2
+
+From 134944bfb0963151e4e65b9b17c5431a41acd28e Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sun, 31 Mar 2013 12:22:35 -0700
+Subject: [PATCH:libX11 37/38] _XkbReadGetMapReply: reject maxKeyCodes smaller
+ than the minKeyCode
+
+Various other bounds checks in the code assume this is true, so
+enforce it when we first get the data from the X server.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/xkb/XKBGetMap.c |    2 ++
+ 1 file changed, 2 insertions(+)
+
+diff --git a/src/xkb/XKBGetMap.c b/src/xkb/XKBGetMap.c
+index d4cc199..862807a 100644
+--- a/src/xkb/XKBGetMap.c
++++ b/src/xkb/XKBGetMap.c
+@@ -482,6 +482,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;
+ 
+-- 
+1.7.9.2
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libX11/CVE-2013-2004.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,207 @@
+From 5004f53889bf65aa9e78cea7a01a51948839dce3 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 12:01:39 -0800
+Subject: [PATCH:libX11 22/38] Unbounded recursion in GetDatabase() when
+ parsing include files [CVE-2013-2004 1/2]
+
+GetIncludeFile() can call GetDatabase() which can call GetIncludeFile()
+which can call GetDatabase() which can call GetIncludeFile() ....
+eventually causing recursive stack overflow and crash.
+
+Easily reproduced with a resource file that #includes itself.
+
+Limit is set to a include depth of 100 files, which should be enough
+for all known use cases, but could be adjusted later if necessary.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/Xrm.c |   24 +++++++++++++++---------
+ 1 file changed, 15 insertions(+), 9 deletions(-)
+
+diff --git a/src/Xrm.c b/src/Xrm.c
+index 3e29ab0..2c0c324 100644
+--- a/src/Xrm.c
++++ b/src/Xrm.c
+@@ -1088,13 +1088,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];
+@@ -1204,7 +1206,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 */
+@@ -1545,7 +1548,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);
+ }
+ 
+@@ -1557,7 +1560,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;
+ }
+@@ -1636,7 +1639,8 @@ GetIncludeFile(
+     XrmDatabase db,
+     _Xconst char *base,
+     _Xconst char *fname,
+-    int fnamelen)
++    int fnamelen,
++    int depth)
+ {
+     int len;
+     char *str;
+@@ -1644,6 +1648,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)
+@@ -1657,7 +1663,7 @@ GetIncludeFile(
+     }
+     if (!(str = ReadInFile(realfname)))
+ 	return;
+-    GetDatabase(db, str, realfname, True);
++    GetDatabase(db, str, realfname, True, depth + 1);
+     Xfree(str);
+ }
+ 
+@@ -1673,7 +1679,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;
+@@ -1697,7 +1703,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)
+-- 
+1.7.9.2
+
+From f94dc4a99aa1845c6a25826e99e11aaa4fff78eb Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 12:39:58 -0800
+Subject: [PATCH:libX11 23/38] Unbounded recursion in _XimParseStringFile()
+ when parsing include files [CVE-2013-2004 2/2]
+
+parseline() can call _XimParseStringFile() which can call parseline()
+which can call _XimParseStringFile() which can call parseline() ....
+eventually causing recursive stack overflow and crash.
+
+Limit is set to a include depth of 100 files, which should be enough
+for all known use cases, but could be adjusted later if necessary.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ modules/im/ximcp/imLcPrs.c |   20 +++++++++++++++++---
+ 1 file changed, 17 insertions(+), 3 deletions(-)
+
+diff --git a/modules/im/ximcp/imLcPrs.c b/modules/im/ximcp/imLcPrs.c
+index 4e54385..4c7d6f0 100644
+--- a/modules/im/ximcp/imLcPrs.c
++++ b/modules/im/ximcp/imLcPrs.c
+@@ -56,6 +56,8 @@ extern int _Xmbstoutf8(
+     int		len
+ );
+ 
++static void parsestringfile(FILE *fp, Xim im, int depth);
++
+ /*
+  *	Parsing File Format:
+  *
+@@ -423,7 +425,8 @@ static int
+ parseline(
+     FILE *fp,
+     Xim   im,
+-    char* tokenbuf)
++    char* tokenbuf,
++    int   depth)
+ {
+     int token;
+     DTModifier modifier_mask;
+@@ -470,11 +473,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,6 +673,15 @@ _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;
+@@ -678,7 +692,7 @@ _XimParseStringFile(
+ 	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);
+ 	}
+     }
+-- 
+1.7.9.2
+
--- a/open-src/lib/libX11/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libX11/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -93,12 +93,20 @@
 	locale-zh_TW.patch \
 	locale-ru-RU.UTF-8.patch
 
+# Patches from May 2013 security alert - will be integrated into libX11 1.6
+SOURCE_PATCHES += upstream-cleanup.patch,-p1
+SOURCE_PATCHES += XEatDataWords.patch,-p1
+SOURCE_PATCHES += CVE-2013-1981.patch,-p1
+SOURCE_PATCHES += CVE-2013-1997.patch,-p1
+SOURCE_PATCHES += CVE-2013-2004.patch,-p1
+SOURCE_PATCHES += alloc-cleanup.patch,-p1
+
 # Library name (used for specfiles/mapfiles)
 LIBNAME=X11
 
 # Dates to show in Oracle copyright notice in pkg license file
 # Earliest & latest of the copyrights in the Oracle files in this pkg
-ORACLE_COPYRIGHT_YEARS = 1986, 2012
+ORACLE_COPYRIGHT_YEARS = 1986, 2013
 
 # ARC cases that covered this module
 # PSARC/1992/077 X11/R5 Xlib API
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libX11/XEatDataWords.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,306 @@
+From d738eb47a3e781477101d706f01dd61148a9086f Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 20:54:24 -0800
+Subject: [PATCH:libX11 02/38] Add _XEatDataWords to discard a given number of
+ 32-bit words of reply 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.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ include/X11/Xlibint.h |    4 ++++
+ src/xcb_io.c          |   17 +++++++++++++++++
+ 2 files changed, 21 insertions(+)
+
+diff --git a/include/X11/Xlibint.h b/include/X11/Xlibint.h
+index 06395b3..d63a534 100644
+--- a/include/X11/Xlibint.h
++++ b/include/X11/Xlibint.h
+@@ -855,6 +855,10 @@ extern void _XEatData(
+     Display*		/* dpy */,
+     unsigned long	/* n */
+ );
++extern void _XEatDataWords(
++    Display*		/* dpy */,
++    unsigned long	/* n */
++);
+ extern char *_XAllocScratch(
+     Display*		/* dpy */,
+     unsigned long	/* nbytes */
+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);
++}
+-- 
+1.7.9.2
+
+From 56623594bb0f132aa2792f76378a573c7efe31e2 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 19 Apr 2013 14:30:40 -0700
+Subject: [PATCH:libX11 38/38] Give GNU & Solaris Studio compilers hints about
+ XEatData branches
+
+Try to offset the cost of all the recent checks we've added by giving
+the compiler a hint that the branches that involve us eating data
+are less likely to be used than the ones that process it.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ include/X11/Xlibint.h |   16 ++++++++++++++--
+ 1 file changed, 14 insertions(+), 2 deletions(-)
+
+diff --git a/include/X11/Xlibint.h b/include/X11/Xlibint.h
+index d63a534..acbad6b 100644
+--- a/include/X11/Xlibint.h
++++ b/include/X11/Xlibint.h
+@@ -832,6 +832,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
+@@ -854,11 +863,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 */
+-- 
+1.7.9.2
+
+From d0944b52f8debb74eb48359a8dc20706b12da834 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 16:56:16 -0800
+Subject: [PATCH:libX11 34/38] Convert more _XEatData callers to
+ _XEatDataWords
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Matthieu Herrb <[email protected]>
+---
+ src/GetAtomNm.c |    4 ++--
+ src/LiICmaps.c  |    8 ++++----
+ src/LiProps.c   |    8 ++++----
+ src/OpenDis.c   |    2 +-
+ src/QuColors.c  |   10 +++++-----
+ src/QuTree.c    |    8 ++++----
+ 6 files changed, 20 insertions(+), 20 deletions(-)
+
+diff --git a/src/GetAtomNm.c b/src/GetAtomNm.c
+index 9823c69..996f7eb 100644
+--- a/src/GetAtomNm.c
++++ b/src/GetAtomNm.c
+@@ -78,7 +78,7 @@ char *XGetAtomName(
+ 	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);
+@@ -176,7 +176,7 @@ XGetAtomNames (
+ 		_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/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/OpenDis.c b/src/OpenDis.c
+index f6d8c70..0bf1b91 100644
+--- a/src/OpenDis.c
++++ b/src/OpenDis.c
+@@ -552,7 +552,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/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;
+-- 
+1.7.9.2
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libX11/alloc-cleanup.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,1182 @@
+From 995dd372e73fcec43fb65bd42ff5adb409765f66 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Thu, 7 Mar 2013 23:46:05 -0800
+Subject: [PATCH:libX11 35/38] Remove more unnecessary casts from
+ Xmalloc/calloc calls
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Context.c    |    8 ++++----
+ src/CrGC.c       |    2 +-
+ src/Depths.c     |    2 +-
+ src/FSWrap.c     |    6 +++---
+ src/Font.c       |   12 ++++++------
+ src/GetAtomNm.c  |    8 ++++----
+ src/GetHints.c   |    9 ++++-----
+ src/GetRGBCMap.c |    3 +--
+ src/ImUtil.c     |    6 +++---
+ src/InitExt.c    |    4 ++--
+ src/IntAtom.c    |    6 +++---
+ src/KeyBind.c    |    8 +++-----
+ src/ModMap.c     |    4 ++--
+ src/OpenDis.c    |   21 +++++++--------------
+ src/PixFormats.c |    4 ++--
+ src/PolyReg.c    |   13 +++++--------
+ src/PropAlloc.c  |    9 ++++-----
+ src/PutBEvent.c  |    2 +-
+ src/PutImage.c   |   13 ++++++-------
+ src/Quarks.c     |    9 ++++-----
+ src/RdBitF.c     |    2 +-
+ src/Region.c     |   19 +++++++++----------
+ src/RegstFlt.c   |    4 ++--
+ src/SetFPath.c   |    2 +-
+ src/SetHints.c   |    6 +++---
+ src/StrToText.c  |    2 +-
+ src/TextToStr.c  |    4 ++--
+ src/VisUtil.c    |    8 +++-----
+ src/WrBitF.c     |    2 +-
+ src/XlibInt.c    |   20 +++++++++-----------
+ src/Xrm.c        |   20 +++++++++-----------
+ src/locking.c    |    8 ++++----
+ src/udcInf.c     |    9 ++++-----
+ 33 files changed, 115 insertions(+), 140 deletions(-)
+
+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/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/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/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/Font.c b/src/Font.c
+index 5dbdb29..3beb8a5 100644
+--- a/src/Font.c
++++ b/src/Font.c
+@@ -215,7 +215,7 @@ _XQueryFont (
+ 	DeqAsyncHandler(dpy, &async);
+     reply_left = reply.length -
+ 	((SIZEOF(xQueryFontReply) - SIZEOF(xReply)) >> 2);
+-    if (! (fs = (XFontStruct *) Xmalloc (sizeof (XFontStruct)))) {
++    if (! (fs = Xmalloc (sizeof (XFontStruct)))) {
+ 	_XEatDataWords(dpy, reply_left);
+ 	return (XFontStruct *)NULL;
+     }
+@@ -323,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;
+@@ -459,7 +459,7 @@ _XF86BigfontQueryFont (
+ 	DeqAsyncHandler(dpy, &async1);
+     reply_left = reply.length -
+ 	((SIZEOF(xXF86BigfontQueryFontReply) - SIZEOF(xReply)) >> 2);
+-    if (! (fs = (XFontStruct *) Xmalloc (sizeof (XFontStruct)))) {
++    if (! (fs = Xmalloc (sizeof (XFontStruct)))) {
+ 	_XEatDataWords(dpy, reply_left);
+ 	return (XFontStruct *)NULL;
+     }
+@@ -521,14 +521,14 @@ _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);
+ 		_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);
+@@ -555,7 +555,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);
+diff --git a/src/GetAtomNm.c b/src/GetAtomNm.c
+index 996f7eb..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,7 +73,7 @@ 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);
+@@ -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,7 +170,7 @@ 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],
+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/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 fa8d464..240a261 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;
+@@ -842,7 +842,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;
+@@ -868,7 +868,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/KeyBind.c b/src/KeyBind.c
+index f22feca..2110772 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/ModMap.c b/src/ModMap.c
+index 122ca80..5c5b426 100644
+--- a/src/ModMap.c
++++ b/src/ModMap.c
+@@ -97,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/OpenDis.c b/src/OpenDis.c
+index 0bf1b91..7318ad9 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 = Xmalloc(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 = Xmalloc(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 = Xmalloc(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 = Xmalloc(dp->nvisuals * sizeof(Visual));
+ 		    if (dp->visuals == NULL) {
+ 			OutOfMemory (dpy);
+ 			return(NULL);
+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/PropAlloc.c b/src/PropAlloc.c
+index 5162830..87817d8 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));
+ }
+ 
+ 
+@@ -64,7 +63,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/Quarks.c b/src/Quarks.c
+index 4eb90c5..60fe127 100644
+--- a/src/Quarks.c
++++ b/src/Quarks.c
+@@ -186,15 +186,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
+@@ -289,13 +288,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/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 1cde48f..0ae0764 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]) {
+@@ -299,7 +299,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/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/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/XlibInt.c b/src/XlibInt.c
+index 1c964fd..b06e57b 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;
+@@ -374,10 +374,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;
+@@ -464,7 +464,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;
+@@ -537,9 +537,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;
+@@ -548,7 +547,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;
+@@ -756,8 +755,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);
+@@ -1518,7 +1516,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/Xrm.c b/src/Xrm.c
+index 2c0c324..d8272ee 100644
+--- a/src/Xrm.c
++++ b/src/Xrm.c
+@@ -495,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;
+@@ -828,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; \
+@@ -841,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; \
+         } \
+@@ -955,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;
+@@ -987,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;
+@@ -1138,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;
+     }
+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/udcInf.c b/src/udcInf.c
+index b7577ac..9ecf156 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 ;
+-- 
+1.7.9.2
+
+From 993349bf944ad312b0dd7096558fb8cfe1eff16b Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 16 Mar 2013 10:03:13 -0700
+Subject: [PATCH:libX11 36/38] Use calloc in XOpenDisplay to initialize
+ structs containing pointers
+
+Prevents trying to free uninitialized pointers if we have to bail out
+partway through setup, such as if we receive a corrupted or incomplete
+connection setup block from the server.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/OpenDis.c |    8 ++++----
+ 1 file changed, 4 insertions(+), 4 deletions(-)
+
+diff --git a/src/OpenDis.c b/src/OpenDis.c
+index 7318ad9..fc67d1a 100644
+--- a/src/OpenDis.c
++++ b/src/OpenDis.c
+@@ -340,7 +340,7 @@ XOpenDisplay (
+ /*
+  * Now iterate down setup information.....
+  */
+-	dpy->pixmap_format = Xmalloc(dpy->nformats * sizeof(ScreenFormat));
++	dpy->pixmap_format = Xcalloc(dpy->nformats, sizeof(ScreenFormat));
+ 	if (dpy->pixmap_format == NULL) {
+ 	        OutOfMemory (dpy);
+ 		return(NULL);
+@@ -368,7 +368,7 @@ XOpenDisplay (
+ /*
+  * next the Screen structures.
+  */
+-	dpy->screens = Xmalloc(dpy->nscreens * sizeof(Screen));
++	dpy->screens = Xcalloc(dpy->nscreens, sizeof(Screen));
+ 	if (dpy->screens == NULL) {
+ 	        OutOfMemory (dpy);
+ 		return(NULL);
+@@ -410,7 +410,7 @@ XOpenDisplay (
+ /*
+  * lets set up the depth structures.
+  */
+-	    sp->depths = Xmalloc(sp->ndepths * sizeof(Depth));
++	    sp->depths = Xcalloc(sp->ndepths, sizeof(Depth));
+ 	    if (sp->depths == NULL) {
+ 		OutOfMemory (dpy);
+ 		return(NULL);
+@@ -432,7 +432,7 @@ XOpenDisplay (
+ 		dp->nvisuals = u.dp->nVisuals;
+ 		u.dp = (xDepth *) (((char *) u.dp) + sz_xDepth);
+ 		if (dp->nvisuals > 0) {
+-		    dp->visuals = Xmalloc(dp->nvisuals * sizeof(Visual));
++		    dp->visuals = Xcalloc(dp->nvisuals, sizeof(Visual));
+ 		    if (dp->visuals == NULL) {
+ 			OutOfMemory (dpy);
+ 			return(NULL);
+-- 
+1.7.9.2
+
--- a/open-src/lib/libX11/mapfile-vers	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libX11/mapfile-vers	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # libX11 version mapfile
 #
-# Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -855,6 +855,7 @@
 	_XDeq;
 	_XDeqAsyncHandler;
 	_XEatData;
+	_XEatDataWords;
 	_XEnq;
 	_XError;
 	_XErrorFunction;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libX11/upstream-cleanup.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,3327 @@
+From 0dc93f7e43deb102b1f8fb7c4c4844cdce7ffd1e Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 29 Jun 2012 22:57:13 -0700
+Subject: [PATCH:libX11 02/58] XCreate{Pix,Bit}map...Data: Free pixmap in
+ error path if XCreateGC fails
+
+Fixes leaks in error paths found by Parfait 1.0.0:
+
+Error: X Resource Leak
+   Leaked X Resource pix
+        at line 62 of CrBFData.c in function 'XCreateBitmapFromData'.
+          pix initialized at line 60 with XCreatePixmap
+Error: X Resource Leak
+   Leaked X Resource pix
+        at line 70 of CrPFBData.c in function 'XCreatePixmapFromBitmapData'.
+          pix initialized at line 66 with XCreatePixmap
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Aaron Plattner <[email protected]>
+---
+ src/CrBFData.c  |    7 +++++--
+ src/CrPFBData.c |    7 +++++--
+ 2 files changed, 10 insertions(+), 4 deletions(-)
+
+diff --git a/src/CrBFData.c b/src/CrBFData.c
+index 4490956..9515875 100644
+--- a/src/CrBFData.c
++++ b/src/CrBFData.c
+@@ -58,8 +58,11 @@ Pixmap XCreateBitmapFromData(
+     Pixmap pix;
+ 
+     pix = XCreatePixmap(display, d, width, height, 1);
+-    if (! (gc = XCreateGC(display, pix, (unsigned long) 0, (XGCValues *) 0)))
+-	return (Pixmap) None;
++    gc = XCreateGC(display, pix, (unsigned long) 0, (XGCValues *) 0);
++    if (gc == NULL) {
++        XFreePixmap(display, pix);
++        return (Pixmap) None;
++    }
+     ximage.height = height;
+     ximage.width = width;
+     ximage.depth = 1;
+diff --git a/src/CrPFBData.c b/src/CrPFBData.c
+index 57cd153..d343420 100644
+--- a/src/CrPFBData.c
++++ b/src/CrPFBData.c
+@@ -66,8 +66,11 @@ Pixmap XCreatePixmapFromBitmapData(
+     pix = XCreatePixmap(display, d, width, height, depth);
+     gcv.foreground = fg;
+     gcv.background = bg;
+-    if (! (gc = XCreateGC(display, pix, GCForeground|GCBackground, &gcv)))
+-	return (Pixmap) NULL;
++    gc = XCreateGC(display, pix, GCForeground|GCBackground, &gcv);
++    if (gc == NULL) {
++        XFreePixmap(display, pix);
++        return (Pixmap) None;
++    }
+     ximage.height = height;
+     ximage.width = width;
+     ximage.depth = 1;
+-- 
+1.7.9.2
+
+From 65358ea5079236b2508f787ac2fb2024a477e36d Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 29 Jun 2012 23:08:04 -0700
+Subject: [PATCH:libX11 03/58] Convert XCreate{Pix,Bit}map...Data to use C99
+ designated initializers
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/CrBFData.c  |   42 ++++++++++++++++++++----------------------
+ src/CrPFBData.c |   49 ++++++++++++++++++++++++-------------------------
+ 2 files changed, 44 insertions(+), 47 deletions(-)
+
+diff --git a/src/CrBFData.c b/src/CrBFData.c
+index 9515875..6708a9b 100644
+--- a/src/CrBFData.c
++++ b/src/CrBFData.c
+@@ -53,30 +53,28 @@ Pixmap XCreateBitmapFromData(
+      unsigned int width,
+      unsigned int height)
+ {
+-    XImage ximage;
+-    GC gc;
+-    Pixmap pix;
+-
+-    pix = XCreatePixmap(display, d, width, height, 1);
+-    gc = XCreateGC(display, pix, (unsigned long) 0, (XGCValues *) 0);
++    Pixmap pix = XCreatePixmap(display, d, width, height, 1);
++    GC gc = XCreateGC(display, pix, (unsigned long) 0, (XGCValues *) 0);
+     if (gc == NULL) {
+         XFreePixmap(display, pix);
+         return (Pixmap) None;
++    } else {
++        XImage ximage = {
++            .height = height,
++            .width = width,
++            .depth = 1,
++            .bits_per_pixel = 1,
++            .xoffset = 0,
++            .format = XYPixmap,
++            .data = (char *) data,
++            .byte_order = LSBFirst,
++            .bitmap_unit = 8,
++            .bitmap_bit_order = LSBFirst,
++            .bitmap_pad = 8,
++            .bytes_per_line = (width + 7) / 8,
++        };
++        XPutImage(display, pix, gc, &ximage, 0, 0, 0, 0, width, height);
++        XFreeGC(display, gc);
++        return(pix);
+     }
+-    ximage.height = height;
+-    ximage.width = width;
+-    ximage.depth = 1;
+-    ximage.bits_per_pixel = 1;
+-    ximage.xoffset = 0;
+-    ximage.format = XYPixmap;
+-    ximage.data = (char *)data;
+-    ximage.byte_order = LSBFirst;
+-    ximage.bitmap_unit = 8;
+-    ximage.bitmap_bit_order = LSBFirst;
+-    ximage.bitmap_pad = 8;
+-    ximage.bytes_per_line = (width+7)/8;
+-
+-    XPutImage(display, pix, gc, &ximage, 0, 0, 0, 0, width, height);
+-    XFreeGC(display, gc);
+-    return(pix);
+ }
+diff --git a/src/CrPFBData.c b/src/CrPFBData.c
+index d343420..17d551b 100644
+--- a/src/CrPFBData.c
++++ b/src/CrPFBData.c
+@@ -58,33 +58,32 @@ Pixmap XCreatePixmapFromBitmapData(
+     unsigned long bg,
+     unsigned int depth)
+ {
+-    XImage ximage;
+-    GC gc;
+-    XGCValues gcv;
+-    Pixmap pix;
+-
+-    pix = XCreatePixmap(display, d, width, height, depth);
+-    gcv.foreground = fg;
+-    gcv.background = bg;
+-    gc = XCreateGC(display, pix, GCForeground|GCBackground, &gcv);
++    Pixmap pix = XCreatePixmap(display, d, width, height, depth);
++    XGCValues gcv = {
++        .foreground = fg,
++        .background = bg
++    };
++    GC gc = XCreateGC(display, pix, GCForeground|GCBackground, &gcv);
+     if (gc == NULL) {
+         XFreePixmap(display, pix);
+         return (Pixmap) None;
++    } else {
++        XImage ximage = {
++            .height = height,
++            .width = width,
++            .depth = 1,
++            .bits_per_pixel = 1,
++            .xoffset = 0,
++            .format = XYBitmap,
++            .data = data,
++            .byte_order = LSBFirst,
++            .bitmap_unit = 8,
++            .bitmap_bit_order = LSBFirst,
++            .bitmap_pad = 8,
++            .bytes_per_line = (width + 7) / 8
++        };
++        XPutImage(display, pix, gc, &ximage, 0, 0, 0, 0, width, height);
++        XFreeGC(display, gc);
++        return(pix);
+     }
+-    ximage.height = height;
+-    ximage.width = width;
+-    ximage.depth = 1;
+-    ximage.bits_per_pixel = 1;
+-    ximage.xoffset = 0;
+-    ximage.format = XYBitmap;
+-    ximage.data = data;
+-    ximage.byte_order = LSBFirst;
+-    ximage.bitmap_unit = 8;
+-    ximage.bitmap_bit_order = LSBFirst;
+-    ximage.bitmap_pad = 8;
+-    ximage.bytes_per_line = (width+7)/8;
+-
+-    XPutImage(display, pix, gc, &ximage, 0, 0, 0, 0, width, height);
+-    XFreeGC(display, gc);
+-    return(pix);
+ }
+-- 
+1.7.9.2
+
+From 59c9ee8cd58857c5769b643611cbe526005a9e45 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sun, 16 Dec 2012 17:44:42 -0800
+Subject: [PATCH:libX11 31/58] Tell clang not to report -Wpadded warnings on
+ public headers we can't fix
+
+Better to silence the compiler warning than break ABI.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ include/X11/Xcms.h    |   12 ++++++++++++
+ include/X11/Xlib.h    |   12 ++++++++++++
+ include/X11/Xlibint.h |   12 ++++++++++++
+ include/X11/Xutil.h   |   12 ++++++++++++
+ 4 files changed, 48 insertions(+)
+
+diff --git a/include/X11/Xcms.h b/include/X11/Xcms.h
+index 8151fd1..6631854 100644
+--- a/include/X11/Xcms.h
++++ b/include/X11/Xcms.h
+@@ -31,6 +31,14 @@
+ 
+ #include <X11/Xlib.h>
+ 
++/* The Xcms structs are full of implicit padding to properly align members.
++   We can't clean that up without breaking ABI, so tell clang not to bother
++   complaining about it. */
++#ifdef __clang__
++#pragma clang diagnostic push
++#pragma clang diagnostic ignored "-Wpadded"
++#endif
++
+     /*
+      * XCMS Status Values
+      */
+@@ -798,6 +806,10 @@ extern Visual *XcmsVisualOfCCC (
+     XcmsCCC		/* ccc */
+ );
+ 
++#ifdef __clang__
++#pragma clang diagnostic pop
++#endif
++
+ _XFUNCPROTOEND
+ 
+ #endif /* _X11_XCMS_H_ */
+diff --git a/include/X11/Xlib.h b/include/X11/Xlib.h
+index dd4c7c4..9618081 100644
+--- a/include/X11/Xlib.h
++++ b/include/X11/Xlib.h
+@@ -81,6 +81,14 @@ _Xmblen(
+    November 2000. Its presence is indicated through the following macro. */
+ #define X_HAVE_UTF8_STRING 1
+ 
++/* The Xlib structs are full of implicit padding to properly align members.
++   We can't clean that up without breaking ABI, so tell clang not to bother
++   complaining about it. */
++#ifdef __clang__
++#pragma clang diagnostic push
++#pragma clang diagnostic ignored "-Wpadded"
++#endif
++
+ typedef char *XPointer;
+ 
+ #define Bool int
+@@ -4019,6 +4027,10 @@ extern void XFreeEventData(
+     XGenericEventCookie*	/* cookie*/
+ );
+ 
++#ifdef __clang__
++#pragma clang diagnostic pop
++#endif
++
+ _XFUNCPROTOEND
+ 
+ #endif /* _X11_XLIB_H_ */
+diff --git a/include/X11/Xlibint.h b/include/X11/Xlibint.h
+index 80edeec..23e751b 100644
+--- a/include/X11/Xlibint.h
++++ b/include/X11/Xlibint.h
+@@ -42,6 +42,14 @@ from The Open Group.
+ #include <X11/Xproto.h>		/* to declare xEvent */
+ #include <X11/XlibConf.h>	/* for configured options like XTHREADS */
+ 
++/* The Xlib structs are full of implicit padding to properly align members.
++   We can't clean that up without breaking ABI, so tell clang not to bother
++   complaining about it. */
++#ifdef __clang__
++#pragma clang diagnostic push
++#pragma clang diagnostic ignored "-Wpadded"
++#endif
++
+ #ifdef WIN32
+ #define _XFlush _XFlushIt
+ #endif
+@@ -1364,6 +1372,10 @@ extern void xlocaledir(
+     int buf_len
+ );
+ 
++#ifdef __clang__
++#pragma clang diagnostic pop
++#endif
++
+ _XFUNCPROTOEND
+ 
+ #endif /* _X11_XLIBINT_H_ */
+diff --git a/include/X11/Xutil.h b/include/X11/Xutil.h
+index 8cab50e..62cdf55 100644
+--- a/include/X11/Xutil.h
++++ b/include/X11/Xutil.h
+@@ -53,6 +53,14 @@ SOFTWARE.
+ #include <X11/Xlib.h>
+ #include <X11/keysym.h>
+ 
++/* The Xlib structs are full of implicit padding to properly align members.
++   We can't clean that up without breaking ABI, so tell clang not to bother
++   complaining about it. */
++#ifdef __clang__
++#pragma clang diagnostic push
++#pragma clang diagnostic ignored "-Wpadded"
++#endif
++
+ /*
+  * Bitmask returned by XParseGeometry().  Each bit tells if the corresponding
+  * value (x, y, width, height) was found in the parsed string.
+@@ -821,6 +829,10 @@ extern int XXorRegion(
+     Region		/* dr_return */
+ );
+ 
++#ifdef __clang__
++#pragma clang diagnostic pop
++#endif
++
+ _XFUNCPROTOEND
+ 
+ #endif /* _X11_XUTIL_H_ */
+-- 
+1.7.9.2
+
+From a6e5b36a3e6d4a7a9fb4bad905ed127e67b1957e Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Wed, 26 Dec 2012 22:56:38 -0800
+Subject: [PATCH:libX11 32/58] Remove unused TLI ("STREAMSCONN") code from
+ Xlib
+
+Has never been converted to build in modular builds, so has been unusable
+since X11R7.0 release in 2005.  All known platforms with TLI/XTI support
+that X11R7 & later releases run on also have (and mostly prefer) BSD
+socket support for their networking API.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ modules/im/ximcp/imTransR.c |    3 --
+ src/globals.c               |  121 -------------------------------------------
+ src/xlibi18n/XimTrInt.h     |    2 +-
+ 3 files changed, 1 insertion(+), 125 deletions(-)
+
+diff --git a/modules/im/ximcp/imTransR.c b/modules/im/ximcp/imTransR.c
+index 1fd0088..4f843a0 100644
+--- a/modules/im/ximcp/imTransR.c
++++ b/modules/im/ximcp/imTransR.c
+@@ -69,9 +69,6 @@ TransportSW _XimTransportRec[] = {
+ #ifdef DNETCONN
+     { "dnet",     _XimTransConf }, /* use X transport lib */
+ #endif /* DNETCONN */
+-#ifdef STREAMSCONN
+-    { "streams",    _XimTransConf }, /* use X transport lib */
+-#endif /* STREAMSCONN */
+     { (char *)NULL, (Bool (*)(Xim, char *))NULL },
+ };
+ 
+diff --git a/src/globals.c b/src/globals.c
+index 89e38a7..b7e49dd 100644
+--- a/src/globals.c
++++ b/src/globals.c
+@@ -87,127 +87,6 @@ ZEROINIT (int, _Xdebug, 0);
+ ZEROINIT (Display *, _XHeadOfDisplayList, NULL);
+ 
+ 
+-
+-#if 0
+-#ifdef STREAMSCONN
+-
+-
+-/* The following are how the Xstream connections are used:              */
+-/*      1)      Local connections over pseudo-tty ports.                */
+-/*      2)      SVR4 local connections using named streams or SVR3.2    */
+-/*              local connections using streams.                        */
+-/*      3)      SVR4 stream pipe code. This code is proprietary and     */
+-/*              the actual code is not included in the XC distribution. */
+-/*      4)      remote connections using tcp                            */
+-/*      5)      remote connections using StarLan                        */
+-
+-/*
+- * descriptor block for streams connections
+- */
+-
+-#include "Xstreams.h"
+-
+-char _XsTypeOfStream[100] = { 0 };
+-
+-extern int write();
+-extern int close();
+-#ifdef SVR4
+-extern int _XsSetupSpStream();
+-extern int _XsSetupNamedStream();
+-#endif
+-extern int _XsSetupLocalStream();
+-extern int _XsConnectLocalClient();
+-extern int _XsCallLocalServer();
+-extern int _XsReadLocalStream();
+-extern int _XsErrorCall();
+-extern int _XsWriteLocalStream();
+-extern int _XsCloseLocalStream();
+-extern int _XsSetupTliStream();
+-extern int _XsConnectTliClient();
+-extern int _XsCallTliServer();
+-extern int _XsReadTliStream();
+-extern int _XsWriteTliStream();
+-extern int _XsCloseTliStream();
+-
+-
+-Xstream _XsStream[] = {
+-
+-    {
+-	/* local connections using pseudo-ttys */
+-
+-	_XsSetupLocalStream,
+-	_XsConnectLocalClient,
+-	_XsCallLocalServer,
+-	_XsReadLocalStream,
+-	_XsErrorCall,
+-	write,
+-	close,
+-	NULL
+-    },
+-    {
+-#ifdef SVR4
+-	/* local connections using named streams */
+-
+-        _XsSetupNamedStream,
+-#else
+-	/* local connections using streams */
+-        _XsSetupLocalStream,
+-#endif
+-        _XsConnectLocalClient,
+-        _XsCallLocalServer,
+-        _XsReadLocalStream,
+-        _XsErrorCall,
+-        write,
+-        close,
+-        NULL
+-    },
+-    /* Enhanced Application Compatibility Support */
+-    {
+-#ifdef SVR4
+-	/* SVR4 stream pipe code */
+-	_XsSetupSpStream,
+-#else
+-	_XsSetupLocalStream,
+-#endif
+-	_XsConnectLocalClient,
+-	_XsCallLocalServer,
+-	_XsReadLocalStream,
+-	_XsErrorCall,
+-	write,
+-	close,
+-	NULL
+-    },
+-    /* End Enhanced Application Compatibility Support */
+-
+-    {
+-	/* remote connections using tcp */
+-        _XsSetupTliStream,
+-        _XsConnectTliClient,
+-        _XsCallTliServer,
+-        _XsReadLocalStream,
+-        _XsErrorCall,
+-	write,
+-	close,
+-	NULL
+-    },
+-    {
+-	/* remote connections using StarLan */
+-        _XsSetupTliStream,
+-        _XsConnectTliClient,
+-        _XsCallTliServer,
+-        _XsReadLocalStream,
+-        _XsErrorCall,
+-        write,
+-        close,
+-        NULL
+-    }
+-};
+-
+-
+-#endif /* STREAMSCONN */
+-#endif
+-
+-
+ #ifdef XTEST1
+ /*
+  * Stuff for input synthesis extension:
+diff --git a/src/xlibi18n/XimTrInt.h b/src/xlibi18n/XimTrInt.h
+index a08ac03..7cc9f85 100644
+--- a/src/xlibi18n/XimTrInt.h
++++ b/src/xlibi18n/XimTrInt.h
+@@ -73,7 +73,7 @@ extern Bool	_XimXConf(
+     char	*address
+ );
+ 
+-#if defined(TCPCONN) || defined(UNIXCONN) || defined(DNETCONN) || defined(STREAMSCONN)
++#if defined(TCPCONN) || defined(UNIXCONN) || defined(DNETCONN)
+ 
+ extern Bool	_XimTransConf(
+     Xim		 im,
+-- 
+1.7.9.2
+
+From 3cd974b1d4d1fa6389d3695fa9fcc0c22a51d50c Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Wed, 26 Dec 2012 22:57:39 -0800
+Subject: [PATCH:libX11 33/58] Remove unused DECnet ("DNETCONN") code from
+ Xlib
+
+Has never been converted to build in modular builds, so has been unusable
+since X11R7.0 release in 2005.  DNETCONN support was removed from xtrans
+back in 2008.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ modules/im/ximcp/imTransR.c |    3 ---
+ src/xlibi18n/XimTrInt.h     |    2 +-
+ 2 files changed, 1 insertion(+), 4 deletions(-)
+
+diff --git a/modules/im/ximcp/imTransR.c b/modules/im/ximcp/imTransR.c
+index 4f843a0..caa5309 100644
+--- a/modules/im/ximcp/imTransR.c
++++ b/modules/im/ximcp/imTransR.c
+@@ -66,9 +66,6 @@ TransportSW _XimTransportRec[] = {
+ #if defined(UNIXCONN) || defined(LOCALCONN)
+     { "local",      _XimTransConf }, /* use X transport lib */
+ #endif /* UNIXCONN */
+-#ifdef DNETCONN
+-    { "dnet",     _XimTransConf }, /* use X transport lib */
+-#endif /* DNETCONN */
+     { (char *)NULL, (Bool (*)(Xim, char *))NULL },
+ };
+ 
+diff --git a/src/xlibi18n/XimTrInt.h b/src/xlibi18n/XimTrInt.h
+index 7cc9f85..bceab98 100644
+--- a/src/xlibi18n/XimTrInt.h
++++ b/src/xlibi18n/XimTrInt.h
+@@ -73,7 +73,7 @@ extern Bool	_XimXConf(
+     char	*address
+ );
+ 
+-#if defined(TCPCONN) || defined(UNIXCONN) || defined(DNETCONN)
++#if defined(TCPCONN) || defined(UNIXCONN)
+ 
+ extern Bool	_XimTransConf(
+     Xim		 im,
+-- 
+1.7.9.2
+
+From deedeada53676ee529d700bf96fde0b29a3a1def Mon Sep 17 00:00:00 2001
+From: Nickolai Zeldovich <[email protected]>
+Date: Tue, 22 Jan 2013 10:03:00 -0500
+Subject: [PATCH:libX11 36/58] XListFontsWithInfo: avoid accessing realloc'ed
+ memory
+
+If exactly one of the two reallocs in XListFontsWithInfo() fails, the
+subsequent code accesses memory freed by the other realloc.
+
+Signed-off-by: Nickolai Zeldovich <[email protected]>
+Reviewed-by: Alan Coopersmith <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/FontInfo.c |   13 +++++++------
+ 1 file changed, 7 insertions(+), 6 deletions(-)
+
+diff --git a/src/FontInfo.c b/src/FontInfo.c
+index a3ab65b..97de40e 100644
+--- a/src/FontInfo.c
++++ b/src/FontInfo.c
+@@ -90,6 +90,11 @@ XFontStruct **info)	/* RETURN */
+ 		    Xrealloc ((char *) flist,
+ 			      (unsigned) (sizeof(char *) * (size+1)));
+ 
++		if (tmp_finfo)
++		    finfo = tmp_finfo;
++		if (tmp_flist)
++		    flist = tmp_flist;
++
+ 		if ((! tmp_finfo) || (! tmp_flist)) {
+ 		    /* free all the memory that we allocated */
+ 		    for (j=(i-1); (j >= 0); j--) {
+@@ -97,14 +102,10 @@ XFontStruct **info)	/* RETURN */
+ 			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);
++		    Xfree((char *) flist);
++		    Xfree((char *) finfo);
+ 		    goto clearwire;
+ 		}
+-		finfo = tmp_finfo;
+-		flist = tmp_flist;
+ 	    }
+ 	    else {
+ 		if (! (finfo = (XFontStruct *)
+-- 
+1.7.9.2
+
+From 54527eab93d46055cf11eb6c18abb353a03ae544 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 15 Feb 2013 22:45:19 -0800
+Subject: [PATCH:libX11 37/58] cmsColNm.c: maintain constness of arguments to
+ qsort helper function
+
+Fixes gcc warning:
+
+cmsColNm.c: In function 'FirstCmp':
+cmsColNm.c:257:20: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+cmsColNm.c:257:45: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/xcms/cmsColNm.c |    2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/src/xcms/cmsColNm.c b/src/xcms/cmsColNm.c
+index 73977e5..a6749c0 100644
+--- a/src/xcms/cmsColNm.c
++++ b/src/xcms/cmsColNm.c
+@@ -254,7 +254,7 @@ FirstCmp(const void *p1, const void *p2)
+  *
+  */
+ {
+-    return(strcmp(((XcmsPair *)p1)->first, ((XcmsPair *)p2)->first));
++    return(strcmp(((const XcmsPair *)p1)->first, ((const XcmsPair *)p2)->first));
+ }
+ 
+ 
+-- 
+1.7.9.2
+
+From 7e3bf4dd83fec22bd568146de75e6d59eff74e21 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 15 Feb 2013 23:14:40 -0800
+Subject: [PATCH:libX11 38/58] XRebindKeysym: Drop unnecessary const-removing
+ cast
+
+C89 defines memcpy as taking a const void *, so casting from
+const unsigned char * to char * simply angers gcc for no benefit:
+
+KeyBind.c:1017:24: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/KeyBind.c |    2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/src/KeyBind.c b/src/KeyBind.c
+index 221cedd..f22feca 100644
+--- a/src/KeyBind.c
++++ b/src/KeyBind.c
+@@ -1014,7 +1014,7 @@ XRebindKeysym (
+     dpy->key_bindings = p;
+     dpy->free_funcs->key_bindings = _XFreeKeyBindings;
+     p->next = tmp;	/* chain onto list */
+-    memcpy (p->string, (char *) str, nbytes);
++    memcpy (p->string, str, nbytes);
+     p->len = nbytes;
+     memcpy ((char *) p->modifiers, (char *) mlist, nb);
+     p->key = keysym;
+-- 
+1.7.9.2
+
+From afd6593da90e51234d59f8921c411317f91ab48b Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 15 Feb 2013 23:25:38 -0800
+Subject: [PATCH:libX11 39/58] XStringToKeysym: preserve constness when
+ casting off unsignedness for strcmp
+
+Fixes gcc warning:
+StrKeysym.c:97:17: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/StrKeysym.c |    2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/src/StrKeysym.c b/src/StrKeysym.c
+index 4394e0c..12fce68 100644
+--- a/src/StrKeysym.c
++++ b/src/StrKeysym.c
+@@ -94,7 +94,7 @@ XStringToKeysym(_Xconst char *s)
+     {
+ 	entry = &_XkeyTable[idx];
+ 	if ((entry[0] == sig1) && (entry[1] == sig2) &&
+-	    !strcmp(s, (char *)entry + 6))
++	    !strcmp(s, (const char *)entry + 6))
+ 	{
+ 	    val = (entry[2] << 24) | (entry[3] << 16) |
+ 	          (entry[4] << 8)  | entry[5];
+-- 
+1.7.9.2
+
+From 6c558ee357292dd9dfc6d9006f4525f625327c52 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 15 Feb 2013 22:58:54 -0800
+Subject: [PATCH:libX11 40/58] Fix comment typo & confusing indentation levels
+ in Data() macro definition
+
+The final } matches the one on the #define line, not one that doesn't
+appear after the else statement it was lined up with
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ include/X11/Xlibint.h |    4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/include/X11/Xlibint.h b/include/X11/Xlibint.h
+index 23e751b..7911fd7 100644
+--- a/include/X11/Xlibint.h
++++ b/include/X11/Xlibint.h
+@@ -574,7 +574,7 @@ extern void _XFlushGCCache(Display *dpy, GC gc);
+  * 32 bit word alignment.  Transmit if the buffer fills.
+  *
+  * "dpy" is a pointer to a Display.
+- * "data" is a pinter to a data buffer.
++ * "data" is a pointer to a data buffer.
+  * "len" is the length of the data buffer.
+  */
+ #ifndef DataRoutineIsProcedure
+@@ -584,7 +584,7 @@ extern void _XFlushGCCache(Display *dpy, GC gc);
+ 		dpy->bufptr += ((len) + 3) & ~3;\
+ 	} else\
+ 		_XSend(dpy, data, len);\
+-	}
++}
+ #endif /* DataRoutineIsProcedure */
+ 
+ 
+-- 
+1.7.9.2
+
+From f0b171c8ea7b055ba520272ea9a2604e18841ac7 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 15 Feb 2013 23:34:40 -0800
+Subject: [PATCH:libX11 41/58] Preserve constness in casting arguments through
+ the Data*() routines
+
+Casts were annoying gcc by dropping constness when changing types,
+when routines simply either copy data into the request buffer or
+send it directly to the X server, and never modify the input.
+
+Fixes gcc warnings including:
+ChProp.c: In function 'XChangeProperty':
+ChProp.c:65:6: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+ChProp.c:65:6: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+ChProp.c:74:6: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+ChProp.c:74:6: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+ChProp.c:83:6: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+SetHints.c: In function 'XSetStandardProperties':
+SetHints.c:262:20: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+SetPntMap.c: In function 'XSetPointerMapping':
+SetPntMap.c:46:5: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+SetPntMap.c:46:5: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+StBytes.c: In function 'XStoreBuffer':
+StBytes.c:97:33: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+StName.c: In function 'XStoreName':
+StName.c:40:27: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+StName.c: In function 'XSetIconName':
+StName.c:51:27: warning: cast discards '__attribute__((const))' qualifier from pointer target type [-Wcast-qual]
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ include/X11/Xlibint.h |   12 ++++++------
+ src/ChProp.c          |    6 +++---
+ src/SetHints.c        |    4 +++-
+ src/SetPntMap.c       |    2 +-
+ src/StBytes.c         |    2 +-
+ src/StName.c          |    6 +++---
+ src/XlibInt.c         |   12 ++++++------
+ 7 files changed, 23 insertions(+), 21 deletions(-)
+
+diff --git a/include/X11/Xlibint.h b/include/X11/Xlibint.h
+index 7911fd7..c2232de 100644
+--- a/include/X11/Xlibint.h
++++ b/include/X11/Xlibint.h
+@@ -610,17 +610,17 @@ extern void _XFlushGCCache(Display *dpy, GC gc);
+     dpy->bufptr += (n);
+ 
+ #ifdef WORD64
+-#define Data16(dpy, data, len) _XData16(dpy, (short *)data, len)
+-#define Data32(dpy, data, len) _XData32(dpy, (long *)data, len)
++#define Data16(dpy, data, len) _XData16(dpy, (_Xconst short *)data, len)
++#define Data32(dpy, data, len) _XData32(dpy, (_Xconst long *)data, len)
+ #else
+-#define Data16(dpy, data, len) Data((dpy), (char *)(data), (len))
++#define Data16(dpy, data, len) Data((dpy), (_Xconst char *)(data), (len))
+ #define _XRead16Pad(dpy, data, len) _XReadPad((dpy), (char *)(data), (len))
+ #define _XRead16(dpy, data, len) _XRead((dpy), (char *)(data), (len))
+ #ifdef LONG64
+-#define Data32(dpy, data, len) _XData32(dpy, (long *)data, len)
++#define Data32(dpy, data, len) _XData32(dpy, (_Xconst long *)data, len)
+ extern int _XData32(
+ 	     Display *dpy,
+-	     register long *data,
++	     register _Xconst long *data,
+ 	     unsigned len
+ );
+ extern void _XRead32(
+@@ -629,7 +629,7 @@ extern void _XRead32(
+ 	     long len
+ );
+ #else
+-#define Data32(dpy, data, len) Data((dpy), (char *)(data), (len))
++#define Data32(dpy, data, len) Data((dpy), (_Xconst char *)(data), (len))
+ #define _XRead32(dpy, data, len) _XRead((dpy), (char *)(data), (len))
+ #endif
+ #endif /* not WORD64 */
+diff --git a/src/ChProp.c b/src/ChProp.c
+index b957751..190a224 100644
+--- a/src/ChProp.c
++++ b/src/ChProp.c
+@@ -62,7 +62,7 @@ XChangeProperty (
+ 	len = ((long)nelements + 3)>>2;
+ 	if (dpy->bigreq_size || req->length + len <= (unsigned) 65535) {
+ 	    SetReqLen(req, len, len);
+-	    Data (dpy, (char *)data, nelements);
++	    Data (dpy, (_Xconst char *)data, nelements);
+ 	} /* else force BadLength */
+         break;
+ 
+@@ -71,7 +71,7 @@ XChangeProperty (
+ 	if (dpy->bigreq_size || req->length + len <= (unsigned) 65535) {
+ 	    SetReqLen(req, len, len);
+ 	    len = (long)nelements << 1;
+-	    Data16 (dpy, (short *) data, len);
++	    Data16 (dpy, (_Xconst short *) data, len);
+ 	} /* else force BadLength */
+ 	break;
+ 
+@@ -80,7 +80,7 @@ XChangeProperty (
+ 	if (dpy->bigreq_size || req->length + len <= (unsigned) 65535) {
+ 	    SetReqLen(req, len, len);
+ 	    len = (long)nelements << 2;
+-	    Data32 (dpy, (long *) data, len);
++	    Data32 (dpy, (_Xconst long *) data, len);
+ 	} /* else force BadLength */
+ 	break;
+ 
+diff --git a/src/SetHints.c b/src/SetHints.c
+index 0c33f59..1cde48f 100644
+--- a/src/SetHints.c
++++ b/src/SetHints.c
+@@ -259,7 +259,9 @@ XSetStandardProperties (
+ 
+ 	if (icon_string != NULL) {
+ 	    XChangeProperty (dpy, w, XA_WM_ICON_NAME, XA_STRING, 8,
+-		PropModeReplace, (unsigned char *)icon_string, safestrlen(icon_string));
++                             PropModeReplace,
++                             (_Xconst unsigned char *)icon_string,
++                             safestrlen(icon_string));
+ 		}
+ 
+ 	if (icon_pixmap != None) {
+diff --git a/src/SetPntMap.c b/src/SetPntMap.c
+index 2e29201..14e104d 100644
+--- a/src/SetPntMap.c
++++ b/src/SetPntMap.c
+@@ -43,7 +43,7 @@ XSetPointerMapping (
+     GetReq (SetPointerMapping, req);
+     req->nElts = nmaps;
+     req->length += (nmaps + 3)>>2;
+-    Data (dpy, (char *)map, (long) nmaps);
++    Data (dpy, (_Xconst char *)map, (long) nmaps);
+     if (_XReply (dpy, (xReply *)&rep, 0, xFalse) == 0)
+ 	rep.success = MappingSuccess;
+     UnlockDisplay(dpy);
+diff --git a/src/StBytes.c b/src/StBytes.c
+index 13ac879..07ee441 100644
+--- a/src/StBytes.c
++++ b/src/StBytes.c
+@@ -94,7 +94,7 @@ XStoreBuffer (
+ {
+     if ((buffer < 0) || (buffer > 7)) return 0;
+     return XChangeProperty(dpy, RootWindow(dpy, 0), n_to_atom[buffer],
+-	XA_STRING, 8, PropModeReplace, (unsigned char *) bytes, nbytes);
++	XA_STRING, 8, PropModeReplace, (_Xconst unsigned char *) bytes, nbytes);
+ }
+ 
+ int
+diff --git a/src/StName.c b/src/StName.c
+index fb1e6f5..b4048bf 100644
+--- a/src/StName.c
++++ b/src/StName.c
+@@ -37,7 +37,7 @@ XStoreName (
+     _Xconst char *name)
+ {
+     return XChangeProperty(dpy, w, XA_WM_NAME, XA_STRING,
+-			   8, PropModeReplace, (unsigned char *)name,
++			   8, PropModeReplace, (_Xconst unsigned char *)name,
+ 			   name ? strlen(name) : 0);
+ }
+ 
+@@ -47,7 +47,7 @@ XSetIconName (
+     Window w,
+     _Xconst char *icon_name)
+ {
+-    return XChangeProperty(dpy, w, XA_WM_ICON_NAME, XA_STRING,
+-			   8, PropModeReplace, (unsigned char *)icon_name,
++    return XChangeProperty(dpy, w, XA_WM_ICON_NAME, XA_STRING, 8,
++                           PropModeReplace, (_Xconst unsigned char *)icon_name,
+ 			   icon_name ? strlen(icon_name) : 0);
+ }
+diff --git a/src/XlibInt.c b/src/XlibInt.c
+index 2827c10..e4d35fd 100644
+--- a/src/XlibInt.c
++++ b/src/XlibInt.c
+@@ -1722,7 +1722,7 @@ void _Xbcopy(b1, b2, length)
+ #ifdef DataRoutineIsProcedure
+ void Data(
+ 	Display *dpy,
+-	char *data,
++	_Xconst char *data,
+ 	long len)
+ {
+ 	if (dpy->bufptr + (len) <= dpy->bufmax) {
+@@ -1739,7 +1739,7 @@ void Data(
+ int
+ _XData32(
+     Display *dpy,
+-    register long *data,
++    register _Xconst long *data,
+     unsigned len)
+ {
+     register int *buf;
+@@ -1781,7 +1781,7 @@ _XData32(
+ 
+ static doData16(
+     register Display *dpy,
+-    short *data,
++    _Xconst short *data,
+     unsigned len,
+     char *packbuffer)
+ {
+@@ -1814,7 +1814,7 @@ static doData16(
+ 
+ _XData16 (
+     Display *dpy,
+-    short *data,
++    _Xconst short *data,
+     unsigned len)
+ {
+     char packbuffer[PACKBUFFERSIZE];
+@@ -1836,7 +1836,7 @@ _XData16 (
+ 
+ static doData32(
+     register Display *dpy
+-    long *data,
++    _Xconst long *data,
+     unsigned len,
+     char *packbuffer)
+ {
+@@ -1867,7 +1867,7 @@ static doData32(
+ 
+ void _XData32(
+     Display *dpy,
+-    long *data,
++    _Xconst long *data,
+     unsigned len)
+ {
+     char packbuffer[PACKBUFFERSIZE];
+-- 
+1.7.9.2
+
+From b092dabbd712d7b656abcf572d253b9b206c0237 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 15 Feb 2013 23:43:12 -0800
+Subject: [PATCH:libX11 42/58] XKeysymToString: move variable declarations to
+ the scope of their usage
+
+Makes it easier for readers to understand scope of variable usage, and
+clears up gcc warning:
+
+KeysymStr.c: In function 'XKeysymToString':
+KeysymStr.c:128:13: warning: declaration of 'i' shadows a previous local [-Wshadow]
+KeysymStr.c:73:18: warning: shadowed declaration is here [-Wshadow]
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/KeysymStr.c |   24 ++++++++++--------------
+ 1 file changed, 10 insertions(+), 14 deletions(-)
+
+diff --git a/src/KeysymStr.c b/src/KeysymStr.c
+index 101f297..f24f3b1 100644
+--- a/src/KeysymStr.c
++++ b/src/KeysymStr.c
+@@ -70,11 +70,6 @@ SameValue(
+ 
+ char *XKeysymToString(KeySym ks)
+ {
+-    register int i, n;
+-    int h;
+-    register int idx;
+-    const unsigned char *entry;
+-    unsigned char val1, val2, val3, val4;
+     XrmDatabase keysymdb;
+ 
+     if (!ks || (ks & ((unsigned long) ~0x1fffffff)) != 0)
+@@ -83,16 +78,17 @@ char *XKeysymToString(KeySym ks)
+ 	ks = 0;
+     if (ks <= 0x1fffffff)
+     {
+-	val1 = ks >> 24;
+-	val2 = (ks >> 16) & 0xff;
+-	val3 = (ks >> 8) & 0xff;
+-	val4 = ks & 0xff;
+-	i = ks % VTABLESIZE;
+-	h = i + 1;
+-	n = VMAXHASH;
++	unsigned char val1 = ks >> 24;
++	unsigned char val2 = (ks >> 16) & 0xff;
++	unsigned char val3 = (ks >> 8) & 0xff;
++	unsigned char val4 = ks & 0xff;
++	int i = ks % VTABLESIZE;
++	int h = i + 1;
++	int n = VMAXHASH;
++	int idx;
+ 	while ((idx = hashKeysym[i]))
+ 	{
+-	    entry = &_XkeyTable[idx];
++	    const unsigned char *entry = &_XkeyTable[idx];
+ 	    if ((entry[0] == val1) && (entry[1] == val2) &&
+                 (entry[2] == val3) && (entry[3] == val4))
+ 		return ((char *)entry + 4);
+@@ -136,7 +132,7 @@ char *XKeysymToString(KeySym ks)
+         i--;
+         s[i--] = '\0';
+         for (; i; i--){
+-            val1 = val & 0xf;
++            unsigned char val1 = val & 0xf;
+             val >>= 4;
+             if (val1 < 10)
+                 s[i] = '0'+ val1;
+-- 
+1.7.9.2
+
+From b687440c28c7da6ee0ae44514d20248db5161606 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 16 Feb 2013 10:42:23 -0800
+Subject: [PATCH:libX11 43/58] Convert more sprintf calls to snprintf
+
+You could analyze most of these and quickly recognize that there was no
+chance of buffer overflow already, but why make everyone spend time doing
+that when we can just make it obviously safe?
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/ErrDes.c    |    9 +++++----
+ src/GetDflt.c   |    2 +-
+ src/KeysymStr.c |    2 +-
+ src/XlibInt.c   |    8 ++++----
+ 4 files changed, 11 insertions(+), 10 deletions(-)
+
+diff --git a/src/ErrDes.c b/src/ErrDes.c
+index 9a5b180..ef5edad 100644
+--- a/src/ErrDes.c
++++ b/src/ErrDes.c
+@@ -109,7 +109,7 @@ XGetErrorText(
+ 
+     if (nbytes == 0) return 0;
+     if (code <= BadImplementation && code > 0) {
+-	sprintf(buf, "%d", code);
++        snprintf(buf, sizeof(buf), "%d", code);
+         (void) XGetErrorDatabaseText(dpy, "XProtoError", buf,
+                                      _XErrorList + _XErrorOffsets[code],
+ 				     buffer, nbytes);
+@@ -125,11 +125,12 @@ XGetErrorText(
+ 	    bext = ext;
+     }
+     if (!buffer[0] && bext) {
+-	sprintf(buf, "%s.%d", bext->name, code - bext->codes.first_error);
++	snprintf(buf, sizeof(buf), "%s.%d",
++                 bext->name, code - bext->codes.first_error);
+ 	(void) XGetErrorDatabaseText(dpy, "XProtoError", buf, "", buffer, nbytes);
+     }
+     if (!buffer[0])
+-	sprintf(buffer, "%d", code);
++	snprintf(buffer, nbytes, "%d", code);
+     return 0;
+ }
+ 
+@@ -190,7 +191,7 @@ XGetErrorDatabaseText(
+ 	else
+ 	    tptr = Xmalloc (tlen);
+ 	if (tptr) {
+-	    sprintf(tptr, "%s.%s", name, type);
++	    snprintf(tptr, tlen, "%s.%s", name, type);
+ 	    XrmGetResource(db, tptr, "ErrorType.ErrorNumber",
+ 	      &type_str, &result);
+ 	    if (tptr != temp)
+diff --git a/src/GetDflt.c b/src/GetDflt.c
+index dfda1c6..6f62cd8 100644
+--- a/src/GetDflt.c
++++ b/src/GetDflt.c
+@@ -110,7 +110,7 @@ GetHomeDir(
+ 	len2 = strlen (ptr2);
+     }
+     if ((len1 + len2 + 1) < len)
+-	sprintf (dest, "%s%s", ptr1, (ptr2) ? ptr2 : "");
++	snprintf (dest, len, "%s%s", ptr1, (ptr2) ? ptr2 : "");
+     else
+ 	*dest = '\0';
+ #else
+diff --git a/src/KeysymStr.c b/src/KeysymStr.c
+index f24f3b1..c7c4704 100644
+--- a/src/KeysymStr.c
++++ b/src/KeysymStr.c
+@@ -107,7 +107,7 @@ char *XKeysymToString(KeySym ks)
+ 	XrmQuark empty = NULLQUARK;
+ 	GRNData data;
+ 
+-	sprintf(buf, "%lX", ks);
++	snprintf(buf, sizeof(buf), "%lX", ks);
+ 	resval.addr = (XPointer)buf;
+ 	resval.size = strlen(buf) + 1;
+ 	data.name = (char *)NULL;
+diff --git a/src/XlibInt.c b/src/XlibInt.c
+index e4d35fd..c436842 100644
+--- a/src/XlibInt.c
++++ b/src/XlibInt.c
+@@ -1432,7 +1432,7 @@ static int _XPrintDefaultError(
+ 	mesg, BUFSIZ);
+     (void) fprintf(fp, mesg, event->request_code);
+     if (event->request_code < 128) {
+-	sprintf(number, "%d", event->request_code);
++	snprintf(number, sizeof(number), "%d", event->request_code);
+ 	XGetErrorDatabaseText(dpy, "XRequest", number, "", buffer, BUFSIZ);
+     } else {
+ 	for (ext = dpy->ext_procs;
+@@ -1452,7 +1452,7 @@ static int _XPrintDefaultError(
+ 	fputs("  ", fp);
+ 	(void) fprintf(fp, mesg, event->minor_code);
+ 	if (ext) {
+-	    sprintf(mesg, "%s.%d", ext->name, event->minor_code);
++	    snprintf(mesg, sizeof(mesg), "%s.%d", ext->name, event->minor_code);
+ 	    XGetErrorDatabaseText(dpy, "XRequest", mesg, "", buffer, BUFSIZ);
+ 	    (void) fprintf(fp, " (%s)", buffer);
+ 	}
+@@ -1475,8 +1475,8 @@ static int _XPrintDefaultError(
+ 		bext = ext;
+ 	}
+ 	if (bext)
+-	    sprintf(buffer, "%s.%d", bext->name,
+-		    event->error_code - bext->codes.first_error);
++	    snprintf(buffer, sizeof(buffer), "%s.%d", bext->name,
++                     event->error_code - bext->codes.first_error);
+ 	else
+ 	    strcpy(buffer, "Value");
+ 	XGetErrorDatabaseText(dpy, mtype, buffer, "", mesg, BUFSIZ);
+-- 
+1.7.9.2
+
+From 9399caf2c12cbe1ed56f4f6b368c5811cb5d0458 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Thu, 28 Feb 2013 20:04:25 -0800
+Subject: [PATCH:libX11 44/58] unifdef MUSTCOPY
+
+MUSTCOPY seems to have only been defined in <X11/Xmd.h> when building for
+CRAY, to handle missing some sizes of integer type.
+
+(mostly performed with unifdef, followed by some manual cleanup of
+ spacing/indenting in the remaining code)
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ include/X11/Xlibint.h        |    9 -----
+ modules/om/generic/omXChar.c |   91 +++++-------------------------------------
+ src/ChWindow.c               |    9 -----
+ src/ConfWind.c               |   13 ------
+ src/CrWindow.c               |    9 -----
+ src/DrArc.c                  |   12 ------
+ src/DrLine.c                 |   16 --------
+ src/DrPoint.c                |   15 -------
+ src/DrRect.c                 |   16 --------
+ src/FillArc.c                |   16 --------
+ src/FillRct.c                |   15 -------
+ src/Font.c                   |   44 +-------------------
+ src/FontInfo.c               |   24 +----------
+ src/MoveWin.c                |    9 -----
+ src/PolyTxt16.c              |   23 -----------
+ src/RestackWs.c              |    9 -----
+ src/StColor.c                |   12 ------
+ src/Text16.c                 |   23 -----------
+ src/XlibAsync.c              |    5 ---
+ 19 files changed, 11 insertions(+), 359 deletions(-)
+
+diff --git a/include/X11/Xlibint.h b/include/X11/Xlibint.h
+index c2232de..5a7c0ed 100644
+--- a/include/X11/Xlibint.h
++++ b/include/X11/Xlibint.h
+@@ -701,19 +701,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;
+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/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/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/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/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/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..25e1790 100644
+--- a/src/Font.c
++++ b/src/Font.c
+@@ -32,7 +32,7 @@ authorization from the X Consortium and the XFree86 Project.
+ #endif
+ #include "Xlibint.h"
+ 
+-#if defined(XF86BIGFONT) && !defined(MUSTCOPY)
++#if defined(XF86BIGFONT)
+ #define USE_XF86BIGFONT
+ #endif
+ #ifdef USE_XF86BIGFONT
+@@ -228,31 +228,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;
+     /*
+@@ -276,7 +254,6 @@ _XQueryFont (
+      * 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);
+@@ -288,27 +265,8 @@ _XQueryFont (
+ 	    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 */
+diff --git a/src/FontInfo.c b/src/FontInfo.c
+index 97de40e..fb296b8 100644
+--- a/src/FontInfo.c
++++ b/src/FontInfo.c
+@@ -29,7 +29,7 @@ in this Software without prior written authorization from The Open Group.
+ #endif
+ #include "Xlibint.h"
+ 
+-#if defined(XF86BIGFONT) && !defined(MUSTCOPY)
++#if defined(XF86BIGFONT)
+ #define USE_XF86BIGFONT
+ #endif
+ #ifdef USE_XF86BIGFONT
+@@ -133,31 +133,9 @@ 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;
+ 	if (fs->n_properties > 0) {
+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/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/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/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/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/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 &&
+-- 
+1.7.9.2
+
+From ca106eb03e5f5468df8033300c5caae3d3c6936b Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Thu, 28 Feb 2013 20:04:25 -0800
+Subject: [PATCH:libX11 45/58] unifdef WORD64
+
+WORD64 seems to have only been defined in <X11/Xmd.h> when building for
+CRAY, to handle int being a 64-bit value (ILP64, not LP64) and having
+64-bit alignment requirements.
+
+It hadn't been fully supported even before autotooling, as can be
+seen by removed code such as:
+
+ #ifdef WORD64
+ _XkbWriteCopyData32 Not Implemented Yet for sizeof(int)==8
+ #endif
+
+(mostly performed with unifdef, followed by some manual cleanup of
+ the remaining code)
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ include/X11/Xlibint.h |   37 +-------
+ src/ImUtil.c          |   14 +--
+ src/LiHosts.c         |    7 --
+ src/Macros.c          |    5 --
+ src/Quarks.c          |    4 -
+ src/SendEvent.c       |    5 --
+ src/XlibInt.c         |  236 -------------------------------------------------
+ src/xkb/XKBNames.c    |   56 ------------
+ src/xkb/XKBRdBuf.c    |   28 ------
+ src/xkb/XKBlibint.h   |    2 +-
+ 10 files changed, 4 insertions(+), 390 deletions(-)
+
+diff --git a/include/X11/Xlibint.h b/include/X11/Xlibint.h
+index 5a7c0ed..48323f7 100644
+--- a/include/X11/Xlibint.h
++++ b/include/X11/Xlibint.h
+@@ -408,25 +408,8 @@ extern LockInfoPtr _Xglobal_lock;
+  * X Protocol packetizing macros.
+  */
+ 
+-/*   Need to start requests on 64 bit word boundaries
+- *   on a CRAY computer so add a NoOp (127) if needed.
+- *   A character pointer on a CRAY computer will be non-zero
+- *   after shifting right 61 bits of it is not pointing to
+- *   a word boundary.
+- */
+-#ifdef WORD64
+-#define WORD64ALIGN if ((long)dpy->bufptr >> 61) {\
+-           dpy->last_req = dpy->bufptr;\
+-           *(dpy->bufptr)   = X_NoOperation;\
+-           *(dpy->bufptr+1) =  0;\
+-           *(dpy->bufptr+2) =  0;\
+-           *(dpy->bufptr+3) =  1;\
+-             dpy->request++;\
+-             dpy->bufptr += 4;\
+-         }
+-#else /* else does not require alignment on 64-bit boundaries */
++/* Leftover from CRAY support - was defined empty on all non-Cray systems */
+ #define WORD64ALIGN
+-#endif /* WORD64 */
+ 
+ /**
+  * Return a len-sized request buffer for the request type. This function may
+@@ -510,18 +493,6 @@ extern void *_XGetRequest(Display *dpy, CARD8 type, size_t len);
+ 	req = (xReq *) _XGetRequest(dpy, X_/**/name, SIZEOF(xReq))
+ #endif
+ 
+-#ifdef WORD64
+-#define MakeBigReq(req,n) \
+-    { \
+-    char _BRdat[4]; \
+-    unsigned long _BRlen = req->length - 1; \
+-    req->length = 0; \
+-    memcpy(_BRdat, ((char *)req) + (_BRlen << 2), 4); \
+-    memmove(((char *)req) + 8, ((char *)req) + 4, _BRlen << 2); \
+-    memcpy(((char *)req) + 4, _BRdat, 4); \
+-    Data32(dpy, (long *)&_BRdat, 4); \
+-    }
+-#else
+ #ifdef LONG64
+ #define MakeBigReq(req,n) \
+     { \
+@@ -545,7 +516,6 @@ extern void *_XGetRequest(Display *dpy, CARD8 type, size_t len);
+     Data32(dpy, &_BRdat, 4); \
+     }
+ #endif
+-#endif
+ 
+ #ifndef __clang_analyzer__
+ #define SetReqLen(req,n,badlen) \
+@@ -609,10 +579,6 @@ extern void _XFlushGCCache(Display *dpy, GC gc);
+     memset(ptr, '\0', n); \
+     dpy->bufptr += (n);
+ 
+-#ifdef WORD64
+-#define Data16(dpy, data, len) _XData16(dpy, (_Xconst short *)data, len)
+-#define Data32(dpy, data, len) _XData32(dpy, (_Xconst long *)data, len)
+-#else
+ #define Data16(dpy, data, len) Data((dpy), (_Xconst char *)(data), (len))
+ #define _XRead16Pad(dpy, data, len) _XReadPad((dpy), (char *)(data), (len))
+ #define _XRead16(dpy, data, len) _XRead((dpy), (char *)(data), (len))
+@@ -632,7 +598,6 @@ extern void _XRead32(
+ #define Data32(dpy, data, len) Data((dpy), (_Xconst char *)(data), (len))
+ #define _XRead32(dpy, data, len) _XRead((dpy), (char *)(data), (len))
+ #endif
+-#endif /* not WORD64 */
+ 
+ #define PackData16(dpy,data,len) Data16 (dpy, data, len)
+ #define PackData32(dpy,data,len) Data32 (dpy, data, len)
+diff --git a/src/ImUtil.c b/src/ImUtil.c
+index 3164d43..fa8d464 100644
+--- a/src/ImUtil.c
++++ b/src/ImUtil.c
+@@ -528,9 +528,7 @@ static unsigned long _XGetPixel (
+ 	  return (pixel & low_bits_table[ximage->depth]);
+ }
+ 
+-#ifndef WORD64
+ static CARD32 const byteorderpixel = MSBFirst << 24;
+-#endif
+ 
+ static unsigned long _XGetPixel32 (
+     register XImage *ximage,
+@@ -543,12 +541,9 @@ static unsigned long _XGetPixel32 (
+ 	if ((ximage->format == ZPixmap) && (ximage->bits_per_pixel == 32)) {
+ 	    addr = &((unsigned char *)ximage->data)
+ 			[y * ximage->bytes_per_line + (x << 2)];
+-#ifndef WORD64
+ 	    if (*((const char *)&byteorderpixel) == ximage->byte_order)
+ 		pixel = *((CARD32 *)addr);
+-	    else
+-#endif
+-	    if (ximage->byte_order == MSBFirst)
++	    else if (ximage->byte_order == MSBFirst)
+ 		pixel = ((unsigned long)addr[0] << 24 |
+ 			 (unsigned long)addr[1] << 16 |
+ 			 (unsigned long)addr[2] << 8 |
+@@ -734,12 +729,9 @@ static int _XPutPixel32 (
+ 	if ((ximage->format == ZPixmap) && (ximage->bits_per_pixel == 32)) {
+ 	    addr = &((unsigned char *)ximage->data)
+ 			[y * ximage->bytes_per_line + (x << 2)];
+-#ifndef WORD64
+ 	    if (*((const char *)&byteorderpixel) == ximage->byte_order)
+ 		*((CARD32 *)addr) = pixel;
+-	    else
+-#endif
+-	    if (ximage->byte_order == MSBFirst) {
++	    else if (ximage->byte_order == MSBFirst) {
+ 		addr[0] = pixel >> 24;
+ 		addr[1] = pixel >> 16;
+ 		addr[2] = pixel >> 8;
+@@ -997,7 +989,6 @@ _XAddPixel (
+ 	    x = ximage->bytes_per_line * ximage->height;
+ 	    while (--x >= 0)
+ 		*dp++ += value;
+-#ifndef WORD64
+ 	} else if ((ximage->format == ZPixmap) &&
+ 		   (ximage->bits_per_pixel == 16) &&
+ 		   (*((const char *)&byteorderpixel) == ximage->byte_order)) {
+@@ -1012,7 +1003,6 @@ _XAddPixel (
+ 	    x = (ximage->bytes_per_line >> 2) * ximage->height;
+ 	    while (--x >= 0)
+ 		*dp++ += value;
+-#endif
+ 	} else {
+ 	    for (y = ximage->height; --y >= 0; ) {
+ 		for (x = ximage->width; --x >= 0; ) {
+diff --git a/src/LiHosts.c b/src/LiHosts.c
+index 5ae70d5..0f5e837 100644
+--- a/src/LiHosts.c
++++ b/src/LiHosts.c
+@@ -111,15 +111,8 @@ XHostAddress *XListHosts (
+ 	_XRead (dpy, (char *) buf, nbytes);
+ 
+ 	for (i = 0; i < reply.nHosts; i++) {
+-#ifdef WORD64
+-	    xHostEntry xhe;
+-	    memcpy((char *)&xhe, bp, SIZEOF(xHostEntry));
+-	    op->family = xhe.family;
+-	    op->length = xhe.length;
+-#else
+ 	    op->family = ((xHostEntry *) bp)->family;
+ 	    op->length =((xHostEntry *) bp)->length;
+-#endif
+ 	    if (op->family == FamilyServerInterpreted) {
+ 		char *tp = (char *) (bp + SIZEOF(xHostEntry));
+ 		char *vp = memchr(tp, 0, op->length);
+diff --git a/src/Macros.c b/src/Macros.c
+index 42d4cf1..cfc083a 100644
+--- a/src/Macros.c
++++ b/src/Macros.c
+@@ -137,12 +137,7 @@ int XImageByteOrder(Display *dpy) { return (ImageByteOrder(dpy)); }
+ 
+ unsigned long XNextRequest(Display *dpy)
+ {
+-#ifdef WORD64
+-    WORD64ALIGN
+-    return dpy->request + 1;
+-#else
+     return (NextRequest(dpy));
+-#endif
+ }
+ 
+ unsigned long XLastKnownRequestProcessed(Display *dpy)
+diff --git a/src/Quarks.c b/src/Quarks.c
+index 7a704b1..4eb90c5 100644
+--- a/src/Quarks.c
++++ b/src/Quarks.c
+@@ -131,10 +131,8 @@ static char *permalloc(unsigned int length)
+     return(ret);
+ }
+ 
+-#ifndef WORD64
+ typedef struct {char a; double b;} TestType1;
+ typedef struct {char a; unsigned long b;} TestType2;
+-#endif
+ 
+ #ifdef XTHREADS
+ static char *_Xpermalloc(unsigned int length);
+@@ -157,7 +155,6 @@ char *Xpermalloc(unsigned int length)
+     int i;
+ 
+     if (neverFreeTableSize && length < NEVERFREETABLESIZE) {
+-#ifndef WORD64
+ 	if ((sizeof(TestType1) !=
+ 	     (sizeof(TestType2) - sizeof(unsigned long) + sizeof(double))) &&
+ 	    !(length & (DALIGN-1)) &&
+@@ -165,7 +162,6 @@ char *Xpermalloc(unsigned int length)
+ 	    neverFreeTableSize -= DALIGN - i;
+ 	    neverFreeTable += DALIGN - i;
+ 	} else
+-#endif
+ 	    if ((i = (NEVERFREETABLESIZE - neverFreeTableSize) & (WALIGN-1))) {
+ 		neverFreeTableSize -= WALIGN - i;
+ 		neverFreeTable += WALIGN - i;
+diff --git a/src/SendEvent.c b/src/SendEvent.c
+index cc8bd5a..1de9860 100644
+--- a/src/SendEvent.c
++++ b/src/SendEvent.c
+@@ -67,12 +67,7 @@ XSendEvent(
+ 	req->destination = w;
+ 	req->propagate = propagate;
+ 	req->eventMask = event_mask;
+-#ifdef WORD64
+-	/* avoid quad-alignment problems */
+-	memcpy ((char *) req->eventdata, (char *) &ev, SIZEOF(xEvent));
+-#else
+ 	req->event = ev;
+-#endif /* WORD64 */
+     }
+ 
+     UnlockDisplay(dpy);
+diff --git a/src/XlibInt.c b/src/XlibInt.c
+index c436842..1c964fd 100644
+--- a/src/XlibInt.c
++++ b/src/XlibInt.c
+@@ -293,124 +293,6 @@ void _XRead32(
+ }
+ #endif /* LONG64 */
+ 
+-#ifdef WORD64
+-
+-/*
+- * XXX This is a *really* stupid way of doing this....
+- * PACKBUFFERSIZE must be a multiple of 4.
+- */
+-
+-#define PACKBUFFERSIZE 4096
+-
+-
+-/*
+- * _XRead32 - Read bytes from the socket unpacking each 32 bits
+- *            into a long (64 bits on a CRAY computer).
+- *
+- */
+-static void _doXRead32(
+-        register Display *dpy,
+-        register long *data
+-        register long size,
+-	register char *packbuffer)
+-{
+- long *lpack,*lp;
+- long mask32 = 0x00000000ffffffff;
+- long maskw, nwords, i, bits;
+-
+-        _XReadPad (dpy, packbuffer, size);
+-
+-        lp = data;
+-        lpack = (long *) packbuffer;
+-        nwords = size >> 2;
+-        bits = 32;
+-
+-        for(i=0;i<nwords;i++){
+-            maskw = mask32 << bits;
+-           *lp++ = ( *lpack & maskw ) >> bits;
+-            bits = bits ^32;
+-            if(bits){
+-               lpack++;
+-            }
+-        }
+-}
+-
+-void _XRead32(
+-    Display *dpy,
+-    long *data,
+-    long len)
+-{
+-    char packbuffer[PACKBUFFERSIZE];
+-    unsigned nunits = PACKBUFFERSIZE >> 2;
+-
+-    for (; len > PACKBUFFERSIZE; len -= PACKBUFFERSIZE, data += nunits) {
+-	_doXRead32 (dpy, data, PACKBUFFERSIZE, packbuffer);
+-    }
+-    if (len) _doXRead32 (dpy, data, len, packbuffer);
+-}
+-
+-
+-
+-/*
+- * _XRead16 - Read bytes from the socket unpacking each 16 bits
+- *            into a long (64 bits on a CRAY computer).
+- *
+- */
+-static _doXRead16(
+-        register Display *dpy,
+-        register short *data,
+-        register long size,
+-	char *packbuffer)
+-{
+-	long *lpack,*lp;
+-	long mask16 = 0x000000000000ffff;
+-	long maskw, nwords, i, bits;
+-
+-        (void) _XRead(dpy,packbuffer,size);	/* don't do a padded read... */
+-
+-        lp = (long *) data;
+-        lpack = (long *) packbuffer;
+-        nwords = size >> 1;  /* number of 16 bit words to be unpacked */
+-        bits = 48;
+-        for(i=0;i<nwords;i++){
+-            maskw = mask16 << bits;
+-           *lp++ = ( *lpack & maskw ) >> bits;
+-            bits -= 16;
+-            if(bits < 0){
+-               lpack++;
+-               bits = 48;
+-            }
+-        }
+-}
+-
+-void _XRead16(
+-    Display *dpy,
+-    short *data,
+-    long len)
+-{
+-    char packbuffer[PACKBUFFERSIZE];
+-    unsigned nunits = PACKBUFFERSIZE >> 1;
+-
+-    for (; len > PACKBUFFERSIZE; len -= PACKBUFFERSIZE, data += nunits) {
+-	_doXRead16 (dpy, data, PACKBUFFERSIZE, packbuffer);
+-    }
+-    if (len) _doXRead16 (dpy, data, len, packbuffer);
+-}
+-
+-void _XRead16Pad(
+-    Display *dpy,
+-    short *data,
+-    long size)
+-{
+-    int slop = (size & 3);
+-    short slopbuf[3];
+-
+-    _XRead16 (dpy, data, size);
+-    if (slop > 0) {
+-	_XRead16 (dpy, slopbuf, 4 - slop);
+-    }
+-}
+-#endif /* WORD64 */
+ 
+ /*
+  * The hard part about this is that we only get 16 bits from a reply.
+@@ -1764,122 +1646,6 @@ _XData32(
+ }
+ #endif /* LONG64 */
+ 
+-#ifdef WORD64
+-
+-/*
+- * XXX This is a *really* stupid way of doing this.  It should just use
+- * dpy->bufptr directly, taking into account where in the word it is.
+- */
+-
+-/*
+- * Data16 - Place 16 bit data in the buffer.
+- *
+- * "dpy" is a pointer to a Display.
+- * "data" is a pointer to the data.
+- * "len" is the length in bytes of the data.
+- */
+-
+-static doData16(
+-    register Display *dpy,
+-    _Xconst short *data,
+-    unsigned len,
+-    char *packbuffer)
+-{
+-    long *lp,*lpack;
+-    long i, nwords,bits;
+-    long mask16 = 0x000000000000ffff;
+-
+-        lp = (long *)data;
+-        lpack = (long *)packbuffer;
+-
+-/*  nwords is the number of 16 bit values to be packed,
+- *  the low order 16 bits of each word will be packed
+- *  into 64 bit words
+- */
+-        nwords = len >> 1;
+-        bits = 48;
+-
+-        for(i=0;i<nwords;i++){
+-	   if (bits == 48) *lpack = 0;
+-           *lpack ^= (*lp & mask16) << bits;
+-           bits -= 16 ;
+-           lp++;
+-           if(bits < 0){
+-               lpack++;
+-               bits = 48;
+-           }
+-        }
+-        Data(dpy, packbuffer, len);
+-}
+-
+-_XData16 (
+-    Display *dpy,
+-    _Xconst short *data,
+-    unsigned len)
+-{
+-    char packbuffer[PACKBUFFERSIZE];
+-    unsigned nunits = PACKBUFFERSIZE >> 1;
+-
+-    for (; len > PACKBUFFERSIZE; len -= PACKBUFFERSIZE, data += nunits) {
+-	doData16 (dpy, data, PACKBUFFERSIZE, packbuffer);
+-    }
+-    if (len) doData16 (dpy, data, len, packbuffer);
+-}
+-
+-/*
+- * Data32 - Place 32 bit data in the buffer.
+- *
+- * "dpy" is a pointer to a Display.
+- * "data" is a pointer to the data.
+- * "len" is the length in bytes of the data.
+- */
+-
+-static doData32(
+-    register Display *dpy
+-    _Xconst long *data,
+-    unsigned len,
+-    char *packbuffer)
+-{
+-    long *lp,*lpack;
+-    long i,bits,nwords;
+-    long mask32 = 0x00000000ffffffff;
+-
+-        lpack = (long *) packbuffer;
+-        lp = data;
+-
+-/*  nwords is the number of 32 bit values to be packed
+- *  the low order 32 bits of each word will be packed
+- *  into 64 bit words
+- */
+-        nwords = len >> 2;
+-        bits = 32;
+-
+-        for(i=0;i<nwords;i++){
+-	   if (bits == 32) *lpack = 0;
+-           *lpack ^= (*lp & mask32) << bits;
+-           bits = bits ^32;
+-           lp++;
+-           if(bits)
+-              lpack++;
+-        }
+-        Data(dpy, packbuffer, len);
+-}
+-
+-void _XData32(
+-    Display *dpy,
+-    _Xconst long *data,
+-    unsigned len)
+-{
+-    char packbuffer[PACKBUFFERSIZE];
+-    unsigned nunits = PACKBUFFERSIZE >> 2;
+-
+-    for (; len > PACKBUFFERSIZE; len -= PACKBUFFERSIZE, data += nunits) {
+-	doData32 (dpy, data, PACKBUFFERSIZE, packbuffer);
+-    }
+-    if (len) doData32 (dpy, data, len, packbuffer);
+-}
+-
+-#endif /* WORD64 */
+ 
+ 
+ /* Make sure this produces the same string as DefineLocal/DefineSelf in xdm.
+@@ -1967,8 +1733,6 @@ void *_XGetRequest(Display *dpy, CARD8 type, size_t len)
+ {
+     xReq *req;
+ 
+-    WORD64ALIGN
+-
+     if (dpy->bufptr + len > dpy->bufmax)
+ 	_XFlush(dpy);
+ 
+diff --git a/src/xkb/XKBNames.c b/src/xkb/XKBNames.c
+index cf2382c..0276c05 100644
+--- a/src/xkb/XKBNames.c
++++ b/src/xkb/XKBNames.c
+@@ -494,38 +494,10 @@ XkbSetNames(	Display *	dpy,
+     if (which&XkbGroupNamesMask)
+ 	_XkbCopyAtoms(dpy,names->groups,groups,XkbNumKbdGroups);
+     if (which&XkbKeyNamesMask) {
+-#ifdef WORD64
+-	char *tmp;
+-	register int i;
+-	BufAlloc(char *,tmp,nKeys*XkbKeyNameLength);
+-	for (i=0;i<nKeys;i++,tmp+= XkbKeyNameLength) {
+-	    tmp[0]= names->keys[firstKey+i].name[0];
+-	    tmp[1]= names->keys[firstKey+i].name[1];
+-	    tmp[2]= names->keys[firstKey+i].name[2];
+-	    tmp[3]= names->keys[firstKey+i].name[3];
+-	}
+-#else
+ 	Data(dpy,(char *)&names->keys[firstKey],nKeys*XkbKeyNameLength);
+-#endif
+     }
+     if (which&XkbKeyAliasesMask) {
+-#ifdef WORD64
+-	char *tmp;
+-	register int i;
+-	BufAlloc(char *,tmp,nKA*XkbKeyNameLength*2);
+-	for (i=0;i<nKeys;i++,tmp+= 2*XkbKeyNameLength) {
+-	    tmp[0]= names->key_aliases[i].real[0];
+-	    tmp[1]= names->key_aliases[i].real[1];
+-	    tmp[2]= names->key_aliases[i].real[2];
+-	    tmp[3]= names->key_aliases[i].real[3];
+-	    tmp[4]= names->key_aliases[i].alias[0];
+-	    tmp[5]= names->key_aliases[i].alias[1];
+-	    tmp[6]= names->key_aliases[i].alias[2];
+-	    tmp[7]= names->key_aliases[i].alias[3];
+-	}
+-#else
+ 	Data(dpy,(char *)names->key_aliases,nKA*XkbKeyNameLength*2);
+-#endif
+     }
+     if (which&XkbRGNamesMask) {
+ 	Data32(dpy,(long *)names->radio_groups,nRG*4);
+@@ -750,38 +722,10 @@ XkbChangeNames(Display *dpy,XkbDescPtr xkb,XkbNameChangesPtr changes)
+     if (which&XkbGroupNamesMask)
+ 	_XkbCopyAtoms(dpy,names->groups,groups,XkbNumKbdGroups);
+     if (which&XkbKeyNamesMask) {
+-#ifdef WORD64
+-	char *tmp;
+-	register int i;
+-	BufAlloc(char *,tmp,nKeys*4);
+-	for (i=0;i<nKeys;i++,tmp+= 4) {
+-	    tmp[0]= names->keys[firstKey+i].name[0];
+-	    tmp[1]= names->keys[firstKey+i].name[1];
+-	    tmp[2]= names->keys[firstKey+i].name[2];
+-	    tmp[3]= names->keys[firstKey+i].name[3];
+-	}
+-#else
+ 	Data(dpy,(char *)&names->keys[firstKey],nKeys*XkbKeyNameLength);
+-#endif
+     }
+     if (which&XkbKeyAliasesMask) {
+-#ifdef WORD64
+-	char *tmp;
+-	register int i;
+-	BufAlloc(char *,tmp,nKA*XkbKeyNameLength*2);
+-	for (i=0;i<nKeys;i++,tmp+= 2*XkbKeyNameLength) {
+-	    tmp[0]= names->key_aliases[i].real[0];
+-	    tmp[1]= names->key_aliases[i].real[1];
+-	    tmp[2]= names->key_aliases[i].real[2];
+-	    tmp[3]= names->key_aliases[i].real[3];
+-	    tmp[4]= names->key_aliases[i].alias[0];
+-	    tmp[5]= names->key_aliases[i].alias[1];
+-	    tmp[6]= names->key_aliases[i].alias[2];
+-	    tmp[7]= names->key_aliases[i].alias[3];
+-	}
+-#else
+ 	Data(dpy,(char *)names->key_aliases,nKA*XkbKeyNameLength*2);
+-#endif
+     }
+     if (which&XkbRGNamesMask) {
+ 	Data32(dpy,(long *)names->radio_groups,nRG*4);
+diff --git a/src/xkb/XKBRdBuf.c b/src/xkb/XKBRdBuf.c
+index 3023a32..bf2883a 100644
+--- a/src/xkb/XKBRdBuf.c
++++ b/src/xkb/XKBRdBuf.c
+@@ -116,30 +116,7 @@ _XkbReadCopyData32(int *wire,long *to,int num_words)
+     }
+     return 1;
+ }
+-#endif
+-#ifdef WORD64
+-int
+-_XkbReadCopyData32(int *from,long *lp,int num_words)
+-{
+-long *lpack;
+-long mask32 = 0x00000000ffffffff;
+-long maskw, i, bits;
+-
+-    lpack = (long *)from;
+-    bits = 32;
+-
+-    for (i=0;i<num_words;i++) {
+-	maskw = mask32 << bits;
+-	*lp++ = (*lpack & maskw) >> bits;
+-	bits = bits ^ 32;
+-	if (bits)
+-	    lpack++;
+-    }
+-    return 1;
+-}
+-#endif
+ 
+-#if defined(LONG64) || defined(WORD64)
+ int
+ _XkbReadBufferCopy32(XkbReadBufferPtr from,long *to,int num_words)
+ {
+@@ -149,9 +126,7 @@ _XkbReadBufferCopy32(XkbReadBufferPtr from,long *to,int num_words)
+     from->data+= (4*num_words);
+     return True;
+ }
+-#endif
+ 
+-#ifdef LONG64
+ int
+ _XkbWriteCopyData32 (register unsigned long *from,CARD32 *to,int len)
+ {
+@@ -163,9 +138,6 @@ _XkbWriteCopyData32 (register unsigned long *from,CARD32 *to,int len)
+ }
+ #endif /* LONG64 */
+ 
+-#ifdef WORD64
+-_XkbWriteCopyData32 Not Implemented Yet for sizeof(int)==8
+-#endif
+ 
+ char *
+ _XkbPeekAtReadBuffer(XkbReadBufferPtr from,int size)
+diff --git a/src/xkb/XKBlibint.h b/src/xkb/XKBlibint.h
+index ce14527..7b41c3b 100644
+--- a/src/xkb/XKBlibint.h
++++ b/src/xkb/XKBlibint.h
+@@ -213,7 +213,7 @@ extern int _XkbCopyFromReadBuffer(
+ );
+ 
+ 
+-#if defined(WORD64) || defined(LONG64)
++#ifdef LONG64
+ extern	int _XkbReadCopyData32(
+     int *		/* from */,
+     long *		/* to */,
+-- 
+1.7.9.2
+
+From 769a0efa2298040fe8316a89fc9e75fb61e288e5 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Thu, 28 Feb 2013 20:04:25 -0800
+Subject: [PATCH:libX11 46/58] unifdef CRAY & _CRAY
+
+(mostly performed with unifdef, followed by some manual cleanup of
+ the remaining code)
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ include/X11/Xlib.h    |    4 ----
+ include/X11/Xlibint.h |    7 -------
+ src/xcms/cmsTrig.c    |    4 ----
+ 3 files changed, 15 deletions(-)
+
+diff --git a/include/X11/Xlib.h b/include/X11/Xlib.h
+index 9618081..65f253c 100644
+--- a/include/X11/Xlib.h
++++ b/include/X11/Xlib.h
+@@ -128,11 +128,7 @@ typedef char *XPointer;
+ #define BitmapBitOrder(dpy) 	(((_XPrivDisplay)dpy)->bitmap_bit_order)
+ #define BitmapPad(dpy) 		(((_XPrivDisplay)dpy)->bitmap_pad)
+ #define ImageByteOrder(dpy) 	(((_XPrivDisplay)dpy)->byte_order)
+-#ifdef CRAY /* unable to get WORD64 without pulling in other symbols */
+-#define NextRequest(dpy)	XNextRequest(dpy)
+-#else
+ #define NextRequest(dpy)	(((_XPrivDisplay)dpy)->request + 1)
+-#endif
+ #define LastKnownRequestProcessed(dpy)	(((_XPrivDisplay)dpy)->last_request_read)
+ 
+ /* macros for screen oriented applications (toolkit) */
+diff --git a/include/X11/Xlibint.h b/include/X11/Xlibint.h
+index 48323f7..40965c4 100644
+--- a/include/X11/Xlibint.h
++++ b/include/X11/Xlibint.h
+@@ -209,13 +209,6 @@ struct _XDisplay
+ 
+ #define XAllocIDs(dpy,ids,n) (*(dpy)->idlist_alloc)(dpy,ids,n)
+ 
+-/*
+- * define the following if you want the Data macro to be a procedure instead
+- */
+-#ifdef CRAY
+-#define DataRoutineIsProcedure
+-#endif /* CRAY */
+-
+ #ifndef _XEVENT_
+ /*
+  * _QEvent datatype for use in input queueing.
+diff --git a/src/xcms/cmsTrig.c b/src/xcms/cmsTrig.c
+index 5a01a56..a917b78 100644
+--- a/src/xcms/cmsTrig.c
++++ b/src/xcms/cmsTrig.c
+@@ -80,12 +80,8 @@ _XcmsModuloF(
+ #define XCMS_FABS(x)		((x) < 0.0 ? -(x) : (x))
+ 
+ /* XCMS_DMAXPOWTWO - largest power of two exactly representable as a double */
+-#ifdef _CRAY
+-#define XCMS_DMAXPOWTWO	((double)(1 < 47))
+-#else
+ #define XCMS_DMAXPOWTWO	((double)(XCMS_LONG_MAX) * \
+ 	    (1L << ((XCMS_NBITS(double)-XCMS_DEXPLEN) - XCMS_NBITS(int) + 1)))
+-#endif
+ 
+ /*
+  *	LOCAL VARIABLES
+-- 
+1.7.9.2
+
+From 9bcfd84aa1410387bc8cf002a5f90f44705aa0d1 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 18:09:07 -0800
+Subject: [PATCH:libX11 47/58] unifdef XKB_IN_SERVER
+
+Leftovers from XKB files that were previously shared between the client
+and server code, but aren't any more.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/xkb/XKBAlloc.c  |   12 ------------
+ src/xkb/XKBGAlloc.c |   12 ------------
+ src/xkb/XKBMAlloc.c |   13 -------------
+ src/xkb/XKBMisc.c   |   13 -------------
+ 4 files changed, 50 deletions(-)
+
+diff --git a/src/xkb/XKBAlloc.c b/src/xkb/XKBAlloc.c
+index 05e9f73..034539b 100644
+--- a/src/xkb/XKBAlloc.c
++++ b/src/xkb/XKBAlloc.c
+@@ -30,7 +30,6 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <config.h>
+ #endif
+ 
+-#ifndef XKB_IN_SERVER
+ 
+ #include <stdio.h>
+ #include "Xlibint.h"
+@@ -39,17 +38,6 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <X11/extensions/XKBproto.h>
+ #include "XKBlibint.h"
+ 
+-#else
+-
+-#include <stdio.h>
+-#include <X11/X.h>
+-#include <X11/Xproto.h>
+-#include "misc.h"
+-#include "inputstr.h"
+-#include <X11/extensions/XKBsrv.h>
+-#include <X11/extensions/XKBgeom.h>
+-
+-#endif /* XKB_IN_SERVER */
+ 
+ /***===================================================================***/
+ 
+diff --git a/src/xkb/XKBGAlloc.c b/src/xkb/XKBGAlloc.c
+index 7679496..e55f5e8 100644
+--- a/src/xkb/XKBGAlloc.c
++++ b/src/xkb/XKBGAlloc.c
+@@ -30,7 +30,6 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <config.h>
+ #endif
+ 
+-#ifndef XKB_IN_SERVER
+ 
+ #include <stdio.h>
+ #include "Xlibint.h"
+@@ -38,17 +37,6 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <X11/extensions/XKBgeom.h>
+ #include <X11/extensions/XKBproto.h>
+ 
+-#else
+-
+-#include <stdio.h>
+-#include <X11/X.h>
+-#include <X11/Xproto.h>
+-#include "misc.h"
+-#include "inputstr.h"
+-#include <X11/extensions/XKBsrv.h>
+-#include <X11/extensions/XKBgeom.h>
+-
+-#endif /* XKB_IN_SERVER */
+ 
+ #ifdef X_NOT_POSIX
+ #define Size_t unsigned int
+diff --git a/src/xkb/XKBMAlloc.c b/src/xkb/XKBMAlloc.c
+index a6b3921..fd75f0c 100644
+--- a/src/xkb/XKBMAlloc.c
++++ b/src/xkb/XKBMAlloc.c
+@@ -30,7 +30,6 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <config.h>
+ #endif
+ 
+-#ifndef XKB_IN_SERVER
+ 
+ #include <stdio.h>
+ #include "Xlibint.h"
+@@ -38,18 +37,6 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <X11/keysym.h>
+ #include "XKBlibint.h"
+ 
+-#else
+-
+-#include <stdio.h>
+-#include <X11/X.h>
+-#include <X11/Xproto.h>
+-#include "misc.h"
+-#include "inputstr.h"
+-#include <X11/keysym.h>
+-#define	XKBSRV_NEED_FILE_FUNCS
+-#include <X11/extensions/XKBsrv.h>
+-
+-#endif /* XKB_IN_SERVER */
+ 
+ /***====================================================================***/
+ 
+diff --git a/src/xkb/XKBMisc.c b/src/xkb/XKBMisc.c
+index 4aa1f73..cd90da7 100644
+--- a/src/xkb/XKBMisc.c
++++ b/src/xkb/XKBMisc.c
+@@ -30,7 +30,6 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <config.h>
+ #endif
+ 
+-#ifndef XKB_IN_SERVER
+ 
+ #include <stdio.h>
+ #include "Xlibint.h"
+@@ -38,18 +37,6 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <X11/keysym.h>
+ #include "XKBlibint.h"
+ 
+-#else
+-
+-#include <stdio.h>
+-#include <X11/X.h>
+-#include <X11/Xproto.h>
+-#include "misc.h"
+-#include "inputstr.h"
+-#include <X11/keysym.h>
+-#define	XKBSRV_NEED_FILE_FUNCS
+-#include <X11/extensions/XKBsrv.h>
+-
+-#endif /* XKB_IN_SERVER */
+ 
+ /***====================================================================***/
+ 
+-- 
+1.7.9.2
+
+From c23d61d1b84dca3740bf4786978c7908d0065fb9 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 1 Mar 2013 18:10:27 -0800
+Subject: [PATCH:libX11 48/58] Assume size_t is always available, since it was
+ defined in C89
+
+Don't provide a fallback definition #ifdef X_NOT_POSIX anymore.
+We already use size_t throughout the rest of Xlib, just had this
+one instance left in XKBGAlloc.c of a fallback definition.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/xkb/XKBGAlloc.c |    9 +--------
+ 1 file changed, 1 insertion(+), 8 deletions(-)
+
+diff --git a/src/xkb/XKBGAlloc.c b/src/xkb/XKBGAlloc.c
+index e55f5e8..6d4c676 100644
+--- a/src/xkb/XKBGAlloc.c
++++ b/src/xkb/XKBGAlloc.c
+@@ -37,13 +37,6 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <X11/extensions/XKBgeom.h>
+ #include <X11/extensions/XKBproto.h>
+ 
+-
+-#ifdef X_NOT_POSIX
+-#define Size_t unsigned int
+-#else
+-#define Size_t size_t
+-#endif
+-
+ /***====================================================================***/
+ 
+ static void
+@@ -464,7 +457,7 @@ _XkbGeomAlloc(	XPointer *		old,
+ 		unsigned short *	num,
+ 		unsigned short *	total,
+ 		int			num_new,
+-		Size_t			sz_elem)
++		size_t			sz_elem)
+ {
+     if (num_new<1)
+ 	return Success;
+-- 
+1.7.9.2
+
+From 466404007f2c8f7166e4faddfea1454c5bfe1e9a Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 8 Mar 2013 17:13:09 -0800
+Subject: [PATCH:libX11 50/58] _xudc_code_to_glyph: check for NULL pointer
+ *before* writing to it, not after
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/udcInf.c |    8 ++++----
+ 1 file changed, 4 insertions(+), 4 deletions(-)
+
+diff --git a/src/udcInf.c b/src/udcInf.c
+index db7ad10..b7577ac 100644
+--- a/src/udcInf.c
++++ b/src/udcInf.c
+@@ -702,14 +702,14 @@ int 		*num_gi;
+     _XlcCloseConverter(conv);
+     _XlcDestroyLC(lcd);
+ 
+-    *gi = (_XUDCGIInf *)Xmalloc(sizeof(_XUDCGIInf));
+-    (*gi)->charset_str = (char *)Xmalloc(strlen(charsetname)+1);
+-    strcpy((*gi)->charset_str,charsetname);
+-    (*gi)->glyph_index = glyph;
++    *gi = Xmalloc(sizeof(_XUDCGIInf));
+     if(*gi == NULL){
+ 	_xudc_utyerrno = 0x03 ;
+         return(_XUDC_ERROR);
+     }
++    (*gi)->charset_str = Xmalloc(strlen(charsetname)+1);
++    strcpy((*gi)->charset_str,charsetname);
++    (*gi)->glyph_index = glyph;
+     *num_gi = 1;
+     return(0);
+ }
+-- 
+1.7.9.2
+
+From 3facbe5c0df1b5597571b7b00d5f7bdbc92fb278 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 2 Mar 2013 12:01:39 -0800
+Subject: [PATCH:libX11 51/58] Add <X11/Xresource.h> hint to all Xrm* man
+ pages
+
+Help users figure out which header file they need to #include
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ man/XrmEnumerateDatabase.man |    2 ++
+ man/XrmGetFileDatabase.man   |    2 ++
+ man/XrmGetResource.man       |    2 ++
+ man/XrmInitialize.man        |    2 ++
+ man/XrmMergeDatabases.man    |    2 ++
+ man/XrmPutResource.man       |    2 ++
+ man/XrmUniqueQuark.man       |    2 ++
+ 7 files changed, 14 insertions(+)
+
+diff --git a/man/XrmEnumerateDatabase.man b/man/XrmEnumerateDatabase.man
+index 8431006..03c0f30 100644
+--- a/man/XrmEnumerateDatabase.man
++++ b/man/XrmEnumerateDatabase.man
+@@ -84,6 +84,8 @@
+ .SH NAME
+ XrmEnumerateDatabase \- enumerate resource database entries
+ .SH SYNTAX
++.HP
++#include <X11/Xresource.h>
+ .TS
+ lw(.5i) lw(2i) lw(2.5i).
+ T{
+diff --git a/man/XrmGetFileDatabase.man b/man/XrmGetFileDatabase.man
+index 3a8a6fa..71ddd9f 100644
+--- a/man/XrmGetFileDatabase.man
++++ b/man/XrmGetFileDatabase.man
+@@ -93,6 +93,8 @@
+ XrmGetFileDatabase, XrmPutFileDatabase, XrmGetStringDatabase, XrmLocaleOfDatabase, XrmGetDatabase, XrmSetDatabase, XrmDestroyDatabase \- retrieve and store resource databases
+ .SH SYNTAX
+ .HP
++#include <X11/Xresource.h>
++.HP
+ XrmDatabase XrmGetFileDatabase\^(\^char *\fIfilename\fP\^); 
+ .HP
+ void XrmPutFileDatabase\^(\^XrmDatabase \fIdatabase\fP\^, char
+diff --git a/man/XrmGetResource.man b/man/XrmGetResource.man
+index 76ca921..ef2cf9a 100644
+--- a/man/XrmGetResource.man
++++ b/man/XrmGetResource.man
+@@ -85,6 +85,8 @@
+ XrmGetResource, XrmQGetResource, XrmQGetSearchList, XrmQGetSearchResource \- retrieve database resources and search lists
+ .SH SYNTAX
+ .HP
++#include <X11/Xresource.h>
++.HP
+ Bool XrmGetResource\^(\^XrmDatabase \fIdatabase\fP\^, char *\fIstr_name\fP\^,
+ char *\fIstr_class\fP\^, char **\fIstr_type_return\fP\^, XrmValue
+ *\fIvalue_return\fP\^); 
+diff --git a/man/XrmInitialize.man b/man/XrmInitialize.man
+index b8b549d..3b3ddd7 100644
+--- a/man/XrmInitialize.man
++++ b/man/XrmInitialize.man
+@@ -83,6 +83,8 @@
+ XrmInitialize, XrmParseCommand, XrmValue, XrmOptionKind, XrmOptionDescRec \- initialize the Resource Manager, Resource Manager structures, and parse the command line
+ .SH SYNTAX
+ .HP
++#include <X11/Xresource.h>
++.HP
+ void XrmInitialize\^(void\^);
+ .HP
+ void XrmParseCommand\^(\^XrmDatabase *\fIdatabase\fP\^, XrmOptionDescList
+diff --git a/man/XrmMergeDatabases.man b/man/XrmMergeDatabases.man
+index 57a6578..41b27bb 100644
+--- a/man/XrmMergeDatabases.man
++++ b/man/XrmMergeDatabases.man
+@@ -83,6 +83,8 @@
+ XrmMergeDatabases, XrmCombineDatabase, XrmCombineFileDatabase \- merge resource databases
+ .SH SYNTAX
+ .HP
++#include <X11/Xresource.h>
++.HP
+ void XrmMergeDatabases(\^XrmDatabase \fIsource_db\fP, XrmDatabase
+ *\fItarget_db\fP\^); 
+ .HP
+diff --git a/man/XrmPutResource.man b/man/XrmPutResource.man
+index 9f9d088..fd64463 100644
+--- a/man/XrmPutResource.man
++++ b/man/XrmPutResource.man
+@@ -83,6 +83,8 @@
+ XrmPutResource, XrmQPutResource, XrmPutStringResource, XrmQPutStringResource, XrmPutLineResource \- store database resources
+ .SH SYNTAX
+ .HP
++#include <X11/Xresource.h>
++.HP
+ void XrmPutResource\^(\^XrmDatabase *\fIdatabase\fP\^, char
+ *\fIspecifier\fP\^, char *\fItype\fP\^, XrmValue *\fIvalue\fP\^); 
+ .HP
+diff --git a/man/XrmUniqueQuark.man b/man/XrmUniqueQuark.man
+index 383d26c..93755f7 100644
+--- a/man/XrmUniqueQuark.man
++++ b/man/XrmUniqueQuark.man
+@@ -83,6 +83,8 @@
+ XrmUniqueQuark, XrmStringToQuark, XrmPermStringToQuark, XrmQuarkToString, XrmStringToQuarkList, XrmStringToBindingQuarkList \- manipulate resource quarks
+ .SH SYNOPSIS
+ .HP
++#include <X11/Xresource.h>
++.HP
+ XrmQuark XrmUniqueQuark\^(void); 
+ .LP
+ \&#define XrmStringToName(string) XrmStringToQuark(string)
+-- 
+1.7.9.2
+
+From 39547d600a13713e15429f49768e54c3173c828d Mon Sep 17 00:00:00 2001
+From: Karl Tomlinson <[email protected]>
+Date: Mon, 18 Feb 2013 01:25:34 +0000
+Subject: [PATCH:libX11 54/58] MakeBigReq: don't move the last word, already
+ handled by Data32
+
+MakeBigReq inserts a length field after the first 4 bytes of the request
+(after req->length), pushing everything else back by 4 bytes.
+
+The current memmove moves everything but the first 4 bytes back.
+If a request aligns to the end of the buffer pointer when MakeBigReq is
+invoked for that request, this runs over the buffer.
+Instead, we need to memmove minus the first 4 bytes (which aren't moved),
+minus the last 4 bytes (so we still align to the previous tail).
+
+The 4 bytes that fell out are already handled with Data32, which will
+handle the buffermax correctly.
+
+The case where req->length = 1 was already not functional.
+
+Reported by Abhishek Arya <[email protected]>.
+
+https://bugzilla.mozilla.org/show_bug.cgi?id=803762
+
+Reviewed-by: Jeff Muizelaar <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ include/X11/Xlibint.h |   19 +++++++++++++++++--
+ 1 file changed, 17 insertions(+), 2 deletions(-)
+
+diff --git a/include/X11/Xlibint.h b/include/X11/Xlibint.h
+index 40965c4..06395b3 100644
+--- a/include/X11/Xlibint.h
++++ b/include/X11/Xlibint.h
+@@ -486,6 +486,14 @@ extern void *_XGetRequest(Display *dpy, CARD8 type, size_t len);
+ 	req = (xReq *) _XGetRequest(dpy, X_/**/name, SIZEOF(xReq))
+ #endif
+ 
++/*
++ * MakeBigReq sets the CARD16 "req->length" to 0 and inserts a new CARD32
++ * length, after req->length, before the data in the request.  The new length
++ * includes the "n" extra 32-bit words.
++ *
++ * Do not use MakeBigReq if there is no data already in the request.
++ * req->length must already be >= 2.
++ */
+ #ifdef LONG64
+ #define MakeBigReq(req,n) \
+     { \
+@@ -493,7 +501,7 @@ extern void *_XGetRequest(Display *dpy, CARD8 type, size_t len);
+     CARD32 _BRlen = req->length - 1; \
+     req->length = 0; \
+     _BRdat = ((CARD32 *)req)[_BRlen]; \
+-    memmove(((char *)req) + 8, ((char *)req) + 4, _BRlen << 2); \
++    memmove(((char *)req) + 8, ((char *)req) + 4, (_BRlen - 1) << 2); \
+     ((CARD32 *)req)[1] = _BRlen + n + 2; \
+     Data32(dpy, &_BRdat, 4); \
+     }
+@@ -504,12 +512,19 @@ extern void *_XGetRequest(Display *dpy, CARD8 type, size_t len);
+     CARD32 _BRlen = req->length - 1; \
+     req->length = 0; \
+     _BRdat = ((CARD32 *)req)[_BRlen]; \
+-    memmove(((char *)req) + 8, ((char *)req) + 4, _BRlen << 2); \
++    memmove(((char *)req) + 8, ((char *)req) + 4, (_BRlen - 1) << 2); \
+     ((CARD32 *)req)[1] = _BRlen + n + 2; \
+     Data32(dpy, &_BRdat, 4); \
+     }
+ #endif
+ 
++/*
++ * SetReqLen increases the count of 32-bit words in the request by "n",
++ * or by "badlen" if "n" is too large.
++ *
++ * Do not use SetReqLen if "req" does not already have data after the
++ * xReq header.  req->length must already be >= 2.
++ */
+ #ifndef __clang_analyzer__
+ #define SetReqLen(req,n,badlen) \
+     if ((req->length + n) > (unsigned)65535) { \
+-- 
+1.7.9.2
+
+From e9bd757630368afb374c5d1bcc5d4d85ad3c6c4c Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 8 Mar 2013 15:37:33 -0800
+Subject: [PATCH:libX11 55/58] XAllocClassHint: Assume calloc sets pointers in
+ allocated memory to NULL
+
+While the C standard technically allows for the compiler to translate
+pointer = 0 or pointer = NULL into something other than filling the
+pointer address with 0 bytes, the rest of the Xlib code already assumes
+that calloc initializes any pointers in the struct to NULL, and there
+are no known systems supported by X.Org where this is not true.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/PropAlloc.c |    7 +------
+ 1 file changed, 1 insertion(+), 6 deletions(-)
+
+diff --git a/src/PropAlloc.c b/src/PropAlloc.c
+index bad7681..5162830 100644
+--- a/src/PropAlloc.c
++++ b/src/PropAlloc.c
+@@ -58,12 +58,7 @@ XWMHints *XAllocWMHints (void)
+ 
+ XClassHint *XAllocClassHint (void)
+ {
+-    register XClassHint *h;
+-
+-    if ((h = (XClassHint *) Xcalloc (1, (unsigned) sizeof (XClassHint))))
+-      h->res_name = h->res_class = NULL;
+-
+-    return h;
++    return Xcalloc (1, sizeof (XClassHint));
+ }
+ 
+ 
+-- 
+1.7.9.2
+
+From f9cd175a471116a616e681fb0ca1a61b3d84a6a0 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 8 Mar 2013 22:33:28 -0800
+Subject: [PATCH:libX11 56/58] Fix very weird indenting in src/GetFProp.c
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/GetFProp.c |   27 ++++++++++++---------------
+ 1 file changed, 12 insertions(+), 15 deletions(-)
+
+diff --git a/src/GetFProp.c b/src/GetFProp.c
+index 27ec98b..1e0cd32 100644
+--- a/src/GetFProp.c
++++ b/src/GetFProp.c
+@@ -29,27 +29,24 @@ in this Software without prior written authorization from The Open Group.
+ #endif
+ #include "Xlibint.h"
+ 
+-Bool XGetFontProperty (
++Bool
++XGetFontProperty(
+     XFontStruct *fs,
+     register Atom name,
+     unsigned long *valuePtr)
+ {
+     /* XXX this is a simple linear search for now.  If the
+-      protocol is changed to sort the property list, this should
+-      become a binary search. */
++       protocol is changed to sort the property list, this should
++       become a binary search. */
+     register XFontProp *prop = fs->properties;
+     register XFontProp *last = prop + fs->n_properties;
++
+     while (prop != last) {
+-	if (prop->name == name) {
+-	    *valuePtr = prop->card32;
+-	    return (1);
+-	    }
+-	prop++;
+-	}
+-    return (0);
++        if (prop->name == name) {
++            *valuePtr = prop->card32;
++            return (1);
++        }
++        prop++;
+     }
+-
+-
+-
+-
+-
++    return (0);
++}
+-- 
+1.7.9.2
+
+From f49bb2dd6d4ea45c55bd21acc0efe2b764441020 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 16 Mar 2013 18:30:56 -0700
+Subject: [PATCH:libX11 58/58] Move big request comment in XOpenDisplay to the
+ right place
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/OpenDis.c |    4 +++-
+ 1 file changed, 3 insertions(+), 1 deletion(-)
+
+diff --git a/src/OpenDis.c b/src/OpenDis.c
+index 9379fec..f6d8c70 100644
+--- a/src/OpenDis.c
++++ b/src/OpenDis.c
+@@ -499,6 +499,9 @@ XOpenDisplay (
+ 	    return(NULL);
+ 	}
+ 
++/*
++ * get availability of large requests
++ */
+ 	dpy->bigreq_size = xcb_get_maximum_request_length(dpy->xcb->connection);
+ 	if(dpy->bigreq_size <= dpy->max_request_size)
+ 		dpy->bigreq_size = 0;
+@@ -525,7 +528,6 @@ XOpenDisplay (
+ 	(void) XSynchronize(dpy, _Xdebug);
+ 
+ /*
+- * get availability of large requests, and
+  * get the resource manager database off the root window.
+  */
+ 	LockDisplay(dpy);
+-- 
+1.7.9.2
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXcursor/CVE-2013-2003.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,39 @@
+From 8f677eaea05290531d007d1fec2768119926088d Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 12 Apr 2013 21:17:28 -0700
+Subject: [PATCH:libXcursor] signedness bug & integer overflow in
+ _XcursorFileHeaderCreate() [CVE-2013-2003]
+
+When parsing cursor files, a user defined (e.g. through environment
+variables) cursor file is opened and parsed.
+
+The header is read in _XcursorReadFileHeader(), which reads an unsigned
+int for the number of toc structures in the header, but it was being
+passed to _XcursorFileHeaderCreate() as a signed int to allocate those
+structures.  If the number was negative, it would pass the bounds check
+and could overflow the calculation for how much memory to allocate to
+store the data being read, leading to overflowing the buffer with the
+data read from the user controlled file.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/file.c |    2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/src/file.c b/src/file.c
+index efe6d4b..ce9de78 100644
+--- a/src/file.c
++++ b/src/file.c
+@@ -205,7 +205,7 @@ _XcursorFileHeaderDestroy (XcursorFileHeader *fileHeader)
+ }
+ 
+ static XcursorFileHeader *
+-_XcursorFileHeaderCreate (int ntoc)
++_XcursorFileHeaderCreate (XcursorUInt ntoc)
+ {
+     XcursorFileHeader	*fileHeader;
+ 
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXcursor/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXcursor/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # Xcursor library for alpha-blended & animated cursors via Xrender extension
 #
-# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -37,7 +37,7 @@
 TARBALL_SHA256= f78827de4a1b7ce8cceca24a9ab9d1b1d2f6a61362f505166ffc19b07c0bad8f
 
 # Patches to apply to source after unpacking, in order
-SOURCE_PATCHES = 
+SOURCE_PATCHES = CVE-2013-2003.patch,-p1
 
 # Library name
 LIBNAME=Xcursor
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXext/CVE-2013-1982.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,700 @@
+From ca84a813716f9de691dc3f60390d83af4b5ae534 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 09:32:12 -0700
+Subject: [PATCH:libXext 1/7] Use _XEatDataWords to avoid overflow of
+ rep.length bit shifting
+
+rep.length is a CARD32, so rep.length << 2 could overflow in 32-bit builds
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ COPYING         |    3 ++-
+ configure.ac    |    6 ++++++
+ src/Makefile.am |    1 +
+ src/XEVI.c      |    4 +++-
+ src/XMultibuf.c |    3 ++-
+ src/XSecurity.c |    3 ++-
+ src/XShape.c    |    3 ++-
+ src/XSync.c     |    3 ++-
+ src/Xcup.c      |    7 ++++---
+ src/eat.h       |   40 ++++++++++++++++++++++++++++++++++++++++
+ 10 files changed, 64 insertions(+), 9 deletions(-)
+ create mode 100644 src/eat.h
+
+diff --git a/COPYING b/COPYING
+index 80622a0..e3a63ef 100644
+--- a/COPYING
++++ b/COPYING
+@@ -160,7 +160,8 @@ makes no representations about the suitability for any purpose
+ of the information in this document.  This documentation is
+ provided ``as is'' without express or implied warranty.
+ 
+-Copyright (c) 1999, 2005, 2006, Oracle and/or its affiliates. All rights reserved.
++Copyright (c) 1999, 2005, 2006, 2013, Oracle and/or its affiliates.
++All rights reserved.
+ 
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of this software and associated documentation files (the "Software"),
+diff --git a/configure.ac b/configure.ac
+index 63775de..fb9888d 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -38,6 +38,12 @@ AC_SUBST(XEXT_SOREV)
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(XEXT, [xproto >= 7.0.13] [x11 >= 1.1.99.1] [xextproto >= 7.1.99])
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib releases
++SAVE_LIBS="$LIBS"
++LIBS="$XEXT_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
+ # Allow checking code with lint, sparse, etc.
+ XORG_WITH_LINT
+ XORG_LINT_LIBRARY([Xext])
+diff --git a/src/Makefile.am b/src/Makefile.am
+index e236c33..b828547 100644
+--- a/src/Makefile.am
++++ b/src/Makefile.am
+@@ -12,6 +12,7 @@ libXext_la_LDFLAGS = -version-number $(XEXT_SOREV) -no-undefined
+ libXext_la_LIBADD = $(XEXT_LIBS)
+ 
+ libXext_la_SOURCES = \
++	eat.h \
+ 	DPMS.c \
+ 	MITMisc.c \
+ 	XAppgroup.c \
+diff --git a/src/XEVI.c b/src/XEVI.c
+index eb09daa..0125c51 100644
+--- a/src/XEVI.c
++++ b/src/XEVI.c
+@@ -30,6 +30,8 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <X11/extensions/Xext.h>
+ #include <X11/extensions/extutil.h>
+ #include <X11/Xutil.h>
++#include "eat.h"
++
+ static XExtensionInfo *xevi_info;/* needs to move to globals.c */
+ static const char *xevi_extension_name = EVINAME;
+ #define XeviCheckExtension(dpy,i,val) \
+@@ -171,7 +173,7 @@ Status XeviGetVisualInfo(
+     xInfoPtr = temp_xInfo = (xExtendedVisualInfo *)Xmalloc(sz_xInfo);
+     xConflictPtr = temp_conflict = (VisualID32 *)Xmalloc(sz_xConflict);
+     if (!*evi_return || !temp_xInfo || !temp_conflict) {
+-        _XEatData(dpy, (sz_xInfo + sz_xConflict + 3) & ~3);
++	_XEatDataWords(dpy, rep.length);
+ 	UnlockDisplay(dpy);
+ 	SyncHandle();
+ 	if (evi_return)
+diff --git a/src/XMultibuf.c b/src/XMultibuf.c
+index 7a746ba..43d56d3 100644
+--- a/src/XMultibuf.c
++++ b/src/XMultibuf.c
+@@ -34,6 +34,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/multibufproto.h>
+ #include <X11/extensions/multibuf.h>
++#include "eat.h"
+ 
+ static XExtensionInfo _multibuf_info_data;
+ static XExtensionInfo *multibuf_info = &_multibuf_info_data;
+@@ -408,7 +409,7 @@ Status XmbufGetWindowAttributes (
+ 	attr->buffers = (Multibuffer *) Xmalloc((unsigned) nbytes);
+ 	nbytes = rep.length << 2;
+ 	if (! attr->buffers) {
+-	    _XEatData(dpy, (unsigned long) nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return (0);
+diff --git a/src/XSecurity.c b/src/XSecurity.c
+index f8c7da1..ab17755 100644
+--- a/src/XSecurity.c
++++ b/src/XSecurity.c
+@@ -33,6 +33,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/securproto.h>
+ #include <X11/extensions/security.h>
++#include "eat.h"
+ 
+ static XExtensionInfo _Security_info_data;
+ static XExtensionInfo *Security_info = &_Security_info_data;
+@@ -282,7 +283,7 @@ XSecurityGenerateAuthorization(
+     }
+     else
+     {
+-	_XEatData(dpy, (unsigned long) (rep.dataLength + 3) & ~3);
++	_XEatDataWords(dpy, rep.length);
+     }
+ 
+     UnlockDisplay (dpy);
+diff --git a/src/XShape.c b/src/XShape.c
+index 6e8fbae..3987876 100644
+--- a/src/XShape.c
++++ b/src/XShape.c
+@@ -35,6 +35,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/shape.h>
+ #include <X11/extensions/shapeproto.h>
++#include "eat.h"
+ 
+ static XExtensionInfo _shape_info_data;
+ static XExtensionInfo *shape_info = &_shape_info_data;
+@@ -468,7 +469,7 @@ XRectangle *XShapeGetRectangles (
+ 		Xfree (xrects);
+ 	    if (rects)
+ 		Xfree (rects);
+-	    _XEatData (dpy, *count * sizeof (xRectangle));
++	    _XEatDataWords (dpy, rep.length);
+ 	    rects = NULL;
+ 	    *count = 0;
+ 	} else {
+diff --git a/src/XSync.c b/src/XSync.c
+index 5775293..3ca1308 100644
+--- a/src/XSync.c
++++ b/src/XSync.c
+@@ -59,6 +59,7 @@ PERFORMANCE OF THIS SOFTWARE.
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/sync.h>
+ #include <X11/extensions/syncproto.h>
++#include "eat.h"
+ 
+ static XExtensionInfo _sync_info_data;
+ static XExtensionInfo *sync_info = &_sync_info_data;
+@@ -364,7 +365,7 @@ XSyncListSystemCounters(Display *dpy, int *n_counters_return)
+ 	{
+ 	    if (list) Xfree((char *) list);
+ 	    if (pWireSysCounter)   Xfree((char *) pWireSysCounter);
+-	    _XEatData(dpy, (unsigned long) replylen);
++	    _XEatDataWords(dpy, rep.length);
+ 	    list = NULL;
+ 	    goto bail;
+ 	}
+diff --git a/src/Xcup.c b/src/Xcup.c
+index bb9e90f..1f1d625 100644
+--- a/src/Xcup.c
++++ b/src/Xcup.c
+@@ -36,6 +36,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <X11/extensions/cupproto.h>
+ #include <X11/extensions/Xext.h>
+ #include <X11/extensions/extutil.h>
++#include "eat.h"
+ 
+ static XExtensionInfo _xcup_info_data;
+ static XExtensionInfo *xcup_info = &_xcup_info_data;
+@@ -144,7 +145,7 @@ XcupGetReservedColormapEntries(
+ 	    rbufp = rbuf;
+ 
+ 	if (rbufp == NULL) {
+-	    _XEatData (dpy, (unsigned long) nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay (dpy);
+ 	    SyncHandle ();
+ 	    return False;
+@@ -221,7 +222,7 @@ XcupStoreColors(
+ 	nbytes = nentries * SIZEOF (xColorItem);
+ 
+ 	if (nentries != ncolors) {
+-	    _XEatData (dpy, (unsigned long) nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay (dpy);
+ 	    SyncHandle ();
+ 	    return False;
+@@ -233,7 +234,7 @@ XcupStoreColors(
+ 	    rbufp = rbuf;
+ 
+ 	if (rbufp == NULL) {
+-	    _XEatData (dpy, (unsigned long) nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay (dpy);
+ 	    SyncHandle ();
+ 	    return False;
+diff --git a/src/eat.h b/src/eat.h
+new file mode 100644
+index 0000000..239532b
+--- /dev/null
++++ b/src/eat.h
+@@ -0,0 +1,40 @@
++/*
++ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
++ *
++ * Permission is hereby granted, free of charge, to any person obtaining a
++ * copy of this software and associated documentation files (the "Software"),
++ * to deal in the Software without restriction, including without limitation
++ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
++ * and/or sell copies of the Software, and to permit persons to whom the
++ * Software is furnished to do so, subject to the following conditions:
++ *
++ * The above copyright notice and this permission notice (including the next
++ * paragraph) 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 AUTHORS OR COPYRIGHT HOLDERS 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.
++ */
++
++#ifdef HAVE_CONFIG_H
++# include "config.h"
++#endif
++
++#ifndef HAVE__XEATDATAWORDS
++#include <X11/Xmd.h>  /* for LONG64 on 64-bit platforms */
++#include <limits.h>
++
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
+-- 
+1.7.9.2
+
+From d05f27a6f74cb419ad5a437f2e4690b17e7faee5 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 14:40:33 -0800
+Subject: [PATCH:libXext 2/7] integer overflow in
+ XcupGetReservedColormapEntries() [CVE-2013-1982
+ 1/6]
+
+If the computed number of entries is large enough that it overflows when
+multiplied by the size of a xColorItem struct, or is treated as negative
+when compared to the size of the stack allocated buffer, then memory
+corruption can occur when more bytes are read from the X server than the
+size of the buffer we allocated to hold them.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Xcup.c |   19 ++++++++++++-------
+ 1 file changed, 12 insertions(+), 7 deletions(-)
+
+diff --git a/src/Xcup.c b/src/Xcup.c
+index 1f1d625..670f356 100644
+--- a/src/Xcup.c
++++ b/src/Xcup.c
+@@ -36,6 +36,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <X11/extensions/cupproto.h>
+ #include <X11/extensions/Xext.h>
+ #include <X11/extensions/extutil.h>
++#include <limits.h>
+ #include "eat.h"
+ 
+ static XExtensionInfo _xcup_info_data;
+@@ -134,15 +135,19 @@ XcupGetReservedColormapEntries(
+     req->xcupReqType = X_XcupGetReservedColormapEntries;
+     req->screen = screen;
+     if (_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
+-	long nbytes;
++	unsigned long nbytes;
+ 	xColorItem* rbufp;
+-	int nentries = rep.length / 3;
++	unsigned int nentries = rep.length / 3;
+ 
+-	nbytes = nentries * SIZEOF (xColorItem);
+-	if (nentries > TYP_RESERVED_ENTRIES)
+-	    rbufp = (xColorItem*) Xmalloc (nbytes);
+-	else
+-	    rbufp = rbuf;
++	if (nentries < (INT_MAX / SIZEOF (xColorItem))) {
++	    nbytes = nentries * SIZEOF (xColorItem);
++
++	    if (nentries > TYP_RESERVED_ENTRIES)
++		rbufp = Xmalloc (nbytes);
++	    else
++		rbufp = rbuf;
++	} else
++	    rbufp = NULL;
+ 
+ 	if (rbufp == NULL) {
+ 	    _XEatDataWords(dpy, rep.length);
+-- 
+1.7.9.2
+
+From 082d70b19848059ba78c9d1c315114fb07e8c0ef Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 14:40:33 -0800
+Subject: [PATCH:libXext 3/7] integer overflow in XcupStoreColors()
+ [CVE-2013-1982 2/6]
+
+If the computed number of entries is large enough that it overflows when
+multiplied by the size of a xColorItem struct, or is treated as negative
+when compared to the size of the stack allocated buffer, then memory
+corruption can occur when more bytes are read from the X server than the
+size of the buffer we allocated to hold them.
+
+The requirement to match the number of colors specified by the caller makes
+this much harder to hit than the one in XcupGetReservedColormapEntries()
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Xcup.c |   25 +++++++++++--------------
+ 1 file changed, 11 insertions(+), 14 deletions(-)
+
+diff --git a/src/Xcup.c b/src/Xcup.c
+index 670f356..cdc64c2 100644
+--- a/src/Xcup.c
++++ b/src/Xcup.c
+@@ -219,24 +219,21 @@ XcupStoreColors(
+     }
+ 
+     if (_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
+-	long nbytes;
++	unsigned long nbytes;
+ 	xColorItem* rbufp;
+ 	xColorItem* cs;
+-	int nentries = rep.length / 3;
+-
+-	nbytes = nentries * SIZEOF (xColorItem);
++	unsigned int nentries = rep.length / 3;
+ 
+-	if (nentries != ncolors) {
+-	    _XEatDataWords(dpy, rep.length);
+-	    UnlockDisplay (dpy);
+-	    SyncHandle ();
+-	    return False;
+-	}
++	if ((nentries == ncolors) &&
++	    (nentries < (INT_MAX / SIZEOF (xColorItem)))) {
++	    nbytes = nentries * SIZEOF (xColorItem);
+ 
+-	if (ncolors > 256)
+-	    rbufp = (xColorItem*) Xmalloc (nbytes);
+-	else
+-	    rbufp = rbuf;
++	    if (ncolors > 256)
++		rbufp = Xmalloc (nbytes);
++	    else
++		rbufp = rbuf;
++	} else
++	    rbufp = NULL;
+ 
+ 	if (rbufp == NULL) {
+ 	    _XEatDataWords(dpy, rep.length);
+-- 
+1.7.9.2
+
+From 96d1da55a08c4cd52b763cb07bdce5cdcbec4da8 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 14:40:33 -0800
+Subject: [PATCH:libXext 4/7] several integer overflows in XdbeGetVisualInfo()
+ [CVE-2013-1982 3/6]
+
+If the number of screens or visuals reported by the server is large enough
+that it overflows when multiplied by the size of the appropriate struct,
+then memory corruption can occur when more bytes are read from the X server
+than the size of the buffer we allocated to hold them.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Xdbe.c |   27 +++++++++++++++++----------
+ 1 file changed, 17 insertions(+), 10 deletions(-)
+
+diff --git a/src/Xdbe.c b/src/Xdbe.c
+index 4b5fa18..016886c 100644
+--- a/src/Xdbe.c
++++ b/src/Xdbe.c
+@@ -39,6 +39,8 @@
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/Xdbe.h>
+ #include <X11/extensions/dbeproto.h>
++#include <limits.h>
++#include "eat.h"
+ 
+ static XExtensionInfo _dbe_info_data;
+ static XExtensionInfo *dbe_info = &_dbe_info_data;
+@@ -352,9 +354,12 @@ XdbeScreenVisualInfo *XdbeGetVisualInfo (
+        *num_screens = rep.m;
+ 
+     /* allocate list of visual information to be returned */
+-    if (!(scrVisInfo =
+-        (XdbeScreenVisualInfo *)Xmalloc(
+-        (unsigned)(*num_screens * sizeof(XdbeScreenVisualInfo))))) {
++    if ((*num_screens > 0) && (*num_screens < 65536))
++        scrVisInfo = Xmalloc(*num_screens * sizeof(XdbeScreenVisualInfo));
++    else
++        scrVisInfo = NULL;
++    if (scrVisInfo == NULL) {
++        _XEatDataWords(dpy, rep.length);
+         UnlockDisplay (dpy);
+         SyncHandle ();
+         return NULL;
+@@ -362,25 +367,27 @@ XdbeScreenVisualInfo *XdbeGetVisualInfo (
+ 
+     for (i = 0; i < *num_screens; i++)
+     {
+-        int nbytes;
+         int j;
+-        long c;
++        unsigned long c;
+ 
+-        _XRead32 (dpy, &c, sizeof(CARD32));
+-        scrVisInfo[i].count = c;
++        _XRead32 (dpy, (long *) &c, sizeof(CARD32));
+ 
+-        nbytes = scrVisInfo[i].count * sizeof(XdbeVisualInfo);
++        if (c < 65536) {
++            scrVisInfo[i].count = c;
++            scrVisInfo[i].visinfo = Xmalloc(c * sizeof(XdbeVisualInfo));
++        } else
++            scrVisInfo[i].visinfo = NULL;
+ 
+         /* if we can not allocate the list of visual/depth info
+          * then free the lists that we already allocate as well
+          * as the visual info list itself
+          */
+-        if (!(scrVisInfo[i].visinfo = (XdbeVisualInfo *)Xmalloc(
+-            (unsigned)nbytes))) {
++        if (scrVisInfo[i].visinfo == NULL) {
+             for (j = 0; j < i; j++) {
+                 Xfree ((char *)scrVisInfo[j].visinfo);
+             }
+             Xfree ((char *)scrVisInfo);
++            _XEatDataWords(dpy, rep.length);
+             UnlockDisplay (dpy);
+             SyncHandle ();
+             return NULL;
+-- 
+1.7.9.2
+
+From 67ecdcf7e29de9fa78b421122620525ed2c7db88 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 14:40:33 -0800
+Subject: [PATCH:libXext 5/7] integer overflow in XeviGetVisualInfo()
+ [CVE-2013-1982 4/6]
+
+If the number of visuals or conflicts reported by the server is large
+enough that it overflows when multiplied by the size of the appropriate
+struct, then memory corruption can occur when more bytes are read from
+the X server than the size of the buffer we allocated to hold them.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XEVI.c |   25 ++++++++++++++++++-------
+ 1 file changed, 18 insertions(+), 7 deletions(-)
+
+diff --git a/src/XEVI.c b/src/XEVI.c
+index 0125c51..5a95583 100644
+--- a/src/XEVI.c
++++ b/src/XEVI.c
+@@ -30,6 +30,7 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ #include <X11/extensions/Xext.h>
+ #include <X11/extensions/extutil.h>
+ #include <X11/Xutil.h>
++#include <limits.h>
+ #include "eat.h"
+ 
+ static XExtensionInfo *xevi_info;/* needs to move to globals.c */
+@@ -165,13 +166,20 @@ Status XeviGetVisualInfo(
+ 	return BadAccess;
+     }
+     Xfree(temp_visual);
+-    sz_info = rep.n_info * sizeof(ExtendedVisualInfo);
+-    sz_xInfo = rep.n_info * sz_xExtendedVisualInfo;
+-    sz_conflict = rep.n_conflicts * sizeof(VisualID);
+-    sz_xConflict = rep.n_conflicts * sz_VisualID32;
+-    infoPtr = *evi_return = (ExtendedVisualInfo *)Xmalloc(sz_info + sz_conflict);
+-    xInfoPtr = temp_xInfo = (xExtendedVisualInfo *)Xmalloc(sz_xInfo);
+-    xConflictPtr = temp_conflict = (VisualID32 *)Xmalloc(sz_xConflict);
++    if ((rep.n_info < 65536) && (rep.n_conflicts < 65536)) {
++	sz_info = rep.n_info * sizeof(ExtendedVisualInfo);
++	sz_xInfo = rep.n_info * sz_xExtendedVisualInfo;
++	sz_conflict = rep.n_conflicts * sizeof(VisualID);
++	sz_xConflict = rep.n_conflicts * sz_VisualID32;
++	*evi_return = Xmalloc(sz_info + sz_conflict);
++	temp_xInfo = Xmalloc(sz_xInfo);
++	temp_conflict = Xmalloc(sz_xConflict);
++    } else {
++	sz_xInfo = sz_xConflict = 0;
++	*evi_return = NULL;
++	temp_xInfo = NULL;
++	temp_conflict = NULL;
++    }
+     if (!*evi_return || !temp_xInfo || !temp_conflict) {
+ 	_XEatDataWords(dpy, rep.length);
+ 	UnlockDisplay(dpy);
+@@ -188,6 +196,9 @@ Status XeviGetVisualInfo(
+     _XRead(dpy, (char *)temp_conflict, sz_xConflict);
+     UnlockDisplay(dpy);
+     SyncHandle();
++    infoPtr = *evi_return;
++    xInfoPtr = temp_xInfo;
++    xConflictPtr = temp_conflict;
+     n_data = rep.n_info;
+     conflict = (VisualID *)(infoPtr + n_data);
+     while (n_data-- > 0) {
+-- 
+1.7.9.2
+
+From 6ecd96e8be3c33e2ffad6631cea4aa0a030d93c2 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 14:40:33 -0800
+Subject: [PATCH:libXext 6/7] integer overflow in XShapeGetRectangles()
+ [CVE-2013-1982 5/6]
+
+If the number of rectangles reported by the server is large enough that
+it overflows when multiplied by the size of the appropriate struct, then
+memory corruption can occur when more bytes are read from the X server
+than the size of the buffer we allocated to hold them.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XShape.c |   24 ++++++++++++++----------
+ 1 file changed, 14 insertions(+), 10 deletions(-)
+
+diff --git a/src/XShape.c b/src/XShape.c
+index 3987876..d025020 100644
+--- a/src/XShape.c
++++ b/src/XShape.c
+@@ -35,6 +35,7 @@ in this Software without prior written authorization from The Open Group.
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/shape.h>
+ #include <X11/extensions/shapeproto.h>
++#include <limits.h>
+ #include "eat.h"
+ 
+ static XExtensionInfo _shape_info_data;
+@@ -443,7 +444,7 @@ XRectangle *XShapeGetRectangles (
+     xShapeGetRectanglesReply	    rep;
+     XRectangle			    *rects;
+     xRectangle			    *xrects;
+-    int				    i;
++    unsigned int		    i;
+ 
+     ShapeCheckExtension (dpy, info, (XRectangle *)NULL);
+ 
+@@ -461,20 +462,23 @@ XRectangle *XShapeGetRectangles (
+     *count = rep.nrects;
+     *ordering = rep.ordering;
+     rects = NULL;
+-    if (*count) {
+-	xrects = (xRectangle *) Xmalloc (*count * sizeof (xRectangle));
+-	rects = (XRectangle *) Xmalloc (*count * sizeof (XRectangle));
++    if (rep.nrects) {
++	if (rep.nrects < (INT_MAX / sizeof (XRectangle))) {
++	    xrects = Xmalloc (rep.nrects * sizeof (xRectangle));
++	    rects = Xmalloc (rep.nrects * sizeof (XRectangle));
++	} else {
++	    xrects = NULL;
++	    rects = NULL;
++	}
+ 	if (!xrects || !rects) {
+-	    if (xrects)
+-		Xfree (xrects);
+-	    if (rects)
+-		Xfree (rects);
++	    Xfree (xrects);
++	    Xfree (rects);
+ 	    _XEatDataWords (dpy, rep.length);
+ 	    rects = NULL;
+ 	    *count = 0;
+ 	} else {
+-	    _XRead (dpy, (char *) xrects, *count * sizeof (xRectangle));
+-	    for (i = 0; i < *count; i++) {
++	    _XRead (dpy, (char *) xrects, rep.nrects * sizeof (xRectangle));
++	    for (i = 0; i < rep.nrects; i++) {
+ 	    	rects[i].x = (short) cvtINT16toInt (xrects[i].x);
+ 	    	rects[i].y = (short) cvtINT16toInt (xrects[i].y);
+ 	    	rects[i].width = xrects[i].width;
+-- 
+1.7.9.2
+
+From dfe6e1f3b8ede3d0bab7a5fa57f73513a09ec649 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 14:40:33 -0800
+Subject: [PATCH:libXext 7/7] integer overflow in XSyncListSystemCounters()
+ [CVE-2013-1982 6/6]
+
+If the number of counters or amount of data reported by the server is
+large enough that it overflows when multiplied by the size of the
+appropriate struct, then memory corruption can occur when more bytes
+are read from the X server than the size of the buffers we allocated
+to hold them.
+
+V2: Make sure we don't walk past the end of the reply when converting
+data from wire format to the structures returned to the caller.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XSync.c |   32 +++++++++++++++++++++++++-------
+ 1 file changed, 25 insertions(+), 7 deletions(-)
+
+diff --git a/src/XSync.c b/src/XSync.c
+index 3ca1308..ce4ab44 100644
+--- a/src/XSync.c
++++ b/src/XSync.c
+@@ -59,6 +59,7 @@ PERFORMANCE OF THIS SOFTWARE.
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/sync.h>
+ #include <X11/extensions/syncproto.h>
++#include <limits.h>
+ #include "eat.h"
+ 
+ static XExtensionInfo _sync_info_data;
+@@ -352,19 +353,28 @@ XSyncListSystemCounters(Display *dpy, int *n_counters_return)
+     if (rep.nCounters > 0)
+     {
+ 	xSyncSystemCounter *pWireSysCounter, *pNextWireSysCounter;
++	xSyncSystemCounter *pLastWireSysCounter;
+ 	XSyncCounter counter;
+-	int replylen;
++	unsigned int replylen;
+ 	int i;
+ 
+-	list = Xmalloc(rep.nCounters * sizeof(XSyncSystemCounter));
+-	replylen = rep.length << 2;
+-	pWireSysCounter = Xmalloc ((unsigned) replylen + sizeof(XSyncCounter));
+-        /* +1 to leave room for last counter read-ahead */
++	if (rep.nCounters < (INT_MAX / sizeof(XSyncSystemCounter)))
++	    list = Xmalloc(rep.nCounters * sizeof(XSyncSystemCounter));
++	if (rep.length < (INT_MAX >> 2)) {
++	    replylen = rep.length << 2;
++	    pWireSysCounter = Xmalloc (replylen + sizeof(XSyncCounter));
++	    /* +1 to leave room for last counter read-ahead */
++	    pLastWireSysCounter = (xSyncSystemCounter *)
++		((char *)pWireSysCounter) + replylen;
++	} else {
++	    replylen = 0;
++	    pWireSysCounter = NULL;
++	}
+ 
+ 	if ((!list) || (!pWireSysCounter))
+ 	{
+-	    if (list) Xfree((char *) list);
+-	    if (pWireSysCounter)   Xfree((char *) pWireSysCounter);
++	    Xfree(list);
++	    Xfree(pWireSysCounter);
+ 	    _XEatDataWords(dpy, rep.length);
+ 	    list = NULL;
+ 	    goto bail;
+@@ -388,6 +398,14 @@ XSyncListSystemCounters(Display *dpy, int *n_counters_return)
+ 	    pNextWireSysCounter = (xSyncSystemCounter *)
+ 		(((char *)pWireSysCounter) + ((SIZEOF(xSyncSystemCounter) +
+ 				     pWireSysCounter->name_length + 3) & ~3));
++	    /* Make sure we haven't gone too far */
++	    if (pNextWireSysCounter > pLastWireSysCounter) {
++		Xfree(list);
++		Xfree(pWireSysCounter);
++		list = NULL;
++		goto bail;
++	    }
++
+ 	    counter = pNextWireSysCounter->counter;
+ 
+ 	    list[i].name = ((char *)pWireSysCounter) +
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXext/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXext/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # Xlib-based client library for common X11 protocol extensions
 #
-# Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -37,12 +37,17 @@
 TARBALL_SHA256= 56229c617eb7bfd6dec40d2805bc4dfb883dfe80f130d99b9a2beb632165e859
 
 # Patches to apply to source after unpacking, in order
-SOURCE_PATCHES  = shm.patch,-p1
+SOURCE_PATCHES += CVE-2013-1982.patch,-p1
+SOURCE_PATCHES += shm.patch,-p1
 SOURCE_PATCHES += sun-exts.patch,-p1
 
 # Library name (used for specfiles/mapfiles)
 LIBNAME=Xext
 
+# Dates to show in Oracle copyright notice in pkg license file
+# Earliest & latest of the copyrights in the Oracle files in this pkg
+ORACLE_COPYRIGHT_YEARS = 1990, 2013
+
 # ARC cases that covered this module
 # PSARC 1999/188 FBPM (Frame Buffer Power Management) Extension
 MODULE_ARC_CASES = PSARC/1999/188
--- a/open-src/lib/libXext/sun-src/src/TransOvl.c	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXext/sun-src/src/TransOvl.c	Wed May 08 18:06:35 2013 -0700
@@ -1,4 +1,4 @@
-/* Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
@@ -33,6 +33,7 @@
 #include <X11/extensions/extutil.h>
 #include <X11/extensions/transovlstr.h>
 #include <X11/extensions/multibuf.h>
+#include <limits.h>
 
 typedef struct {
     XExtData		extdata;
@@ -1171,10 +1172,14 @@
 	SyncHandle();
 	return NULL;
     }
-    nbytes = (long)rep.length << 2;
-    data = (char *)Xmalloc((size_t)nbytes);
+    if (rep.length < (INT_MAX >> 2)) {
+	nbytes = (long)rep.length << 2;
+	data = Xmalloc((size_t)nbytes);
+    } else {
+	data = NULL;
+    }
     if (!data) {
-	_XEatData(dpy, (unsigned long)nbytes);
+	_XEatDataWords(dpy, rep.length);
 	UnlockDisplay(dpy);
 	SyncHandle();
 	return NULL;
--- a/open-src/lib/libXext/sun-src/src/XPanoramiX.c	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXext/sun-src/src/XPanoramiX.c	Wed May 08 18:06:35 2013 -0700
@@ -26,7 +26,7 @@
 Equipment Corporation.
 
 ******************************************************************/
-/* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
@@ -648,23 +648,37 @@
 	return NULL;
     }
 
-    if(rep.number) {
-	if((scrnInfo = Xmalloc(sizeof(XineramaScreenInfo) * rep.number))) {
-	    xXineramaScreenInfo scratch;
-	    int i;
+    /*
+     * rep.number is a CARD32 so could be as large as 2^32
+     * The X11 protocol limits the total screen size to 64k x 64k,
+     * and no screen can be smaller than a pixel.  While technically
+     * that means we could theoretically reach 2^32 screens, and that's
+     * not even taking overlap into account, Xorg is currently limited
+     * to 16 screens, and few known servers have a much higher limit,
+     * so 1024 seems more than enough to prevent both integer overflow
+     * and insane X server responses causing massive memory allocation.
+     */
+    if ((rep.number > 0) && (rep.number <= 1024))
+	scrnInfo = Xmalloc(sizeof(XineramaScreenInfo) * rep.number);
+    if (scrnInfo != NULL) {
+	int i;
 
-	    for(i = 0; i < rep.number; i++) {
-		_XRead(dpy, (char*)(&scratch), sz_XineramaScreenInfo);
-		scrnInfo[i].screen_number = i;
-		scrnInfo[i].x_org 	  = scratch.x_org;
-		scrnInfo[i].y_org 	  = scratch.y_org;
-		scrnInfo[i].width 	  = scratch.width;
-		scrnInfo[i].height 	  = scratch.height;
-	    }
+	for (i = 0; i < rep.number; i++) {
+	    xXineramaScreenInfo scratch;
+
+	    _XRead(dpy, (char*)(&scratch), sz_XineramaScreenInfo);
 
-	    *number = rep.number;
-	} else
-	    _XEatData(dpy, rep.length << 2);
+	    scrnInfo[i].screen_number = i;
+	    scrnInfo[i].x_org	= scratch.x_org;
+	    scrnInfo[i].y_org	= scratch.y_org;
+	    scrnInfo[i].width	= scratch.width;
+	    scrnInfo[i].height	= scratch.height;
+	}
+
+	*number = rep.number;
+    } else {
+	_XEatDataWords(dpy, rep.length);
+	*number = 0;
     }
 
     UnlockDisplay (dpy);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXfixes/CVE-2013-1983.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,169 @@
+From b031e3b60fa1af9e49449f23d4a84395868be3ab Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 10:20:59 -0700
+Subject: [PATCH:libXfixes 1/2] Use _XEatDataWords to avoid overflow of
+ _XEatData calculations
+
+rep.length is a CARD32, so rep.length << 2 could overflow in 32-bit builds
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ configure.ac    |    7 +++++++
+ src/Cursor.c    |    4 ++--
+ src/Region.c    |    2 +-
+ src/Xfixesint.h |   14 ++++++++++++++
+ 4 files changed, 24 insertions(+), 3 deletions(-)
+
+diff --git a/configure.ac b/configure.ac
+index b942ffa..bb8e976 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -57,6 +57,13 @@ AC_SUBST(FIXESEXT_VERSION)
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(FIXESEXT, xproto [fixesproto >= $FIXESEXT_VERSION] xextproto x11)
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib releases
++SAVE_LIBS="$LIBS"
++LIBS="$FIXESEXT_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
++
+ AC_CONFIG_FILES([Makefile
+ 		src/Makefile
+ 		man/Makefile
+diff --git a/src/Cursor.c b/src/Cursor.c
+index b3dfed1..641b747 100644
+--- a/src/Cursor.c
++++ b/src/Cursor.c
+@@ -113,7 +113,7 @@ XFixesGetCursorImage (Display *dpy)
+     image = (XFixesCursorImage *) Xmalloc (rlength);
+     if (!image)
+     {
+-	_XEatData (dpy, nbytes);
++	_XEatDataWords(dpy, rep.length);
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return NULL;
+@@ -191,7 +191,7 @@ XFixesGetCursorName (Display *dpy, Cursor cursor, Atom *atom)
+ 	_XReadPad(dpy, name, (long)rep.nbytes);
+ 	name[rep.nbytes] = '\0';
+     } else {
+-	_XEatData(dpy, (unsigned long) (rep.nbytes + 3) & ~3);
++	_XEatDataWords(dpy, rep.length);
+ 	name = (char *) NULL;
+     }
+     UnlockDisplay(dpy);
+diff --git a/src/Region.c b/src/Region.c
+index 042f966..cb0cf6e 100644
+--- a/src/Region.c
++++ b/src/Region.c
+@@ -338,7 +338,7 @@ XFixesFetchRegionAndBounds (Display	    *dpy,
+     rects = Xmalloc (nrects * sizeof (XRectangle));
+     if (!rects)
+     {
+-	_XEatData (dpy, nbytes);
++	_XEatDataWords(dpy, rep.length);
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return NULL;
+diff --git a/src/Xfixesint.h b/src/Xfixesint.h
+index 8a4d5fd..7bf5bfd 100644
+--- a/src/Xfixesint.h
++++ b/src/Xfixesint.h
+@@ -60,4 +60,18 @@ XFixesFindDisplay (Display *dpy);
+ #define XFixesSimpleCheckExtension(dpy,i) \
+   if (!XFixesHasExtension(i)) { return; }
+ 
++#ifndef HAVE__XEATDATAWORDS
++#include <X11/Xmd.h>  /* for LONG64 on 64-bit platforms */
++#include <limits.h>
++
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
++
+ #endif /* _XFIXESINT_H_ */
+-- 
+1.7.9.2
+
+From c480fe3271873ec7471b0cbd680f4dac18ca8904 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 10:24:08 -0700
+Subject: [PATCH:libXfixes 2/2] integer overflow in XFixesGetCursorImage()
+ [CVE-2013-1983]
+
+If the reported cursor dimensions or name length are too large, the
+calculations to allocate memory for them may overflow, leaving us
+writing beyond the bounds of the allocation.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Cursor.c |   30 ++++++++++++++++++------------
+ 1 file changed, 18 insertions(+), 12 deletions(-)
+
+diff --git a/src/Cursor.c b/src/Cursor.c
+index 641b747..33590b7 100644
+--- a/src/Cursor.c
++++ b/src/Cursor.c
+@@ -47,6 +47,7 @@
+ #include <config.h>
+ #endif
+ #include "Xfixesint.h"
++#include <limits.h>
+ 
+ void
+ XFixesSelectCursorInput (Display	*dpy,
+@@ -74,9 +75,9 @@ XFixesGetCursorImage (Display *dpy)
+     XFixesExtDisplayInfo		*info = XFixesFindDisplay (dpy);
+     xXFixesGetCursorImageAndNameReq	*req;
+     xXFixesGetCursorImageAndNameReply	rep;
+-    int					npixels;
+-    int					nbytes_name;
+-    int					nbytes, nread, rlength;
++    size_t				npixels;
++    size_t				nbytes_name;
++    size_t				nbytes, nread, rlength;
+     XFixesCursorImage			*image;
+     char				*name;
+ 
+@@ -101,16 +102,21 @@ XFixesGetCursorImage (Display *dpy)
+     }
+     npixels = rep.width * rep.height;
+     nbytes_name = rep.nbytes;
+-    /* reply data length */
+-    nbytes = (long) rep.length << 2;
+-    /* bytes of actual data in the reply */
+-    nread = (npixels << 2) + nbytes_name;
+-    /* size of data returned to application */
+-    rlength = (sizeof (XFixesCursorImage) + 
+-	       npixels * sizeof (unsigned long) +
+-	       nbytes_name + 1);
++    if ((rep.length < (INT_MAX >> 2)) &&
++	npixels < (((INT_MAX >> 3) - sizeof (XFixesCursorImage) - 1)
++		   - nbytes_name)) {
++	/* reply data length */
++	nbytes = (size_t) rep.length << 2;
++	/* bytes of actual data in the reply */
++	nread = (npixels << 2) + nbytes_name;
++	/* size of data returned to application */
++	rlength = (sizeof (XFixesCursorImage) +
++		   npixels * sizeof (unsigned long) +
++		   nbytes_name + 1);
+ 
+-    image = (XFixesCursorImage *) Xmalloc (rlength);
++	image = Xmalloc (rlength);
++    } else
++	image = NULL;
+     if (!image)
+     {
+ 	_XEatDataWords(dpy, rep.length);
+
+
--- a/open-src/lib/libXfixes/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXfixes/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # Xfixes 1.x Makefile
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -37,6 +37,7 @@
 
 # Patches to apply to source after unpacking, in order
 SOURCE_PATCHES = soversion.patch,-p1
+SOURCE_PATCHES += CVE-2013-1983.patch,-p1
 
 # Need to autoreconf since soversion.patch changes Makefile.am's
 AUTORECONF=yes
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXi/CVE-2013-19XX.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,1247 @@
+From bb82c72a1d69eaf60b7586570faf797df967f661 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Mon, 29 Apr 2013 18:39:34 -0700
+Subject: [PATCH:libXi] Expand comment on the memory vs. reply ordering in
+ XIGetSelectedEvents()
+
+Unpacking from the wire involves un-interleaving the structs & masks,
+which wasn't obvious to me the first time I read it, so make notes
+before I forget again.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Signed-off-by: Peter Hutterer <[email protected]>
+---
+ src/XISelEv.c |   10 ++++++++--
+ 1 file changed, 8 insertions(+), 2 deletions(-)
+
+diff --git a/src/XISelEv.c b/src/XISelEv.c
+index fa7eb54..f871222 100644
+--- a/src/XISelEv.c
++++ b/src/XISelEv.c
+@@ -135,8 +135,14 @@ XIGetSelectedEvents(Display* dpy, Window win, int *num_masks_return)
+ 
+     _XRead(dpy, (char*)mask_in, reply.length * 4);
+ 
+-    /* Memory layout of the XIEventMask for a 3 mask reply:
+-     * [struct a][struct b][struct c][masks a][masks b][masks c]
++    /*
++     * This function takes interleaved xXIEventMask structs & masks off
++     * the wire, such as this 3 mask reply:
++     *   [struct a][masks a][struct b][masks b][struct c][masks c]
++     * And generates a memory buffer to be returned to callers in which
++     * they are not interleaved, so that callers can treat the returned
++     * pointer as a simple array of XIEventMask structs, such as:
++     *   [struct a][struct b][struct c][masks a][masks b][masks c]
+      */
+     len = reply.num_masks * sizeof(XIEventMask);
+ 
+-- 
+1.7.9.2
+
+From 63841a81a340f1979cf5b0ffa1f7047dca988994 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Wed, 1 May 2013 23:58:39 -0700
+Subject: [PATCH:libXi 01/13] Use _XEatDataWords to avoid overflow of
+ rep.length bit shifting
+
+rep.length is a CARD32, so rep.length << 2 could overflow in 32-bit builds
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ configure.ac       |    6 ++++++
+ src/XGMotion.c     |    2 +-
+ src/XGetDCtl.c     |    2 +-
+ src/XGetDProp.c    |    5 ++---
+ src/XGetFCtl.c     |    2 +-
+ src/XGetKMap.c     |    2 +-
+ src/XGetMMap.c     |    2 +-
+ src/XGetProp.c     |    4 +---
+ src/XGtSelect.c    |    2 +-
+ src/XIProperties.c |    7 +++----
+ src/XIint.h        |   14 ++++++++++++++
+ src/XListDProp.c   |    2 +-
+ src/XListDev.c     |    2 +-
+ src/XOpenDev.c     |    2 +-
+ src/XQueryDv.c     |    2 +-
+ 15 files changed, 36 insertions(+), 20 deletions(-)
+
+diff --git a/configure.ac b/configure.ac
+index 8dbca38..f5ef1e2 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -31,6 +31,12 @@ PKG_CHECK_MODULES(XI, [xproto >= 7.0.13] [x11 >= 1.4.99.1] [xextproto >= 7.0.3]
+ # CFLAGS only for PointerBarrier typedef
+ PKG_CHECK_MODULES(XFIXES, [xfixes >= 5])
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib releases
++SAVE_LIBS="$LIBS"
++LIBS="$XI_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
+ # Check for xmlto and asciidoc for man page conversion
+ # (only needed by people building tarballs)
+ if test "$have_xmlto" = yes && test "$have_asciidoc" = yes; then
+diff --git a/src/XGMotion.c b/src/XGMotion.c
+index 99b1c44..5feac85 100644
+--- a/src/XGMotion.c
++++ b/src/XGMotion.c
+@@ -112,7 +112,7 @@ XGetDeviceMotionEvents(
+ 	Xfree(bufp);
+ 	Xfree(savp);
+ 	*nEvents = 0;
+-	_XEatData(dpy, (unsigned long)size);
++	_XEatDataWords(dpy, rep.length);
+ 	UnlockDisplay(dpy);
+ 	SyncHandle();
+ 	return (NULL);
+diff --git a/src/XGetDCtl.c b/src/XGetDCtl.c
+index c66212d..f73a4e8 100644
+--- a/src/XGetDCtl.c
++++ b/src/XGetDCtl.c
+@@ -95,7 +95,7 @@ XGetDeviceControl(
+ 	nbytes = (long)rep.length << 2;
+ 	d = (xDeviceState *) Xmalloc((unsigned)nbytes);
+ 	if (!d) {
+-	    _XEatData(dpy, (unsigned long)nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    goto out;
+ 	}
+ 	sav = d;
+diff --git a/src/XGetDProp.c b/src/XGetDProp.c
+index 5d44f91..f9e8f0c 100644
+--- a/src/XGetDProp.c
++++ b/src/XGetDProp.c
+@@ -112,14 +112,13 @@ XGetDeviceProperty(Display* dpy, XDevice* dev,
+ 	     * This part of the code should never be reached.  If it is,
+ 	     * the server sent back a property with an invalid format.
+ 	     */
+-	    nbytes = rep.length << 2;
+-	    _XEatData(dpy, (unsigned long) nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return(BadImplementation);
+ 	}
+ 	if (! *prop) {
+-	    _XEatData(dpy, (unsigned long) nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return(BadAlloc);
+diff --git a/src/XGetFCtl.c b/src/XGetFCtl.c
+index 43afa00..28fab4d 100644
+--- a/src/XGetFCtl.c
++++ b/src/XGetFCtl.c
+@@ -95,7 +95,7 @@ XGetFeedbackControl(
+ 	nbytes = (long)rep.length << 2;
+ 	f = (xFeedbackState *) Xmalloc((unsigned)nbytes);
+ 	if (!f) {
+-	    _XEatData(dpy, (unsigned long)nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    goto out;
+ 	}
+ 	sav = f;
+diff --git a/src/XGetKMap.c b/src/XGetKMap.c
+index 9431fbb..00dde06 100644
+--- a/src/XGetKMap.c
++++ b/src/XGetKMap.c
+@@ -99,7 +99,7 @@ XGetDeviceKeyMapping(register Display * dpy, XDevice * dev,
+ 	if (mapping)
+ 	    _XRead(dpy, (char *)mapping, nbytes);
+ 	else
+-	    _XEatData(dpy, (unsigned long)nbytes);
++	    _XEatDataWords(dpy, rep.length);
+     }
+ 
+     UnlockDisplay(dpy);
+diff --git a/src/XGetMMap.c b/src/XGetMMap.c
+index 8a1cdb2..ce10c2d 100644
+--- a/src/XGetMMap.c
++++ b/src/XGetMMap.c
+@@ -92,7 +92,7 @@ XGetDeviceModifierMapping(
+ 	if (res->modifiermap)
+ 	    _XReadPad(dpy, (char *)res->modifiermap, nbytes);
+ 	else
+-	    _XEatData(dpy, (unsigned long)nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	res->max_keypermod = rep.numKeyPerModifier;
+     }
+ 
+diff --git a/src/XGetProp.c b/src/XGetProp.c
+index c5d088b..34bc581 100644
+--- a/src/XGetProp.c
++++ b/src/XGetProp.c
+@@ -68,7 +68,6 @@ XGetDeviceDontPropagateList(
+     int			*count)
+ {
+     XEventClass *list = NULL;
+-    int rlen;
+     xGetDeviceDontPropagateListReq *req;
+     xGetDeviceDontPropagateListReply rep;
+     XExtDisplayInfo *info = XInput_find_display(dpy);
+@@ -90,7 +89,6 @@ XGetDeviceDontPropagateList(
+     *count = rep.count;
+ 
+     if (*count) {
+-	rlen = rep.length << 2;
+ 	list = (XEventClass *) Xmalloc(rep.length * sizeof(XEventClass));
+ 	if (list) {
+ 	    int i;
+@@ -105,7 +103,7 @@ XGetDeviceDontPropagateList(
+ 		list[i] = (XEventClass) ec;
+ 	    }
+ 	} else
+-	    _XEatData(dpy, (unsigned long)rlen);
++	    _XEatDataWords(dpy, rep.length);
+     }
+ 
+     UnlockDisplay(dpy);
+diff --git a/src/XGtSelect.c b/src/XGtSelect.c
+index f890db7..5c0f812 100644
+--- a/src/XGtSelect.c
++++ b/src/XGtSelect.c
+@@ -104,7 +104,7 @@ XGetSelectedExtensionEvents(
+ 		(XEventClass *) Xmalloc(*this_client_count *
+ 					sizeof(XEventClass));
+ 	    if (!*this_client_list) {
+-		_XEatData(dpy, (unsigned long)tlen + alen);
++		_XEatDataWords(dpy, rep.length);
+                 UnlockDisplay(dpy);
+                 SyncHandle();
+ 		return (Success);
+diff --git a/src/XIProperties.c b/src/XIProperties.c
+index 83a7a68..5e58fb6 100644
+--- a/src/XIProperties.c
++++ b/src/XIProperties.c
+@@ -64,7 +64,7 @@ XIListProperties(Display* dpy, int deviceid, int *num_props_return)
+         props = (Atom*)Xmalloc(rep.num_properties * sizeof(Atom));
+         if (!props)
+         {
+-            _XEatData(dpy, rep.num_properties << 2);
++            _XEatDataWords(dpy, rep.length);
+             goto cleanup;
+         }
+ 
+@@ -203,8 +203,7 @@ XIGetProperty(Display* dpy, int deviceid, Atom property, long offset,
+ 	     * This part of the code should never be reached.  If it is,
+ 	     * the server sent back a property with an invalid format.
+ 	     */
+-	    nbytes = rep.length << 2;
+-	    _XEatData(dpy, nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return(BadImplementation);
+@@ -222,7 +221,7 @@ XIGetProperty(Display* dpy, int deviceid, Atom property, long offset,
+         *data = Xmalloc(rbytes);
+ 
+ 	if (!(*data)) {
+-	    _XEatData(dpy, nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return(BadAlloc);
+diff --git a/src/XIint.h b/src/XIint.h
+index 571bb23..3ddc3c5 100644
+--- a/src/XIint.h
++++ b/src/XIint.h
+@@ -83,4 +83,18 @@ next_block(void **ptr, int size) {
+     return ret;
+ }
+ 
++#ifndef HAVE__XEATDATAWORDS
++#include <X11/Xmd.h>  /* for LONG64 on 64-bit platforms */
++#include <limits.h>
++
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
++
+ #endif
+diff --git a/src/XListDProp.c b/src/XListDProp.c
+index 8667350..bde6cb5 100644
+--- a/src/XListDProp.c
++++ b/src/XListDProp.c
+@@ -65,7 +65,7 @@ XListDeviceProperties(Display* dpy, XDevice* dev, int *nprops_return)
+         props = (Atom*)Xmalloc(rep.nAtoms * sizeof(Atom));
+         if (!props)
+         {
+-            _XEatData(dpy, rep.nAtoms << 2);
++            _XEatDataWords(dpy, rep.length);
+             goto cleanup;
+         }
+ 
+diff --git a/src/XListDev.c b/src/XListDev.c
+index bd6e70a..1fa4747 100644
+--- a/src/XListDev.c
++++ b/src/XListDev.c
+@@ -202,7 +202,7 @@ XListInputDevices(
+ 	list = (xDeviceInfo *) Xmalloc(rlen);
+ 	slist = list;
+ 	if (!slist) {
+-	    _XEatData(dpy, (unsigned long)rlen);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return (XDeviceInfo *) NULL;
+diff --git a/src/XOpenDev.c b/src/XOpenDev.c
+index 74f18ac..e784f8b 100644
+--- a/src/XOpenDev.c
++++ b/src/XOpenDev.c
+@@ -101,7 +101,7 @@ XOpenDevice(
+ 	if (rlen - dlen > 0)
+ 	    _XEatData(dpy, (unsigned long)rlen - dlen);
+     } else
+-	_XEatData(dpy, (unsigned long)rlen);
++	_XEatDataWords(dpy, rep.length);
+ 
+     UnlockDisplay(dpy);
+     SyncHandle();
+diff --git a/src/XQueryDv.c b/src/XQueryDv.c
+index 24d4e4e..69c285b 100644
+--- a/src/XQueryDv.c
++++ b/src/XQueryDv.c
+@@ -91,7 +91,7 @@ XQueryDeviceState(
+     if (rlen > 0) {
+ 	data = Xmalloc(rlen);
+ 	if (!data) {
+-	    _XEatData(dpy, (unsigned long)rlen);
++	    _XEatDataWords(dpy, rep.length);
+ 	    goto out;
+ 	}
+ 	_XRead(dpy, data, rlen);
+-- 
+1.7.9.2
+
+From 0acd07e1c9583e2e7c26c13f8628bde992d9bce5 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 22:26:52 -0800
+Subject: [PATCH:libXi 02/13] Stack buffer overflow in
+ XGetDeviceButtonMapping() [CVE-2013-1998 1/3]
+
+We copy the entire reply sent by the server into the fixed size
+mapping[] array on the stack, even if the server says it's a larger
+size than the mapping array can hold.  HULK SMASH STACK!
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XGetBMap.c |   21 +++++++++++++--------
+ 1 file changed, 13 insertions(+), 8 deletions(-)
+
+diff --git a/src/XGetBMap.c b/src/XGetBMap.c
+index 211c9ca..002daba 100644
+--- a/src/XGetBMap.c
++++ b/src/XGetBMap.c
+@@ -60,6 +60,7 @@ SOFTWARE.
+ #include <X11/extensions/XInput.h>
+ #include <X11/extensions/extutil.h>
+ #include "XIint.h"
++#include <limits.h>
+ 
+ #ifdef MIN	/* some systems define this in <sys/param.h> */
+ #undef MIN
+@@ -75,7 +76,6 @@ XGetDeviceButtonMapping(
+ {
+     int status = 0;
+     unsigned char mapping[256];	/* known fixed size */
+-    long nbytes;
+     XExtDisplayInfo *info = XInput_find_display(dpy);
+ 
+     register xGetDeviceButtonMappingReq *req;
+@@ -92,13 +92,18 @@ XGetDeviceButtonMapping(
+ 
+     status = _XReply(dpy, (xReply *) & rep, 0, xFalse);
+     if (status == 1) {
+-	nbytes = (long)rep.length << 2;
+-	_XRead(dpy, (char *)mapping, nbytes);
+-
+-	/* don't return more data than the user asked for. */
+-	if (rep.nElts)
+-	    memcpy((char *)map, (char *)mapping, MIN((int)rep.nElts, nmap));
+-	status = rep.nElts;
++	if (rep.length <= (sizeof(mapping) >> 2)) {
++	    unsigned long nbytes = rep.length << 2;
++	    _XRead(dpy, (char *)mapping, nbytes);
++
++	    /* don't return more data than the user asked for. */
++	    if (rep.nElts)
++		memcpy(map, mapping, MIN((int)rep.nElts, nmap));
++	    status = rep.nElts;
++	} else {
++	    _XEatDataWords(dpy, rep.length);
++	    status = 0;
++	}
+     } else
+ 	status = 0;
+     UnlockDisplay(dpy);
+-- 
+1.7.9.2
+
+From 18855aa8c261863c00690b7df1e5ce4660687fb6 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 23:37:23 -0800
+Subject: [PATCH:libXi 03/13] memory corruption in _XIPassiveGrabDevice()
+ [CVE-2013-1998 2/3]
+
+If the server returned more modifiers than the caller asked for,
+we'd just keep copying past the end of the array provided by the
+caller, writing over who-knows-what happened to be there.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XIPassiveGrab.c |    2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/src/XIPassiveGrab.c b/src/XIPassiveGrab.c
+index ac17c01..53b4084 100644
+--- a/src/XIPassiveGrab.c
++++ b/src/XIPassiveGrab.c
+@@ -88,7 +88,7 @@ _XIPassiveGrabDevice(Display* dpy, int deviceid, int grabtype, int detail,
+         return -1;
+     _XRead(dpy, (char*)failed_mods, reply.num_modifiers * sizeof(xXIGrabModifierInfo));
+ 
+-    for (i = 0; i < reply.num_modifiers; i++)
++    for (i = 0; i < reply.num_modifiers && i < num_modifiers; i++)
+     {
+         modifiers_inout[i].status = failed_mods[i].status;
+         modifiers_inout[i].modifiers = failed_mods[i].modifiers;
+-- 
+1.7.9.2
+
+From a74690ba880036e01fc39f522b7567daf3746a31 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 26 Apr 2013 22:48:36 -0700
+Subject: [PATCH:libXi 04/13] unvalidated lengths in XQueryDeviceState()
+ [CVE-2013-1998 3/3]
+
+If the lengths given for each class state in the reply add up to more
+than the rep.length, we could read past the end of the buffer allocated
+to hold the data read from the server.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XQueryDv.c |   17 ++++++++++++-----
+ 1 file changed, 12 insertions(+), 5 deletions(-)
+
+diff --git a/src/XQueryDv.c b/src/XQueryDv.c
+index 69c285b..3836777 100644
+--- a/src/XQueryDv.c
++++ b/src/XQueryDv.c
+@@ -59,6 +59,7 @@ SOFTWARE.
+ #include <X11/extensions/XInput.h>
+ #include <X11/extensions/extutil.h>
+ #include "XIint.h"
++#include <limits.h>
+ 
+ XDeviceState *
+ XQueryDeviceState(
+@@ -66,8 +67,8 @@ XQueryDeviceState(
+     XDevice		*dev)
+ {
+     int i, j;
+-    int rlen;
+-    int size = 0;
++    unsigned long rlen;
++    size_t size = 0;
+     xQueryDeviceStateReq *req;
+     xQueryDeviceStateReply rep;
+     XDeviceState *state = NULL;
+@@ -87,9 +88,11 @@ XQueryDeviceState(
+     if (!_XReply(dpy, (xReply *) & rep, 0, xFalse))
+         goto out;
+ 
+-    rlen = rep.length << 2;
+-    if (rlen > 0) {
+-	data = Xmalloc(rlen);
++    if (rep.length > 0) {
++	if (rep.length < (INT_MAX >> 2)) {
++	    rlen = (unsigned long) rep.length << 2;
++	    data = Xmalloc(rlen);
++	}
+ 	if (!data) {
+ 	    _XEatDataWords(dpy, rep.length);
+ 	    goto out;
+@@ -97,6 +100,10 @@ XQueryDeviceState(
+ 	_XRead(dpy, data, rlen);
+ 
+ 	for (i = 0, any = (XInputClass *) data; i < (int)rep.num_classes; i++) {
++	    if (any->length > rlen)
++		goto out;
++	    rlen -= any->length;
++
+ 	    switch (any->class) {
+ 	    case KeyClass:
+ 		size += sizeof(XKeyState);
+-- 
+1.7.9.2
+
+From 38b563078ee050086526294f42f9f162be4bf97d Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 22:55:23 -0800
+Subject: [PATCH:libXi 05/13] integer overflow in XGetDeviceControl()
+ [CVE-2013-1984 1/8]
+
+If the number of valuators reported by the server is large enough that
+it overflows when multiplied by the size of the appropriate struct, then
+memory corruption can occur when more bytes are copied from the X server
+reply than the size of the buffer we allocated to hold them.
+
+v2: check that reply size fits inside the data read from the server, so
+we don't read out of bounds either
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XGetDCtl.c |   31 ++++++++++++++++++++++++-------
+ 1 file changed, 24 insertions(+), 7 deletions(-)
+
+diff --git a/src/XGetDCtl.c b/src/XGetDCtl.c
+index f73a4e8..51ed0ae 100644
+--- a/src/XGetDCtl.c
++++ b/src/XGetDCtl.c
+@@ -61,6 +61,7 @@ SOFTWARE.
+ #include <X11/extensions/XInput.h>
+ #include <X11/extensions/extutil.h>
+ #include "XIint.h"
++#include <limits.h>
+ 
+ XDeviceControl *
+ XGetDeviceControl(
+@@ -68,8 +69,6 @@ XGetDeviceControl(
+     XDevice		*dev,
+     int			 control)
+ {
+-    int size = 0;
+-    int nbytes, i;
+     XDeviceControl *Device = NULL;
+     XDeviceControl *Sav = NULL;
+     xDeviceState *d = NULL;
+@@ -92,8 +91,12 @@ XGetDeviceControl(
+ 	goto out;
+ 
+     if (rep.length > 0) {
+-	nbytes = (long)rep.length << 2;
+-	d = (xDeviceState *) Xmalloc((unsigned)nbytes);
++	unsigned long nbytes;
++	size_t size = 0;
++	if (rep.length < (INT_MAX >> 2)) {
++	    nbytes = (unsigned long) rep.length << 2;
++	    d = Xmalloc(nbytes);
++	}
+ 	if (!d) {
+ 	    _XEatDataWords(dpy, rep.length);
+ 	    goto out;
+@@ -111,33 +114,46 @@ XGetDeviceControl(
+ 	case DEVICE_RESOLUTION:
+ 	{
+ 	    xDeviceResolutionState *r;
++	    size_t val_size;
+ 
+ 	    r = (xDeviceResolutionState *) d;
+-	    size += sizeof(XDeviceResolutionState) +
+-		(3 * sizeof(int) * r->num_valuators);
++	    if (r->num_valuators >= (INT_MAX / (3 * sizeof(int))))
++		goto out;
++	    val_size = 3 * sizeof(int) * r->num_valuators;
++	    if ((sizeof(xDeviceResolutionState) + val_size) > nbytes)
++		goto out;
++	    size += sizeof(XDeviceResolutionState) + val_size;
+ 	    break;
+ 	}
+         case DEVICE_ABS_CALIB:
+         {
++            if (sizeof(xDeviceAbsCalibState) > nbytes)
++                goto out;
+             size += sizeof(XDeviceAbsCalibState);
+             break;
+         }
+         case DEVICE_ABS_AREA:
+         {
++            if (sizeof(xDeviceAbsAreaState) > nbytes)
++                goto out;
+             size += sizeof(XDeviceAbsAreaState);
+             break;
+         }
+         case DEVICE_CORE:
+         {
++            if (sizeof(xDeviceCoreState) > nbytes)
++                goto out;
+             size += sizeof(XDeviceCoreState);
+             break;
+         }
+ 	default:
++	    if (d->length > nbytes)
++		goto out;
+ 	    size += d->length;
+ 	    break;
+ 	}
+ 
+-	Device = (XDeviceControl *) Xmalloc((unsigned)size);
++	Device = Xmalloc(size);
+ 	if (!Device)
+ 	    goto out;
+ 
+@@ -150,6 +166,7 @@ XGetDeviceControl(
+ 	    int *iptr, *iptr2;
+ 	    xDeviceResolutionState *r;
+ 	    XDeviceResolutionState *R;
++	    unsigned int i;
+ 
+ 	    r = (xDeviceResolutionState *) d;
+ 	    R = (XDeviceResolutionState *) Device;
+-- 
+1.7.9.2
+
+From 9e39ad6e66a517c2324426c3aa32f4cfcc1cd4f5 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 22:55:23 -0800
+Subject: [PATCH:libXi 06/13] integer overflow in XGetFeedbackControl()
+ [CVE-2013-1984 2/8]
+
+If the number of feedbacks reported by the server is large enough that
+it overflows when multiplied by the size of the appropriate struct, or
+if the total size of all the feedback structures overflows when added
+together, then memory corruption can occur when more bytes are copied from
+the X server reply than the size of the buffer we allocated to hold them.
+
+v2: check that reply size fits inside the data read from the server, so
+    we don't read out of bounds either
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XGetFCtl.c |   24 +++++++++++++++++++-----
+ 1 file changed, 19 insertions(+), 5 deletions(-)
+
+diff --git a/src/XGetFCtl.c b/src/XGetFCtl.c
+index 28fab4d..bb50bf3 100644
+--- a/src/XGetFCtl.c
++++ b/src/XGetFCtl.c
+@@ -61,6 +61,7 @@ SOFTWARE.
+ #include <X11/extensions/XInput.h>
+ #include <X11/extensions/extutil.h>
+ #include "XIint.h"
++#include <limits.h>
+ 
+ XFeedbackState *
+ XGetFeedbackControl(
+@@ -68,8 +69,6 @@ XGetFeedbackControl(
+     XDevice		*dev,
+     int			*num_feedbacks)
+ {
+-    int size = 0;
+-    int nbytes, i;
+     XFeedbackState *Feedback = NULL;
+     XFeedbackState *Sav = NULL;
+     xFeedbackState *f = NULL;
+@@ -91,9 +90,16 @@ XGetFeedbackControl(
+ 	goto out;
+ 
+     if (rep.length > 0) {
++	unsigned long nbytes;
++	size_t size = 0;
++	int i;
++
+ 	*num_feedbacks = rep.num_feedbacks;
+-	nbytes = (long)rep.length << 2;
+-	f = (xFeedbackState *) Xmalloc((unsigned)nbytes);
++
++	if (rep.length < (INT_MAX >> 2)) {
++	    nbytes = rep.length << 2;
++	    f = Xmalloc(nbytes);
++	}
+ 	if (!f) {
+ 	    _XEatDataWords(dpy, rep.length);
+ 	    goto out;
+@@ -102,6 +108,10 @@ XGetFeedbackControl(
+ 	_XRead(dpy, (char *)f, nbytes);
+ 
+ 	for (i = 0; i < *num_feedbacks; i++) {
++	    if (f->length > nbytes)
++		goto out;
++	    nbytes -= f->length;
++
+ 	    switch (f->class) {
+ 	    case KbdFeedbackClass:
+ 		size += sizeof(XKbdFeedbackState);
+@@ -116,6 +126,8 @@ XGetFeedbackControl(
+ 	    {
+ 		xStringFeedbackState *strf = (xStringFeedbackState *) f;
+ 
++		if (strf->num_syms_supported >= (INT_MAX / sizeof(KeySym)))
++		    goto out;
+ 		size += sizeof(XStringFeedbackState) +
+ 		    (strf->num_syms_supported * sizeof(KeySym));
+ 	    }
+@@ -130,10 +142,12 @@ XGetFeedbackControl(
+ 		size += f->length;
+ 		break;
+ 	    }
++	    if (size > INT_MAX)
++		goto out;
+ 	    f = (xFeedbackState *) ((char *)f + f->length);
+ 	}
+ 
+-	Feedback = (XFeedbackState *) Xmalloc((unsigned)size);
++	Feedback = Xmalloc(size);
+ 	if (!Feedback)
+ 	    goto out;
+ 
+-- 
+1.7.9.2
+
+From 0bb14773ba37dfa8098b3e1784c80658019f9f21 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 22:55:23 -0800
+Subject: [PATCH:libXi 07/13] integer overflow in
+ XGetDeviceDontPropagateList() [CVE-2013-1984
+ 3/8]
+
+If the number of event classes reported by the server is large enough
+that it overflows when multiplied by the size of the appropriate struct,
+then memory corruption can occur when more bytes are copied from the
+X server reply than the size of the buffer we allocated to hold them.
+
+V2: EatData if count is 0 but length is > 0 to avoid XIOErrors
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XGetProp.c |    8 +++++---
+ 1 file changed, 5 insertions(+), 3 deletions(-)
+
+diff --git a/src/XGetProp.c b/src/XGetProp.c
+index 34bc581..b49328c 100644
+--- a/src/XGetProp.c
++++ b/src/XGetProp.c
+@@ -60,6 +60,7 @@ SOFTWARE.
+ #include <X11/extensions/XInput.h>
+ #include <X11/extensions/extutil.h>
+ #include "XIint.h"
++#include <limits.h>
+ 
+ XEventClass *
+ XGetDeviceDontPropagateList(
+@@ -88,10 +89,11 @@ XGetDeviceDontPropagateList(
+     }
+     *count = rep.count;
+ 
+-    if (*count) {
+-	list = (XEventClass *) Xmalloc(rep.length * sizeof(XEventClass));
++    if (rep.length != 0) {
++	if ((rep.count != 0) && (rep.length < (INT_MAX / sizeof(XEventClass))))
++	    list = Xmalloc(rep.length * sizeof(XEventClass));
+ 	if (list) {
+-	    int i;
++	    unsigned int i;
+ 	    CARD32 ec;
+ 
+ 	    /* read and assign each XEventClass separately because
+-- 
+1.7.9.2
+
+From 3d1fc7cd03e9a41b86cd83a8922df551a1b87179 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 22:55:23 -0800
+Subject: [PATCH:libXi 08/13] integer overflow in XGetDeviceMotionEvents()
+ [CVE-2013-1984 4/8]
+
+If the number of events or axes reported by the server is large enough
+that it overflows when multiplied by the size of the appropriate struct,
+then memory corruption can occur when more bytes are copied from the
+X server reply than the size of the buffer we allocated to hold them.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XGMotion.c |   22 +++++++++++++++++-----
+ 1 file changed, 17 insertions(+), 5 deletions(-)
+
+diff --git a/src/XGMotion.c b/src/XGMotion.c
+index 5feac85..a4c75b6 100644
+--- a/src/XGMotion.c
++++ b/src/XGMotion.c
+@@ -59,6 +59,7 @@ SOFTWARE.
+ #include <X11/extensions/XInput.h>
+ #include <X11/extensions/extutil.h>
+ #include "XIint.h"
++#include <limits.h>
+ 
+ XDeviceTimeCoord *
+ XGetDeviceMotionEvents(
+@@ -74,7 +75,7 @@ XGetDeviceMotionEvents(
+     xGetDeviceMotionEventsReply rep;
+     XDeviceTimeCoord *tc;
+     int *data, *bufp, *readp, *savp;
+-    long size, size2;
++    unsigned long size;
+     int i, j;
+     XExtDisplayInfo *info = XInput_find_display(dpy);
+ 
+@@ -104,10 +105,21 @@ XGetDeviceMotionEvents(
+ 	SyncHandle();
+ 	return (NULL);
+     }
+-    size = rep.length << 2;
+-    size2 = rep.nEvents * (sizeof(XDeviceTimeCoord) + (rep.axes * sizeof(int)));
+-    savp = readp = (int *)Xmalloc(size);
+-    bufp = (int *)Xmalloc(size2);
++    if (rep.length < (INT_MAX >> 2)) {
++	size = rep.length << 2;
++	savp = readp = Xmalloc(size);
++    } else {
++	size = 0;
++	savp = readp = NULL;
++    }
++    /* rep.axes is a CARD8, so assume max number of axes for bounds check */
++    if (rep.nEvents <
++	(INT_MAX / (sizeof(XDeviceTimeCoord) + (UCHAR_MAX * sizeof(int))))) {
++	size_t bsize = rep.nEvents *
++	    (sizeof(XDeviceTimeCoord) + (rep.axes * sizeof(int)));
++	bufp = Xmalloc(bsize);
++    } else
++	bufp = NULL;
+     if (!bufp || !savp) {
+ 	Xfree(bufp);
+ 	Xfree(savp);
+-- 
+1.7.9.2
+
+From 1202a8fc208581e184d327118a8a8ac3a27bbe64 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 22:55:23 -0800
+Subject: [PATCH:libXi 09/13] integer overflow in XIGetProperty()
+ [CVE-2013-1984 5/8]
+
+If the number of items reported by the server is large enough that
+it overflows when multiplied by the size of the appropriate item type,
+then memory corruption can occur when more bytes are copied from the
+X server reply than the size of the buffer we allocated to hold them.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XIProperties.c |   11 +++++++----
+ 1 file changed, 7 insertions(+), 4 deletions(-)
+
+diff --git a/src/XIProperties.c b/src/XIProperties.c
+index 5e58fb6..32436d1 100644
+--- a/src/XIProperties.c
++++ b/src/XIProperties.c
+@@ -38,6 +38,7 @@
+ #include <X11/extensions/XInput2.h>
+ #include <X11/extensions/extutil.h>
+ #include "XIint.h"
++#include <limits.h>
+ 
+ Atom*
+ XIListProperties(Display* dpy, int deviceid, int *num_props_return)
+@@ -170,7 +171,7 @@ XIGetProperty(Display* dpy, int deviceid, Atom property, long offset,
+ {
+     xXIGetPropertyReq   *req;
+     xXIGetPropertyReply rep;
+-    long                    nbytes, rbytes;
++    unsigned long       nbytes, rbytes;
+ 
+     XExtDisplayInfo *info = XInput_find_display(dpy);
+ 
+@@ -216,9 +217,11 @@ XIGetProperty(Display* dpy, int deviceid, Atom property, long offset,
+ 	 * recopy the string to make it null terminated.
+ 	 */
+ 
+-        nbytes = rep.num_items * rep.format/8;
+-        rbytes = nbytes + 1;
+-        *data = Xmalloc(rbytes);
++	if (rep.num_items < (INT_MAX / (rep.format/8))) {
++	    nbytes = rep.num_items * rep.format/8;
++	    rbytes = nbytes + 1;
++	    *data = Xmalloc(rbytes);
++	}
+ 
+ 	if (!(*data)) {
+ 	    _XEatDataWords(dpy, rep.length);
+-- 
+1.7.9.2
+
+From a3e76afd699b7afa590c8d3567663460c9870924 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 22:55:23 -0800
+Subject: [PATCH:libXi 10/13] integer overflow in XIGetSelectedEvents()
+ [CVE-2013-1984 6/8]
+
+If the number of events or masks reported by the server is large enough
+that it overflows when multiplied by the size of the appropriate struct,
+or the sizes overflow as they are totaled up, then memory corruption can
+occur when more bytes are copied from the X server reply than the size
+of the buffer we allocated to hold them.
+
+v2: check that reply size fits inside the data read from the server,
+    so that we don't read out of bounds either
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XISelEv.c |   25 +++++++++++++++++++------
+ 1 file changed, 19 insertions(+), 6 deletions(-)
+
+diff --git a/src/XISelEv.c b/src/XISelEv.c
+index f871222..0471bef 100644
+--- a/src/XISelEv.c
++++ b/src/XISelEv.c
+@@ -42,6 +42,7 @@ in this Software without prior written authorization from the author.
+ #include <X11/extensions/ge.h>
+ #include <X11/extensions/geproto.h>
+ #include "XIint.h"
++#include <limits.h>
+ 
+ int
+ XISelectEvents(Display* dpy, Window win, XIEventMask* masks, int num_masks)
+@@ -101,13 +102,14 @@ out:
+ XIEventMask*
+ XIGetSelectedEvents(Display* dpy, Window win, int *num_masks_return)
+ {
+-    int i, len = 0;
++    unsigned int i, len = 0;
+     unsigned char *mask;
+     XIEventMask *mask_out = NULL;
+     xXIEventMask *mask_in = NULL, *mi;
+     xXIGetSelectedEventsReq *req;
+     xXIGetSelectedEventsReply reply;
+     XExtDisplayInfo *info = XInput_find_display(dpy);
++    size_t rbytes;
+ 
+     *num_masks_return = -1;
+     LockDisplay(dpy);
+@@ -129,11 +131,16 @@ XIGetSelectedEvents(Display* dpy, Window win, int *num_masks_return)
+         goto out;
+     }
+ 
+-    mask_in = Xmalloc(reply.length * 4);
+-    if (!mask_in)
++    if (reply.length < (INT_MAX >> 2)) {
++        rbytes = (unsigned long) reply.length << 2;
++        mask_in = Xmalloc(rbytes);
++    }
++    if (!mask_in) {
++        _XEatDataWords(dpy, reply.length);
+         goto out;
++    }
+ 
+-    _XRead(dpy, (char*)mask_in, reply.length * 4);
++    _XRead(dpy, (char*)mask_in, rbytes);
+ 
+     /*
+      * This function takes interleaved xXIEventMask structs & masks off
+@@ -148,8 +155,14 @@ XIGetSelectedEvents(Display* dpy, Window win, int *num_masks_return)
+ 
+     for (i = 0, mi = mask_in; i < reply.num_masks; i++)
+     {
+-        len += mi->mask_len * 4;
+-        mi = (xXIEventMask*)((char*)mi + mi->mask_len * 4);
++        unsigned int mask_bytes = mi->mask_len * 4;
++        len += mask_bytes;
++        if (len > INT_MAX)
++            goto out;
++        if ((sizeof(xXIEventMask) + mask_bytes) > rbytes)
++            goto out;
++        rbytes -= (sizeof(xXIEventMask) + mask_bytes);
++        mi = (xXIEventMask*)((char*)mi + mask_bytes);
+         mi++;
+     }
+ 
+-- 
+1.7.9.2
+
+From b6246afd838842d28ac94d901507390624f31c7d Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sun, 10 Mar 2013 13:30:55 -0700
+Subject: [PATCH:libXi 11/13] Avoid integer overflow in XGetDeviceProperties()
+ [CVE-2013-1984 7/8]
+
+If the number of items as reported by the Xserver is too large, it
+could overflow the calculation for the size of the buffer to copy the
+reply into, causing memory corruption.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XGetDProp.c |   61 +++++++++++++++++++++++++++++++++----------------------
+ 1 file changed, 37 insertions(+), 24 deletions(-)
+
+diff --git a/src/XGetDProp.c b/src/XGetDProp.c
+index f9e8f0c..3691122 100644
+--- a/src/XGetDProp.c
++++ b/src/XGetDProp.c
+@@ -38,6 +38,7 @@ in this Software without prior written authorization from the author.
+ #include <X11/extensions/XInput.h>
+ #include <X11/extensions/extutil.h>
+ #include "XIint.h"
++#include <limits.h>
+ 
+ int
+ XGetDeviceProperty(Display* dpy, XDevice* dev,
+@@ -48,7 +49,8 @@ XGetDeviceProperty(Display* dpy, XDevice* dev,
+ {
+     xGetDevicePropertyReq   *req;
+     xGetDevicePropertyReply rep;
+-    long                    nbytes, rbytes;
++    unsigned long           nbytes, rbytes;
++    int                     ret = Success;
+ 
+     XExtDisplayInfo *info = XInput_find_display(dpy);
+ 
+@@ -81,30 +83,43 @@ XGetDeviceProperty(Display* dpy, XDevice* dev,
+ 	 * data, but this last byte is null terminated and convenient for
+ 	 * returning string properties, so the client doesn't then have to
+ 	 * recopy the string to make it null terminated.
++	 *
++	 * Maximum item limits are set to both prevent integer overflow when
++	 * calculating the amount of memory to malloc, and to limit how much
++	 * memory will be used if a server provides an insanely high count.
+ 	 */
+ 	switch (rep.format) {
+ 	case 8:
+-	    nbytes = rep.nItems;
+-	    rbytes = rep.nItems + 1;
+-	    if (rbytes > 0 &&
+-		(*prop = (unsigned char *) Xmalloc ((unsigned)rbytes)))
+-		_XReadPad (dpy, (char *) *prop, nbytes);
++	    if (rep.nItems < INT_MAX) {
++		nbytes = rep.nItems;
++		rbytes = rep.nItems + 1;
++		if ((*prop = Xmalloc (rbytes)))
++		    _XReadPad (dpy, (char *) *prop, nbytes);
++		else
++		    ret = BadAlloc;
++	    }
+ 	    break;
+ 
+ 	case 16:
+-	    nbytes = rep.nItems << 1;
+-	    rbytes = rep.nItems * sizeof (short) + 1;
+-	    if (rbytes > 0 &&
+-		(*prop = (unsigned char *) Xmalloc ((unsigned)rbytes)))
+-		_XRead16Pad (dpy, (short *) *prop, nbytes);
++	    if (rep.nItems < (INT_MAX / sizeof (short))) {
++		nbytes = rep.nItems << 1;
++		rbytes = rep.nItems * sizeof (short) + 1;
++		if ((*prop = Xmalloc (rbytes)))
++		    _XRead16Pad (dpy, (short *) *prop, nbytes);
++		else
++		    ret = BadAlloc;
++	    }
+ 	    break;
+ 
+ 	case 32:
+-	    nbytes = rep.nItems << 2;
+-	    rbytes = rep.nItems * sizeof (long) + 1;
+-	    if (rbytes > 0 &&
+-		(*prop = (unsigned char *) Xmalloc ((unsigned)rbytes)))
+-		_XRead32 (dpy, (long *) *prop, nbytes);
++	    if (rep.nItems < (INT_MAX / sizeof (long))) {
++		nbytes = rep.nItems << 2;
++		rbytes = rep.nItems * sizeof (long) + 1;
++		if ((*prop = Xmalloc (rbytes)))
++		    _XRead32 (dpy, (long *) *prop, nbytes);
++		else
++		    ret = BadAlloc;
++	    }
+ 	    break;
+ 
+ 	default:
+@@ -112,16 +127,13 @@ XGetDeviceProperty(Display* dpy, XDevice* dev,
+ 	     * This part of the code should never be reached.  If it is,
+ 	     * the server sent back a property with an invalid format.
+ 	     */
+-	    _XEatDataWords(dpy, rep.length);
+-	    UnlockDisplay(dpy);
+-	    SyncHandle();
+-	    return(BadImplementation);
++	    ret = BadImplementation;
+ 	}
+ 	if (! *prop) {
+ 	    _XEatDataWords(dpy, rep.length);
+-	    UnlockDisplay(dpy);
+-	    SyncHandle();
+-	    return(BadAlloc);
++	    if (ret == Success)
++		ret = BadAlloc;
++	    goto out;
+ 	}
+ 	(*prop)[rbytes - 1] = '\0';
+     }
+@@ -130,9 +142,10 @@ XGetDeviceProperty(Display* dpy, XDevice* dev,
+     *actual_format = rep.format;
+     *nitems = rep.nItems;
+     *bytes_after = rep.bytesAfter;
++  out:
+     UnlockDisplay (dpy);
+     SyncHandle ();
+ 
+-    return Success;
++    return ret;
+ }
+ 
+-- 
+1.7.9.2
+
+From 03f9746651d8d67c6d449737bd1681eb394b094c Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sun, 10 Mar 2013 00:22:14 -0800
+Subject: [PATCH:libXi 12/13] Avoid integer overflow in XListInputDevices()
+ [CVE-2013-1984 8/8]
+
+If the length of the reply as reported by the Xserver is too long, it
+could overflow the calculation for the size of the buffer to copy the
+reply into, causing memory corruption.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XListDev.c |   10 ++++++----
+ 1 file changed, 6 insertions(+), 4 deletions(-)
+
+diff --git a/src/XListDev.c b/src/XListDev.c
+index 1fa4747..1c14b96 100644
+--- a/src/XListDev.c
++++ b/src/XListDev.c
+@@ -60,6 +60,7 @@ SOFTWARE.
+ #include <X11/extensions/XInput.h>
+ #include <X11/extensions/extutil.h>
+ #include "XIint.h"
++#include <limits.h>
+ 
+ /* Calculate length field to a multiples of sizeof(XID). XIDs are typedefs
+  * to ulong and thus may be 8 bytes on some platforms. This can trigger a
+@@ -179,7 +180,7 @@ XListInputDevices(
+     XAnyClassPtr Any;
+     char *nptr, *Nptr;
+     int i;
+-    long rlen;
++    unsigned long rlen;
+     XExtDisplayInfo *info = XInput_find_display(dpy);
+ 
+     LockDisplay(dpy);
+@@ -198,9 +199,10 @@ XListInputDevices(
+ 
+     if ((*ndevices = rep.ndevices)) {	/* at least 1 input device */
+ 	size = *ndevices * sizeof(XDeviceInfo);
+-	rlen = rep.length << 2;	/* multiply length by 4    */
+-	list = (xDeviceInfo *) Xmalloc(rlen);
+-	slist = list;
++	if (rep.length < (INT_MAX >> 2)) {
++	    rlen = rep.length << 2;	/* multiply length by 4    */
++	    slist = list = Xmalloc(rlen);
++	}
+ 	if (!slist) {
+ 	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+-- 
+1.7.9.2
+
+From 5019f7a8f06b6826cd197d8def6feb841f1490ec Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sun, 10 Mar 2013 00:16:22 -0800
+Subject: [PATCH:libXi 13/13] sign extension issue in XListInputDevices()
+ [CVE-2013-1995]
+
+nptr is (signed) char, which can be negative, and will sign extend
+when added to the int size, which means size can be subtracted from,
+leading to allocating too small a buffer to hold the data being copied
+from the X server's reply.
+
+v2: check that string size fits inside the data read from the server,
+    so that we don't read out of bounds either
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XListDev.c |   16 ++++++++++------
+ 1 file changed, 10 insertions(+), 6 deletions(-)
+
+diff --git a/src/XListDev.c b/src/XListDev.c
+index 1c14b96..b85ff3c 100644
+--- a/src/XListDev.c
++++ b/src/XListDev.c
+@@ -73,7 +73,7 @@ static int pad_to_xid(int base_size)
+     return ((base_size + padsize - 1)/padsize) * padsize;
+ }
+ 
+-static int
++static size_t
+ SizeClassInfo(xAnyClassPtr *any, int num_classes)
+ {
+     int size = 0;
+@@ -170,7 +170,7 @@ XListInputDevices(
+     register Display	*dpy,
+     int			*ndevices)
+ {
+-    int size;
++    size_t size;
+     xListInputDevicesReq *req;
+     xListInputDevicesReply rep;
+     xDeviceInfo *list, *slist = NULL;
+@@ -178,7 +178,7 @@ XListInputDevices(
+     XDeviceInfo *clist = NULL;
+     xAnyClassPtr any, sav_any;
+     XAnyClassPtr Any;
+-    char *nptr, *Nptr;
++    unsigned char *nptr, *Nptr;
+     int i;
+     unsigned long rlen;
+     XExtDisplayInfo *info = XInput_find_display(dpy);
+@@ -217,9 +217,12 @@ XListInputDevices(
+             size += SizeClassInfo(&any, (int)list->num_classes);
+ 	}
+ 
+-	for (i = 0, nptr = (char *)any; i < *ndevices; i++) {
++	Nptr = ((unsigned char *)list) + rlen + 1;
++	for (i = 0, nptr = (unsigned char *)any; i < *ndevices; i++) {
+ 	    size += *nptr + 1;
+ 	    nptr += (*nptr + 1);
++	    if (nptr > Nptr)
++		goto out;
+ 	}
+ 
+ 	clist = (XDeviceInfoPtr) Xmalloc(size);
+@@ -245,8 +248,8 @@ XListInputDevices(
+ 	}
+ 
+ 	clist = sclist;
+-	nptr = (char *)any;
+-	Nptr = (char *)Any;
++	nptr = (unsigned char *)any;
++	Nptr = (unsigned char *)Any;
+ 	for (i = 0; i < *ndevices; i++, clist++) {
+ 	    clist->name = (char *)Nptr;
+ 	    memcpy(Nptr, nptr + 1, *nptr);
+@@ -256,6 +259,7 @@ XListInputDevices(
+ 	}
+     }
+ 
++  out:
+     XFree((char *)slist);
+     UnlockDisplay(dpy);
+     SyncHandle();
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXi/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXi/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # libXi Makefile
 #
-# Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -39,6 +39,7 @@
 # Patches to apply to source after unpacking, in order
 SOURCE_PATCHES = solaris-abi.patch,-p1
 SOURCE_PATCHES += man-fixme.patch,-p1 shadow-man-pages.patch,-p1
+SOURCE_PATCHES += CVE-2013-19XX.patch,-p1
 
 # Need to regen Makefile.in after man-fixme.patch changes Makefile.am
 AUTORECONF=yes
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXinerama/CVE-2013-1985.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,154 @@
+From 7ce3ce4be46087f9cc57cb415875abaaa961f734 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 4 May 2013 09:21:14 -0700
+Subject: [PATCH:libXinerama 1/2] Use _XEatDataWords to avoid overflow of
+ _XEatData calculations
+
+rep.length is a CARD32, so rep.length << 2 could overflow in 32-bit builds
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ configure.ac   |    6 ++++++
+ src/Xinerama.c |   19 ++++++++++++++++++-
+ 2 files changed, 24 insertions(+), 1 deletion(-)
+
+diff --git a/configure.ac b/configure.ac
+index e335508..046a1aa 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -42,6 +42,12 @@ XORG_CHECK_MALLOC_ZERO
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(XINERAMA, x11 xext xextproto [xineramaproto >= 1.1.99.1])
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib releases
++SAVE_LIBS="$LIBS"
++LIBS="$XINERAMA_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
+ # Allow checking code with lint, sparse, etc.
+ XORG_WITH_LINT
+ LINT_FLAGS="${LINT_FLAGS} ${XINERAMA_CFLAGS}"
+diff --git a/src/Xinerama.c b/src/Xinerama.c
+index 7d7e4d8..04189b6 100644
+--- a/src/Xinerama.c
++++ b/src/Xinerama.c
+@@ -23,6 +23,10 @@ dealings in this Software without prior written authorization from Digital
+ Equipment Corporation.
+ ******************************************************************/
+ 
++#ifdef HAVE_CONFIG_H
++# include "config.h"
++#endif
++
+ #include <X11/Xlibint.h>
+ #include <X11/Xutil.h>
+ #include <X11/extensions/Xext.h>
+@@ -31,6 +35,19 @@ Equipment Corporation.
+ #include <X11/extensions/panoramiXproto.h>
+ #include <X11/extensions/Xinerama.h>
+ 
++#ifndef HAVE__XEATDATAWORDS
++#include <X11/Xmd.h>  /* for LONG64 on 64-bit platforms */
++#include <limits.h>
++
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
+ 
+ static XExtensionInfo _panoramiX_ext_info_data;
+ static XExtensionInfo *panoramiX_ext_info = &_panoramiX_ext_info_data;
+@@ -302,7 +319,7 @@ XineramaQueryScreens(
+ 
+ 	    *number = rep.number;
+ 	} else
+-	    _XEatData(dpy, rep.length << 2);
++	    _XEatDataWords(dpy, rep.length);
+     } else {
+ 	*number = 0;
+     }
+-- 
+1.7.9.2
+
+From 99c644fc8488657bdd106717df7446d606f9ef22 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 8 Mar 2013 19:55:55 -0800
+Subject: [PATCH:libXinerama 2/2] integer overflow in XineramaQueryScreens()
+ [CVE-2013-1985]
+
+If the reported number of screens is too large, the calculations to
+allocate memory for them may overflow, leaving us writing beyond the
+bounds of the allocation.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Xinerama.c |   44 ++++++++++++++++++++++++++++----------------
+ 1 file changed, 28 insertions(+), 16 deletions(-)
+
+diff --git a/src/Xinerama.c b/src/Xinerama.c
+index 04189b6..67a35b5 100644
+--- a/src/Xinerama.c
++++ b/src/Xinerama.c
+@@ -303,24 +303,36 @@ XineramaQueryScreens(
+ 	return NULL;
+     }
+ 
+-    if(rep.number) {
+-	if((scrnInfo = Xmalloc(sizeof(XineramaScreenInfo) * rep.number))) {
++    /*
++     * rep.number is a CARD32 so could be as large as 2^32
++     * The X11 protocol limits the total screen size to 64k x 64k,
++     * and no screen can be smaller than a pixel.  While technically
++     * that means we could theoretically reach 2^32 screens, and that's
++     * not even taking overlap into account, Xorg is currently limited
++     * to 16 screens, and few known servers have a much higher limit,
++     * so 1024 seems more than enough to prevent both integer overflow
++     * and insane X server responses causing massive memory allocation.
++     */
++    if ((rep.number > 0) && (rep.number <= 1024))
++	scrnInfo = Xmalloc(sizeof(XineramaScreenInfo) * rep.number);
++    if (scrnInfo != NULL) {
++	int i;
++
++	for (i = 0; i < rep.number; i++) {
+ 	    xXineramaScreenInfo scratch;
+-	    int i;
+-
+-	    for(i = 0; i < rep.number; i++) {
+-		_XRead(dpy, (char*)(&scratch), sz_XineramaScreenInfo);
+-		scrnInfo[i].screen_number = i;
+-		scrnInfo[i].x_org 	  = scratch.x_org;
+-		scrnInfo[i].y_org 	  = scratch.y_org;
+-		scrnInfo[i].width 	  = scratch.width;
+-		scrnInfo[i].height 	  = scratch.height;
+-	    }
+-
+-	    *number = rep.number;
+-	} else
+-	    _XEatDataWords(dpy, rep.length);
++
++	    _XRead(dpy, (char*)(&scratch), sz_XineramaScreenInfo);
++
++	    scrnInfo[i].screen_number = i;
++	    scrnInfo[i].x_org	= scratch.x_org;
++	    scrnInfo[i].y_org	= scratch.y_org;
++	    scrnInfo[i].width	= scratch.width;
++	    scrnInfo[i].height	= scratch.height;
++	}
++
++	*number = rep.number;
+     } else {
++	_XEatDataWords(dpy, rep.length);
+ 	*number = 0;
+     }
+ 
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXinerama/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXinerama/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # libXinerama - Xlib-based client library for Xinerama extension protocol
 #
-# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -38,6 +38,7 @@
 
 # Patches to apply to source after unpacking, in order
 SOURCE_PATCHES = sun-abi.patch
+SOURCE_PATCHES += CVE-2013-1985.patch,-p1
 
 # Library name
 LIBNAME=Xinerama
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXp/CVE-2013-2062.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,269 @@
+From babb1fc823ab3be192c48fe115feeb0d57f74d05 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 26 Apr 2013 23:59:25 -0700
+Subject: [PATCH:libXp 2/4] integer overflow in XpGetAttributes &
+ XpGetOneAttribute [CVE-2013-2062 1/3]
+
+stringLen & valueLen are CARD32s and need to be bounds checked before adding
+one to them to come up with the total size to allocate, to avoid integer
+overflow leading to underallocation and writing data from the network past
+the end of the allocated buffer.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XpAttr.c |   36 +++++++++++++++++++-----------------
+ 1 file changed, 19 insertions(+), 17 deletions(-)
+
+diff --git a/src/XpAttr.c b/src/XpAttr.c
+index 6818daf..665e2e8 100644
+--- a/src/XpAttr.c
++++ b/src/XpAttr.c
+@@ -48,6 +48,7 @@
+ 
+ #include <stdio.h>
+ #include <sys/stat.h>
++#include <limits.h>
+ 
+ char *
+ XpGetAttributes (
+@@ -83,17 +84,18 @@ XpGetAttributes (
+     /*
+      * Read pool and return to caller.
+      */
+-    buf = Xmalloc( (unsigned) rep.stringLen + 1 );
++    if (rep.stringLen < INT_MAX)
++        buf = Xmalloc(rep.stringLen + 1);
++    else
++        buf = NULL;
+ 
+     if (!buf) {
+-        UnlockDisplay(dpy);
+-        SyncHandle();
+-        return( (char *) NULL ); /* malloc error */
++        _XEatDataWords(dpy, rep.length);
++    }
++    else {
++        _XReadPad (dpy, (char *) buf, rep.stringLen );
++        buf[rep.stringLen] = 0;
+     }
+-
+-    _XReadPad (dpy, (char *) buf, (long) rep.stringLen );
+-
+-    buf[rep.stringLen] = 0;
+ 
+     UnlockDisplay(dpy);
+     SyncHandle();
+@@ -144,18 +146,18 @@ XpGetOneAttribute (
+     /*
+      * Read variable answer.
+      */
+-    buf = Xmalloc( (unsigned) rep.valueLen + 1 );
++    if (rep.valueLen < INT_MAX)
++        buf = Xmalloc(rep.valueLen + 1);
++    else
++        buf = NULL;
+ 
+     if (!buf) {
+-        UnlockDisplay(dpy);
+-        SyncHandle();
+-        return( (char *) NULL ); /* malloc error */
++        _XEatDataWords(dpy, rep.length);
++    }
++    else {
++        _XReadPad (dpy, (char *) buf, rep.valueLen);
++        buf[rep.valueLen] = 0;
+     }
+-
+-    buf[rep.valueLen] = 0;
+-
+-    _XReadPad (dpy, (char *) buf, (long) rep.valueLen );
+-    buf[rep.valueLen] = 0;
+ 
+     UnlockDisplay(dpy);
+     SyncHandle();
+-- 
+1.7.9.2
+
+From cc90f6be64bfd6973ae270b9bff494f577e1bda7 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 26 Apr 2013 23:59:25 -0700
+Subject: [PATCH:libXp 3/4] integer overflows in XpGetPrinterList()
+ [CVE-2013-2062 2/3]
+
+listCount is a CARD32 that needs to be bounds checked before it is
+multiplied by the size of the structs to allocate, and the string
+lengths are CARD32s and need to be bounds checked before adding one
+to them to come up with the total size to allocate, to avoid integer
+overflow leading to underallocation and writing data from the network
+past the end of the allocated buffer.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XpPrinter.c |   43 +++++++++++++++++++++++--------------------
+ 1 file changed, 23 insertions(+), 20 deletions(-)
+
+diff --git a/src/XpPrinter.c b/src/XpPrinter.c
+index bdc96e6..03b18c4 100644
+--- a/src/XpPrinter.c
++++ b/src/XpPrinter.c
+@@ -42,6 +42,7 @@
+ #include <X11/extensions/Printstr.h>
+ #include <X11/Xlibint.h>
+ #include "XpExtUtil.h"
++#include <limits.h>
+ 
+ #define _XpPadOut(len) (((len) + 3) & ~3)
+ 
+@@ -62,7 +63,7 @@ XpGetPrinterList (
+     long	dataLenVR;
+     CARD8	*dataVR;	/* aka STRING8 */
+ 
+-    XPPrinterList ptr_list;
++    XPPrinterList ptr_list = NULL;
+ 
+     XExtDisplayInfo *info = (XExtDisplayInfo *) xp_find_display (dpy);
+ 
+@@ -128,13 +129,12 @@ XpGetPrinterList (
+     *list_count = rep.listCount;
+ 
+     if (*list_count) {
+-	ptr_list = (XPPrinterList)
+-		Xmalloc( (unsigned) (sizeof(XPPrinterRec) * (*list_count + 1)));
++	if (rep.listCount < (INT_MAX / sizeof(XPPrinterRec)))
++	    ptr_list = Xmalloc(sizeof(XPPrinterRec) * (*list_count + 1));
+ 
+ 	if (!ptr_list) {
+-            UnlockDisplay(dpy);
+-            SyncHandle();
+-            return ( (XPPrinterList) NULL ); /* malloc error */
++	    _XEatDataWords(dpy, rep.length);
++	    goto out;
+ 	}
+ 
+ 	/*
+@@ -150,16 +150,17 @@ XpGetPrinterList (
+ 	    _XRead32 (dpy, &dataLenVR, (long) sizeof(CARD32) );
+ 
+ 	    if (dataLenVR) {
+-		dataVR = (CARD8 *) Xmalloc( (unsigned) dataLenVR + 1 );
++		if (dataLenVR < INT_MAX)
++		    dataVR = Xmalloc(dataLenVR + 1);
++		else
++		    dataVR = NULL;
+ 
+ 		if (!dataVR) {
+-		    UnlockDisplay(dpy);
+-		    SyncHandle();
+-		    return ( (XPPrinterList) NULL ); /* malloc error */
++		    _XEatData(dpy, dataLenVR);
++		} else {
++		    _XReadPad (dpy, (char *) dataVR, (long) dataLenVR);
++		    dataVR[dataLenVR] = 0;
+ 		}
+-
+-		_XReadPad (dpy, (char *) dataVR, (long) dataLenVR);
+-		dataVR[dataLenVR] = 0;
+ 		ptr_list[i].name = (char *) dataVR;
+ 	    }
+ 	    else {
+@@ -172,16 +173,17 @@ XpGetPrinterList (
+ 	    _XRead32 (dpy, &dataLenVR, (long) sizeof(CARD32) );
+ 
+ 	    if (dataLenVR) {
+-		dataVR = (CARD8 *) Xmalloc( (unsigned) dataLenVR + 1 );
++		if (dataLenVR < INT_MAX)
++		    dataVR = Xmalloc(dataLenVR + 1);
++		else
++		    dataVR = NULL;
+ 
+ 		if (!dataVR) {
+-		    UnlockDisplay(dpy);
+-		    SyncHandle();
+-		    return ( (XPPrinterList) NULL ); /* malloc error */
++		    _XEatData(dpy, dataLenVR);
++		} else {
++		    _XReadPad (dpy, (char *) dataVR, (long) dataLenVR);
++		    dataVR[dataLenVR] = 0;
+ 		}
+-
+-		_XReadPad (dpy, (char *) dataVR, (long) dataLenVR);
+-		dataVR[dataLenVR] = 0;
+ 		ptr_list[i].desc = (char *) dataVR;
+ 	    }
+ 	    else {
+@@ -193,6 +195,7 @@ XpGetPrinterList (
+ 	ptr_list = (XPPrinterList) NULL;
+     }
+ 
++  out:
+     UnlockDisplay(dpy);
+     SyncHandle();
+ 
+-- 
+1.7.9.2
+
+From e111065f6dd790c820fa67ea31055b18c68481e3 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 26 Apr 2013 23:59:25 -0700
+Subject: [PATCH:libXp 4/4] integer overflows in XpQueryScreens()
+ [CVE-2013-2062 3/3]
+
+listCount is a CARD32 that needs to be bounds checked before it is
+multiplied by the size of the pointers to allocate, to avoid integer
+overflow leading to underallocation and writing data from the network
+past the end of the allocated buffer.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XpScreens.c |   16 ++++++++--------
+ 1 file changed, 8 insertions(+), 8 deletions(-)
+
+diff --git a/src/XpScreens.c b/src/XpScreens.c
+index 815dfbf..b31e554 100644
+--- a/src/XpScreens.c
++++ b/src/XpScreens.c
+@@ -42,6 +42,7 @@
+ #include <X11/extensions/Printstr.h>
+ #include <X11/Xlibint.h>
+ #include "XpExtUtil.h"
++#include <limits.h>
+ 
+ 
+ Screen **
+@@ -82,19 +83,17 @@ XpQueryScreens (
+     *list_count = rep.listCount;
+ 
+     if (*list_count) {
+-	scr_list = (Screen **)
+-		   Xmalloc( (unsigned) (sizeof(Screen *) * *list_count) );
++	if (rep.listCount < (INT_MAX / sizeof(Screen *)))
++	    scr_list = Xmalloc(sizeof(Screen *) * *list_count);
++	else
++	    scr_list = NULL;
+ 
+ 	if (!scr_list) {
+-            UnlockDisplay(dpy);
+-            SyncHandle();
+-            return ( (Screen **) NULL ); /* malloc error */
++	    _XEatDataWords(dpy, rep.length);
++	    goto out;
+ 	}
+ 	i = 0;
+ 	while(i < *list_count){
+-	    /*
+-	     * Pull printer length and then name.
+-	     */
+ 	    _XRead32 (dpy, &rootWindow, (long) sizeof(CARD32) );
+ 	    scr_list[i] = NULL;
+ 	    for ( j = 0; j < XScreenCount(dpy); j++ ) {
+@@ -118,6 +117,7 @@ XpQueryScreens (
+ 	scr_list = (Screen **) NULL;
+     }
+ 
++  out:
+     UnlockDisplay(dpy);
+     SyncHandle();
+ 
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXp/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXp/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # Xp 1.x Makefile
 #
-# Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -37,6 +37,7 @@
 
 # Patches to apply to source after unpacking, in order
 SOURCE_PATCHES = solaris-abi.patch 6724993.patch
+SOURCE_PATCHES += CVE-2013-2062.patch,-p1
 
 # Since we're patching src/Makefile.am in solaris-abi.patch,
 # we need to autoreconf
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXrandr/CVE-2013-1986.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,573 @@
+From 1c7ad6773ce6be00dcd6e51e9be08f203abe5071 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 3 May 2013 23:29:22 -0700
+Subject: [PATCH:libXrandr 1/6] Use _XEatDataWords to avoid overflow of
+ rep.length bit shifting
+
+rep.length is a CARD32, so rep.length << 2 could overflow in 32-bit builds
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ configure.ac              |    6 ++++++
+ src/Xrandrint.h           |   13 +++++++++++++
+ src/XrrCrtc.c             |    6 +++---
+ src/XrrOutput.c           |    2 +-
+ src/XrrProperty.c         |    9 ++++-----
+ src/XrrProvider.c         |    4 ++--
+ src/XrrProviderProperty.c |    9 ++++-----
+ src/XrrScreen.c           |    2 +-
+ 8 files changed, 34 insertions(+), 17 deletions(-)
+
+diff --git a/configure.ac b/configure.ac
+index 3f28bef..8466999 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -55,6 +55,12 @@ AC_SUBST(RANDR_VERSION)
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(RANDR, x11 randrproto >= $RANDR_VERSION xext xextproto xrender renderproto)
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib release
++SAVE_LIBS="$LIBS"
++LIBS="$RANDR_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
+ AC_CONFIG_FILES([Makefile
+ 		src/Makefile
+ 		man/Makefile
+diff --git a/src/Xrandrint.h b/src/Xrandrint.h
+index aed10e4..1687c29 100644
+--- a/src/Xrandrint.h
++++ b/src/Xrandrint.h
+@@ -42,6 +42,19 @@ extern char XRRExtensionName[];
+ 
+ XExtDisplayInfo *XRRFindDisplay (Display *dpy);
+ 
++#ifndef HAVE__XEATDATAWORDS
++#include <X11/Xmd.h>  /* for LONG64 on 64-bit platforms */
++#include <limits.h>
++
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
+ 
+ /* deliberately opaque internal data structure; can be extended,
+    but not reordered */
+diff --git a/src/XrrCrtc.c b/src/XrrCrtc.c
+index 04087c5..a704a52 100644
+--- a/src/XrrCrtc.c
++++ b/src/XrrCrtc.c
+@@ -74,7 +74,7 @@ XRRGetCrtcInfo (Display *dpy, XRRScreenResources *resources, RRCrtc crtc)
+ 
+     xci = (XRRCrtcInfo *) Xmalloc(rbytes);
+     if (xci == NULL) {
+-	_XEatData (dpy, (unsigned long) nbytes);
++	_XEatDataWords (dpy, rep.length);
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return NULL;
+@@ -203,7 +203,7 @@ XRRGetCrtcGamma (Display *dpy, RRCrtc crtc)
+ 
+     if (!crtc_gamma)
+     {
+-	_XEatData (dpy, (unsigned long) nbytes);
++	_XEatDataWords (dpy, rep.length);
+ 	goto out;
+     }
+     _XRead16 (dpy, crtc_gamma->red, rep.size * 2);
+@@ -397,7 +397,7 @@ XRRGetCrtcTransform (Display	*dpy,
+ 	    int extraBytes = rep.length * 4 - CrtcTransformExtra;
+ 	    extra = Xmalloc (extraBytes);
+ 	    if (!extra) {
+-		_XEatData (dpy, extraBytes);
++		_XEatDataWords (dpy, rep.length - (CrtcTransformExtra >> 2));
+ 		UnlockDisplay (dpy);
+ 		SyncHandle ();
+ 		return False;
+diff --git a/src/XrrOutput.c b/src/XrrOutput.c
+index f13a932..4df894e 100644
+--- a/src/XrrOutput.c
++++ b/src/XrrOutput.c
+@@ -81,7 +81,7 @@ XRRGetOutputInfo (Display *dpy, XRRScreenResources *resources, RROutput output)
+ 
+     xoi = (XRROutputInfo *) Xmalloc(rbytes);
+     if (xoi == NULL) {
+-	_XEatData (dpy, (unsigned long) nbytes);
++	_XEatDataWords (dpy, rep.length - (OutputInfoExtra >> 2));
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return NULL;
+diff --git a/src/XrrProperty.c b/src/XrrProperty.c
+index 4c3fdb0..2b065b2 100644
+--- a/src/XrrProperty.c
++++ b/src/XrrProperty.c
+@@ -62,7 +62,7 @@ XRRListOutputProperties (Display *dpy, RROutput output, int *nprop)
+ 
+ 	props = (Atom *) Xmalloc (rbytes);
+ 	if (props == NULL) {
+-	    _XEatData (dpy, nbytes);
++	    _XEatDataWords (dpy, rep.length);
+ 	    UnlockDisplay (dpy);
+ 	    SyncHandle ();
+ 	    *nprop = 0;
+@@ -107,7 +107,7 @@ XRRQueryOutputProperty (Display *dpy, RROutput output, Atom property)
+ 
+     prop_info = (XRRPropertyInfo *) Xmalloc (rbytes);
+     if (prop_info == NULL) {
+-	_XEatData (dpy, nbytes);
++	_XEatDataWords(dpy, rep.length);
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return NULL;
+@@ -313,14 +313,13 @@ XRRGetOutputProperty (Display *dpy, RROutput output,
+ 	     * This part of the code should never be reached.  If it is,
+ 	     * the server sent back a property with an invalid format.
+ 	     */
+-	    nbytes = rep.length << 2;
+-	    _XEatData(dpy, (unsigned long) nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return(BadImplementation);
+ 	}
+ 	if (! *prop) {
+-	    _XEatData(dpy, (unsigned long) nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return(BadAlloc);
+diff --git a/src/XrrProvider.c b/src/XrrProvider.c
+index fcd06ff..309e321 100644
+--- a/src/XrrProvider.c
++++ b/src/XrrProvider.c
+@@ -67,7 +67,7 @@ XRRGetProviderResources(Display *dpy, Window window)
+     xrpr = (XRRProviderResources *) Xmalloc(rbytes);
+ 
+     if (xrpr == NULL) {
+-       _XEatData (dpy, (unsigned long) nbytes);
++       _XEatDataWords (dpy, rep.length);
+        UnlockDisplay (dpy);
+        SyncHandle ();
+        return NULL;
+@@ -136,7 +136,7 @@ XRRGetProviderInfo(Display *dpy, XRRScreenResources *resources, RRProvider provi
+ 
+     xpi = (XRRProviderInfo *)Xmalloc(rbytes);
+     if (xpi == NULL) {
+-	_XEatData (dpy, (unsigned long) nbytes);
++	_XEatDataWords (dpy, rep.length - (ProviderInfoExtra >> 2));
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return NULL;
+diff --git a/src/XrrProviderProperty.c b/src/XrrProviderProperty.c
+index c8c08e9..2d90a0a 100644
+--- a/src/XrrProviderProperty.c
++++ b/src/XrrProviderProperty.c
+@@ -62,7 +62,7 @@ XRRListProviderProperties (Display *dpy, RRProvider provider, int *nprop)
+ 
+ 	props = (Atom *) Xmalloc (rbytes);
+ 	if (props == NULL) {
+-	    _XEatData (dpy, nbytes);
++	    _XEatDataWords (dpy, rep.length);
+ 	    UnlockDisplay (dpy);
+ 	    SyncHandle ();
+ 	    *nprop = 0;
+@@ -107,7 +107,7 @@ XRRQueryProviderProperty (Display *dpy, RRProvider provider, Atom property)
+ 
+     prop_info = (XRRPropertyInfo *) Xmalloc (rbytes);
+     if (prop_info == NULL) {
+-	_XEatData (dpy, nbytes);
++	_XEatDataWords (dpy, rep.length);
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return NULL;
+@@ -313,14 +313,13 @@ XRRGetProviderProperty (Display *dpy, RRProvider provider,
+ 	     * This part of the code should never be reached.  If it is,
+ 	     * the server sent back a property with an invalid format.
+ 	     */
+-	    nbytes = rep.length << 2;
+-	    _XEatData(dpy, (unsigned long) nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return(BadImplementation);
+ 	}
+ 	if (! *prop) {
+-	    _XEatData(dpy, (unsigned long) nbytes);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay(dpy);
+ 	    SyncHandle();
+ 	    return(BadAlloc);
+diff --git a/src/XrrScreen.c b/src/XrrScreen.c
+index f830913..08710b6 100644
+--- a/src/XrrScreen.c
++++ b/src/XrrScreen.c
+@@ -129,7 +129,7 @@ doGetScreenResources (Display *dpy, Window window, int poll)
+     if (xrsr == NULL || wire_names == NULL) {
+ 	if (xrsr) Xfree (xrsr);
+ 	if (wire_names) Xfree (wire_names);
+-	_XEatData (dpy, (unsigned long) nbytes);
++	_XEatDataWords (dpy, rep.length);
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return NULL;
+-- 
+1.7.9.2
+
+From 0e79d96c36aef5889ae2e2a3fc2e96e93f30dc21 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 12 Apr 2013 21:44:59 -0700
+Subject: [PATCH:libXrandr 2/6] integer overflow in XRRQueryOutputProperty()
+ [CVE-2013-1986 1/4]
+
+rep.length is a CARD32, while rbytes was a signed int, so
+   rbytes = sizeof (XRRPropertyInfo) + rep.length * sizeof (long);
+could result in integer overflow, leading to an undersized malloc
+and reading data off the connection and writing it past the end of
+the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XrrProperty.c |   13 +++++++++----
+ 1 file changed, 9 insertions(+), 4 deletions(-)
+
+diff --git a/src/XrrProperty.c b/src/XrrProperty.c
+index 2b065b2..50382bf 100644
+--- a/src/XrrProperty.c
++++ b/src/XrrProperty.c
+@@ -31,6 +31,7 @@
+ #include <X11/extensions/render.h>
+ #include <X11/extensions/Xrender.h>
+ #include "Xrandrint.h"
++#include <limits.h>
+ 
+ Atom *
+ XRRListOutputProperties (Display *dpy, RROutput output, int *nprop)
+@@ -84,7 +85,7 @@ XRRQueryOutputProperty (Display *dpy, RROutput output, Atom property)
+     XExtDisplayInfo		*info = XRRFindDisplay(dpy);
+     xRRQueryOutputPropertyReply rep;
+     xRRQueryOutputPropertyReq	*req;
+-    int				rbytes, nbytes;
++    unsigned int		rbytes, nbytes;
+     XRRPropertyInfo		*prop_info;
+ 
+     RRCheckExtension (dpy, info, NULL);
+@@ -102,10 +103,14 @@ XRRQueryOutputProperty (Display *dpy, RROutput output, Atom property)
+ 	return NULL;
+     }
+ 
+-    rbytes = sizeof (XRRPropertyInfo) + rep.length * sizeof (long);
+-    nbytes = rep.length << 2;
++    if (rep.length < ((INT_MAX / sizeof(long)) - sizeof (XRRPropertyInfo))) {
++        rbytes = sizeof (XRRPropertyInfo) + (rep.length * sizeof (long));
++        nbytes = rep.length << 2;
++
++        prop_info = Xmalloc (rbytes);
++    } else
++        prop_info = NULL;
+ 
+-    prop_info = (XRRPropertyInfo *) Xmalloc (rbytes);
+     if (prop_info == NULL) {
+ 	_XEatDataWords(dpy, rep.length);
+ 	UnlockDisplay (dpy);
+-- 
+1.7.9.2
+
+From 1da5b838c2a8565d4d95a4e948f951ce6b466345 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 12 Apr 2013 21:44:59 -0700
+Subject: [PATCH:libXrandr 3/6] integer overflow in XRRQueryProviderProperty()
+ [CVE-2013-1986 2/4]
+
+Same problem as XRRQueryOutputProperty() that it was cloned from
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XrrProviderProperty.c |   13 +++++++++----
+ 1 file changed, 9 insertions(+), 4 deletions(-)
+
+diff --git a/src/XrrProviderProperty.c b/src/XrrProviderProperty.c
+index 2d90a0a..dc699f6 100644
+--- a/src/XrrProviderProperty.c
++++ b/src/XrrProviderProperty.c
+@@ -31,6 +31,7 @@
+ #include <X11/extensions/render.h>
+ #include <X11/extensions/Xrender.h>
+ #include "Xrandrint.h"
++#include <limits.h>
+ 
+ Atom *
+ XRRListProviderProperties (Display *dpy, RRProvider provider, int *nprop)
+@@ -84,7 +85,7 @@ XRRQueryProviderProperty (Display *dpy, RRProvider provider, Atom property)
+     XExtDisplayInfo		*info = XRRFindDisplay(dpy);
+     xRRQueryProviderPropertyReply rep;
+     xRRQueryProviderPropertyReq	*req;
+-    int				rbytes, nbytes;
++    unsigned int		rbytes, nbytes;
+     XRRPropertyInfo		*prop_info;
+ 
+     RRCheckExtension (dpy, info, NULL);
+@@ -102,10 +103,14 @@ XRRQueryProviderProperty (Display *dpy, RRProvider provider, Atom property)
+ 	return NULL;
+     }
+ 
+-    rbytes = sizeof (XRRPropertyInfo) + rep.length * sizeof (long);
+-    nbytes = rep.length << 2;
++    if (rep.length < ((INT_MAX / sizeof(long)) - sizeof (XRRPropertyInfo))) {
++        rbytes = sizeof (XRRPropertyInfo) + (rep.length * sizeof (long));
++        nbytes = rep.length << 2;
++
++        prop_info = Xmalloc (rbytes);
++    } else
++        prop_info = NULL;
+ 
+-    prop_info = (XRRPropertyInfo *) Xmalloc (rbytes);
+     if (prop_info == NULL) {
+ 	_XEatDataWords (dpy, rep.length);
+ 	UnlockDisplay (dpy);
+-- 
+1.7.9.2
+
+From 289a1927949e6f278c18d115772e454837702e35 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 4 May 2013 21:37:49 -0700
+Subject: [PATCH:libXrandr 4/6] integer overflow in XRRGetOutputProperty()
+ [CVE-2013-1986 3/4]
+
+If the reported number of properties is too large, the calculations
+to allocate memory for them may overflow, leaving us returning less
+memory to the caller than implied by the value written to *nitems.
+
+(Same as reported against libX11 XGetWindowProperty by Ilja Van Sprundel)
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XrrProperty.c |   22 ++++++++++++++--------
+ 1 file changed, 14 insertions(+), 8 deletions(-)
+
+diff --git a/src/XrrProperty.c b/src/XrrProperty.c
+index 50382bf..707a28d 100644
+--- a/src/XrrProperty.c
++++ b/src/XrrProperty.c
+@@ -257,7 +257,7 @@ XRRGetOutputProperty (Display *dpy, RROutput output,
+     XExtDisplayInfo		*info = XRRFindDisplay(dpy);
+     xRRGetOutputPropertyReply	rep;
+     xRRGetOutputPropertyReq	*req;
+-    long    			nbytes, rbytes;
++    unsigned long		nbytes, rbytes;
+ 
+     RRCheckExtension (dpy, info, 1);
+ 
+@@ -282,34 +282,40 @@ XRRGetOutputProperty (Display *dpy, RROutput output,
+ 
+     *prop = (unsigned char *) NULL;
+     if (rep.propertyType != None) {
++	int format = rep.format;
++
++	/*
++	 * Protect against both integer overflow and just plain oversized
++	 * memory allocation - no server should ever return this many props.
++	 */
++	if (rep.nItems >= (INT_MAX >> 4))
++	    format = -1;        /* fall through to default error case */
++
+ 	/*
+ 	 * One extra byte is malloced than is needed to contain the property
+ 	 * data, but this last byte is null terminated and convenient for
+ 	 * returning string properties, so the client doesn't then have to
+ 	 * recopy the string to make it null terminated.
+ 	 */
+-	switch (rep.format) {
++	switch (format) {
+ 	case 8:
+ 	    nbytes = rep.nItems;
+ 	    rbytes = rep.nItems + 1;
+-	    if (rbytes > 0 &&
+-		(*prop = (unsigned char *) Xmalloc ((unsigned)rbytes)))
++	    if (rbytes > 0 && (*prop = Xmalloc (rbytes)))
+ 		_XReadPad (dpy, (char *) *prop, nbytes);
+ 	    break;
+ 
+ 	case 16:
+ 	    nbytes = rep.nItems << 1;
+ 	    rbytes = rep.nItems * sizeof (short) + 1;
+-	    if (rbytes > 0 &&
+-		(*prop = (unsigned char *) Xmalloc ((unsigned)rbytes)))
++	    if (rbytes > 0 && (*prop = Xmalloc (rbytes)))
+ 		_XRead16Pad (dpy, (short *) *prop, nbytes);
+ 	    break;
+ 
+ 	case 32:
+ 	    nbytes = rep.nItems << 2;
+ 	    rbytes = rep.nItems * sizeof (long) + 1;
+-	    if (rbytes > 0 &&
+-		(*prop = (unsigned char *) Xmalloc ((unsigned)rbytes)))
++	    if (rbytes > 0 && (*prop = Xmalloc (rbytes)))
+ 		_XRead32 (dpy, (long *) *prop, nbytes);
+ 	    break;
+ 
+-- 
+1.7.9.2
+
+From 4254bf0ee4c7a8f9d03841cf0d8e16cbb201dfbd Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 4 May 2013 21:37:49 -0700
+Subject: [PATCH:libXrandr 5/6] integer overflow in XRRGetProviderProperty()
+ [CVE-2013-1986 4/4]
+
+If the reported number of properties is too large, the calculations
+to allocate memory for them may overflow, leaving us returning less
+memory to the caller than implied by the value written to *nitems.
+
+(Same as reported against libX11 XGetWindowProperty by Ilja Van Sprundel)
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XrrProviderProperty.c |   22 ++++++++++++++--------
+ 1 file changed, 14 insertions(+), 8 deletions(-)
+
+diff --git a/src/XrrProviderProperty.c b/src/XrrProviderProperty.c
+index dc699f6..6989580 100644
+--- a/src/XrrProviderProperty.c
++++ b/src/XrrProviderProperty.c
+@@ -257,7 +257,7 @@ XRRGetProviderProperty (Display *dpy, RRProvider provider,
+     XExtDisplayInfo		*info = XRRFindDisplay(dpy);
+     xRRGetProviderPropertyReply	rep;
+     xRRGetProviderPropertyReq	*req;
+-    long    			nbytes, rbytes;
++    unsigned long		nbytes, rbytes;
+ 
+     RRCheckExtension (dpy, info, 1);
+ 
+@@ -282,34 +282,40 @@ XRRGetProviderProperty (Display *dpy, RRProvider provider,
+ 
+     *prop = (unsigned char *) NULL;
+     if (rep.propertyType != None) {
++	int format = rep.format;
++
++	/*
++	 * Protect against both integer overflow and just plain oversized
++	 * memory allocation - no server should ever return this many props.
++	 */
++	if (rep.nItems >= (INT_MAX >> 4))
++	    format = -1;        /* fall through to default error case */
++
+ 	/*
+ 	 * One extra byte is malloced than is needed to contain the property
+ 	 * data, but this last byte is null terminated and convenient for
+ 	 * returning string properties, so the client doesn't then have to
+ 	 * recopy the string to make it null terminated.
+ 	 */
+-	switch (rep.format) {
++	switch (format) {
+ 	case 8:
+ 	    nbytes = rep.nItems;
+ 	    rbytes = rep.nItems + 1;
+-	    if (rbytes > 0 &&
+-		(*prop = (unsigned char *) Xmalloc ((unsigned)rbytes)))
++	    if (rbytes > 0 && (*prop = Xmalloc (rbytes)))
+ 		_XReadPad (dpy, (char *) *prop, nbytes);
+ 	    break;
+ 
+ 	case 16:
+ 	    nbytes = rep.nItems << 1;
+ 	    rbytes = rep.nItems * sizeof (short) + 1;
+-	    if (rbytes > 0 &&
+-		(*prop = (unsigned char *) Xmalloc ((unsigned)rbytes)))
++	    if (rbytes > 0 && (*prop = Xmalloc (rbytes)))
+ 		_XRead16Pad (dpy, (short *) *prop, nbytes);
+ 	    break;
+ 
+ 	case 32:
+ 	    nbytes = rep.nItems << 2;
+ 	    rbytes = rep.nItems * sizeof (long) + 1;
+-	    if (rbytes > 0 &&
+-		(*prop = (unsigned char *) Xmalloc ((unsigned)rbytes)))
++	    if (rbytes > 0 && (*prop = Xmalloc (rbytes)))
+ 		_XRead32 (dpy, (long *) *prop, nbytes);
+ 	    break;
+ 
+-- 
+1.7.9.2
+
+From c90f74497dbcb96854346435349c6e2207b530c5 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 4 May 2013 21:47:50 -0700
+Subject: [PATCH:libXrandr 6/6] Make XRRGet*Property() always initialize
+ returned values
+
+Avoids memory corruption and other errors when callers access them
+without checking to see if the calls returned an error value.
+
+Callers are still required to check for errors, this just reduces the
+damage when they don't.
+
+(Same as reported against libX11 XGetWindowProperty by Ilja Van Sprundel)
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XrrProperty.c         |    8 +++++++-
+ src/XrrProviderProperty.c |    8 +++++++-
+ 2 files changed, 14 insertions(+), 2 deletions(-)
+
+diff --git a/src/XrrProperty.c b/src/XrrProperty.c
+index 707a28d..2096c56 100644
+--- a/src/XrrProperty.c
++++ b/src/XrrProperty.c
+@@ -259,6 +259,13 @@ XRRGetOutputProperty (Display *dpy, RROutput output,
+     xRRGetOutputPropertyReq	*req;
+     unsigned long		nbytes, rbytes;
+ 
++    /* 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 = *bytes_after = 0L;
++    *prop = (unsigned char *) NULL;
++
+     RRCheckExtension (dpy, info, 1);
+ 
+     LockDisplay (dpy);
+@@ -280,7 +287,6 @@ XRRGetOutputProperty (Display *dpy, RROutput output,
+ 	return ((xError *)&rep)->errorCode;
+     }
+ 
+-    *prop = (unsigned char *) NULL;
+     if (rep.propertyType != None) {
+ 	int format = rep.format;
+ 
+diff --git a/src/XrrProviderProperty.c b/src/XrrProviderProperty.c
+index 6989580..34cc082 100644
+--- a/src/XrrProviderProperty.c
++++ b/src/XrrProviderProperty.c
+@@ -259,6 +259,13 @@ XRRGetProviderProperty (Display *dpy, RRProvider provider,
+     xRRGetProviderPropertyReq	*req;
+     unsigned long		nbytes, rbytes;
+ 
++    /* 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 = *bytes_after = 0L;
++    *prop = (unsigned char *) NULL;
++
+     RRCheckExtension (dpy, info, 1);
+ 
+     LockDisplay (dpy);
+@@ -280,7 +287,6 @@ XRRGetProviderProperty (Display *dpy, RRProvider provider,
+ 	return ((xError *)&rep)->errorCode;
+     }
+ 
+-    *prop = (unsigned char *) NULL;
+     if (rep.propertyType != None) {
+ 	int format = rep.format;
+ 
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXrandr/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXrandr/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # Xrandr 1.x Makefile
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -36,7 +36,7 @@
 TARBALL_SHA1 = 2353d16635a20521a64838f568bb4c8a10823316
 
 # Patches to apply to source after unpacking, in order
-SOURCE_PATCHES = 
+SOURCE_PATCHES = CVE-2013-1986.patch,-p1
 
 # Library name
 LIBNAME=Xrandr
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXrender/CVE-2013-1987.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,333 @@
+From 73e77eb21d649edc1ce1746739f9358e337b2935 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 3 May 2013 22:48:11 -0700
+Subject: [PATCH:libXrender 1/4] Use _XEatDataWords to avoid overflow of
+ rep.length bit shifting
+
+rep.length is a CARD32, so rep.length << 2 could overflow in 32-bit builds
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ configure.ac     |    6 ++++++
+ src/Filter.c     |    2 +-
+ src/Xrender.c    |    4 ++--
+ src/Xrenderint.h |   14 ++++++++++++++
+ 4 files changed, 23 insertions(+), 3 deletions(-)
+
+diff --git a/configure.ac b/configure.ac
+index 19dce7a..7c2496c 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -58,6 +58,12 @@ AC_SUBST(RENDER_VERSION)
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(RENDER, x11 renderproto >= $RENDER_VERSION)
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib release
++SAVE_LIBS="$LIBS"
++LIBS="$RENDER_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
+ AC_CONFIG_FILES([Makefile
+ 		src/Makefile
+ 		xrender.pc])
+diff --git a/src/Filter.c b/src/Filter.c
+index 5fe9df9..924b2a3 100644
+--- a/src/Filter.c
++++ b/src/Filter.c
+@@ -79,7 +79,7 @@ XRenderQueryFilters (Display *dpy, Drawable drawable)
+ 
+     if (!filters)
+     {
+-	_XEatData (dpy, (unsigned long) rep.length << 2);
++	_XEatDataWords(dpy, rep.length);
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return NULL;
+diff --git a/src/Xrender.c b/src/Xrender.c
+index 769503a..5c8e5f5 100644
+--- a/src/Xrender.c
++++ b/src/Xrender.c
+@@ -475,7 +475,7 @@ XRenderQueryFormats (Display *dpy)
+     {
+ 	if (xri) Xfree (xri);
+ 	if (xData) Xfree (xData);
+-	_XEatData (dpy, nbytes);
++	_XEatDataWords (dpy, rep.length);
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return 0;
+@@ -859,7 +859,7 @@ XRenderQueryPictIndexValues(Display			*dpy,
+     values = (XIndexValue *)Xmalloc (rlength);
+     if (!values)
+     {
+-	_XEatData (dpy, nbytes);
++	_XEatDataWords (dpy, rep.length);
+ 	UnlockDisplay (dpy);
+ 	SyncHandle ();
+ 	return NULL;
+diff --git a/src/Xrenderint.h b/src/Xrenderint.h
+index 57b13da..daaa6fe 100644
+--- a/src/Xrenderint.h
++++ b/src/Xrenderint.h
+@@ -109,4 +109,18 @@ XRenderFindDisplay (Display *dpy);
+ #define DataInt32(dpy,d,len)	Data(dpy,(char *) (d),len)
+ #endif
+ 
++#ifndef HAVE__XEATDATAWORDS
++#include <X11/Xmd.h>  /* for LONG64 on 64-bit platforms */
++#include <limits.h>
++
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
++
+ #endif /* _XRENDERINT_H_ */
+-- 
+1.7.9.2
+
+From e52853974664289fe42a92909667ed77cfa1cec5 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 12 Apr 2013 22:45:20 -0700
+Subject: [PATCH:libXrender 2/4] integer overflow in XRenderQueryFilters()
+ [CVE-2013-1987 1/3]
+
+The length, numFilters & numAliases members of the reply are all CARD32
+and need to be bounds checked before multiplying & adding them together
+to come up with the total size to allocate, to avoid integer overflow
+leading to underallocation and writing data from the network past the
+end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Filter.c |   39 +++++++++++++++++++++++++--------------
+ 1 file changed, 25 insertions(+), 14 deletions(-)
+
+diff --git a/src/Filter.c b/src/Filter.c
+index 924b2a3..edfa572 100644
+--- a/src/Filter.c
++++ b/src/Filter.c
+@@ -25,6 +25,7 @@
+ #include <config.h>
+ #endif
+ #include "Xrenderint.h"
++#include <limits.h>
+ 
+ XFilters *
+ XRenderQueryFilters (Display *dpy, Drawable drawable)
+@@ -37,7 +38,7 @@ XRenderQueryFilters (Display *dpy, Drawable drawable)
+     char			*name;
+     char			len;
+     int				i;
+-    long			nbytes, nbytesAlias, nbytesName;
++    unsigned long		nbytes, nbytesAlias, nbytesName;
+ 
+     if (!RenderHasExtension (info))
+ 	return NULL;
+@@ -60,22 +61,32 @@ XRenderQueryFilters (Display *dpy, Drawable drawable)
+ 	SyncHandle ();
+ 	return NULL;
+     }
+-    /*
+-     * Compute total number of bytes for filter names
+-     */
+-    nbytes = (long)rep.length << 2;
+-    nbytesAlias = rep.numAliases * 2;
+-    if (rep.numAliases & 1)
+-	nbytesAlias += 2;
+-    nbytesName = nbytes - nbytesAlias;
+ 
+     /*
+-     * Allocate one giant block for the whole data structure
++     * Limit each component of combined size to 1/4 the max, which is far
++     * more than they should ever possibly need.
+      */
+-    filters = Xmalloc (sizeof (XFilters) +
+-		       rep.numFilters * sizeof (char *) +
+-		       rep.numAliases * sizeof (short) +
+-		       nbytesName);
++    if ((rep.length < (INT_MAX >> 2)) &&
++	(rep.numFilters < ((INT_MAX / 4) / sizeof (char *))) &&
++	(rep.numAliases < ((INT_MAX / 4) / sizeof (short)))) {
++	/*
++	 * Compute total number of bytes for filter names
++	 */
++	nbytes = (unsigned long)rep.length << 2;
++	nbytesAlias = rep.numAliases * 2;
++	if (rep.numAliases & 1)
++	    nbytesAlias += 2;
++	nbytesName = nbytes - nbytesAlias;
++
++	/*
++	 * Allocate one giant block for the whole data structure
++	 */
++	filters = Xmalloc (sizeof (XFilters) +
++			   (rep.numFilters * sizeof (char *)) +
++			   (rep.numAliases * sizeof (short)) +
++			   nbytesName);
++    } else
++	filters = NULL;
+ 
+     if (!filters)
+     {
+-- 
+1.7.9.2
+
+From 9e577d40322b9e3d8bdefec0eefa44d8ead451a4 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 12 Apr 2013 23:02:11 -0700
+Subject: [PATCH:libXrender 3/4] integer overflow in XRenderQueryFormats()
+ [CVE-2013-1987 2/3]
+
+The length, numFormats, numScreens, numDepths, and numVisuals members of
+the reply are all CARD32 and need to be bounds checked before multiplying
+and adding them together to come up with the total size to allocate, to
+avoid integer overflow leading to underallocation and writing data from
+the network past the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Xrender.c |   40 ++++++++++++++++++++++++++--------------
+ 1 file changed, 26 insertions(+), 14 deletions(-)
+
+diff --git a/src/Xrender.c b/src/Xrender.c
+index 5c8e5f5..a62c753 100644
+--- a/src/Xrender.c
++++ b/src/Xrender.c
+@@ -26,6 +26,7 @@
+ #include <config.h>
+ #endif
+ #include "Xrenderint.h"
++#include <limits.h>
+ 
+ XRenderExtInfo XRenderExtensionInfo;
+ char XRenderExtensionName[] = RENDER_NAME;
+@@ -411,8 +412,8 @@ XRenderQueryFormats (Display *dpy)
+     CARD32			*xSubpixel;
+     void			*xData;
+     int				nf, ns, nd, nv;
+-    int				rlength;
+-    int				nbytes;
++    unsigned long		rlength;
++    unsigned long		nbytes;
+ 
+     RenderCheckExtension (dpy, info, 0);
+     LockDisplay (dpy);
+@@ -458,18 +459,29 @@ XRenderQueryFormats (Display *dpy)
+     if (async_state.major_version == 0 && async_state.minor_version < 6)
+ 	rep.numSubpixel = 0;
+ 
+-    xri = (XRenderInfo *) Xmalloc (sizeof (XRenderInfo) +
+-				   rep.numFormats * sizeof (XRenderPictFormat) +
+-				   rep.numScreens * sizeof (XRenderScreen) +
+-				   rep.numDepths * sizeof (XRenderDepth) +
+-				   rep.numVisuals * sizeof (XRenderVisual));
+-    rlength = (rep.numFormats * sizeof (xPictFormInfo) +
+-	       rep.numScreens * sizeof (xPictScreen) +
+-	       rep.numDepths * sizeof (xPictDepth) +
+-	       rep.numVisuals * sizeof (xPictVisual) +
+-	       rep.numSubpixel * 4);
+-    xData = (void *) Xmalloc (rlength);
+-    nbytes = (int) rep.length << 2;
++    if ((rep.numFormats < ((INT_MAX / 4) / sizeof (XRenderPictFormat))) &&
++	(rep.numScreens < ((INT_MAX / 4) / sizeof (XRenderScreen))) &&
++	(rep.numDepths  < ((INT_MAX / 4) / sizeof (XRenderDepth))) &&
++	(rep.numVisuals < ((INT_MAX / 4) / sizeof (XRenderVisual))) &&
++	(rep.numSubpixel < ((INT_MAX / 4) / 4)) &&
++	(rep.length < (INT_MAX >> 2)) ) {
++	xri = Xmalloc (sizeof (XRenderInfo) +
++		       (rep.numFormats * sizeof (XRenderPictFormat)) +
++		       (rep.numScreens * sizeof (XRenderScreen)) +
++		       (rep.numDepths * sizeof (XRenderDepth)) +
++		       (rep.numVisuals * sizeof (XRenderVisual)));
++	rlength = ((rep.numFormats * sizeof (xPictFormInfo)) +
++		   (rep.numScreens * sizeof (xPictScreen)) +
++		   (rep.numDepths * sizeof (xPictDepth)) +
++		   (rep.numVisuals * sizeof (xPictVisual)) +
++		   (rep.numSubpixel * 4));
++	xData = Xmalloc (rlength);
++	nbytes = (unsigned long) rep.length << 2;
++    } else {
++	xri = NULL;
++	xData = NULL;
++	rlength = nbytes = 0;
++    }
+ 
+     if (!xri || !xData || nbytes < rlength)
+     {
+-- 
+1.7.9.2
+
+From 786f78fd8df6d165ccbc81f306fd9f22b5c1551c Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 12 Apr 2013 23:02:11 -0700
+Subject: [PATCH:libXrender 4/4] integer overflow in
+ XRenderQueryPictIndexValues() [CVE-2013-1987
+ 3/3]
+
+The length and numIndexValues members of the reply are both CARD32 and
+need to be bounds checked before multiplying by sizeof (XIndexValue) to
+avoid integer overflow leading to underallocation and writing data from
+the network past the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Xrender.c |   25 ++++++++++++++++---------
+ 1 file changed, 16 insertions(+), 9 deletions(-)
+
+diff --git a/src/Xrender.c b/src/Xrender.c
+index a62c753..3102eb2 100644
+--- a/src/Xrender.c
++++ b/src/Xrender.c
+@@ -844,7 +844,7 @@ XRenderQueryPictIndexValues(Display			*dpy,
+     xRenderQueryPictIndexValuesReq	*req;
+     xRenderQueryPictIndexValuesReply	rep;
+     XIndexValue				*values;
+-    int					nbytes, nread, rlength, i;
++    unsigned int			nbytes, nread, rlength, i;
+ 
+     RenderCheckExtension (dpy, info, NULL);
+ 
+@@ -860,15 +860,22 @@ XRenderQueryPictIndexValues(Display			*dpy,
+ 	return NULL;
+     }
+ 
+-    /* request data length */
+-    nbytes = (long)rep.length << 2;
+-    /* bytes of actual data in the request */
+-    nread = rep.numIndexValues * SIZEOF (xIndexValue);
+-    /* size of array returned to application */
+-    rlength = rep.numIndexValues * sizeof (XIndexValue);
++    if ((rep.length < (INT_MAX >> 2)) &&
++	(rep.numIndexValues < (INT_MAX / sizeof (XIndexValue)))) {
++	/* request data length */
++	nbytes = rep.length << 2;
++	/* bytes of actual data in the request */
++	nread = rep.numIndexValues * SIZEOF (xIndexValue);
++	/* size of array returned to application */
++	rlength = rep.numIndexValues * sizeof (XIndexValue);
++
++	/* allocate returned data */
++	values = Xmalloc (rlength);
++    } else {
++	nbytes = nread = rlength = 0;
++	values = NULL;
++    }
+ 
+-    /* allocate returned data */
+-    values = (XIndexValue *)Xmalloc (rlength);
+     if (!values)
+     {
+ 	_XEatDataWords (dpy, rep.length);
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXrender/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXrender/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # libXrender - Xlib-based client library for Render extension protocol
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -37,7 +37,7 @@
 TARBALL_SHA256= f9b46b93c9bc15d5745d193835ac9ba2a2b411878fad60c504bbb8f98492bbe6
 
 # Patches to apply to source after unpacking, in order
-SOURCE_PATCHES = 
+SOURCE_PATCHES = CVE-2013-1987.patch,-p1
 
 # Library name
 LIBNAME=Xrender
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXres/CVE-2013-1988.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,149 @@
+From 95b352b0f4a1ab1bc254e78adbc73cd65223ded4 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 10:34:22 -0700
+Subject: [PATCH:libXRes 1/3] Use _XEatDataWords to avoid overflow of
+ rep.length shifting
+
+rep.length is a CARD32, so rep.length << 2 could overflow in 32-bit builds
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ configure.ac |    6 ++++++
+ src/XRes.c   |   15 +++++++++++++--
+ 2 files changed, 19 insertions(+), 2 deletions(-)
+
+diff --git a/configure.ac b/configure.ac
+index bc4e8a6..10e47d2 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -55,6 +55,12 @@ RES_VERSION=[`echo $VERSION | sed 's/^\([0-9][0-9]*\.[0-9][0-9]*\).*$/\1/'`]
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(XRES, x11 xext xextproto [resourceproto >= $RES_VERSION])
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib release
++SAVE_LIBS="$LIBS"
++LIBS="$XRES_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
+ AC_CONFIG_FILES([Makefile
+ 		src/Makefile
+ 		man/Makefile
+diff --git a/src/XRes.c b/src/XRes.c
+index 6091c96..ae86206 100644
+--- a/src/XRes.c
++++ b/src/XRes.c
+@@ -12,7 +12,18 @@
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/XResproto.h>
+ #include <X11/extensions/XRes.h>
++#include <limits.h>
+ 
++#ifndef HAVE__XEATDATAWORDS
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
+ 
+ static XExtensionInfo _xres_ext_info_data;
+ static XExtensionInfo *xres_ext_info = &_xres_ext_info_data;
+@@ -131,7 +142,7 @@ Status XResQueryClients (
+             *num_clients = rep.num_clients;
+             result = 1;
+         } else {
+-            _XEatData(dpy, rep.length << 2);
++            _XEatDataWords(dpy, rep.length);
+         }
+     }
+ 
+@@ -183,7 +194,7 @@ Status XResQueryClientResources (
+             *num_types = rep.num_types;
+             result = 1;
+         } else {
+-            _XEatData(dpy, rep.length << 2);
++            _XEatDataWords(dpy, rep.length);
+         }
+     }
+ 
+-- 
+1.7.9.2
+
+From 3ec2db9eeb9ba8fb561802b0c4b8bf79e321b7a2 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 12 Apr 2013 23:36:13 -0700
+Subject: [PATCH:libXRes 2/3] integer overflow in XResQueryClients()
+ [CVE-2013-1988 1/2]
+
+The CARD32 rep.num_clients needs to be bounds checked before multiplying
+by sizeof(XResClient) to avoid integer overflow leading to underallocation
+and writing data from the network past the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XRes.c |    7 ++++++-
+ 1 file changed, 6 insertions(+), 1 deletion(-)
+
+diff --git a/src/XRes.c b/src/XRes.c
+index ae86206..5117321 100644
+--- a/src/XRes.c
++++ b/src/XRes.c
+@@ -129,7 +129,12 @@ Status XResQueryClients (
+     }
+ 
+     if(rep.num_clients) {
+-        if((clnts = Xmalloc(sizeof(XResClient) * rep.num_clients))) {
++        if (rep.num_clients < (INT_MAX / sizeof(XResClient)))
++            clnts = Xmalloc(sizeof(XResClient) * rep.num_clients);
++        else
++            clnts = NULL;
++
++        if (clnts != NULL) {
+             xXResClient scratch;
+             int i;
+ 
+-- 
+1.7.9.2
+
+From ad156a716a324ee60362c8ba66a5ed8c835c219b Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 12 Apr 2013 23:36:13 -0700
+Subject: [PATCH:libXRes 3/3] integer overflow in XResQueryClientResources()
+ [CVE-2013-1988 2/2]
+
+The CARD32 rep.num_types needs to be bounds checked before multiplying
+by sizeof(XResType) to avoid integer overflow leading to underallocation
+and writing data from the network past the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XRes.c |    7 ++++++-
+ 1 file changed, 6 insertions(+), 1 deletion(-)
+
+diff --git a/src/XRes.c b/src/XRes.c
+index 5117321..ff21dd4 100644
+--- a/src/XRes.c
++++ b/src/XRes.c
+@@ -186,7 +186,12 @@ Status XResQueryClientResources (
+     }
+ 
+     if(rep.num_types) {
+-        if((typs = Xmalloc(sizeof(XResType) * rep.num_types))) {
++        if (rep.num_types < (INT_MAX / sizeof(XResType)))
++            typs = Xmalloc(sizeof(XResType) * rep.num_types);
++        else
++            typs = NULL;
++
++        if (typs != NULL) {
+             xXResType scratch;
+             int i;
+ 
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXres/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXres/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # libXres - Xlib-based client library for Xinerama extension protocol
 #
-# Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -40,7 +40,7 @@
 MODULE_LD_OPTIONS = -M $(PWD)/mapfile-vers
 
 # Patches to apply to source after unpacking, in order
-SOURCE_PATCHES = 
+SOURCE_PATCHES = CVE-2013-1988.patch,-p1
 
 # Library name (used for specfiles/mapfiles)
 LIBNAME=XRes
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXt/CVE-2013-2002.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,78 @@
+From 9264a21b688891dbdcee630ff72cf39aa75fc4e1 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 11:44:14 -0800
+Subject: [PATCH:libXt 2/3] unvalidated length in _XtResourceConfigurationEH
+ [CVE-2013-2002]
+
+The RCM_DATA property is expected to be in the format:
+    resource_length, resource, value
+
+If the property contains a resource_length thats results in a pointer
+outside the property string, memory corruption can occur.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/ResConfig.c |   41 ++++++++++++++++++++++++++---------------
+ 1 file changed, 26 insertions(+), 15 deletions(-)
+
+diff --git a/src/ResConfig.c b/src/ResConfig.c
+index 68da536..1f3edbe 100644
+--- a/src/ResConfig.c
++++ b/src/ResConfig.c
+@@ -971,26 +971,37 @@ _XtResourceConfigurationEH (
+ 	 *      resource and value fields.
+ 	 */
+ 		if (data) {
++			char *data_end = data + nitems;
++			char *data_value;
++
+ 			resource_len = Strtoul ((void *)data, &data_ptr, 10);
+-			data_ptr++;
+ 
+-			data_ptr[resource_len] = '\0';
++			if (data_ptr != (char *) data) {
++				data_ptr++;
++				data_value = data_ptr + resource_len;
++			} else /* strtoul failed to convert a number */
++				data_ptr = data_value = NULL;
++
++			if (data_value > data_ptr && data_value < data_end) {
++				*data_value++ = '\0';
+ 
+-			resource = XtNewString (data_ptr);
+-			value = XtNewString (&data_ptr[resource_len + 1]);
++				resource = XtNewString (data_ptr);
++				value = XtNewString (data_value);
+ #ifdef DEBUG
+-			fprintf (stderr, "resource_len=%d\n",resource_len);
+-			fprintf (stderr, "resource = %s\t value = %s\n",
+-					resource, value);
++				fprintf (stderr, "resource_len=%d\n"
++					 resource_len);
++				fprintf (stderr, "resource = %s\t value = %s\n",
++					 resource, value);
+ #endif
+-			/*
+-			 * descend the application widget tree and
+-			 * apply the value to the appropriate widgets
+-			 */
+-			_search_widget_tree (w, resource, value);
+-
+-			XtFree (resource);
+-			XtFree (value);
++				/*
++				 * descend the application widget tree and
++				 * apply the value to the appropriate widgets
++				 */
++				_search_widget_tree (w, resource, value);
++
++				XtFree (resource);
++				XtFree (value);
++			}
+ 		}
+ 	}
+ 
+-- 
+1.7.9.2
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXt/CVE-2013-2005.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,175 @@
+From eae57493feec958bcf733ad0d334715107029f8b Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 11:29:21 -0800
+Subject: [PATCH:libXt 1/3] Unchecked return values of XGetWindowProperty
+ [CVE-2013-2005]
+
+Multiple functions in Selection.c assumed that XGetWindowProperty() would
+always set the pointer to the property, but before libX11 1.6, it could
+fail to do so in some cases, leading to libXt freeing or operating on an
+uninitialized pointer value, so libXt should always initialize the pointers
+and check for failure itself.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Selection.c |   84 +++++++++++++++++++++++++++++++------------------------
+ 1 file changed, 47 insertions(+), 37 deletions(-)
+
+diff --git a/src/Selection.c b/src/Selection.c
+index f35cb44..4f59d70 100644
+--- a/src/Selection.c
++++ b/src/Selection.c
+@@ -839,14 +839,16 @@ static void HandleSelectionEvents(
+ 	      IndirectPair *p;
+ 	      int format;
+ 	      unsigned long bytesafter, length;
+-	      unsigned char *value;
++	      unsigned char *value = NULL;
+ 	      ev.property = event->xselectionrequest.property;
+ 	      StartProtectedSection(ev.display, ev.requestor);
+-	      (void) XGetWindowProperty(ev.display, ev.requestor,
++	      if (XGetWindowProperty(ev.display, ev.requestor,
+ 			event->xselectionrequest.property, 0L, 1000000,
+ 			False,(Atom)AnyPropertyType, &target, &format, &length,
+-			&bytesafter, &value);
+-	      count = BYTELENGTH(length, format) / sizeof(IndirectPair);
++			&bytesafter, &value) == Success)
++		  count = BYTELENGTH(length, format) / sizeof(IndirectPair);
++	      else
++		  count = 0;
+ 	      for (p = (IndirectPair *)value; count; p++, count--) {
+ 		  EndProtectedSection(ctx->dpy);
+ 		  if (!GetConversion(ctx, (XSelectionRequestEvent*)event,
+@@ -1053,9 +1055,10 @@ static Boolean IsINCRtype(
+ 
+     if (prop == None) return False;
+ 
+-    (void)XGetWindowProperty(XtDisplay(info->widget), window, prop, 0L, 0L,
+-			     False, info->ctx->prop_list->incr_atom,
+-			     &type, &format, &length, &bytesafter, &value);
++    if (XGetWindowProperty(XtDisplay(info->widget), window, prop, 0L, 0L,
++			   False, info->ctx->prop_list->incr_atom, &type,
++			   &format, &length, &bytesafter, &value) != Success)
++	return False;
+ 
+     return (type == info->ctx->prop_list->incr_atom);
+ }
+@@ -1069,7 +1072,6 @@ static void ReqCleanup(
+ {
+     CallBackInfo info = (CallBackInfo)closure;
+     unsigned long bytesafter, length;
+-    char *value;
+     int format;
+     Atom target;
+ 
+@@ -1093,17 +1095,19 @@ static void ReqCleanup(
+ 		(ev->xproperty.state == PropertyNewValue) &&
+ 	        (ev->xproperty.atom == info->property)) {
+ 	XPropertyEvent *event = (XPropertyEvent *) ev;
+-        (void) XGetWindowProperty(event->display, XtWindow(widget),
+-			   event->atom, 0L, 1000000, True, AnyPropertyType,
+-			   &target, &format, &length, &bytesafter,
+-			   (unsigned char **) &value);
+-	XFree(value);
+-	if (length == 0) {
+-           XtRemoveEventHandler(widget, (EventMask) PropertyChangeMask, FALSE,
+-			   ReqCleanup, (XtPointer) info );
+-           FreeSelectionProperty(XtDisplay(widget), info->property);
+-	   XtFree(info->value);	/* requestor never got this, so free now */
+-	   FreeInfo(info);
++	char *value = NULL;
++	if (XGetWindowProperty(event->display, XtWindow(widget),
++			       event->atom, 0L, 1000000, True, AnyPropertyType,
++			       &target, &format, &length, &bytesafter,
++			       (unsigned char **) &value) == Success) {
++	    XFree(value);
++	    if (length == 0) {
++		XtRemoveEventHandler(widget, (EventMask) PropertyChangeMask,
++				     FALSE, ReqCleanup, (XtPointer) info );
++		FreeSelectionProperty(XtDisplay(widget), info->property);
++		XtFree(info->value); /* requestor never got this, so free now */
++		FreeInfo(info);
++	    }
+ 	}
+     }
+ }
+@@ -1121,20 +1125,23 @@ static void ReqTimedOut(
+     unsigned long bytesafter;
+     unsigned long proplength;
+     Atom type;
+-    IndirectPair *pairs;
+     XtPointer *c;
+     int i;
+ 
+     if (*info->target == info->ctx->prop_list->indirect_atom) {
+-        (void) XGetWindowProperty(XtDisplay(info->widget),
+-			   XtWindow(info->widget), info->property, 0L,
+-			   10000000, True, AnyPropertyType, &type, &format,
+-			   &proplength, &bytesafter, (unsigned char **) &pairs);
+-       XFree((char*)pairs);
+-       for (proplength = proplength / IndirectPairWordSize, i = 0, c = info->req_closure;
+-	           proplength; proplength--, c++, i++)
+-	    (*info->callbacks[i])(info->widget, *c,
+-   	          &info->ctx->selection, &resulttype, value, &length, &format);
++	IndirectPair *pairs = NULL;
++	if (XGetWindowProperty(XtDisplay(info->widget), XtWindow(info->widget),
++			       info->property, 0L, 10000000, True,
++			       AnyPropertyType, &type, &format, &proplength,
++			       &bytesafter, (unsigned char **) &pairs)
++	    == Success) {
++	    XFree(pairs);
++	    for (proplength = proplength / IndirectPairWordSize, i = 0,
++		     c = info->req_closure;
++		 proplength; proplength--, c++, i++)
++		(*info->callbacks[i])(info->widget, *c, &info->ctx->selection,
++				      &resulttype, value, &length, &format);
++	}
+     } else {
+ 	(*info->callbacks[0])(info->widget, *info->req_closure,
+ 	    &info->ctx->selection, &resulttype, value, &length, &format);
+@@ -1280,12 +1287,13 @@ Boolean HandleNormal(
+     unsigned long length;
+     int format;
+     Atom type;
+-    unsigned char *value;
++    unsigned char *value = NULL;
+     int number = info->current;
+ 
+-    (void) XGetWindowProperty(dpy, XtWindow(widget), property, 0L,
+-			      10000000, False, AnyPropertyType,
+-			      &type, &format, &length, &bytesafter, &value);
++    if (XGetWindowProperty(dpy, XtWindow(widget), property, 0L, 10000000,
++			   False, AnyPropertyType, &type, &format, &length,
++			   &bytesafter, &value) != Success)
++	return FALSE;
+ 
+     if (type == info->ctx->prop_list->incr_atom) {
+ 	unsigned long size = IncrPropSize(widget, value, format, length);
+@@ -1370,7 +1378,6 @@ static void HandleSelectionReplies(
+     Display *dpy = event->display;
+     CallBackInfo info = (CallBackInfo) closure;
+     Select ctx = info->ctx;
+-    IndirectPair *pairs, *p;
+     unsigned long bytesafter;
+     unsigned long length;
+     int format;
+@@ -1385,9 +1392,12 @@ static void HandleSelectionReplies(
+     XtRemoveEventHandler(widget, (EventMask)0, TRUE,
+ 		HandleSelectionReplies, (XtPointer) info );
+     if (event->target == ctx->prop_list->indirect_atom) {
+-        (void) XGetWindowProperty(dpy, XtWindow(widget), info->property, 0L,
+-			   10000000, True, AnyPropertyType, &type, &format,
+-			   &length, &bytesafter, (unsigned char **) &pairs);
++       IndirectPair *pairs = NULL, *p;
++       if (XGetWindowProperty(dpy, XtWindow(widget), info->property, 0L,
++			      10000000, True, AnyPropertyType, &type, &format,
++			      &length, &bytesafter, (unsigned char **) &pairs)
++	   != Success)
++	   length = 0;
+        for (length = length / IndirectPairWordSize, p = pairs,
+ 	    c = info->req_closure;
+ 	    length; length--, p++, c++, info->current++) {
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXt/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXt/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # X Toolkit Intrinsics library (libXt)
 #
-# Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -42,6 +42,7 @@
 
 # Patches to apply to source after unpacking, in order
 SOURCE_PATCHES = 6671721.patch,-p1
+SOURCE_PATCHES += CVE-2013-2002.patch,-p1 CVE-2013-2005.patch,-p1
 
 # Regenerate configure script & Makefile.in's after applying patches
 AUTORECONF=yes
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXtst/CVE-2013-2063.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,170 @@
+From 46ed6283034b5b7d14584009453f5d974cfacf1e Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 11:05:27 -0700
+Subject: [PATCH:libXtst 1/2] Use _XEatDataWords to eat data in error cases
+
+Avoids having to do calculcations based on response contents
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ configure.ac  |    6 ++++++
+ src/XRecord.c |   23 +++++++++++++++++------
+ 2 files changed, 23 insertions(+), 6 deletions(-)
+
+diff --git a/configure.ac b/configure.ac
+index 7ef0153..d83d4d8 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -47,6 +47,12 @@ XORG_CHECK_SGML_DOCTOOLS(1.8)
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(XTST, x11 [xext >= 1.0.99.4] xi [recordproto >= 1.13.99.1] [xextproto >= 7.0.99.3] inputproto)
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib release
++SAVE_LIBS="$LIBS"
++LIBS="$XTST_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
+ # Determine if the source for man pages is available
+ # It may already be present (tarball) or can be generated using xmlto
+ AM_CONDITIONAL([INSTALL_MANPAGES],
+diff --git a/src/XRecord.c b/src/XRecord.c
+index b65451c..ba628b6 100644
+--- a/src/XRecord.c
++++ b/src/XRecord.c
+@@ -49,6 +49,9 @@ from The Open Group.
+  * By Stephen Gildea, X Consortium, and Martha Zimet, NCD.
+  */
+ 
++#ifdef HAVE_CONFIG_H
++#include <config.h>
++#endif
+ #include <stdio.h>
+ #include <assert.h>
+ #include <X11/Xlibint.h>
+@@ -56,6 +59,18 @@ from The Open Group.
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/recordproto.h>
+ #include <X11/extensions/record.h>
++#include <limits.h>
++
++#ifndef HAVE__XEATDATAWORDS
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
+ 
+ static XExtensionInfo _xrecord_info_data;
+ static XExtensionInfo *xrecord_info = &_xrecord_info_data;
+@@ -427,7 +442,7 @@ XRecordGetContext(Display *dpy, XRecordContext context,
+ 
+     ret = (XRecordState*)Xmalloc(sizeof(XRecordState));
+     if (!ret) {
+-	/* XXX - eat data */
++	_XEatDataWords (dpy, rep.length);
+ 	UnlockDisplay(dpy);
+ 	SyncHandle();
+ 	return 0;
+@@ -446,11 +461,7 @@ XRecordGetContext(Display *dpy, XRecordContext context,
+ 	}
+         if (!client_inf || !client_inf_str)
+         {
+-           for(i = 0; i < count; i++)
+-           {
+-	        _XEatData (dpy, sizeof(xRecordClientInfo));
+-                _XEatData (dpy, SIZEOF(xRecordRange)); /* XXX - don't know how many */
+-           }
++	   _XEatDataWords (dpy, rep.length);
+ 	   UnlockDisplay(dpy);
+ 	   XRecordFreeState(ret);
+ 	   SyncHandle();
+-- 
+1.7.9.2
+
+From e7e04b7be3f018ad636aba3a36bfc1cd80b9906d Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 11:27:26 -0700
+Subject: [PATCH:libXtst 2/2] integer overflow in XRecordGetContext()
+ [CVE-2013-2063]
+
+The nclients and nranges members of the reply are both CARD32 and need
+to be bounds checked before multiplying by the size of the structs to
+avoid integer overflow leading to underallocation and writing data from
+the network past the end of the allocated buffer.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XRecord.c |   32 +++++++++++++++++++++-----------
+ 1 file changed, 21 insertions(+), 11 deletions(-)
+
+diff --git a/src/XRecord.c b/src/XRecord.c
+index ba628b6..5bbd5ac 100644
+--- a/src/XRecord.c
++++ b/src/XRecord.c
+@@ -420,11 +420,9 @@ XRecordGetContext(Display *dpy, XRecordContext context,
+     XExtDisplayInfo 	*info = find_display (dpy);
+     register 		xRecordGetContextReq   	*req;
+     xRecordGetContextReply 	rep;
+-    int			count, i, rn;
++    unsigned int	count, i, rn;
+     xRecordRange   	xrange;
+-    XRecordRange	*ranges = NULL;
+     xRecordClientInfo   xclient_inf;
+-    XRecordClientInfo	**client_inf, *client_inf_str = NULL;
+     XRecordState	*ret;
+ 
+     XRecordCheckExtension (dpy, info, 0);
+@@ -454,13 +452,18 @@ XRecordGetContext(Display *dpy, XRecordContext context,
+ 
+     if (count)
+     {
+-     	client_inf = (XRecordClientInfo **) Xcalloc(count, sizeof(XRecordClientInfo*));
+-	ret->client_info = client_inf;
+-	if (client_inf != NULL) {
+-	    client_inf_str = (XRecordClientInfo *) Xmalloc(count*sizeof(XRecordClientInfo));
++	XRecordClientInfo	**client_inf = NULL;
++	XRecordClientInfo	*client_inf_str = NULL;
++
++	if (count < (INT_MAX / sizeof(XRecordClientInfo))) {
++	    client_inf = Xcalloc(count, sizeof(XRecordClientInfo *));
++	    if (client_inf != NULL)
++		client_inf_str = Xmalloc(count * sizeof(XRecordClientInfo));
+ 	}
++	ret->client_info = client_inf;
+         if (!client_inf || !client_inf_str)
+         {
++	   free(client_inf);
+ 	   _XEatDataWords (dpy, rep.length);
+ 	   UnlockDisplay(dpy);
+ 	   XRecordFreeState(ret);
+@@ -476,11 +479,18 @@ XRecordGetContext(Display *dpy, XRecordContext context,
+ 
+ 	    if (xclient_inf.nRanges)
+ 	    {
+-		client_inf_str[i].ranges = (XRecordRange**) Xcalloc(xclient_inf.nRanges, sizeof(XRecordRange*));
+-		if (client_inf_str[i].ranges != NULL) {
+-		    ranges = (XRecordRange*)
+-			Xmalloc(xclient_inf.nRanges * sizeof(XRecordRange));
++		XRecordRange	*ranges = NULL;
++
++		if (xclient_inf.nRanges < (INT_MAX / sizeof(XRecordRange))) {
++		    client_inf_str[i].ranges =
++			Xcalloc(xclient_inf.nRanges, sizeof(XRecordRange *));
++		    if (client_inf_str[i].ranges != NULL)
++			ranges =
++			    Xmalloc(xclient_inf.nRanges * sizeof(XRecordRange));
+ 		}
++		else
++		    client_inf_str[i].ranges = NULL;
++
+ 		if (!client_inf_str[i].ranges || !ranges) {
+ 		    /* XXX eat data */
+ 		    UnlockDisplay(dpy);
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXtst/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXtst/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # libXtst - Xlib-based client library for Xtest & Record extension protocols
 #
-# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -37,8 +37,8 @@
 TARBALL_SHA256= 7eea3e66e392aca3f9dad6238198753c28e1c32fa4903cbb7739607a2504e5e0
 
 # Patches to apply to source after unpacking, in order
-SOURCE_PATCHES = \
-	solaris-abi.patch
+SOURCE_PATCHES  = solaris-abi.patch
+SOURCE_PATCHES += CVE-2013-2063.patch,-p1
 
 # Need to regenerate automake files after solaris-abi.patch
 AUTORECONF=yes
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXv/CVE-2013-1989.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,256 @@
+From 79362c764a6df7e7fbe5247756bdbf60f3a58baf Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 00:28:34 -0700
+Subject: [PATCH:libXv 1/5] Use _XEatDataWords to avoid overflow of rep.length
+ shifting
+
+rep.length is a CARD32, so rep.length << 2 could overflow in 32-bit builds
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ configure.ac |    6 ++++++
+ src/Xv.c     |   22 +++++++++++++++++++---
+ 2 files changed, 25 insertions(+), 3 deletions(-)
+
+diff --git a/configure.ac b/configure.ac
+index 5494b5d..6a335db 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -43,6 +43,12 @@ XORG_CHECK_MALLOC_ZERO
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(XV, x11 xext xextproto videoproto)
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib release
++SAVE_LIBS="$LIBS"
++LIBS="$XV_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
+ # Allow checking code with lint, sparse, etc.
+ XORG_WITH_LINT
+ XORG_LINT_LIBRARY([Xv])
+diff --git a/src/Xv.c b/src/Xv.c
+index b081e8a..5be1d95 100644
+--- a/src/Xv.c
++++ b/src/Xv.c
+@@ -49,11 +49,27 @@ SOFTWARE.
+ **
+ */
+ 
++#ifdef HAVE_CONFIG_H
++# include "config.h"
++#endif
++
+ #include <stdio.h>
+ #include "Xvlibint.h"
+ #include <X11/extensions/Xext.h>
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/XShm.h>
++#include <limits.h>
++
++#ifndef HAVE__XEATDATAWORDS
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
+ 
+ static XExtensionInfo _xv_info_data;
+ static XExtensionInfo *xv_info = &_xv_info_data;
+@@ -853,7 +869,7 @@ XvQueryPortAttributes(Display *dpy, XvPortID port, int *num)
+ 	      (*num)++;
+ 	  }
+       } else
+-	_XEatData(dpy, rep.length << 2);
++	  _XEatDataWords(dpy, rep.length);
+   }
+ 
+   UnlockDisplay(dpy);
+@@ -923,7 +939,7 @@ XvImageFormatValues * XvListImageFormats (
+ 	      (*num)++;
+ 	  }
+       } else
+-	_XEatData(dpy, rep.length << 2);
++	  _XEatDataWords(dpy, rep.length);
+   }
+ 
+   UnlockDisplay(dpy);
+@@ -976,7 +992,7 @@ XvImage * XvCreateImage (
+   	_XRead(dpy, (char*)(ret->pitches), rep.num_planes << 2);
+ 	_XRead(dpy, (char*)(ret->offsets), rep.num_planes << 2);
+    } else
+-	_XEatData(dpy, rep.length << 2);
++       _XEatDataWords(dpy, rep.length);
+ 
+    UnlockDisplay(dpy);
+    SyncHandle();
+-- 
+1.7.9.2
+
+From 6e1b743a276651195be3cd68dff41e38426bf3ab Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 00:03:03 -0700
+Subject: [PATCH:libXv 2/5] integer overflow in XvQueryPortAttributes()
+ [CVE-2013-1989 1/3]
+
+The num_attributes & text_size members of the reply are both CARD32s
+and need to be bounds checked before multiplying & adding them together
+to come up with the total size to allocate, to avoid integer overflow
+leading to underallocation and writing data from the network past the
+end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Xv.c |   10 ++++++++--
+ 1 file changed, 8 insertions(+), 2 deletions(-)
+
+diff --git a/src/Xv.c b/src/Xv.c
+index 5be1d95..3cbad35 100644
+--- a/src/Xv.c
++++ b/src/Xv.c
+@@ -851,9 +851,15 @@ XvQueryPortAttributes(Display *dpy, XvPortID port, int *num)
+   }
+ 
+   if(rep.num_attributes) {
+-      int size = (rep.num_attributes * sizeof(XvAttribute)) + rep.text_size;
++      unsigned long size;
++      /* limit each part to no more than one half the max size */
++      if ((rep.num_attributes < ((INT_MAX / 2) / sizeof(XvAttribute))) &&
++	  (rep.text_size < (INT_MAX / 2))) {
++	  size = (rep.num_attributes * sizeof(XvAttribute)) + rep.text_size;
++	  ret = Xmalloc(size);
++      }
+ 
+-      if((ret = Xmalloc(size))) {
++      if (ret != NULL) {
+ 	  char* marker = (char*)(&ret[rep.num_attributes]);
+ 	  xvAttributeInfo Info;
+ 	  int i;
+-- 
+1.7.9.2
+
+From 15ab7dec17d686c38f2c82ac23a17cac5622322a Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 00:16:14 -0700
+Subject: [PATCH:libXv 3/5] buffer overflow in XvQueryPortAttributes()
+ [CVE-2013-2066]
+
+Each attribute returned in the reply includes the number of bytes
+to read for its marker.  We had been always trusting it, and never
+validating that it wouldn't cause us to write past the end of the
+buffer we allocated based on the reported text_size.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Xv.c |   10 ++++++++--
+ 1 file changed, 8 insertions(+), 2 deletions(-)
+
+diff --git a/src/Xv.c b/src/Xv.c
+index 3cbad35..f9813eb 100644
+--- a/src/Xv.c
++++ b/src/Xv.c
+@@ -864,14 +864,20 @@ XvQueryPortAttributes(Display *dpy, XvPortID port, int *num)
+ 	  xvAttributeInfo Info;
+ 	  int i;
+ 
++	  /* keep track of remaining room for text strings */
++	  size = rep.text_size;
++
+ 	  for(i = 0; i < rep.num_attributes; i++) {
+              _XRead(dpy, (char*)(&Info), sz_xvAttributeInfo);
+ 	      ret[i].flags = (int)Info.flags;
+ 	      ret[i].min_value = Info.min;
+ 	      ret[i].max_value = Info.max;
+ 	      ret[i].name = marker;
+-	      _XRead(dpy, marker, Info.size);
+-	      marker += Info.size;
++	      if (Info.size <= size) {
++		  _XRead(dpy, marker, Info.size);
++		  marker += Info.size;
++		  size -= Info.size;
++	      }
+ 	      (*num)++;
+ 	  }
+       } else
+-- 
+1.7.9.2
+
+From 59301c1b5095f7dc6359d5b396dbbcdee7038270 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 00:03:03 -0700
+Subject: [PATCH:libXv 4/5] integer overflow in XvListImageFormats()
+ [CVE-2013-1989 2/3]
+
+num_formats is a CARD32 and needs to be bounds checked before multiplying
+by sizeof(XvImageFormatValues) to come up with the total size to allocate,
+to avoid integer overflow leading to underallocation and writing data from
+the network past the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Xv.c |    5 +++--
+ 1 file changed, 3 insertions(+), 2 deletions(-)
+
+diff --git a/src/Xv.c b/src/Xv.c
+index f9813eb..0a07d9d 100644
+--- a/src/Xv.c
++++ b/src/Xv.c
+@@ -918,9 +918,10 @@ XvImageFormatValues * XvListImageFormats (
+   }
+ 
+   if(rep.num_formats) {
+-      int size = (rep.num_formats * sizeof(XvImageFormatValues));
++      if (rep.num_formats < (INT_MAX / sizeof(XvImageFormatValues)))
++	  ret = Xmalloc(rep.num_formats * sizeof(XvImageFormatValues));
+ 
+-      if((ret = Xmalloc(size))) {
++      if (ret != NULL) {
+ 	  xvImageFormatInfo Info;
+ 	  int i;
+ 
+-- 
+1.7.9.2
+
+From 50fc4cb18069cb9450a02c13f80223ef23511409 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 00:03:03 -0700
+Subject: [PATCH:libXv 5/5] integer overflow in XvCreateImage() [CVE-2013-1989
+ 3/3]
+
+num_planes is a CARD32 and needs to be bounds checked before bit shifting
+and adding to sizeof(XvImage) to come up with the total size to allocate,
+to avoid integer overflow leading to underallocation and writing data from
+the network past the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/Xv.c |    5 ++++-
+ 1 file changed, 4 insertions(+), 1 deletion(-)
+
+diff --git a/src/Xv.c b/src/Xv.c
+index 0a07d9d..f268f8e 100644
+--- a/src/Xv.c
++++ b/src/Xv.c
+@@ -992,7 +992,10 @@ XvImage * XvCreateImage (
+       return NULL;
+    }
+ 
+-   if((ret = (XvImage*)Xmalloc(sizeof(XvImage) + (rep.num_planes << 3)))) {
++   if (rep.num_planes < ((INT_MAX >> 3) - sizeof(XvImage)))
++       ret = Xmalloc(sizeof(XvImage) + (rep.num_planes << 3));
++
++   if (ret != NULL) {
+ 	ret->id = id;
+ 	ret->width = rep.width;
+ 	ret->height = rep.height;
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXv/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXv/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # libXv - Xlib-based client library for XVideo extension protocol
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -37,7 +37,7 @@
 TARBALL_SHA256= 5d664aeb641f8c867331a0c6b4574a5e7e420f00bf5fcefd874e8d003ea59010
 
 # Patches to apply to source after unpacking, in order
-SOURCE_PATCHES = 
+SOURCE_PATCHES = CVE-2013-1989.patch,-p1
 
 # Library name
 LIBNAME=Xv
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXvMC/CVE-2013-1990.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,329 @@
+From cf1a1dc1b9ca34a29d0471da9389f8eae70ddbd9 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 00:47:57 -0700
+Subject: [PATCH:libXvMC 1/5] Use _XEatDataWords to avoid overflow of
+ rep.length shifting
+
+rep.length is a CARD32, so rep.length << 2 could overflow in 32-bit builds
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ configure.ac |    6 ++++++
+ src/XvMC.c   |   24 ++++++++++++++++++------
+ 2 files changed, 24 insertions(+), 6 deletions(-)
+
+diff --git a/configure.ac b/configure.ac
+index b44f80d..f9d59a1 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -42,6 +42,12 @@ XORG_CHECK_MALLOC_ZERO
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(XVMC, x11 xext xv xextproto videoproto)
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib release
++SAVE_LIBS="$LIBS"
++LIBS="$XVMC_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
+ # Checks for library functions.
+ AC_CHECK_FUNCS([shmat])
+ 
+diff --git a/src/XvMC.c b/src/XvMC.c
+index 5a4cf0d..b3e97ec 100644
+--- a/src/XvMC.c
++++ b/src/XvMC.c
+@@ -16,6 +16,18 @@
+ #include <sys/time.h>
+ #include <X11/extensions/Xext.h>
+ #include <X11/extensions/extutil.h>
++#include <limits.h>
++
++#ifndef HAVE__XEATDATAWORDS
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
+ 
+ static XExtensionInfo _xvmc_info_data;
+ static XExtensionInfo *xvmc_info = &_xvmc_info_data;
+@@ -134,7 +146,7 @@ XvMCSurfaceInfo * XvMCListSurfaceTypes(Display *dpy, XvPortID port, int *num)
+ 	       surface_info[i].flags = sinfo.flags;
+ 	    }
+ 	} else
+-	   _XEatData(dpy, rep.length << 2);
++	   _XEatDataWords(dpy, rep.length);
+     }
+ 
+     UnlockDisplay (dpy);
+@@ -207,7 +219,7 @@ XvImageFormatValues * XvMCListSubpictureTypes (
+               ret[i].scanline_order = Info.scanline_order;
+             }
+         } else
+-	   _XEatData(dpy, rep.length << 2);
++	   _XEatDataWords(dpy, rep.length);
+     }
+ 
+     UnlockDisplay (dpy);
+@@ -278,7 +290,7 @@ Status _xvmc_create_context (
+             _XRead(dpy, (char*)(*priv_data), rep.length << 2);
+ 	    *priv_count = rep.length;
+ 	} else
+-	    _XEatData(dpy, rep.length << 2);
++	    _XEatDataWords(dpy, rep.length);
+     }
+ 
+     UnlockDisplay (dpy);
+@@ -359,7 +371,7 @@ Status _xvmc_create_surface (
+             _XRead(dpy, (char*)(*priv_data), rep.length << 2);
+             *priv_count = rep.length;
+         } else
+-            _XEatData(dpy, rep.length << 2);
++            _XEatDataWords(dpy, rep.length);
+     }
+ 
+     UnlockDisplay (dpy);
+@@ -449,7 +461,7 @@ Status _xvmc_create_subpicture (
+             _XRead(dpy, (char*)(*priv_data), rep.length << 2);
+             *priv_count = rep.length;
+         } else
+-            _XEatData(dpy, rep.length << 2);
++            _XEatDataWords(dpy, rep.length);
+     }
+ 
+     UnlockDisplay (dpy);
+@@ -579,7 +591,7 @@ Status XvMCGetDRInfo(Display *dpy, XvPortID port,
+ 
+ 	} else {
+ 
+-	    _XEatData(dpy, realSize);
++	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay (dpy);
+ 	    SyncHandle ();
+ 	    return -1;
+-- 
+1.7.9.2
+
+From 2712383813b26475dc6713888414d842be57f8ca Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 00:50:02 -0700
+Subject: [PATCH:libXvMC 2/5] integer overflow in XvMCListSurfaceTypes()
+ [CVE-2013-1990 1/2]
+
+rep.num is a CARD32 and needs to be bounds checked before multiplying
+by sizeof(XvMCSurfaceInfo) to come up with the total size to allocate,
+to avoid integer overflow leading to underallocation and writing data from
+the network past the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XvMC.c |    4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/src/XvMC.c b/src/XvMC.c
+index b3e97ec..5d8c2cf 100644
+--- a/src/XvMC.c
++++ b/src/XvMC.c
+@@ -123,8 +123,8 @@ XvMCSurfaceInfo * XvMCListSurfaceTypes(Display *dpy, XvPortID port, int *num)
+     }
+ 
+     if(rep.num > 0) {
+-	surface_info =
+-	    (XvMCSurfaceInfo*)Xmalloc(rep.num * sizeof(XvMCSurfaceInfo));
++        if (rep.num < (INT_MAX / sizeof(XvMCSurfaceInfo)))
++            surface_info = Xmalloc(rep.num * sizeof(XvMCSurfaceInfo));
+ 
+         if(surface_info) {
+ 	    xvmcSurfaceInfo sinfo;
+-- 
+1.7.9.2
+
+From 478d4e5873eeee2ebdce6673e4e3469816ab63b8 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 00:50:02 -0700
+Subject: [PATCH:libXvMC 3/5] integer overflow in XvMCListSubpictureTypes()
+ [CVE-2013-1990 2/2]
+
+rep.num is a CARD32 and needs to be bounds checked before multiplying by
+sizeof(XvImageFormatValues) to come up with the total size to allocate,
+to avoid integer overflow leading to underallocation and writing data from
+the network past the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XvMC.c |    4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/src/XvMC.c b/src/XvMC.c
+index 5d8c2cf..8d602ec 100644
+--- a/src/XvMC.c
++++ b/src/XvMC.c
+@@ -184,8 +184,8 @@ XvImageFormatValues * XvMCListSubpictureTypes (
+     }
+ 
+     if(rep.num > 0) {
+-        ret =
+-	   (XvImageFormatValues*)Xmalloc(rep.num * sizeof(XvImageFormatValues));
++        if (rep.num < (INT_MAX / sizeof(XvImageFormatValues)))
++            ret = Xmalloc(rep.num * sizeof(XvImageFormatValues));
+ 
+         if(ret) {
+             xvImageFormatInfo Info;
+-- 
+1.7.9.2
+
+From 5fd871e5f878810f8f8837725d548e07e89577ab Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 00:50:02 -0700
+Subject: [PATCH:libXvMC 4/5] integer overflow in _xvmc_create_*()
+
+rep.length is a CARD32 and should be bounds checked before left-shifting
+by 2 bits to come up with the total size to allocate, though in these
+cases, no buffer overflow should occur here, since the XRead call is passed
+the same rep.length << 2 length argument, but the *priv_count returned to
+the caller could be interpreted or used to calculate a larger buffer size
+than was actually allocated, leading them to go out of bounds.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XvMC.c |    9 ++++++---
+ 1 file changed, 6 insertions(+), 3 deletions(-)
+
+diff --git a/src/XvMC.c b/src/XvMC.c
+index 8d602ec..d8bc59d 100644
+--- a/src/XvMC.c
++++ b/src/XvMC.c
+@@ -285,7 +285,8 @@ Status _xvmc_create_context (
+     context->flags = rep.flags_return;
+ 
+     if(rep.length) {
+-	*priv_data = Xmalloc(rep.length << 2);
++	if (rep.length < (INT_MAX >> 2))
++	    *priv_data = Xmalloc(rep.length << 2);
+ 	if(*priv_data) {
+             _XRead(dpy, (char*)(*priv_data), rep.length << 2);
+ 	    *priv_count = rep.length;
+@@ -366,7 +367,8 @@ Status _xvmc_create_surface (
+     }
+ 
+     if(rep.length) {
+-        *priv_data = Xmalloc(rep.length << 2);
++        if (rep.length < (INT_MAX >> 2))
++            *priv_data = Xmalloc(rep.length << 2);
+         if(*priv_data) {
+             _XRead(dpy, (char*)(*priv_data), rep.length << 2);
+             *priv_count = rep.length;
+@@ -456,7 +458,8 @@ Status _xvmc_create_subpicture (
+     subpicture->component_order[3] = rep.component_order[3];
+ 
+     if(rep.length) {
+-        *priv_data = Xmalloc(rep.length << 2);
++        if (rep.length < (INT_MAX >> 2))
++            *priv_data = Xmalloc(rep.length << 2);
+         if(*priv_data) {
+             _XRead(dpy, (char*)(*priv_data), rep.length << 2);
+             *priv_count = rep.length;
+-- 
+1.7.9.2
+
+From e9415ddef2ac81d4139bd32d5e9cda9394a60051 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 01:20:08 -0700
+Subject: [PATCH:libXvMC 5/5] Multiple unvalidated assumptions in
+ XvMCGetDRInfo() [CVE-2013-1999]
+
+The individual string sizes is assumed to not be more than the amount of
+data read from the network, and could cause buffer overflow if they are.
+
+The strings returned from the X server are assumed to be null terminated,
+and could cause callers to read past the end of the buffer if they are not.
+
+Also be sure to set the returned pointers to NULL, so callers don't try
+accessing bad pointers on failure cases.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XvMC.c |   36 +++++++++++++++++++-----------------
+ 1 file changed, 19 insertions(+), 17 deletions(-)
+
+diff --git a/src/XvMC.c b/src/XvMC.c
+index d8bc59d..cb42487 100644
+--- a/src/XvMC.c
++++ b/src/XvMC.c
+@@ -499,7 +499,6 @@ Status XvMCGetDRInfo(Display *dpy, XvPortID port,
+     XExtDisplayInfo *info = xvmc_find_display(dpy);
+     xvmcGetDRInfoReply rep;
+     xvmcGetDRInfoReq  *req;
+-    char *tmpBuf = NULL;
+     CARD32 magic;
+ 
+ #ifdef HAVE_SHMAT
+@@ -510,6 +509,9 @@ Status XvMCGetDRInfo(Display *dpy, XvPortID port,
+     here.tz_dsttime = 0;
+ #endif
+ 
++    *name = NULL;
++    *busID = NULL;
++
+     XvMCCheckExtension (dpy, info, BadImplementation);
+ 
+     LockDisplay (dpy);
+@@ -568,31 +570,31 @@ Status XvMCGetDRInfo(Display *dpy, XvPortID port,
+ #endif
+ 
+     if (rep.length > 0) {
+-
+-        int realSize = rep.length << 2;
+-
+-	tmpBuf = (char *) Xmalloc(realSize);
+-	if (tmpBuf) {
+-	    *name = (char *) Xmalloc(rep.nameLen);
+-	    if (*name) {
+-		*busID = (char *) Xmalloc(rep.busIDLen);
+-		if (! *busID) {
+-		    XFree(*name);
+-		    XFree(tmpBuf);
+-		}
+-	    } else {
+-		XFree(tmpBuf);
++	unsigned long realSize = 0;
++	char *tmpBuf = NULL;
++
++	if (rep.length < (INT_MAX >> 2)) {
++	    realSize = rep.length << 2;
++	    if (realSize >= (rep.nameLen + rep.busIDLen)) {
++		tmpBuf = Xmalloc(realSize);
++		*name = Xmalloc(rep.nameLen);
++		*busID = Xmalloc(rep.busIDLen);
+ 	    }
+ 	}
+ 
+ 	if (*name && *busID && tmpBuf) {
+-
+ 	    _XRead(dpy, tmpBuf, realSize);
+ 	    strncpy(*name,tmpBuf,rep.nameLen);
++	    name[rep.nameLen - 1] = '\0';
+ 	    strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen);
++	    busID[rep.busIDLen - 1] = '\0';
+ 	    XFree(tmpBuf);
+-
+ 	} else {
++	    XFree(*name);
++	    *name = NULL;
++	    XFree(*busID);
++	    *name = NULL;
++	    XFree(tmpBuf);
+ 
+ 	    _XEatDataWords(dpy, rep.length);
+ 	    UnlockDisplay (dpy);
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXvMC/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXvMC/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # libXvMC - Xlib-based client library for X-Video Motion Compensation extension
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -37,7 +37,7 @@
 TARBALL_SHA256= 28f085fc8518a3dadfe355360705d50153051f09898093e69af806c0b437cea3
 
 # Patches to apply to source after unpacking, in order
-SOURCE_PATCHES = 
+SOURCE_PATCHES = CVE-2013-1990.patch,-p1
 
 # Library name
 LIBNAME=XvMC
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXxf86vm/CVE-2013-2001.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,222 @@
+From 284a88e21fc05a63466115b33efa411c60d988c9 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 14:24:12 -0700
+Subject: [PATCH:libXxf86vm 1/3] Use _XEatDataWords to avoid overflow of
+ length calculations
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ configure.ac    |    6 ++++++
+ src/XF86VMode.c |   35 +++++++++++++++++++++++++----------
+ 2 files changed, 31 insertions(+), 10 deletions(-)
+
+diff --git a/configure.ac b/configure.ac
+index d8a23b0..b637788 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -22,6 +22,12 @@ XORG_CHECK_MALLOC_ZERO
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(XXF86VM, xproto x11 xextproto xext [xf86vidmodeproto >= 2.2.99.1])
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib release
++SAVE_LIBS="$LIBS"
++LIBS="$XXF86VM_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
+ AC_CONFIG_FILES([Makefile
+ 		src/Makefile
+ 		man/Makefile
+diff --git a/src/XF86VMode.c b/src/XF86VMode.c
+index 1b907f4..bd54937 100644
+--- a/src/XF86VMode.c
++++ b/src/XF86VMode.c
+@@ -30,11 +30,27 @@ from Kaleb S. KEITHLEY.
+ 
+ /* THIS IS NOT AN X CONSORTIUM STANDARD */
+ 
++#ifdef HAVE_CONFIG_H
++#include <config.h>
++#endif
++
+ #include <X11/Xlibint.h>
+ #include <X11/extensions/xf86vmproto.h>
+ #include <X11/extensions/xf86vmode.h>
+ #include <X11/extensions/Xext.h>
+ #include <X11/extensions/extutil.h>
++#include <limits.h>
++
++#ifndef HAVE__XEATDATAWORDS
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
+ 
+ #ifdef DEBUG
+ #include <stdio.h>
+@@ -257,7 +273,8 @@ XF86VidModeGetModeLine(Display* dpy, int screen, int* dotclock,
+     if (modeline->privsize > 0) {
+ 	modeline->private = Xcalloc(modeline->privsize, sizeof(INT32));
+ 	if (modeline->private == NULL) {
+-	    _XEatData(dpy, (modeline->privsize) * sizeof(INT32));
++	    _XEatDataWords(dpy, rep.length -
++		((SIZEOF(xXF86VidModeGetModeLineReply) - SIZEOF(xReply)) >> 2));
+ 	    result = False;
+ 	} else
+ 	    _XRead(dpy, (char*)modeline->private, modeline->privsize * sizeof(INT32));
+@@ -318,10 +335,8 @@ XF86VidModeGetAllModeLines(Display* dpy, int screen, int* modecount,
+     if (!(modelines = (XF86VidModeModeInfo **) Xcalloc(rep.modecount,
+                                           sizeof(XF86VidModeModeInfo *)
+                                           +sizeof(XF86VidModeModeInfo)))) {
+-	if (majorVersion < 2)
+-            _XEatData(dpy, (rep.modecount) * sizeof(xXF86OldVidModeModeInfo));
+-	else
+-            _XEatData(dpy, (rep.modecount) * sizeof(xXF86VidModeModeInfo));
++	_XEatDataWords(dpy, rep.length -
++	    ((SIZEOF(xXF86VidModeGetAllModeLinesReply) - SIZEOF(xReply)) >> 2));
+ 	UnlockDisplay(dpy);
+ 	SyncHandle();
+         return False;
+@@ -354,7 +369,7 @@ XF86VidModeGetAllModeLines(Display* dpy, int screen, int* modecount,
+ 		if (oldxmdline.privsize > 0) {
+ 	            if (!(modelines[i]->private =
+ 			    Xcalloc(oldxmdline.privsize, sizeof(INT32)))) {
+-			_XEatData(dpy, (oldxmdline.privsize) * sizeof(INT32));
++			_XEatDataWords(dpy, oldxmdline.privsize);
+ 		    } else {
+ 			_XRead(dpy, (char*)modelines[i]->private,
+ 			     oldxmdline.privsize * sizeof(INT32));
+@@ -384,7 +399,7 @@ XF86VidModeGetAllModeLines(Display* dpy, int screen, int* modecount,
+ 		if (xmdline.privsize > 0) {
+ 		    if (!(modelines[i]->private =
+ 			    Xcalloc(xmdline.privsize, sizeof(INT32)))) {
+-			_XEatData(dpy, (xmdline.privsize) * sizeof(INT32));
++			_XEatDataWords(dpy, xmdline.privsize);
+ 		    } else {
+ 			_XRead(dpy, (char*)modelines[i]->private,
+ 			     xmdline.privsize * sizeof(INT32));
+@@ -902,8 +917,7 @@ XF86VidModeGetMonitor(Display* dpy, int screen, XF86VidModeMonitor* monitor)
+ 	monitor->hsync = monitor->vsync = NULL;
+     }
+     if (result == False) {
+-	_XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 +
+-		  ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3));
++	_XEatDataWords(dpy, rep.length);
+ 	Xfree(monitor->vendor);
+ 	monitor->vendor = NULL;
+ 	Xfree(monitor->model);
+@@ -1036,7 +1050,8 @@ XF86VidModeGetDotClocks(Display* dpy, int screen, int *flagsPtr,
+ 
+     dotclocks = Xcalloc(rep.clocks, sizeof(int));
+     if (dotclocks == NULL) {
+-        _XEatData(dpy, (rep.clocks) * 4);
++        _XEatDataWords(dpy, rep.length -
++	    ((SIZEOF(xXF86VidModeGetDotClocksReply) - SIZEOF(xReply)) >> 2));
+         result = False;
+     }
+     else {
+-- 
+1.7.9.2
+
+From 47bb28ac0e6e49d3b6eb90c7c215f2fcf54f1a95 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 14:33:32 -0700
+Subject: [PATCH:libXxf86vm 2/3] memory corruption in
+ XF86VidModeGetGammaRamp() [CVE-2013-2001]
+
+We trusted the server not to return more data than the client said it had
+allocated room for, and would overflow the provided buffers if it did.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XF86VMode.c |   21 +++++++++++++--------
+ 1 file changed, 13 insertions(+), 8 deletions(-)
+
+diff --git a/src/XF86VMode.c b/src/XF86VMode.c
+index bd54937..a32564e 100644
+--- a/src/XF86VMode.c
++++ b/src/XF86VMode.c
+@@ -1110,6 +1110,7 @@ XF86VidModeGetGammaRamp (
+     XExtDisplayInfo *info = find_display (dpy);
+     xXF86VidModeGetGammaRampReq *req;
+     xXF86VidModeGetGammaRampReply rep;
++    Bool result = True;
+ 
+     XF86VidModeCheckExtension (dpy, info, False);
+ 
+@@ -1120,19 +1121,23 @@ XF86VidModeGetGammaRamp (
+     req->screen = screen;
+     req->size = size;
+     if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
+-        UnlockDisplay (dpy);
+-        SyncHandle ();
+-        return False;
++        result = False;
+     }
+-    if(rep.size) {
+-	_XRead(dpy, (char*)red, rep.size << 1);
+-	_XRead(dpy, (char*)green, rep.size << 1);
+-	_XRead(dpy, (char*)blue, rep.size << 1);
++    else if (rep.size) {
++	if (rep.size <= size) {
++	    _XRead(dpy, (char*)red, rep.size << 1);
++	    _XRead(dpy, (char*)green, rep.size << 1);
++	    _XRead(dpy, (char*)blue, rep.size << 1);
++	}
++	else {
++	    _XEatDataWords(dpy, rep.length);
++	    result = False;
++	}
+     }
+ 
+     UnlockDisplay(dpy);
+     SyncHandle();
+-    return True;
++    return result;
+ }
+ 
+ Bool XF86VidModeGetGammaRampSize(
+-- 
+1.7.9.2
+
+From 4c4123441e40da97acd10f58911193ad3dcef5cd Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 14:43:48 -0700
+Subject: [PATCH:libXxf86vm 3/3] avoid integer overflow in
+ XF86VidModeGetModeLine()
+
+rep.privsize is a CARD32 and needs to be bounds checked before multiplying
+by sizeof(INT32) to come up with the total size to allocate & read to avoid
+integer overflow, though it would not result in buffer overflow as the same
+calculation was used for both allocation & reading from the network.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/XF86VMode.c |    5 ++++-
+ 1 file changed, 4 insertions(+), 1 deletion(-)
+
+diff --git a/src/XF86VMode.c b/src/XF86VMode.c
+index a32564e..fb94816 100644
+--- a/src/XF86VMode.c
++++ b/src/XF86VMode.c
+@@ -271,7 +271,10 @@ XF86VidModeGetModeLine(Display* dpy, int screen, int* dotclock,
+     }
+ 
+     if (modeline->privsize > 0) {
+-	modeline->private = Xcalloc(modeline->privsize, sizeof(INT32));
++	if (modeline->privsize < (INT_MAX / sizeof(INT32)))
++	    modeline->private = Xcalloc(modeline->privsize, sizeof(INT32));
++	else
++	    modeline->private = NULL;
+ 	if (modeline->private == NULL) {
+ 	    _XEatDataWords(dpy, rep.length -
+ 		((SIZEOF(xXF86VidModeGetModeLineReply) - SIZEOF(xReply)) >> 2));
+-- 
+1.7.9.2
+
--- a/open-src/lib/libXxf86vm/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libXxf86vm/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # libXxf86vm - Xlib-based client library for XFree86-VidMode extension protocol
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -37,7 +37,7 @@
 TARBALL_SHA256= a564172fb866b1b587bbccb7d041088931029845245e0d15c32ca7f1bb48fc84
 
 # Patches to apply to source after unpacking, in order
-SOURCE_PATCHES = 
+SOURCE_PATCHES = upstream-error-fixes.patch,-p1 CVE-2013-2001.patch,-p1
 
 # Library name
 LIBNAME=Xxf86vm
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libXxf86vm/upstream-error-fixes.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,331 @@
+From ef95f1c3737d9efc7d97fb1784f80ef3540a846b Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 15:13:06 -0700
+Subject: [PATCH:libXxf86vm 1/8] When Xcalloc() returns NULL, you don't need
+ to Xfree() it
+
+I have no words to explain how this ever happened.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XF86VMode.c |    5 -----
+ 1 file changed, 5 deletions(-)
+
+diff --git a/src/XF86VMode.c b/src/XF86VMode.c
+index 4f19cf3..c0e50e6 100644
+--- a/src/XF86VMode.c
++++ b/src/XF86VMode.c
+@@ -256,7 +256,6 @@ XF86VidModeGetModeLine(Display* dpy, int screen, int* dotclock,
+     if (modeline->privsize > 0) {
+ 	if (!(modeline->private = Xcalloc(modeline->privsize, sizeof(INT32)))) {
+ 	    _XEatData(dpy, (modeline->privsize) * sizeof(INT32));
+-	    Xfree(modeline->private);
+ 	    return False;
+ 	}
+ 	_XRead(dpy, (char*)modeline->private, modeline->privsize * sizeof(INT32));
+@@ -321,7 +320,6 @@ XF86VidModeGetAllModeLines(Display* dpy, int screen, int* modecount,
+             _XEatData(dpy, (rep.modecount) * sizeof(xXF86OldVidModeModeInfo));
+ 	else
+             _XEatData(dpy, (rep.modecount) * sizeof(xXF86VidModeModeInfo));
+-        Xfree(modelines);
+         return False;
+     }
+     mdinfptr = (XF86VidModeModeInfo *) (
+@@ -353,7 +351,6 @@ XF86VidModeGetAllModeLines(Display* dpy, int screen, int* modecount,
+ 	            if (!(modelines[i]->private =
+ 			    Xcalloc(oldxmdline.privsize, sizeof(INT32)))) {
+ 			_XEatData(dpy, (oldxmdline.privsize) * sizeof(INT32));
+-			Xfree(modelines[i]->private);
+ 		    } else {
+ 			_XRead(dpy, (char*)modelines[i]->private,
+ 			     oldxmdline.privsize * sizeof(INT32));
+@@ -384,7 +381,6 @@ XF86VidModeGetAllModeLines(Display* dpy, int screen, int* modecount,
+ 		    if (!(modelines[i]->private =
+ 			    Xcalloc(xmdline.privsize, sizeof(INT32)))) {
+ 			_XEatData(dpy, (xmdline.privsize) * sizeof(INT32));
+-			Xfree(modelines[i]->private);
+ 		    } else {
+ 			_XRead(dpy, (char*)modelines[i]->private,
+ 			     xmdline.privsize * sizeof(INT32));
+@@ -1039,7 +1035,6 @@ XF86VidModeGetDotClocks(Display* dpy, int screen, int *flagsPtr,
+ 
+     if (!(dotclocks = (int*) Xcalloc(rep.clocks, sizeof(int)))) {
+         _XEatData(dpy, (rep.clocks) * 4);
+-        Xfree(dotclocks);
+         return False;
+     }
+ 
+-- 
+1.7.9.2
+
+From a89b1ad3377bfef9bab52f15f98b00f6540d531a Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 17:40:24 -0700
+Subject: [PATCH:libXxf86vm 2/8] Improve error handling in
+ XF86VidModeGetMonitor()
+
+Ensure that when we return an error we unlock the display first, and
+NULL out any pointers we freed in error cleanup.
+
+Instead of adding these fixes to every error check, instead combine
+the error handling cleanup into a single copy.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XF86VMode.c |   82 ++++++++++++++++++++++++++-----------------------------
+ 1 file changed, 39 insertions(+), 43 deletions(-)
+
+diff --git a/src/XF86VMode.c b/src/XF86VMode.c
+index c0e50e6..165f8ba 100644
+--- a/src/XF86VMode.c
++++ b/src/XF86VMode.c
+@@ -856,6 +856,7 @@ XF86VidModeGetMonitor(Display* dpy, int screen, XF86VidModeMonitor* monitor)
+     xXF86VidModeGetMonitorReq *req;
+     CARD32 syncrange;
+     int i;
++    Bool result = True;
+ 
+     XF86VidModeCheckExtension (dpy, info, False);
+ 
+@@ -875,63 +876,58 @@ XF86VidModeGetMonitor(Display* dpy, int screen, XF86VidModeMonitor* monitor)
+     monitor->bandwidth = (float)rep.bandwidth / 1e6;
+ #endif
+     if (rep.vendorLength) {
+-	if (!(monitor->vendor = (char *)Xcalloc(rep.vendorLength + 1, 1))) {
+-	    _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 +
+-		      ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3));
+-	    return False;
+-	}
++	monitor->vendor = Xcalloc(rep.vendorLength + 1, 1);
++	if (monitor->vendor == NULL)
++	    result = False;
+     } else {
+ 	monitor->vendor = NULL;
+     }
+-    if (rep.modelLength) {
+-	if (!(monitor->model = Xcalloc(rep.modelLength + 1, 1))) {
+-	    _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 +
+-		      ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3));
+-	    if (monitor->vendor)
+-		Xfree(monitor->vendor);
+-	    return False;
+-	}
++    if (result && rep.modelLength) {
++	monitor->model = Xcalloc(rep.modelLength + 1, 1);
++	if (monitor->model == NULL)
++	    result = False;
+     } else {
+ 	monitor->model = NULL;
+     }
+-    if (!(monitor->hsync = Xcalloc(rep.nhsync, sizeof(XF86VidModeSyncRange)))) {
+-	_XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 +
+-		  ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3));
+-
+-	if (monitor->vendor)
+-	    Xfree(monitor->vendor);
+-	if (monitor->model)
+-	    Xfree(monitor->model);
+-	return False;
++    if (result) {
++	monitor->hsync = Xcalloc(rep.nhsync, sizeof(XF86VidModeSyncRange));
++	monitor->vsync = Xcalloc(rep.nvsync, sizeof(XF86VidModeSyncRange));
++	if ((monitor->hsync == NULL) || (monitor->vsync == NULL))
++	    result = False;
++    } else {
++	monitor->hsync = monitor->vsync = NULL;
+     }
+-    if (!(monitor->vsync = Xcalloc(rep.nvsync, sizeof(XF86VidModeSyncRange)))) {
++    if (result == False) {
+ 	_XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 +
+ 		  ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3));
+-	if (monitor->vendor)
+-	    Xfree(monitor->vendor);
+-	if (monitor->model)
+-	    Xfree(monitor->model);
++	Xfree(monitor->vendor);
++	monitor->vendor = NULL;
++	Xfree(monitor->model);
++	monitor->model = NULL;
+ 	Xfree(monitor->hsync);
+-	return False;
+-    }
+-    for (i = 0; i < rep.nhsync; i++) {
+-	_XRead(dpy, (char *)&syncrange, 4);
+-	monitor->hsync[i].lo = (float)(syncrange & 0xFFFF) / 100.0;
+-	monitor->hsync[i].hi = (float)(syncrange >> 16) / 100.0;
++	monitor->hsync = NULL;
++	Xfree(monitor->vsync);
++	monitor->vsync = NULL;
+     }
+-    for (i = 0; i < rep.nvsync; i++) {
+-	_XRead(dpy, (char *)&syncrange, 4);
+-	monitor->vsync[i].lo = (float)(syncrange & 0xFFFF) / 100.0;
+-	monitor->vsync[i].hi = (float)(syncrange >> 16) / 100.0;
++    else {
++	for (i = 0; i < rep.nhsync; i++) {
++	    _XRead(dpy, (char *)&syncrange, 4);
++	    monitor->hsync[i].lo = (float)(syncrange & 0xFFFF) / 100.0;
++	    monitor->hsync[i].hi = (float)(syncrange >> 16) / 100.0;
++	}
++	for (i = 0; i < rep.nvsync; i++) {
++	    _XRead(dpy, (char *)&syncrange, 4);
++	    monitor->vsync[i].lo = (float)(syncrange & 0xFFFF) / 100.0;
++	    monitor->vsync[i].hi = (float)(syncrange >> 16) / 100.0;
++	}
++	if (rep.vendorLength)
++	    _XReadPad(dpy, monitor->vendor, rep.vendorLength);
++	if (rep.modelLength)
++	    _XReadPad(dpy, monitor->model, rep.modelLength);
+     }
+-    if (rep.vendorLength)
+-	_XReadPad(dpy, monitor->vendor, rep.vendorLength);
+-    if (rep.modelLength)
+-	_XReadPad(dpy, monitor->model, rep.modelLength);
+-
+     UnlockDisplay(dpy);
+     SyncHandle();
+-    return True;
++    return result;
+ }
+ 
+ Bool
+-- 
+1.7.9.2
+
+From 8ed00bd0a7c44c7fece687e2566d920ea74ef809 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 17:52:12 -0700
+Subject: [PATCH:libXxf86vm 3/8] Unlock display before returning alloc error
+ in XF86VidModeGetModeLine()
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XF86VMode.c |   12 +++++++-----
+ 1 file changed, 7 insertions(+), 5 deletions(-)
+
+diff --git a/src/XF86VMode.c b/src/XF86VMode.c
+index 165f8ba..28c79c1 100644
+--- a/src/XF86VMode.c
++++ b/src/XF86VMode.c
+@@ -203,6 +203,7 @@ XF86VidModeGetModeLine(Display* dpy, int screen, int* dotclock,
+     xXF86OldVidModeGetModeLineReply oldrep;
+     xXF86VidModeGetModeLineReq *req;
+     int majorVersion, minorVersion;
++    Bool result = True;
+ 
+     XF86VidModeCheckExtension (dpy, info, False);
+     XF86VidModeQueryVersion(dpy, &majorVersion, &minorVersion);
+@@ -254,17 +255,18 @@ XF86VidModeGetModeLine(Display* dpy, int screen, int* dotclock,
+     }
+ 
+     if (modeline->privsize > 0) {
+-	if (!(modeline->private = Xcalloc(modeline->privsize, sizeof(INT32)))) {
++	modeline->private = Xcalloc(modeline->privsize, sizeof(INT32));
++	if (modeline->private == NULL) {
+ 	    _XEatData(dpy, (modeline->privsize) * sizeof(INT32));
+-	    return False;
+-	}
+-	_XRead(dpy, (char*)modeline->private, modeline->privsize * sizeof(INT32));
++	    result = False;
++	} else
++	    _XRead(dpy, (char*)modeline->private, modeline->privsize * sizeof(INT32));
+     } else {
+ 	modeline->private = NULL;
+     }
+     UnlockDisplay(dpy);
+     SyncHandle();
+-    return True;
++    return result;
+ }
+ 
+ Bool
+-- 
+1.7.9.2
+
+From 6c82906f25abcb0f8ec92bcdaf1872bd8b63ca5d Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 17:54:45 -0700
+Subject: [PATCH:libXxf86vm 4/8] Unlock display before returning alloc error
+ in XF86VidModeGetAllModeLines()
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XF86VMode.c |    2 ++
+ 1 file changed, 2 insertions(+)
+
+diff --git a/src/XF86VMode.c b/src/XF86VMode.c
+index 28c79c1..76276b6 100644
+--- a/src/XF86VMode.c
++++ b/src/XF86VMode.c
+@@ -322,6 +322,8 @@ XF86VidModeGetAllModeLines(Display* dpy, int screen, int* modecount,
+             _XEatData(dpy, (rep.modecount) * sizeof(xXF86OldVidModeModeInfo));
+ 	else
+             _XEatData(dpy, (rep.modecount) * sizeof(xXF86VidModeModeInfo));
++	UnlockDisplay(dpy);
++	SyncHandle();
+         return False;
+     }
+     mdinfptr = (XF86VidModeModeInfo *) (
+-- 
+1.7.9.2
+
+From d0355b28dd53fba6fb29c350e090ed4a73d4c480 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 13 Apr 2013 17:58:28 -0700
+Subject: [PATCH:libXxf86vm 5/8] Unlock display before returning alloc error
+ in XF86VidModeGetDotClocks()
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+Reviewed-by: Peter Hutterer <[email protected]>
+---
+ src/XF86VMode.c |   17 ++++++++++-------
+ 1 file changed, 10 insertions(+), 7 deletions(-)
+
+diff --git a/src/XF86VMode.c b/src/XF86VMode.c
+index 76276b6..1b907f4 100644
+--- a/src/XF86VMode.c
++++ b/src/XF86VMode.c
+@@ -1014,6 +1014,7 @@ XF86VidModeGetDotClocks(Display* dpy, int screen, int *flagsPtr,
+     xXF86VidModeGetDotClocksReq *req;
+     int i, *dotclocks;
+     CARD32 dotclk;
++    Bool result = True;
+ 
+     XF86VidModeCheckExtension (dpy, info, False);
+ 
+@@ -1033,19 +1034,21 @@ XF86VidModeGetDotClocks(Display* dpy, int screen, int *flagsPtr,
+     *maxclocksPtr = rep.maxclocks;
+     *flagsPtr     = rep.flags;
+ 
+-    if (!(dotclocks = (int*) Xcalloc(rep.clocks, sizeof(int)))) {
++    dotclocks = Xcalloc(rep.clocks, sizeof(int));
++    if (dotclocks == NULL) {
+         _XEatData(dpy, (rep.clocks) * 4);
+-        return False;
++        result = False;
+     }
+-
+-    for (i = 0; i < rep.clocks; i++) {
+-        _XRead(dpy, (char*)&dotclk, 4);
+-	dotclocks[i] = dotclk;
++    else {
++	for (i = 0; i < rep.clocks; i++) {
++	    _XRead(dpy, (char*)&dotclk, 4);
++	    dotclocks[i] = dotclk;
++	}
+     }
+     *clocksPtr = dotclocks;
+     UnlockDisplay(dpy);
+     SyncHandle();
+-    return True;
++    return result;
+ }
+ 
+ Bool
+-- 
+1.7.9.2
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libdmx/CVE-2013-1992.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,290 @@
+From f34f6f64698c3b957aadba7315bb13726e3d79b0 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 3 May 2013 23:10:47 -0700
+Subject: [PATCH:libdmx 1/4] Use _XEatDataWords to avoid overflow of
+ rep.length bit shifting
+
+rep.length is a CARD32, so rep.length << 2 could overflow in 32-bit builds
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ configure.ac |    7 +++++++
+ src/dmx.c    |   17 +++++++++++++++++
+ 2 files changed, 24 insertions(+)
+
+diff --git a/configure.ac b/configure.ac
+index 24e03fc..4629cf8 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -43,6 +43,13 @@ XORG_CHECK_MALLOC_ZERO
+ # Obtain compiler/linker options for depedencies
+ PKG_CHECK_MODULES(DMX, x11 xext xextproto [dmxproto >= 2.2.99.1])
+ 
++# Check for _XEatDataWords function that may be patched into older Xlib releases
++SAVE_LIBS="$LIBS"
++LIBS="$DMX_LIBS"
++AC_CHECK_FUNCS([_XEatDataWords])
++LIBS="$SAVE_LIBS"
++
++
+ AC_CONFIG_FILES([Makefile
+ 		src/Makefile
+ 		man/Makefile
+diff --git a/src/dmx.c b/src/dmx.c
+index 201568e..e43d624 100644
+--- a/src/dmx.c
++++ b/src/dmx.c
+@@ -38,12 +38,16 @@
+  * can be included in client applications by linking with the libdmx.a
+  * library. */
+ 
++#ifdef HAVE_CONFIG_H
++# include "config.h"
++#endif
+ #include <X11/Xlibint.h>
+ #include <X11/extensions/Xext.h>
+ #define EXTENSION_PROC_ARGS void *
+ #include <X11/extensions/extutil.h>
+ #include <X11/extensions/dmxproto.h>
+ #include <X11/extensions/dmxext.h>
++#include <limits.h>
+ 
+ static XExtensionInfo dmx_extension_info_data;
+ static XExtensionInfo *dmx_extension_info = &dmx_extension_info_data;
+@@ -82,6 +86,19 @@ static XEXT_GENERATE_FIND_DISPLAY(find_display, dmx_extension_info,
+ 
+ static XEXT_GENERATE_CLOSE_DISPLAY(close_display, dmx_extension_info)
+ 
++#ifndef HAVE__XEATDATAWORDS
++#include <X11/Xmd.h>  /* for LONG64 on 64-bit platforms */
++
++static inline void _XEatDataWords(Display *dpy, unsigned long n)
++{
++# ifndef LONG64
++    if (n >= (ULONG_MAX >> 2))
++        _XIOError(dpy);
++# endif
++    _XEatData (dpy, n << 2);
++}
++#endif
++
+ 
+ /*****************************************************************************
+  *                                                                           *
+-- 
+1.7.9.2
+
+From 78e11efe70d00063c830475eaaaa42f19380755d Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 13:48:28 -0800
+Subject: [PATCH:libdmx 2/4] integer overflow in DMXGetScreenAttributes()
+ [CVE-2013-1992 1/3]
+
+If the server provided displayNameLength causes integer overflow
+when padding length is added, a smaller buffer would be allocated
+than the amount of data written to it.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/dmx.c |   17 +++++++++++++++--
+ 1 file changed, 15 insertions(+), 2 deletions(-)
+
+diff --git a/src/dmx.c b/src/dmx.c
+index e43d624..15a6650 100644
+--- a/src/dmx.c
++++ b/src/dmx.c
+@@ -250,6 +250,7 @@ Bool DMXGetScreenAttributes(Display *dpy, int physical_screen,
+     XExtDisplayInfo              *info = find_display(dpy);
+     xDMXGetScreenAttributesReply rep;
+     xDMXGetScreenAttributesReq   *req;
++    Bool                          ret = False;
+ 
+     DMXCheckExtension(dpy, info, False);
+ 
+@@ -264,7 +265,15 @@ Bool DMXGetScreenAttributes(Display *dpy, int physical_screen,
+         SyncHandle();
+         return False;
+     }
+-    attr->displayName  = Xmalloc(rep.displayNameLength + 1 + 4 /* for pad */);
++
++    if (rep.displayNameLength < 1024)
++        attr->displayName = Xmalloc(rep.displayNameLength + 1 + 4 /* for pad */);
++    else
++        attr->displayName = NULL;  /* name length is unbelievable, reject */
++    if (attr->displayName == NULL) {
++        _XEatDataWords(dpy, rep.length);
++        goto end;
++    }
+     _XReadPad(dpy, attr->displayName, rep.displayNameLength);
+     attr->displayName[rep.displayNameLength] = '\0';
+     attr->logicalScreen       = rep.logicalScreen;
+@@ -280,9 +289,13 @@ Bool DMXGetScreenAttributes(Display *dpy, int physical_screen,
+     attr->rootWindowYoffset   = rep.rootWindowYoffset;
+     attr->rootWindowXorigin   = rep.rootWindowXorigin;
+     attr->rootWindowYorigin   = rep.rootWindowYorigin;
++
++    ret = True;
++
++  end:
+     UnlockDisplay(dpy);
+     SyncHandle();
+-    return True;
++    return ret;
+ }
+ 
+ static CARD32 _DMXGetScreenAttribute(int bit, DMXScreenAttributes *attr)
+-- 
+1.7.9.2
+
+From b6fe1a7af34ea620e002fc453f9c5eacf7db3969 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 13:48:28 -0800
+Subject: [PATCH:libdmx 3/4] integer overflow in DMXGetWindowAttributes()
+ [CVE-2013-1992 2/3]
+
+If the server provided screenCount causes integer overflow when
+multiplied by the size of each array element, a smaller buffer
+would be allocated than the amount of data written to it.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/dmx.c |   34 ++++++++++++++++++++++++++++------
+ 1 file changed, 28 insertions(+), 6 deletions(-)
+
+diff --git a/src/dmx.c b/src/dmx.c
+index 15a6650..67434c8 100644
+--- a/src/dmx.c
++++ b/src/dmx.c
+@@ -524,6 +524,7 @@ Bool DMXGetWindowAttributes(Display *dpy, Window window,
+     CARD32                       *windows; /* Must match protocol size */
+     XRectangle                   *pos;     /* Must match protocol size */
+     XRectangle                   *vis;     /* Must match protocol size */
++    Bool                          ret = False;
+ 
+     DMXCheckExtension(dpy, info, False);
+ 
+@@ -538,11 +539,30 @@ Bool DMXGetWindowAttributes(Display *dpy, Window window,
+         return False;
+     }
+ 
+-                                /* FIXME: check for NULL? */
+-    screens    = Xmalloc(rep.screenCount * sizeof(*screens));
+-    windows    = Xmalloc(rep.screenCount * sizeof(*windows));
+-    pos        = Xmalloc(rep.screenCount * sizeof(*pos));
+-    vis        = Xmalloc(rep.screenCount * sizeof(*vis));
++    /*
++     * rep.screenCount is a CARD32 so could be as large as 2^32
++     * The X11 protocol limits the total screen size to 64k x 64k,
++     * and no screen can be smaller than a pixel.  While technically
++     * that means we could theoretically reach 2^32 screens, and that's
++     * not even taking overlap into account, 64k seems far larger than
++     * any reasonable configuration, so we limit to that to prevent both
++     * integer overflow in the size calculations, and bad X server
++     * responses causing massive memory allocation.
++     */
++    if (rep.screenCount < 65536) {
++        screens    = Xmalloc(rep.screenCount * sizeof(*screens));
++        windows    = Xmalloc(rep.screenCount * sizeof(*windows));
++        pos        = Xmalloc(rep.screenCount * sizeof(*pos));
++        vis        = Xmalloc(rep.screenCount * sizeof(*vis));
++    } else {
++        screens = windows = NULL;
++        pos = vis = NULL;
++    }
++
++    if (!screens || !windows || !pos || !vis) {
++        _XEatDataWords(dpy, rep.length);
++        goto end;
++    }
+ 
+     _XRead(dpy, (char *)screens, rep.screenCount * sizeof(*screens));
+     _XRead(dpy, (char *)windows, rep.screenCount * sizeof(*windows));
+@@ -558,7 +578,9 @@ Bool DMXGetWindowAttributes(Display *dpy, Window window,
+         inf->pos       = pos[current];
+         inf->vis       = vis[current];
+     }
++    ret = True;
+ 
++  end:
+     Xfree(vis);
+     Xfree(pos);
+     Xfree(windows);
+@@ -566,7 +588,7 @@ Bool DMXGetWindowAttributes(Display *dpy, Window window,
+ 
+     UnlockDisplay(dpy);
+     SyncHandle();
+-    return True;
++    return ret;
+ }
+ 
+ /** If the DMXGetDesktopAttributes protocol request returns information
+-- 
+1.7.9.2
+
+From 5074d9d64192bd04519a438062b7d5bf216d06ee Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Sat, 9 Mar 2013 13:48:28 -0800
+Subject: [PATCH:libdmx 4/4] integer overflow in DMXGetInputAttributes()
+ [CVE-2013-1992 3/3]
+
+If the server provided nameLength causes integer overflow
+when padding length is added, a smaller buffer would be allocated
+than the amount of data written to it.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/dmx.c |   16 ++++++++++++++--
+ 1 file changed, 14 insertions(+), 2 deletions(-)
+
+diff --git a/src/dmx.c b/src/dmx.c
+index 67434c8..d097062 100644
+--- a/src/dmx.c
++++ b/src/dmx.c
+@@ -723,6 +723,7 @@ Bool DMXGetInputAttributes(Display *dpy, int id, DMXInputAttributes *inf)
+     xDMXGetInputAttributesReply rep;
+     xDMXGetInputAttributesReq   *req;
+     char                        *buffer;
++    Bool                         ret = False;
+ 
+     DMXCheckExtension(dpy, info, False);
+ 
+@@ -737,6 +738,16 @@ Bool DMXGetInputAttributes(Display *dpy, int id, DMXInputAttributes *inf)
+         return False;
+     }
+ 
++    if (rep.nameLength < 1024)
++        buffer      = Xmalloc(rep.nameLength + 1 + 4 /* for pad */);
++    else
++        buffer      = NULL;  /* name length is unbelievable, reject */
++
++    if (buffer == NULL) {
++        _XEatDataWords(dpy, rep.length);
++        goto end;
++    }
++
+     switch (rep.inputType) {
+     case 0: inf->inputType = DMXLocalInputType;   break;
+     case 1: inf->inputType = DMXConsoleInputType; break;
+@@ -748,13 +759,14 @@ Bool DMXGetInputAttributes(Display *dpy, int id, DMXInputAttributes *inf)
+     inf->isCore         = rep.isCore;
+     inf->sendsCore      = rep.sendsCore;
+     inf->detached       = rep.detached;
+-    buffer              = Xmalloc(rep.nameLength + 1 + 4 /* for pad */);
+     _XReadPad(dpy, buffer, rep.nameLength);
+     buffer[rep.nameLength] = '\0';
+     inf->name           = buffer;
++    ret = True;
++  end:
+     UnlockDisplay(dpy);
+     SyncHandle();
+-    return True;
++    return ret;
+ }
+ 
+ /** Add input. */
+-- 
+1.7.9.2
+
--- a/open-src/lib/libdmx/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libdmx/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -2,7 +2,7 @@
 #
 # Xlib-based client library for Distributed Multihead X (DMX) extension
 #
-# Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
@@ -36,6 +36,9 @@
 TARBALL_SHA1  = 76956d4127ded2e6d1bb5746a6d1603ee23b442a
 TARBALL_SHA256= a7870b648a8768d65432af76dd11581ff69f3955118540d5967eb1eef43838ba
 
+# Patches to apply to source after unpacking, in order
+SOURCE_PATCHES = CVE-2013-1992.patch,-p1
+
 # Package metadata
 ORACLE_TPNO = 3811
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/libxcb/CVE-2013-2064.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,48 @@
+From e480abd0af181242022a85bff2d4d5e73385255e Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Wed, 1 May 2013 17:59:31 -0700
+Subject: [PATCH:libxcb] integer overflow in read_packet() [CVE-2013-2064]
+
+Ensure that when calculating the size of the incoming response from the
+Xserver, we don't overflow the integer used in the calculations when we
+multiply the int32_t length by 4 and add it to the default response size.
+
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/xcb_in.c |   13 +++++++++----
+ 1 file changed, 9 insertions(+), 4 deletions(-)
+
+diff --git a/src/xcb_in.c b/src/xcb_in.c
+index b810783..8a7af92 100644
+--- a/src/xcb_in.c
++++ b/src/xcb_in.c
+@@ -93,8 +93,9 @@ static void remove_finished_readers(reader_list **prev_reader, uint64_t complete
+ static int read_packet(xcb_connection_t *c)
+ {
+     xcb_generic_reply_t genrep;
+-    int length = 32;
+-    int eventlength = 0; /* length after first 32 bytes for GenericEvents */
++    uint64_t length = 32;
++    uint64_t eventlength = 0; /* length after first 32 bytes for GenericEvents */
++    uint64_t bufsize;
+     void *buf;
+     pending_reply *pend = 0;
+     struct event_list *event;
+@@ -169,8 +170,12 @@ static int read_packet(xcb_connection_t *c)
+     if ((genrep.response_type & 0x7f) == XCB_XGE_EVENT)
+         eventlength = genrep.length * 4;
+ 
+-    buf = malloc(length + eventlength +
+-            (genrep.response_type == XCB_REPLY ? 0 : sizeof(uint32_t)));
++    bufsize = length + eventlength +
++        (genrep.response_type == XCB_REPLY ? 0 : sizeof(uint32_t));
++    if (bufsize < INT32_MAX)
++        buf = malloc((size_t) bufsize);
++    else
++        buf = NULL;
+     if(!buf)
+     {
+         _xcb_conn_shutdown(c, XCB_CONN_CLOSED_MEM_INSUFFICIENT);
+-- 
+1.7.9.2
+
--- a/open-src/lib/libxcb/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/libxcb/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -46,6 +46,7 @@
 SOURCE_PATCHES  = Makefile.am.0.patch,-p1
 SOURCE_PATCHES += Makefile.am.4.patch,-p1
 SOURCE_PATCHES += 16702043.patch
+SOURCE_PATCHES += CVE-2013-2064.patch,-p1
 
 # Regenerate Makefile.in's from Makefile.am's after patching them
 AUTORECONF=yes
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/open-src/lib/mesa/CVE-2013-1993.patch	Wed May 08 18:06:35 2013 -0700
@@ -0,0 +1,86 @@
+From e13eef2d952fdc082f76f66bebe6cee08c5144ab Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 26 Apr 2013 16:31:58 -0700
+Subject: [PATCH:mesa 1/2] integer overflow in XF86DRIOpenConnection()
+ [CVE-2013-1993 1/2]
+
+busIdStringLength is a CARD32 and needs to be bounds checked before adding
+one to it to come up with the total size to allocate, to avoid integer
+overflow leading to underallocation and writing data from the network past
+the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/glx/XF86dri.c |    7 ++++++-
+ 1 file changed, 6 insertions(+), 1 deletion(-)
+
+diff --git a/src/glx/XF86dri.c b/src/glx/XF86dri.c
+index b1cdc9b..8f53bd7 100644
+--- a/src/glx/XF86dri.c
++++ b/src/glx/XF86dri.c
+@@ -43,6 +43,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ #include <X11/extensions/Xext.h>
+ #include <X11/extensions/extutil.h>
+ #include "xf86dristr.h"
++#include <limits.h>
+ 
+ static XExtensionInfo _xf86dri_info_data;
+ static XExtensionInfo *xf86dri_info = &_xf86dri_info_data;
+@@ -201,7 +202,11 @@ XF86DRIOpenConnection(Display * dpy, int screen, drm_handle_t * hSAREA,
+    }
+ 
+    if (rep.length) {
+-      if (!(*busIdString = (char *) Xcalloc(rep.busIdStringLength + 1, 1))) {
++      if (rep.busIdStringLength < INT_MAX)
++         *busIdString = calloc(rep.busIdStringLength + 1, 1);
++      else
++         *busIdString = NULL;
++      if (*busIdString == NULL) {
+          _XEatData(dpy, ((rep.busIdStringLength + 3) & ~3));
+          UnlockDisplay(dpy);
+          SyncHandle();
+
+-- 
+1.7.9.2
+
+From 166bdb02bbbe73c11bc4b96a29f277695f4ae495 Mon Sep 17 00:00:00 2001
+From: Alan Coopersmith <[email protected]>
+Date: Fri, 26 Apr 2013 16:33:03 -0700
+Subject: [PATCH:mesa 2/2] integer overflow in XF86DRIGetClientDriverName()
+ [CVE-2013-1993 2/2]
+
+clientDriverNameLength is a CARD32 and needs to be bounds checked before
+adding one to it to come up with the total size to allocate, to avoid
+integer overflow leading to underallocation and writing data from the
+network past the end of the allocated buffer.
+
+Reported-by: Ilja Van Sprundel <[email protected]>
+Signed-off-by: Alan Coopersmith <[email protected]>
+---
+ src/glx/XF86dri.c |    8 +++++---
+ 1 file changed, 5 insertions(+), 3 deletions(-)
+
+diff --git a/src/glx/XF86dri.c b/src/glx/XF86dri.c
+index 8f53bd7..56e3557 100644
+--- a/src/glx/XF86dri.c
++++ b/src/glx/XF86dri.c
+@@ -305,9 +305,11 @@ XF86DRIGetClientDriverName(Display * dpy, int screen,
+    *ddxDriverPatchVersion = rep.ddxDriverPatchVersion;
+ 
+    if (rep.length) {
+-      if (!
+-          (*clientDriverName =
+-           (char *) Xcalloc(rep.clientDriverNameLength + 1, 1))) {
++      if (rep.clientDriverNameLength < INT_MAX)
++         *clientDriverName = calloc(rep.clientDriverNameLength + 1, 1);
++      else
++         *clientDriverName = NULL;
++      if (*clientDriverName == NULL) {
+          _XEatData(dpy, ((rep.clientDriverNameLength + 3) & ~3));
+          UnlockDisplay(dpy);
+          SyncHandle();
+
+-- 
+1.7.9.2
+
--- a/open-src/lib/mesa/Makefile	Thu May 02 12:44:00 2013 -0700
+++ b/open-src/lib/mesa/Makefile	Wed May 08 18:06:35 2013 -0700
@@ -65,6 +65,7 @@
 
 # Patches to apply to source after unpacking, in order
 SOURCE_PATCHES= \
+	CVE-2013-1993.patch,-p1 \
 	install-pc-dir.patch \
 	glu-no-mangled-exports.patch \
 	solaris-port.patch \