[Xquartz-changes] xserver: Branch 'server-1.12-apple' - 122 commits

Jeremy Huddleston jeremyhu at freedesktop.org
Mon Dec 19 21:44:51 PST 2011


Rebased ref, commits from common ancestor:
commit 3b6f4f5fe23ab6f1753dba596628710dd0f89c36
Author: Jeremy Huddleston <jeremyhu at apple.com>
Date:   Fri Feb 12 19:48:52 2010 -0800

    fb: Revert fb changes that broke XQuartz
    
    http://bugs.freedesktop.org/show_bug.cgi?id=26124
    
    Revert "Fix source pictures getting random transforms after 2d6a8f668342a5190cdf43b5."
    Revert "fb: Adjust transform or composite coordinates for pixman operations"
    
    http://bugs.freedesktop.org/26124
    
    This reverts commit a72c65e9176c51de95db2fdbf4c5d946a4911695.
    This reverts commit a6bd5d2e482a5aa84acb3d4932e2a166d8670ef1.
    
    Signed-off-by: Jeremy Huddleston <jeremyhu at apple.com>

diff --git a/fb/fb.h b/fb/fb.h
index eaa21ad..e65a1c0 100644
--- a/fb/fb.h
+++ b/fb/fb.h
@@ -2049,11 +2049,8 @@ fbFillRegionSolid (DrawablePtr	pDrawable,
 		   FbBits	xor);
 
 extern _X_EXPORT pixman_image_t *
-image_from_pict (PicturePtr	pict,
-		 Bool		has_clip,
-		 int		*xoff,
-		 int		*yoff);
-
+image_from_pict (PicturePtr pict,
+		 Bool       has_clip);
 extern _X_EXPORT void free_pixman_pict (PicturePtr, pixman_image_t *);
 
 #endif /* _FB_H_ */
diff --git a/fb/fbpict.c b/fb/fbpict.c
index 57c93fd..127e5c7 100644
--- a/fb/fbpict.c
+++ b/fb/fbpict.c
@@ -50,24 +50,19 @@ fbComposite (CARD8      op,
 	     CARD16     height)
 {
     pixman_image_t *src, *mask, *dest;
-    int src_xoff, src_yoff;
-    int msk_xoff, msk_yoff;
-    int dst_xoff, dst_yoff;
     
     miCompositeSourceValidate (pSrc);
     if (pMask)
 	miCompositeSourceValidate (pMask);
     
-    src = image_from_pict (pSrc, FALSE, &src_xoff, &src_yoff);
-    mask = image_from_pict (pMask, FALSE, &msk_xoff, &msk_yoff);
-    dest = image_from_pict (pDst, TRUE, &dst_xoff, &dst_yoff);
+    src = image_from_pict (pSrc, TRUE);
+    mask = image_from_pict (pMask, TRUE);
+    dest = image_from_pict (pDst, TRUE);
 
     if (src && dest && !(pMask && !mask))
     {
 	pixman_image_composite (op, src, mask, dest,
-				xSrc + src_xoff, ySrc + src_yoff,
-				xMask + msk_xoff, yMask + msk_yoff,
-				xDst + dst_xoff, yDst + dst_yoff,
+				xSrc, ySrc, xMask, yMask, xDst, yDst,
 				width, height);
     }
 
@@ -146,22 +141,22 @@ create_conical_gradient_image (PictGradient *gradient)
 
 static pixman_image_t *
 create_bits_picture (PicturePtr pict,
-		     Bool       has_clip,
-		     int	*xoff,
-		     int	*yoff)
+		     Bool       has_clip)
 {
-    PixmapPtr pixmap;
     FbBits *bits;
     FbStride stride;
-    int bpp;
+    int bpp, xoff, yoff;
     pixman_image_t *image;
     
-    fbGetDrawablePixmap (pict->pDrawable, pixmap, *xoff, *yoff);
-    fbGetPixmapBitsData(pixmap, bits, stride, bpp);
+    fbGetDrawable (pict->pDrawable, bits, stride, bpp, xoff, yoff);
+
+    bits = (FbBits*)((CARD8*)bits +
+		     (pict->pDrawable->y + yoff) * stride * sizeof(FbBits) +
+		     (pict->pDrawable->x + xoff) * (bpp / 8));
 
     image = pixman_image_create_bits (
 	(pixman_format_code_t)pict->format,
-	pixmap->drawable.width, pixmap->drawable.height,
+	pict->pDrawable->width, pict->pDrawable->height,
 	(uint32_t *)bits, stride * sizeof (FbStride));
 
     if (!image)
@@ -189,55 +184,33 @@ create_bits_picture (PicturePtr pict,
 	if (pict->clientClipType != CT_NONE)
 	    pixman_image_set_has_client_clip (image, TRUE);
 
-	if (*xoff || *yoff)
-	    pixman_region_translate (pict->pCompositeClip, *xoff, *yoff);
+	pixman_region_translate (pict->pCompositeClip, - pict->pDrawable->x, - pict->pDrawable->y);
 
 	pixman_image_set_clip_region (image, pict->pCompositeClip);
 
-	if (*xoff || *yoff)
-	    pixman_region_translate (pict->pCompositeClip, -*xoff, -*yoff);
+	pixman_region_translate (pict->pCompositeClip, pict->pDrawable->x, pict->pDrawable->y);
     }
     
     /* Indexed table */
     if (pict->pFormat->index.devPrivate)
 	pixman_image_set_indexed (image, pict->pFormat->index.devPrivate);
 
-    /* Add in drawable origin to position within the image */
-    *xoff += pict->pDrawable->x;
-    *yoff += pict->pDrawable->y;
-
     return image;
 }
 
 static pixman_image_t *
-image_from_pict_internal (PicturePtr pict, Bool has_clip, int *xoff, int *yoff, Bool is_alpha_map);
+image_from_pict_internal (PicturePtr pict, Bool has_clip, Bool is_alpha_map);
 
 static void
-set_image_properties (pixman_image_t *image, PicturePtr pict, Bool has_clip, int *xoff, int *yoff, Bool is_alpha_map)
+set_image_properties (pixman_image_t *image, PicturePtr pict, Bool is_alpha_map)
 {
     pixman_repeat_t repeat;
     pixman_filter_t filter;
     
     if (pict->transform)
     {
-	/* For source images, adjust the transform to account
-	 * for the drawable offset within the pixman image,
-	 * then set the offset to 0 as it will be used
-	 * to compute positions within the transformed image.
-	 */
-	if (!has_clip) {
-	    struct pixman_transform	adjusted;
-
-	    adjusted = *pict->transform;
-	    pixman_transform_translate(&adjusted,
-				       NULL,
-				       pixman_int_to_fixed(*xoff),
-				       pixman_int_to_fixed(*yoff));
-	    pixman_image_set_transform (image, &adjusted);
-	    *xoff = 0;
-	    *yoff = 0;
-	} else
-	    pixman_image_set_transform (image, pict->transform);
+	pixman_image_set_transform (
+	    image, (pixman_transform_t *)pict->transform);
     }
     
     switch (pict->repeatType)
@@ -267,8 +240,7 @@ set_image_properties (pixman_image_t *image, PicturePtr pict, Bool has_clip, int
      */
     if (pict->alphaMap && !is_alpha_map)
     {
-	int alpha_xoff, alpha_yoff;
-	pixman_image_t *alpha_map = image_from_pict_internal (pict->alphaMap, FALSE, &alpha_xoff, &alpha_yoff, TRUE);
+	pixman_image_t *alpha_map = image_from_pict_internal (pict->alphaMap, TRUE, TRUE);
 	
 	pixman_image_set_alpha_map (
 	    image, alpha_map, pict->alphaOrigin.x, pict->alphaOrigin.y);
@@ -301,7 +273,8 @@ set_image_properties (pixman_image_t *image, PicturePtr pict, Bool has_clip, int
 }
 
 static pixman_image_t *
-image_from_pict_internal (PicturePtr pict, Bool has_clip, int *xoff, int *yoff, Bool is_alpha_map)
+image_from_pict_internal (PicturePtr pict,
+		 Bool has_clip, Bool is_alpha_map)
 {
     pixman_image_t *image = NULL;
 
@@ -310,7 +283,7 @@ image_from_pict_internal (PicturePtr pict, Bool has_clip, int *xoff, int *yoff,
 
     if (pict->pDrawable)
     {
-	image = create_bits_picture (pict, has_clip, xoff, yoff);
+	image = create_bits_picture (pict, has_clip);
     }
     else if (pict->pSourcePict)
     {
@@ -331,19 +304,18 @@ image_from_pict_internal (PicturePtr pict, Bool has_clip, int *xoff, int *yoff,
 	    else if (sp->type == SourcePictTypeConical)
 		image = create_conical_gradient_image (gradient);
 	}
-	*xoff = *yoff = 0;
     }
     
     if (image)
-	set_image_properties (image, pict, has_clip, xoff, yoff, is_alpha_map);
+	set_image_properties (image, pict, is_alpha_map);
     
     return image;
 }
 
 pixman_image_t *
-image_from_pict (PicturePtr pict, Bool has_clip, int *xoff, int *yoff)
+image_from_pict (PicturePtr pict, Bool has_clip)
 {
-    return image_from_pict_internal (pict, has_clip, xoff, yoff, FALSE);
+    return image_from_pict_internal (pict, has_clip, FALSE);
 }
 
 void
diff --git a/fb/fbtrap.c b/fb/fbtrap.c
index 0b5a638..fbe2647 100644
--- a/fb/fbtrap.c
+++ b/fb/fbtrap.c
@@ -39,12 +39,11 @@ fbAddTraps (PicturePtr	pPicture,
 	    xTrap	*traps)
 {
     pixman_image_t *image;
-    int dst_xoff, dst_yoff;
 
-    if (!(image = image_from_pict (pPicture, FALSE, &dst_xoff, &dst_yoff)))
+    if (!(image = image_from_pict (pPicture, FALSE)))
 	return;
     
-    pixman_add_traps (image, x_off + dst_xoff, y_off + dst_yoff,
+    pixman_add_traps (image, x_off, y_off,
 		      ntrap, (pixman_trap_t *)traps);
 
     free_pixman_pict (pPicture, image);
@@ -57,14 +56,13 @@ fbRasterizeTrapezoid (PicturePtr    pPicture,
 		      int	    y_off)
 {
     pixman_image_t *image;
-    int	dst_xoff, dst_yoff;
 
-    if (!(image = image_from_pict (pPicture, FALSE, &dst_xoff, &dst_yoff)))
+    if (!(image = image_from_pict (pPicture, FALSE)))
 	return;
 
     pixman_rasterize_trapezoid (image, (pixman_trapezoid_t *)trap,
-				x_off + dst_xoff,
-				y_off + dst_yoff);
+				x_off,
+				y_off);
 
     free_pixman_pict (pPicture, image);
 }
@@ -77,13 +75,12 @@ fbAddTriangles (PicturePtr  pPicture,
 		xTriangle *tris)
 {
     pixman_image_t *image;
-    int dst_xoff, dst_yoff;
 
-    if (!(image = image_from_pict (pPicture, FALSE, &dst_xoff, &dst_yoff)))
+    if (!(image = image_from_pict (pPicture, FALSE)))
 	return;
     
     pixman_add_triangles (image,
-			  dst_xoff + x_off, dst_yoff + y_off,
+			  x_off, y_off,
 			  ntri, (pixman_triangle_t *)tris);
 
     free_pixman_pict (pPicture, image);
@@ -110,13 +107,11 @@ fbShapes (CompositeShapesFunc	composite,
 	  const uint8_t *	shapes)
 {
     pixman_image_t *src, *dst;
-    int src_xoff, src_yoff;
-    int dst_xoff, dst_yoff;
 
     miCompositeSourceValidate (pSrc);
 
-    src = image_from_pict (pSrc, FALSE, &src_xoff, &src_yoff);
-    dst = image_from_pict (pDst, TRUE, &dst_xoff, &dst_yoff);
+    src = image_from_pict (pSrc, FALSE);
+    dst = image_from_pict (pDst, TRUE);
 
     if (src && dst)
     {
@@ -136,10 +131,10 @@ fbShapes (CompositeShapesFunc	composite,
 	    for (i = 0; i < nshapes; ++i)
 	    {
 		composite (op, src, dst, format,
-			   xSrc + src_xoff,
-			   ySrc + src_yoff,
-			   dst_xoff,
-			   dst_yoff,
+			   xSrc,
+			   ySrc,
+			   0,
+			   0,
 			   1, shapes + i * shape_size);
 	    }
 	}
@@ -162,10 +157,10 @@ fbShapes (CompositeShapesFunc	composite,
 	    }
 	    
 	    composite (op, src, dst, format,
-		       xSrc + src_xoff,
-		       ySrc + src_yoff,
-		       dst_xoff,
-		       dst_yoff,
+		       xSrc,
+		       ySrc,
+		       0,
+		       0,
 		       nshapes, shapes);
 	}
 
commit 2529789faaa9c1fc60d614641b6e17c3e0538ae1
Author: Jeremy Huddleston <jeremyhu at apple.com>
Date:   Fri Apr 30 13:08:25 2010 -0700

    Workaround the GC clipping problem in miPaintWindow and add some debugging output.
    
    Signed-off-by: Jeremy Huddleston <jeremyhu at apple.com>

diff --git a/mi/miexpose.c b/mi/miexpose.c
index 0f1ebe5..dcbfe1c 100644
--- a/mi/miexpose.c
+++ b/mi/miexpose.c
@@ -521,6 +521,7 @@ void RootlessSetPixmapOfAncestors(WindowPtr pWin);
 void RootlessStartDrawing(WindowPtr pWin);
 void RootlessDamageRegion(WindowPtr pWin, RegionPtr prgn);
 Bool IsFramedWindow(WindowPtr pWin);
+#include "../fb/fb.h"
 #endif 
 
 void
@@ -548,24 +549,37 @@ miPaintWindow(WindowPtr pWin, RegionPtr prgn, int what)
     Bool	solid = TRUE;
     DrawablePtr	drawable = &pWin->drawable;
 
+#ifdef XQUARTZ_CLIP_DEBUG
+    ErrorF("START %d BS %d (pR = %ld)\n", what, pWin->backgroundState, ParentRelative);
+    ErrorF("      Rgn: %d %d %d %d\n", prgn->extents.x1, prgn->extents.y1,
+	                               prgn->extents.x2 - prgn->extents.x1,
+	                               prgn->extents.y2 - prgn->extents.y1);
+    ErrorF("      Win: %d %d (%d %d) %d %d\n", pWin->origin.x, pWin->origin.y,
+	                                       pWin->winSize.extents.x1, pWin->winSize.extents.y1,
+	                                       pWin->winSize.extents.x2 - pWin->winSize.extents.x1,
+					       pWin->winSize.extents.y2 - pWin->winSize.extents.y1);
+    ErrorF("     Draw: %d %d %d %d\n", pWin->drawable.x, pWin->drawable.y,
+				       pWin->drawable.width, pWin->drawable.height);
+#endif
+
 #ifdef ROOTLESS
     if(!drawable || drawable->type == UNDRAWABLE_WINDOW)
 	return;
-
-    if(IsFramedWindow(pWin)) {
-        RootlessStartDrawing(pWin);
-        RootlessDamageRegion(pWin, prgn);
-    
-        if(pWin->backgroundState == ParentRelative) {
-            if((what == PW_BACKGROUND) || 
-               (what == PW_BORDER && !pWin->borderIsPixel))
-                RootlessSetPixmapOfAncestors(pWin);
-        }
-    }
 #endif
     
     if (what == PW_BACKGROUND)
     {
+#ifdef ROOTLESS
+	if(IsFramedWindow(pWin)) {
+	    RootlessStartDrawing(pWin);
+	    RootlessDamageRegion(pWin, prgn);
+
+	    if(pWin->backgroundState == ParentRelative) {
+		RootlessSetPixmapOfAncestors(pWin);
+	    }
+	}
+#endif
+
 	while (pWin->backgroundState == ParentRelative)
 	    pWin = pWin->parent;
 
@@ -591,6 +605,18 @@ miPaintWindow(WindowPtr pWin, RegionPtr prgn, int what)
     {
 	PixmapPtr   pixmap;
 
+#ifdef ROOTLESS
+	if(IsFramedWindow(pWin)) {
+	    RootlessStartDrawing(pWin);
+	    RootlessDamageRegion(pWin, prgn);
+	    
+	    if(!pWin->borderIsPixel &&
+		pWin->backgroundState == ParentRelative) {
+		RootlessSetPixmapOfAncestors(pWin);
+	    }
+	}
+#endif
+
 	tile_x_off = drawable->x;
 	tile_y_off = drawable->y;
 	
@@ -599,6 +625,12 @@ miPaintWindow(WindowPtr pWin, RegionPtr prgn, int what)
 	    return;
 	pixmap = (*pScreen->GetWindowPixmap) ((WindowPtr) drawable);
 	drawable = &pixmap->drawable;
+
+#ifdef XQUARTZ_CLIP_DEBUG
+	ErrorF("     Draw: %d %d %d %d\n",
+	       drawable->x, drawable->y, drawable->width, drawable->height);    
+#endif
+	
 #ifdef COMPOSITE
 	draw_x_off = pixmap->screen_x;
 	draw_y_off = pixmap->screen_y;
@@ -661,6 +693,57 @@ miPaintWindow(WindowPtr pWin, RegionPtr prgn, int what)
     ChangeGC (NullClient, pGC, gcmask, gcval);
     ValidateGC (drawable, pGC);
 
+#ifdef XQUARTZ_CLIP_DEBUG
+    ErrorF("       GC: %d %d %d %d\n",
+	   pGC->pCompositeClip->extents.x1, pGC->pCompositeClip->extents.y1,
+	   pGC->pCompositeClip->extents.x2 - pGC->pCompositeClip->extents.x1,
+	   pGC->pCompositeClip->extents.y2 - pGC->pCompositeClip->extents.y1);
+#endif
+    
+#ifdef XQUARTZ
+    /* Looks like our clipping isn't set right for some reason:
+     * http://xquartz.macosforge.org/trac/ticket/290
+     */
+    if(what == PW_BORDER) {
+
+#if 0
+	if(solid) {
+#if 1
+	    fbFillRegionSolid(&pWin->drawable,
+			      prgn,
+			      0,
+			      fbReplicatePixel(fill.pixel,
+					       pWin->drawable.bitsPerPixel));
+#else
+	    fbFillRegionSolid(drawable,
+			      prgn,
+			      0,
+			      fbReplicatePixel(fill.pixel,
+					       drawable->bitsPerPixel));
+#endif
+	    return;
+	}
+#endif
+    
+	pGC->pCompositeClip->extents.x1 += prgn->extents.x1;
+	pGC->pCompositeClip->extents.y1 += prgn->extents.y1;
+	pGC->pCompositeClip->extents.x2 += prgn->extents.x1;
+	pGC->pCompositeClip->extents.y2 += prgn->extents.y1;
+	
+	if(pGC->pCompositeClip->extents.x2 > drawable->pScreen->width)
+	    pGC->pCompositeClip->extents.x2 = drawable->pScreen->width;
+	if(pGC->pCompositeClip->extents.y2 > drawable->pScreen->height)
+	    pGC->pCompositeClip->extents.y2 = drawable->pScreen->height;
+    }
+#endif
+
+#ifdef XQUARTZ_CLIP_DEBUG
+    ErrorF("       GC: %d %d %d %d\n",
+	   pGC->pCompositeClip->extents.x1, pGC->pCompositeClip->extents.y1,
+	   pGC->pCompositeClip->extents.x2 - pGC->pCompositeClip->extents.x1,
+	   pGC->pCompositeClip->extents.y2 - pGC->pCompositeClip->extents.y1);    
+#endif
+
     numRects = RegionNumRects(prgn);
     pbox = RegionRects(prgn);
     for (i= numRects; --i >= 0; pbox++, prect++)
commit 1deede3c48d5ac91f50774c79f02afc6e036614e
Author: Jeremy Huddleston <jeremyhu at apple.com>
Date:   Sat Dec 17 12:56:59 2011 -0800

    kdrive/linux: Fix compilation with -Werror=int-to-pointer-cast -Werror=pointer-to-int-cast
    
    Reported-by: Arkadiusz Miśkiewicz <arekm at maven.pl>
    Signed-off-by: Jeremy Huddleston <jeremyhu at apple.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>

diff --git a/hw/kdrive/linux/keyboard.c b/hw/kdrive/linux/keyboard.c
index f5f9d9b..ba2637b 100644
--- a/hw/kdrive/linux/keyboard.c
+++ b/hw/kdrive/linux/keyboard.c
@@ -692,7 +692,7 @@ LinuxKeyboardEnable (KdKeyboardInfo *ki)
         return !Success;
 
     fd = LinuxConsoleFd;
-    ki->driverPrivate = (void *) fd;
+    ki->driverPrivate = (void *) (intptr_t) fd;
 
     ioctl (fd, KDGKBMODE, &LinuxKbdTrans);
     tcgetattr (fd, &LinuxTermios);
@@ -724,7 +724,7 @@ LinuxKeyboardDisable (KdKeyboardInfo *ki)
     if (!ki)
         return;
 
-    fd = (int) ki->driverPrivate;
+    fd = (int) (intptr_t) ki->driverPrivate;
 
     KdUnregisterFd(ki, fd, FALSE);
     ioctl(fd, KDSKBMODE, LinuxKbdTrans);
@@ -753,7 +753,7 @@ LinuxKeyboardLeds (KdKeyboardInfo *ki, int leds)
     if (!ki)
         return;
 
-    ioctl ((int)ki->driverPrivate, KDSETLED, leds & 7);
+    ioctl ((int)(intptr_t)ki->driverPrivate, KDSETLED, leds & 7);
 }
 
 KdKeyboardDriver LinuxKeyboardDriver = {
diff --git a/hw/kdrive/linux/ms.c b/hw/kdrive/linux/ms.c
index b6151cd..176e125 100644
--- a/hw/kdrive/linux/ms.c
+++ b/hw/kdrive/linux/ms.c
@@ -152,7 +152,7 @@ MsEnable (KdPointerInfo *pi)
     }
     if (KdRegisterFd (port, MsRead, pi))
 	return TRUE;
-    pi->driverPrivate = (void *)port;
+    pi->driverPrivate = (void *)(intptr_t)port;
 
     return Success;
 
@@ -164,7 +164,7 @@ MsEnable (KdPointerInfo *pi)
 static void
 MsDisable (KdPointerInfo *pi)
 {
-    KdUnregisterFd (pi, (int)pi->driverPrivate, TRUE);
+    KdUnregisterFd (pi, (int)(intptr_t)pi->driverPrivate, TRUE);
 }
 
 static void
diff --git a/hw/kdrive/linux/ps2.c b/hw/kdrive/linux/ps2.c
index 465b963..b62d769 100644
--- a/hw/kdrive/linux/ps2.c
+++ b/hw/kdrive/linux/ps2.c
@@ -159,7 +159,7 @@ Ps2Enable (KdPointerInfo *pi)
         return BadAlloc;
     }
 
-    pi->driverPrivate = (void *)fd;
+    pi->driverPrivate = (void *)(intptr_t)fd;
 
     return Success;
 }
@@ -168,7 +168,7 @@ Ps2Enable (KdPointerInfo *pi)
 static void
 Ps2Disable (KdPointerInfo *pi)
 {
-    KdUnregisterFd (pi, (int)pi->driverPrivate, TRUE);
+    KdUnregisterFd (pi, (int)(intptr_t)pi->driverPrivate, TRUE);
 }
 
 static void
commit d0170d54c71fc761b8f1ae7a0e555dc2ca23cf9c
Author: Jeremy Huddleston <jeremyhu at apple.com>
Date:   Sat Dec 17 12:25:26 2011 -0800

    configure.ac: Make Xephyr dependency error message more informative
    
    Signed-off-by: Jeremy Huddleston <jeremyhu at apple.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>

diff --git a/configure.ac b/configure.ac
index db8d33c..e94b408 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2020,12 +2020,10 @@ if test "$KDRIVE" = yes; then
         XEPHYR_REQUIRED_LIBS="$XEPHYR_REQUIRED_LIBS $LIBGL libdrm"
     fi
 
-    PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
     if test "x$XEPHYR" = xauto; then
-        XEPHYR=$xephyr
-    fi
-    if test "x$XEPHYR" = xyes && test "x$xephyr" = xno; then	
-        AC_MSG_ERROR([Xephyr dependencies missing])
+        PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [XEPHYR="yes"], [XEPHYR="no"])
+    elif test "x$XEPHYR" = xyes ; then
+        PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS)
     fi
 
     # Xephyr needs nanosleep() which is in librt on Solaris
commit 511beddffab3c4fd43c75556132159117b6ba884
Author: Jeremy Huddleston <jeremyhu at apple.com>
Date:   Fri Nov 25 09:45:25 2011 -0800

    XQuartz: Provide in-tree implementation of strndup(3) if needed
    
    This function was added to Mac OS X 10.7, so we need to provide it
    for earlier releases.
    
    Signed-off-by: Jeremy Huddleston <jeremyhu at apple.com>

diff --git a/hw/xquartz/mach-startup/Makefile.am b/hw/xquartz/mach-startup/Makefile.am
index 0b1f897..21ad5b5 100644
--- a/hw/xquartz/mach-startup/Makefile.am
+++ b/hw/xquartz/mach-startup/Makefile.am
@@ -12,6 +12,13 @@ x11app_PROGRAMS = X11.bin
 dist_X11_bin_SOURCES = \
 	bundle-main.c 
 
+# strndup(3) was added in Mac OS X 10.7, but we do this unconditionally to deal
+# with the case where we build on Lion but target Snow Leopard as the minimum
+# OS version.
+#if NEED_STRNDUP
+dist_X11_bin_SOURCES += $(top_srcdir)/os/strndup.c
+#endif
+
 nodist_X11_bin_SOURCES = \
 	mach_startupServer.c \
 	mach_startupUser.c
commit c065f7b16329e30cb976359e0a807c2adaf50123
Author: Keith Packard <keithp at keithp.com>
Date:   Sat Dec 17 17:22:45 2011 -0800

    Version 1.11.99.2 (1.12 snapshot 2)
    
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/configure.ac b/configure.ac
index 518eb06..db8d33c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -26,8 +26,8 @@ dnl
 dnl Process this file with autoconf to create configure.
 
 AC_PREREQ(2.60)
-AC_INIT([xorg-server], 1.11.99.1, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
-RELEASE_DATE="2011-11-20"
+AC_INIT([xorg-server], 1.11.99.2, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+RELEASE_DATE="2011-12-17"
 AC_CONFIG_SRCDIR([Makefile.am])
 AM_INIT_AUTOMAKE([foreign dist-bzip2])
 AM_MAINTAINER_MODE
commit ead968a4300c0adeff89b9886e888b6d284c75cc
Author: Antoine Martin <antoine at nagafix.co.uk>
Date:   Sat Dec 17 01:36:51 2011 +0700

    xserver: check for elevated privileges not uid=0
    
    This allows us to run the server as a normal user whilst still
    being able to use the -modulepath, -logfile and -config switches
    We define a xf86PrivsElevated which will do the checks and cache
    the result in case it is called more than once.
    Also renamed the paths #defines to match their new meaning.
    Original discussion which led to this patch can be found here:
    http://lists.freedesktop.org/archives/xorg-devel/2011-September/025853.html
    
    Signed-off-by: Antoine Martin <antoine at nagafix.co.uk>
    Tested-by: Michal Suchanek <hramrach at centrum.cz>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Adam Jackson <ajax at redhat.com>

diff --git a/configure.ac b/configure.ac
index 27bf6ab..518eb06 100644
--- a/configure.ac
+++ b/configure.ac
@@ -212,7 +212,7 @@ AC_CHECK_FUNC([dlopen], [],
 AC_SUBST(DLOPEN_LIBS)
 
 dnl Checks for library functions.
-AC_CHECK_FUNCS([backtrace ffs \
+AC_CHECK_FUNCS([backtrace ffs geteuid getuid issetugid getresuid \
 	getdtablesize getifaddrs getpeereid getpeerucred getzoneid \
 	mmap shmctl64 strncasecmp vasprintf vsnprintf walkcontext])
 AC_REPLACE_FUNCS([strcasecmp strcasestr strlcat strlcpy strndup])
diff --git a/hw/xfree86/common/xf86Config.c b/hw/xfree86/common/xf86Config.c
index 569695c..f51be7e 100644
--- a/hw/xfree86/common/xf86Config.c
+++ b/hw/xfree86/common/xf86Config.c
@@ -72,8 +72,8 @@
  * These paths define the way the config file search is done.  The escape
  * sequences are documented in parser/scan.c.
  */
-#ifndef ROOT_CONFIGPATH
-#define ROOT_CONFIGPATH	"%A," "%R," \
+#ifndef ALL_CONFIGPATH
+#define ALL_CONFIGPATH	"%A," "%R," \
 			"/etc/X11/%R," "%P/etc/X11/%R," \
 			"%E," "%F," \
 			"/etc/X11/%F," "%P/etc/X11/%F," \
@@ -83,8 +83,8 @@
 			"%P/lib/X11/%X.%H," \
 			"%P/lib/X11/%X"
 #endif
-#ifndef USER_CONFIGPATH
-#define USER_CONFIGPATH	"/etc/X11/%S," "%P/etc/X11/%S," \
+#ifndef RESTRICTED_CONFIGPATH
+#define RESTRICTED_CONFIGPATH	"/etc/X11/%S," "%P/etc/X11/%S," \
 			"/etc/X11/%G," "%P/etc/X11/%G," \
 			"/etc/X11/%X," "/etc/%X," \
 			"%P/etc/X11/%X.%H," \
@@ -92,14 +92,14 @@
 			"%P/lib/X11/%X.%H," \
 			"%P/lib/X11/%X"
 #endif
-#ifndef ROOT_CONFIGDIRPATH
-#define ROOT_CONFIGDIRPATH	"%A," "%R," \
+#ifndef ALL_CONFIGDIRPATH
+#define ALL_CONFIGDIRPATH	"%A," "%R," \
 				"/etc/X11/%R," "%C/X11/%R," \
 				"/etc/X11/%X," "%C/X11/%X"
 #endif
-#ifndef USER_CONFIGDIRPATH
-#define USER_CONFIGDIRPATH	"/etc/X11/%R," "%C/X11/%R," \
-				"/etc/X11/%X," "%C/X11/%X"
+#ifndef RESTRICTED_CONFIGDIRPATH
+#define RESTRICTED_CONFIGDIRPATH	"/etc/X11/%R," "%C/X11/%R," \
+					"/etc/X11/%X," "%C/X11/%X"
 #endif
 #ifndef SYS_CONFIGDIRPATH
 #define SYS_CONFIGDIRPATH	"/usr/share/X11/%X," "%D/X11/%X"
@@ -2310,12 +2310,12 @@ xf86HandleConfigFile(Bool autoconfig)
 	MessageType filefrom = X_DEFAULT;
 	MessageType dirfrom = X_DEFAULT;
 
-	if (getuid() == 0) {
-	    filesearch = ROOT_CONFIGPATH;
-	    dirsearch = ROOT_CONFIGDIRPATH;
+	if (!xf86PrivsElevated()) {
+	    filesearch = ALL_CONFIGPATH;
+	    dirsearch = ALL_CONFIGDIRPATH;
 	} else {
-	    filesearch = USER_CONFIGPATH;
-	    dirsearch = USER_CONFIGDIRPATH;
+	    filesearch = RESTRICTED_CONFIGPATH;
+	    dirsearch = RESTRICTED_CONFIGDIRPATH;
 	}
 
 	if (xf86ConfigFile)
diff --git a/hw/xfree86/common/xf86Init.c b/hw/xfree86/common/xf86Init.c
index c1e48ee..5263b5f 100644
--- a/hw/xfree86/common/xf86Init.c
+++ b/hw/xfree86/common/xf86Init.c
@@ -238,6 +238,65 @@ xf86PrintMarkers(void)
   LogPrintMarkers();
 }
 
+Bool xf86PrivsElevated(void)
+{
+  static Bool privsTested = FALSE;
+  static Bool privsElevated = TRUE;
+
+  if (!privsTested) {
+#if defined(WIN32)
+    privsElevated = FALSE;
+#else
+    if ((getuid() != geteuid()) || (getgid() != getegid())) {
+      privsElevated = TRUE;
+    } else {
+#if defined(HAVE_ISSETUGID)
+      privsElevated = issetugid();
+#elif defined(HAVE_GETRESUID)
+      uid_t ruid, euid, suid;
+      gid_t rgid, egid, sgid;
+
+      if ((getresuid(&ruid, &euid, &suid) == 0) &&
+          (getresgid(&rgid, &egid, &sgid) == 0)) {
+        privsElevated = (euid != suid) || (egid != sgid);
+      }
+      else {
+        printf("Failed getresuid or getresgid");
+        /* Something went wrong, make defensive assumption */
+        privsElevated = TRUE;
+      }
+#else
+      if (getuid()==0) {
+        /* running as root: uid==euid==0 */
+        privsElevated = FALSE;
+      }
+      else {
+        /*
+         * If there are saved ID's the process might still be privileged
+         * even though the above test succeeded. If issetugid() and
+         * getresgid() aren't available, test this by trying to set
+         * euid to 0.
+         */
+        unsigned int oldeuid;
+        oldeuid = geteuid();
+
+        if (seteuid(0) != 0) {
+          privsElevated = FALSE;
+        } else {
+          if (seteuid(oldeuid) != 0) {
+            FatalError("Failed to drop privileges.  Exiting\n");
+          }
+          privsElevated = TRUE;
+        }
+      }
+#endif
+    }
+#endif
+    privsTested = TRUE;
+  }
+  return privsElevated;
+}
+
 static Bool
 xf86CreateRootWindow(WindowPtr pWin)
 {
@@ -872,7 +931,7 @@ OsVendorInit(void)
 
 #ifdef O_NONBLOCK
   if (!beenHere) {
-    if (geteuid() == 0 && getuid() != geteuid())
+    if (xf86PrivsElevated())
     {
       int status;
 
@@ -1043,10 +1102,11 @@ ddxProcessArgument(int argc, char **argv, int i)
       FatalError("Required argument to %s not specified\n", argv[i]);	\
     }
 
-  /* First the options that are only allowed for root */
+  /* First the options that are not allowed with elevated privileges */
   if (!strcmp(argv[i], "-modulepath") || !strcmp(argv[i], "-logfile")) {
-    if ( (geteuid() == 0) && (getuid() != 0) ) {
-      FatalError("The '%s' option can only be used by root.\n", argv[i]);
+    if (xf86PrivsElevated()) {
+      FatalError("The '%s' option cannot be used with "
+                 "elevated privileges.\n", argv[i]);
     }
     else if (!strcmp(argv[i], "-modulepath"))
     {
@@ -1074,9 +1134,9 @@ ddxProcessArgument(int argc, char **argv, int i)
   if (!strcmp(argv[i], "-config") || !strcmp(argv[i], "-xf86config"))
   {
     CHECK_FOR_REQUIRED_ARGUMENT();
-    if (getuid() != 0 && !xf86PathIsSafe(argv[i + 1])) {
+    if (xf86PrivsElevated() && !xf86PathIsSafe(argv[i + 1])) {
       FatalError("\nInvalid argument for %s\n"
-	  "\tFor non-root users, the file specified with %s must be\n"
+	  "\tWith elevated privileges, the file specified with %s must be\n"
 	  "\ta relative path and must not contain any \"..\" elements.\n"
 	  "\tUsing default "__XCONFIGFILE__" search path.\n\n",
 	  argv[i], argv[i]);
@@ -1087,9 +1147,9 @@ ddxProcessArgument(int argc, char **argv, int i)
   if (!strcmp(argv[i], "-configdir"))
   {
     CHECK_FOR_REQUIRED_ARGUMENT();
-    if (getuid() != 0 && !xf86PathIsSafe(argv[i + 1])) {
+    if (xf86PrivsElevated() && !xf86PathIsSafe(argv[i + 1])) {
       FatalError("\nInvalid argument for %s\n"
-	  "\tFor non-root users, the file specified with %s must be\n"
+	  "\tWith elevated privileges, the file specified with %s must be\n"
 	  "\ta relative path and must not contain any \"..\" elements.\n"
 	  "\tUsing default "__XCONFIGDIR__" search path.\n\n",
 	  argv[i], argv[i]);
@@ -1375,7 +1435,7 @@ ddxUseMsg(void)
   ErrorF("\n");
   ErrorF("\n");
   ErrorF("Device Dependent Usage\n");
-  if (getuid() == 0 || geteuid() != 0)
+  if (!xf86PrivsElevated())
   {
     ErrorF("-modulepath paths      specify the module search path\n");
     ErrorF("-logfile file          specify a log file name\n");
diff --git a/hw/xfree86/common/xf86Priv.h b/hw/xfree86/common/xf86Priv.h
index e0b1809..255407b 100644
--- a/hw/xfree86/common/xf86Priv.h
+++ b/hw/xfree86/common/xf86Priv.h
@@ -145,6 +145,7 @@ extern _X_EXPORT Bool xf86LoadModules(char **list, pointer *optlist);
 extern _X_EXPORT int xf86SetVerbosity(int verb);
 extern _X_EXPORT int xf86SetLogVerbosity(int verb);
 extern _X_EXPORT Bool xf86CallDriverProbe( struct _DriverRec * drv, Bool detect_only );
+extern _X_EXPORT Bool xf86PrivsElevated(void);
 
 #endif /* _NO_XF86_PROTOTYPES */
 
diff --git a/include/xorg-config.h.in b/include/xorg-config.h.in
index 6b9230f..2cc416a 100644
--- a/include/xorg-config.h.in
+++ b/include/xorg-config.h.in
@@ -130,4 +130,10 @@
 /* Use libpciaccess */
 #undef XSERVER_LIBPCIACCESS
 
+/* Have setugid */
+#undef HAVE_ISSETUGID
+
+/* Have getresuid */
+#undef HAVE_GETRESUID
+
 #endif /* _XORG_CONFIG_H_ */
commit 2c1d0a539c0fb1860ac89a00d1fb609f1959e1b6
Author: Gaetan Nadon <memsize at videotron.ca>
Date:   Fri Dec 9 07:45:02 2011 -0500

    dmx: fix distcheck failure, missing compsize.h in Makefile.am
    
    which was added in commit:
    dmx: Build fix for -Werror=implicit-function-declaration
    
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Gaetan Nadon <memsize at videotron.ca>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/dmx/glxProxy/Makefile.am b/hw/dmx/glxProxy/Makefile.am
index 8516048..4ee1036 100644
--- a/hw/dmx/glxProxy/Makefile.am
+++ b/hw/dmx/glxProxy/Makefile.am
@@ -1,10 +1,12 @@
 noinst_LIBRARIES = libglxproxy.a
 
 libglxproxy_a_SOURCES = compsize.c \
+                        compsize.h \
                         g_disptab.c \
                         g_disptab.h \
                         global.c \
                         glxcmds.c \
+                        glxcmds.h \
                         glxcmdsswap.c \
                         glxcontext.h \
                         glxdrawable.h \
commit f7ea7a324520844beaac8be7503ac50e20da5ab1
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Dec 14 10:34:19 2011 +1000

    configure: split the required modules up
    
    We do the same thing for libraries and optional modules already, and it's
    much easier to read when one of them changes
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Gaetan Nadon <memsize at videotron.ca>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/configure.ac b/configure.ac
index 27bf7db..27bf6ab 100644
--- a/configure.ac
+++ b/configure.ac
@@ -771,6 +771,20 @@ VIDMODEPROTO="xf86vidmodeproto >= 2.2.99.1"
 WINDOWSWMPROTO="windowswmproto"
 APPLEWMPROTO="applewmproto >= 1.4"
 
+dnl Required modules
+XPROTO="xproto >= 7.0.22"
+RANDRPROTO="randrproto >= 1.2.99.3"
+RENDERPROTO="renderproto >= 0.11"
+XEXTPROTO="xextproto >= 7.1.99"
+INPUTPROTO="inputproto >= 2.0.99.1"
+KBPROTO="kbproto >= 1.0.3"
+FONTSPROTO="fontsproto"
+FIXESPROTO="fixesproto >= 5.0"
+DAMAGEPROTO="damageproto >= 1.1"
+XCMISCPROTO="xcmiscproto >= 1.2.0"
+BIGREQSPROTO="bigreqsproto >= 1.1.0"
+XTRANS="xtrans >= 1.2.2"
+
 dnl List of libraries that require a specific version
 LIBAPPLEWM="applewm >= 1.4"
 LIBDMX="dmx >= 1.0.99.1"
@@ -793,11 +807,11 @@ PKG_CHECK_MODULES(PIXMAN, $LIBPIXMAN)
 REQUIRED_LIBS="$REQUIRED_LIBS $LIBPIXMAN $LIBXFONT xau"
 
 dnl Core modules for most extensions, et al.
-SDK_REQUIRED_MODULES="[xproto >= 7.0.22] [randrproto >= 1.2.99.3] [renderproto >= 0.11] [xextproto >= 7.1.99] [inputproto >= 2.0.99.1] [kbproto >= 1.0.3] fontsproto $LIBPIXMAN"
+SDK_REQUIRED_MODULES="$XPROTO $RANDRPROTO $RENDERPROTO $XEXTPROTO $INPUTPROTO $KBPROTO $FONTSPROTO $LIBPIXMAN"
 # Make SDK_REQUIRED_MODULES available for inclusion in xorg-server.pc
 AC_SUBST(SDK_REQUIRED_MODULES)
 
-REQUIRED_MODULES="[fixesproto >= 5.0] [damageproto >= 1.1] [xcmiscproto >= 1.2.0] [xtrans >= 1.2.2] [bigreqsproto >= 1.1.0] $SDK_REQUIRED_MODULES"
+REQUIRED_MODULES="$FIXESPROTO $DAMAGEPROTO $XCMISCPROTO $XTRANS $BIGREQSPROTO $SDK_REQUIRED_MODULES"
 
 if test "x$CONFIG_UDEV" = xyes &&
  { test "x$CONFIG_DBUS_API" = xyes || test "x$CONFIG_HAL" = xyes; }; then
commit 7da7aa96a0acb895e1fe57a9d3f2d093479cf2a2
Merge: b79de3f 7528a6b
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Dec 14 11:40:10 2011 -0800

    Merge remote-tracking branch 'whot/for-keith'

commit 7528a6b88eb32098af4369a8bd9d70a808fa6f1c
Merge: f0de5e3 898d976
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Dec 13 14:19:54 2011 +1000

    Merge branch 'for-whot' of git://people.freedesktop.org/~alanc/xserver into for-keith

diff --cc dix/grabs.c
index 6f8b39e,3286eb7..da014df
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@@ -60,8 -60,8 +60,9 @@@ SOFTWARE
  #include "dixgrabs.h"
  #include "xace.h"
  #include "exevents.h"
 +#include "exglobals.h"
  #include "inpututils.h"
+ #include "client.h"
  
  #define BITMASK(i) (((Mask)1) << ((i) & 31))
  #define MASKIDX(i) ((i) >> 5)
@@@ -78,11 -78,12 +79,12 @@@ PrintDeviceGrabInfo(DeviceIntPtr dev
      int i, j;
      GrabInfoPtr devGrab = &dev->deviceGrab;
      GrabPtr grab = devGrab->grab;
+     Bool clientIdPrinted = FALSE;
  
-     ErrorF("Active grab 0x%lx (%s) on device '%s' (%d):",
+     ErrorF("Active grab 0x%lx (%s) on device '%s' (%d):\n",
             (unsigned long) grab->resource,
 -           (grab->grabtype == GRABTYPE_XI2) ? "xi2" :
 -            ((grab->grabtype == GRABTYPE_CORE) ? "core" : "xi1"),
 +           (grab->grabtype == XI2) ? "xi2" :
 +            ((grab->grabtype == CORE) ? "core" : "xi1"),
             dev->name, dev->id);
  
      client = clients[CLIENT_ID(grab->resource)];
commit f0de5e3990b70df9899b7dd17d7ee6ff7c768183
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Sun Dec 11 07:31:43 2011 +1000

    dix: add a MAXEVENTS define for the number of core + extension events
    
    Not including GenericEvents
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Walter Harms <wharms at bfs.de>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 357b8d1..6538139 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -367,9 +367,9 @@ extern int DeviceMotionNotify;
  * time a button is pressed, the filter is modified to also contain the
  * matching ButtonXMotion mask.
  */
-Mask event_filters[MAXDEVICES][128];
+Mask event_filters[MAXDEVICES][MAXEVENTS];
 
-static const Mask default_filter[128] =
+static const Mask default_filter[MAXEVENTS] =
 {
 	NoSuchEvent,		       /* 0 */
 	NoSuchEvent,		       /* 1 */
@@ -673,7 +673,7 @@ SetMaskForEvent(int deviceid, Mask mask, int event)
 void
 SetCriticalEvent(int event)
 {
-    if (event >= 128)
+    if (event >= MAXEVENTS)
 	FatalError("SetCriticalEvent: bogus event number");
     criticalEvents[event >> 3] |= 1 << (event & 7);
 }
diff --git a/dix/extension.c b/dix/extension.c
index cc516b6..af9ba31 100644
--- a/dix/extension.c
+++ b/dix/extension.c
@@ -61,7 +61,6 @@ SOFTWARE.
 #include "registry.h"
 #include "xace.h"
 
-#define LAST_EVENT  128
 #define LAST_ERROR 255
 
 static ExtensionEntry **extensions = (ExtensionEntry **)NULL;
@@ -82,7 +81,7 @@ AddExtension(const char *name, int NumEvents, int NumErrors,
 
     if (!MainProc || !SwappedMainProc || !MinorOpcodeProc)
         return((ExtensionEntry *) NULL);
-    if ((lastEvent + NumEvents > LAST_EVENT) || 
+    if ((lastEvent + NumEvents > MAXEVENTS) || 
 	        (unsigned)(lastError + NumErrors > LAST_ERROR)) {
         LogMessage(X_ERROR, "Not enabling extension %s: maximum number of "
                    "events or errors exceeded.\n", name);
diff --git a/dix/tables.c b/dix/tables.c
index 5bd9ea0..45ae2a9 100644
--- a/dix/tables.c
+++ b/dix/tables.c
@@ -592,7 +592,7 @@ int (* SwappedProcVector[256]) (
     ProcBadRequest
 };
 
-EventSwapPtr EventSwapVector[128] =
+EventSwapPtr EventSwapVector[MAXEVENTS] =
 {
     (EventSwapPtr)SErrorEvent,
     NotImplemented,
diff --git a/include/inpututils.h b/include/inpututils.h
index 5aa60c2..9e22c5a 100644
--- a/include/inpututils.h
+++ b/include/inpututils.h
@@ -32,7 +32,7 @@
 #include "input.h"
 #include <X11/extensions/XI2proto.h>
 
-extern Mask filters[MAXDEVICES][128];
+extern Mask event_filters[MAXDEVICES][MAXEVENTS];
 
 struct _ValuatorMask {
     int8_t      last_bit; /* highest bit set in mask */
diff --git a/include/misc.h b/include/misc.h
index d9811ca..09f928a 100644
--- a/include/misc.h
+++ b/include/misc.h
@@ -89,6 +89,8 @@ OF THIS SOFTWARE.
 #define MAXFORMATS	8
 #define MAXDEVICES	40 /* input devices */
 
+/* 128 event opcodes for core + extension events, excluding GE */
+#define MAXEVENTS       128
 #define EXTENSION_EVENT_BASE 64
 #define EXTENSION_BASE 128
 
commit adf8a0d62c0643f4c44a3b6d2e3c6c9b02532915
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Dec 9 18:38:53 2011 +1000

    dix: move event filter retrieval helpers to inpututils.c
    
    No functional changes
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index e98f7b2..357b8d1 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -367,7 +367,7 @@ extern int DeviceMotionNotify;
  * time a button is pressed, the filter is modified to also contain the
  * matching ButtonXMotion mask.
  */
-static Mask filters[MAXDEVICES][128];
+Mask event_filters[MAXDEVICES][128];
 
 static const Mask default_filter[128] =
 {
@@ -408,18 +408,6 @@ static const Mask default_filter[128] =
 	CantBeFiltered		       /* MappingNotify */
 };
 
-static inline Mask
-GetEventFilterMask(DeviceIntPtr dev, int evtype)
-{
-    return filters[dev ? dev->id : 0][evtype];
-}
-
-inline Mask
-GetXI2EventFilterMask(int evtype)
-{
-    return (1 << (evtype % 8));
-}
-
 /**
  * For the given event, return the matching event filter. This filter may then
  * be AND'ed with the selected event mask.
@@ -441,9 +429,9 @@ GetEventFilter(DeviceIntPtr dev, xEvent *event)
     int evtype = 0;
 
     if (event->u.u.type != GenericEvent)
-        return GetEventFilterMask(dev, event->u.u.type);
+        return event_get_filter_from_type(dev, event->u.u.type);
     else if ((evtype = xi2_get_type(event)))
-        return GetXI2EventFilterMask(evtype);
+        return event_get_filter_from_xi2type(evtype);
     ErrorF("[dix] Unknown event type %d. No filter\n", event->u.u.type);
     return 0;
 }
@@ -459,7 +447,7 @@ GetXI2MaskByte(XI2Mask *mask, DeviceIntPtr dev, int event_type)
      * for this mask anyway.
      */
     if (xi2mask_isset(mask, dev, event_type))
-        return GetXI2EventFilterMask(event_type);
+        return event_get_filter_from_xi2type(event_type);
     else
         return 0;
 }
@@ -679,7 +667,7 @@ SetMaskForEvent(int deviceid, Mask mask, int event)
 {
     if (deviceid < 0 || deviceid >= MAXDEVICES)
         FatalError("SetMaskForEvent: bogus device id");
-    filters[deviceid][event] = mask;
+    event_filters[deviceid][event] = mask;
 }
 
 void
@@ -2554,7 +2542,7 @@ EventIsDeliverable(DeviceIntPtr dev, int evtype, WindowPtr win)
 
     if ((type = GetXIType(evtype)) != 0)
     {
-        filter = GetEventFilterMask(dev, type);
+        filter = event_get_filter_from_type(dev, type);
 
         /* Check for XI mask */
         if (inputMasks &&
@@ -2570,7 +2558,7 @@ EventIsDeliverable(DeviceIntPtr dev, int evtype, WindowPtr win)
 
     if ((type = GetCoreType(evtype)) != 0)
     {
-        filter = GetEventFilterMask(dev, type);
+        filter = event_get_filter_from_type(dev, type);
 
         /* Check for core mask */
         if ((win->deliverableEvents & filter) &&
@@ -5350,7 +5338,7 @@ InitEvents(void)
     inputInfo.pointer = (DeviceIntPtr)NULL;
     for (i = 0; i < MAXDEVICES; i++)
     {
-        memcpy(&filters[i], default_filter, sizeof(default_filter));
+        memcpy(&event_filters[i], default_filter, sizeof(default_filter));
     }
 
     syncEvents.replayDev = (DeviceIntPtr)NULL;
diff --git a/dix/inpututils.c b/dix/inpututils.c
index 5844daf..9232bdc 100644
--- a/dix/inpututils.c
+++ b/dix/inpututils.c
@@ -695,6 +695,25 @@ void event_set_state(DeviceIntPtr mouse, DeviceIntPtr kbd, DeviceEvent *event)
     }
 }
 
+/**
+ * Return the event filter mask for the given device and the given core or
+ * XI1 protocol type.
+ */
+Mask
+event_get_filter_from_type(DeviceIntPtr dev, int evtype)
+{
+    return event_filters[dev ? dev->id : 0][evtype];
+}
+
+/**
+ * Return the event filter mask for the given device and the given core or
+ * XI2 protocol type.
+ */
+Mask
+event_get_filter_from_xi2type(int evtype)
+{
+    return (1 << (evtype % 8));
+}
 
 Bool
 point_on_screen(ScreenPtr pScreen, int x, int y)
diff --git a/include/input.h b/include/input.h
index fb24fd5..bd12f68 100644
--- a/include/input.h
+++ b/include/input.h
@@ -544,7 +544,6 @@ extern _X_EXPORT void FreeInputAttributes(InputAttributes *attrs);
 extern Mask GetEventMask(DeviceIntPtr dev, xEvent* ev, InputClientsPtr clients);
 extern Mask GetEventFilter(DeviceIntPtr dev, xEvent *event);
 extern Bool WindowXI2MaskIsset(DeviceIntPtr dev, WindowPtr win, xEvent* ev);
-extern Mask GetXI2EventFilterMask(int evtype);
 extern int GetXI2MaskByte(XI2Mask *mask, DeviceIntPtr dev, int event_type);
 void FixUpEventFromWindow(SpritePtr pSprite,
                           xEvent *xE,
diff --git a/include/inpututils.h b/include/inpututils.h
index 96ad6df..5aa60c2 100644
--- a/include/inpututils.h
+++ b/include/inpututils.h
@@ -32,6 +32,8 @@
 #include "input.h"
 #include <X11/extensions/XI2proto.h>
 
+extern Mask filters[MAXDEVICES][128];
+
 struct _ValuatorMask {
     int8_t      last_bit; /* highest bit set in mask */
     uint8_t     mask[(MAX_VALUATORS + 7)/8];
@@ -42,6 +44,8 @@ extern void verify_internal_event(const InternalEvent *ev);
 extern void init_device_event(DeviceEvent *event, DeviceIntPtr dev, Time ms);
 extern int event_get_corestate(DeviceIntPtr mouse, DeviceIntPtr kbd);
 extern void event_set_state(DeviceIntPtr mouse, DeviceIntPtr kbd, DeviceEvent *event);
+extern Mask event_get_filter_from_type(DeviceIntPtr dev, int evtype);
+extern Mask event_get_filter_from_xi2type(int evtype);
 
 FP3232 double_to_fp3232(double in);
 FP1616 double_to_fp1616(double in);
commit a03fe819506fbcbfcb299d4919d16061603fd4ec
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Dec 9 18:02:49 2011 +1000

    dix: switch EventIsDeliverable to take the event type only
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 086f438..e98f7b2 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -2532,27 +2532,27 @@ FixUpEventFromWindow(
  * client.
  *
  * @param[in] dev The device this event is being sent for.
- * @param[in] event The event that is to be sent.
+ * @param[in] evtype The event type of the event that is to be sent.
  * @param[in] win The current event window.
  *
  * @return Bitmask of ::EVENT_XI2_MASK, ::EVENT_XI1_MASK, ::EVENT_CORE_MASK, and
  *         ::EVENT_DONT_PROPAGATE_MASK.
  */
 int
-EventIsDeliverable(DeviceIntPtr dev, InternalEvent* event, WindowPtr win)
+EventIsDeliverable(DeviceIntPtr dev, int evtype, WindowPtr win)
 {
     int rc = 0;
     int filter = 0;
     int type;
     OtherInputMasks *inputMasks = wOtherInputMasks(win);
 
-    if ((type = GetXI2Type(event->any.type)) != 0)
+    if ((type = GetXI2Type(evtype)) != 0)
     {
         if (inputMasks && xi2mask_isset(inputMasks->xi2mask, dev, type))
             rc |= EVENT_XI2_MASK;
     }
 
-    if ((type = GetXIType(event->any.type)) != 0)
+    if ((type = GetXIType(evtype)) != 0)
     {
         filter = GetEventFilterMask(dev, type);
 
@@ -2568,7 +2568,7 @@ EventIsDeliverable(DeviceIntPtr dev, InternalEvent* event, WindowPtr win)
 
     }
 
-    if ((type = GetCoreType(event->any.type)) != 0)
+    if ((type = GetCoreType(evtype)) != 0)
     {
         filter = GetEventFilterMask(dev, type);
 
@@ -2667,7 +2667,7 @@ DeliverDeviceEvents(WindowPtr pWin, InternalEvent *event, GrabPtr grab,
 
     while (pWin)
     {
-        if ((mask = EventIsDeliverable(dev, event, pWin)))
+        if ((mask = EventIsDeliverable(dev, event->any.type, pWin)))
         {
             /* XI2 events first */
             if (mask & EVENT_XI2_MASK)
diff --git a/include/input.h b/include/input.h
index 7c5ad3c..fb24fd5 100644
--- a/include/input.h
+++ b/include/input.h
@@ -552,8 +552,7 @@ void FixUpEventFromWindow(SpritePtr pSprite,
                           Window child,
                           Bool calcChild);
 extern WindowPtr XYToWindow(SpritePtr pSprite, int x, int y);
-extern int EventIsDeliverable(DeviceIntPtr dev, InternalEvent* event,
-                              WindowPtr win);
+extern int EventIsDeliverable(DeviceIntPtr dev, int evtype, WindowPtr win);
 extern Bool ActivatePassiveGrab(DeviceIntPtr dev, GrabPtr grab,
                                 InternalEvent *ev);
 /**
commit 10a8c428fac0d4ff8f8a3e3487c13dd349d27ed7
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Dec 9 15:49:04 2011 +1000

    dix: move storing last.valuators into a helper function
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/getevents.c b/dix/getevents.c
index 8798f64..57d8c17 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -1094,6 +1094,30 @@ transformAbsolute(DeviceIntPtr dev, ValuatorMask *mask)
         valuator_mask_set_double(mask, 1, y);
 }
 
+static void
+storeLastValuators(DeviceIntPtr dev, ValuatorMask *mask,
+                   int xaxis, int yaxis,
+                   double devx, double devy)
+{
+    int i;
+
+    /* store desktop-wide in last.valuators */
+    if (valuator_mask_isset(mask, xaxis))
+        dev->last.valuators[0] = devx;
+    if (valuator_mask_isset(mask, yaxis))
+        dev->last.valuators[1] = devy;
+
+    for (i = 0; i < valuator_mask_size(mask); i++)
+    {
+        if (i == xaxis || i == yaxis)
+            continue;
+
+        if (valuator_mask_isset(mask, i))
+            dev->last.valuators[i] = valuator_mask_get_double(mask, i);
+    }
+
+}
+
 /**
  * Generate internal events representing this pointer event and enqueue them
  * on the event queue.
@@ -1162,7 +1186,7 @@ fill_pointer_events(InternalEvent *events, DeviceIntPtr pDev, int type,
                     int buttons, CARD32 ms, int flags,
                     const ValuatorMask *mask_in)
 {
-    int num_events = 1, i;
+    int num_events = 1;
     DeviceEvent *event;
     RawDeviceEvent *raw;
     double screenx = 0.0, screeny = 0.0; /* desktop coordinate system */
@@ -1237,17 +1261,7 @@ fill_pointer_events(InternalEvent *events, DeviceIntPtr pDev, int type,
 
     clipValuators(pDev, &mask);
 
-    /* store desktop-wide in last.valuators */
-    if (valuator_mask_isset(&mask, 0))
-        pDev->last.valuators[0] = devx;
-    if (valuator_mask_isset(&mask, 1))
-        pDev->last.valuators[1] = devy;
-
-    for (i = 2; i < valuator_mask_size(&mask); i++)
-    {
-        if (valuator_mask_isset(&mask, i))
-            pDev->last.valuators[i] = valuator_mask_get_double(&mask, i);
-    }
+    storeLastValuators(pDev, &mask, 0, 1, devx, devy);
 
     /* Update the MD's co-ordinates, which are always in desktop space. */
     if (!IsMaster(pDev) || !IsFloating(pDev)) {
commit a15abf82ddb5a209dbc30c4d12e1dc23c4adf3e4
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Dec 8 15:38:44 2011 +1000

    dix: always allocate and set the grab's sync.event
    
    Allocate the memory at device creation time and always store the event, even
    if we're not frozen. This way we know which event triggered the grab.
    Since the event was never freed anyway except on device shutdown, this
    doesn't really change things much.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/devices.c b/dix/devices.c
index e448eab..9ca8fe0 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -275,6 +275,7 @@ AddInputDevice(ClientPtr client, DeviceProc deviceProc, Bool autoStart)
     dev->deviceGrab.ActivateGrab = ActivateKeyboardGrab;
     dev->deviceGrab.DeactivateGrab = DeactivateKeyboardGrab;
     dev->deviceGrab.activeGrab = AllocGrab();
+    dev->deviceGrab.sync.event = calloc(1, sizeof(DeviceEvent));
 
     XkbSetExtension(dev, ProcessKeyboardEvent);
 
diff --git a/dix/events.c b/dix/events.c
index db86f51..086f438 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -3717,12 +3717,8 @@ ActivatePassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event)
     }
 
     if (grabinfo->sync.state == FROZEN_NO_EVENT)
-    {
-        if (!grabinfo->sync.event)
-            grabinfo->sync.event = calloc(1, sizeof(DeviceEvent));
-        *grabinfo->sync.event = event->device_event;
         grabinfo->sync.state = FROZEN_WITH_EVENT;
-    }
+    *grabinfo->sync.event = event->device_event;
 
     free(xE);
     return TRUE;
@@ -4310,8 +4306,6 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
 	case FREEZE_NEXT_EVENT:
 	    grabinfo->sync.state = FROZEN_WITH_EVENT;
 	    FreezeThaw(thisDev, TRUE);
-	    if (!grabinfo->sync.event)
-		grabinfo->sync.event = calloc(1, sizeof(InternalEvent));
 	    *grabinfo->sync.event = event->device_event;
 	    break;
 	}
commit 218752bdc5d9323d1e6202e762573a925cf8a4eb
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Dec 8 14:27:01 2011 +1000

    input: replace GRABTYPE_* with the InputLevel enums
    
    They achieve the same thing, re-use the more generic InputLevel so we can
    convert to/fro easier.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 405a8b1..45a289a 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1389,9 +1389,9 @@ DeviceFocusEvent(DeviceIntPtr dev, int type, int mode, int detail,
 int
 CheckGrabValues(ClientPtr client, GrabParameters* param)
 {
-    if (param->grabtype != GRABTYPE_CORE &&
-        param->grabtype != GRABTYPE_XI &&
-        param->grabtype != GRABTYPE_XI2)
+    if (param->grabtype != CORE &&
+        param->grabtype != XI &&
+        param->grabtype != XI2)
     {
         ErrorF("[Xi] grabtype is invalid. This is a bug.\n");
         return BadImplementation;
@@ -1408,7 +1408,7 @@ CheckGrabValues(ClientPtr client, GrabParameters* param)
 	return BadValue;
     }
 
-    if (param->grabtype != GRABTYPE_XI2 && (param->modifiers != AnyModifier) &&
+    if (param->grabtype != XI2 && (param->modifiers != AnyModifier) &&
         (param->modifiers & ~AllModifiersMask)) {
 	client->errorValue = param->modifiers;
 	return BadValue;
@@ -1423,7 +1423,7 @@ CheckGrabValues(ClientPtr client, GrabParameters* param)
 
 int
 GrabButton(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
-           int button, GrabParameters *param, GrabType grabtype,
+           int button, GrabParameters *param, enum InputLevel grabtype,
 	   GrabMask *mask)
 {
     WindowPtr pWin, confineTo;
@@ -1463,9 +1463,9 @@ GrabButton(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
     if (rc != Success)
 	return rc;
 
-    if (grabtype == GRABTYPE_XI)
+    if (grabtype == XI)
         type = DeviceButtonPress;
-    else if (grabtype == GRABTYPE_XI2)
+    else if (grabtype == XI2)
         type = XI_ButtonPress;
 
     grab = CreateGrab(client->index, dev, modifier_device, pWin, grabtype,
@@ -1476,12 +1476,12 @@ GrabButton(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
 }
 
 /**
- * Grab the given key. If grabtype is GRABTYPE_XI, the key is a keycode. If
- * grabtype is GRABTYPE_XI2, the key is a keysym.
+ * Grab the given key. If grabtype is XI, the key is a keycode. If
+ * grabtype is XI2, the key is a keysym.
  */
 int
 GrabKey(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
-        int key, GrabParameters *param, GrabType grabtype, GrabMask *mask)
+        int key, GrabParameters *param, enum InputLevel grabtype, GrabMask *mask)
 {
     WindowPtr pWin;
     GrabPtr grab;
@@ -1494,7 +1494,7 @@ GrabKey(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
         return rc;
     if ((dev->id != XIAllDevices && dev->id != XIAllMasterDevices) && k == NULL)
 	return BadMatch;
-    if (grabtype == GRABTYPE_XI)
+    if (grabtype == XI)
     {
         if ((key > k->xkbInfo->desc->max_key_code ||
                     key < k->xkbInfo->desc->min_key_code)
@@ -1503,7 +1503,7 @@ GrabKey(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
             return BadValue;
         }
         type = DeviceKeyPress;
-    } else if (grabtype == GRABTYPE_XI2)
+    } else if (grabtype == XI2)
         type = XI_KeyPress;
 
     rc = dixLookupWindow(&pWin, param->grabWindow, client, DixSetAttrAccess);
@@ -1558,7 +1558,7 @@ GrabWindow(ClientPtr client, DeviceIntPtr dev, int type,
     if (rc != Success)
 	return rc;
 
-    grab = CreateGrab(client->index, dev, dev, pWin, GRABTYPE_XI2,
+    grab = CreateGrab(client->index, dev, dev, pWin, XI2,
                       mask, param, (type == XIGrabtypeEnter) ? XI_Enter : XI_FocusIn,
                       0, NULL, cursor);
 
diff --git a/Xi/grabdev.c b/Xi/grabdev.c
index 4572c33..8fd114e 100644
--- a/Xi/grabdev.c
+++ b/Xi/grabdev.c
@@ -130,7 +130,7 @@ ProcXGrabDevice(ClientPtr client)
     rc = GrabDevice(client, dev, stuff->other_devices_mode,
                     stuff->this_device_mode, stuff->grabWindow,
 		    stuff->ownerEvents, stuff->time,
-		    &mask, GRABTYPE_XI, None, None,
+		    &mask, XI, None, None,
 		    &rep.status);
 
     if (rc != Success)
diff --git a/Xi/grabdevb.c b/Xi/grabdevb.c
index 2897d41..dda0da8 100644
--- a/Xi/grabdevb.c
+++ b/Xi/grabdevb.c
@@ -137,7 +137,7 @@ ProcXGrabDeviceButton(ClientPtr client)
 	return ret;
 
     memset(&param, 0, sizeof(param));
-    param.grabtype = GRABTYPE_XI;
+    param.grabtype = XI;
     param.ownerEvents = stuff->ownerEvents;
     param.this_device_mode = stuff->this_device_mode;
     param.other_devices_mode = stuff->other_devices_mode;
@@ -146,7 +146,7 @@ ProcXGrabDeviceButton(ClientPtr client)
     mask.xi = tmp[stuff->grabbed_device].mask;
 
     ret = GrabButton(client, dev, mdev, stuff->button, &param,
-                     GRABTYPE_XI, &mask);
+                     XI, &mask);
 
     return ret;
 }
diff --git a/Xi/grabdevk.c b/Xi/grabdevk.c
index cedd90d..61ab43a 100644
--- a/Xi/grabdevk.c
+++ b/Xi/grabdevk.c
@@ -135,7 +135,7 @@ ProcXGrabDeviceKey(ClientPtr client)
 
 
     memset(&param, 0, sizeof(param));
-    param.grabtype = GRABTYPE_XI;
+    param.grabtype = XI;
     param.ownerEvents = stuff->ownerEvents;
     param.this_device_mode = stuff->this_device_mode;
     param.other_devices_mode = stuff->other_devices_mode;
@@ -143,7 +143,7 @@ ProcXGrabDeviceKey(ClientPtr client)
     param.modifiers = stuff->modifiers;
     mask.xi = tmp[stuff->grabbed_device].mask;
 
-    ret = GrabKey(client, dev, mdev, stuff->key, &param, GRABTYPE_XI, &mask);
+    ret = GrabKey(client, dev, mdev, stuff->key, &param, XI, &mask);
 
     return ret;
 }
diff --git a/Xi/ungrdev.c b/Xi/ungrdev.c
index bc66cfc..58c1f57 100644
--- a/Xi/ungrdev.c
+++ b/Xi/ungrdev.c
@@ -102,7 +102,7 @@ ProcXUngrabDevice(ClientPtr client)
     time = ClientTimeToServerTime(stuff->time);
     if ((CompareTimeStamps(time, currentTime) != LATER) &&
 	(CompareTimeStamps(time, dev->deviceGrab.grabTime) != EARLIER) &&
-	(grab) && SameClient(grab, client) && grab->grabtype == GRABTYPE_XI)
+	(grab) && SameClient(grab, client) && grab->grabtype == XI)
 	(*dev->deviceGrab.DeactivateGrab) (dev);
     return Success;
 }
diff --git a/Xi/ungrdevb.c b/Xi/ungrdevb.c
index 6280248..0ba395c 100644
--- a/Xi/ungrdevb.c
+++ b/Xi/ungrdevb.c
@@ -134,7 +134,7 @@ ProcXUngrabDeviceButton(ClientPtr client)
     temporaryGrab->device = dev;
     temporaryGrab->window = pWin;
     temporaryGrab->type = DeviceButtonPress;
-    temporaryGrab->grabtype = GRABTYPE_XI;
+    temporaryGrab->grabtype = XI;
     temporaryGrab->modifierDevice = mdev;
     temporaryGrab->modifiersDetail.exact = stuff->modifiers;
     temporaryGrab->modifiersDetail.pMask = NULL;
diff --git a/Xi/ungrdevk.c b/Xi/ungrdevk.c
index b0d83cb..8785989 100644
--- a/Xi/ungrdevk.c
+++ b/Xi/ungrdevk.c
@@ -141,7 +141,7 @@ ProcXUngrabDeviceKey(ClientPtr client)
     temporaryGrab->device = dev;
     temporaryGrab->window = pWin;
     temporaryGrab->type = DeviceKeyPress;
-    temporaryGrab->grabtype = GRABTYPE_XI;
+    temporaryGrab->grabtype = XI;
     temporaryGrab->modifierDevice = mdev;
     temporaryGrab->modifiersDetail.exact = stuff->modifiers;
     temporaryGrab->modifiersDetail.pMask = NULL;
diff --git a/Xi/xigrabdev.c b/Xi/xigrabdev.c
index 1cfbf24..2b30550 100644
--- a/Xi/xigrabdev.c
+++ b/Xi/xigrabdev.c
@@ -96,7 +96,7 @@ ProcXIGrabDevice(ClientPtr client)
                      stuff->owner_events,
                      stuff->time,
                      &mask,
-                     GRABTYPE_XI2,
+                     XI2,
                      stuff->cursor,
                      None /* confineTo */,
                      &status);
@@ -148,7 +148,7 @@ ProcXIUngrabDevice(ClientPtr client)
     time = ClientTimeToServerTime(stuff->time);
     if ((CompareTimeStamps(time, currentTime) != LATER) &&
 	(CompareTimeStamps(time, dev->deviceGrab.grabTime) != EARLIER) &&
-	(grab) && SameClient(grab, client) && grab->grabtype == GRABTYPE_XI2)
+	(grab) && SameClient(grab, client) && grab->grabtype == XI2)
 	(*dev->deviceGrab.DeactivateGrab) (dev);
 
     return Success;
diff --git a/Xi/xipassivegrab.c b/Xi/xipassivegrab.c
index 4860757..713a165 100644
--- a/Xi/xipassivegrab.c
+++ b/Xi/xipassivegrab.c
@@ -139,7 +139,7 @@ ProcXIPassiveGrabDevice(ClientPtr client)
     rep.num_modifiers = 0;
 
     memset(&param, 0, sizeof(param));
-    param.grabtype = GRABTYPE_XI2;
+    param.grabtype = XI2;
     param.ownerEvents = stuff->owner_events;
     param.this_device_mode = stuff->grab_mode;
     param.other_devices_mode = stuff->paired_device_mode;
@@ -183,11 +183,11 @@ ProcXIPassiveGrabDevice(ClientPtr client)
         {
             case XIGrabtypeButton:
                 status = GrabButton(client, dev, mod_dev, stuff->detail,
-                                    &param, GRABTYPE_XI2, &mask);
+                                    &param, XI2, &mask);
                 break;
             case XIGrabtypeKeycode:
                 status = GrabKey(client, dev, mod_dev, stuff->detail,
-                                 &param, GRABTYPE_XI2, &mask);
+                                 &param, XI2, &mask);
                 break;
             case XIGrabtypeEnter:
             case XIGrabtypeFocusIn:
@@ -313,7 +313,7 @@ ProcXIPassiveUngrabDevice(ClientPtr client)
         case XIGrabtypeEnter:   tempGrab->type = XI_Enter;       break;
         case XIGrabtypeFocusIn: tempGrab->type = XI_FocusIn;     break;
     }
-    tempGrab->grabtype = GRABTYPE_XI2;
+    tempGrab->grabtype = XI2;
     tempGrab->modifierDevice = mod_dev;
     tempGrab->modifiersDetail.pMask = NULL;
     tempGrab->detail.exact = stuff->detail;
diff --git a/dix/events.c b/dix/events.c
index 9703ca9..db86f51 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1484,7 +1484,7 @@ ActivatePointerGrab(DeviceIntPtr mouse, GrabPtr grab,
     Bool isPassive = autoGrab & ~ImplicitGrabMask;
 
     /* slave devices need to float for the duration of the grab. */
-    if (grab->grabtype == GRABTYPE_XI2 &&
+    if (grab->grabtype == XI2 &&
         !(autoGrab & ImplicitGrabMask) && !IsMaster(mouse))
         DetachFromMaster(mouse);
 
@@ -1543,7 +1543,7 @@ DeactivatePointerGrab(DeviceIntPtr mouse)
     if (grab->cursor)
 	FreeCursor(grab->cursor, (Cursor)0);
 
-    if (!wasImplicit && grab->grabtype == GRABTYPE_XI2)
+    if (!wasImplicit && grab->grabtype == XI2)
         ReattachToOldMaster(mouse);
 
     ComputeFreezes();
@@ -1561,7 +1561,7 @@ ActivateKeyboardGrab(DeviceIntPtr keybd, GrabPtr grab, TimeStamp time, Bool pass
     WindowPtr oldWin;
 
     /* slave devices need to float for the duration of the grab. */
-    if (grab->grabtype == GRABTYPE_XI2 &&
+    if (grab->grabtype == XI2 &&
         !(passive & ImplicitGrabMask) &&
         !IsMaster(keybd))
         DetachFromMaster(keybd);
@@ -1616,7 +1616,7 @@ DeactivateKeyboardGrab(DeviceIntPtr keybd)
     }
     DoFocusEvents(keybd, grab->window, focusWin, NotifyUngrab);
 
-    if (!wasImplicit && grab->grabtype == GRABTYPE_XI2)
+    if (!wasImplicit && grab->grabtype == XI2)
         ReattachToOldMaster(keybd);
 
     ComputeFreezes();
@@ -1974,14 +1974,14 @@ ActivateImplicitGrab(DeviceIntPtr dev, ClientPtr client, WindowPtr win,
     GrabPtr tempGrab;
     OtherInputMasks *inputMasks;
     CARD8 type = event->u.u.type;
-    GrabType grabtype;
+    enum InputLevel grabtype;
 
     if (type == ButtonPress)
-        grabtype = GRABTYPE_CORE;
+        grabtype = CORE;
     else if (type == DeviceButtonPress)
-        grabtype = GRABTYPE_XI;
+        grabtype = XI;
     else if ((type = xi2_get_type(event)) == XI_ButtonPress)
-        grabtype = GRABTYPE_XI2;
+        grabtype = XI2;
     else
         return FALSE;
 
@@ -3656,13 +3656,13 @@ ActivatePassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event)
 
     /* The only consumers of corestate are Xi 1.x and core events, which
      * are guaranteed to come from DeviceEvents. */
-    if (grab->grabtype == GRABTYPE_XI || grab->grabtype == GRABTYPE_CORE)
+    if (grab->grabtype == XI || grab->grabtype == CORE)
     {
         DeviceIntPtr gdev;
 
         event->device_event.corestate &= 0x1f00;
 
-        if (grab->grabtype == GRABTYPE_CORE)
+        if (grab->grabtype == CORE)
             gdev = GetMaster(device, KEYBOARD_OR_FLOAT);
         else
             gdev = grab->modifierDevice;
@@ -3672,7 +3672,7 @@ ActivatePassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event)
                 gdev->key->xkbInfo->state.grab_mods & (~0x1f00);
     }
 
-    if (grab->grabtype == GRABTYPE_CORE)
+    if (grab->grabtype == CORE)
     {
         rc = EventToCore(event, &xE, &count);
         if (rc != Success)
@@ -3681,7 +3681,7 @@ ActivatePassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event)
                          "(%d, %d).\n", device->name, event->any.type, rc);
             return FALSE;
         }
-    } else if (grab->grabtype == GRABTYPE_XI2)
+    } else if (grab->grabtype == XI2)
     {
         rc = EventToXI2(event, &xE);
         if (rc != Success)
@@ -3737,7 +3737,7 @@ CoreGrabInterferes(DeviceIntPtr device, GrabPtr grab)
     for (other = inputInfo.devices; other; other = other->next)
     {
         GrabPtr othergrab = other->deviceGrab.grab;
-        if (othergrab && othergrab->grabtype == GRABTYPE_CORE &&
+        if (othergrab && othergrab->grabtype == CORE &&
                 SameClient(grab, rClient(othergrab)) &&
                 ((IsPointerDevice(grab->device) &&
                   IsPointerDevice(othergrab->device)) ||
@@ -3781,18 +3781,18 @@ MatchForType(const GrabPtr grab, GrabPtr tmp, enum InputLevel level, int event_t
     switch(level)
     {
         case XI2:
-            grabtype = GRABTYPE_XI2;
+            grabtype = XI2;
             evtype = GetXI2Type(event_type);
             BUG_WARN(!evtype);
             match = XI2_MATCH;
             break;
         case XI:
-            grabtype = GRABTYPE_XI;
+            grabtype = XI;
             evtype = GetXIType(event_type);
             match = XI_MATCH;
             break;
         case CORE:
-            grabtype = GRABTYPE_CORE;
+            grabtype = CORE;
             evtype = GetCoreType(event_type);
             match = CORE_MATCH;
             ignore_device = TRUE;
@@ -3830,10 +3830,10 @@ CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
     enum MatchFlags match = 0;
 
     gdev = grab->modifierDevice;
-    if (grab->grabtype == GRABTYPE_CORE)
+    if (grab->grabtype == CORE)
     {
         gdev = GetMaster(device, KEYBOARD_OR_FLOAT);
-    } else if (grab->grabtype == GRABTYPE_XI2)
+    } else if (grab->grabtype == XI2)
     {
         /* if the device is an attached slave device, gdev must be the
          * attached master keyboard. Since the slave may have been
@@ -3868,7 +3868,7 @@ CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
      * device.
      */
 
-    if (grab->grabtype == GRABTYPE_CORE)
+    if (grab->grabtype == CORE)
     {
         /* A passive grab may have been created for a different device
            than it is assigned to at this point in time.
@@ -4272,7 +4272,7 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
 
         sendCore = (IsMaster(thisDev) && thisDev->coreEvents);
         /* try core event */
-        if (sendCore && grab->grabtype == GRABTYPE_CORE)
+        if (sendCore && grab->grabtype == CORE)
         {
             deliveries = DeliverOneGrabbedEvent(event, thisDev, CORE);
         }
@@ -4970,7 +4970,7 @@ ProcGrabPointer(ClientPtr client)
 
     rc = GrabDevice(client, device, stuff->pointerMode, stuff->keyboardMode,
                     stuff->grabWindow, stuff->ownerEvents, stuff->time,
-                    &mask, GRABTYPE_CORE, stuff->cursor,
+                    &mask, CORE, stuff->cursor,
                     stuff->confineTo, &rep.status);
     if (rc != Success)
         return rc;
@@ -5178,9 +5178,9 @@ GrabDevice(ClientPtr client, DeviceIntPtr dev,
 	tempGrab->ownerEvents = ownerEvents;
 	tempGrab->keyboardMode = keyboard_mode;
 	tempGrab->pointerMode = pointer_mode;
-	if (grabtype == GRABTYPE_CORE)
+	if (grabtype == CORE)
 	    tempGrab->eventMask = mask->core;
-	else if (grabtype == GRABTYPE_XI)
+	else if (grabtype == XI)
 	    tempGrab->eventMask = mask->xi;
 	else
             xi2mask_merge(tempGrab->xi2mask, mask->xi2mask);
@@ -5217,7 +5217,7 @@ ProcGrabKeyboard(ClientPtr client)
 
     result = GrabDevice(client, keyboard, stuff->pointerMode,
             stuff->keyboardMode, stuff->grabWindow, stuff->ownerEvents,
-            stuff->time, &mask, GRABTYPE_CORE, None, None,
+            stuff->time, &mask, CORE, None, None,
             &rep.status);
 
     if (result != Success)
@@ -5250,7 +5250,7 @@ ProcUngrabKeyboard(ClientPtr client)
     time = ClientTimeToServerTime(stuff->id);
     if ((CompareTimeStamps(time, currentTime) != LATER) &&
 	(CompareTimeStamps(time, device->deviceGrab.grabTime) != EARLIER) &&
-	(grab) && SameClient(grab, client) && grab->grabtype == GRABTYPE_CORE)
+	(grab) && SameClient(grab, client) && grab->grabtype == CORE)
 	(*device->deviceGrab.DeactivateGrab)(device);
     return Success;
 }
@@ -5542,7 +5542,7 @@ ProcUngrabKey(ClientPtr client)
     tempGrab->modifiersDetail.pMask = NULL;
     tempGrab->modifierDevice = keybd;
     tempGrab->type = KeyPress;
-    tempGrab->grabtype = GRABTYPE_CORE;
+    tempGrab->grabtype = CORE;
     tempGrab->detail.exact = stuff->key;
     tempGrab->detail.pMask = NULL;
     tempGrab->next = NULL;
@@ -5575,7 +5575,7 @@ ProcGrabKey(ClientPtr client)
     REQUEST_SIZE_MATCH(xGrabKeyReq);
 
     memset(&param, 0, sizeof(param));
-    param.grabtype = GRABTYPE_CORE;
+    param.grabtype = CORE;
     param.ownerEvents = stuff->ownerEvents;
     param.this_device_mode = stuff->keyboardMode;
     param.other_devices_mode = stuff->pointerMode;
@@ -5599,7 +5599,7 @@ ProcGrabKey(ClientPtr client)
 
     mask.core = (KeyPressMask | KeyReleaseMask);
 
-    grab = CreateGrab(client->index, keybd, keybd, pWin, GRABTYPE_CORE, &mask,
+    grab = CreateGrab(client->index, keybd, keybd, pWin, CORE, &mask,
                       &param, KeyPress, stuff->key, NullWindow, NullCursor);
     if (!grab)
 	return BadAlloc;
@@ -5690,7 +5690,7 @@ ProcGrabButton(ClientPtr client)
 	return rc;
 
     memset(&param, 0, sizeof(param));
-    param.grabtype = GRABTYPE_CORE;
+    param.grabtype = CORE;
     param.ownerEvents = stuff->ownerEvents;
     param.this_device_mode = stuff->keyboardMode;
     param.other_devices_mode = stuff->pointerMode;
@@ -5699,7 +5699,7 @@ ProcGrabButton(ClientPtr client)
     mask.core = stuff->eventMask;
 
     grab = CreateGrab(client->index, ptr, modifierDevice, pWin,
-                      GRABTYPE_CORE, &mask, &param, ButtonPress,
+                      CORE, &mask, &param, ButtonPress,
                       stuff->button, confineTo, cursor);
     if (!grab)
 	return BadAlloc;
@@ -5744,7 +5744,7 @@ ProcUngrabButton(ClientPtr client)
     tempGrab->modifierDevice = GetMaster(ptr, MASTER_KEYBOARD);
     tempGrab->type = ButtonPress;
     tempGrab->detail.exact = stuff->button;
-    tempGrab->grabtype = GRABTYPE_CORE;
+    tempGrab->grabtype = CORE;
     tempGrab->detail.pMask = NULL;
     tempGrab->next = NULL;
 
@@ -6151,7 +6151,7 @@ PickPointer(ClientPtr client)
     for(it = inputInfo.devices; it; it = it->next)
     {
         GrabPtr grab = it->deviceGrab.grab;
-        if (grab && grab->grabtype == GRABTYPE_CORE && SameClient(grab, client))
+        if (grab && grab->grabtype == CORE && SameClient(grab, client))
         {
             it = GetMaster(it, MASTER_POINTER);
             return it; /* Always return a core grabbed device */
diff --git a/dix/grabs.c b/dix/grabs.c
index 0157b78..6f8b39e 100644
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@ -81,8 +81,8 @@ PrintDeviceGrabInfo(DeviceIntPtr dev)
 
     ErrorF("Active grab 0x%lx (%s) on device '%s' (%d):",
            (unsigned long) grab->resource,
-           (grab->grabtype == GRABTYPE_XI2) ? "xi2" :
-            ((grab->grabtype == GRABTYPE_CORE) ? "core" : "xi1"),
+           (grab->grabtype == XI2) ? "xi2" :
+            ((grab->grabtype == CORE) ? "core" : "xi1"),
            dev->name, dev->id);
 
     client = clients[CLIENT_ID(grab->resource)];
@@ -111,18 +111,18 @@ PrintDeviceGrabInfo(DeviceIntPtr dev)
            devGrab->sync.frozen ? "frozen" : "thawed",
            devGrab->sync.state);
 
-    if (grab->grabtype == GRABTYPE_CORE)
+    if (grab->grabtype == CORE)
     {
         ErrorF("        core event mask 0x%lx\n",
                (unsigned long) grab->eventMask);
     }
-    else if (grab->grabtype == GRABTYPE_XI)
+    else if (grab->grabtype == XI)
     {
         ErrorF("      xi1 event mask 0x%lx\n",
                devGrab->implicitGrab ? (unsigned long) grab->deviceMask :
                                        (unsigned long) grab->eventMask);
     }
-    else if (grab->grabtype == GRABTYPE_XI2)
+    else if (grab->grabtype == XI2)
     {
         for (i = 0; i < xi2mask_num_masks(grab->xi2mask); i++)
         {
@@ -206,7 +206,7 @@ CreateGrab(
     DeviceIntPtr device,
     DeviceIntPtr modDevice,
     WindowPtr window,
-    GrabType grabtype,
+    enum InputLevel grabtype,
     GrabMask *mask,
     GrabParameters *param,
     int type,
@@ -238,7 +238,7 @@ CreateGrab(
     grab->cursor = cursor;
     grab->next = NULL;
 
-    if (grabtype == GRABTYPE_XI2)
+    if (grabtype == XI2)
         xi2mask_merge(grab->xi2mask, mask->xi2mask);
     if (cursor)
 	cursor->refcnt++;
@@ -410,7 +410,7 @@ DetailSupersedesSecond(
 static Bool
 GrabSupersedesSecond(GrabPtr pFirstGrab, GrabPtr pSecondGrab)
 {
-    unsigned int any_modifier = (pFirstGrab->grabtype == GRABTYPE_XI2) ?
+    unsigned int any_modifier = (pFirstGrab->grabtype == XI2) ?
                                 (unsigned int)XIAnyModifier :
                                 (unsigned int)AnyModifier;
     if (!DetailSupersedesSecond(pFirstGrab->modifiersDetail,
@@ -441,14 +441,14 @@ GrabSupersedesSecond(GrabPtr pFirstGrab, GrabPtr pSecondGrab)
 Bool
 GrabMatchesSecond(GrabPtr pFirstGrab, GrabPtr pSecondGrab, Bool ignoreDevice)
 {
-    unsigned int any_modifier = (pFirstGrab->grabtype == GRABTYPE_XI2) ?
+    unsigned int any_modifier = (pFirstGrab->grabtype == XI2) ?
                                 (unsigned int)XIAnyModifier :
                                 (unsigned int)AnyModifier;
 
     if (pFirstGrab->grabtype != pSecondGrab->grabtype)
         return FALSE;
 
-    if (pFirstGrab->grabtype == GRABTYPE_XI2)
+    if (pFirstGrab->grabtype == XI2)
     {
         if (pFirstGrab->device == inputInfo.all_devices ||
             pSecondGrab->device == inputInfo.all_devices)
@@ -500,7 +500,7 @@ GrabMatchesSecond(GrabPtr pFirstGrab, GrabPtr pSecondGrab, Bool ignoreDevice)
 static Bool
 GrabsAreIdentical(GrabPtr pFirstGrab, GrabPtr pSecondGrab)
 {
-    unsigned int any_modifier = (pFirstGrab->grabtype == GRABTYPE_XI2) ?
+    unsigned int any_modifier = (pFirstGrab->grabtype == XI2) ?
                                 (unsigned int)XIAnyModifier :
                                 (unsigned int)AnyModifier;
 
@@ -550,7 +550,7 @@ AddPassiveGrabToList(ClientPtr client, GrabPtr pGrab)
 
     for (grab = wPassiveGrabs(pGrab->window); grab; grab = grab->next)
     {
-	if (GrabMatchesSecond(pGrab, grab, (pGrab->grabtype == GRABTYPE_CORE)))
+	if (GrabMatchesSecond(pGrab, grab, (pGrab->grabtype == CORE)))
 	{
 	    if (CLIENT_BITS(pGrab->resource) != CLIENT_BITS(grab->resource))
 	    {
@@ -628,9 +628,9 @@ DeletePassiveGrabFromList(GrabPtr pMinuendGrab)
 	return FALSE;
     }
 
-    any_modifier = (pMinuendGrab->grabtype == GRABTYPE_XI2) ?
+    any_modifier = (pMinuendGrab->grabtype == XI2) ?
                    (unsigned int)XIAnyModifier : (unsigned int)AnyModifier;
-    any_key = (pMinuendGrab->grabtype == GRABTYPE_XI2) ?
+    any_key = (pMinuendGrab->grabtype == XI2) ?
                    (unsigned int)XIAnyKeycode : (unsigned int)AnyKey;
     ndels = nadds = nups = 0;
     ok = TRUE;
@@ -640,7 +640,7 @@ DeletePassiveGrabFromList(GrabPtr pMinuendGrab)
     {
 	if ((CLIENT_BITS(grab->resource) != CLIENT_BITS(pMinuendGrab->resource)) ||
 	    !GrabMatchesSecond(grab, pMinuendGrab,
-                               (grab->grabtype == GRABTYPE_CORE)))
+                               (grab->grabtype == CORE)))
 	    continue;
 	if (GrabSupersedesSecond(pMinuendGrab, grab))
 	{
diff --git a/include/dixgrabs.h b/include/dixgrabs.h
index ea88770..4dd5eae 100644
--- a/include/dixgrabs.h
+++ b/include/dixgrabs.h
@@ -40,7 +40,7 @@ extern GrabPtr CreateGrab(
 	DeviceIntPtr /* device */,
 	DeviceIntPtr /* modDevice */,
 	WindowPtr /* window */,
-        GrabType /* grabtype */,
+        enum InputLevel /* grabtype */,
         GrabMask * /* mask */,
         struct _GrabParameters * /* param */,
 	int /* type */,
diff --git a/include/eventconvert.h b/include/eventconvert.h
index bb45eef..571a511 100644
--- a/include/eventconvert.h
+++ b/include/eventconvert.h
@@ -31,12 +31,6 @@
 
 #define FP1616(integral, frac) ((integral) * (1 << 16) + (frac) * (1 << 16))
 
-enum InputLevel {
-    CORE,
-    XI,
-    XI2,
-};
-
 _X_EXPORT int EventToCore(InternalEvent *event, xEvent **core, int *count);
 _X_EXPORT int EventToXI(InternalEvent *ev, xEvent **xi, int *count);
 _X_EXPORT int EventToXI2(InternalEvent *ev, xEvent **xi);
diff --git a/include/exevents.h b/include/exevents.h
index 12ea378..0ab04f5 100644
--- a/include/exevents.h
+++ b/include/exevents.h
@@ -159,7 +159,7 @@ typedef struct _XIClientRec {
 
 
 typedef struct _GrabParameters {
-    int                 grabtype;               /* GRABTYPE_CORE, etc. */
+    int                 grabtype;               /* CORE, etc. */
     unsigned int        ownerEvents;
     unsigned int        this_device_mode;
     unsigned int        other_devices_mode;
@@ -200,7 +200,7 @@ GrabButton(
 	DeviceIntPtr           /* modifier_device */,
 	int                    /* button */,
         GrabParameters*        /* param */,
-        GrabType               /* grabtype */,
+        enum InputLevel        /* grabtype */,
 	GrabMask*              /* eventMask */);
 
 extern int
@@ -210,7 +210,7 @@ GrabKey(
 	DeviceIntPtr           /* modifier_device */,
 	int                    /* key */,
         GrabParameters*        /* param */,
-        GrabType               /* grabtype */,
+        enum InputLevel        /* grabtype */,
 	GrabMask*              /* eventMask */);
 
 extern int
diff --git a/include/input.h b/include/input.h
index cbfaba7..7c5ad3c 100644
--- a/include/input.h
+++ b/include/input.h
@@ -102,6 +102,12 @@ SOFTWARE.
 #define RevertToFollowKeyboard	3
 #endif
 
+enum InputLevel {
+    CORE,
+    XI,
+    XI2,
+};
+
 typedef unsigned long Leds;
 typedef struct _OtherClients *OtherClientsPtr;
 typedef struct _InputClients *InputClientsPtr;
diff --git a/include/inputstr.h b/include/inputstr.h
index 5634f3c..754a3f8 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -167,12 +167,6 @@ typedef struct _DetailRec {		/* Grab details may be bit masks */
     Mask                *pMask;
 } DetailRec;
 
-typedef enum {
-    GRABTYPE_CORE,
-    GRABTYPE_XI,
-    GRABTYPE_XI2
-} GrabType;
-
 union _GrabMask {
     Mask core;
     Mask xi;
@@ -200,7 +194,7 @@ typedef struct _GrabRec {
     unsigned		ownerEvents:1;
     unsigned		keyboardMode:1;
     unsigned		pointerMode:1;
-    GrabType		grabtype;
+    enum InputLevel	grabtype;
     CARD8		type;		/* event type */
     DetailRec		modifiersDetail;
     DeviceIntPtr	modifierDevice;
diff --git a/test/input.c b/test/input.c
index c44e5f6..d27b3f0 100644
--- a/test/input.c
+++ b/test/input.c
@@ -148,7 +148,7 @@ static void dix_check_grab_values(void)
 
     memset(&client, 0, sizeof(client));
 
-    param.grabtype = GRABTYPE_CORE;
+    param.grabtype = CORE;
     param.this_device_mode = GrabModeSync;
     param.other_devices_mode = GrabModeSync;
     param.modifiers = AnyModifier;
@@ -531,22 +531,22 @@ static void dix_grab_matching(void)
     memset(&b, 0, sizeof(b));
 
     /* different grabtypes must fail */
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = CORE;
+    b.grabtype = XI2;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = XI;
+    b.grabtype = XI2;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = XI;
+    b.grabtype = CORE;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
@@ -568,8 +568,8 @@ static void dix_grab_matching(void)
 
     inputInfo.all_devices = &xi_all_devices;
     inputInfo.all_master_devices = &xi_all_master_devices;
-    a.grabtype = GRABTYPE_XI2;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = XI2;
+    b.grabtype = XI2;
     a.device = &dev1;
     b.device = &dev2;
 
@@ -598,8 +598,8 @@ static void dix_grab_matching(void)
     assert(rc == FALSE);
 
     /* ignoreDevice FALSE must fail for different devices for CORE and XI */
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI;
+    a.grabtype = XI;
+    b.grabtype = XI;
     a.device = &dev1;
     b.device = &dev2;
     a.modifierDevice = &dev1;
@@ -607,8 +607,8 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = CORE;
+    b.grabtype = CORE;
     a.device = &dev1;
     b.device = &dev2;
     a.modifierDevice = &dev1;
@@ -618,8 +618,8 @@ static void dix_grab_matching(void)
 
     /* ignoreDevice FALSE must fail for different modifier devices for CORE
      * and XI */
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI;
+    a.grabtype = XI;
+    b.grabtype = XI;
     a.device = &dev1;
     b.device = &dev1;
     a.modifierDevice = &dev1;
@@ -627,8 +627,8 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = CORE;
+    b.grabtype = CORE;
     a.device = &dev1;
     b.device = &dev1;
     a.modifierDevice = &dev1;
@@ -637,8 +637,8 @@ static void dix_grab_matching(void)
     assert(rc == FALSE);
 
     /* different event type must fail */
-    a.grabtype = GRABTYPE_XI2;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = XI2;
+    b.grabtype = XI2;
     a.device = &dev1;
     b.device = &dev1;
     a.modifierDevice = &dev1;
@@ -650,8 +650,8 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&a, &b, TRUE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = CORE;
+    b.grabtype = CORE;
     a.device = &dev1;
     b.device = &dev1;
     a.modifierDevice = &dev1;
@@ -663,8 +663,8 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&a, &b, TRUE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI;
+    a.grabtype = XI;
+    b.grabtype = XI;
     a.device = &dev1;
     b.device = &dev1;
     a.modifierDevice = &dev1;
@@ -677,8 +677,8 @@ static void dix_grab_matching(void)
     assert(rc == FALSE);
 
     /* different modifiers must fail */
-    a.grabtype = GRABTYPE_XI2;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = XI2;
+    b.grabtype = XI2;
     a.device = &dev1;
     b.device = &dev1;
     a.modifierDevice = &dev1;
@@ -692,23 +692,23 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = CORE;
+    b.grabtype = CORE;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI;
+    a.grabtype = XI;
+    b.grabtype = XI;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
     /* AnyModifier must fail for XI2 */
-    a.grabtype = GRABTYPE_XI2;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = XI2;
+    b.grabtype = XI2;
     a.modifiersDetail.exact = AnyModifier;
     b.modifiersDetail.exact = 1;
     rc = GrabMatchesSecond(&a, &b, FALSE);
@@ -717,8 +717,8 @@ static void dix_grab_matching(void)
     assert(rc == FALSE);
 
     /* XIAnyModifier must fail for CORE and XI */
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI;
+    a.grabtype = XI;
+    b.grabtype = XI;
     a.modifiersDetail.exact = XIAnyModifier;
     b.modifiersDetail.exact = 1;
     rc = GrabMatchesSecond(&a, &b, FALSE);
@@ -726,8 +726,8 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = CORE;
+    b.grabtype = CORE;
     a.modifiersDetail.exact = XIAnyModifier;
     b.modifiersDetail.exact = 1;
     rc = GrabMatchesSecond(&a, &b, FALSE);
@@ -736,8 +736,8 @@ static void dix_grab_matching(void)
     assert(rc == FALSE);
 
     /* different detail must fail */
-    a.grabtype = GRABTYPE_XI2;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = XI2;
+    b.grabtype = XI2;
     a.detail.exact = 1;
     b.detail.exact = 2;
     a.modifiersDetail.exact = 1;
@@ -747,23 +747,23 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI;
+    a.grabtype = XI;
+    b.grabtype = XI;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = CORE;
+    b.grabtype = CORE;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
     /* detail of AnyModifier must fail */
-    a.grabtype = GRABTYPE_XI2;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = XI2;
+    b.grabtype = XI2;
     a.detail.exact = AnyModifier;
     b.detail.exact = 1;
     a.modifiersDetail.exact = 1;
@@ -773,23 +773,23 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = CORE;
+    b.grabtype = CORE;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI;
+    a.grabtype = XI;
+    b.grabtype = XI;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
     /* detail of XIAnyModifier must fail */
-    a.grabtype = GRABTYPE_XI2;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = XI2;
+    b.grabtype = XI2;
     a.detail.exact = XIAnyModifier;
     b.detail.exact = 1;
     a.modifiersDetail.exact = 1;
@@ -799,23 +799,23 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = CORE;
+    b.grabtype = CORE;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI;
+    a.grabtype = XI;
+    b.grabtype = XI;
     rc = GrabMatchesSecond(&a, &b, FALSE);
     assert(rc == FALSE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == FALSE);
 
     /* XIAnyModifier or AnyModifer must succeed */
-    a.grabtype = GRABTYPE_XI2;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = XI2;
+    b.grabtype = XI2;
     a.detail.exact = 1;
     b.detail.exact = 1;
     a.modifiersDetail.exact = XIAnyModifier;
@@ -825,8 +825,8 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == TRUE);
 
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = CORE;
+    b.grabtype = CORE;
     a.detail.exact = 1;
     b.detail.exact = 1;
     a.modifiersDetail.exact = AnyModifier;
@@ -836,8 +836,8 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == TRUE);
 
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI;
+    a.grabtype = XI;
+    b.grabtype = XI;
     a.detail.exact = 1;
     b.detail.exact = 1;
     a.modifiersDetail.exact = AnyModifier;
@@ -848,8 +848,8 @@ static void dix_grab_matching(void)
     assert(rc == TRUE);
 
     /* AnyKey or XIAnyKeycode must succeed */
-    a.grabtype = GRABTYPE_XI2;
-    b.grabtype = GRABTYPE_XI2;
+    a.grabtype = XI2;
+    b.grabtype = XI2;
     a.detail.exact = XIAnyKeycode;
     b.detail.exact = 1;
     a.modifiersDetail.exact = 1;
@@ -859,8 +859,8 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == TRUE);
 
-    a.grabtype = GRABTYPE_CORE;
-    b.grabtype = GRABTYPE_CORE;
+    a.grabtype = CORE;
+    b.grabtype = CORE;
     a.detail.exact = AnyKey;
     b.detail.exact = 1;
     a.modifiersDetail.exact = 1;
@@ -870,8 +870,8 @@ static void dix_grab_matching(void)
     rc = GrabMatchesSecond(&b, &a, FALSE);
     assert(rc == TRUE);
 
-    a.grabtype = GRABTYPE_XI;
-    b.grabtype = GRABTYPE_XI;
+    a.grabtype = XI;
+    b.grabtype = XI;
     a.detail.exact = AnyKey;
     b.detail.exact = 1;
     a.modifiersDetail.exact = 1;
diff --git a/test/xi2/protocol-xipassivegrabdevice.c b/test/xi2/protocol-xipassivegrabdevice.c
index 1ffcdee..89ffc3d 100644
--- a/test/xi2/protocol-xipassivegrabdevice.c
+++ b/test/xi2/protocol-xipassivegrabdevice.c
@@ -49,7 +49,7 @@ struct test_data {
 } testdata;
 
 int __wrap_GrabButton(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
-                      int button, GrabParameters *param, GrabType grabtype,
+                      int button, GrabParameters *param, enum InputLevel grabtype,
                       GrabMask *mask);
 static void reply_XIPassiveGrabDevice_data(ClientPtr client, int len, char *data, void *userdata);
 
@@ -69,7 +69,7 @@ int __wrap_dixLookupWindow(WindowPtr *win, XID id, ClientPtr client, Mask access
 }
 
 int __wrap_GrabButton(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
-                      int button, GrabParameters *param, GrabType grabtype,
+                      int button, GrabParameters *param, enum InputLevel grabtype,
                       GrabMask *mask)
 {
     /* Fail every odd modifier */
commit cd56bd7b3ee34a4b10eb3a57a6e94cac7512167a
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Dec 8 14:59:06 2011 +1000

    Add GrabIsPointerGrab and GrabIsKeyboardGrab helpers
    
    No functional changes
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 8747599..405a8b1 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1001,9 +1001,7 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
         case ET_KeyRelease:
             if (grab && device->deviceGrab.fromPassiveGrab &&
                 (key == device->deviceGrab.activatingKey) &&
-                (device->deviceGrab.grab->type == KeyPress ||
-                 device->deviceGrab.grab->type == DeviceKeyPress ||
-                 device->deviceGrab.grab->type == XI_KeyPress))
+                GrabIsKeyboardGrab(device->deviceGrab.grab))
                 deactivateDeviceGrab = TRUE;
             break;
         case ET_ButtonPress:
@@ -1023,9 +1021,7 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
             event->detail.button = b->map[key];
             if (grab && !b->buttonsDown &&
                 device->deviceGrab.fromPassiveGrab &&
-                (device->deviceGrab.grab->type == ButtonPress ||
-                 device->deviceGrab.grab->type == DeviceButtonPress ||
-                 device->deviceGrab.grab->type == XI_ButtonPress))
+                GrabIsPointerGrab(device->deviceGrab.grab))
                 deactivateDeviceGrab = TRUE;
         default:
             break;
diff --git a/dix/grabs.c b/dix/grabs.c
index aced130..0157b78 100644
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@ -60,6 +60,7 @@ SOFTWARE.
 #include "dixgrabs.h"
 #include "xace.h"
 #include "exevents.h"
+#include "exglobals.h"
 #include "inpututils.h"
 
 #define BITMASK(i) (((Mask)1) << ((i) & 31))
@@ -737,3 +738,19 @@ DeletePassiveGrabFromList(GrabPtr pMinuendGrab)
 
 #undef UPDATE
 }
+
+Bool
+GrabIsPointerGrab(GrabPtr grab)
+{
+    return (grab->type == ButtonPress ||
+            grab->type == DeviceButtonPress ||
+            grab->type == XI_ButtonPress);
+}
+
+Bool
+GrabIsKeyboardGrab(GrabPtr grab)
+{
+   return (grab->type == KeyPress ||
+           grab->type == DeviceKeyPress ||
+           grab->type == XI_KeyPress);
+}
diff --git a/include/dixgrabs.h b/include/dixgrabs.h
index 65ff45d..ea88770 100644
--- a/include/dixgrabs.h
+++ b/include/dixgrabs.h
@@ -64,4 +64,6 @@ extern _X_EXPORT int AddPassiveGrabToList(
 extern _X_EXPORT Bool DeletePassiveGrabFromList(
 	GrabPtr /* pMinuendGrab */);
 
+extern Bool GrabIsPointerGrab(GrabPtr grab);
+extern Bool GrabIsKeyboardGrab(GrabPtr grab);
 #endif /* DIXGRABS_H */
commit 47734b2ba2e1f9246fd1a3b7059ca60b0e15acb2
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Dec 8 12:00:34 2011 +1000

    dix: move delivery stop condition out of event mask
    
    Previously, this was only called if there was a mask match, so even if we
    had a no-propagate flag set or a stopAt window specified, if no mask
    triggered on the window we would recurse up to the root window and
    eventually deliver.
    Move this, so that the stopAt and do-not-propagate mask is honoured.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 9fcd447..9703ca9 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -2693,12 +2693,13 @@ DeliverDeviceEvents(WindowPtr pWin, InternalEvent *event, GrabPtr grab,
                     break;
             }
 
-            if ((deliveries < 0) || (pWin == stopAt) ||
-                (mask & EVENT_DONT_PROPAGATE_MASK))
-            {
-                deliveries = 0;
-                break;
-            }
+        }
+
+        if ((deliveries < 0) || (pWin == stopAt) ||
+            (mask & EVENT_DONT_PROPAGATE_MASK))
+        {
+            deliveries = 0;
+            break;
         }
 
         child = pWin->drawable.id;
commit 1d01e861b69d7ca8fe2335270b8286bc115fb6e9
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Dec 8 10:22:26 2011 +1000

    dix: split out core state and event state setting into helper functions
    
    no functional changes.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 7983776..8747599 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -915,7 +915,7 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
     int key = 0, rootX, rootY;
     ButtonClassPtr b;
     int ret = 0;
-    int corestate, i;
+    int corestate;
     DeviceIntPtr mouse = NULL, kbd = NULL;
     DeviceEvent *event = &ev->device_event;
 
@@ -945,33 +945,8 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
             mouse = NULL;
     }
 
-    /* core state needs to be assembled BEFORE the device is updated. */
-    corestate = (kbd && kbd->key) ? XkbStateFieldFromRec(&kbd->key->xkbInfo->state) : 0;
-    corestate |= (mouse && mouse->button) ? (mouse->button->state) : 0;
-
-    for (i = 0; mouse && mouse->button && i < mouse->button->numButtons; i++)
-        if (BitIsOn(mouse->button->down, i))
-            SetBit(event->buttons, i);
-
-    if (kbd && kbd->key)
-    {
-        XkbStatePtr state;
-        /* we need the state before the event happens */
-        if (event->type == ET_KeyPress || event->type == ET_KeyRelease)
-            state = &kbd->key->xkbInfo->prev_state;
-        else
-            state = &kbd->key->xkbInfo->state;
-
-        event->mods.base = state->base_mods;
-        event->mods.latched = state->latched_mods;
-        event->mods.locked = state->locked_mods;
-        event->mods.effective = state->mods;
-
-        event->group.base = state->base_group;
-        event->group.latched = state->latched_group;
-        event->group.locked = state->locked_group;
-        event->group.effective = state->group;
-    }
+    corestate = event_get_corestate(mouse, kbd);
+    event_set_state(mouse, kbd, event);
 
     ret = UpdateDeviceState(device, event);
     if (ret == DONT_PROCESS)
diff --git a/dix/inpututils.c b/dix/inpututils.c
index 60f9fa0..5844daf 100644
--- a/dix/inpututils.c
+++ b/dix/inpututils.c
@@ -657,6 +657,45 @@ void init_device_event(DeviceEvent *event, DeviceIntPtr dev, Time ms)
     event->sourceid = dev->id;
 }
 
+int event_get_corestate(DeviceIntPtr mouse, DeviceIntPtr kbd)
+{
+    int corestate;
+    /* core state needs to be assembled BEFORE the device is updated. */
+    corestate = (kbd && kbd->key) ? XkbStateFieldFromRec(&kbd->key->xkbInfo->state) : 0;
+    corestate |= (mouse && mouse->button) ? (mouse->button->state) : 0;
+    return corestate;
+}
+
+void event_set_state(DeviceIntPtr mouse, DeviceIntPtr kbd, DeviceEvent *event)
+{
+    int i;
+
+    for (i = 0; mouse && mouse->button && i < mouse->button->numButtons; i++)
+        if (BitIsOn(mouse->button->down, i))
+            SetBit(event->buttons, i);
+
+    if (kbd && kbd->key)
+    {
+        XkbStatePtr state;
+        /* we need the state before the event happens */
+        if (event->type == ET_KeyPress || event->type == ET_KeyRelease)
+            state = &kbd->key->xkbInfo->prev_state;
+        else
+            state = &kbd->key->xkbInfo->state;
+
+        event->mods.base = state->base_mods;
+        event->mods.latched = state->latched_mods;
+        event->mods.locked = state->locked_mods;
+        event->mods.effective = state->mods;
+
+        event->group.base = state->base_group;
+        event->group.latched = state->latched_group;
+        event->group.locked = state->locked_group;
+        event->group.effective = state->group;
+    }
+}
+
+
 Bool
 point_on_screen(ScreenPtr pScreen, int x, int y)
 {
diff --git a/include/inpututils.h b/include/inpututils.h
index 5f9dfec..96ad6df 100644
--- a/include/inpututils.h
+++ b/include/inpututils.h
@@ -40,6 +40,8 @@ struct _ValuatorMask {
 
 extern void verify_internal_event(const InternalEvent *ev);
 extern void init_device_event(DeviceEvent *event, DeviceIntPtr dev, Time ms);
+extern int event_get_corestate(DeviceIntPtr mouse, DeviceIntPtr kbd);
+extern void event_set_state(DeviceIntPtr mouse, DeviceIntPtr kbd, DeviceEvent *event);
 
 FP3232 double_to_fp3232(double in);
 FP1616 double_to_fp1616(double in);
commit fb010c543696b781a83b945f72865b7d7b75bf95
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Dec 7 14:41:18 2011 +1000

    dix: move grab matching code into a helper function
    
    No functional changes.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 4d80358..9fcd447 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -3751,6 +3751,62 @@ CoreGrabInterferes(DeviceIntPtr device, GrabPtr grab)
     return interfering;
 }
 
+enum MatchFlags {
+    NO_MATCH    = 0x0,
+    CORE_MATCH  = 0x1,
+    XI_MATCH    = 0x2,
+    XI2_MATCH   = 0x4,
+};
+
+/**
+ * Match the grab against the temporary grab on the given input level.
+ * Modifies the temporary grab pointer.
+ *
+ * @param grab The grab to match against
+ * @param tmp The temporary grab to use for matching
+ * @param level The input level we want to match on
+ * @param event_type Wire protocol event type
+ *
+ * @return The respective matched flag or 0 for no match
+ */
+static enum MatchFlags
+MatchForType(const GrabPtr grab, GrabPtr tmp, enum InputLevel level, int event_type)
+{
+    enum MatchFlags match;
+    BOOL ignore_device = FALSE;
+    int grabtype;
+    int evtype;
+
+    switch(level)
+    {
+        case XI2:
+            grabtype = GRABTYPE_XI2;
+            evtype = GetXI2Type(event_type);
+            BUG_WARN(!evtype);
+            match = XI2_MATCH;
+            break;
+        case XI:
+            grabtype = GRABTYPE_XI;
+            evtype = GetXIType(event_type);
+            match = XI_MATCH;
+            break;
+        case CORE:
+            grabtype = GRABTYPE_CORE;
+            evtype = GetCoreType(event_type);
+            match = CORE_MATCH;
+            ignore_device = TRUE;
+            break;
+    }
+
+    tmp->grabtype = grabtype;
+    tmp->type = evtype;
+
+    if (tmp->type && GrabMatchesSecond(tmp, grab, ignore_device))
+        return match;
+
+    return NO_MATCH;
+}
+
 /**
  * Check an individual grab against an event to determine if a passive grab
  * should be activated.
@@ -3768,12 +3824,9 @@ static Bool
 CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
                  Bool checkCore, GrabPtr tempGrab)
 {
-    static const int CORE_MATCH = 0x1;
-    static const int XI_MATCH = 0x2;
-    static const int XI2_MATCH = 0x4;
     DeviceIntPtr gdev;
     XkbSrvInfoPtr xkbi = NULL;
-    int match = 0;
+    enum MatchFlags match = 0;
 
     gdev = grab->modifierDevice;
     if (grab->grabtype == GRABTYPE_CORE)
@@ -3795,27 +3848,13 @@ CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
     tempGrab->modifiersDetail.exact = xkbi ? xkbi->state.grab_mods : 0;
 
     /* Check for XI2 and XI grabs first */
-    tempGrab->type = GetXI2Type(event->any.type);
-    tempGrab->grabtype = GRABTYPE_XI2;
-    if (GrabMatchesSecond(tempGrab, grab, FALSE))
-        match = XI2_MATCH;
+    match = MatchForType(grab, tempGrab, XI2, GetXI2Type(event->any.type));
 
     if (!match)
-    {
-        tempGrab->grabtype = GRABTYPE_XI;
-        if ((tempGrab->type = GetXIType(event->any.type)) &&
-            (GrabMatchesSecond(tempGrab, grab, FALSE)))
-            match = XI_MATCH;
-    }
+        match = MatchForType(grab, tempGrab, XI, GetXIType(event->any.type));
 
-    /* Check for a core grab (ignore the device when comparing) */
     if (!match && checkCore)
-    {
-        tempGrab->grabtype = GRABTYPE_CORE;
-        if ((tempGrab->type = GetCoreType(event->any.type)) &&
-            (GrabMatchesSecond(tempGrab, grab, TRUE)))
-            match = CORE_MATCH;
-    }
+        match = MatchForType(grab, tempGrab, CORE, GetCoreType(event->any.type));
 
     if (!match || (grab->confineTo &&
                    (!grab->confineTo->realized ||
commit d253a262c2c690357a4db7e235c48ab5dd0b77f8
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Dec 7 13:57:25 2011 +1000

    dix: split core grab interference check into helper function
    
    No functional changes.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 349d9b4..4d80358 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -3727,6 +3727,30 @@ ActivatePassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event)
     return TRUE;
 }
 
+static BOOL
+CoreGrabInterferes(DeviceIntPtr device, GrabPtr grab)
+{
+    DeviceIntPtr other;
+    BOOL interfering = FALSE;
+
+    for (other = inputInfo.devices; other; other = other->next)
+    {
+        GrabPtr othergrab = other->deviceGrab.grab;
+        if (othergrab && othergrab->grabtype == GRABTYPE_CORE &&
+                SameClient(grab, rClient(othergrab)) &&
+                ((IsPointerDevice(grab->device) &&
+                  IsPointerDevice(othergrab->device)) ||
+                 (IsKeyboardDevice(grab->device) &&
+                  IsKeyboardDevice(othergrab->device))))
+        {
+            interfering = TRUE;
+            break;
+        }
+    }
+
+    return interfering;
+}
+
 /**
  * Check an individual grab against an event to determine if a passive grab
  * should be activated.
@@ -3806,9 +3830,6 @@ CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
 
     if (grab->grabtype == GRABTYPE_CORE)
     {
-        DeviceIntPtr other;
-        BOOL interfering = FALSE;
-
         /* A passive grab may have been created for a different device
            than it is assigned to at this point in time.
            Update the grab's device and modifier device to reflect the
@@ -3822,21 +3843,7 @@ CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
             grab->modifierDevice = GetMaster(device, MASTER_KEYBOARD);
         }
 
-        for (other = inputInfo.devices; other; other = other->next)
-        {
-            GrabPtr othergrab = other->deviceGrab.grab;
-            if (othergrab && othergrab->grabtype == GRABTYPE_CORE &&
-                SameClient(grab, rClient(othergrab)) &&
-                ((IsPointerDevice(grab->device) &&
-                 IsPointerDevice(othergrab->device)) ||
-                 (IsKeyboardDevice(grab->device) &&
-                  IsKeyboardDevice(othergrab->device))))
-            {
-                interfering = TRUE;
-                break;
-            }
-        }
-        if (interfering)
+        if (CoreGrabInterferes(device, grab))
             return FALSE;
     }
 
commit 97d79dd740ed1ac4eb02b0d4135850f953716278
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Dec 7 13:54:28 2011 +1000

    dix: compare the grab type, not the tempGrab type
    
    No functional change. To get here, GrabMatchesSecond() needs to be TRUE and
    for that the two grab types must be identical.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index e94001a..349d9b4 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -3816,7 +3816,7 @@ CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
            Since XGrabDeviceButton requires to specify the
            modifierDevice explicitly, we don't override this choice.
          */
-        if (tempGrab->type < GenericEvent)
+        if (grab->type < GenericEvent)
         {
             grab->device = device;
             grab->modifierDevice = GetMaster(device, MASTER_KEYBOARD);
commit b9d6ae42b686287d7d23c2eefe2b12da98fe6ff8
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Dec 7 15:43:31 2011 +1000

    dix: remove event type check
    
    Can't remember why this is there but we'll need to pass in XI2 events soon,
    so this check is obsolete.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 3041ae6..e94001a 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -3653,13 +3653,6 @@ ActivatePassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event)
     int count;
     int rc;
 
-    if (!GetXIType(event->any.type) && !GetCoreType(event->any.type))
-    {
-        ErrorF("Event type %d in CheckPassiveGrabsOnWindow is neither"
-               " XI 1.x nor core\n", event->any.type);
-        return FALSE;
-    }
-
     /* The only consumers of corestate are Xi 1.x and core events, which
      * are guaranteed to come from DeviceEvents. */
     if (grab->grabtype == GRABTYPE_XI || grab->grabtype == GRABTYPE_CORE)
commit 80816366aa77f1730a1b6ddabfa55a946d76d494
Author: Chase Douglas <chase.douglas at canonical.com>
Date:   Fri Nov 25 13:57:03 2011 -0800

    dix: Split ActivatePassiveGrab() from CheckPassiveGrab()
    
    The changed logic means we don't require the explicit grab = NULL setting
    and early exit anymore. Not 100% of it, but if we see that message pop up in
    a log we know it's broken.
    
    Signed-off-by: Chase Douglas <chase.douglas at canonical.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/events.c b/dix/events.c
index 09d38a1..3041ae6 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -3635,38 +3635,128 @@ BorderSizeNotEmpty(DeviceIntPtr pDev, WindowPtr pWin)
 }
 
 /**
+ * Activate the given passive grab. If the grab is activated successfully, the
+ * event has been delivered to the client.
+ *
+ * @param device The device of the event to check.
+ * @param grab The grab to check.
+ * @param event The current device event.
+ *
+ * @return Whether the grab has been activated.
+ */
+Bool
+ActivatePassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event)
+{
+    SpritePtr pSprite = device->spriteInfo->sprite;
+    GrabInfoPtr grabinfo = &device->deviceGrab;
+    xEvent *xE = NULL;
+    int count;
+    int rc;
+
+    if (!GetXIType(event->any.type) && !GetCoreType(event->any.type))
+    {
+        ErrorF("Event type %d in CheckPassiveGrabsOnWindow is neither"
+               " XI 1.x nor core\n", event->any.type);
+        return FALSE;
+    }
+
+    /* The only consumers of corestate are Xi 1.x and core events, which
+     * are guaranteed to come from DeviceEvents. */
+    if (grab->grabtype == GRABTYPE_XI || grab->grabtype == GRABTYPE_CORE)
+    {
+        DeviceIntPtr gdev;
+
+        event->device_event.corestate &= 0x1f00;
+
+        if (grab->grabtype == GRABTYPE_CORE)
+            gdev = GetMaster(device, KEYBOARD_OR_FLOAT);
+        else
+            gdev = grab->modifierDevice;
+
+        if (gdev && gdev->key && gdev->key->xkbInfo)
+            event->device_event.corestate |=
+                gdev->key->xkbInfo->state.grab_mods & (~0x1f00);
+    }
+
+    if (grab->grabtype == GRABTYPE_CORE)
+    {
+        rc = EventToCore(event, &xE, &count);
+        if (rc != Success)
+        {
+            BUG_WARN_MSG(rc != BadMatch,"[dix] %s: core conversion failed"
+                         "(%d, %d).\n", device->name, event->any.type, rc);
+            return FALSE;
+        }
+    } else if (grab->grabtype == GRABTYPE_XI2)
+    {
+        rc = EventToXI2(event, &xE);
+        if (rc != Success)
+        {
+            if (rc != BadMatch)
+                BUG_WARN_MSG(rc != BadMatch,"[dix] %s: XI2 conversion failed"
+                             "(%d, %d).\n", device->name, event->any.type, rc);
+            return FALSE;
+        }
+        count = 1;
+    } else
+    {
+        rc = EventToXI(event, &xE, &count);
+        if (rc != Success)
+        {
+            if (rc != BadMatch)
+                BUG_WARN_MSG(rc != BadMatch,"[dix] %s: XI conversion failed"
+                             "(%d, %d).\n", device->name, event->any.type, rc);
+            return FALSE;
+        }
+    }
+
+    (*grabinfo->ActivateGrab)(device, grab, currentTime, TRUE);
+
+    if (xE)
+    {
+        FixUpEventFromWindow(pSprite, xE, grab->window, None, TRUE);
+
+        /* XXX: XACE? */
+        TryClientEvents(rClient(grab), device, xE, count,
+                        GetEventFilter(device, xE),
+                        GetEventFilter(device, xE), grab);
+    }
+
+    if (grabinfo->sync.state == FROZEN_NO_EVENT)
+    {
+        if (!grabinfo->sync.event)
+            grabinfo->sync.event = calloc(1, sizeof(DeviceEvent));
+        *grabinfo->sync.event = event->device_event;
+        grabinfo->sync.state = FROZEN_WITH_EVENT;
+    }
+
+    free(xE);
+    return TRUE;
+}
+
+/**
  * Check an individual grab against an event to determine if a passive grab
  * should be activated.
- * If activate is true and a passive grab is found, it will be activated, and
- * the event will be delivered to the client.
  *
  * @param device The device of the event to check.
  * @param grab The grab to check.
  * @param event The current device event.
  * @param checkCore Check for core grabs too.
- * @param activate Whether to activate a matching grab.
  * @param tempGrab A pre-allocated temporary grab record for matching. This
  *        must have the window and device values filled in.
- * @param[out] grab_return The modified value of grab, to be used in the
- * caller for grab activation if a this function returns TRUE. May be NULL.
  *
  * @return Whether the grab matches the event.
  */
 static Bool
 CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
-                 Bool checkCore, Bool activate, GrabPtr tempGrab, GrabPtr *grab_return)
+                 Bool checkCore, GrabPtr tempGrab)
 {
     static const int CORE_MATCH = 0x1;
     static const int XI_MATCH = 0x2;
     static const int XI2_MATCH = 0x4;
-    SpritePtr pSprite = device->spriteInfo->sprite;
-    GrabInfoPtr grabinfo;
     DeviceIntPtr gdev;
     XkbSrvInfoPtr xkbi = NULL;
-    xEvent *xE = NULL;
     int match = 0;
-    int count;
-    int rc;
 
     gdev = grab->modifierDevice;
     if (grab->grabtype == GRABTYPE_CORE)
@@ -3715,8 +3805,6 @@ CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
                     !BorderSizeNotEmpty(device, grab->confineTo))))
         return FALSE;
 
-    *grab_return = grab;
-    grabinfo = &device->deviceGrab;
     /* In some cases a passive core grab may exist, but the client
      * already has a core grab on some other device. In this case we
      * must not get the grab, otherwise we may never ungrab the
@@ -3759,79 +3847,6 @@ CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
             return FALSE;
     }
 
-    if (!activate)
-        return TRUE;
-    else if (!GetXIType(event->any.type) && !GetCoreType(event->any.type))
-    {
-        ErrorF("Event type %d in CheckPassiveGrabsOnWindow is neither"
-               " XI 1.x nor core\n", event->any.type);
-        *grab_return = NULL;
-        return TRUE;
-    }
-
-    /* The only consumers of corestate are Xi 1.x and core events, which
-     * are guaranteed to come from DeviceEvents. */
-    if (match & (XI_MATCH | CORE_MATCH))
-    {
-        event->device_event.corestate &= 0x1f00;
-        event->device_event.corestate |= tempGrab->modifiersDetail.exact &
-                                          (~0x1f00);
-    }
-
-    if (match & CORE_MATCH)
-    {
-        rc = EventToCore(event, &xE, &count);
-        if (rc != Success)
-        {
-            if (rc != BadMatch)
-                ErrorF("[dix] %s: core conversion failed in CPGFW "
-                        "(%d, %d).\n", device->name, event->any.type, rc);
-            return TRUE;
-        }
-    } else if (match & XI2_MATCH)
-    {
-        rc = EventToXI2(event, &xE);
-        if (rc != Success)
-        {
-            if (rc != BadMatch)
-                ErrorF("[dix] %s: XI2 conversion failed in CPGFW "
-                        "(%d, %d).\n", device->name, event->any.type, rc);
-            return TRUE;
-        }
-        count = 1;
-    } else
-    {
-        rc = EventToXI(event, &xE, &count);
-        if (rc != Success)
-        {
-            if (rc != BadMatch)
-                ErrorF("[dix] %s: XI conversion failed in CPGFW "
-                        "(%d, %d).\n", device->name, event->any.type, rc);
-            return TRUE;
-        }
-    }
-
-    (*grabinfo->ActivateGrab)(device, grab, currentTime, TRUE);
-
-    if (xE)
-    {
-        FixUpEventFromWindow(pSprite, xE, grab->window, None, TRUE);
-
-        /* XXX: XACE? */
-        TryClientEvents(rClient(grab), device, xE, count,
-                        GetEventFilter(device, xE),
-                        GetEventFilter(device, xE), grab);
-    }
-
-    if (grabinfo->sync.state == FROZEN_NO_EVENT)
-    {
-        if (!grabinfo->sync.event)
-            grabinfo->sync.event = calloc(1, sizeof(DeviceEvent));
-        *grabinfo->sync.event = event->device_event;
-        grabinfo->sync.state = FROZEN_WITH_EVENT;
-    }
-
-    free(xE);
     return TRUE;
 }
 
@@ -3887,9 +3902,15 @@ CheckPassiveGrabsOnWindow(
     tempGrab->next = NULL;
 
     for (; grab; grab = grab->next)
-        if (CheckPassiveGrab(device, grab, event, checkCore, activate,
-                             tempGrab, &grab))
-            break;
+    {
+        if (!CheckPassiveGrab(device, grab, event, checkCore, tempGrab))
+            continue;
+
+        if (activate && !ActivatePassiveGrab(device, grab, event))
+            continue;
+
+        break;
+    }
 
     FreeGrab(tempGrab);
     return grab;
diff --git a/include/input.h b/include/input.h
index de2a75d..cbfaba7 100644
--- a/include/input.h
+++ b/include/input.h
@@ -548,6 +548,8 @@ void FixUpEventFromWindow(SpritePtr pSprite,
 extern WindowPtr XYToWindow(SpritePtr pSprite, int x, int y);
 extern int EventIsDeliverable(DeviceIntPtr dev, InternalEvent* event,
                               WindowPtr win);
+extern Bool ActivatePassiveGrab(DeviceIntPtr dev, GrabPtr grab,
+                                InternalEvent *ev);
 /**
  * Masks specifying the type of event to deliver for an InternalEvent; used
  * by EventIsDeliverable.
commit 9ee62cd8ce3c3effc3663f3d56b322385ce12fdb
Author: Chase Douglas <chase.douglas at canonical.com>
Date:   Thu Nov 17 17:40:24 2011 -0800

    dix: Move grab check and activation logic to CheckPassiveGrab()
    
    This is needed for future pointer emulation work.
    
    Signed-off-by: Chase Douglas <chase.douglas at canonical.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/events.c b/dix/events.c
index 12c1678..09d38a1 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -3635,6 +3635,207 @@ BorderSizeNotEmpty(DeviceIntPtr pDev, WindowPtr pWin)
 }
 
 /**
+ * Check an individual grab against an event to determine if a passive grab
+ * should be activated.
+ * If activate is true and a passive grab is found, it will be activated, and
+ * the event will be delivered to the client.
+ *
+ * @param device The device of the event to check.
+ * @param grab The grab to check.
+ * @param event The current device event.
+ * @param checkCore Check for core grabs too.
+ * @param activate Whether to activate a matching grab.
+ * @param tempGrab A pre-allocated temporary grab record for matching. This
+ *        must have the window and device values filled in.
+ * @param[out] grab_return The modified value of grab, to be used in the
+ * caller for grab activation if a this function returns TRUE. May be NULL.
+ *
+ * @return Whether the grab matches the event.
+ */
+static Bool
+CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
+                 Bool checkCore, Bool activate, GrabPtr tempGrab, GrabPtr *grab_return)
+{
+    static const int CORE_MATCH = 0x1;
+    static const int XI_MATCH = 0x2;
+    static const int XI2_MATCH = 0x4;
+    SpritePtr pSprite = device->spriteInfo->sprite;
+    GrabInfoPtr grabinfo;
+    DeviceIntPtr gdev;
+    XkbSrvInfoPtr xkbi = NULL;
+    xEvent *xE = NULL;
+    int match = 0;
+    int count;
+    int rc;
+
+    gdev = grab->modifierDevice;
+    if (grab->grabtype == GRABTYPE_CORE)
+    {
+        gdev = GetMaster(device, KEYBOARD_OR_FLOAT);
+    } else if (grab->grabtype == GRABTYPE_XI2)
+    {
+        /* if the device is an attached slave device, gdev must be the
+         * attached master keyboard. Since the slave may have been
+         * reattached after the grab, the modifier device may not be the
+         * same. */
+        if (!IsMaster(grab->device) && !IsFloating(device))
+            gdev = GetMaster(device, MASTER_KEYBOARD);
+    }
+
+    if (gdev && gdev->key)
+        xkbi= gdev->key->xkbInfo;
+    tempGrab->modifierDevice = grab->modifierDevice;
+    tempGrab->modifiersDetail.exact = xkbi ? xkbi->state.grab_mods : 0;
+
+    /* Check for XI2 and XI grabs first */
+    tempGrab->type = GetXI2Type(event->any.type);
+    tempGrab->grabtype = GRABTYPE_XI2;
+    if (GrabMatchesSecond(tempGrab, grab, FALSE))
+        match = XI2_MATCH;
+
+    if (!match)
+    {
+        tempGrab->grabtype = GRABTYPE_XI;
+        if ((tempGrab->type = GetXIType(event->any.type)) &&
+            (GrabMatchesSecond(tempGrab, grab, FALSE)))
+            match = XI_MATCH;
+    }
+
+    /* Check for a core grab (ignore the device when comparing) */
+    if (!match && checkCore)
+    {
+        tempGrab->grabtype = GRABTYPE_CORE;
+        if ((tempGrab->type = GetCoreType(event->any.type)) &&
+            (GrabMatchesSecond(tempGrab, grab, TRUE)))
+            match = CORE_MATCH;
+    }
+
+    if (!match || (grab->confineTo &&
+                   (!grab->confineTo->realized ||
+                    !BorderSizeNotEmpty(device, grab->confineTo))))
+        return FALSE;
+
+    *grab_return = grab;
+    grabinfo = &device->deviceGrab;
+    /* In some cases a passive core grab may exist, but the client
+     * already has a core grab on some other device. In this case we
+     * must not get the grab, otherwise we may never ungrab the
+     * device.
+     */
+
+    if (grab->grabtype == GRABTYPE_CORE)
+    {
+        DeviceIntPtr other;
+        BOOL interfering = FALSE;
+
+        /* A passive grab may have been created for a different device
+           than it is assigned to at this point in time.
+           Update the grab's device and modifier device to reflect the
+           current state.
+           Since XGrabDeviceButton requires to specify the
+           modifierDevice explicitly, we don't override this choice.
+         */
+        if (tempGrab->type < GenericEvent)
+        {
+            grab->device = device;
+            grab->modifierDevice = GetMaster(device, MASTER_KEYBOARD);
+        }
+
+        for (other = inputInfo.devices; other; other = other->next)
+        {
+            GrabPtr othergrab = other->deviceGrab.grab;
+            if (othergrab && othergrab->grabtype == GRABTYPE_CORE &&
+                SameClient(grab, rClient(othergrab)) &&
+                ((IsPointerDevice(grab->device) &&
+                 IsPointerDevice(othergrab->device)) ||
+                 (IsKeyboardDevice(grab->device) &&
+                  IsKeyboardDevice(othergrab->device))))
+            {
+                interfering = TRUE;
+                break;
+            }
+        }
+        if (interfering)
+            return FALSE;
+    }
+
+    if (!activate)
+        return TRUE;
+    else if (!GetXIType(event->any.type) && !GetCoreType(event->any.type))
+    {
+        ErrorF("Event type %d in CheckPassiveGrabsOnWindow is neither"
+               " XI 1.x nor core\n", event->any.type);
+        *grab_return = NULL;
+        return TRUE;
+    }
+
+    /* The only consumers of corestate are Xi 1.x and core events, which
+     * are guaranteed to come from DeviceEvents. */
+    if (match & (XI_MATCH | CORE_MATCH))
+    {
+        event->device_event.corestate &= 0x1f00;
+        event->device_event.corestate |= tempGrab->modifiersDetail.exact &
+                                          (~0x1f00);
+    }
+
+    if (match & CORE_MATCH)
+    {
+        rc = EventToCore(event, &xE, &count);
+        if (rc != Success)
+        {
+            if (rc != BadMatch)
+                ErrorF("[dix] %s: core conversion failed in CPGFW "
+                        "(%d, %d).\n", device->name, event->any.type, rc);
+            return TRUE;
+        }
+    } else if (match & XI2_MATCH)
+    {
+        rc = EventToXI2(event, &xE);
+        if (rc != Success)
+        {
+            if (rc != BadMatch)
+                ErrorF("[dix] %s: XI2 conversion failed in CPGFW "
+                        "(%d, %d).\n", device->name, event->any.type, rc);
+            return TRUE;
+        }
+        count = 1;
+    } else
+    {
+        rc = EventToXI(event, &xE, &count);
+        if (rc != Success)
+        {
+            if (rc != BadMatch)
+                ErrorF("[dix] %s: XI conversion failed in CPGFW "
+                        "(%d, %d).\n", device->name, event->any.type, rc);
+            return TRUE;
+        }
+    }
+
+    (*grabinfo->ActivateGrab)(device, grab, currentTime, TRUE);
+
+    if (xE)
+    {
+        FixUpEventFromWindow(pSprite, xE, grab->window, None, TRUE);
+
+        /* XXX: XACE? */
+        TryClientEvents(rClient(grab), device, xE, count,
+                        GetEventFilter(device, xE),
+                        GetEventFilter(device, xE), grab);
+    }
+
+    if (grabinfo->sync.state == FROZEN_NO_EVENT)
+    {
+        if (!grabinfo->sync.event)
+            grabinfo->sync.event = calloc(1, sizeof(DeviceEvent));
+        *grabinfo->sync.event = event->device_event;
+        grabinfo->sync.state = FROZEN_WITH_EVENT;
+    }
+
+    free(xE);
+    return TRUE;
+}
+
+/**
  * "CheckPassiveGrabsOnWindow" checks to see if the event passed in causes a
  * passive grab set on the window to be activated.
  * If activate is true and a passive grab is found, it will be activated,
@@ -3655,14 +3856,8 @@ CheckPassiveGrabsOnWindow(
     BOOL checkCore,
     BOOL activate)
 {
-    SpritePtr pSprite = device->spriteInfo->sprite;
     GrabPtr grab = wPassiveGrabs(pWin);
     GrabPtr tempGrab;
-    GrabInfoPtr grabinfo;
-#define CORE_MATCH      0x1
-#define XI_MATCH        0x2
-#define XI2_MATCH        0x4
-    int match = 0;
 
     if (!grab)
 	return NULL;
@@ -3690,185 +3885,14 @@ CheckPassiveGrabsOnWindow(
     tempGrab->detail.pMask = NULL;
     tempGrab->modifiersDetail.pMask = NULL;
     tempGrab->next = NULL;
-    for (; grab; grab = grab->next)
-    {
-	DeviceIntPtr	gdev;
-	XkbSrvInfoPtr	xkbi = NULL;
-	xEvent *xE = NULL;
-        int count, rc;
-
-	gdev= grab->modifierDevice;
-        if (grab->grabtype == GRABTYPE_CORE)
-        {
-            gdev = GetMaster(device, KEYBOARD_OR_FLOAT);
-        } else if (grab->grabtype == GRABTYPE_XI2)
-        {
-            /* if the device is an attached slave device, gdev must be the
-             * attached master keyboard. Since the slave may have been
-             * reattached after the grab, the modifier device may not be the
-             * same. */
-            if (!IsMaster(grab->device) && !IsFloating(device))
-                gdev = GetMaster(device, MASTER_KEYBOARD);
-        }
 
-
-        if (gdev && gdev->key)
-            xkbi= gdev->key->xkbInfo;
-        tempGrab->modifierDevice = grab->modifierDevice;
-        tempGrab->modifiersDetail.exact = xkbi ? xkbi->state.grab_mods : 0;
-
-        /* Check for XI2 and XI grabs first */
-        tempGrab->type = GetXI2Type(event->any.type);
-        tempGrab->grabtype = GRABTYPE_XI2;
-        if (GrabMatchesSecond(tempGrab, grab, FALSE))
-            match = XI2_MATCH;
-
-        if (!match)
-        {
-            tempGrab->grabtype = GRABTYPE_XI;
-            if ((tempGrab->type = GetXIType(event->any.type)) &&
-                (GrabMatchesSecond(tempGrab, grab, FALSE)))
-                match = XI_MATCH;
-        }
-
-        /* Check for a core grab (ignore the device when comparing) */
-        if (!match && checkCore)
-        {
-            tempGrab->grabtype = GRABTYPE_CORE;
-            if ((tempGrab->type = GetCoreType(event->any.type)) &&
-                (GrabMatchesSecond(tempGrab, grab, TRUE)))
-                match = CORE_MATCH;
-        }
-
-        if (!match || (grab->confineTo &&
-                       (!grab->confineTo->realized ||
-                        !BorderSizeNotEmpty(device, grab->confineTo))))
-            continue;
-
-        grabinfo = &device->deviceGrab;
-        /* In some cases a passive core grab may exist, but the client
-         * already has a core grab on some other device. In this case we
-         * must not get the grab, otherwise we may never ungrab the
-         * device.
-         */
-
-        if (grab->grabtype == GRABTYPE_CORE)
-        {
-            DeviceIntPtr other;
-            BOOL interfering = FALSE;
-
-            /* A passive grab may have been created for a different device
-               than it is assigned to at this point in time.
-               Update the grab's device and modifier device to reflect the
-               current state.
-               Since XGrabDeviceButton requires to specify the
-               modifierDevice explicitly, we don't override this choice.
-               */
-            if (tempGrab->type < GenericEvent)
-            {
-                grab->device = device;
-                grab->modifierDevice = GetMaster(device, MASTER_KEYBOARD);
-            }
-
-            for (other = inputInfo.devices; other; other = other->next)
-            {
-                GrabPtr othergrab = other->deviceGrab.grab;
-                if (othergrab && othergrab->grabtype == GRABTYPE_CORE &&
-                    SameClient(grab, rClient(othergrab)) &&
-                    ((IsPointerDevice(grab->device) &&
-                     IsPointerDevice(othergrab->device)) ||
-                     (IsKeyboardDevice(grab->device) &&
-                      IsKeyboardDevice(othergrab->device))))
-                {
-                    interfering = TRUE;
-                    break;
-                }
-            }
-            if (interfering)
-                continue;
-        }
-
-        if (!activate)
-            break;
-        else if (!GetXIType(event->any.type) && !GetCoreType(event->any.type))
-        {
-            ErrorF("Event type %d in CheckPassiveGrabsOnWindow is neither"
-                   " XI 1.x nor core\n", event->any.type);
-            grab = NULL;
+    for (; grab; grab = grab->next)
+        if (CheckPassiveGrab(device, grab, event, checkCore, activate,
+                             tempGrab, &grab))
             break;
-        }
-
-        /* The only consumers of corestate are Xi 1.x and core events, which
-         * are guaranteed to come from DeviceEvents. */
-        if (match & (XI_MATCH | CORE_MATCH))
-        {
-            event->device_event.corestate &= 0x1f00;
-            event->device_event.corestate |= tempGrab->modifiersDetail.exact &
-                                              (~0x1f00);
-        }
-
-        if (match & CORE_MATCH)
-        {
-            rc = EventToCore(event, &xE, &count);
-            if (rc != Success)
-            {
-                if (rc != BadMatch)
-                    ErrorF("[dix] %s: core conversion failed in CPGFW "
-                            "(%d, %d).\n", device->name, event->any.type, rc);
-                continue;
-            }
-        } else if (match & XI2_MATCH)
-        {
-            rc = EventToXI2(event, &xE);
-            if (rc != Success)
-            {
-                if (rc != BadMatch)
-                    ErrorF("[dix] %s: XI2 conversion failed in CPGFW "
-                            "(%d, %d).\n", device->name, event->any.type, rc);
-                continue;
-            }
-            count = 1;
-        } else
-        {
-            rc = EventToXI(event, &xE, &count);
-            if (rc != Success)
-            {
-                if (rc != BadMatch)
-                    ErrorF("[dix] %s: XI conversion failed in CPGFW "
-                            "(%d, %d).\n", device->name, event->any.type, rc);
-                continue;
-            }
-        }
-
-        (*grabinfo->ActivateGrab)(device, grab, currentTime, TRUE);
-
-        if (xE)
-        {
-            FixUpEventFromWindow(pSprite, xE, grab->window, None, TRUE);
-
-            /* XXX: XACE? */
-            TryClientEvents(rClient(grab), device, xE, count,
-                            GetEventFilter(device, xE),
-                            GetEventFilter(device, xE), grab);
-        }
-
-        if (grabinfo->sync.state == FROZEN_NO_EVENT)
-        {
-            if (!grabinfo->sync.event)
-                grabinfo->sync.event = calloc(1, sizeof(DeviceEvent));
-            *grabinfo->sync.event = event->device_event;
-            grabinfo->sync.state = FROZEN_WITH_EVENT;
-        }
-
-        free(xE);
-        break;
-    }
 
     FreeGrab(tempGrab);
     return grab;
-#undef CORE_MATCH
-#undef XI_MATCH
-#undef XI2_MATCH
 }
 
 /**
commit c53651dabc66aeb9882819a404a799a364f00a29
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Dec 6 12:57:38 2011 +1000

    dix: move EventDeliveryState into a header file, we'll need it elsewhere
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 6e015fe..12c1678 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -2014,13 +2014,6 @@ ActivateImplicitGrab(DeviceIntPtr dev, ClientPtr client, WindowPtr win,
     return TRUE;
 }
 
-enum EventDeliveryState {
-    EVENT_DELIVERED,     /**< Event has been delivered to a client  */
-    EVENT_NOT_DELIVERED, /**< Event was not delivered to any client */
-    EVENT_SKIP,          /**< Event can be discarded by the caller  */
-    EVENT_REJECTED,      /**< Event was rejected for delivery to the client */
-};
-
 /**
  * Attempt event delivery to the client owning the window.
  */
diff --git a/include/input.h b/include/input.h
index 917e92f..de2a75d 100644
--- a/include/input.h
+++ b/include/input.h
@@ -560,6 +560,13 @@ extern int EventIsDeliverable(DeviceIntPtr dev, InternalEvent* event,
 #define EVENT_XI2_MASK                (1 << 3) /**< XI2 mask set on window */
 /* @} */
 
+enum EventDeliveryState {
+    EVENT_DELIVERED,     /**< Event has been delivered to a client  */
+    EVENT_NOT_DELIVERED, /**< Event was not delivered to any client */
+    EVENT_SKIP,          /**< Event can be discarded by the caller  */
+    EVENT_REJECTED,      /**< Event was rejected for delivery to the client */
+};
+
 /* Implemented by the DDX. */
 extern _X_EXPORT int NewInputDeviceRequest(
     InputOption *options,
commit 86c3137c81e924bacd919e9d65809e07afeabbff
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Dec 6 12:04:11 2011 +1000

    Xi: split updating button count and state into helper functions
    
    Functional change: for a button mapped to 0, the motionHintWindow is not
    updated to the NullWindow anymore. Before it got updated unconditionally to
    the button mapping. I have no idea what the practical effect of this is, but
    I guess it's closer to the correct behaviour: pressing a button that's
    logically disabled now does not disrupt the motion hint delivery.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 2110957..7983776 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -726,6 +726,32 @@ UpdateDeviceMotionMask(DeviceIntPtr device, unsigned short state,
     SetMaskForEvent(device->id, mask, MotionNotify);
 }
 
+static void
+IncreaseButtonCount(DeviceIntPtr dev, int key, CARD8 *buttons_down,
+                    Mask *motion_mask, unsigned short *state)
+{
+    if (dev->valuator)
+        dev->valuator->motionHintWindow = NullWindow;
+
+    (*buttons_down)++;
+    *motion_mask = DeviceButtonMotionMask;
+    if (dev->button->map[key] <= 5)
+        *state |= (Button1Mask >> 1) << dev->button->map[key];
+}
+
+static void
+DecreaseButtonCount(DeviceIntPtr dev, int key, CARD8 *buttons_down,
+                    Mask *motion_mask, unsigned short *state)
+{
+    if (dev->valuator)
+        dev->valuator->motionHintWindow = NullWindow;
+
+    if (*buttons_down >= 1 && !--(*buttons_down))
+        *motion_mask = 0;
+    if (dev->button->map[key] <= 5)
+        *state &= ~((Button1Mask >> 1) << dev->button->map[key]);
+}
+
 /**
  * Update the device state according to the data in the event.
  *
@@ -831,15 +857,11 @@ UpdateDeviceState(DeviceIntPtr device, DeviceEvent* event)
             return DONT_PROCESS;
 
         set_button_down(device, key, BUTTON_PROCESSED);
-	if (device->valuator)
-	    device->valuator->motionHintWindow = NullWindow;
+
         if (!b->map[key])
             return DONT_PROCESS;
-        b->buttonsDown++;
-	b->motionMask = DeviceButtonMotionMask;
-        if (b->map[key] <= 5)
-	    b->state |= (Button1Mask >> 1) << b->map[key];
 
+        IncreaseButtonCount(device, key, &b->buttonsDown, &b->motionMask, &b->state);
         UpdateDeviceMotionMask(device, b->state, b->motionMask);
     } else if (event->type == ET_ButtonRelease) {
         if (!b)
@@ -867,15 +889,10 @@ UpdateDeviceState(DeviceIntPtr device, DeviceEvent* event)
             }
         }
         set_button_up(device, key, BUTTON_PROCESSED);
-	if (device->valuator)
-	    device->valuator->motionHintWindow = NullWindow;
         if (!b->map[key])
             return DONT_PROCESS;
-        if (b->buttonsDown >= 1 && !--b->buttonsDown)
-	    b->motionMask = 0;
-	if (b->map[key] <= 5)
-	    b->state &= ~((Button1Mask >> 1) << b->map[key]);
 
+        DecreaseButtonCount(device, key, &b->buttonsDown, &b->motionMask, &b->state);
         UpdateDeviceMotionMask(device,  b->state, b->motionMask);
     } else if (event->type == ET_ProximityIn)
 	device->proximity->in_proximity = TRUE;
commit e0f37250ffff5dcb3bc0e8cad63439995ce01a20
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Dec 6 11:40:33 2011 +1000

    Xi: deduplicate button motion mask setting
    
    No functional changes
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index b2e82ec..2110957 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -704,6 +704,29 @@ ChangeMasterDeviceClasses(DeviceIntPtr device, DeviceChangedEvent *dce)
 }
 
 /**
+ * Add state and motionMask to the filter for this event. The protocol
+ * supports some extra masks for motion when a button is down:
+ * ButtonXMotionMask and the DeviceButtonMotionMask to trigger only when at
+ * least one button (or that specific button is down). These masks need to
+ * be added to the filters for core/XI motion events.
+ *
+ * @param device The device to update the mask for
+ * @param state The current button state mask
+ * @param motion_mask The motion mask (DeviceButtonMotionMask or 0)
+ */
+static void
+UpdateDeviceMotionMask(DeviceIntPtr device, unsigned short state,
+                       Mask motion_mask)
+{
+    Mask mask;
+
+    mask = DevicePointerMotionMask | state | motion_mask;
+    SetMaskForEvent(device->id, mask, DeviceMotionNotify);
+    mask = PointerMotionMask | state | motion_mask;
+    SetMaskForEvent(device->id, mask, MotionNotify);
+}
+
+/**
  * Update the device state according to the data in the event.
  *
  * return values are
@@ -801,7 +824,6 @@ UpdateDeviceState(DeviceIntPtr device, DeviceEvent* event)
 	    device->valuator->motionHintWindow = NullWindow;
 	set_key_up(device, key, KEY_PROCESSED);
     } else if (event->type == ET_ButtonPress) {
-        Mask mask;
         if (!b)
             return DONT_PROCESS;
 
@@ -818,13 +840,8 @@ UpdateDeviceState(DeviceIntPtr device, DeviceEvent* event)
         if (b->map[key] <= 5)
 	    b->state |= (Button1Mask >> 1) << b->map[key];
 
-        /* Add state and motionMask to the filter for this event */
-        mask = DevicePointerMotionMask | b->state | b->motionMask;
-        SetMaskForEvent(device->id, mask, DeviceMotionNotify);
-        mask = PointerMotionMask | b->state | b->motionMask;
-        SetMaskForEvent(device->id, mask, MotionNotify);
+        UpdateDeviceMotionMask(device, b->state, b->motionMask);
     } else if (event->type == ET_ButtonRelease) {
-        Mask mask;
         if (!b)
             return DONT_PROCESS;
 
@@ -859,11 +876,7 @@ UpdateDeviceState(DeviceIntPtr device, DeviceEvent* event)
 	if (b->map[key] <= 5)
 	    b->state &= ~((Button1Mask >> 1) << b->map[key]);
 
-        /* Add state and motionMask to the filter for this event */
-        mask = DevicePointerMotionMask | b->state | b->motionMask;
-        SetMaskForEvent(device->id, mask, DeviceMotionNotify);
-        mask = PointerMotionMask | b->state | b->motionMask;
-        SetMaskForEvent(device->id, mask, MotionNotify);
+        UpdateDeviceMotionMask(device,  b->state, b->motionMask);
     } else if (event->type == ET_ProximityIn)
 	device->proximity->in_proximity = TRUE;
     else if (event->type == ET_ProximityOut)
commit 6eff14a789341d366b3013c5aa020e959c954651
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Dec 5 18:54:30 2011 +1000

    dix: deduplicate callers of DeliverDeviceEvents in DeliverGrabbedEvents
    
    No functional change.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 37039c6..6e015fe 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -4156,6 +4156,7 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
     if (grab->ownerEvents)
     {
 	WindowPtr focus;
+	WindowPtr win;
 
         /* Hack: Some pointer device have a focus class. So we need to check
          * for the type of event, to see if we really want to deliver it to
@@ -4172,15 +4173,16 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
 	else
 	    focus = PointerRootWin;
 	if (focus == PointerRootWin)
-	    deliveries = DeliverDeviceEvents(pSprite->win, event, grab,
-                                             NullWindow, thisDev);
-	else if (focus && (focus == pSprite->win ||
-                    IsParent(focus, pSprite->win)))
-	    deliveries = DeliverDeviceEvents(pSprite->win, event, grab, focus,
-					     thisDev);
+	{
+	    win = pSprite->win;
+	    focus = NullWindow;
+	} else if (focus && (focus == pSprite->win ||
+		    IsParent(focus, pSprite->win)))
+	    win = pSprite->win;
 	else if (focus)
-	    deliveries = DeliverDeviceEvents(focus, event, grab, focus,
-					     thisDev);
+	    win = focus;
+
+	deliveries = DeliverDeviceEvents(win, event, grab, focus, thisDev);
     }
     if (!deliveries)
     {
commit 93945b0a74aa8156a88f52b8ba77f1210042f396
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Dec 5 18:42:05 2011 +1000

    dix: split grab event conversion and delivery into a helper function
    
    Effective functional change: XI2 events are checked with XACE now.
    
    DeliverOneGrabbedEvent is exported for future use by touch events.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 705b079..37039c6 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -4061,6 +4061,75 @@ unwind:
     return;
 }
 
+
+int
+DeliverOneGrabbedEvent(InternalEvent *event, DeviceIntPtr dev, enum InputLevel level)
+{
+    SpritePtr pSprite = dev->spriteInfo->sprite;
+    int rc;
+    xEvent *xE = NULL;
+    int count = 0;
+    int deliveries = 0;
+    Mask mask;
+    GrabInfoPtr grabinfo = &dev->deviceGrab;
+    GrabPtr grab = grabinfo->grab;
+    Mask filter;
+
+    switch(level)
+    {
+        case XI2:
+            rc = EventToXI2(event, &xE);
+            count = 1;
+            if (rc == Success)
+            {
+                int evtype = xi2_get_type(xE);
+                mask = xi2mask_isset(grab->xi2mask, dev, evtype);
+                filter = 1;
+            }
+            break;
+        case XI:
+            if (grabinfo->fromPassiveGrab && grabinfo->implicitGrab)
+                mask = grab->deviceMask;
+            else
+                mask = grab->eventMask;
+            rc = EventToXI(event, &xE, &count);
+            if (rc == Success)
+                filter = GetEventFilter(dev, xE);
+            break;
+        case CORE:
+            rc = EventToCore(event, &xE, &count);
+            mask = grab->eventMask;
+            if (rc == Success)
+                filter = GetEventFilter(dev, xE);
+            break;
+        default:
+            BUG_WARN_MSG(1, "Invalid input level %d\n", level);
+            return 0;
+    }
+
+    if (rc == Success)
+    {
+        FixUpEventFromWindow(pSprite, xE, grab->window, None, TRUE);
+        if (XaceHook(XACE_SEND_ACCESS, 0, dev,
+                    grab->window, xE, count) ||
+                XaceHook(XACE_RECEIVE_ACCESS, rClient(grab),
+                    grab->window, xE, count))
+            deliveries = 1; /* don't send, but pretend we did */
+        else if (level != CORE || !IsInterferingGrab(rClient(grab), dev, xE))
+        {
+            deliveries = TryClientEvents(rClient(grab), dev,
+                    xE, count, mask, filter,
+                    grab);
+        }
+    } else
+        BUG_WARN_MSG(rc != BadMatch, "%s: conversion to mode %d failed on %d with %d\n",
+                dev->name, level, event->any.type, rc);
+
+    free(xE);
+    return deliveries;
+}
+
+
 /**
  * Deliver an event from a device that is currently grabbed. Uses
  * DeliverDeviceEvents() for further delivery if a ownerEvents is set on the
@@ -4080,10 +4149,6 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
     DeviceIntPtr dev;
     SpritePtr pSprite = thisDev->spriteInfo->sprite;
     BOOL sendCore = FALSE;
-    int rc, count = 0;
-    xEvent *xi = NULL;
-    xEvent *xi2 = NULL;
-    xEvent *core = NULL;
 
     grabinfo = &thisDev->deviceGrab;
     grab = grabinfo->grab;
@@ -4119,88 +4184,27 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
     }
     if (!deliveries)
     {
-        Mask mask;
-
         /* XXX: In theory, we could pass the internal events through to
          * everything and only convert just before hitting the wire. We can't
          * do that yet, so DGE is the last stop for internal events. From here
          * onwards, we deal with core/XI events.
          */
 
-        mask = grab->eventMask;
-
         sendCore = (IsMaster(thisDev) && thisDev->coreEvents);
         /* try core event */
         if (sendCore && grab->grabtype == GRABTYPE_CORE)
         {
-            rc = EventToCore(event, &core, &count);
-            if (rc == Success)
-            {
-                FixUpEventFromWindow(pSprite, core, grab->window, None, TRUE);
-                if (XaceHook(XACE_SEND_ACCESS, 0, thisDev,
-                            grab->window, core, count) ||
-                        XaceHook(XACE_RECEIVE_ACCESS, rClient(grab),
-                            grab->window, core, count))
-                    deliveries = 1; /* don't send, but pretend we did */
-                else if (!IsInterferingGrab(rClient(grab), thisDev, core))
-                {
-                    deliveries = TryClientEvents(rClient(grab), thisDev,
-                            core, count, mask,
-                            GetEventFilter(thisDev, core),
-                            grab);
-                }
-            } else
-                BUG_WARN_MSG(rc != BadMatch, "%s: Core conversion failed on %d with %d\n",
-                             thisDev->name, event->any.type, rc);
+            deliveries = DeliverOneGrabbedEvent(event, thisDev, CORE);
         }
 
         if (!deliveries)
         {
-            rc = EventToXI2(event, &xi2);
-            if (rc == Success)
-            {
-                int evtype = xi2_get_type(xi2);
-                mask = xi2mask_isset(grab->xi2mask, thisDev, evtype);
-                /* try XI2 event */
-                FixUpEventFromWindow(pSprite, xi2, grab->window, None, TRUE);
-                /* XXX: XACE */
-                deliveries = TryClientEvents(rClient(grab), thisDev, xi2, 1, mask, 1, grab);
-            } else
-                BUG_WARN_MSG(rc != BadMatch, "%s: XI2 conversion failed on %d with %d\n",
-                             thisDev->name, event->any.type, rc);
+            deliveries = DeliverOneGrabbedEvent(event, thisDev, XI2);
         }
 
         if (!deliveries)
         {
-            rc = EventToXI(event, &xi, &count);
-            if (rc == Success)
-            {
-                /* try XI event */
-                if (grabinfo->fromPassiveGrab  &&
-                        grabinfo->implicitGrab)
-                    mask = grab->deviceMask;
-                else
-                    mask = grab->eventMask;
-
-                FixUpEventFromWindow(pSprite, xi, grab->window, None, TRUE);
-
-                if (XaceHook(XACE_SEND_ACCESS, 0, thisDev,
-                            grab->window, xi, count) ||
-                        XaceHook(XACE_RECEIVE_ACCESS, rClient(grab),
-                            grab->window, xi, count))
-                    deliveries = 1; /* don't send, but pretend we did */
-                else
-                {
-                    deliveries =
-                        TryClientEvents(rClient(grab), thisDev,
-                                xi, count,
-                                mask,
-                                GetEventFilter(thisDev, xi),
-                                grab);
-                }
-            } else
-                BUG_WARN_MSG(rc != BadMatch, "%s: XI conversion failed on %d with %d\n",
-                             thisDev->name, event->any.type, rc);
+            deliveries = DeliverOneGrabbedEvent(event, thisDev, XI);
         }
 
         if (deliveries && (event->any.type == ET_Motion))
@@ -4233,10 +4237,6 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
 	}
     }
 
-    free(core);
-    free(xi);
-    free(xi2);
-
     return deliveries;
 }
 
diff --git a/include/dix.h b/include/dix.h
index cfbfa1f..9b9dc4b 100644
--- a/include/dix.h
+++ b/include/dix.h
@@ -400,6 +400,11 @@ extern int DeliverDeviceEvents(
     WindowPtr /* stopAt */,
     DeviceIntPtr /* dev */);
 
+extern int DeliverOneGrabbedEvent(
+    InternalEvent* /* event*/,
+    DeviceIntPtr /* dev */,
+    enum InputLevel /* level */);
+
 extern void InitializeSprite(
     DeviceIntPtr /* pDev */,
     WindowPtr    /* pWin */);
commit c81cdb0862e2184f033b3933e6bacbe0809ef2c0
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Dec 5 18:29:27 2011 +1000

    dix: replace conversion errors with BUG_WARN_MSG
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index ced29f7..705b079 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -4149,8 +4149,9 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
                             GetEventFilter(thisDev, core),
                             grab);
                 }
-            } else if (rc != BadMatch)
-                ErrorF("[dix] DeliverGrabbedEvent. Core conversion failed.\n");
+            } else
+                BUG_WARN_MSG(rc != BadMatch, "%s: Core conversion failed on %d with %d\n",
+                             thisDev->name, event->any.type, rc);
         }
 
         if (!deliveries)
@@ -4164,9 +4165,9 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
                 FixUpEventFromWindow(pSprite, xi2, grab->window, None, TRUE);
                 /* XXX: XACE */
                 deliveries = TryClientEvents(rClient(grab), thisDev, xi2, 1, mask, 1, grab);
-            } else if (rc != BadMatch)
-                ErrorF("[dix] %s: XI2 conversion failed in DGE (%d, %d). Skipping delivery.\n",
-                        thisDev->name, event->any.type, rc);
+            } else
+                BUG_WARN_MSG(rc != BadMatch, "%s: XI2 conversion failed on %d with %d\n",
+                             thisDev->name, event->any.type, rc);
         }
 
         if (!deliveries)
@@ -4197,9 +4198,9 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
                                 GetEventFilter(thisDev, xi),
                                 grab);
                 }
-            } else if (rc != BadMatch)
-                ErrorF("[dix] %s: XI conversion failed in DGE (%d, %d). Skipping delivery.\n",
-                        thisDev->name, event->any.type, rc);
+            } else
+                BUG_WARN_MSG(rc != BadMatch, "%s: XI conversion failed on %d with %d\n",
+                             thisDev->name, event->any.type, rc);
         }
 
         if (deliveries && (event->any.type == ET_Motion))
commit 6368c2aa4613a7c7eb0e8afca8d41f1a9bc4fc4d
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Dec 5 16:46:18 2011 +1000

    dix: deduplicate event delivery code
    
    Move all the event delivery code into DeliverOneEvent, based on the
    InputLevel we're sending to.
    
    Functional change: we now check XI2 events with XACE too.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 49f70c3..ced29f7 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -2592,6 +2592,57 @@ EventIsDeliverable(DeviceIntPtr dev, InternalEvent* event, WindowPtr win)
     return rc;
 }
 
+static int
+DeliverEvent(DeviceIntPtr dev, xEvent *xE, int count,
+             WindowPtr win, Window child, GrabPtr grab)
+{
+    SpritePtr pSprite = dev->spriteInfo->sprite;
+    Mask filter;
+    int deliveries = 0;
+
+    if (XaceHook(XACE_SEND_ACCESS, NULL, dev, win, xE, count) == Success) {
+        filter = GetEventFilter(dev, xE);
+        FixUpEventFromWindow(pSprite, xE, win, child, FALSE);
+        deliveries = DeliverEventsToWindow(dev, win, xE, count,
+                filter, grab);
+    }
+
+    return deliveries;
+}
+
+static int
+DeliverOneEvent(InternalEvent *event, DeviceIntPtr dev, enum InputLevel level,
+                WindowPtr win, Window child, GrabPtr grab)
+{
+    xEvent *xE = NULL;
+    int count = 0;
+    int deliveries = 0;
+    int rc;
+
+    switch(level)
+    {
+        case XI2:
+            rc = EventToXI2(event, &xE);
+            count = 1;
+            break;
+        case XI:
+            rc = EventToXI(event, &xE, &count);
+            break;
+        case CORE:
+            rc = EventToCore(event, &xE, &count);
+            break;
+    }
+
+    if (rc == Success)
+    {
+        deliveries = DeliverEvent(dev, xE, count, win, child, grab);
+        free(xE);
+    } else
+        BUG_WARN_MSG(rc != BadMatch, "%s: conversion to level %d failed with rc %d\n",
+                     dev->name, level, rc);
+    return deliveries;
+}
+
 /**
  * Deliver events caused by input devices.
  *
@@ -2615,12 +2666,9 @@ int
 DeliverDeviceEvents(WindowPtr pWin, InternalEvent *event, GrabPtr grab,
                     WindowPtr stopAt, DeviceIntPtr dev)
 {
-    SpritePtr pSprite = dev->spriteInfo->sprite;
     Window child = None;
-    Mask filter;
     int deliveries = 0;
-    xEvent *xE = NULL, *core = NULL;
-    int rc, mask, count = 0;
+    int mask;
 
     verify_internal_event(event);
 
@@ -2631,64 +2679,32 @@ DeliverDeviceEvents(WindowPtr pWin, InternalEvent *event, GrabPtr grab,
             /* XI2 events first */
             if (mask & EVENT_XI2_MASK)
             {
-                xEvent *xi2 = NULL;
-                rc = EventToXI2(event, &xi2);
-                if (rc == Success)
-                {
-                    /* XXX: XACE */
-                    filter = GetEventFilter(dev, xi2);
-                    FixUpEventFromWindow(pSprite, xi2, pWin, child, FALSE);
-                    deliveries = DeliverEventsToWindow(dev, pWin, xi2, 1,
-                                                       filter, grab);
-                    free(xi2);
-                    if (deliveries > 0)
-                        goto unwind;
-                } else if (rc != BadMatch)
-                    ErrorF("[dix] %s: XI2 conversion failed in DDE (%d).\n",
-                            dev->name, rc);
+                deliveries = DeliverOneEvent(event, dev, XI2, pWin, child, grab);
+                if (deliveries > 0)
+                    break;
             }
 
             /* XI events */
             if (mask & EVENT_XI1_MASK)
             {
-                rc = EventToXI(event, &xE, &count);
-                if (rc == Success) {
-                    if (XaceHook(XACE_SEND_ACCESS, NULL, dev, pWin, xE, count) == Success) {
-                        filter = GetEventFilter(dev, xE);
-                        FixUpEventFromWindow(pSprite, xE, pWin, child, FALSE);
-                        deliveries = DeliverEventsToWindow(dev, pWin, xE, count,
-                                                           filter, grab);
-                        if (deliveries > 0)
-                            goto unwind;
-                    }
-                } else if (rc != BadMatch)
-                    ErrorF("[dix] %s: XI conversion failed in DDE (%d, %d). Skipping delivery.\n",
-                            dev->name, event->any.type, rc);
+                deliveries = DeliverOneEvent(event, dev, XI, pWin, child, grab);
+                if (deliveries > 0)
+                    break;
             }
 
             /* Core event */
             if ((mask & EVENT_CORE_MASK) && IsMaster(dev) && dev->coreEvents)
             {
-                rc = EventToCore(event, &core, &count);
-                if (rc == Success) {
-                    if (XaceHook(XACE_SEND_ACCESS, NULL, dev, pWin, core, count) == Success) {
-                        filter = GetEventFilter(dev, core);
-                        FixUpEventFromWindow(pSprite, core, pWin, child, FALSE);
-                        deliveries = DeliverEventsToWindow(dev, pWin, core,
-                                                           count, filter, grab);
-                        if (deliveries > 0)
-                            goto unwind;
-                    }
-                } else if (rc != BadMatch)
-                        ErrorF("[dix] %s: Core conversion failed in DDE (%d, %d).\n",
-                                dev->name, event->any.type, rc);
+                deliveries = DeliverOneEvent(event, dev, CORE, pWin, child, grab);
+                if (deliveries > 0)
+                    break;
             }
 
             if ((deliveries < 0) || (pWin == stopAt) ||
                 (mask & EVENT_DONT_PROPAGATE_MASK))
             {
                 deliveries = 0;
-                goto unwind;
+                break;
             }
         }
 
@@ -2696,9 +2712,6 @@ DeliverDeviceEvents(WindowPtr pWin, InternalEvent *event, GrabPtr grab,
         pWin = pWin->parent;
     }
 
-unwind:
-    free(core);
-    free(xE);
     return deliveries;
 }
 
commit 7e2207548b3173afc9accb5ccd532c181a7b94ed
Author: Chase Douglas <chase.douglas at canonical.com>
Date:   Wed Dec 7 20:32:28 2011 +1000

    include: Add an InputLevel enum
    
    Currently unused, but will be in the future.
    
    Signed-off-by: Chase Douglas <chase.douglas at canonical.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/include/eventconvert.h b/include/eventconvert.h
index 571a511..bb45eef 100644
--- a/include/eventconvert.h
+++ b/include/eventconvert.h
@@ -31,6 +31,12 @@
 
 #define FP1616(integral, frac) ((integral) * (1 << 16) + (frac) * (1 << 16))
 
+enum InputLevel {
+    CORE,
+    XI,
+    XI2,
+};
+
 _X_EXPORT int EventToCore(InternalEvent *event, xEvent **core, int *count);
 _X_EXPORT int EventToXI(InternalEvent *ev, xEvent **xi, int *count);
 _X_EXPORT int EventToXI2(InternalEvent *ev, xEvent **xi);
commit 898d97672907a8074031d0d1038cd44bb5caf40d
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    verify_internal_event: preserve constness of data pointer
    
    All we're using it for is ErrorF calls, so make it a const char *
    to stop gcc from warning:
    
    inpututils.c: In function 'verify_internal_event':
    inpututils.c:629:9: warning: cast discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/inpututils.c b/dix/inpututils.c
index 60f9fa0..5e2ab87 100644
--- a/dix/inpututils.c
+++ b/dix/inpututils.c
@@ -626,7 +626,7 @@ void verify_internal_event(const InternalEvent *ev)
     if (ev && ev->any.header != ET_Internal)
     {
         int i;
-        unsigned char *data = (unsigned char*)ev;
+        const unsigned char *data = (const unsigned char*)ev;
 
         ErrorF("dix: invalid event type %d\n", ev->any.header);
 
commit 79d09647d878e66721a778979a9eb1f4bba5f8d6
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    Use const cast in BitIsOn macro to avoid angering gcc
    
    Fixes gcc warnings such as:
    inpututils.c: In function 'valuator_mask_isset':
    inpututils.c:498:5: warning: cast discards qualifiers from pointer target type
    inpututils.c: In function 'CountBits':
    inpututils.c:613:9: warning: cast discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/include/inputstr.h b/include/inputstr.h
index 5634f3c..6af7264 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -57,7 +57,7 @@ SOFTWARE.
 #include "geext.h"
 #include "privates.h"
 
-#define BitIsOn(ptr, bit) (!!(((BYTE *) (ptr))[(bit)>>3] & (1 << ((bit) & 7))))
+#define BitIsOn(ptr, bit) (!!(((const BYTE *) (ptr))[(bit)>>3] & (1 << ((bit) & 7))))
 #define SetBit(ptr, bit)  (((BYTE *) (ptr))[(bit)>>3] |= (1 << ((bit) & 7)))
 #define ClearBit(ptr, bit) (((BYTE *)(ptr))[(bit)>>3] &= ~(1 << ((bit) & 7)))
 extern _X_EXPORT int CountBits(const uint8_t *mask, int len);
commit 99dfe9b1de09cb481e95bd4c45dcf7493480798b
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:32 2011 -0800

    Fix deconstifying cast warning in xi2_get_type
    
    Since we're just comparing values in the struct, cast it to a
    const xGenericEvent * to clear gcc warning of:
    
    events.c: In function 'xi2_get_type':
    events.c:193:5: warning: cast discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/events.c b/dix/events.c
index 59caa91..5c0f9dd 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -190,7 +190,7 @@ core_get_type(const xEvent *event)
 static inline int
 xi2_get_type(const xEvent *event)
 {
-    xGenericEvent* e = (xGenericEvent*)event;
+    const xGenericEvent* e = (const xGenericEvent*)event;
 
     return (e->type != GenericEvent || e->extension != IReqCode) ? 0 : e->evtype;
 }
commit dd80156bf05c9eb4000d0981e00d0d9fb69a94f6
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Wed Dec 7 22:58:45 2011 -0800

    Include client name if available in PrintDeviceGrabInfo
    
    Also adds missing newline to first line of output.
    
    Before patch:
    
    [3581472.414] (II) Printing all currently active device grabs:
    [3581472.414] Active grab 0x1800000 (core) on device 'Virtual core pointer' (2):
          client pid 26174 uid 0 gid 10
    [3581472.415]       at 3581469139 (from active grab) (device thawed, state 1)
    [3581472.415]         core event mask 0x0
    [3581472.415]       owner-events true, kb 1 ptr 1, confine 0, cursor 0x0
    [3581472.415] Active grab 0x1800000 (core) on device 'Virtual core keyboard' (3)
    :      client pid 26174 uid 0 gid 10
    [3581472.415]       at 3581469139 (from active grab) (device thawed, state 1)
    [3581472.415]         core event mask 0x3
    [3581472.415]       owner-events true, kb 1 ptr 1, confine 0, cursor 0x0
    [3581472.415] (II) End list of active device grabs
    
    After patch:
    [3581736.601] (II) Printing all currently active device grabs:
    [3581736.601] Active grab 0x1600000 (core) on device 'Virtual core pointer' (2):
    [3581736.601]       client pid 26741 /usr/bin/xscreensaver -nosplash
    [3581736.601]       at 3581735000 (from active grab) (device thawed, state 1)
    [3581736.601]         core event mask 0x0
    [3581736.601]       owner-events true, kb 1 ptr 1, confine 0, cursor 0x0
    [3581736.601] Active grab 0x1600000 (core) on device 'Virtual core keyboard' (3)
    :
    [3581736.601]       client pid 26741 /usr/bin/xscreensaver -nosplash
    [3581736.601]       at 3581735000 (from active grab) (device thawed, state 1)
    [3581736.601]         core event mask 0x3
    [3581736.601]       owner-events true, kb 1 ptr 1, confine 0, cursor 0x0
    [3581736.601] (II) End list of active device grabs
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Rami Ylimäki <rami.ylimaki at vincit.fi>

diff --git a/dix/grabs.c b/dix/grabs.c
index aced130..3286eb7 100644
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@ -61,6 +61,7 @@ SOFTWARE.
 #include "xace.h"
 #include "exevents.h"
 #include "inpututils.h"
+#include "client.h"
 
 #define BITMASK(i) (((Mask)1) << ((i) & 31))
 #define MASKIDX(i) ((i) >> 5)
@@ -77,25 +78,41 @@ PrintDeviceGrabInfo(DeviceIntPtr dev)
     int i, j;
     GrabInfoPtr devGrab = &dev->deviceGrab;
     GrabPtr grab = devGrab->grab;
+    Bool clientIdPrinted = FALSE;
 
-    ErrorF("Active grab 0x%lx (%s) on device '%s' (%d):",
+    ErrorF("Active grab 0x%lx (%s) on device '%s' (%d):\n",
            (unsigned long) grab->resource,
            (grab->grabtype == GRABTYPE_XI2) ? "xi2" :
             ((grab->grabtype == GRABTYPE_CORE) ? "core" : "xi1"),
            dev->name, dev->id);
 
     client = clients[CLIENT_ID(grab->resource)];
-    if (client && GetLocalClientCreds(client, &lcc) != -1)
+    if (client)
     {
-        ErrorF("      client pid %ld uid %ld gid %ld\n",
-               (lcc->fieldsSet & LCC_PID_SET) ? (long) lcc->pid : 0,
-               (lcc->fieldsSet & LCC_UID_SET) ? (long) lcc->euid : 0,
-               (lcc->fieldsSet & LCC_GID_SET) ? (long) lcc->egid : 0);
-        FreeLocalClientCreds(lcc);
+        pid_t clientpid = GetClientPid(client);
+        const char *cmdname = GetClientCmdName(client);
+        const char *cmdargs = GetClientCmdArgs(client);
+
+        if ((clientpid > 0) && (cmdname != NULL))
+        {
+            ErrorF("      client pid %ld %s %s\n",
+                   (long) clientpid, cmdname, cmdargs ? cmdargs : "");
+            clientIdPrinted = TRUE;
+        }
+        else if (GetLocalClientCreds(client, &lcc) != -1)
+        {
+            ErrorF("      client pid %ld uid %ld gid %ld\n",
+                   (lcc->fieldsSet & LCC_PID_SET) ? (long) lcc->pid : 0,
+                   (lcc->fieldsSet & LCC_UID_SET) ? (long) lcc->euid : 0,
+                   (lcc->fieldsSet & LCC_GID_SET) ? (long) lcc->egid : 0);
+            FreeLocalClientCreds(lcc);
+            clientIdPrinted = TRUE;
+        }
     }
-    else
+    if (!clientIdPrinted)
     {
-        ErrorF("      (no client information available)\n");
+        ErrorF("      (no client information available for client %d)\n",
+               CLIENT_ID(grab->resource));
     }
 
     /* XXX is this even correct? */
commit b79de3f42ff8412dcabf2f2a805cbcbd1c6907c3
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:35 2011 -0800

    xf86 parser: convert Error to a varargs macro to clear gcc format warnings
    
    Previously it always passed a format string with exactly one argument,
    using NULL when the format string needed none.   Now pass the right number
    of arguments to clear gcc warnings of 'too many arguments for format'.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/parser/Configint.h b/hw/xfree86/parser/Configint.h
index 82d7de4..3f84ff0 100644
--- a/hw/xfree86/parser/Configint.h
+++ b/hw/xfree86/parser/Configint.h
@@ -119,8 +119,8 @@ else\
 }\
 }
 
-#define Error(a,b) do { \
-			xf86parseError (a, b); CLEANUP (ptr); return NULL; \
+#define Error(...) do { \
+		xf86parseError (__VA_ARGS__); CLEANUP (ptr); return NULL; \
 		   } while (0)
 
 /* 
diff --git a/hw/xfree86/parser/DRI.c b/hw/xfree86/parser/DRI.c
index f51f6b9..77846da 100644
--- a/hw/xfree86/parser/DRI.c
+++ b/hw/xfree86/parser/DRI.c
@@ -64,7 +64,7 @@ xf86parseDRISection (void)
 		else if (token == NUMBER)
 		    ptr->dri_group = val.num;
 		else
-		    Error (GROUP_MSG, NULL);
+		    Error (GROUP_MSG);
 		break;
 	    case MODE:
 		if (xf86getSubToken (&(ptr->dri_comment)) != NUMBER)
@@ -74,7 +74,7 @@ xf86parseDRISection (void)
 		ptr->dri_mode = val.num;
 		break;
 	    case EOF_TOKEN:
-		Error (UNEXPECTED_EOF_MSG, NULL);
+		Error (UNEXPECTED_EOF_MSG);
 		break;
 	    case COMMENT:
 		ptr->dri_comment = xf86addComment(ptr->dri_comment, val.str);
diff --git a/hw/xfree86/parser/Device.c b/hw/xfree86/parser/Device.c
index d71abc6..d99dbf7 100644
--- a/hw/xfree86/parser/Device.c
+++ b/hw/xfree86/parser/Device.c
@@ -245,7 +245,7 @@ xf86parseDeviceSection (void)
 			ptr->dev_screen = val.num;
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -254,7 +254,7 @@ xf86parseDeviceSection (void)
 	}
 
 	if (!has_ident)
-		Error (NO_IDENT_MSG, NULL);
+		Error (NO_IDENT_MSG);
 
 #ifdef DEBUG
 	printf ("Device section parsed\n");
diff --git a/hw/xfree86/parser/Extensions.c b/hw/xfree86/parser/Extensions.c
index 4003b52..662f526 100644
--- a/hw/xfree86/parser/Extensions.c
+++ b/hw/xfree86/parser/Extensions.c
@@ -62,7 +62,7 @@ xf86parseExtensionsSection (void)
 		ptr->ext_option_lst = xf86parseOption(ptr->ext_option_lst);
 		break;
 	    case EOF_TOKEN:
-		Error (UNEXPECTED_EOF_MSG, NULL);
+		Error (UNEXPECTED_EOF_MSG);
 		break;
 	    case COMMENT:
 		ptr->extensions_comment =
diff --git a/hw/xfree86/parser/Files.c b/hw/xfree86/parser/Files.c
index 0c71835..a95be9e 100644
--- a/hw/xfree86/parser/Files.c
+++ b/hw/xfree86/parser/Files.c
@@ -162,7 +162,7 @@ xf86parseFilesSection (void)
 			ptr->file_xkbdir = val.str;
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		case OBSOLETE_TOKEN:
 			xf86parseError (OBSOLETE_MSG, xf86tokenString ());
diff --git a/hw/xfree86/parser/Flags.c b/hw/xfree86/parser/Flags.c
index 87fd3ed..c2a0406 100644
--- a/hw/xfree86/parser/Flags.c
+++ b/hw/xfree86/parser/Flags.c
@@ -160,7 +160,7 @@ xf86parseFlagsSection (void)
 			break;
 
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -440,7 +440,7 @@ xf86parseOption(XF86OptionPtr head)
 	int token;
 
 	if ((token = xf86getSubToken(&comment)) != STRING) {
-		xf86parseError(BAD_OPTION_MSG, NULL);
+		xf86parseError(BAD_OPTION_MSG);
 		free(comment);
 		return head;
 	}
diff --git a/hw/xfree86/parser/Input.c b/hw/xfree86/parser/Input.c
index faff0f4..e603773 100644
--- a/hw/xfree86/parser/Input.c
+++ b/hw/xfree86/parser/Input.c
@@ -114,7 +114,7 @@ xf86parseInputSection (void)
 			ptr->inp_option_lst = xf86parseOption(ptr->inp_option_lst);
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -123,7 +123,7 @@ xf86parseInputSection (void)
 	}
 
 	if (!has_ident)
-		Error (NO_IDENT_MSG, NULL);
+		Error (NO_IDENT_MSG);
 
 #ifdef DEBUG
 	printf ("InputDevice section parsed\n");
diff --git a/hw/xfree86/parser/InputClass.c b/hw/xfree86/parser/InputClass.c
index 2cdc912..919ae18 100644
--- a/hw/xfree86/parser/InputClass.c
+++ b/hw/xfree86/parser/InputClass.c
@@ -241,7 +241,7 @@ xf86parseInputClassSection(void)
                 Error(BOOL_MSG, "MatchIsTouchscreen");
             break;
         case EOF_TOKEN:
-            Error(UNEXPECTED_EOF_MSG, NULL);
+            Error(UNEXPECTED_EOF_MSG);
             break;
         default:
             Error(INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -250,7 +250,7 @@ xf86parseInputClassSection(void)
     }
 
     if (!has_ident)
-        Error(NO_IDENT_MSG, NULL);
+        Error(NO_IDENT_MSG);
 
 #ifdef DEBUG
     printf("InputClass section parsed\n");
diff --git a/hw/xfree86/parser/Layout.c b/hw/xfree86/parser/Layout.c
index 4487b0d..7dd4ebf 100644
--- a/hw/xfree86/parser/Layout.c
+++ b/hw/xfree86/parser/Layout.c
@@ -124,7 +124,7 @@ xf86parseLayoutSection (void)
 				iptr->list.next = NULL;
 				if (xf86getSubToken (&(ptr->lay_comment)) != STRING) {
 					free (iptr);
-					Error (INACTIVE_MSG, NULL);
+					Error (INACTIVE_MSG);
 				}
 				iptr->inactive_device_str = val.str;
 				ptr->lay_inactive_lst = (XF86ConfInactivePtr)
@@ -150,7 +150,7 @@ xf86parseLayoutSection (void)
 				token = xf86getSubToken(&(ptr->lay_comment));
 				if (token != STRING) {
 					free(aptr);
-					Error (SCREEN_MSG, NULL);
+					Error (SCREEN_MSG);
 				}
 				aptr->adj_screen_str = val.str;
 
@@ -178,7 +178,7 @@ xf86parseLayoutSection (void)
 					break;
 				case EOF_TOKEN:
 					free(aptr);
-					Error (UNEXPECTED_EOF_MSG, NULL);
+					Error (UNEXPECTED_EOF_MSG);
 					break;
 				default:
 					xf86unGetToken (token);
@@ -199,13 +199,13 @@ xf86parseLayoutSection (void)
 						token = xf86getSubToken(&(ptr->lay_comment));
 						if (token != NUMBER) {
 							free(aptr);
-							Error(INVALID_SCR_MSG, NULL);
+							Error(INVALID_SCR_MSG);
 						}
 						aptr->adj_y = val.num;
 					} else {
 						if (absKeyword) {
 							free(aptr);
-							Error(INVALID_SCR_MSG, NULL);
+							Error(INVALID_SCR_MSG);
 						} else
 							xf86unGetToken (token);
 					}
@@ -218,7 +218,7 @@ xf86parseLayoutSection (void)
 					token = xf86getSubToken(&(ptr->lay_comment));
 					if (token != STRING) {
 						free(aptr);
-						Error(INVALID_SCR_MSG, NULL);
+						Error(INVALID_SCR_MSG);
 					}
 					aptr->adj_refscreen = val.str;
 					if (aptr->adj_where == CONF_ADJ_RELATIVE)
@@ -226,13 +226,13 @@ xf86parseLayoutSection (void)
 						token = xf86getSubToken(&(ptr->lay_comment));
 						if (token != NUMBER) {
 							free(aptr);
-							Error(INVALID_SCR_MSG, NULL);
+							Error(INVALID_SCR_MSG);
 						}
 						aptr->adj_x = val.num;
 						token = xf86getSubToken(&(ptr->lay_comment));
 						if (token != NUMBER) {
 							free(aptr);
-							Error(INVALID_SCR_MSG, NULL);
+							Error(INVALID_SCR_MSG);
 						}
 						aptr->adj_y = val.num;
 					}
@@ -244,21 +244,21 @@ xf86parseLayoutSection (void)
 					/* bottom */
 					if (xf86getSubToken (&(ptr->lay_comment)) != STRING) {
 						free(aptr);
-						Error (SCREEN_MSG, NULL);
+						Error (SCREEN_MSG);
 					}
 					aptr->adj_bottom_str = val.str;
 
 					/* left */
 					if (xf86getSubToken (&(ptr->lay_comment)) != STRING) {
 						free(aptr);
-						Error (SCREEN_MSG, NULL);
+						Error (SCREEN_MSG);
 					}
 					aptr->adj_left_str = val.str;
 
 					/* right */
 					if (xf86getSubToken (&(ptr->lay_comment)) != STRING) {
 						free(aptr);
-						Error (SCREEN_MSG, NULL);
+						Error (SCREEN_MSG);
 					}
 					aptr->adj_right_str = val.str;
 
@@ -276,7 +276,7 @@ xf86parseLayoutSection (void)
 				iptr->iref_option_lst = NULL;
 				if (xf86getSubToken (&(ptr->lay_comment)) != STRING) {
 					free(iptr);
-					Error (INPUTDEV_MSG, NULL);
+					Error (INPUTDEV_MSG);
 				}
 				iptr->iref_inputdev_str = val.str;
 				while ((token = xf86getSubToken (&(ptr->lay_comment))) == STRING)
@@ -293,7 +293,7 @@ xf86parseLayoutSection (void)
 			ptr->lay_option_lst = xf86parseOption(ptr->lay_option_lst);
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -302,7 +302,7 @@ xf86parseLayoutSection (void)
 	}
 
 	if (!has_ident)
-		Error (NO_IDENT_MSG, NULL);
+		Error (NO_IDENT_MSG);
 
 #ifdef DEBUG
 	printf ("Layout section parsed\n");
diff --git a/hw/xfree86/parser/Module.c b/hw/xfree86/parser/Module.c
index ca323fc..3c4cefc 100644
--- a/hw/xfree86/parser/Module.c
+++ b/hw/xfree86/parser/Module.c
@@ -107,7 +107,7 @@ xf86parseModuleSubSection (XF86LoadPtr head, char *name)
 			ptr->load_opt = xf86parseOption(ptr->load_opt);
 			break;
 		case EOF_TOKEN:
-			xf86parseError (UNEXPECTED_EOF_MSG, NULL);
+			xf86parseError (UNEXPECTED_EOF_MSG);
 			free(ptr);
 			return NULL;
 		default:
@@ -163,7 +163,7 @@ xf86parseModuleSection (void)
 				xf86parseModuleSubSection (ptr->mod_load_lst, val.str);
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
diff --git a/hw/xfree86/parser/Monitor.c b/hw/xfree86/parser/Monitor.c
index 970406d..52c5500 100644
--- a/hw/xfree86/parser/Monitor.c
+++ b/hw/xfree86/parser/Monitor.c
@@ -145,52 +145,52 @@ xf86parseModeLine (void)
 
 	/* Identifier */
 	if (xf86getSubToken (&(ptr->ml_comment)) != STRING)
-		Error ("ModeLine identifier expected", NULL);
+		Error ("ModeLine identifier expected");
 	ptr->ml_identifier = val.str;
 
 	/* DotClock */
 	if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-		Error ("ModeLine dotclock expected", NULL);
+		Error ("ModeLine dotclock expected");
 	ptr->ml_clock = (int) (val.realnum * 1000.0 + 0.5);
 
 	/* HDisplay */
 	if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-		Error ("ModeLine Hdisplay expected", NULL);
+		Error ("ModeLine Hdisplay expected");
 	ptr->ml_hdisplay = val.num;
 
 	/* HSyncStart */
 	if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-		Error ("ModeLine HSyncStart expected", NULL);
+		Error ("ModeLine HSyncStart expected");
 	ptr->ml_hsyncstart = val.num;
 
 	/* HSyncEnd */
 	if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-		Error ("ModeLine HSyncEnd expected", NULL);
+		Error ("ModeLine HSyncEnd expected");
 	ptr->ml_hsyncend = val.num;
 
 	/* HTotal */
 	if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-		Error ("ModeLine HTotal expected", NULL);
+		Error ("ModeLine HTotal expected");
 	ptr->ml_htotal = val.num;
 
 	/* VDisplay */
 	if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-		Error ("ModeLine Vdisplay expected", NULL);
+		Error ("ModeLine Vdisplay expected");
 	ptr->ml_vdisplay = val.num;
 
 	/* VSyncStart */
 	if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-		Error ("ModeLine VSyncStart expected", NULL);
+		Error ("ModeLine VSyncStart expected");
 	ptr->ml_vsyncstart = val.num;
 
 	/* VSyncEnd */
 	if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-		Error ("ModeLine VSyncEnd expected", NULL);
+		Error ("ModeLine VSyncEnd expected");
 	ptr->ml_vsyncend = val.num;
 
 	/* VTotal */
 	if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-		Error ("ModeLine VTotal expected", NULL);
+		Error ("ModeLine VTotal expected");
 	ptr->ml_vtotal = val.num;
 
 	token = xf86getSubTokenWithTab (&(ptr->ml_comment), TimingTab);
@@ -247,7 +247,7 @@ xf86parseModeLine (void)
 			ptr->ml_flags |= XF86CONF_VSCAN;
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -271,7 +271,7 @@ xf86parseVerboseMode (void)
 	parsePrologue (XF86ConfModeLinePtr, XF86ConfModeLineRec)
 
 		if (xf86getSubToken (&(ptr->ml_comment)) != STRING)
-		Error ("Mode name expected", NULL);
+		Error ("Mode name expected");
 	ptr->ml_identifier = val.str;
 	while ((token = xf86getToken (ModeTab)) != ENDMODE)
 	{
@@ -290,44 +290,44 @@ xf86parseVerboseMode (void)
 			if (xf86getSubToken (&(ptr->ml_comment)) == NUMBER)
 				ptr->ml_hdisplay = val.num;
 			else
-				Error ("Horizontal display expected", NULL);
+				Error ("Horizontal display expected");
 
 			if (xf86getSubToken (&(ptr->ml_comment)) == NUMBER)
 				ptr->ml_hsyncstart = val.num;
 			else
-				Error ("Horizontal sync start expected", NULL);
+				Error ("Horizontal sync start expected");
 
 			if (xf86getSubToken (&(ptr->ml_comment)) == NUMBER)
 				ptr->ml_hsyncend = val.num;
 			else
-				Error ("Horizontal sync end expected", NULL);
+				Error ("Horizontal sync end expected");
 
 			if (xf86getSubToken (&(ptr->ml_comment)) == NUMBER)
 				ptr->ml_htotal = val.num;
 			else
-				Error ("Horizontal total expected", NULL);
+				Error ("Horizontal total expected");
 			had_htimings = 1;
 			break;
 		case VTIMINGS:
 			if (xf86getSubToken (&(ptr->ml_comment)) == NUMBER)
 				ptr->ml_vdisplay = val.num;
 			else
-				Error ("Vertical display expected", NULL);
+				Error ("Vertical display expected");
 
 			if (xf86getSubToken (&(ptr->ml_comment)) == NUMBER)
 				ptr->ml_vsyncstart = val.num;
 			else
-				Error ("Vertical sync start expected", NULL);
+				Error ("Vertical sync start expected");
 
 			if (xf86getSubToken (&(ptr->ml_comment)) == NUMBER)
 				ptr->ml_vsyncend = val.num;
 			else
-				Error ("Vertical sync end expected", NULL);
+				Error ("Vertical sync end expected");
 
 			if (xf86getSubToken (&(ptr->ml_comment)) == NUMBER)
 				ptr->ml_vtotal = val.num;
 			else
-				Error ("Vertical total expected", NULL);
+				Error ("Vertical total expected");
 			had_vtimings = 1;
 			break;
 		case FLAGS:
@@ -367,10 +367,10 @@ xf86parseVerboseMode (void)
 					ptr->ml_flags |= XF86CONF_DBLSCAN;
 					break;
 				case EOF_TOKEN:
-					Error (UNEXPECTED_EOF_MSG, NULL);
+					Error (UNEXPECTED_EOF_MSG);
 					break;
 				default:
-					Error ("Unknown flag string", NULL);
+					Error ("Unknown flag string");
 					break;
 				}
 				token = xf86getSubToken (&(ptr->ml_comment));
@@ -379,29 +379,29 @@ xf86parseVerboseMode (void)
 			break;
 		case HSKEW:
 			if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-				Error ("Horizontal skew expected", NULL);
+				Error ("Horizontal skew expected");
 			ptr->ml_flags |= XF86CONF_HSKEW;
 			ptr->ml_hskew = val.num;
 			break;
 		case VSCAN:
 			if (xf86getSubToken (&(ptr->ml_comment)) != NUMBER)
-				Error ("Vertical scan count expected", NULL);
+				Error ("Vertical scan count expected");
 			ptr->ml_flags |= XF86CONF_VSCAN;
 			ptr->ml_vscan = val.num;
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
-			Error ("Unexepcted token in verbose \"Mode\" entry\n", NULL);
+			Error ("Unexepcted token in verbose \"Mode\" entry\n");
 		}
 	}
 	if (!had_dotclock)
-		Error ("the dotclock is missing", NULL);
+		Error ("the dotclock is missing");
 	if (!had_htimings)
-		Error ("the horizontal timings are missing", NULL);
+		Error ("the horizontal timings are missing");
 	if (!had_vtimings)
-		Error ("the vertical timings are missing", NULL);
+		Error ("the vertical timings are missing");
 
 #ifdef DEBUG
 	printf ("Verbose Mode parsed\n");
@@ -455,19 +455,19 @@ xf86parseMonitorSection (void)
 			break;
 		case DISPLAYSIZE:
 			if (xf86getSubToken (&(ptr->mon_comment)) != NUMBER)
-				Error (DISPLAYSIZE_MSG, NULL);
+				Error (DISPLAYSIZE_MSG);
 			ptr->mon_width = val.realnum;
 			if (xf86getSubToken (&(ptr->mon_comment)) != NUMBER)
-				Error (DISPLAYSIZE_MSG, NULL);
+				Error (DISPLAYSIZE_MSG);
 			ptr->mon_height = val.realnum;
 			break;
 
 		case HORIZSYNC:
 			if (xf86getSubToken (&(ptr->mon_comment)) != NUMBER)
-				Error (HORIZSYNC_MSG, NULL);
+				Error (HORIZSYNC_MSG);
 			do {
 				if (ptr->mon_n_hsync >= CONF_MAX_HSYNC)
-					Error ("Sorry. Too many horizontal sync intervals.", NULL);
+					Error ("Sorry. Too many horizontal sync intervals.");
 				ptr->mon_hsync[ptr->mon_n_hsync].lo = val.realnum;
 				switch (token = xf86getSubToken (&(ptr->mon_comment)))
 				{
@@ -478,7 +478,7 @@ xf86parseMonitorSection (void)
 					case DASH:
 						if (xf86getSubToken (&(ptr->mon_comment)) != NUMBER ||
 						    (float)val.realnum < ptr->mon_hsync[ptr->mon_n_hsync].lo)
-							Error (HORIZSYNC_MSG, NULL);
+							Error (HORIZSYNC_MSG);
 						ptr->mon_hsync[ptr->mon_n_hsync].hi = val.realnum;
 						if ((token = xf86getSubToken (&(ptr->mon_comment))) == COMMA)
 							break;
@@ -501,7 +501,7 @@ HorizDone:
 
 		case VERTREFRESH:
 			if (xf86getSubToken (&(ptr->mon_comment)) != NUMBER)
-				Error (VERTREFRESH_MSG, NULL);
+				Error (VERTREFRESH_MSG);
 			do {
 				ptr->mon_vrefresh[ptr->mon_n_vrefresh].lo = val.realnum;
 				switch (token = xf86getSubToken (&(ptr->mon_comment)))
@@ -513,7 +513,7 @@ HorizDone:
 					case DASH:
 						if (xf86getSubToken (&(ptr->mon_comment)) != NUMBER ||
 						    (float)val.realnum < ptr->mon_vrefresh[ptr->mon_n_vrefresh].lo)
-							Error (VERTREFRESH_MSG, NULL);
+							Error (VERTREFRESH_MSG);
 						ptr->mon_vrefresh[ptr->mon_n_vrefresh].hi = val.realnum;
 						if ((token = xf86getSubToken (&(ptr->mon_comment))) == COMMA)
 							break;
@@ -529,7 +529,7 @@ HorizDone:
 						goto VertDone;
 				}
 				if (ptr->mon_n_vrefresh >= CONF_MAX_VREFRESH)
-					Error ("Sorry. Too many vertical refresh intervals.", NULL);
+					Error ("Sorry. Too many vertical refresh intervals.");
 				ptr->mon_n_vrefresh++;
 			} while ((token = xf86getSubToken (&(ptr->mon_comment))) == NUMBER);
 VertDone:
@@ -539,7 +539,7 @@ VertDone:
 		case GAMMA:
 			if( xf86getSubToken (&(ptr->mon_comment)) != NUMBER )
 			{
-				Error (INVALID_GAMMA_MSG, NULL);
+				Error (INVALID_GAMMA_MSG);
 			}
 			else
 			{
@@ -554,7 +554,7 @@ VertDone:
 					}
 					else
 					{
-						Error (INVALID_GAMMA_MSG, NULL);
+						Error (INVALID_GAMMA_MSG);
 					}
 				}
 				else
@@ -583,7 +583,7 @@ VertDone:
 			}
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			xf86parseError (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -594,7 +594,7 @@ VertDone:
 	}
 
 	if (!has_ident)
-		Error (NO_IDENT_MSG, NULL);
+		Error (NO_IDENT_MSG);
 
 #ifdef DEBUG
 	printf ("Monitor section parsed\n");
@@ -644,7 +644,7 @@ xf86parseModesSection (void)
 	}
 
 	if (!has_ident)
-		Error (NO_IDENT_MSG, NULL);
+		Error (NO_IDENT_MSG);
 
 #ifdef DEBUG
 	printf ("Modes section parsed\n");
diff --git a/hw/xfree86/parser/Pointer.c b/hw/xfree86/parser/Pointer.c
index e8ad290..4edbf74 100644
--- a/hw/xfree86/parser/Pointer.c
+++ b/hw/xfree86/parser/Pointer.c
@@ -184,10 +184,10 @@ xf86parsePointerSection (void)
 			switch (xf86getToken(ZMapTab)) {
 			case NUMBER:
 				if (val.num < 0)
-					Error (ZAXISMAPPING_MSG, NULL);
+					Error (ZAXISMAPPING_MSG);
 				val1 = val.num;
 				if (xf86getSubToken (&(ptr->inp_comment)) != NUMBER || val.num < 0) {
-					Error (ZAXISMAPPING_MSG, NULL);
+					Error (ZAXISMAPPING_MSG);
 				}
 				if (asprintf(&s, "%lu %u", val1, val.num) == -1)
 				    s = NULL;
@@ -199,7 +199,7 @@ xf86parsePointerSection (void)
 				s = strdup("y");
 				break;
 			default:
-				Error (ZAXISMAPPING_MSG, NULL);
+				Error (ZAXISMAPPING_MSG);
 				break;
 			}
 			ptr->inp_option_lst = xf86addNewOption(ptr->inp_option_lst,
@@ -209,7 +209,7 @@ xf86parsePointerSection (void)
 		case ALWAYSCORE:
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
diff --git a/hw/xfree86/parser/Screen.c b/hw/xfree86/parser/Screen.c
index dd2319d..2ca2c57 100644
--- a/hw/xfree86/parser/Screen.c
+++ b/hw/xfree86/parser/Screen.c
@@ -101,18 +101,18 @@ xf86parseDisplaySubSection (void)
 			break;
 		case VIEWPORT:
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (VIEWPORT_MSG, NULL);
+				Error (VIEWPORT_MSG);
 			ptr->disp_frameX0 = val.num;
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (VIEWPORT_MSG, NULL);
+				Error (VIEWPORT_MSG);
 			ptr->disp_frameY0 = val.num;
 			break;
 		case VIRTUAL:
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (VIRTUAL_MSG, NULL);
+				Error (VIRTUAL_MSG);
 			ptr->disp_virtualX = val.num;
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (VIRTUAL_MSG, NULL);
+				Error (VIRTUAL_MSG);
 			ptr->disp_virtualY = val.num;
 			break;
 		case DEPTH:
@@ -132,35 +132,35 @@ xf86parseDisplaySubSection (void)
 			break;
 		case WEIGHT:
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (WEIGHT_MSG, NULL);
+				Error (WEIGHT_MSG);
 			ptr->disp_weight.red = val.num;
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (WEIGHT_MSG, NULL);
+				Error (WEIGHT_MSG);
 			ptr->disp_weight.green = val.num;
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (WEIGHT_MSG, NULL);
+				Error (WEIGHT_MSG);
 			ptr->disp_weight.blue = val.num;
 			break;
 		case BLACK_TOK:
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (BLACK_MSG, NULL);
+				Error (BLACK_MSG);
 			ptr->disp_black.red = val.num;
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (BLACK_MSG, NULL);
+				Error (BLACK_MSG);
 			ptr->disp_black.green = val.num;
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (BLACK_MSG, NULL);
+				Error (BLACK_MSG);
 			ptr->disp_black.blue = val.num;
 			break;
 		case WHITE_TOK:
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (WHITE_MSG, NULL);
+				Error (WHITE_MSG);
 			ptr->disp_white.red = val.num;
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (WHITE_MSG, NULL);
+				Error (WHITE_MSG);
 			ptr->disp_white.green = val.num;
 			if (xf86getSubToken (&(ptr->disp_comment)) != NUMBER)
-				Error (WHITE_MSG, NULL);
+				Error (WHITE_MSG);
 			ptr->disp_white.blue = val.num;
 			break;
 		case MODES:
@@ -183,7 +183,7 @@ xf86parseDisplaySubSection (void)
 			break;
 			
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -302,10 +302,10 @@ xf86parseScreenSection (void)
 			break;
 		case VIRTUAL:
 			if (xf86getSubToken (&(ptr->scrn_comment)) != NUMBER)
-				Error (VIRTUAL_MSG, NULL);
+				Error (VIRTUAL_MSG);
 			ptr->scrn_virtualX = val.num;
 			if (xf86getSubToken (&(ptr->scrn_comment)) != NUMBER)
-				Error (VIRTUAL_MSG, NULL);
+				Error (VIRTUAL_MSG);
 			ptr->scrn_virtualY = val.num;
 			break;
 		case OPTION:
@@ -321,7 +321,7 @@ xf86parseScreenSection (void)
 			}
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -330,7 +330,7 @@ xf86parseScreenSection (void)
 	}
 
 	if (!has_ident && !has_driver)
-		Error (NO_IDENT_MSG, NULL);
+		Error (NO_IDENT_MSG);
 
 #ifdef DEBUG
 	printf ("Screen section parsed\n");
diff --git a/hw/xfree86/parser/Vendor.c b/hw/xfree86/parser/Vendor.c
index dce3f1c..d61f0a0 100644
--- a/hw/xfree86/parser/Vendor.c
+++ b/hw/xfree86/parser/Vendor.c
@@ -102,7 +102,7 @@ xf86parseVendorSubSection (void)
 			break;
 
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -164,7 +164,7 @@ xf86parseVendorSection (void)
 			}
 			break;
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -174,7 +174,7 @@ xf86parseVendorSection (void)
 	}
 
 	if (!has_ident)
-		Error (NO_IDENT_MSG, NULL);
+		Error (NO_IDENT_MSG);
 
 #ifdef DEBUG
 	printf ("Vendor section parsed\n");
diff --git a/hw/xfree86/parser/Video.c b/hw/xfree86/parser/Video.c
index 3774387..19a5418 100644
--- a/hw/xfree86/parser/Video.c
+++ b/hw/xfree86/parser/Video.c
@@ -117,7 +117,7 @@ xf86parseVideoPortSubSection (void)
 			break;
 
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -205,7 +205,7 @@ xf86parseVideoAdaptorSection (void)
 			break;
 
 		case EOF_TOKEN:
-			Error (UNEXPECTED_EOF_MSG, NULL);
+			Error (UNEXPECTED_EOF_MSG);
 			break;
 		default:
 			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
@@ -214,7 +214,7 @@ xf86parseVideoAdaptorSection (void)
 	}
 
 	if (!has_ident)
-		Error (NO_IDENT_MSG, NULL);
+		Error (NO_IDENT_MSG);
 
 #ifdef DEBUG
 	printf ("VideoAdaptor section parsed\n");
commit 7801b3dcd6501e3de93a6d2cee93b2593806e922
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:35 2011 -0800

    Add some printf format attributes suggested by gcc
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xext/security.c b/Xext/security.c
index 63892aa..df5bd58 100644
--- a/Xext/security.c
+++ b/Xext/security.c
@@ -97,7 +97,7 @@ static const Mask SecurityClientMask = DixGetAttrAccess;
  *	Writes the message to the log file if security logging is on.
  */
 
-static void
+static void _X_ATTRIBUTE_PRINTF(1,2)
 SecurityAudit(const char *format, ...)
 {
     va_list args;
diff --git a/hw/xfree86/common/xf86.h b/hw/xfree86/common/xf86.h
index f216d5e..b711f05 100644
--- a/hw/xfree86/common/xf86.h
+++ b/hw/xfree86/common/xf86.h
@@ -232,7 +232,7 @@ extern _X_EXPORT void xf86SetDpi(ScrnInfoPtr pScrn, int x, int y);
 extern _X_EXPORT void xf86SetBlackWhitePixels(ScreenPtr pScreen);
 extern _X_EXPORT void xf86EnableDisableFBAccess(int scrnIndex, Bool enable);
 extern _X_EXPORT void xf86VDrvMsgVerb(int scrnIndex, MessageType type, int verb,
-		     const char *format, va_list args);
+		     const char *format, va_list args) _X_ATTRIBUTE_PRINTF(4,0);
 extern _X_EXPORT void xf86DrvMsgVerb(int scrnIndex, MessageType type, int verb,
 		    const char *format, ...) _X_ATTRIBUTE_PRINTF(4,5);
 extern _X_EXPORT void xf86DrvMsg(int scrnIndex, MessageType type, const char *format, ...)
diff --git a/hw/xfree86/common/xf86Config.c b/hw/xfree86/common/xf86Config.c
index 94d2b15..569695c 100644
--- a/hw/xfree86/common/xf86Config.c
+++ b/hw/xfree86/common/xf86Config.c
@@ -552,7 +552,7 @@ xf86DriverlistFromCompile(void)
  *      Print a READABLE ErrorMessage!!!  All information that is 
  *      available is printed.
  */
-static void
+static void _X_ATTRIBUTE_PRINTF(1,2)
 xf86ConfigError(const char *msg, ...)
 {
     va_list ap;
diff --git a/hw/xfree86/common/xf86Xinput.h b/hw/xfree86/common/xf86Xinput.h
index 909fb57..7d96fac 100644
--- a/hw/xfree86/common/xf86Xinput.h
+++ b/hw/xfree86/common/xf86Xinput.h
@@ -173,7 +173,7 @@ extern _X_EXPORT void xf86VIDrvMsgVerb(InputInfoPtr dev,
 				       MessageType type,
 				       int verb,
 				       const char *format,
-				       va_list args);
+				       va_list args) _X_ATTRIBUTE_PRINTF(4,0);
 
 /* xf86Option.c */
 extern _X_EXPORT void xf86CollectInputOptions(InputInfoPtr pInfo, const char **defaultOpts);
diff --git a/hw/xfree86/parser/configProcs.h b/hw/xfree86/parser/configProcs.h
index 114cdfe..d67acc6 100644
--- a/hw/xfree86/parser/configProcs.h
+++ b/hw/xfree86/parser/configProcs.h
@@ -95,8 +95,8 @@ int xf86getSubToken(char **comment);
 int xf86getSubTokenWithTab(char **comment, xf86ConfigSymTabRec *tab);
 void xf86unGetToken(int token);
 char *xf86tokenString(void);
-void xf86parseError(const char *format, ...);
-void xf86validationError(const char *format, ...);
+void xf86parseError(const char *format, ...) _X_ATTRIBUTE_PRINTF(1,2);
+void xf86validationError(const char *format, ...) _X_ATTRIBUTE_PRINTF(1,2);
 void xf86setSection(const char *section);
 int xf86getStringToken(xf86ConfigSymTabRec *tab);
 /* write.c */
commit f68df9dfd2c7ca03c24aaa0a895b7191ecb81e85
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:34 2011 -0800

    xf86Priv.h: Add some noreturn attributes suggested by gcc
    
    Both functions call exit() at the end and have no other return path.
    Also correct comment/heading to reflect commit 6450f6ca7ee0 moving
    DoShowOptions into xf86Configure.c.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/common/xf86Priv.h b/hw/xfree86/common/xf86Priv.h
index 8c69859..e0b1809 100644
--- a/hw/xfree86/common/xf86Priv.h
+++ b/hw/xfree86/common/xf86Priv.h
@@ -125,10 +125,8 @@ extern _X_EXPORT const DisplayModeRec xf86DefaultModes[];
 extern _X_EXPORT const int xf86NumDefaultModes;
 
 /* xf86Configure.c */
-extern _X_EXPORT void DoConfigure(void);
-
-/* xf86ShowOpts.c */
-extern _X_EXPORT void DoShowOptions(void);
+extern _X_EXPORT void DoConfigure(void) _X_NORETURN;
+extern _X_EXPORT void DoShowOptions(void) _X_NORETURN;
 
 /* xf86Events.c */
 
commit 3823eedf3c124d3a20360480ba349bea72de3069
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:34 2011 -0800

    Remove duplicate declarations of KdAdd*Driver in kdrive.h
    
    Clears gcc warnings in every file that includes kdrive.h:
    kdrive.h:507:1: warning: redundant redeclaration of 'KdAddPointerDriver'
    kdrive.h:225:6: note: previous declaration of 'KdAddPointerDriver' was here
    kdrive.h:510:1: warning: redundant redeclaration of 'KdAddKeyboardDriver'
    kdrive.h:284:6: note: previous declaration of 'KdAddKeyboardDriver' was here
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/kdrive/src/kdrive.h b/hw/kdrive/src/kdrive.h
index be884ab..cda965d 100644
--- a/hw/kdrive/src/kdrive.h
+++ b/hw/kdrive/src/kdrive.h
@@ -503,12 +503,6 @@ KdInitInput(void);
 void
 KdCloseInput(void);
 
-void
-KdAddPointerDriver(KdPointerDriver *);
-
-void
-KdAddKeyboardDriver(KdKeyboardDriver *);
-
 Bool
 KdRegisterFd (int fd, void (*read) (int fd, void *closure), void *closure);
 
commit 471e5373b6f87336dac3b9de9b3852f63a2b10dc
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:34 2011 -0800

    Remove duplicate declaration of xf86ValidateModesFlags in xf86Modes.h
    
    Clears gcc warning in every file that includes xf86Modes.h:
    xf86Modes.h:102:1: warning: redundant redeclaration of 'xf86ValidateModesFlags'
    xf86Modes.h:72:1: note: previous declaration of 'xf86ValidateModesFlags' was here
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/modes/xf86Modes.h b/hw/xfree86/modes/xf86Modes.h
index c72a935..89ec0d8 100644
--- a/hw/xfree86/modes/xf86Modes.h
+++ b/hw/xfree86/modes/xf86Modes.h
@@ -99,10 +99,6 @@ extern _X_EXPORT DisplayModePtr
 xf86PruneDuplicateModes(DisplayModePtr modes);
 
 extern _X_EXPORT void
-xf86ValidateModesFlags(ScrnInfoPtr pScrn, DisplayModePtr modeList,
-		       int flags);
-
-extern _X_EXPORT void
 xf86ValidateModesUserConfig(ScrnInfoPtr pScrn, DisplayModePtr modeList);
 
 extern _X_EXPORT DisplayModePtr
commit 41dd7cf673e47ab74c5065b8dbf268b2e5facb64
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:34 2011 -0800

    _XkbFilterDeviceBtn: move variable declarations to match usage scope
    
    The main body of this function is an if { } else if { } pair of blocks.
    Previously there was int button at the top level scope which is used
    only in the first block, and a redeclaration of int button inside the
    second block.   Since there's no overlap in the code paths for the
    two uses of button, move the one from the outer block into the first
    block to help the programmer more quickly determine they are unrelated
    usages, and to silence the gcc warning of:
    
    xkbActions.c: In function '_XkbFilterDeviceBtn':
    xkbActions.c:999:6: warning: declaration of 'button' shadows a previous local
    xkbActions.c:955:6: warning: shadowed declaration is here
    
    For consistency, move DeviceIntPtr dev declarations as well that are
    used in the same way.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/xkb/xkbActions.c b/xkb/xkbActions.c
index 1e94d26..33864e1 100644
--- a/xkb/xkbActions.c
+++ b/xkb/xkbActions.c
@@ -951,13 +951,13 @@ _XkbFilterDeviceBtn(	XkbSrvInfoPtr	xkbi,
 			unsigned	keycode,
 			XkbAction *	pAction)
 {
-DeviceIntPtr	dev;
-int		button;
-
     if (xkbi->device == inputInfo.keyboard)
         return 0;
 
     if (filter->keycode==0) {		/* initial press */
+	DeviceIntPtr	dev;
+	int		button;
+
 	_XkbLookupButtonDevice(&dev, pAction->devbtn.device, serverClient,
 			       DixUnknownAccess, &button);
 	if (!dev || !dev->public.on)
@@ -996,7 +996,8 @@ int		button;
 	}
     }
     else if (filter->keycode==keycode) {
-	int	button;
+	DeviceIntPtr	dev;
+	int		button;
 
 	filter->active= 0;
 	_XkbLookupButtonDevice(&dev, filter->upAction.devbtn.device,
commit d8eb9b5faa2d2c9350bdaffef8749a9cac3c87b8
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:34 2011 -0800

    XkbFindSrvLedInfo: remove extraneous name-clashing sli variable
    
    Variable is already defined outside the outer if statement, and
    there's no need to redefine inside the if statement.
    
    No point in setting sli before if (dev->kbdfeed->xkb_sli==NULL)
    check - if check is true, we immediately set it, if check is false,
    we immediately return without further reference or use of it.
    
    The one thing we do with it inside the inner if statement is store
    an allocation in it for a brief moment before writing to the final
    destination, which is immediately returned to the caller.
    
    In short, there's no benefit to the variable at all in this block,
    it just gives the optimizer more code to figure out how to omit.
    
    Fixes gcc warning:
    xkbLEDs.c: In function 'XkbFindSrvLedInfo':
    xkbLEDs.c:683:19: warning: declaration of 'sli' shadows a previous local
    xkbLEDs.c:679:18: warning: shadowed declaration is here
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/xkb/xkbLEDs.c b/xkb/xkbLEDs.c
index 515e9b7..24fcd3b 100644
--- a/xkb/xkbLEDs.c
+++ b/xkb/xkbLEDs.c
@@ -680,11 +680,9 @@ XkbSrvLedInfoPtr	sli;
 
     /* optimization to check for most common case */
     if (((class==XkbDfltXIClass)&&(id==XkbDfltXIId))&&(dev->kbdfeed)) {
-	XkbSrvLedInfoPtr	sli;
-	sli= dev->kbdfeed->xkb_sli;
 	if (dev->kbdfeed->xkb_sli==NULL) {
-	    sli= XkbAllocSrvLedInfo(dev,dev->kbdfeed,NULL,needed_parts);
-	    dev->kbdfeed->xkb_sli= sli;
+	    dev->kbdfeed->xkb_sli=
+		XkbAllocSrvLedInfo(dev,dev->kbdfeed,NULL,needed_parts);
 	}
 	return dev->kbdfeed->xkb_sli;
     }
commit 9edfa47bd58cd318d57d0f114714fd146be35a79
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:34 2011 -0800

    KdParseFindNext: Constify delim argument
    
    It's only used as input to strchr to find the delimiters, never
    written to.
    
    Clears a bunch of gcc warnings of the form:
    kdrive.c:323:2: warning: passing argument 2 of 'KdParseFindNext' discards qualifiers from pointer target type
    kdrive.c:261:1: note: expected 'char *' but argument is of type 'const char *'
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/kdrive/src/kdrive.c b/hw/kdrive/src/kdrive.c
index 2c64940..f6cc351 100644
--- a/hw/kdrive/src/kdrive.c
+++ b/hw/kdrive/src/kdrive.c
@@ -253,7 +253,7 @@ Bool	kdDumbDriver;
 Bool	kdSoftCursor;
 
 char *
-KdParseFindNext (char *cur, char *delim, char *save, char *last)
+KdParseFindNext (char *cur, const char *delim, char *save, char *last)
 {
     while (*cur && !strchr (delim, *cur))
     {
diff --git a/hw/kdrive/src/kdrive.h b/hw/kdrive/src/kdrive.h
index 9ac5a19..be884ab 100644
--- a/hw/kdrive/src/kdrive.h
+++ b/hw/kdrive/src/kdrive.h
@@ -424,7 +424,7 @@ KdKeyboardInfo *
 KdParseKeyboard (char *arg);
 
 char *
-KdParseFindNext (char *cur, char *delim, char *save, char *last);
+KdParseFindNext (char *cur, const char *delim, char *save, char *last);
 
 void
 KdParseRgba (char *rgba);
commit ff64ad6c74a3e14ca34bacb8866bdbd2262bddff
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:34 2011 -0800

    Convert KdDoSwitchCmd to use asprintf instead of malloc/strcat/etc.
    
    Also fix the reason argument to be const char * to clear several gcc
    warnings of:
    kdrive.c:151:2: warning: passing argument 1 of 'KdDoSwitchCmd' discards qualifiers from pointer target type
    kdrive.c:116:1: note: expected 'char *' but argument is of type 'const char *'
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/kdrive/src/kdrive.c b/hw/kdrive/src/kdrive.c
index 8dd039e..2c64940 100644
--- a/hw/kdrive/src/kdrive.c
+++ b/hw/kdrive/src/kdrive.c
@@ -113,19 +113,14 @@ KdDisableScreen (ScreenPtr pScreen)
 }
 
 static void
-KdDoSwitchCmd (char *reason)
+KdDoSwitchCmd (const char *reason)
 {
     if (kdSwitchCmd)
     {
-	char    *command = malloc(strlen (kdSwitchCmd) +
-				   1 +
-				   strlen (reason) +
-				   1);
-	if (!command)
+	char    *command;
+
+	if (asprintf(&command, "%s %s", kdSwitchCmd, reason) == -1)
 	    return;
-	strcpy (command, kdSwitchCmd);
-	strcat (command, " ");
-	strcat (command, reason);
 	system (command);
 	free(command);
     }
commit 5bc590bde23ce1c57015b1d9e1cc63189c37448e
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:34 2011 -0800

    DoShowOptions: preserve constness of options list as we walk it
    
    Since all we do with the option list is walk down the list printing
    the names, there's no need to cast away its constness.
    
    Clears gcc warning:
    xf86Configure.c: In function 'DoShowOptions':
    xf86Configure.c:781:4: warning: cast discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/common/xf86Configure.c b/hw/xfree86/common/xf86Configure.c
index 24f367e..994d46f 100644
--- a/hw/xfree86/common/xf86Configure.c
+++ b/hw/xfree86/common/xf86Configure.c
@@ -778,7 +778,8 @@ void DoShowOptions (void) {
 	free(vlist);
 	for (i = 0; i < xf86NumDrivers; i++) {
 		if (xf86DriverList[i]->AvailableOptions) {
-			OptionInfoPtr pOption = (OptionInfoPtr)(*xf86DriverList[i]->AvailableOptions)(0,0);
+			const OptionInfoRec *pOption =
+			    (*xf86DriverList[i]->AvailableOptions)(0,0);
 			if (! pOption) {
 				ErrorF ("(EE) Couldn't read option table for %s driver\n",
 					xf86DriverList[i]->driverName
@@ -790,7 +791,7 @@ void DoShowOptions (void) {
 			initData = LoaderSymbol (pSymbol);
 			if (initData) {
 				XF86ModuleVersionInfo *vers = initData->vers;
-				OptionInfoPtr p;
+				const OptionInfoRec *p;
 				ErrorF ("Driver[%d]:%s[%s] {\n",
 					i,xf86DriverList[i]->driverName,vers->vendor
 				);
commit 71efd868282d47a6db405a16de18ac322926962b
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:34 2011 -0800

    x86emu: constify debug strings
    
    Strings are all pointers to literal constants, just used as input
    to printf calls when debugging is enabled.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/x86emu/debug.c b/hw/xfree86/x86emu/debug.c
index 04d0741..6dea9c7 100644
--- a/hw/xfree86/x86emu/debug.c
+++ b/hw/xfree86/x86emu/debug.c
@@ -163,13 +163,13 @@ void x86emu_inc_decoded_inst_len (int x)
 	M.x86.enc_pos += x;
 }
 
-void x86emu_decode_printf (char *x)
+void x86emu_decode_printf (const char *x)
 {
 	sprintf(M.x86.decoded_buf+M.x86.enc_str_pos,"%s",x);
 	M.x86.enc_str_pos += strlen(x);
 }
 
-void x86emu_decode_printf2 (char *x, int y)
+void x86emu_decode_printf2 (const char *x, int y)
 {
 	char temp[100];
 	snprintf(temp,sizeof(temp),x,y);
diff --git a/hw/xfree86/x86emu/fpu.c b/hw/xfree86/x86emu/fpu.c
index b72de1e..fbc602d 100644
--- a/hw/xfree86/x86emu/fpu.c
+++ b/hw/xfree86/x86emu/fpu.c
@@ -52,7 +52,7 @@ void x86emuOp_esc_coprocess_d8(u8 X86EMU_UNUSED(op1))
 
 #ifdef DEBUG
 
-static char *x86emu_fpu_op_d9_tab[] = {
+static const char *x86emu_fpu_op_d9_tab[] = {
     "FLD\tDWORD PTR ", "ESC_D9\t", "FST\tDWORD PTR ", "FSTP\tDWORD PTR ",
     "FLDENV\t", "FLDCW\t", "FSTENV\t", "FSTCW\t",
 
@@ -63,7 +63,7 @@ static char *x86emu_fpu_op_d9_tab[] = {
     "FLDENV\t", "FLDCW\t", "FSTENV\t", "FSTCW\t",
 };
 
-static char *x86emu_fpu_op_d9_tab1[] = {
+static const char *x86emu_fpu_op_d9_tab1[] = {
     "FLD\t", "FLD\t", "FLD\t", "FLD\t",
     "FLD\t", "FLD\t", "FLD\t", "FLD\t",
 
@@ -299,7 +299,7 @@ void x86emuOp_esc_coprocess_d9(u8 X86EMU_UNUSED(op1))
 
 #ifdef DEBUG
 
-char *x86emu_fpu_op_da_tab[] = {
+static const char *x86emu_fpu_op_da_tab[] = {
     "FIADD\tDWORD PTR ", "FIMUL\tDWORD PTR ", "FICOM\tDWORD PTR ",
     "FICOMP\tDWORD PTR ",
     "FISUB\tDWORD PTR ", "FISUBR\tDWORD PTR ", "FIDIV\tDWORD PTR ",
@@ -392,7 +392,7 @@ void x86emuOp_esc_coprocess_da(u8 X86EMU_UNUSED(op1))
 
 #ifdef DEBUG
 
-char *x86emu_fpu_op_db_tab[] = {
+static const char *x86emu_fpu_op_db_tab[] = {
     "FILD\tDWORD PTR ", "ESC_DB\t19", "FIST\tDWORD PTR ", "FISTP\tDWORD PTR ",
     "ESC_DB\t1C", "FLD\tTBYTE PTR ", "ESC_DB\t1E", "FSTP\tTBYTE PTR ",
 
@@ -513,7 +513,7 @@ void x86emuOp_esc_coprocess_db(u8 X86EMU_UNUSED(op1))
 }
 
 #ifdef DEBUG
-char *x86emu_fpu_op_dc_tab[] = {
+static const char *x86emu_fpu_op_dc_tab[] = {
     "FADD\tQWORD PTR ", "FMUL\tQWORD PTR ", "FCOM\tQWORD PTR ",
     "FCOMP\tQWORD PTR ",
     "FSUB\tQWORD PTR ", "FSUBR\tQWORD PTR ", "FDIV\tQWORD PTR ",
@@ -631,7 +631,7 @@ void x86emuOp_esc_coprocess_dc(u8 X86EMU_UNUSED(op1))
 
 #ifdef DEBUG
 
-static char *x86emu_fpu_op_dd_tab[] = {
+static const char *x86emu_fpu_op_dd_tab[] = {
     "FLD\tQWORD PTR ", "ESC_DD\t29,", "FST\tQWORD PTR ", "FSTP\tQWORD PTR ",
     "FRSTOR\t", "ESC_DD\t2D,", "FSAVE\t", "FSTSW\t",
 
@@ -734,7 +734,7 @@ void x86emuOp_esc_coprocess_dd(u8 X86EMU_UNUSED(op1))
 
 #ifdef DEBUG
 
-static char *x86emu_fpu_op_de_tab[] =
+static const char *x86emu_fpu_op_de_tab[] =
 {
     "FIADD\tWORD PTR ", "FIMUL\tWORD PTR ", "FICOM\tWORD PTR ",
     "FICOMP\tWORD PTR ",
@@ -856,7 +856,7 @@ void x86emuOp_esc_coprocess_de(u8 X86EMU_UNUSED(op1))
 
 #ifdef DEBUG
 
-static char *x86emu_fpu_op_df_tab[] = {
+static const char *x86emu_fpu_op_df_tab[] = {
     /* mod == 00 */
     "FILD\tWORD PTR ", "ESC_DF\t39\n", "FIST\tWORD PTR ", "FISTP\tWORD PTR ",
     "FBLD\tTBYTE PTR ", "FILD\tQWORD PTR ", "FBSTP\tTBYTE PTR ",
diff --git a/hw/xfree86/x86emu/ops2.c b/hw/xfree86/x86emu/ops2.c
index 39bd041..501d5fc 100644
--- a/hw/xfree86/x86emu/ops2.c
+++ b/hw/xfree86/x86emu/ops2.c
@@ -110,7 +110,7 @@ Handles opcode 0x0f,0x80-0x8F
 static void x86emuOp2_long_jump(u8 op2)
 {
     s32 target;
-    char *name = NULL;
+    const char *name = NULL;
     int cond = 0;
 
     /* conditional jump to word offset. */
@@ -204,7 +204,7 @@ static void x86emuOp2_set_byte(u8 op2)
     int mod, rl, rh;
     uint destoffset;
     u8  *destreg;
-    char *name = NULL;
+    const char *name = NULL;
     int cond = 0;
 
     START_OF_INSTR();
diff --git a/hw/xfree86/x86emu/x86emu/debug.h b/hw/xfree86/x86emu/x86emu/debug.h
index 47aacb6..5f78d05 100644
--- a/hw/xfree86/x86emu/x86emu/debug.h
+++ b/hw/xfree86/x86emu/x86emu/debug.h
@@ -189,8 +189,8 @@ extern "C" {            			/* Use "C" linkage when in C++ mode */
 #endif
 
 extern void x86emu_inc_decoded_inst_len (int x);
-extern void x86emu_decode_printf (char *x);
-extern void x86emu_decode_printf2 (char *x, int y);
+extern void x86emu_decode_printf (const char *x);
+extern void x86emu_decode_printf2 (const char *x, int y);
 extern void x86emu_just_disassemble (void);
 extern void x86emu_single_step (void);
 extern void x86emu_end_instr (void);
commit d5a5eece670dee963765eab1431c21525c16d9ee
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:34 2011 -0800

    CompareISOLatin1Lowered: constify arguments
    
    Allows callers to avoid deconstifying arguments when calling, fixing
    gcc warning:
    
    filter.c: In function 'PictureGetFilterId':
    filter.c:59:2: warning: cast discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/dixutils.c b/dix/dixutils.c
index 1e31346..00bbde6 100644
--- a/dix/dixutils.c
+++ b/dix/dixutils.c
@@ -167,8 +167,8 @@ ISOLatin1ToLower (unsigned char source)
 
 
 int
-CompareISOLatin1Lowered(unsigned char *s1, int s1len, 
-			unsigned char *s2, int s2len)
+CompareISOLatin1Lowered(const unsigned char *s1, int s1len,
+			const unsigned char *s2, int s2len)
 {
     unsigned char   c1, c2;
     
diff --git a/include/dix.h b/include/dix.h
index cfbfa1f..2d8d315 100644
--- a/include/dix.h
+++ b/include/dix.h
@@ -175,9 +175,9 @@ extern _X_HIDDEN Bool CreateConnectionBlock(void);
 /* dixutils.c */
 
 extern _X_EXPORT int CompareISOLatin1Lowered(
-    unsigned char * /*a*/,
+    const unsigned char * /*a*/,
     int alen,
-    unsigned char * /*b*/,
+    const unsigned char * /*b*/,
     int blen);
 
 extern _X_EXPORT int dixLookupWindow(
diff --git a/render/filter.c b/render/filter.c
index 0cbd47b..c513ee8 100644
--- a/render/filter.c
+++ b/render/filter.c
@@ -56,7 +56,8 @@ PictureGetFilterId (const char *filter, int len, Bool makeit)
     if (len < 0)
 	len = strlen (filter);
     for (i = 0; i < nfilterNames; i++)
-	if (!CompareISOLatin1Lowered ((unsigned char *) filterNames[i], -1, (unsigned char *) filter, len))
+	if (!CompareISOLatin1Lowered ((const unsigned char *) filterNames[i], -1,
+				      (const unsigned char *) filter, len))
 	    return i;
     if (!makeit)
 	return -1;
commit 83ac9502ea9f1dedf3a8002745668af16bb1f2af
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    xdmcp.c: fix three small const warnings
    
    xdmcp.c:63:36: warning: initialization discards qualifiers from pointer target type
    
    xdmcp.c: In function 'XdmcpRegisterConnection':
    xdmcp.c:482:8: warning: cast discards qualifiers from pointer target type
    xdmcp.c:482:8: warning: cast discards qualifiers from pointer target type
    xdmcp.c:482:8: warning: cast discards qualifiers from pointer target type
    
    xdmcp.c: In function 'get_mcast_options':
    xdmcp.c:1596:21: warning: initialization discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/os/xdmcp.c b/os/xdmcp.c
index 4644071..77f02da 100644
--- a/os/xdmcp.c
+++ b/os/xdmcp.c
@@ -60,7 +60,7 @@
 #define X_INCLUDE_NETDB_H
 #include <X11/Xos_r.h>
 
-static char *defaultDisplayClass = COMPILEDDISPLAYCLASS;
+static const char *defaultDisplayClass = COMPILEDDISPLAYCLASS;
 
 static int		    xdmcpSocket, sessionSocket;
 static xdmcp_states	    state;
@@ -479,7 +479,7 @@ XdmcpRegisterConnection (
 	    if (SOCKADDR_FAMILY(FromAddress) == AF_INET6) {
 		fromAddr = &((struct sockaddr_in6 *)&FromAddress)->sin6_addr;
 	    } else if ((SOCKADDR_FAMILY(FromAddress) == AF_INET) &&
-	      IN6_IS_ADDR_V4MAPPED((struct in6_addr *) address)) {
+	      IN6_IS_ADDR_V4MAPPED((const struct in6_addr *) address)) {
 		fromAddr = &((struct sockaddr_in *)&FromAddress)->sin_addr;
 		regAddr = &((struct sockaddr_in6 *)&address)->sin6_addr.s6_addr[12];
 		regAddrlen = sizeof(struct in_addr);
@@ -1593,7 +1593,7 @@ get_fromaddr_by_name(
 static int
 get_mcast_options(int argc, char **argv, int i)
 {
-    char *address = XDM_DEFAULT_MCAST_ADDR6;
+    const char *address = XDM_DEFAULT_MCAST_ADDR6;
     int hopcount = 1;
     struct addrinfo hints;
     char portstr[6];
commit 3839d1480877818f3ccc04e25237d853bab210c3
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    LockServer: store path to LOCKDIR literal string in a const char *
    
    And instead of initializing to NULL, then resetting to LOCKDIR almost
    immediately (before ever using the NULL value), skip directly to setting
    it to LOCKDIR.
    
    tmppath variable is only used as input for generating the path name
    via calls to strlen, sprintf, etc.
    
    Fixes gcc warning of:
    utils.c: In function 'LockServer':
    utils.c:259:11: warning: assignment discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/os/utils.c b/os/utils.c
index b49fd32..6461ed5 100644
--- a/os/utils.c
+++ b/os/utils.c
@@ -248,7 +248,7 @@ LockServer(void)
 {
   char tmp[PATH_MAX], pid_str[12];
   int lfd, i, haslock, l_pid, t;
-  char *tmppath = NULL;
+  const char *tmppath = LOCK_DIR;
   int len;
   char port[20];
 
@@ -256,8 +256,6 @@ LockServer(void)
   /*
    * Path names
    */
-  tmppath = LOCK_DIR;
-
   snprintf(port, sizeof(port), "%d", atoi(display));
   len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) :
 						strlen(LOCK_TMP_PREFIX);
commit af4113bfeb1d155f5f037c3492e50513336fa4a7
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    WriteToClient: preserve constness of buf while extracting length value
    
    Fixes gcc warning:
    io.c: In function 'WriteToClient':
    io.c:826:6: warning: cast discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/os/io.c b/os/io.c
index 955bf8b..ebb8216 100644
--- a/os/io.c
+++ b/os/io.c
@@ -823,7 +823,7 @@ WriteToClient (ClientPtr who, int count, const void *__buf)
 	    CARD32 replylen;
 	    unsigned long bytesleft;
 
-	    replylen = ((xGenericReply *)buf)->length;
+	    replylen = ((const xGenericReply *)buf)->length;
 	    if (who->swapped)
 		swapl(&replylen);
 	    bytesleft = (replylen * 4) + SIZEOF(xReply) - count - padBytes;
commit 2c9800f91559fbb12dd276cf0536631104092f67
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    OsInit: store "/dev/null" in a const char *
    
    It's only passed as the input side of a strcpy and as the filename to
    fopen, so doesn't need to be non-const.   Fixes gcc warning:
    
    osinit.c: In function 'OsInit':
    osinit.c:154:28: warning: initialization discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/os/osinit.c b/os/osinit.c
index acea682..ff3c45d 100644
--- a/os/osinit.c
+++ b/os/osinit.c
@@ -151,7 +151,7 @@ void
 OsInit(void)
 {
     static Bool been_here = FALSE;
-    static char* devnull = "/dev/null";
+    static const char* devnull = "/dev/null";
     char fname[PATH_MAX];
 
     if (!been_here) {
commit 50b1097643934c8caec9530e5eda6ed6534aaf61
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    Constify the reason string throughout the authorization check framework
    
    Almost all of the places the string is assigned point to a literal
    string constant, so use const char * for those, and const char **
    for function calls that return it via an argument.   Fortunately
    the top level function, ClientAuthorized, which returns the string
    as its return value is called from only one place, ProcEstablishConnection.
    
    ProcEstablishConnection stores either that return value or a string literal
    in char *reason.  It only uses reason as an argument to SendConnSetup.
    SendConnSetup passes the reason argument to strlen & WriteToClient,
    both of which already have const qualifiers on their args.
    Thus added const to the reason variable in ProcEstablishConnection
    and the reason argument to SendConnSetup.
    
    Fixes gcc warnings:
    dispatch.c: In function 'ProcEstablishConnection':
    dispatch.c:3711:9: warning: assignment discards qualifiers from pointer target type
    auth.c: In function 'CheckAuthorization':
    auth.c:218:14: warning: assignment discards qualifiers from pointer target type
    auth.c:220:20: warning: assignment discards qualifiers from pointer target type
    connection.c: In function 'ClientAuthorized':
    connection.c:683:3: warning: return discards qualifiers from pointer target type
    mitauth.c: In function 'MitCheckCookie':
    mitauth.c:88:13: warning: assignment discards qualifiers from pointer target type
    xdmauth.c:259:14: warning: assignment discards qualifiers from pointer target type
    xdmauth.c:270:14: warning: assignment discards qualifiers from pointer target type
    xdmauth.c:277:11: warning: assignment discards qualifiers from pointer target type
    xdmauth.c:293:15: warning: assignment discards qualifiers from pointer target type
    xdmauth.c:313:14: warning: assignment discards qualifiers from pointer target type
    xdmauth.c:322:11: warning: assignment discards qualifiers from pointer target type
    rpcauth.c: In function 'SecureRPCCheck':
    rpcauth.c:136:10: warning: assignment discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/dispatch.c b/dix/dispatch.c
index b39271f..048dff6 100644
--- a/dix/dispatch.c
+++ b/dix/dispatch.c
@@ -3600,7 +3600,7 @@ ProcInitialConnection(ClientPtr client)
 }
 
 static int
-SendConnSetup(ClientPtr client, char *reason)
+SendConnSetup(ClientPtr client, const char *reason)
 {
     xWindowRoot *root;
     int i;
@@ -3699,7 +3699,8 @@ SendConnSetup(ClientPtr client, char *reason)
 int
 ProcEstablishConnection(ClientPtr client)
 {
-    char *reason, *auth_proto, *auth_string;
+    const char *reason;
+    char *auth_proto, *auth_string;
     xConnClientPrefix *prefix;
     REQUEST(xReq);
 
diff --git a/include/os.h b/include/os.h
index 0b50241..48ce329 100644
--- a/include/os.h
+++ b/include/os.h
@@ -127,7 +127,7 @@ extern _X_EXPORT void CloseWellKnownConnections(void);
 
 extern _X_EXPORT XID AuthorizationIDOfClient(ClientPtr /*client*/);
 
-extern _X_EXPORT char *ClientAuthorized(
+extern _X_EXPORT const char *ClientAuthorized(
     ClientPtr /*client*/,
     unsigned int /*proto_n*/,
     char* /*auth_proto*/,
@@ -415,7 +415,7 @@ extern _X_EXPORT XID CheckAuthorization(
     unsigned int /*datalength*/,
     const char * /*data*/,
     ClientPtr /*client*/,
-    char ** /*reason*/
+    const char ** /*reason*/
 );
 
 extern _X_EXPORT void ResetAuthorization(void);
diff --git a/os/auth.c b/os/auth.c
index 9d36249..6669c14 100644
--- a/os/auth.c
+++ b/os/auth.c
@@ -163,7 +163,7 @@ CheckAuthorization (
     unsigned int data_length,
     const char	*data,
     ClientPtr client,
-    char	**reason)	/* failure message.  NULL for default msg */
+    const char	**reason)	/* failure message.  NULL for default msg */
 {
     int	i;
     struct stat buf;
diff --git a/os/connection.c b/os/connection.c
index 6f480de..8a677a7 100644
--- a/os/connection.c
+++ b/os/connection.c
@@ -629,7 +629,7 @@ AuthorizationIDOfClient(ClientPtr client)
  *
  *****************************************************************/
 
-char *
+const char *
 ClientAuthorized(ClientPtr client, 
     unsigned int proto_n, char *auth_proto, 
     unsigned int string_n, char *auth_string)
@@ -639,7 +639,7 @@ ClientAuthorized(ClientPtr client,
     int 		family;
     int			fromlen;
     XID	 		auth_id;
-    char	 	*reason = NULL;
+    const char	 	*reason = NULL;
     XtransConnInfo	trans_conn;
 
     priv = (OsCommPtr)client->osPrivate;
diff --git a/os/mitauth.c b/os/mitauth.c
index 4b8f6e9..477736e 100644
--- a/os/mitauth.c
+++ b/os/mitauth.c
@@ -76,7 +76,7 @@ MitCheckCookie (
     unsigned short	data_length,
     const char		*data,
     ClientPtr		client,
-    char		**reason)
+    const char		**reason)
 {
     struct auth	*auth;
 
diff --git a/os/osdep.h b/os/osdep.h
index 72bd7d7..71a7e44 100644
--- a/os/osdep.h
+++ b/os/osdep.h
@@ -137,7 +137,7 @@ typedef void (*AuthInitFunc) (AuthInitArgs);
 #define AuthAddCArgs unsigned short data_length, const char *data, XID id
 typedef int (*AuthAddCFunc) (AuthAddCArgs);
 
-#define AuthCheckArgs unsigned short data_length, const char *data, ClientPtr client, char **reason
+#define AuthCheckArgs unsigned short data_length, const char *data, ClientPtr client, const char **reason
 typedef XID (*AuthCheckFunc) (AuthCheckArgs);
 
 #define AuthFromIDArgs XID id, unsigned short *data_lenp, char **datap
diff --git a/os/rpcauth.c b/os/rpcauth.c
index 989a49a..63b97b6 100644
--- a/os/rpcauth.c
+++ b/os/rpcauth.c
@@ -128,7 +128,7 @@ static char rpc_error[MAXNETNAMELEN+50];
 
 _X_HIDDEN XID
 SecureRPCCheck (unsigned short data_length, const char *data,
-    ClientPtr client, char **reason)
+    ClientPtr client, const char **reason)
 {
     char *fullname;
     
diff --git a/os/xdmauth.c b/os/xdmauth.c
index b8cbada..733fda5 100644
--- a/os/xdmauth.c
+++ b/os/xdmauth.c
@@ -248,7 +248,7 @@ XdmClientAuthTimeout (long now)
 
 static XdmClientAuthPtr
 XdmAuthorizationValidate (unsigned char *plain, int length, 
-    XdmAuthKeyPtr rho, ClientPtr xclient, char **reason)
+    XdmAuthKeyPtr rho, ClientPtr xclient, const char **reason)
 {
     XdmClientAuthPtr	client, existing;
     long		now;
@@ -376,7 +376,7 @@ XdmAddCookie (unsigned short data_length, const char *data, XID id)
 
 XID
 XdmCheckCookie (unsigned short cookie_length, const char *cookie,
-    ClientPtr xclient, char **reason)
+    ClientPtr xclient, const char **reason)
 {
     XdmAuthorizationPtr	auth;
     XdmClientAuthPtr	client;
commit 99998196017ef38ec88459b50605aa20f628788b
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    Constify string for authorization protocol names
    
    gcc was warning from storing string constants in a char *name field:
    auth.c:64:1: warning: initialization discards qualifiers from pointer target type
    auth.c:72:1: warning: initialization discards qualifiers from pointer target type
    auth.c:81:1: warning: initialization discards qualifiers from pointer target type
    
    Making the field const requires changing AuthorizationFromID to take
    a const char ** pointer for the name argument which it sets to point
    to the matching name entry.
    
    Changing that argument requires changing its sole caller in the security
    extension to pass the address of a const char * variable to it, which it
    can do, since the only thing it does with the returned name is to pass
    it back to the RemoveAuthorization function that already expects a const
    char *name.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xext/security.c b/Xext/security.c
index 6fc1eaf..63892aa 100644
--- a/Xext/security.c
+++ b/Xext/security.c
@@ -171,7 +171,8 @@ SecurityDeleteAuthorization(
 {
     SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)value;
     unsigned short name_len, data_len;
-    char *name, *data;
+    const char *name;
+    char *data;
     int status;
     int i;
     OtherClientsPtr pEventClient;
diff --git a/include/os.h b/include/os.h
index 1fd5367..0b50241 100644
--- a/include/os.h
+++ b/include/os.h
@@ -405,7 +405,7 @@ extern _X_EXPORT void InitAuthorization(char * /*filename*/);
 extern _X_EXPORT int AuthorizationFromID (
 	XID 		id,
 	unsigned short	*name_lenp,
-	char		**namep,
+	const char	**namep,
 	unsigned short	*data_lenp,
 	char		**datap);
 
diff --git a/os/auth.c b/os/auth.c
index 7685751..9d36249 100644
--- a/os/auth.c
+++ b/os/auth.c
@@ -48,7 +48,7 @@ from The Open Group.
 
 struct protocol {
     unsigned short   name_length;
-    char    *name;
+    const char         *name;
     AuthAddCFunc	Add;	/* new authorization data */
     AuthCheckFunc	Check;	/* verify client authorization data */
     AuthRstCFunc	Reset;	/* delete all authorization data entries */
@@ -236,7 +236,7 @@ int
 AuthorizationFromID (
 	XID 		id,
 	unsigned short	*name_lenp,
-	char		**namep,
+	const char	**namep,
 	unsigned short	*data_lenp,
 	char		**datap)
 {
commit 01834e99e461e2a8354f3b4aef7f14c5e83fa255
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    os/access.c: replace acmp & acopy macros with memcmp & memcpy calls
    
    No need to cast to char * now that all supported platforms use C89-standard
    void * argument types, so just drop the casts from acmp & acopy macros,
    which clears the gcc warnings for places const pointers were cast non-const:
    
    access.c: In function 'DefineSelf':
    access.c:786:3: warning: cast discards qualifiers from pointer target type
    access.c:795:6: warning: cast discards qualifiers from pointer target type
    access.c: In function 'NewHost':
    access.c:1293:9: warning: cast discards qualifiers from pointer target type
    access.c:1298:6: warning: cast discards qualifiers from pointer target type
    access.c:1309:5: warning: cast discards qualifiers from pointer target type
    
    Without the casts, acmp & acopy are just a funny way to write memcmp
    & memmove, so drop the macros and inline the calls, taking care to
    swap the first two arguments to memmove since it had swapped them.
    
    Since all the calls to memmove end up being to non-overlapping memory
    (mostly copying from an existing pointer to a newly allocated one),
    replace those with memcpy.
    
    And finally, don't actually call memcpy to copy 0 bytes from one place
    to another, since that's just a waste of a perfectly good function call.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/os/access.c b/os/access.c
index 0800c7f..b609442 100644
--- a/os/access.c
+++ b/os/access.c
@@ -176,12 +176,10 @@ SOFTWARE.
 
 Bool defeatAccessControl = FALSE;
 
-#define acmp(a1, a2, len) memcmp((char *)(a1), (char *)(a2), len)
-#define acopy(a1, a2, len) memmove((char *)(a2), (char *)(a1), len)
 #define addrEqual(fam, address, length, host) \
 			 ((fam) == (host)->family &&\
 			  (length) == (host)->len &&\
-			  !acmp (address, (host)->addr, length))
+			  !memcmp (address, (host)->addr, length))
 
 static int ConvertAddr(struct sockaddr * /*saddr*/,
 		       int * /*len*/,
@@ -371,13 +369,13 @@ DefineSelf (int fd)
 	switch (hp->h_addrtype) {
 	case AF_INET:
 	    inetaddr = (struct sockaddr_in *) (&(saddr.sa));
-	    acopy ( hp->h_addr, &(inetaddr->sin_addr), hp->h_length);
+	    memcpy ( &(inetaddr->sin_addr), hp->h_addr, hp->h_length);
 	    len = sizeof(saddr.sa);
 	    break;
 #if defined(IPv6) && defined(AF_INET6)
 	case AF_INET6:
 	    inet6addr = (struct sockaddr_in6 *) (&(saddr.sa));
-	    acopy ( hp->h_addr, &(inet6addr->sin6_addr), hp->h_length);
+	    memcpy ( &(inet6addr->sin6_addr), hp->h_addr, hp->h_length);
 	    len = sizeof(saddr.in6);
 	    break;
 #endif
@@ -398,7 +396,7 @@ DefineSelf (int fd)
 		{
 		    host->family = family;
 		    host->len = len;
-		    acopy ( addr, host->addr, len);
+		    memcpy ( host->addr, addr, len);
 		    host->next = selfhosts;
 		    selfhosts = host;
 		}
@@ -448,7 +446,7 @@ DefineLocalHost:
 	{
 	    host->family = FamilyLocalHost;
 	    host->len = 0;
-	    acopy("", host->addr, 0);
+	    /* Nothing to store in host->addr */
 	    host->next = selfhosts;
 	    selfhosts = host;
 	}
@@ -585,7 +583,7 @@ DefineSelf (int fd)
 	{
 	    host->family = family;
 	    host->len = len;
-	    acopy(addr, host->addr, len);
+	    memcpy(host->addr, addr, len);
 	    host->next = selfhosts;
 	    selfhosts = host;
 	}
@@ -717,7 +715,7 @@ DefineSelf (int fd)
 	if (host != NULL) {
 	    host->family = family;
 	    host->len = len;
-	    acopy(addr, host->addr, len);
+	    memcpy(host->addr, addr, len);
 	    host->next = selfhosts;
 	    selfhosts = host;
 	}
@@ -792,7 +790,7 @@ DefineSelf (int fd)
 	{
 	    host->family = FamilyLocalHost;
 	    host->len = 0;
-	    acopy("", host->addr, 0);
+	    /* Nothing to store in host->addr */
 	    host->next = selfhosts;
 	    selfhosts = host;
 	}
@@ -821,7 +819,7 @@ AugmentSelf(pointer from, int len)
 	return;
     host->family = family;
     host->len = len;
-    acopy(addr, host->addr, len);
+    memcpy(host->addr, addr, len);
     host->next = selfhosts;
     selfhosts = host;
 }
@@ -1306,7 +1304,7 @@ NewHost (int		family,
 	return FALSE;
     host->family = family;
     host->len = len;
-    acopy(addr, host->addr, len);
+    memcpy(host->addr, addr, len);
     host->next = validhosts;
     validhosts = host;
     return TRUE;
@@ -1400,7 +1398,7 @@ GetHosts (
 	    ((xHostEntry *)ptr)->family = host->family;
 	    ((xHostEntry *)ptr)->length = len;
 	    ptr += sizeof(xHostEntry);
-	    acopy (host->addr, ptr, len);
+	    memcpy (ptr, host->addr, len);
 	    ptr += pad_to_int32(len);
         }
     } else {
@@ -1763,7 +1761,7 @@ siHostnameAddrMatch(int family, pointer addr, int len,
 		hostaddrlen = a->ai_addrlen;
 		f = ConvertAddr(a->ai_addr,&hostaddrlen,&hostaddr);
 		if ((f == family) && (len == hostaddrlen) &&
-		  (acmp (addr, hostaddr, len) == 0) ) {
+		  (memcmp (addr, hostaddr, len) == 0) ) {
 		    res = TRUE;
 		    break;
 		}
@@ -1798,12 +1796,12 @@ siHostnameAddrMatch(int family, pointer addr, int len,
 		struct  sockaddr_in  sin;
 
     		sin.sin_family = hp->h_addrtype;
-		acopy ( *addrlist, &(sin.sin_addr), hp->h_length);
+		memcpy ( &(sin.sin_addr), *addrlist, hp->h_length);
 		hostaddrlen = sizeof(sin);
     		f = ConvertAddr ((struct sockaddr *)&sin, 
 		  &hostaddrlen, &hostaddr);
 		if ((f == family) && (len == hostaddrlen) &&
-		  (acmp (addr, hostaddr, len) == 0) ) {
+		  (memcmp (addr, hostaddr, len) == 0) ) {
 		    res = TRUE;
 		    break;
 		}
commit 020d83d361b0ab54ac962e97b12935be785f9a67
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    xres.c: Preserve constness of string returned by LookupResourceName
    
    MakeAtom now accepts a const char * so we don't need to cast down to
    char * anymore.   Fixes gcc warning of:
    
    xres.c: In function 'ProcXResQueryClientResources':
    xres.c:155:6: warning: cast discards qualifiers from pointer target type
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xext/xres.c b/Xext/xres.c
index b952728..232fbab 100644
--- a/Xext/xres.c
+++ b/Xext/xres.c
@@ -147,12 +147,12 @@ ProcXResQueryClientResources (ClientPtr client)
 
     if(num_types) {
         xXResType scratch;
-	char *name;
+	const char *name;
 
         for(i = 0; i < lastResourceType; i++) {
             if(!counts[i]) continue;
 
-	    name = (char *)LookupResourceName(i + 1);
+	    name = LookupResourceName(i + 1);
             if (strcmp(name, XREGISTRY_UNKNOWN))
 		scratch.resource_type = MakeAtom(name, strlen(name), TRUE);
 	    else {
commit 2ddae8f0bd2a9ce0cd15bf3848393af29e615acf
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Dec 12 16:49:33 2011 -0800

    constify strings in resource name registry
    
    LookupResourceName already returned a const char *, so just needed
    to change the variable we're storing the list in to be a const char **
    and then add const to the name argument to RegisterResourceName
    (which just stores name in the array) and CreateNewResourceType
    (which just passes name to RegisterResourceName).
    
    Clears a bunch of gcc warnings of the form:
    registry.c:319:5: warning: passing argument 2 of 'RegisterResourceName' discards qualifiers from pointer target type
    registry.c:200:1: note: expected 'char *' but argument is of type 'const char *'
    
    and from all the extensions:
    damageext.c: In function 'DamageExtensionInit':
    damageext.c:490:5: warning: passing argument 2 of 'CreateNewResourceType' discards qualifiers from pointer target type
    ../include/resource.h:159:26: note: expected 'char *' but argument is of type 'const char *'
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/registry.c b/dix/registry.c
index fc35dbb..5ab25ad 100644
--- a/dix/registry.c
+++ b/dix/registry.c
@@ -41,7 +41,8 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 static FILE *fh;
 
-static char ***requests, **events, **errors, **resources;
+static char ***requests, **events, **errors;
+static const char **resources;
 static unsigned nmajor, *nminor, nevent, nerror, nresource;
 
 /*
@@ -197,7 +198,7 @@ RegisterExtensionNames(ExtensionEntry *extEntry)
  */
 
 void
-RegisterResourceName(RESTYPE resource, char *name)
+RegisterResourceName(RESTYPE resource, const char *name)
 {
     resource &= TypeMask;
 
diff --git a/dix/resource.c b/dix/resource.c
index eb9f049..be8a8f8 100644
--- a/dix/resource.c
+++ b/dix/resource.c
@@ -242,7 +242,7 @@ CallResourceStateCallback(ResourceState state, ResourceRec *res)
 }
 
 RESTYPE
-CreateNewResourceType(DeleteType deleteFunc, char *name)
+CreateNewResourceType(DeleteType deleteFunc, const char *name)
 {
     RESTYPE next = lastResourceType + 1;
     struct ResourceType *types;
diff --git a/include/registry.h b/include/registry.h
index 325f765..44f7925 100644
--- a/include/registry.h
+++ b/include/registry.h
@@ -28,7 +28,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  * Registration functions.  The name string is not copied, so it must
  * not be a stack variable.
  */
-extern _X_EXPORT void RegisterResourceName(RESTYPE type, char *name);
+extern _X_EXPORT void RegisterResourceName(RESTYPE type, const char *name);
 extern _X_EXPORT void RegisterExtensionNames(ExtensionEntry *ext);
 
 /*
diff --git a/include/resource.h b/include/resource.h
index 772b7b8..5da2819 100644
--- a/include/resource.h
+++ b/include/resource.h
@@ -157,7 +157,7 @@ typedef Bool (*FindComplexResType)(
     pointer /*cdata*/);
 
 extern _X_EXPORT RESTYPE CreateNewResourceType(
-    DeleteType /*deleteFunc*/, char * /*name*/);
+    DeleteType /*deleteFunc*/, const char * /*name*/);
 
 extern _X_EXPORT void SetResourceTypeErrorValue(
     RESTYPE /*type*/, int /*errorValue*/);
commit 424dbde891486ad6a6c00c61a334031ff18f5556
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Fri Dec 9 10:08:55 2011 -0800

    CheckForEmptyMask does not need to declare int n twice
    
    Just use the existing n variable again in the ARGB_CURSOR loop
    instead of creating another one.
    
    Fixes gcc -Wshadow warning:
    cursor.c: In function 'CheckForEmptyMask':
    cursor.c:155:6: warning: declaration of 'n' shadows a previous local
    cursor.c:146:9: warning: shadowed declaration is here
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/cursor.c b/dix/cursor.c
index f29cb11..6bff447 100644
--- a/dix/cursor.c
+++ b/dix/cursor.c
@@ -152,7 +152,7 @@ CheckForEmptyMask(CursorBitsPtr bits)
     if (bits->argb)
     {
 	CARD32 *argb = bits->argb;
-	int n = bits->width * bits->height;
+	n = bits->width * bits->height;
 	while (n--)
 	    if (*argb++ & 0xff000000) return;
     }
commit b2bc38e4a553c29f49a0284333b34b4d6c8a8c12
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sat Dec 10 10:01:18 2011 -0800

    Even more correctly free config file names
    
    If we didn't go into the if (!autoconfig) { } block, the filename,
    dirname, and sysdirname pointers were never initialized, but we
    freed them outside the block, leading to potential memory corruption.
    
    Move the frees inside the block where they're initialized to avoid this.
    
    To avoid similar problems, move the declarations of the variables that
    are only used in this block inside the block.
    
    Regression introduced by commit 3d635fe84d6de53e2f74203b10e89f7851fe3fc1
    
    Found by gcc warning:
    xf86Config.c: In function 'xf86HandleConfigFile':
    xf86Config.c:2303:11: warning: 'filename' may be used uninitialized in this function
    xf86Config.c:2303:22: warning: 'dirname' may be used uninitialized in this function
    xf86Config.c:2303:32: warning: 'sysdirname' may be used uninitialized in this function
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Paulo Zanoni <paulo.r.zanoni at intel.com>

diff --git a/hw/xfree86/common/xf86Config.c b/hw/xfree86/common/xf86Config.c
index fef4bf1..94d2b15 100644
--- a/hw/xfree86/common/xf86Config.c
+++ b/hw/xfree86/common/xf86Config.c
@@ -2300,15 +2300,16 @@ checkInput(serverLayoutPtr layout, Bool implicit_layout) {
 ConfigStatus
 xf86HandleConfigFile(Bool autoconfig)
 {
-    char *filename, *dirname, *sysdirname;
-    const char *filesearch, *dirsearch;
-    MessageType filefrom = X_DEFAULT;
-    MessageType dirfrom = X_DEFAULT;
     char *scanptr;
     Bool singlecard = 0;
     Bool implicit_layout = FALSE;
 
     if (!autoconfig) {
+	char *filename, *dirname, *sysdirname;
+	const char *filesearch, *dirsearch;
+	MessageType filefrom = X_DEFAULT;
+	MessageType dirfrom = X_DEFAULT;
+
 	if (getuid() == 0) {
 	    filesearch = ROOT_CONFIGPATH;
 	    dirsearch = ROOT_CONFIGDIRPATH;
@@ -2350,11 +2351,11 @@ xf86HandleConfigFile(Bool autoconfig)
 			sysdirname);
 	if (!filename && !dirname && !sysdirname)
 	    return CONFIG_NOFILE;
-    }
 
-    free(filename);
-    free(dirname);
-    free(sysdirname);
+	free(filename);
+	free(dirname);
+	free(sysdirname);
+    }
 
     if ((xf86configptr = xf86readConfigFile ()) == NULL) {
 	xf86Msg(X_ERROR, "Problem parsing the config file\n");
commit 33d6e6743d86324c2078f156991b16ac4f2593fc
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Wed Dec 7 19:06:05 2011 -0800

    xf86RegisterRootWindowProperty is confused about xnfcalloc
    
    It will never return NULL, so don't try to handle a NULL condition,
    since that just confuses programmers and static analyzers.
    
    It uses calloc, so all the allocated memory is cleared, so there's
    no point looping over the memory to manually initialize it NULL.
    
    And just because it's annoying, it doesn't need to be the only
    place in this file to do if (NULL==...) instead of if (... == NULL).
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Paulo Zanoni <paulo.r.zanoni at intel.com>

diff --git a/hw/xfree86/common/xf86Helper.c b/hw/xfree86/common/xf86Helper.c
index d99522c..248ccf4 100644
--- a/hw/xfree86/common/xf86Helper.c
+++ b/hw/xfree86/common/xf86Helper.c
@@ -1734,7 +1734,6 @@ xf86RegisterRootWindowProperty(int ScrnIndex, Atom property, Atom type,
 			       int format, unsigned long len, pointer value )
 {
     RootWinPropPtr pNewProp = NULL, pRegProp;
-    int i;
     Bool existing = FALSE;
 
     DebugF("xf86RegisterRootWindowProperty(%d, %ld, %ld, %d, %ld, %p)\n",
@@ -1775,15 +1774,11 @@ xf86RegisterRootWindowProperty(int ScrnIndex, Atom property, Atom type,
 
     DebugF("new property filled\n");
 
-    if (NULL==xf86RegisteredPropertiesTable) {
+    if (xf86RegisteredPropertiesTable == NULL) {
       DebugF("creating xf86RegisteredPropertiesTable[] size %d\n",
 	     xf86NumScreens);
-      if ( NULL==(xf86RegisteredPropertiesTable=(RootWinPropPtr*)xnfcalloc(sizeof(RootWinProp),xf86NumScreens) )) {
-	return BadAlloc;
-      }
-      for (i=0; i<xf86NumScreens; i++) {
-	xf86RegisteredPropertiesTable[i] = NULL;
-      }
+      xf86RegisteredPropertiesTable =
+	  xnfcalloc(sizeof(RootWinProp), xf86NumScreens);
     }
 
     DebugF("xf86RegisteredPropertiesTable %p\n",
commit e5aa00989cda9ebd18063c5e955235123ad37b88
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Dec 7 14:14:10 2011 +1000

    Change GetXI2/XI/CoreType to just take a type argument
    
    Avoids the dummy-event dance if we have an event type and need to get the
    matching XI2 type.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/eventconvert.c b/dix/eventconvert.c
index c9da396..67b420a 100644
--- a/dix/eventconvert.c
+++ b/dix/eventconvert.c
@@ -647,7 +647,7 @@ eventToDeviceEvent(DeviceEvent *ev, xEvent **xi)
     xde = (xXIDeviceEvent*)*xi;
     xde->type           = GenericEvent;
     xde->extension      = IReqCode;
-    xde->evtype         = GetXI2Type((InternalEvent*)ev);
+    xde->evtype         = GetXI2Type(ev->type);
     xde->time           = ev->time;
     xde->length         = bytes_to_int32(len - sizeof(xEvent));
     xde->detail         = ev->detail.button;
@@ -714,7 +714,7 @@ eventToRawEvent(RawDeviceEvent *ev, xEvent **xi)
     raw = (xXIRawEvent*)*xi;
     raw->type           = GenericEvent;
     raw->extension      = IReqCode;
-    raw->evtype         = GetXI2Type((InternalEvent*)ev);
+    raw->evtype         = GetXI2Type(ev->type);
     raw->time           = ev->time;
     raw->length         = bytes_to_int32(len - sizeof(xEvent));
     raw->detail         = ev->detail.button;
@@ -746,10 +746,10 @@ eventToRawEvent(RawDeviceEvent *ev, xEvent **xi)
  * equivalent exists.
  */
 int
-GetCoreType(InternalEvent *event)
+GetCoreType(enum EventType type)
 {
     int coretype = 0;
-    switch(event->any.type)
+    switch(type)
     {
         case ET_Motion:         coretype = MotionNotify;  break;
         case ET_ButtonPress:    coretype = ButtonPress;   break;
@@ -767,10 +767,10 @@ GetCoreType(InternalEvent *event)
  * equivalent exists.
  */
 int
-GetXIType(InternalEvent *event)
+GetXIType(enum EventType type)
 {
     int xitype = 0;
-    switch(event->any.type)
+    switch(type)
     {
         case ET_Motion:         xitype = DeviceMotionNotify;  break;
         case ET_ButtonPress:    xitype = DeviceButtonPress;   break;
@@ -790,11 +790,11 @@ GetXIType(InternalEvent *event)
  * equivalent exists.
  */
 int
-GetXI2Type(InternalEvent *event)
+GetXI2Type(enum EventType type)
 {
     int xi2type = 0;
 
-    switch(event->any.type)
+    switch(type)
     {
         case ET_Motion:         xi2type = XI_Motion;           break;
         case ET_ButtonPress:    xi2type = XI_ButtonPress;      break;
diff --git a/dix/events.c b/dix/events.c
index 5dfcbf3..49f70c3 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -2553,13 +2553,13 @@ EventIsDeliverable(DeviceIntPtr dev, InternalEvent* event, WindowPtr win)
     int type;
     OtherInputMasks *inputMasks = wOtherInputMasks(win);
 
-    if ((type = GetXI2Type(event)) != 0)
+    if ((type = GetXI2Type(event->any.type)) != 0)
     {
         if (inputMasks && xi2mask_isset(inputMasks->xi2mask, dev, type))
             rc |= EVENT_XI2_MASK;
     }
 
-    if ((type = GetXIType(event)) != 0)
+    if ((type = GetXIType(event->any.type)) != 0)
     {
         filter = GetEventFilterMask(dev, type);
 
@@ -2575,7 +2575,7 @@ EventIsDeliverable(DeviceIntPtr dev, InternalEvent* event, WindowPtr win)
 
     }
 
-    if ((type = GetCoreType(event)) != 0)
+    if ((type = GetCoreType(event->any.type)) != 0)
     {
         filter = GetEventFilterMask(dev, type);
 
@@ -3712,7 +3712,7 @@ CheckPassiveGrabsOnWindow(
         tempGrab->modifiersDetail.exact = xkbi ? xkbi->state.grab_mods : 0;
 
         /* Check for XI2 and XI grabs first */
-        tempGrab->type = GetXI2Type(event);
+        tempGrab->type = GetXI2Type(event->any.type);
         tempGrab->grabtype = GRABTYPE_XI2;
         if (GrabMatchesSecond(tempGrab, grab, FALSE))
             match = XI2_MATCH;
@@ -3720,7 +3720,7 @@ CheckPassiveGrabsOnWindow(
         if (!match)
         {
             tempGrab->grabtype = GRABTYPE_XI;
-            if ((tempGrab->type = GetXIType(event)) &&
+            if ((tempGrab->type = GetXIType(event->any.type)) &&
                 (GrabMatchesSecond(tempGrab, grab, FALSE)))
                 match = XI_MATCH;
         }
@@ -3729,7 +3729,7 @@ CheckPassiveGrabsOnWindow(
         if (!match && checkCore)
         {
             tempGrab->grabtype = GRABTYPE_CORE;
-            if ((tempGrab->type = GetCoreType(event)) &&
+            if ((tempGrab->type = GetCoreType(event->any.type)) &&
                 (GrabMatchesSecond(tempGrab, grab, TRUE)))
                 match = CORE_MATCH;
         }
@@ -3784,7 +3784,7 @@ CheckPassiveGrabsOnWindow(
 
         if (!activate)
             break;
-        else if (!GetXIType(event) && !GetCoreType(event))
+        else if (!GetXIType(event->any.type) && !GetCoreType(event->any.type))
         {
             ErrorF("Event type %d in CheckPassiveGrabsOnWindow is neither"
                    " XI 1.x nor core\n", event->any.type);
diff --git a/hw/xfree86/common/xf86DGA.c b/hw/xfree86/common/xf86DGA.c
index 46e3005..0c958cd 100644
--- a/hw/xfree86/common/xf86DGA.c
+++ b/hw/xfree86/common/xf86DGA.c
@@ -1037,7 +1037,7 @@ DGAProcessKeyboardEvent (ScreenPtr pScreen, DGAEvent *event, DeviceIntPtr keybd)
     if (pScreenPriv->client)
     {
         dgaEvent de;
-        de.u.u.type = *XDGAEventBase + GetCoreType((InternalEvent*)&ev);
+        de.u.u.type = *XDGAEventBase + GetCoreType(ev.type);
         de.u.u.detail = event->detail;
         de.u.event.time = event->time;
         de.u.event.dx = event->dx;
@@ -1091,7 +1091,7 @@ DGAProcessPointerEvent (ScreenPtr pScreen, DGAEvent *event, DeviceIntPtr mouse)
         dgaEvent        de;
         int		coreEquiv;
 
-        coreEquiv = GetCoreType((InternalEvent*)&ev);
+        coreEquiv = GetCoreType(ev.type);
 
         de.u.u.type = *XDGAEventBase + coreEquiv;
         de.u.u.detail = event->detail;
diff --git a/include/eventconvert.h b/include/eventconvert.h
index b000abc..571a511 100644
--- a/include/eventconvert.h
+++ b/include/eventconvert.h
@@ -27,14 +27,15 @@
 #include <X11/extensions/XIproto.h>
 #include "input.h"
 #include "events.h"
+#include "eventstr.h"
 
 #define FP1616(integral, frac) ((integral) * (1 << 16) + (frac) * (1 << 16))
 
 _X_EXPORT int EventToCore(InternalEvent *event, xEvent **core, int *count);
 _X_EXPORT int EventToXI(InternalEvent *ev, xEvent **xi, int *count);
 _X_EXPORT int EventToXI2(InternalEvent *ev, xEvent **xi);
-_X_INTERNAL int GetCoreType(InternalEvent* ev);
-_X_INTERNAL int GetXIType(InternalEvent* ev);
-_X_INTERNAL int GetXI2Type(InternalEvent* ev);
+_X_INTERNAL int GetCoreType(enum EventType type);
+_X_INTERNAL int GetXIType(enum EventType type);
+_X_INTERNAL int GetXI2Type(enum EventType type);
 
 #endif /* _EVENTCONVERT_H_ */
diff --git a/test/xi2/protocol-eventconvert.c b/test/xi2/protocol-eventconvert.c
index dce1c50..e2037f9 100644
--- a/test/xi2/protocol-eventconvert.c
+++ b/test/xi2/protocol-eventconvert.c
@@ -59,7 +59,7 @@ static void test_values_XIRawEvent(RawDeviceEvent *in, xXIRawEvent *out,
 
     assert(out->type == GenericEvent);
     assert(out->extension == 0); /* IReqCode defaults to 0 */
-    assert(out->evtype == GetXI2Type((InternalEvent*)in));
+    assert(out->evtype == GetXI2Type(in->type));
     assert(out->time == in->time);
     assert(out->detail == in->detail.button);
     assert(out->deviceid == in->deviceid);
@@ -305,7 +305,7 @@ static void test_values_XIDeviceEvent(DeviceEvent *in, xXIDeviceEvent *out,
     }
 
     assert(out->extension == 0); /* IReqCode defaults to 0 */
-    assert(out->evtype == GetXI2Type((InternalEvent*)in));
+    assert(out->evtype == GetXI2Type(in->type));
     assert(out->time == in->time);
     assert(out->detail == in->detail.button);
     assert(out->length >= 12);
@@ -662,7 +662,7 @@ static void test_values_XIDeviceChangedEvent(DeviceChangedEvent *in,
 
     assert(out->type == GenericEvent);
     assert(out->extension == 0); /* IReqCode defaults to 0 */
-    assert(out->evtype == GetXI2Type((InternalEvent*)in));
+    assert(out->evtype == GetXI2Type(in->type));
     assert(out->time == in->time);
     assert(out->deviceid == in->deviceid);
     assert(out->sourceid == in->sourceid);
commit 6cc0e6a0afa6a87802767d484aa4e68fa935d3eb
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Oct 28 12:55:55 2011 +1000

    include: add GetXI2MaskByte and GetXI2EventFilterMask to headers
    
    This is needed for touch event processing.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 59caa91..5dfcbf3 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -414,7 +414,7 @@ GetEventFilterMask(DeviceIntPtr dev, int evtype)
     return filters[dev ? dev->id : 0][evtype];
 }
 
-static inline Mask
+inline Mask
 GetXI2EventFilterMask(int evtype)
 {
     return (1 << (evtype % 8));
@@ -452,7 +452,7 @@ GetEventFilter(DeviceIntPtr dev, xEvent *event)
  * Return the single byte of the device's XI2 mask that contains the mask
  * for the event_type.
  */
-static int
+int
 GetXI2MaskByte(XI2Mask *mask, DeviceIntPtr dev, int event_type)
 {
     /* we just return the matching filter because that's the only use
diff --git a/include/input.h b/include/input.h
index 8b0c18e..917e92f 100644
--- a/include/input.h
+++ b/include/input.h
@@ -57,6 +57,7 @@ SOFTWARE.
 #include "xkbrules.h"
 #include "events.h"
 #include "list.h"
+#include <X11/extensions/XI2.h>
 
 #define DEVICE_INIT	0
 #define DEVICE_ON	1
@@ -537,6 +538,8 @@ extern _X_EXPORT void FreeInputAttributes(InputAttributes *attrs);
 extern Mask GetEventMask(DeviceIntPtr dev, xEvent* ev, InputClientsPtr clients);
 extern Mask GetEventFilter(DeviceIntPtr dev, xEvent *event);
 extern Bool WindowXI2MaskIsset(DeviceIntPtr dev, WindowPtr win, xEvent* ev);
+extern Mask GetXI2EventFilterMask(int evtype);
+extern int GetXI2MaskByte(XI2Mask *mask, DeviceIntPtr dev, int event_type);
 void FixUpEventFromWindow(SpritePtr pSprite,
                           xEvent *xE,
                           WindowPtr pWin,
commit 372a6f10dc2d74d2d179e8b92449e9b8636a99ef
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Thu Dec 8 21:52:07 2011 -0800

    Change disable_clientpointer return type to void
    
    It doesn't return anything, nor does it's caller expect it to.
    
    Fixes Solaris Studio compiler error:
    "xichangehierarchy.c", line 214: Function has no return statement : disable_clientpointer
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/Xi/xichangehierarchy.c b/Xi/xichangehierarchy.c
index a8bc761..503404e 100644
--- a/Xi/xichangehierarchy.c
+++ b/Xi/xichangehierarchy.c
@@ -200,7 +200,7 @@ unwind:
     return rc;
 }
 
-static int
+static void
 disable_clientpointer(DeviceIntPtr dev)
 {
     int i;
commit 522f8bcc0360d6a117e929a004bc956ab92037e9
Merge: 6369b59 2abe83d
Author: Keith Packard <keithp at keithp.com>
Date:   Thu Dec 8 20:57:26 2011 -0800

    Merge remote-tracking branch 'whot/for-keith'

commit 2abe83df686ed64c4f4df711ac3c1fd12131c2e4
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Dec 5 14:02:51 2011 +1000

    include: add BUG_WARN_MSG for custom error message on bug condition
    
    __BUG_WARN_MSG is a simple helper to enable call with and without varargs. I
    couldn't find a way to otherwise do this without getting gcc warnings.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/include/misc.h b/include/misc.h
index ef86fa5..d9811ca 100644
--- a/include/misc.h
+++ b/include/misc.h
@@ -359,11 +359,18 @@ typedef struct _CharInfo *CharInfoPtr; /* also in fonts/include/font.h */
 extern _X_EXPORT unsigned long globalSerialNumber;
 extern _X_EXPORT unsigned long serverGeneration;
 
-#define BUG_WARN(cond)                                                    \
+/* Don't use this directly, use BUG_WARN or BUG_WARN_MSG instead */
+#define __BUG_WARN_MSG(cond, with_msg, ...)                                \
           do { if (cond) {                                                \
               ErrorF("BUG: triggered 'if (" #cond ")'\nBUG: %s:%d in %s()\n",     \
                       __FILE__, __LINE__, __func__);                      \
+              if (with_msg) ErrorF(__VA_ARGS__);                          \
               xorg_backtrace();                                           \
           } } while(0)
 
+#define BUG_WARN_MSG(cond, msg, ...)                                      \
+          __BUG_WARN_MSG(cond, 1, msg, __VA_ARGS__)
+
+#define BUG_WARN(cond)  __BUG_WARN_MSG(cond, 0, NULL)
+
 #endif /* MISC_H */
commit 4fc797f3756611a97767f407e1af0b6a7cf2f1d9
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Nov 11 16:25:30 2011 +1000

    xfree86: include xorg-config.h from xaalocal.h
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/hw/xfree86/xaa/xaalocal.h b/hw/xfree86/xaa/xaalocal.h
index a9a70da..0780fb1 100644
--- a/hw/xfree86/xaa/xaalocal.h
+++ b/hw/xfree86/xaa/xaalocal.h
@@ -2,6 +2,10 @@
 #ifndef _XAALOCAL_H
 #define _XAALOCAL_H
 
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
 /* This file is very unorganized ! */
 
 
commit 8c9589c71d47f287588314d77ddbfcc22cd04c8a
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Dec 5 11:55:58 2011 +1000

    Xi: rename "state" to "corestate" in ProcessDeviceEvents
    
    'state' is shadowed by the XKB 'state' as well (which feeds into the event
    too), so rename this one to clarify that this is the core event state only.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 532f04e..b2e82ec 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -885,7 +885,7 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
     int key = 0, rootX, rootY;
     ButtonClassPtr b;
     int ret = 0;
-    int state, i;
+    int corestate, i;
     DeviceIntPtr mouse = NULL, kbd = NULL;
     DeviceEvent *event = &ev->device_event;
 
@@ -915,9 +915,9 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
             mouse = NULL;
     }
 
-    /* State needs to be assembled BEFORE the device is updated. */
-    state = (kbd && kbd->key) ? XkbStateFieldFromRec(&kbd->key->xkbInfo->state) : 0;
-    state |= (mouse && mouse->button) ? (mouse->button->state) : 0;
+    /* core state needs to be assembled BEFORE the device is updated. */
+    corestate = (kbd && kbd->key) ? XkbStateFieldFromRec(&kbd->key->xkbInfo->state) : 0;
+    corestate |= (mouse && mouse->button) ? (mouse->button->state) : 0;
 
     for (i = 0; mouse && mouse->button && i < mouse->button->numButtons; i++)
         if (BitIsOn(mouse->button->down, i))
@@ -965,7 +965,7 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
             event->root_x = rootX;
             event->root_y = rootY;
             NoticeEventTime((InternalEvent*)event);
-            event->corestate = state;
+            event->corestate = corestate;
             key = event->detail.key;
             break;
         default:
commit 631516a4aa9858874ee197444cd93d91b97a1089
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Dec 2 15:47:58 2011 +1000

    Xi: check button mapping value _before_ assigning it
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 5e446ec..532f04e 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1002,11 +1002,9 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
                 deactivateDeviceGrab = TRUE;
             break;
         case ET_ButtonPress:
-            event->detail.button = b->map[key];
-            if (!event->detail.button) { /* there's no button 0 */
-                event->detail.button = key;
+            if (b->map[key] == 0) /* there's no button 0 */
                 return;
-            }
+            event->detail.button = b->map[key];
             if (!grab && CheckDeviceGrabs(device, event, 0))
             {
                 /* if a passive grab was activated, the event has been sent
@@ -1015,11 +1013,9 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
             }
             break;
         case ET_ButtonRelease:
-            event->detail.button = b->map[key];
-            if (!event->detail.button) { /* there's no button 0 */
-                event->detail.button = key;
+            if (b->map[key] == 0) /* there's no button 0 */
                 return;
-            }
+            event->detail.button = b->map[key];
             if (grab && !b->buttonsDown &&
                 device->deviceGrab.fromPassiveGrab &&
                 (device->deviceGrab.grab->type == ButtonPress ||
commit a1304d6cb69301899c3c8450d6bf3e68573599df
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Dec 5 11:26:30 2011 +1000

    Xi: skip superfluous cast
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 7a84c6b..5e446ec 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1033,7 +1033,7 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
 
     if (grab)
         DeliverGrabbedEvent((InternalEvent*)event, device, deactivateDeviceGrab);
-    else if (device->focus && !IsPointerEvent((InternalEvent*)ev))
+    else if (device->focus && !IsPointerEvent(ev))
         DeliverFocusedEvent(device, (InternalEvent*)event,
                             GetSpriteWindow(device));
     else
commit 1ab50be938524dcd4a9e56d27e3b96a27c2db2c0
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Nov 30 09:06:06 2011 +1000

    xfixes: don't dereference a NULL cursor
    
    If the new cursor is the NULL cursor, don't dereference it and use zeros
    instead.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Jeremy Huddleston <jeremyhu at apple.com>

diff --git a/xfixes/cursor.c b/xfixes/cursor.c
index 2950e45..53f9f20 100644
--- a/xfixes/cursor.c
+++ b/xfixes/cursor.c
@@ -179,9 +179,9 @@ CursorDisplayCursor (DeviceIntPtr pDev,
 		ev.type = XFixesEventBase + XFixesCursorNotify;
 		ev.subtype = XFixesDisplayCursorNotify;
 		ev.window = e->pWindow->drawable.id;
-		ev.cursorSerial = pCursor->serialNumber;
+		ev.cursorSerial = pCursor ? pCursor->serialNumber : 0;
 		ev.timestamp = currentTime.milliseconds;
-		ev.name = pCursor->name;
+		ev.name = pCursor ? pCursor->name : None;
 		WriteEventsToClient (e->pClient, 1, (xEvent *) &ev);
 	    }
 	}
commit d2ebbcdaf6b13d70eee704b1764ff349e1be22a0
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Nov 29 16:15:37 2011 +1000

    Xi: when removing a device, reset ClientPointers where needed
    
    if a client had the to-be-removed device as ClientPointer, reset to NULL.
    
    Fixes #43165
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Jeremy Huddleston <jeremyhu at apple.com>

diff --git a/Xi/xichangehierarchy.c b/Xi/xichangehierarchy.c
index 614d231..a8bc761 100644
--- a/Xi/xichangehierarchy.c
+++ b/Xi/xichangehierarchy.c
@@ -201,6 +201,19 @@ unwind:
 }
 
 static int
+disable_clientpointer(DeviceIntPtr dev)
+{
+    int i;
+
+    for (i = 0; i < currentMaxClients; i++)
+    {
+        ClientPtr client = clients[i];
+        if (client && client->clientPtr == dev)
+            client->clientPtr = NULL;
+    }
+}
+
+static int
 remove_master(ClientPtr client, xXIRemoveMasterInfo *r,
               int flags[MAXDEVICES])
 {
@@ -250,6 +263,8 @@ remove_master(ClientPtr client, xXIRemoveMasterInfo *r,
     if (rc != Success)
         goto unwind;
 
+    disable_clientpointer(ptr);
+
     /* Disabling sends the devices floating, reattach them if
      * desired. */
     if (r->return_mode == XIAttachToMaster)
commit 27425f07b29e0ddaa782345c1899273ca742891e
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Nov 9 14:45:02 2011 +1000

    dix: use BUG_WARN for input mask size issues
    
    Yes, we're likely corrupting memory here but really this is unlikely to be
    triggered other than a real bug in the server. In which case a stacktrace is
    going to be more useful than any silent error handling.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/inpututils.c b/dix/inpututils.c
index 05d4c7c..60f9fa0 100644
--- a/dix/inpututils.c
+++ b/dix/inpututils.c
@@ -972,8 +972,9 @@ xi2mask_isset(XI2Mask* mask, const DeviceIntPtr dev, int event_type)
 {
     int set = 0;
 
-    if (dev->id < 0 || dev->id >= mask->nmasks || event_type >= mask->mask_size)
-        return 0;
+    BUG_WARN(dev->id < 0);
+    BUG_WARN(dev->id >= mask->nmasks);
+    BUG_WARN(bits_to_bytes(event_type + 1) > mask->mask_size);
 
     set = !!BitIsOn(mask->masks[XIAllDevices], event_type);
     if (!set)
@@ -990,8 +991,9 @@ xi2mask_isset(XI2Mask* mask, const DeviceIntPtr dev, int event_type)
 void
 xi2mask_set(XI2Mask *mask, int deviceid, int event_type)
 {
-    if (deviceid < 0 || deviceid >= mask->nmasks || event_type >= mask->mask_size)
-        return;
+    BUG_WARN(deviceid < 0);
+    BUG_WARN(deviceid >= mask->nmasks);
+    BUG_WARN(bits_to_bytes(event_type + 1) > mask->mask_size);
 
     SetBit(mask->masks[deviceid], event_type);
 }
@@ -1005,8 +1007,7 @@ xi2mask_zero(XI2Mask *mask, int deviceid)
 {
     int i;
 
-    if (deviceid > 0 && deviceid >= mask->nmasks)
-        return;
+    BUG_WARN(deviceid > 0 && deviceid >= mask->nmasks);
 
     if (deviceid >= 0)
         memset(mask->masks[deviceid], 0, mask->mask_size);
@@ -1055,8 +1056,8 @@ xi2mask_mask_size(const XI2Mask *mask)
 void
 xi2mask_set_one_mask(XI2Mask *xi2mask, int deviceid, const unsigned char *mask, size_t mask_size)
 {
-    if (deviceid < 0 || deviceid >= xi2mask->nmasks)
-        return;
+    BUG_WARN(deviceid < 0);
+    BUG_WARN(deviceid >= xi2mask->nmasks);
 
     memcpy(xi2mask->masks[deviceid], mask, min(xi2mask->mask_size, mask_size));
 }
@@ -1067,8 +1068,8 @@ xi2mask_set_one_mask(XI2Mask *xi2mask, int deviceid, const unsigned char *mask,
 const unsigned char*
 xi2mask_get_one_mask(const XI2Mask *mask, int deviceid)
 {
-    if (deviceid < 0 || deviceid >= mask->nmasks)
-        return NULL;
+    BUG_WARN(deviceid < 0);
+    BUG_WARN(deviceid >= mask->nmasks);
 
     return mask->masks[deviceid];
 }
commit 9b570ecbda954227c89938ee6f94b9efd192d3c6
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Dec 9 10:48:05 2011 +1000

    xfree86: bump the input ABI
    
    The last few patches broke the ABI, bump it for convenience.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/common/xf86Module.h b/hw/xfree86/common/xf86Module.h
index a9645e7..d354643 100644
--- a/hw/xfree86/common/xf86Module.h
+++ b/hw/xfree86/common/xf86Module.h
@@ -83,7 +83,7 @@ typedef enum {
  */
 #define ABI_ANSIC_VERSION	SET_ABI_VERSION(0, 4)
 #define ABI_VIDEODRV_VERSION	SET_ABI_VERSION(12, 0)
-#define ABI_XINPUT_VERSION	SET_ABI_VERSION(14, 0)
+#define ABI_XINPUT_VERSION	SET_ABI_VERSION(15, 0)
 #define ABI_EXTENSION_VERSION	SET_ABI_VERSION(6, 0)
 #define ABI_FONT_VERSION	SET_ABI_VERSION(0, 6)
 
commit 86bb3781b336c09e4279136ed81974de5acdba7f
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Nov 4 11:29:01 2011 +1000

    input: swap the server over to use the XI2mask struct
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 8ef9746..7a84c6b 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1631,6 +1631,7 @@ SelectForWindow(DeviceIntPtr dev, WindowPtr pWin, ClientPtr client,
 static void
 FreeInputClient(InputClientsPtr *other)
 {
+    xi2mask_free(&(*other)->xi2mask);
     free(*other);
     *other = NULL;
 }
@@ -1653,6 +1654,9 @@ AddExtensionClient(WindowPtr pWin, ClientPtr client, Mask mask, int mskidx)
 	return BadAlloc;
     if (!pWin->optional->inputMasks && !MakeInputMasks(pWin))
 	goto bail;
+    others->xi2mask = xi2mask_new();
+    if (!others->xi2mask)
+        goto bail;
     others->mask[mskidx] = mask;
     others->resource = FakeClientID(client->index);
     others->next = pWin->optional->inputMasks->inputClients;
@@ -1674,6 +1678,12 @@ MakeInputMasks(WindowPtr pWin)
     imasks = calloc(1, sizeof(struct _OtherInputMasks));
     if (!imasks)
 	return FALSE;
+    imasks->xi2mask = xi2mask_new();
+    if (!imasks->xi2mask)
+    {
+        free(imasks);
+        return FALSE;
+    }
     pWin->optional->inputMasks = imasks;
     return TRUE;
 }
@@ -1681,6 +1691,7 @@ MakeInputMasks(WindowPtr pWin)
 static void
 FreeInputMask(OtherInputMasks **imask)
 {
+    xi2mask_free(&(*imask)->xi2mask);
     free(*imask);
     *imask = NULL;
 }
@@ -1691,20 +1702,17 @@ RecalculateDeviceDeliverableEvents(WindowPtr pWin)
     InputClientsPtr others;
     struct _OtherInputMasks *inputMasks;	/* default: NULL */
     WindowPtr pChild, tmp;
-    int i, j;
+    int i;
 
     pChild = pWin;
     while (1) {
 	if ((inputMasks = wOtherInputMasks(pChild)) != 0) {
-            for (i = 0; i < EMASKSIZE; i++)
-                memset(inputMasks->xi2mask[i], 0, sizeof(inputMasks->xi2mask[i]));
+            xi2mask_zero(inputMasks->xi2mask, -1);
 	    for (others = inputMasks->inputClients; others;
 		 others = others->next) {
 		for (i = 0; i < EMASKSIZE; i++)
 		    inputMasks->inputEvents[i] |= others->mask[i];
-                for (i = 0; i < EMASKSIZE; i++)
-                    for (j = 0; j < XI2MASKSIZE; j++)
-                        inputMasks->xi2mask[i][j] |= others->xi2mask[i][j];
+                xi2mask_merge(inputMasks->xi2mask, others->xi2mask);
 	    }
 	    for (i = 0; i < EMASKSIZE; i++)
 		inputMasks->deliverableEvents[i] = inputMasks->inputEvents[i];
@@ -2188,14 +2196,12 @@ XISetEventMask(DeviceIntPtr dev, WindowPtr win, ClientPtr client,
 	for (others = wOtherInputMasks(win)->inputClients; others;
 	     others = others->next) {
 	    if (SameClient(others, client)) {
-                memset(others->xi2mask[dev->id], 0,
-                       sizeof(others->xi2mask[dev->id]));
+                xi2mask_zero(others->xi2mask, dev->id);
                 break;
             }
         }
     }
 
-    len = min(len, sizeof(others->xi2mask[dev->id]));
 
     if (len && !others)
     {
@@ -2204,11 +2210,14 @@ XISetEventMask(DeviceIntPtr dev, WindowPtr win, ClientPtr client,
         others= wOtherInputMasks(win)->inputClients;
     }
 
-    if (others)
-        memset(others->xi2mask[dev->id], 0, sizeof(others->xi2mask[dev->id]));
+    if (others) {
+        xi2mask_zero(others->xi2mask, dev->id);
+        len = min(len, xi2mask_mask_size(others->xi2mask));
+    }
 
-    if (len)
-        memcpy(others->xi2mask[dev->id], mask, len);
+    if (len) {
+        xi2mask_set_one_mask(others->xi2mask, dev->id, mask, len);
+    }
 
     RecalculateDeviceDeliverableEvents(win);
 
diff --git a/Xi/xigrabdev.c b/Xi/xigrabdev.c
index a9b655c..1cfbf24 100644
--- a/Xi/xigrabdev.c
+++ b/Xi/xigrabdev.c
@@ -41,6 +41,7 @@
 #include "exglobals.h" /* BadDevice */
 #include "exevents.h"
 #include "xigrabdev.h"
+#include "inpututils.h"
 
 int
 SProcXIGrabDevice(ClientPtr client)
@@ -64,7 +65,7 @@ ProcXIGrabDevice(ClientPtr client)
     xXIGrabDeviceReply rep;
     int ret = Success;
     uint8_t status;
-    GrabMask mask;
+    GrabMask mask = { 0 };
     int mask_len;
 
     REQUEST(xXIGrabDeviceReq);
@@ -81,9 +82,13 @@ ProcXIGrabDevice(ClientPtr client)
                                stuff->mask_len * 4) != Success)
         return BadValue;
 
-    mask_len = min(sizeof(mask.xi2mask[stuff->deviceid]), stuff->mask_len * 4);
-    memset(mask.xi2mask, 0, sizeof(mask.xi2mask));
-    memcpy(mask.xi2mask, (char*)&stuff[1], mask_len);
+    mask.xi2mask = xi2mask_new();
+    if (!mask.xi2mask)
+        return BadAlloc;
+
+    mask_len = min(xi2mask_mask_size(mask.xi2mask), stuff->mask_len * 4);
+    /* FIXME: I think the old code was broken here */
+    xi2mask_set_one_mask(mask.xi2mask, dev->id, (unsigned char*)&stuff[1], mask_len);
 
     ret = GrabDevice(client, dev, stuff->grab_mode,
                      stuff->paired_device_mode,
@@ -96,6 +101,8 @@ ProcXIGrabDevice(ClientPtr client)
                      None /* confineTo */,
                      &status);
 
+    xi2mask_free(&mask.xi2mask);
+
     if (ret != Success)
         return ret;
 
diff --git a/Xi/xipassivegrab.c b/Xi/xipassivegrab.c
index 4fa887a..4860757 100644
--- a/Xi/xipassivegrab.c
+++ b/Xi/xipassivegrab.c
@@ -44,6 +44,7 @@
 #include "xipassivegrab.h"
 #include "dixgrabs.h"
 #include "misc.h"
+#include "inpututils.h"
 
 int
 SProcXIPassiveGrabDevice(ClientPtr client)
@@ -82,7 +83,7 @@ ProcXIPassiveGrabDevice(ClientPtr client)
     int i, ret = Success;
     uint32_t *modifiers;
     xXIGrabModifierInfo *modifiers_failed;
-    GrabMask mask;
+    GrabMask mask = { 0 };
     GrabParameters param;
     void *tmp;
     int mask_len;
@@ -124,9 +125,12 @@ ProcXIPassiveGrabDevice(ClientPtr client)
                                stuff->mask_len * 4) != Success)
         return BadValue;
 
-    mask_len = min(sizeof(mask.xi2mask[stuff->deviceid]), stuff->mask_len * 4);
-    memset(mask.xi2mask, 0, sizeof(mask.xi2mask));
-    memcpy(mask.xi2mask[stuff->deviceid], &stuff[1], mask_len * 4);
+    mask.xi2mask = xi2mask_new();
+    if (!mask.xi2mask)
+        return BadAlloc;
+
+    mask_len = min(xi2mask_mask_size(mask.xi2mask), stuff->mask_len * 4);
+    xi2mask_set_one_mask(mask.xi2mask, stuff->deviceid, (unsigned char*)&stuff[1], mask_len * 4);
 
     rep.repType = X_Reply;
     rep.RepType = X_XIPassiveGrabDevice;
@@ -212,6 +216,7 @@ ProcXIPassiveGrabDevice(ClientPtr client)
 
     free(modifiers_failed);
 out:
+    xi2mask_free(&mask.xi2mask);
     return ret;
 }
 
diff --git a/Xi/xiselectev.c b/Xi/xiselectev.c
index 3af4f1f..ee14edb 100644
--- a/Xi/xiselectev.c
+++ b/Xi/xiselectev.c
@@ -33,6 +33,7 @@
 #include "exglobals.h"
 #include "exevents.h"
 #include <X11/extensions/XI2proto.h>
+#include "inpututils.h"
 
 #include "xiselectev.h"
 
@@ -249,7 +250,7 @@ ProcXIGetSelectedEvents(ClientPtr client)
     for (i = 0; i < MAXDEVICES; i++)
     {
         int j;
-        unsigned char *devmask = others->xi2mask[i];
+        const unsigned char *devmask = xi2mask_get_one_mask(others->xi2mask, i);
 
         if (i > 2)
         {
@@ -259,7 +260,7 @@ ProcXIGetSelectedEvents(ClientPtr client)
         }
 
 
-        for (j = XI2MASKSIZE - 1; j >= 0; j--)
+        for (j = xi2mask_mask_size(others->xi2mask) - 1; j >= 0; j--)
         {
             if (devmask[j] != 0)
             {
diff --git a/dix/events.c b/dix/events.c
index 8f8531c..59caa91 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -420,12 +420,6 @@ GetXI2EventFilterMask(int evtype)
     return (1 << (evtype % 8));
 }
 
-static inline int
-GetXI2EventFilterOffset(int evtype)
-{
-    return (evtype / 8);
-}
-
 /**
  * For the given event, return the matching event filter. This filter may then
  * be AND'ed with the selected event mask.
@@ -459,12 +453,15 @@ GetEventFilter(DeviceIntPtr dev, xEvent *event)
  * for the event_type.
  */
 static int
-GetXI2MaskByte(unsigned char xi2mask[][XI2MASKSIZE], DeviceIntPtr dev, int event_type)
+GetXI2MaskByte(XI2Mask *mask, DeviceIntPtr dev, int event_type)
 {
-    int byte = GetXI2EventFilterOffset(event_type);
-    return xi2mask[dev->id][byte] |
-           xi2mask[XIAllDevices][byte] |
-           (IsMaster(dev) ? xi2mask[XIAllMasterDevices][byte] : 0);
+    /* we just return the matching filter because that's the only use
+     * for this mask anyway.
+     */
+    if (xi2mask_isset(mask, dev, event_type))
+        return GetXI2EventFilterMask(event_type);
+    else
+        return 0;
 }
 
 
@@ -476,16 +473,14 @@ Bool
 WindowXI2MaskIsset(DeviceIntPtr dev, WindowPtr win, xEvent* ev)
 {
     OtherInputMasks *inputMasks = wOtherInputMasks(win);
-    int filter;
     int evtype;
 
     if (!inputMasks || xi2_get_type(ev) == 0)
         return 0;
 
     evtype = ((xGenericEvent*)ev)->evtype;
-    filter = GetEventFilter(dev, ev);
 
-    return !!(GetXI2MaskByte(inputMasks->xi2mask, dev, evtype) & filter);
+    return xi2mask_isset(inputMasks->xi2mask, dev, evtype);
 }
 
 Mask
@@ -2011,8 +2006,7 @@ ActivateImplicitGrab(DeviceIntPtr dev, ClientPtr client, WindowPtr win,
     tempGrab->deviceMask = (inputMasks) ? inputMasks->inputEvents[dev->id]: 0;
 
     if (inputMasks)
-        memcpy(tempGrab->xi2mask, inputMasks->xi2mask,
-               sizeof(tempGrab->xi2mask));
+        xi2mask_merge(tempGrab->xi2mask, inputMasks->xi2mask);
 
     (*dev->deviceGrab.ActivateGrab)(dev, tempGrab,
                                     currentTime, TRUE | ImplicitGrabMask);
@@ -2561,10 +2555,7 @@ EventIsDeliverable(DeviceIntPtr dev, InternalEvent* event, WindowPtr win)
 
     if ((type = GetXI2Type(event)) != 0)
     {
-        filter = GetXI2EventFilterMask(type);
-
-        if (inputMasks &&
-            (GetXI2MaskByte(inputMasks->xi2mask,  dev, type) & filter))
+        if (inputMasks && xi2mask_isset(inputMasks->xi2mask, dev, type))
             rc |= EVENT_XI2_MASK;
     }
 
@@ -4155,12 +4146,11 @@ DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
             if (rc == Success)
             {
                 int evtype = xi2_get_type(xi2);
-                mask = GetXI2MaskByte(grab->xi2mask, thisDev, evtype);
+                mask = xi2mask_isset(grab->xi2mask, thisDev, evtype);
                 /* try XI2 event */
                 FixUpEventFromWindow(pSprite, xi2, grab->window, None, TRUE);
                 /* XXX: XACE */
-                deliveries = TryClientEvents(rClient(grab), thisDev, xi2, 1, mask,
-                        GetEventFilter(thisDev, xi2), grab);
+                deliveries = TryClientEvents(rClient(grab), thisDev, xi2, 1, mask, 1, grab);
             } else if (rc != BadMatch)
                 ErrorF("[dix] %s: XI2 conversion failed in DGE (%d, %d). Skipping delivery.\n",
                         thisDev->name, event->any.type, rc);
@@ -4634,9 +4624,8 @@ DeviceEnterLeaveEvent(
     if (grab)
     {
         Mask mask;
-        mask = GetXI2MaskByte(grab->xi2mask, mouse, type);
-        TryClientEvents(rClient(grab), mouse, (xEvent*)event, 1, mask,
-                        filter, grab);
+        mask = xi2mask_isset(grab->xi2mask, mouse, type);
+        TryClientEvents(rClient(grab), mouse, (xEvent*)event, 1, mask, 1, grab);
     } else {
         if (!WindowXI2MaskIsset(mouse, pWin, (xEvent*)event))
             goto out;
@@ -5100,7 +5089,7 @@ GrabDevice(ClientPtr client, DeviceIntPtr dev,
 	else if (grabtype == GRABTYPE_XI)
 	    tempGrab->eventMask = mask->xi;
 	else
-	    memcpy(tempGrab->xi2mask, mask->xi2mask, sizeof(tempGrab->xi2mask));
+            xi2mask_merge(tempGrab->xi2mask, mask->xi2mask);
 	tempGrab->device = dev;
 	tempGrab->cursor = cursor;
 	tempGrab->confineTo = confineTo;
diff --git a/dix/grabs.c b/dix/grabs.c
index a1d56c5..aced130 100644
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@ -60,6 +60,7 @@ SOFTWARE.
 #include "dixgrabs.h"
 #include "xace.h"
 #include "exevents.h"
+#include "inpututils.h"
 
 #define BITMASK(i) (((Mask)1) << ((i) & 31))
 #define MASKIDX(i) ((i) >> 5)
@@ -122,13 +123,15 @@ PrintDeviceGrabInfo(DeviceIntPtr dev)
     }
     else if (grab->grabtype == GRABTYPE_XI2)
     {
-        for (i = 0; i < EMASKSIZE; i++)
+        for (i = 0; i < xi2mask_num_masks(grab->xi2mask); i++)
         {
+            const unsigned char *mask;
             int print;
             print = 0;
             for (j = 0; j < XI2MASKSIZE; j++)
             {
-                if (grab->xi2mask[i][j])
+                mask = xi2mask_get_one_mask(grab->xi2mask, i);
+                if (mask[j])
                 {
                     print = 1;
                     break;
@@ -137,8 +140,8 @@ PrintDeviceGrabInfo(DeviceIntPtr dev)
             if (!print)
                 continue;
             ErrorF("      xi2 event mask for device %d: 0x", dev->id);
-            for (j = 0; j < XI2MASKSIZE; j++)
-                ErrorF("%x", grab->xi2mask[i][j]);
+            for (j = 0; j < xi2mask_mask_size(grab->xi2mask); j++)
+                ErrorF("%x", mask[j]);
             ErrorF("\n");
         }
     }
@@ -185,6 +188,14 @@ AllocGrab(void)
 {
     GrabPtr grab = calloc(1, sizeof(GrabRec));
 
+    if (grab) {
+        grab->xi2mask = xi2mask_new();
+        if (!grab->xi2mask) {
+            free(grab);
+            grab = NULL;
+        }
+    }
+
     return grab;
 }
 
@@ -227,7 +238,7 @@ CreateGrab(
     grab->next = NULL;
 
     if (grabtype == GRABTYPE_XI2)
-        memcpy(grab->xi2mask, mask->xi2mask, sizeof(mask->xi2mask));
+        xi2mask_merge(grab->xi2mask, mask->xi2mask);
     if (cursor)
 	cursor->refcnt++;
     return grab;
@@ -243,6 +254,7 @@ FreeGrab(GrabPtr pGrab)
     if (pGrab->cursor)
 	FreeCursor(pGrab->cursor, (Cursor)0);
 
+    xi2mask_free(&pGrab->xi2mask);
     free(pGrab);
 }
 
@@ -251,6 +263,7 @@ CopyGrab(GrabPtr dst, const GrabPtr src)
 {
     Mask *mdetails_mask = NULL;
     Mask *details_mask = NULL;
+    XI2Mask *xi2mask;
 
     if (src->cursor)
         src->cursor->refcnt++;
@@ -273,9 +286,24 @@ CopyGrab(GrabPtr dst, const GrabPtr src)
         memcpy(details_mask, src->detail.pMask, len);
     }
 
+    if (!dst->xi2mask) {
+        xi2mask = xi2mask_new();
+        if (!xi2mask) {
+            free(mdetails_mask);
+            free(details_mask);
+            return FALSE;
+        }
+    } else {
+        xi2mask = dst->xi2mask;
+        xi2mask_zero(xi2mask, -1);
+    }
+
     *dst = *src;
     dst->modifiersDetail.pMask = mdetails_mask;
     dst->detail.pMask = details_mask;
+    dst->xi2mask = xi2mask;
+
+    xi2mask_merge(dst->xi2mask, src->xi2mask);
 
     return TRUE;
 }
diff --git a/include/inputstr.h b/include/inputstr.h
index a73ace8..5634f3c 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -118,7 +118,7 @@ typedef struct _InputClients {
     XID			resource; /**< id for putting into resource manager */
     Mask		mask[EMASKSIZE]; /**< Actual XI event mask, deviceid is index */
     /** XI2 event masks. One per device, each bit is a mask of (1 << type) */
-    unsigned char       xi2mask[EMASKSIZE][XI2MASKSIZE];
+    struct _XI2Mask     *xi2mask;
 } InputClients;
 
 /**
@@ -148,7 +148,7 @@ typedef struct _OtherInputMasks {
     /** The clients that selected for events */
     InputClientsPtr	inputClients;
     /* XI2 event masks. One per device, each bit is a mask of (1 << type) */
-    unsigned char       xi2mask[EMASKSIZE][XI2MASKSIZE];
+    struct _XI2Mask     *xi2mask;
 } OtherInputMasks;
 
 /*
@@ -176,7 +176,7 @@ typedef enum {
 union _GrabMask {
     Mask core;
     Mask xi;
-    char xi2mask[EMASKSIZE][XI2MASKSIZE];
+    struct _XI2Mask *xi2mask;
 };
 
 /**
@@ -210,7 +210,7 @@ typedef struct _GrabRec {
     Mask		eventMask;
     Mask                deviceMask;     
     /* XI2 event masks. One per device, each bit is a mask of (1 << type) */
-    unsigned char       xi2mask[EMASKSIZE][XI2MASKSIZE];
+    struct _XI2Mask *xi2mask;
 } GrabRec;
 
 /**
commit b8b90cd1610331ff12fa3f70bf372670af7795ec
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Nov 3 13:39:59 2011 +1000

    Add a new XI2Mask struct and a few helper functions.
    
    The current XI2 mask handling is handy for copying (fixed size arrays) but a
    pain to deal with otherwise. Add a struct for XI2 masks and the required
    accessors.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/inpututils.c b/dix/inpututils.c
index c152b2d..05d4c7c 100644
--- a/dix/inpututils.c
+++ b/dix/inpututils.c
@@ -892,3 +892,183 @@ double_to_fp3232(double in)
     ret.frac = frac_d;
     return ret;
 }
+
+/**
+ * DO NOT USE THIS FUNCTION. It only exists for the test cases. Use
+ * xi2mask_new() instead to get the standard sized masks.
+ *
+ * @param nmasks The number of masks (== number of devices)
+ * @param size The size of the masks in bytes
+ * @return The new mask or NULL on allocation error.
+ */
+XI2Mask*
+xi2mask_new_with_size(size_t nmasks, size_t size)
+{
+    int i;
+
+    XI2Mask *mask = calloc(1, sizeof(*mask));
+    if (!mask)
+        return NULL;
+
+
+    mask->nmasks = nmasks;
+    mask->mask_size = size;
+
+    mask->masks = calloc(mask->nmasks, sizeof(*mask->masks));
+    if (!mask->masks)
+        goto unwind;
+
+    for (i = 0; i < mask->nmasks; i++) {
+        mask->masks[i] = calloc(1, mask->mask_size);
+        if (!mask->masks[i])
+            goto unwind;
+    }
+    return mask;
+
+unwind:
+    xi2mask_free(&mask);
+    return NULL;
+}
+
+
+/**
+ * Create a new XI2 mask of the standard size, i.e. for all devices + fake
+ * devices and for the highest supported XI2 event type.
+ *
+ * @return The new mask or NULL on allocation error.
+ */
+XI2Mask*
+xi2mask_new(void)
+{
+    return xi2mask_new_with_size(EMASKSIZE, XI2MASKSIZE);
+}
+
+/**
+ * Frees memory associated with mask and resets mask to NULL.
+ */
+void
+xi2mask_free(XI2Mask** mask)
+{
+    int i;
+
+    if (!(*mask))
+        return;
+
+    for (i = 0; (*mask)->masks && i < (*mask)->nmasks; i++)
+        free((*mask)->masks[i]);
+    free((*mask)->masks);
+    free((*mask));
+    *mask = NULL;
+}
+
+/**
+ * Test if the bit for event type is set for this device, or the
+ * XIAllDevices/XIAllMasterDevices (if applicable) is set.
+ *
+ * @return TRUE if the bit is set, FALSE otherwise
+ */
+Bool
+xi2mask_isset(XI2Mask* mask, const DeviceIntPtr dev, int event_type)
+{
+    int set = 0;
+
+    if (dev->id < 0 || dev->id >= mask->nmasks || event_type >= mask->mask_size)
+        return 0;
+
+    set = !!BitIsOn(mask->masks[XIAllDevices], event_type);
+    if (!set)
+        set = !!BitIsOn(mask->masks[dev->id], event_type);
+    if (!set && IsMaster(dev))
+        set = !!BitIsOn(mask->masks[XIAllMasterDevices], event_type);
+
+    return set;
+}
+
+/**
+ * Set the mask bit for this event type for this device.
+ */
+void
+xi2mask_set(XI2Mask *mask, int deviceid, int event_type)
+{
+    if (deviceid < 0 || deviceid >= mask->nmasks || event_type >= mask->mask_size)
+        return;
+
+    SetBit(mask->masks[deviceid], event_type);
+}
+
+/**
+ * Zero out the xi2mask, for the deviceid given. If the deviceid is < 0, all
+ * masks are zeroed.
+ */
+void
+xi2mask_zero(XI2Mask *mask, int deviceid)
+{
+    int i;
+
+    if (deviceid > 0 && deviceid >= mask->nmasks)
+        return;
+
+    if (deviceid >= 0)
+        memset(mask->masks[deviceid], 0, mask->mask_size);
+    else
+        for (i = 0; i < mask->nmasks; i++)
+            memset(mask->masks[i], 0, mask->mask_size);
+}
+
+/**
+ * Merge source into dest, i.e. dest |= source.
+ * If the masks are of different size, only the overlapping section is merged.
+ */
+void
+xi2mask_merge(XI2Mask *dest, const XI2Mask *source)
+{
+    int i, j;
+
+    for (i = 0; i < min(dest->nmasks, source->nmasks); i++)
+        for (j = 0; j < min(dest->mask_size, source->mask_size); j++)
+            dest->masks[i][j] |= source->masks[i][j];
+}
+
+/**
+ * @return The number of masks in mask
+ */
+size_t
+xi2mask_num_masks(const XI2Mask *mask)
+{
+    return mask->nmasks;
+}
+
+/**
+ * @return The size of each mask in bytes
+ */
+size_t
+xi2mask_mask_size(const XI2Mask *mask)
+{
+    return mask->mask_size;
+}
+
+/**
+ * Set the mask for the given deviceid to the source mask.
+ * If the mask given is larger than the target memory, only the overlapping
+ * parts are copied.
+ */
+void
+xi2mask_set_one_mask(XI2Mask *xi2mask, int deviceid, const unsigned char *mask, size_t mask_size)
+{
+    if (deviceid < 0 || deviceid >= xi2mask->nmasks)
+        return;
+
+    memcpy(xi2mask->masks[deviceid], mask, min(xi2mask->mask_size, mask_size));
+}
+
+/**
+ * Get a reference to the XI2mask for this particular device.
+ */
+const unsigned char*
+xi2mask_get_one_mask(const XI2Mask *mask, int deviceid)
+{
+    if (deviceid < 0 || deviceid >= mask->nmasks)
+        return NULL;
+
+    return mask->masks[deviceid];
+}
diff --git a/include/input.h b/include/input.h
index 8e7b47a..8b0c18e 100644
--- a/include/input.h
+++ b/include/input.h
@@ -205,6 +205,7 @@ extern _X_EXPORT KeybdCtrl	defaultKeyboardControl;
 extern _X_EXPORT PtrCtrl	defaultPointerControl;
 
 typedef struct _InputOption InputOption;
+typedef struct _XI2Mask XI2Mask;
 
 typedef struct _InputAttributes {
     char                *product;
diff --git a/include/inputstr.h b/include/inputstr.h
index f9cb8fe..a73ace8 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -622,4 +622,10 @@ static inline WindowPtr DeepestSpriteWin(SpritePtr sprite)
     return sprite->spriteTrace[sprite->spriteTraceGood - 1];
 }
 
+struct _XI2Mask {
+    unsigned char **masks;      /* event mask in masks[deviceid][event type byte] */
+    size_t nmasks;              /* number of masks */
+    size_t mask_size;           /* size of each mask in bytes */
+};
+
 #endif /* INPUTSTRUCT_H */
diff --git a/include/inpututils.h b/include/inpututils.h
index 2832ed5..5f9dfec 100644
--- a/include/inpututils.h
+++ b/include/inpututils.h
@@ -46,4 +46,16 @@ FP1616 double_to_fp1616(double in);
 double fp1616_to_double(FP1616 in);
 double fp3232_to_double(FP3232 in);
 
+
+XI2Mask* xi2mask_new(void);
+XI2Mask* xi2mask_new_with_size(size_t, size_t); /* don't use it */
+void xi2mask_free(XI2Mask** mask);
+Bool xi2mask_isset(XI2Mask* mask, const DeviceIntPtr dev, int event_type);
+void xi2mask_set(XI2Mask *mask, int deviceid, int event_type);
+void xi2mask_zero(XI2Mask *mask, int deviceid);
+void xi2mask_merge(XI2Mask *dest, const XI2Mask *source);
+size_t xi2mask_num_masks(const XI2Mask *mask);
+size_t xi2mask_mask_size(const XI2Mask *mask);
+void xi2mask_set_one_mask(XI2Mask *xi2mask, int deviceid, const unsigned char *mask, size_t mask_size);
+const unsigned char* xi2mask_get_one_mask(const XI2Mask *xi2mask, int deviceid);
 #endif
diff --git a/test/xi2/Makefile.am b/test/xi2/Makefile.am
index c6e93e7..913ba0f 100644
--- a/test/xi2/Makefile.am
+++ b/test/xi2/Makefile.am
@@ -10,7 +10,8 @@ noinst_PROGRAMS =  \
         protocol-xipassivegrabdevice \
         protocol-xiquerypointer \
         protocol-xiwarppointer \
-        protocol-eventconvert
+        protocol-eventconvert \
+        xi2
 
 TESTS=$(noinst_PROGRAMS)
 TESTS_ENVIRONMENT = $(XORG_MALLOC_DEBUG_ENV)
@@ -34,6 +35,7 @@ protocol_xiquerypointer_LDADD=$(TEST_LDADD)
 protocol_xipassivegrabdevice_LDADD=$(TEST_LDADD)
 protocol_xiwarppointer_LDADD=$(TEST_LDADD)
 protocol_eventconvert_LDADD=$(TEST_LDADD)
+xi2_LDADD=$(TEST_LDADD)
 
 protocol_xiqueryversion_LDFLAGS=$(AM_LDFLAGS) -Wl,-wrap,WriteToClient
 protocol_xiquerydevice_LDFLAGS=$(AM_LDFLAGS) -Wl,-wrap,WriteToClient
@@ -44,6 +46,7 @@ protocol_xigetclientpointer_LDFLAGS=$(AM_LDFLAGS) -Wl,-wrap,WriteToClient -Wl,-w
 protocol_xipassivegrabdevice_LDFLAGS=$(AM_LDFLAGS) -Wl,-wrap,GrabButton -Wl,-wrap,dixLookupWindow -Wl,-wrap,WriteToClient
 protocol_xiquerypointer_LDFLAGS=$(AM_LDFLAGS) -Wl,-wrap,WriteToClient -Wl,-wrap,dixLookupWindow
 protocol_xiwarppointer_LDFLAGS=$(AM_LDFLAGS) -Wl,-wrap,WriteToClient -Wl,-wrap,dixLookupWindow
+xi2_LDFLAGS=$(AM_LDFLAGS)
 
 protocol_xiqueryversion_SOURCES=$(COMMON_SOURCES) protocol-xiqueryversion.c
 protocol_xiquerydevice_SOURCES=$(COMMON_SOURCES) protocol-xiquerydevice.c
diff --git a/test/xi2/xi2.c b/test/xi2/xi2.c
new file mode 100644
index 0000000..5143caf
--- /dev/null
+++ b/test/xi2/xi2.c
@@ -0,0 +1,129 @@
+/**
+ * Copyright © 2011 Red Hat, Inc.
+ *
+ *  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_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <stdint.h>
+#include "inpututils.h"
+#include "inputstr.h"
+#include "assert.h"
+
+static void xi2mask_test(void)
+{
+    XI2Mask *xi2mask = NULL,
+            *mergemask = NULL;
+    unsigned char *mask;
+    DeviceIntRec dev;
+    int i;
+
+    /* size >= nmasks * 2 for the test cases below */
+    xi2mask = xi2mask_new_with_size(MAXDEVICES + 2, (MAXDEVICES + 2) * 2);
+    assert(xi2mask);
+    assert(xi2mask->nmasks > 0);
+    assert(xi2mask->mask_size > 0);
+
+    assert(xi2mask_mask_size(xi2mask) == xi2mask->mask_size);
+    assert(xi2mask_num_masks(xi2mask) == xi2mask->nmasks);
+
+    mask = calloc(1, xi2mask_mask_size(xi2mask));
+    /* ensure zeros */
+    for (i = 0; i < xi2mask_num_masks(xi2mask); i++) {
+        const unsigned char *m = xi2mask_get_one_mask(xi2mask, i);
+        assert(memcmp(mask, m, xi2mask_mask_size(xi2mask)) == 0);
+    }
+
+    /* set various bits */
+    for (i = 0; i < xi2mask_num_masks(xi2mask); i++) {
+        const unsigned char *m;
+        xi2mask_set(xi2mask, i, i);
+
+        dev.id = i;
+        assert(xi2mask_isset(xi2mask, &dev, i));
+
+        m = xi2mask_get_one_mask(xi2mask, i);
+        SetBit(mask, i);
+        assert(memcmp(mask, m, xi2mask_mask_size(xi2mask)) == 0);
+        ClearBit(mask, i);
+    }
+
+    /* ensure zeros one-by-one */
+    for (i = 0; i < xi2mask_num_masks(xi2mask); i++) {
+        const unsigned char *m = xi2mask_get_one_mask(xi2mask, i);
+        assert(memcmp(mask, m, xi2mask_mask_size(xi2mask)) != 0);
+        xi2mask_zero(xi2mask, i);
+        assert(memcmp(mask, m, xi2mask_mask_size(xi2mask)) == 0);
+    }
+
+    /* re-set, zero all */
+    for (i = 0; i < xi2mask_num_masks(xi2mask); i++)
+        xi2mask_set(xi2mask, i, i);
+    xi2mask_zero(xi2mask, -1);
+
+    for (i = 0; i < xi2mask_num_masks(xi2mask); i++) {
+        const unsigned char *m = xi2mask_get_one_mask(xi2mask, i);
+        assert(memcmp(mask, m, xi2mask_mask_size(xi2mask)) == 0);
+    }
+
+    for (i = 0; i < xi2mask_num_masks(xi2mask); i++) {
+        const unsigned char *m;
+        SetBit(mask, i);
+        xi2mask_set_one_mask(xi2mask, i, mask, xi2mask_mask_size(xi2mask));
+        m = xi2mask_get_one_mask(xi2mask, i);
+        assert(memcmp(mask, m, xi2mask_mask_size(xi2mask)) == 0);
+        ClearBit(mask, i);
+    }
+
+    mergemask = xi2mask_new_with_size(MAXDEVICES + 2, (MAXDEVICES + 2) * 2);
+    for (i = 0; i < xi2mask_num_masks(mergemask); i++) {
+        dev.id = i;
+        xi2mask_set(mergemask, i, i * 2);
+    }
+
+    /* xi2mask still has all i bits set, should now also have all i * 2 bits */
+    xi2mask_merge(xi2mask, mergemask);
+    for (i = 0; i < xi2mask_num_masks(mergemask); i++) {
+        const unsigned char *m = xi2mask_get_one_mask(xi2mask, i);
+        SetBit(mask, i);
+        SetBit(mask, i * 2);
+        assert(memcmp(mask, m, xi2mask_mask_size(xi2mask)) == 0);
+        ClearBit(mask, i);
+        ClearBit(mask, i * 2);
+    }
+
+    xi2mask_free(&xi2mask);
+    assert(xi2mask == NULL);
+
+    xi2mask_free(&mergemask);
+    assert(mergemask == NULL);
+    free(mask);
+}
+
+
+int main(int argc, char** argv)
+{
+    xi2mask_test();
+
+    return 0;
+}
commit 4bc2761ad5ec2d0668aec639780ffb136605fbc8
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Nov 4 14:16:37 2011 +1000

    dix: switch the dev->deviceGrab.activeGrab from GrabRec to GrabPtr
    
    This breaks the input ABI.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/devices.c b/dix/devices.c
index 37cbcdb..e448eab 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -73,6 +73,7 @@ SOFTWARE.
 #include "dixevents.h"
 #include "mipointer.h"
 #include "eventstr.h"
+#include "dixgrabs.h"
 
 #include <X11/extensions/XI.h>
 #include <X11/extensions/XI2.h>
@@ -273,6 +274,7 @@ AddInputDevice(ClientPtr client, DeviceProc deviceProc, Bool autoStart)
     dev->deviceGrab.grabTime = currentTime;
     dev->deviceGrab.ActivateGrab = ActivateKeyboardGrab;
     dev->deviceGrab.DeactivateGrab = DeactivateKeyboardGrab;
+    dev->deviceGrab.activeGrab = AllocGrab();
 
     XkbSetExtension(dev, ProcessKeyboardEvent);
 
@@ -941,6 +943,7 @@ CloseDevice(DeviceIntPtr dev)
         }
     }
 
+    FreeGrab(dev->deviceGrab.activeGrab);
     free(dev->deviceGrab.sync.event);
     free(dev->config_info);     /* Allocated in xf86ActivateDevice. */
     free(dev->last.scroll);
diff --git a/dix/events.c b/dix/events.c
index bd7e93b..8f8531c 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1509,8 +1509,8 @@ ActivatePointerGrab(DeviceIntPtr mouse, GrabPtr grab,
 	grabinfo->grabTime = time;
     if (grab->cursor)
 	grab->cursor->refcnt++;
-    CopyGrab(&grabinfo->activeGrab, grab);
-    grabinfo->grab = &grabinfo->activeGrab;
+    CopyGrab(grabinfo->activeGrab, grab);
+    grabinfo->grab = grabinfo->activeGrab;
     grabinfo->fromPassiveGrab = isPassive;
     grabinfo->implicitGrab = autoGrab & ImplicitGrabMask;
     PostNewCursor(mouse);
@@ -1586,8 +1586,8 @@ ActivateKeyboardGrab(DeviceIntPtr keybd, GrabPtr grab, TimeStamp time, Bool pass
 	grabinfo->grabTime = syncEvents.time;
     else
 	grabinfo->grabTime = time;
-    CopyGrab(&grabinfo->activeGrab, grab);
-    grabinfo->grab = &grabinfo->activeGrab;
+    CopyGrab(grabinfo->activeGrab, grab);
+    grabinfo->grab = grabinfo->activeGrab;
     grabinfo->fromPassiveGrab = passive;
     grabinfo->implicitGrab = passive & ImplicitGrabMask;
     CheckGrabForSyncs(keybd, (Bool)grab->keyboardMode, (Bool)grab->pointerMode);
diff --git a/include/inputstr.h b/include/inputstr.h
index 0568e0c..f9cb8fe 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -451,7 +451,7 @@ typedef struct _GrabInfoRec {
     TimeStamp	    grabTime;
     Bool            fromPassiveGrab;    /* true if from passive grab */
     Bool            implicitGrab;       /* implicit from ButtonPress */
-    GrabRec         activeGrab;
+    GrabPtr         activeGrab;
     GrabPtr         grab;
     CARD8           activatingKey;
     void	    (*ActivateGrab) (
commit b601ea769f1b8a4d7f19e9d4a13541c78e865fe5
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Nov 4 10:47:27 2011 +1000

    dix: allocate temporary grabs on the heap
    
    Once grabs start having nested memory locations, we can't just use the
    GrabRec on the stack anymore, we need to alloc/copy/free the grabs.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 20495e7..8ef9746 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -2024,20 +2024,25 @@ CheckDeviceGrabAndHintWindow(WindowPtr pWin, int type,
 	dev->valuator->motionHintWindow = pWin;
     else if ((type == DeviceButtonPress) && (!grab) &&
 	     (deliveryMask & DeviceButtonGrabMask)) {
-	GrabRec tempGrab;
+	GrabPtr tempGrab;
 
-	tempGrab.device = dev;
-	tempGrab.resource = client->clientAsMask;
-	tempGrab.window = pWin;
-	tempGrab.ownerEvents =
+	tempGrab = AllocGrab();
+	if (!tempGrab)
+	    return;
+
+	tempGrab->device = dev;
+	tempGrab->resource = client->clientAsMask;
+	tempGrab->window = pWin;
+	tempGrab->ownerEvents =
 	    (deliveryMask & DeviceOwnerGrabButtonMask) ? TRUE : FALSE;
-	tempGrab.eventMask = deliveryMask;
-	tempGrab.keyboardMode = GrabModeAsync;
-	tempGrab.pointerMode = GrabModeAsync;
-	tempGrab.confineTo = NullWindow;
-	tempGrab.cursor = NullCursor;
-        tempGrab.next = NULL;
-	(*dev->deviceGrab.ActivateGrab) (dev, &tempGrab, currentTime, TRUE);
+	tempGrab->eventMask = deliveryMask;
+	tempGrab->keyboardMode = GrabModeAsync;
+	tempGrab->pointerMode = GrabModeAsync;
+	tempGrab->confineTo = NullWindow;
+	tempGrab->cursor = NullCursor;
+	tempGrab->next = NULL;
+	(*dev->deviceGrab.ActivateGrab) (dev, tempGrab, currentTime, TRUE);
+	FreeGrab(tempGrab);
     }
 }
 
diff --git a/Xi/ungrdevb.c b/Xi/ungrdevb.c
index 9e9ece4..6280248 100644
--- a/Xi/ungrdevb.c
+++ b/Xi/ungrdevb.c
@@ -96,7 +96,7 @@ ProcXUngrabDeviceButton(ClientPtr client)
     DeviceIntPtr dev;
     DeviceIntPtr mdev;
     WindowPtr pWin;
-    GrabRec temporaryGrab;
+    GrabPtr temporaryGrab;
     int rc;
 
     REQUEST(xUngrabDeviceButtonReq);
@@ -126,17 +126,23 @@ ProcXUngrabDeviceButton(ClientPtr client)
 	(stuff->modifiers & ~AllModifiersMask))
 	return BadValue;
 
-    temporaryGrab.resource = client->clientAsMask;
-    temporaryGrab.device = dev;
-    temporaryGrab.window = pWin;
-    temporaryGrab.type = DeviceButtonPress;
-    temporaryGrab.grabtype = GRABTYPE_XI;
-    temporaryGrab.modifierDevice = mdev;
-    temporaryGrab.modifiersDetail.exact = stuff->modifiers;
-    temporaryGrab.modifiersDetail.pMask = NULL;
-    temporaryGrab.detail.exact = stuff->button;
-    temporaryGrab.detail.pMask = NULL;
-
-    DeletePassiveGrabFromList(&temporaryGrab);
+    temporaryGrab = AllocGrab();
+    if (!temporaryGrab)
+        return BadAlloc;
+
+    temporaryGrab->resource = client->clientAsMask;
+    temporaryGrab->device = dev;
+    temporaryGrab->window = pWin;
+    temporaryGrab->type = DeviceButtonPress;
+    temporaryGrab->grabtype = GRABTYPE_XI;
+    temporaryGrab->modifierDevice = mdev;
+    temporaryGrab->modifiersDetail.exact = stuff->modifiers;
+    temporaryGrab->modifiersDetail.pMask = NULL;
+    temporaryGrab->detail.exact = stuff->button;
+    temporaryGrab->detail.pMask = NULL;
+
+    DeletePassiveGrabFromList(temporaryGrab);
+
+    FreeGrab(temporaryGrab);
     return Success;
 }
diff --git a/Xi/ungrdevk.c b/Xi/ungrdevk.c
index 526347d..b0d83cb 100644
--- a/Xi/ungrdevk.c
+++ b/Xi/ungrdevk.c
@@ -98,7 +98,7 @@ ProcXUngrabDeviceKey(ClientPtr client)
     DeviceIntPtr dev;
     DeviceIntPtr mdev;
     WindowPtr pWin;
-    GrabRec temporaryGrab;
+    GrabPtr temporaryGrab;
     int rc;
 
     REQUEST(xUngrabDeviceKeyReq);
@@ -133,17 +133,22 @@ ProcXUngrabDeviceKey(ClientPtr client)
 	(stuff->modifiers & ~AllModifiersMask))
 	return BadValue;
 
-    temporaryGrab.resource = client->clientAsMask;
-    temporaryGrab.device = dev;
-    temporaryGrab.window = pWin;
-    temporaryGrab.type = DeviceKeyPress;
-    temporaryGrab.grabtype = GRABTYPE_XI;
-    temporaryGrab.modifierDevice = mdev;
-    temporaryGrab.modifiersDetail.exact = stuff->modifiers;
-    temporaryGrab.modifiersDetail.pMask = NULL;
-    temporaryGrab.detail.exact = stuff->key;
-    temporaryGrab.detail.pMask = NULL;
-
-    DeletePassiveGrabFromList(&temporaryGrab);
+    temporaryGrab = AllocGrab();
+    if (!temporaryGrab)
+        return BadAlloc;
+
+    temporaryGrab->resource = client->clientAsMask;
+    temporaryGrab->device = dev;
+    temporaryGrab->window = pWin;
+    temporaryGrab->type = DeviceKeyPress;
+    temporaryGrab->grabtype = GRABTYPE_XI;
+    temporaryGrab->modifierDevice = mdev;
+    temporaryGrab->modifiersDetail.exact = stuff->modifiers;
+    temporaryGrab->modifiersDetail.pMask = NULL;
+    temporaryGrab->detail.exact = stuff->key;
+    temporaryGrab->detail.pMask = NULL;
+
+    DeletePassiveGrabFromList(temporaryGrab);
+    FreeGrab(temporaryGrab);
     return Success;
 }
diff --git a/Xi/xipassivegrab.c b/Xi/xipassivegrab.c
index 2f13a95..4fa887a 100644
--- a/Xi/xipassivegrab.c
+++ b/Xi/xipassivegrab.c
@@ -253,7 +253,7 @@ ProcXIPassiveUngrabDevice(ClientPtr client)
 {
     DeviceIntPtr dev, mod_dev;
     WindowPtr win;
-    GrabRec tempGrab;
+    GrabPtr tempGrab;
     uint32_t* modifiers;
     int i, rc;
 
@@ -293,29 +293,36 @@ ProcXIPassiveUngrabDevice(ClientPtr client)
 
     mod_dev = (IsFloating(dev)) ? dev : GetMaster(dev, MASTER_KEYBOARD);
 
-    tempGrab.resource = client->clientAsMask;
-    tempGrab.device = dev;
-    tempGrab.window = win;
+
+    tempGrab = AllocGrab();
+    if (!tempGrab)
+        return BadAlloc;
+
+    tempGrab->resource = client->clientAsMask;
+    tempGrab->device = dev;
+    tempGrab->window = win;
     switch(stuff->grab_type)
     {
-        case XIGrabtypeButton:  tempGrab.type = XI_ButtonPress; break;
-        case XIGrabtypeKeycode:  tempGrab.type = XI_KeyPress;    break;
-        case XIGrabtypeEnter:   tempGrab.type = XI_Enter;       break;
-        case XIGrabtypeFocusIn: tempGrab.type = XI_FocusIn;     break;
+        case XIGrabtypeButton:  tempGrab->type = XI_ButtonPress; break;
+        case XIGrabtypeKeycode:  tempGrab->type = XI_KeyPress;    break;
+        case XIGrabtypeEnter:   tempGrab->type = XI_Enter;       break;
+        case XIGrabtypeFocusIn: tempGrab->type = XI_FocusIn;     break;
     }
-    tempGrab.grabtype = GRABTYPE_XI2;
-    tempGrab.modifierDevice = mod_dev;
-    tempGrab.modifiersDetail.pMask = NULL;
-    tempGrab.detail.exact = stuff->detail;
-    tempGrab.detail.pMask = NULL;
+    tempGrab->grabtype = GRABTYPE_XI2;
+    tempGrab->modifierDevice = mod_dev;
+    tempGrab->modifiersDetail.pMask = NULL;
+    tempGrab->detail.exact = stuff->detail;
+    tempGrab->detail.pMask = NULL;
 
     modifiers = (uint32_t*)&stuff[1];
 
     for (i = 0; i < stuff->num_modifiers; i++, modifiers++)
     {
-        tempGrab.modifiersDetail.exact = *modifiers;
-        DeletePassiveGrabFromList(&tempGrab);
+        tempGrab->modifiersDetail.exact = *modifiers;
+        DeletePassiveGrabFromList(tempGrab);
     }
 
+    FreeGrab(tempGrab);
+
     return Success;
 }
diff --git a/dix/events.c b/dix/events.c
index c1c296d..bd7e93b 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1976,7 +1976,7 @@ static BOOL
 ActivateImplicitGrab(DeviceIntPtr dev, ClientPtr client, WindowPtr win,
                      xEvent *event, Mask deliveryMask)
 {
-    GrabRec tempGrab;
+    GrabPtr tempGrab;
     OtherInputMasks *inputMasks;
     CARD8 type = event->u.u.type;
     GrabType grabtype;
@@ -1990,30 +1990,33 @@ ActivateImplicitGrab(DeviceIntPtr dev, ClientPtr client, WindowPtr win,
     else
         return FALSE;
 
-    memset(&tempGrab, 0, sizeof(GrabRec));
-    tempGrab.next = NULL;
-    tempGrab.device = dev;
-    tempGrab.resource = client->clientAsMask;
-    tempGrab.window = win;
-    tempGrab.ownerEvents = (deliveryMask & OwnerGrabButtonMask) ? TRUE : FALSE;
-    tempGrab.eventMask = deliveryMask;
-    tempGrab.keyboardMode = GrabModeAsync;
-    tempGrab.pointerMode = GrabModeAsync;
-    tempGrab.confineTo = NullWindow;
-    tempGrab.cursor = NullCursor;
-    tempGrab.type = type;
-    tempGrab.grabtype = grabtype;
+    tempGrab = AllocGrab();
+    if (!tempGrab)
+        return FALSE;
+    tempGrab->next = NULL;
+    tempGrab->device = dev;
+    tempGrab->resource = client->clientAsMask;
+    tempGrab->window = win;
+    tempGrab->ownerEvents = (deliveryMask & OwnerGrabButtonMask) ? TRUE : FALSE;
+    tempGrab->eventMask = deliveryMask;
+    tempGrab->keyboardMode = GrabModeAsync;
+    tempGrab->pointerMode = GrabModeAsync;
+    tempGrab->confineTo = NullWindow;
+    tempGrab->cursor = NullCursor;
+    tempGrab->type = type;
+    tempGrab->grabtype = grabtype;
 
     /* get the XI and XI2 device mask */
     inputMasks = wOtherInputMasks(win);
-    tempGrab.deviceMask = (inputMasks) ? inputMasks->inputEvents[dev->id]: 0;
+    tempGrab->deviceMask = (inputMasks) ? inputMasks->inputEvents[dev->id]: 0;
 
     if (inputMasks)
-        memcpy(tempGrab.xi2mask, inputMasks->xi2mask,
-               sizeof(tempGrab.xi2mask));
+        memcpy(tempGrab->xi2mask, inputMasks->xi2mask,
+               sizeof(tempGrab->xi2mask));
 
-    (*dev->deviceGrab.ActivateGrab)(dev, &tempGrab,
+    (*dev->deviceGrab.ActivateGrab)(dev, tempGrab,
                                     currentTime, TRUE | ImplicitGrabMask);
+    FreeGrab(tempGrab);
     return TRUE;
 }
 
@@ -3657,7 +3660,7 @@ CheckPassiveGrabsOnWindow(
 {
     SpritePtr pSprite = device->spriteInfo->sprite;
     GrabPtr grab = wPassiveGrabs(pWin);
-    GrabRec tempGrab;
+    GrabPtr tempGrab;
     GrabInfoPtr grabinfo;
 #define CORE_MATCH      0x1
 #define XI_MATCH        0x2
@@ -3666,27 +3669,30 @@ CheckPassiveGrabsOnWindow(
 
     if (!grab)
 	return NULL;
+
+    tempGrab = AllocGrab();
+
     /* Fill out the grab details, but leave the type for later before
      * comparing */
     switch (event->any.type)
     {
         case ET_KeyPress:
         case ET_KeyRelease:
-            tempGrab.detail.exact = event->device_event.detail.key;
+            tempGrab->detail.exact = event->device_event.detail.key;
             break;
         case ET_ButtonPress:
         case ET_ButtonRelease:
-            tempGrab.detail.exact = event->device_event.detail.button;
+            tempGrab->detail.exact = event->device_event.detail.button;
             break;
         default:
-            tempGrab.detail.exact = 0;
+            tempGrab->detail.exact = 0;
             break;
     }
-    tempGrab.window = pWin;
-    tempGrab.device = device;
-    tempGrab.detail.pMask = NULL;
-    tempGrab.modifiersDetail.pMask = NULL;
-    tempGrab.next = NULL;
+    tempGrab->window = pWin;
+    tempGrab->device = device;
+    tempGrab->detail.pMask = NULL;
+    tempGrab->modifiersDetail.pMask = NULL;
+    tempGrab->next = NULL;
     for (; grab; grab = grab->next)
     {
 	DeviceIntPtr	gdev;
@@ -3711,29 +3717,29 @@ CheckPassiveGrabsOnWindow(
 
         if (gdev && gdev->key)
             xkbi= gdev->key->xkbInfo;
-	tempGrab.modifierDevice = grab->modifierDevice;
-        tempGrab.modifiersDetail.exact = xkbi ? xkbi->state.grab_mods : 0;
+        tempGrab->modifierDevice = grab->modifierDevice;
+        tempGrab->modifiersDetail.exact = xkbi ? xkbi->state.grab_mods : 0;
 
         /* Check for XI2 and XI grabs first */
-        tempGrab.type = GetXI2Type(event);
-        tempGrab.grabtype = GRABTYPE_XI2;
-        if (GrabMatchesSecond(&tempGrab, grab, FALSE))
+        tempGrab->type = GetXI2Type(event);
+        tempGrab->grabtype = GRABTYPE_XI2;
+        if (GrabMatchesSecond(tempGrab, grab, FALSE))
             match = XI2_MATCH;
 
         if (!match)
         {
-            tempGrab.grabtype = GRABTYPE_XI;
-            if ((tempGrab.type = GetXIType(event)) &&
-                (GrabMatchesSecond(&tempGrab, grab, FALSE)))
+            tempGrab->grabtype = GRABTYPE_XI;
+            if ((tempGrab->type = GetXIType(event)) &&
+                (GrabMatchesSecond(tempGrab, grab, FALSE)))
                 match = XI_MATCH;
         }
 
         /* Check for a core grab (ignore the device when comparing) */
         if (!match && checkCore)
         {
-            tempGrab.grabtype = GRABTYPE_CORE;
-            if ((tempGrab.type = GetCoreType(event)) &&
-                (GrabMatchesSecond(&tempGrab, grab, TRUE)))
+            tempGrab->grabtype = GRABTYPE_CORE;
+            if ((tempGrab->type = GetCoreType(event)) &&
+                (GrabMatchesSecond(tempGrab, grab, TRUE)))
                 match = CORE_MATCH;
         }
 
@@ -3761,7 +3767,7 @@ CheckPassiveGrabsOnWindow(
                Since XGrabDeviceButton requires to specify the
                modifierDevice explicitly, we don't override this choice.
                */
-            if (tempGrab.type < GenericEvent)
+            if (tempGrab->type < GenericEvent)
             {
                 grab->device = device;
                 grab->modifierDevice = GetMaster(device, MASTER_KEYBOARD);
@@ -3800,7 +3806,7 @@ CheckPassiveGrabsOnWindow(
         if (match & (XI_MATCH | CORE_MATCH))
         {
             event->device_event.corestate &= 0x1f00;
-            event->device_event.corestate |= tempGrab.modifiersDetail.exact &
+            event->device_event.corestate |= tempGrab->modifiersDetail.exact &
                                               (~0x1f00);
         }
 
@@ -3861,6 +3867,7 @@ CheckPassiveGrabsOnWindow(
         break;
     }
 
+    FreeGrab(tempGrab);
     return grab;
 #undef CORE_MATCH
 #undef XI_MATCH
@@ -5078,29 +5085,30 @@ GrabDevice(ClientPtr client, DeviceIntPtr dev,
 	*status = GrabFrozen;
     else
     {
-	GrabRec tempGrab;
+	GrabPtr tempGrab;
 
-        /* Otherwise segfaults happen on grabbed MPX devices */
-        memset(&tempGrab, 0, sizeof(GrabRec));
+	tempGrab = AllocGrab();
 
-        tempGrab.next = NULL;
-	tempGrab.window = pWin;
-	tempGrab.resource = client->clientAsMask;
-	tempGrab.ownerEvents = ownerEvents;
-	tempGrab.keyboardMode = keyboard_mode;
-	tempGrab.pointerMode = pointer_mode;
+	tempGrab->next = NULL;
+	tempGrab->window = pWin;
+	tempGrab->resource = client->clientAsMask;
+	tempGrab->ownerEvents = ownerEvents;
+	tempGrab->keyboardMode = keyboard_mode;
+	tempGrab->pointerMode = pointer_mode;
 	if (grabtype == GRABTYPE_CORE)
-	    tempGrab.eventMask = mask->core;
+	    tempGrab->eventMask = mask->core;
 	else if (grabtype == GRABTYPE_XI)
-	    tempGrab.eventMask = mask->xi;
+	    tempGrab->eventMask = mask->xi;
 	else
-	    memcpy(tempGrab.xi2mask, mask->xi2mask, sizeof(tempGrab.xi2mask));
-	tempGrab.device = dev;
-	tempGrab.cursor = cursor;
-	tempGrab.confineTo = confineTo;
-	tempGrab.grabtype = grabtype;
-	(*grabInfo->ActivateGrab)(dev, &tempGrab, time, FALSE);
+	    memcpy(tempGrab->xi2mask, mask->xi2mask, sizeof(tempGrab->xi2mask));
+	tempGrab->device = dev;
+	tempGrab->cursor = cursor;
+	tempGrab->confineTo = confineTo;
+	tempGrab->grabtype = grabtype;
+	(*grabInfo->ActivateGrab)(dev, tempGrab, time, FALSE);
 	*status = GrabSuccess;
+
+	FreeGrab(tempGrab);
     }
     return Success;
 }
@@ -5419,7 +5427,7 @@ ProcUngrabKey(ClientPtr client)
 {
     REQUEST(xUngrabKeyReq);
     WindowPtr pWin;
-    GrabRec tempGrab;
+    GrabPtr tempGrab;
     DeviceIntPtr keybd = PickKeyboard(client);
     int rc;
 
@@ -5441,21 +5449,27 @@ ProcUngrabKey(ClientPtr client)
 	client->errorValue = stuff->modifiers;
 	return BadValue;
     }
-    tempGrab.resource = client->clientAsMask;
-    tempGrab.device = keybd;
-    tempGrab.window = pWin;
-    tempGrab.modifiersDetail.exact = stuff->modifiers;
-    tempGrab.modifiersDetail.pMask = NULL;
-    tempGrab.modifierDevice = keybd;
-    tempGrab.type = KeyPress;
-    tempGrab.grabtype = GRABTYPE_CORE;
-    tempGrab.detail.exact = stuff->key;
-    tempGrab.detail.pMask = NULL;
-    tempGrab.next = NULL;
-
-    if (!DeletePassiveGrabFromList(&tempGrab))
-	return BadAlloc;
-    return Success;
+    tempGrab = AllocGrab();
+    if (!tempGrab)
+        return BadAlloc;
+    tempGrab->resource = client->clientAsMask;
+    tempGrab->device = keybd;
+    tempGrab->window = pWin;
+    tempGrab->modifiersDetail.exact = stuff->modifiers;
+    tempGrab->modifiersDetail.pMask = NULL;
+    tempGrab->modifierDevice = keybd;
+    tempGrab->type = KeyPress;
+    tempGrab->grabtype = GRABTYPE_CORE;
+    tempGrab->detail.exact = stuff->key;
+    tempGrab->detail.pMask = NULL;
+    tempGrab->next = NULL;
+
+    if (!DeletePassiveGrabFromList(tempGrab))
+        rc = BadAlloc;
+
+    FreeGrab(tempGrab);
+
+    return rc;
 }
 
 /**
@@ -5619,7 +5633,7 @@ ProcUngrabButton(ClientPtr client)
 {
     REQUEST(xUngrabButtonReq);
     WindowPtr pWin;
-    GrabRec tempGrab;
+    GrabPtr tempGrab;
     int rc;
     DeviceIntPtr ptr;
 
@@ -5636,21 +5650,26 @@ ProcUngrabButton(ClientPtr client)
 
     ptr = PickPointer(client);
 
-    tempGrab.resource = client->clientAsMask;
-    tempGrab.device = ptr;
-    tempGrab.window = pWin;
-    tempGrab.modifiersDetail.exact = stuff->modifiers;
-    tempGrab.modifiersDetail.pMask = NULL;
-    tempGrab.modifierDevice = GetMaster(ptr, MASTER_KEYBOARD);
-    tempGrab.type = ButtonPress;
-    tempGrab.detail.exact = stuff->button;
-    tempGrab.grabtype = GRABTYPE_CORE;
-    tempGrab.detail.pMask = NULL;
-    tempGrab.next = NULL;
-
-    if (!DeletePassiveGrabFromList(&tempGrab))
-	return BadAlloc;
-    return Success;
+    tempGrab = AllocGrab();
+    if (!tempGrab)
+        return BadAlloc;
+    tempGrab->resource = client->clientAsMask;
+    tempGrab->device = ptr;
+    tempGrab->window = pWin;
+    tempGrab->modifiersDetail.exact = stuff->modifiers;
+    tempGrab->modifiersDetail.pMask = NULL;
+    tempGrab->modifierDevice = GetMaster(ptr, MASTER_KEYBOARD);
+    tempGrab->type = ButtonPress;
+    tempGrab->detail.exact = stuff->button;
+    tempGrab->grabtype = GRABTYPE_CORE;
+    tempGrab->detail.pMask = NULL;
+    tempGrab->next = NULL;
+
+    if (!DeletePassiveGrabFromList(tempGrab))
+        rc = BadAlloc;
+
+    FreeGrab(tempGrab);
+    return rc;
 }
 
 /**
commit b0e9e2e32616d09c30a02b9d0ae9db0b13e150d1
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Nov 4 10:44:31 2011 +1000

    dix: add CopyGrab() function
    
    Not really needed at this point, but will be once touch support is added.
    Since grabs are now expected to be allocated/freed with AllocGrab and
    FreeGrab, CopyGrab must increase the refcount and duplicate the modifier
    masks. Until the callers are switched to use FreeGrab, this introduces
    memleaks.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 3c21a96..c1c296d 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1509,7 +1509,7 @@ ActivatePointerGrab(DeviceIntPtr mouse, GrabPtr grab,
 	grabinfo->grabTime = time;
     if (grab->cursor)
 	grab->cursor->refcnt++;
-    grabinfo->activeGrab = *grab;
+    CopyGrab(&grabinfo->activeGrab, grab);
     grabinfo->grab = &grabinfo->activeGrab;
     grabinfo->fromPassiveGrab = isPassive;
     grabinfo->implicitGrab = autoGrab & ImplicitGrabMask;
@@ -1586,7 +1586,7 @@ ActivateKeyboardGrab(DeviceIntPtr keybd, GrabPtr grab, TimeStamp time, Bool pass
 	grabinfo->grabTime = syncEvents.time;
     else
 	grabinfo->grabTime = time;
-    grabinfo->activeGrab = *grab;
+    CopyGrab(&grabinfo->activeGrab, grab);
     grabinfo->grab = &grabinfo->activeGrab;
     grabinfo->fromPassiveGrab = passive;
     grabinfo->implicitGrab = passive & ImplicitGrabMask;
diff --git a/dix/grabs.c b/dix/grabs.c
index 3b07186..a1d56c5 100644
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@ -246,6 +246,40 @@ FreeGrab(GrabPtr pGrab)
     free(pGrab);
 }
 
+Bool
+CopyGrab(GrabPtr dst, const GrabPtr src)
+{
+    Mask *mdetails_mask = NULL;
+    Mask *details_mask = NULL;
+
+    if (src->cursor)
+        src->cursor->refcnt++;
+
+    if (src->modifiersDetail.pMask) {
+        int len = MasksPerDetailMask * sizeof(Mask);
+        mdetails_mask = malloc(len);
+        if (!mdetails_mask)
+            return FALSE;
+        memcpy(mdetails_mask, src->modifiersDetail.pMask, len);
+    }
+
+    if (src->detail.pMask) {
+        int len = MasksPerDetailMask * sizeof(Mask);
+        details_mask = malloc(len);
+        if (!details_mask) {
+            free(mdetails_mask);
+            return FALSE;
+        }
+        memcpy(details_mask, src->detail.pMask, len);
+    }
+
+    *dst = *src;
+    dst->modifiersDetail.pMask = mdetails_mask;
+    dst->detail.pMask = details_mask;
+
+    return TRUE;
+}
+
 int
 DeletePassiveGrab(pointer value, XID id)
 {
diff --git a/include/dixgrabs.h b/include/dixgrabs.h
index 2ed8a54..65ff45d 100644
--- a/include/dixgrabs.h
+++ b/include/dixgrabs.h
@@ -33,6 +33,7 @@ extern void UngrabAllDevices(Bool kill_client);
 
 extern GrabPtr AllocGrab(void);
 extern void FreeGrab(GrabPtr grab);
+extern Bool CopyGrab(GrabPtr dst, const GrabPtr src);
 
 extern GrabPtr CreateGrab(
 	int /* client */,
commit 347f377f3b3f8c9d230d6309ec8ae92aa86d78b7
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Nov 3 16:12:09 2011 +1000

    dix: add AllocGrab helper function
    
    Not needed since the GrabRec is a self-contained struct but will be needed
    for the xi2 input mask rework.
    FreeGrab already exists, make it available to other callers.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/grabs.c b/dix/grabs.c
index c28356d..3b07186 100644
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@ -181,6 +181,14 @@ UngrabAllDevices(Bool kill_client)
 }
 
 GrabPtr
+AllocGrab(void)
+{
+    GrabPtr grab = calloc(1, sizeof(GrabRec));
+
+    return grab;
+}
+
+GrabPtr
 CreateGrab(
     int client,
     DeviceIntPtr device,
@@ -196,7 +204,7 @@ CreateGrab(
 {
     GrabPtr grab;
 
-    grab = calloc(1, sizeof(GrabRec));
+    grab = AllocGrab();
     if (!grab)
 	return (GrabPtr)NULL;
     grab->resource = FakeClientID(client);
@@ -226,7 +234,7 @@ CreateGrab(
 
 }
 
-static void
+void
 FreeGrab(GrabPtr pGrab)
 {
     free(pGrab->modifiersDetail.pMask);
diff --git a/include/dixgrabs.h b/include/dixgrabs.h
index 229c8bb..2ed8a54 100644
--- a/include/dixgrabs.h
+++ b/include/dixgrabs.h
@@ -31,6 +31,9 @@ struct _GrabParameters;
 extern void PrintDeviceGrabInfo(DeviceIntPtr dev);
 extern void UngrabAllDevices(Bool kill_client);
 
+extern GrabPtr AllocGrab(void);
+extern void FreeGrab(GrabPtr grab);
+
 extern GrabPtr CreateGrab(
 	int /* client */,
 	DeviceIntPtr /* device */,
commit 7af23259d88f4c28ed21140f82cc03b3724c06bb
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Nov 21 11:41:12 2011 -0800

    dix: switch the syncEvent queue to a struct list
    
    No effective functionality change, just cleanup to make this code slightly
    more sane.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 4847db0..3c21a96 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1132,12 +1132,14 @@ NoticeEventTime(InternalEvent *ev)
 void
 EnqueueEvent(InternalEvent *ev, DeviceIntPtr device)
 {
-    QdEventPtr	tail = *syncEvents.pendtail;
+    QdEventPtr	tail;
     QdEventPtr	qe;
     SpritePtr	pSprite = device->spriteInfo->sprite;
     int		eventlen;
     DeviceEvent *event = &ev->device_event;
 
+    tail = list_last_entry(&syncEvents.pending, QdEventRec, next);
+
     NoticeTime((InternalEvent*)event);
 
     /* Fix for key repeating bug. */
@@ -1196,15 +1198,13 @@ EnqueueEvent(InternalEvent *ev, DeviceIntPtr device)
     qe = malloc(sizeof(QdEventRec) + eventlen);
     if (!qe)
 	return;
-    qe->next = (QdEventPtr)NULL;
+    list_init(&qe->next);
     qe->device = device;
     qe->pScreen = pSprite->hotPhys.pScreen;
     qe->months = currentTime.months;
     qe->event = (InternalEvent *)(qe + 1);
     memcpy(qe->event, event, eventlen);
-    if (tail)
-	syncEvents.pendtail = &tail->next;
-    *syncEvents.pendtail = qe;
+    list_append(&qe->next, &syncEvents.pending);
 }
 
 /**
@@ -1216,22 +1216,20 @@ EnqueueEvent(InternalEvent *ev, DeviceIntPtr device)
  * If there is none, we're done. If there is at least one device that is not
  * frozen, then re-run from the beginning of the event queue.
  */
-static void
+void
 PlayReleasedEvents(void)
 {
-    QdEventPtr *prev, qe;
+    QdEventPtr tmp;
+    QdEventPtr qe;
     DeviceIntPtr dev;
     DeviceIntPtr pDev;
 
-    prev = &syncEvents.pending;
-    while ( (qe = *prev) )
-    {
+restart:
+    list_for_each_entry_safe(qe, tmp, &syncEvents.pending, next) {
 	if (!qe->device->deviceGrab.sync.frozen)
 	{
-	    *prev = qe->next;
-            pDev = qe->device;
-	    if (*syncEvents.pendtail == *prev)
-		syncEvents.pendtail = prev;
+	    list_del(&qe->next);
+	    pDev = qe->device;
 	    if (qe->event->any.type == ET_Motion)
 		CheckVirtualMotion(pDev, qe, NullWindow);
 	    syncEvents.time.months = qe->months;
@@ -1268,12 +1266,11 @@ PlayReleasedEvents(void)
 		;
 	    if (!dev)
 		break;
+
 	    /* Playing the event may have unfrozen another device. */
 	    /* So to play it safe, restart at the head of the queue */
-	    prev = &syncEvents.pending;
+	    goto restart;
 	}
-	else
-	    prev = &qe->next;
     }
 }
 
@@ -1314,7 +1311,8 @@ ComputeFreezes(void)
     for (dev = inputInfo.devices; dev; dev = dev->next)
 	FreezeThaw(dev, dev->deviceGrab.sync.other ||
                 (dev->deviceGrab.sync.state >= FROZEN));
-    if (syncEvents.playingEvents || (!replayDev && !syncEvents.pending))
+    if (syncEvents.playingEvents ||
+        (!replayDev && list_is_empty(&syncEvents.pending)))
 	return;
     syncEvents.playingEvents = TRUE;
     if (replayDev)
@@ -5258,6 +5256,7 @@ void
 InitEvents(void)
 {
     int i;
+    QdEventPtr qe, tmp;
 
     inputInfo.numDevices = 0;
     inputInfo.devices = (DeviceIntPtr)NULL;
@@ -5271,13 +5270,10 @@ InitEvents(void)
 
     syncEvents.replayDev = (DeviceIntPtr)NULL;
     syncEvents.replayWin = NullWindow;
-    while (syncEvents.pending)
-    {
-	QdEventPtr next = syncEvents.pending->next;
-	free(syncEvents.pending);
-	syncEvents.pending = next;
-    }
-    syncEvents.pendtail = &syncEvents.pending;
+    if (syncEvents.pending.next)
+        list_for_each_entry_safe(qe, tmp, &syncEvents.pending, next)
+            free(qe);
+    list_init(&syncEvents.pending);
     syncEvents.playingEvents = FALSE;
     syncEvents.time.months = 0;
     syncEvents.time.milliseconds = 0;	/* hardly matters */
diff --git a/include/dix.h b/include/dix.h
index 34661f3..8e35d2c 100644
--- a/include/dix.h
+++ b/include/dix.h
@@ -339,6 +339,7 @@ extern _X_EXPORT void NoticeEventTime(InternalEvent *ev);
 extern void EnqueueEvent(
     InternalEvent * /* ev */,
     DeviceIntPtr  /* device */);
+extern void PlayReleasedEvents(void);
 
 extern void ActivatePointerGrab(
     DeviceIntPtr /* mouse */,
diff --git a/include/inputstr.h b/include/inputstr.h
index f482a22..0568e0c 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -575,7 +575,7 @@ extern _X_EXPORT InputInfo inputInfo;
 /* for keeping the events for devices grabbed synchronously */
 typedef struct _QdEvent *QdEventPtr;
 typedef struct _QdEvent {
-    QdEventPtr		next;
+    struct list		next;
     DeviceIntPtr	device;
     ScreenPtr		pScreen;	/* what screen the pointer was on */
     unsigned long	months;		/* milliseconds is in the event */
@@ -591,8 +591,8 @@ typedef struct _QdEvent {
  * replayed and processed as if they would come from the device directly.
  */
 typedef struct _EventSyncInfo {
-    QdEventPtr          pending, /**<  list of queued events */
-                        *pendtail; /**< last event in list */
+    struct list         pending;
+
     /** The device to replay events for. Only set in AllowEvents(), in which
      * case it is set to the device specified in the request. */
     DeviceIntPtr        replayDev;      /* kludgy rock to put flag for */
diff --git a/test/input.c b/test/input.c
index 5b4c8c1..c44e5f6 100644
--- a/test/input.c
+++ b/test/input.c
@@ -1674,8 +1674,75 @@ mieq_test(void) {
     mieqFini();
 }
 
+/* Simple check that we're replaying events in-order */
+static void
+process_input_proc(InternalEvent *ev, DeviceIntPtr device)
+{
+    static int last_evtype = -1;
+
+    if (ev->any.header == 0xac)
+        last_evtype = -1;
+
+    assert(ev->any.type == ++last_evtype);
+}
+
+static void
+dix_enqueue_events(void) {
+#define NEVENTS 5
+    DeviceIntRec dev;
+    InternalEvent ev[NEVENTS];
+    SpriteInfoRec spriteInfo;
+    SpriteRec sprite;
+    QdEventPtr qe;
+    int i;
+
+    memset(&dev, 0, sizeof(dev));
+    dev.public.processInputProc = process_input_proc;
+
+    memset(&spriteInfo, 0, sizeof(spriteInfo));
+    memset(&sprite, 0, sizeof(sprite));
+    dev.spriteInfo = &spriteInfo;
+    spriteInfo.sprite = &sprite;
+
+    InitEvents();
+    assert(list_is_empty(&syncEvents.pending));
+
+    /* this way PlayReleasedEvents really runs through all events in the
+     * queue */
+    inputInfo.devices = &dev;
+
+    /* to reset process_input_proc */
+    ev[0].any.header = 0xac;
+
+    for (i = 0; i < NEVENTS; i++)
+    {
+        ev[i].any.length = sizeof(*ev);
+        ev[i].any.type = i;
+        EnqueueEvent(&ev[i], &dev);
+        assert(!list_is_empty(&syncEvents.pending));
+        qe = list_last_entry(&syncEvents.pending, QdEventRec, next);
+        assert(memcmp(qe->event, &ev[i], ev[i].any.length) == 0);
+        qe = list_first_entry(&syncEvents.pending, QdEventRec, next);
+        assert(memcmp(qe->event, &ev[0], ev[i].any.length) == 0);
+    }
+
+    /* calls process_input_proc */
+    dev.deviceGrab.sync.frozen = 1;
+    PlayReleasedEvents();
+    assert(!list_is_empty(&syncEvents.pending));
+
+
+    dev.deviceGrab.sync.frozen = 0;
+    PlayReleasedEvents();
+    assert(list_is_empty(&syncEvents.pending));
+
+    inputInfo.devices = NULL;
+}
+
+
 int main(int argc, char** argv)
 {
+    dix_enqueue_events();
     dix_double_fp_conversion();
     dix_input_valuator_masks();
     dix_input_attributes();
commit 6369b59668613e51131857fbaeaa393a65a73048
Author: Gaetan Nadon <memsize at videotron.ca>
Date:   Thu Dec 1 16:24:32 2011 -0500

    test: update .gitignore with xfree86 and sort alphabetically
    
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Signed-off-by: Gaetan Nadon <memsize at videotron.ca>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/test/.gitignore b/test/.gitignore
index 7dcad36..e5aa9ec 100644
--- a/test/.gitignore
+++ b/test/.gitignore
@@ -1,7 +1,8 @@
-xkb
+fixes
 input
-xtest
 list
 misc
-fixes
 string
+xfree86
+xkb
+xtest
commit 3ab8ee32470f7cf1223e04238bb8c5f74ed52fc3
Merge: 22a666f 98c4a88
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Dec 7 12:42:17 2011 -0800

    Merge remote-tracking branch 'airlied/reviewed-fixes'

commit 22a666f9952feb7248e9bb2faf777edaaac8175f
Merge: 3824f55 e89b032
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Dec 7 12:27:23 2011 -0800

    Merge remote-tracking branch 'alanc/master'

commit 3824f558cc2ee051da8314c7bf08b8647b44e84a
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Dec 7 12:13:37 2011 -0800

    hw/xfree86: fix segfault in config parser when config dir is missing
    
    Treat a scandir error from a missing (or unusable) directory return as
    if it simply returned no files at all, which is what we want.
    
    cc: Paulo Zanoni <przanoni at gmail.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/parser/scan.c b/hw/xfree86/parser/scan.c
index 9099227..156bc29 100644
--- a/hw/xfree86/parser/scan.c
+++ b/hw/xfree86/parser/scan.c
@@ -852,6 +852,10 @@ OpenConfigDir(const char *path, const char *cmdline, const char *projroot,
 
 		/* match files named *.conf */
 		num = scandir(dirpath, &list, ConfigFilter, alphasort);
+		if (num < 0) {
+			list = NULL;
+			num = 0;
+		}
 		found = AddConfigDirFiles(dirpath, list, num);
 		if (!found) {
 			free(dirpath);
commit 98c4a888a4428789386c7c47cecc81933b5999ba
Author: Dave Airlie <airlied at redhat.com>
Date:   Mon Nov 28 16:37:59 2011 +0000

    kdrive: drop screen crossing code.
    
    The only kdrive server we probably care about anymore is Xephyr,
    and this screen enable/disable code totally breaks it in multi-screen mode.
    
    When you are in one screen the other stops updating.
    
    Fixes https://bugzilla.redhat.com/show_bug.cgi?id=757457
    
    Signed-off-by: Dave Airlie <airlied at redhat.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/kdrive/src/kinput.c b/hw/kdrive/src/kinput.c
index 9c0b34f..968ebb1 100644
--- a/hw/kdrive/src/kinput.c
+++ b/hw/kdrive/src/kinput.c
@@ -2146,12 +2146,6 @@ KdCursorOffScreen(ScreenPtr *ppScreen, int *x, int *y)
 static void
 KdCrossScreen(ScreenPtr pScreen, Bool entering)
 {
-#ifndef XIPAQ
-    if (entering)
-	KdEnableScreen (pScreen);
-    else
-	KdDisableScreen (pScreen);
-#endif
 }
 
 int KdCurScreen;	/* current event screen */
commit 8d3731a811e33e263920dd7c8ec63d02968cb56e
Author: Dave Airlie <airlied at redhat.com>
Date:   Thu Oct 20 10:48:26 2011 +0100

    hal: free tmp_val in one missing case
    
    Pointed out by coverity scan.
    
    Signed-off-by: Dave Airlie <airlied at redhat.com>
    Reviewed-by: Daniel Stone <daniel at fooishbar.org>

diff --git a/config/hal.c b/config/hal.c
index aa234eb..088c993 100644
--- a/config/hal.c
+++ b/config/hal.c
@@ -348,6 +348,7 @@ device_added(LibHalContext *hal_ctx, const char *udi)
                         if (!strcasecmp(tmp, ".options") && (!xkb_opts.options))
                             xkb_opts.options = strdup(tmp_val);
                     }
+                    free(tmp_val);
                 }
             }
         }
commit 41229392b790f30a0f0ef1f4ed95647c5bca4001
Author: Dave Airlie <airlied at redhat.com>
Date:   Thu Oct 20 11:00:43 2011 +0100

    xv: test correct number of requests. (v2)
    
    Pointed out by coverity.
    
    v2: fix swapped as well, as pointed out by Alan
    
    Signed-off-by: Dave Airlie <airlied at redhat.com>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/Xext/xvdisp.c b/Xext/xvdisp.c
index 364a90c..0795a14 100644
--- a/Xext/xvdisp.c
+++ b/Xext/xvdisp.c
@@ -1238,7 +1238,7 @@ ProcXvDispatch(ClientPtr client)
 
   UpdateCurrentTime();
 
-  if (stuff->data > xvNumRequests) {
+  if (stuff->data >= xvNumRequests) {
     SendErrorToClient(client, XvReqCode, stuff->data, 0, BadRequest);
     return BadRequest;
   }
@@ -1542,7 +1542,7 @@ SProcXvDispatch(ClientPtr client)
 
   UpdateCurrentTime();
 
-  if (stuff->data > xvNumRequests) {
+  if (stuff->data >= xvNumRequests) {
     SendErrorToClient(client, XvReqCode, stuff->data, 0, BadRequest);
     return BadRequest;
   }
commit 1049139499d9132a20cd6d4d156fe9da9cddb6c2
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Oct 19 16:57:13 2011 +0100

    xaa: avoid possible freed pointer reuse in epilogue
    
    If the pGCPriv->flags == 2, then we try to assign the freed pGCPriv->XAAOps
    avoid this by clearing the flags in to be destroyed pGCPriv.
    
    Reported by coverity.
    
    Signed-off-by: Dave Airlie <airlied at redhat.com>
    Reviewed-by: Jeremy Huddleston <jeremyhu at apple.com>

diff --git a/hw/xfree86/xaa/xaaGC.c b/hw/xfree86/xaa/xaaGC.c
index 44d50e6..1bc35d9 100644
--- a/hw/xfree86/xaa/xaaGC.c
+++ b/hw/xfree86/xaa/xaaGC.c
@@ -239,6 +239,7 @@ XAADestroyGC(GCPtr pGC)
 	free(pGCPriv->XAAOps);
 
     free(pGCPriv->DashPattern);
+    pGCPriv->flags = 0;
 
     (*pGC->funcs->DestroyGC)(pGC);
     XAA_GC_FUNC_EPILOGUE (pGC);
commit 682c09a2cedd234b005334cc01247d859dd7f26a
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Oct 19 16:22:31 2011 +0100

    Xi: avoid overrun of callback array.
    
    This code had an off-by-one and would allow writing one past the end of
    the callbacks array.
    
    Pointed out by coverity.
    
    Signed-off-by: Dave Airlie <airlied at redhat.com>
    Reviewed-by: Jeremy Huddleston <jeremyhu at apple.com>

diff --git a/Xi/extinit.c b/Xi/extinit.c
index a2c807b..b43f9bb 100644
--- a/Xi/extinit.c
+++ b/Xi/extinit.c
@@ -409,7 +409,7 @@ static int
 ProcIDispatch(ClientPtr client)
 {
     REQUEST(xReq);
-    if (stuff->data > ARRAY_SIZE(ProcIVector) || !ProcIVector[stuff->data])
+    if (stuff->data >= ARRAY_SIZE(ProcIVector) || !ProcIVector[stuff->data])
         return BadRequest;
 
     return (*ProcIVector[stuff->data])(client);
@@ -428,7 +428,7 @@ static int
 SProcIDispatch(ClientPtr client)
 {
     REQUEST(xReq);
-    if (stuff->data > ARRAY_SIZE(SProcIVector) || !SProcIVector[stuff->data])
+    if (stuff->data >= ARRAY_SIZE(SProcIVector) || !SProcIVector[stuff->data])
         return BadRequest;
 
     return (*SProcIVector[stuff->data])(client);
commit b62dc4fcbcffd10de16650bee284702c8608bb60
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Oct 19 16:21:26 2011 +0100

    xext: don't free uninitialised pointer when malloc fails. (v2)
    
    Initialise the pAttr->values to values so if the values allocation
    fails it just ends up as free(NULL).
    
    Pointed out by coverity.
    
    v2: use Alan's suggestion.
    
    Signed-off-by: Dave Airlie <airlied at redhat.com>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jeremy Huddleston <jeremyhu at apple.com>

diff --git a/Xext/saver.c b/Xext/saver.c
index 142758c..18d5e46 100644
--- a/Xext/saver.c
+++ b/Xext/saver.c
@@ -925,7 +925,7 @@ ScreenSaverSetAttributes (ClientPtr client)
 	goto bail;
     }
     /* over allocate for override redirect */
-    values = malloc((len + 1) * sizeof (unsigned long));
+    pAttr->values = values = malloc((len + 1) * sizeof (unsigned long));
     if (!values)
     {
 	ret = BadAlloc;
@@ -945,7 +945,6 @@ ScreenSaverSetAttributes (ClientPtr client)
     pAttr->pCursor = NullCursor;
     pAttr->pBackgroundPixmap = NullPixmap;
     pAttr->pBorderPixmap = NullPixmap;
-    pAttr->values = values;
     /*
      * go through the mask, checking the values,
      * looking up pixmaps and cursors and hold a reference
commit 22605effd188436629a0dbc688666549473741e4
Author: Adam Jackson <ajax at redhat.com>
Date:   Thu Apr 28 13:34:28 2011 +1000

    fbdevhw: iterate over all modes that match a mode. (v3)
    
    So on RHEL5 anaconda sets an xorg.conf with a fixed 800x600 mode in it,
    we run radeonfb and fbdev since ati won't work in userspace due to domain
    issues in the older codebase.
    
    On certain pseries blades the built-in KVM can't accept an 800x600-43 mode,
    it requires the 800x600-60 mode, so we have to have the kernel radeonfb
    driver reject the 800x600-43 mode when it sees it. However then fbdev
    doesn't try any of the other 800x600 modes in the modelist, and we end up
    getting a default 640x480 mode we don't want.
    
    This patch changes the mode validation loop to continue on with the other modes
    that match to find one that works.
    
    v2: move code around to avoid extra loop, after comment from Jamey.
    v3: move loop setup back into loop as per Jeremy's review.
    
    Signed-off-by: Dave Airlie <airlied at redhat.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Jeremy Huddleston <jeremyhu at apple.com>

diff --git a/hw/xfree86/fbdevhw/fbdevhw.c b/hw/xfree86/fbdevhw/fbdevhw.c
index 2019741..309fa65 100644
--- a/hw/xfree86/fbdevhw/fbdevhw.c
+++ b/hw/xfree86/fbdevhw/fbdevhw.c
@@ -506,20 +506,22 @@ fbdevHWSetVideoModes(ScrnInfoPtr pScrn)
 	pScrn->virtualY = pScrn->display->virtualY;
 
 	for (modename = pScrn->display->modes; *modename != NULL; modename++) {
-		for (mode = pScrn->monitor->Modes; mode != NULL; mode = mode->next)
-			if (0 == strcmp(mode->name,*modename))
-				break;
+		for (mode = pScrn->monitor->Modes; mode != NULL; mode = mode->next) {
+			if (0 == strcmp(mode->name,*modename)) {
+				if (fbdevHWSetMode(pScrn, mode, TRUE))
+					break;
+
+				xf86DrvMsg(pScrn->scrnIndex, X_INFO,
+					   "\tmode \"%s\" test failed\n", *modename);
+			}
+		}
+
 		if (NULL == mode) {
 			xf86DrvMsg(pScrn->scrnIndex, X_INFO,
 				   "\tmode \"%s\" not found\n", *modename);
 			continue;
 		}
 
-		if (!fbdevHWSetMode(pScrn, mode, TRUE)) {
-			xf86DrvMsg(pScrn->scrnIndex, X_INFO,
-				   "\tmode \"%s\" test failed\n", *modename);
-			continue;
-		}
 		xf86DrvMsg(pScrn->scrnIndex, X_INFO,
 			   "\tmode \"%s\" ok\n", *modename);
 
commit fac464e310b82fadcedf790798d1016c4805640b
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Dec 2 08:52:53 2011 +1000

    include: rename "foos" to "list_of_foos" in the struct list documentation
    
    Makes things a little easier to read.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/include/list.h b/include/list.h
index 77cc5f9..6ec2bac 100644
--- a/include/list.h
+++ b/include/list.h
@@ -36,16 +36,16 @@
  *
  *     struct bar {
  *          ...
- *          struct foo *foos; -----> struct foo {}, struct foo {}, struct foo{}
+ *          struct foo *list_of_foos; -----> struct foo {}, struct foo {}, struct foo{}
  *          ...
  *     }
  *
- * We need one list head in bar and a list element in all foos (both are of
+ * We need one list head in bar and a list element in all list_of_foos (both are of
  * data type 'struct list').
  *
  *     struct bar {
  *          ...
- *          struct list foos;
+ *          struct list list_of_foos;
  *          ...
  *     }
  *
@@ -59,27 +59,27 @@
  *
  *     struct bar bar;
  *     ...
- *     list_init(&bar.foos);
+ *     list_init(&bar.list_of_foos);
  *
  * Then we create the first element and add it to this list:
  *
  *     struct foo *foo = malloc(...);
  *     ....
- *     list_add(&foo->entry, &bar.foos);
+ *     list_add(&foo->entry, &bar.list_of_foos);
  *
  * Repeat the above for each element you want to add to the list. Deleting
  * works with the element itself.
  *      list_del(&foo->entry);
  *      free(foo);
  *
- * Note: calling list_del(&bar.foos) will set bar.foos to an empty
+ * Note: calling list_del(&bar.list_of_foos) will set bar.list_of_foos to an empty
  * list again.
  *
  * Looping through the list requires a 'struct foo' as iterator and the
  * name of the field the subnodes use.
  *
  * struct foo *iterator;
- * list_for_each_entry(iterator, &bar.foos, entry) {
+ * list_for_each_entry(iterator, &bar.list_of_foos, entry) {
  *      if (iterator->something == ...)
  *             ...
  * }
@@ -88,7 +88,7 @@
  * loop. You need to run the safe for-each loop instead:
  *
  * struct foo *iterator, *next;
- * list_for_each_entry_safe(iterator, next, &bar.foos, entry) {
+ * list_for_each_entry_safe(iterator, next, &bar.list_of_foos, entry) {
  *      if (...)
  *              list_del(&iterator->entry);
  * }
@@ -113,7 +113,7 @@ struct list {
  * Initialize the list as an empty list.
  *
  * Example:
- * list_init(&bar->foos);
+ * list_init(&bar->list_of_foos);
  *
  * @param The list to initialized.
  */
@@ -144,7 +144,7 @@ __list_add(struct list *entry,
  *
  * Example:
  * struct foo *newfoo = malloc(...);
- * list_add(&newfoo->entry, &bar->foos);
+ * list_add(&newfoo->entry, &bar->list_of_foos);
  *
  * @param entry The new element to prepend to the list.
  * @param head The existing list.
@@ -165,7 +165,7 @@ list_add(struct list *entry, struct list *head)
  *
  * Example:
  * struct foo *newfoo = malloc(...);
- * list_append(&newfoo->entry, &bar->foos);
+ * list_append(&newfoo->entry, &bar->list_of_foos);
  *
  * @param entry The new element to prepend to the list.
  * @param head The existing list.
@@ -209,7 +209,7 @@ list_del(struct list *entry)
  * Check if the list is empty.
  *
  * Example:
- * list_is_empty(&bar->foos);
+ * list_is_empty(&bar->list_of_foos);
  *
  * @return True if the list contains one or more elements or False otherwise.
  */
@@ -248,7 +248,7 @@ list_is_empty(struct list *head)
  *
  * Example:
  * struct foo *first;
- * first = list_first_entry(&bar->foos, struct foo, foos);
+ * first = list_first_entry(&bar->list_of_foos, struct foo, list_of_foos);
  *
  * @param ptr The list head
  * @param type Data type of the list element to retrieve
@@ -263,7 +263,7 @@ list_is_empty(struct list *head)
  *
  * Example:
  * struct foo *first;
- * first = list_last_entry(&bar->foos, struct foo, foos);
+ * first = list_last_entry(&bar->list_of_foos, struct foo, list_of_foos);
  *
  * @param ptr The list head
  * @param type Data type of the list element to retrieve
@@ -281,7 +281,7 @@ list_is_empty(struct list *head)
  *
  * Example:
  * struct foo *iterator;
- * list_for_each_entry(iterator, &bar->foos, entry) {
+ * list_for_each_entry(iterator, &bar->list_of_foos, entry) {
  *      [modify iterator]
  * }
  *
commit 7dfe8c32a96d3f96c8aaeb2802f5b122e381a1e4
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Dec 2 08:51:24 2011 +1000

    include: update struct list documentation to use one set of structs only
    
    The example at the top of the file used a struct bar and a list of struct
    foos. Use those two throughout instead of a different struct foo for the
    examples and for the API documentation.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/include/list.h b/include/list.h
index 677fd92..77cc5f9 100644
--- a/include/list.h
+++ b/include/list.h
@@ -97,14 +97,8 @@
 
 /**
  * The linkage struct for list nodes. This struct must be part of your
- * to-be-linked struct.
- *
- * Example:
- * struct foo {
- *      int a;
- *      void *b;
- *      struct list *mylist;
- * }
+ * to-be-linked struct. struct list is required for both the head of the
+ * list and for each list node.
  *
  * Position and name of the struct list field is irrelevant.
  * There are no requirements that elements of a list are of the same type.
@@ -119,7 +113,7 @@ struct list {
  * Initialize the list as an empty list.
  *
  * Example:
- * list_init(&foo->mylist);
+ * list_init(&bar->foos);
  *
  * @param The list to initialized.
  */
@@ -150,7 +144,7 @@ __list_add(struct list *entry,
  *
  * Example:
  * struct foo *newfoo = malloc(...);
- * list_add(&newfoo->mylist, &foo->mylist);
+ * list_add(&newfoo->entry, &bar->foos);
  *
  * @param entry The new element to prepend to the list.
  * @param head The existing list.
@@ -171,7 +165,7 @@ list_add(struct list *entry, struct list *head)
  *
  * Example:
  * struct foo *newfoo = malloc(...);
- * list_append(&newfoo->mylist, &foo->mylist);
+ * list_append(&newfoo->entry, &bar->foos);
  *
  * @param entry The new element to prepend to the list.
  * @param head The existing list.
@@ -200,7 +194,7 @@ __list_del(struct list *prev, struct list *next)
  * the list but rather reset the list as empty list.
  *
  * Example:
- * list_del(&newfoo->mylist);
+ * list_del(&foo->entry);
  *
  * @param entry The element to remove.
  */
@@ -215,7 +209,7 @@ list_del(struct list *entry)
  * Check if the list is empty.
  *
  * Example:
- * list_is_empty(&foo->mylist);
+ * list_is_empty(&bar->foos);
  *
  * @return True if the list contains one or more elements or False otherwise.
  */
@@ -230,7 +224,7 @@ list_is_empty(struct list *head)
  *
  * Example:
  * struct foo* f;
- * f = container_of(&foo->mylist, struct foo, mylist);
+ * f = container_of(&foo->entry, struct foo, entry);
  * assert(f == foo);
  *
  * @param ptr Pointer to the struct list.
@@ -254,7 +248,7 @@ list_is_empty(struct list *head)
  *
  * Example:
  * struct foo *first;
- * first = list_first_entry(&foo->mylist, struct foo, mylist);
+ * first = list_first_entry(&bar->foos, struct foo, foos);
  *
  * @param ptr The list head
  * @param type Data type of the list element to retrieve
@@ -269,7 +263,7 @@ list_is_empty(struct list *head)
  *
  * Example:
  * struct foo *first;
- * first = list_last_entry(&foo->mylist, struct foo, mylist);
+ * first = list_last_entry(&bar->foos, struct foo, foos);
  *
  * @param ptr The list head
  * @param type Data type of the list element to retrieve
@@ -287,7 +281,7 @@ list_is_empty(struct list *head)
  *
  * Example:
  * struct foo *iterator;
- * list_for_each_entry(iterator, &foo->mylist, mylist) {
+ * list_for_each_entry(iterator, &bar->foos, entry) {
  *      [modify iterator]
  * }
  *
commit 18539c89eca8f6e272ead2b631365da530065ae7
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Dec 2 08:51:04 2011 +1000

    include: a new list element does not need initialization, state so
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/include/list.h b/include/list.h
index 733a579..677fd92 100644
--- a/include/list.h
+++ b/include/list.h
@@ -141,7 +141,8 @@ __list_add(struct list *entry,
 }
 
 /**
- * Insert a new element after the given list head.
+ * Insert a new element after the given list head. The new element does not
+ * need to be initialised as empty list.
  * The list changes from:
  *      head → some element → ...
  * to
commit 58dc73314b6508121ca094bbcf00612fe19ed69f
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Dec 2 08:43:45 2011 +1000

    include: point to the tests in list.c as examples
    
    Even with the documentation, the list.c tests are the best examples.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/include/list.h b/include/list.h
index 73ff0be..733a579 100644
--- a/include/list.h
+++ b/include/list.h
@@ -28,6 +28,7 @@
 
 /**
  * @file Classic doubly-link circular list implementation.
+ * For real usage examples of the linked list, see the file test/list.c
  *
  * Example:
  * We need to keep a list of struct foo in the parent struct bar, i.e. what
commit c8e451a8e719ba432bcfa8976774c07307087809
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Dec 1 14:12:11 2011 +1000

    include: add list_last_entry to get the tail of a list
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/include/list.h b/include/list.h
index f8659f0..73ff0be 100644
--- a/include/list.h
+++ b/include/list.h
@@ -262,6 +262,21 @@ list_is_empty(struct list *head)
 #define list_first_entry(ptr, type, member) \
     list_entry((ptr)->next, type, member)
 
+/**
+ * Retrieve the last list entry for the given listpointer.
+ *
+ * Example:
+ * struct foo *first;
+ * first = list_last_entry(&foo->mylist, struct foo, mylist);
+ *
+ * @param ptr The list head
+ * @param type Data type of the list element to retrieve
+ * @param member Member name of the struct list field in the list element.
+ * @return A pointer to the last list element.
+ */
+#define list_last_entry(ptr, type, member) \
+    list_entry((ptr)->prev, type, member)
+
 #define __container_of(ptr, sample, member)				\
     (void *)((char *)(ptr)						\
 	     - ((char *)&(sample)->member - (char *)(sample)))
diff --git a/test/list.c b/test/list.c
index b96182e..ffb85ef 100644
--- a/test/list.c
+++ b/test/list.c
@@ -103,14 +103,20 @@ test_list_append(void)
 
     c = list_first_entry(&parent.children, struct child, node);
     assert(memcmp(c, &child[0], sizeof(struct child)) == 0);
+    c = list_last_entry(&parent.children, struct child, node);
+    assert(memcmp(c, &child[0], sizeof(struct child)) == 0);
 
     list_append(&child[1].node, &parent.children);
     c = list_first_entry(&parent.children, struct child, node);
     assert(memcmp(c, &child[0], sizeof(struct child)) == 0);
+    c = list_last_entry(&parent.children, struct child, node);
+    assert(memcmp(c, &child[1], sizeof(struct child)) == 0);
 
     list_append(&child[2].node, &parent.children);
     c = list_first_entry(&parent.children, struct child, node);
     assert(memcmp(c, &child[0], sizeof(struct child)) == 0);
+    c = list_last_entry(&parent.children, struct child, node);
+    assert(memcmp(c, &child[2], sizeof(struct child)) == 0);
 
     i = 0;
     list_for_each_entry(c, &parent.children, node) {
commit 6acebf9e1298939593b942ec91ae9ec9e74faa19
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Dec 1 13:35:50 2011 +1000

    include: add list_append()
    
    The existing list_add() prepends to the list, but in some cases we need the
    list ordered in the way we append the elements.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/include/list.h b/include/list.h
index 4706e17..f8659f0 100644
--- a/include/list.h
+++ b/include/list.h
@@ -159,6 +159,28 @@ list_add(struct list *entry, struct list *head)
     __list_add(entry, head, head->next);
 }
 
+/**
+ * Append a new element to the end of the list given with this list head.
+ *
+ * The list changes from:
+ *      head → some element → ... → lastelement
+ * to
+ *      head → some element → ... → lastelement → new element
+ *
+ * Example:
+ * struct foo *newfoo = malloc(...);
+ * list_append(&newfoo->mylist, &foo->mylist);
+ *
+ * @param entry The new element to prepend to the list.
+ * @param head The existing list.
+ */
+static inline void
+list_append(struct list *entry, struct list *head)
+{
+    __list_add(entry, head->prev, head);
+}
+
+
 static inline void
 __list_del(struct list *prev, struct list *next)
 {
diff --git a/test/list.c b/test/list.c
index f7d7bff..b96182e 100644
--- a/test/list.c
+++ b/test/list.c
@@ -89,6 +89,36 @@ test_list_add(void)
 };
 
 static void
+test_list_append(void)
+{
+    struct parent parent = {0};
+    struct child child[3];
+    struct child *c;
+    int i;
+
+    list_init(&parent.children);
+
+    list_append(&child[0].node, &parent.children);
+    assert(!list_is_empty(&parent.children));
+
+    c = list_first_entry(&parent.children, struct child, node);
+    assert(memcmp(c, &child[0], sizeof(struct child)) == 0);
+
+    list_append(&child[1].node, &parent.children);
+    c = list_first_entry(&parent.children, struct child, node);
+    assert(memcmp(c, &child[0], sizeof(struct child)) == 0);
+
+    list_append(&child[2].node, &parent.children);
+    c = list_first_entry(&parent.children, struct child, node);
+    assert(memcmp(c, &child[0], sizeof(struct child)) == 0);
+
+    i = 0;
+    list_for_each_entry(c, &parent.children, node) {
+        assert(memcmp(c, &child[i++], sizeof(struct child)) == 0);
+    }
+};
+
+static void
 test_list_del(void)
 {
     struct parent parent = {0};
@@ -325,6 +355,7 @@ int main(int argc, char** argv)
 {
     test_list_init();
     test_list_add();
+    test_list_append();
     test_list_del();
     test_list_for_each();
 
commit e89b0324da89ba5c0ba64af1ef46a12b7f55f879
Author: Gaetan Nadon <memsize at videotron.ca>
Date:   Sat Dec 3 21:23:51 2011 -0500

    autoconf: the minimum required level for autoconf is 2.60
    
    The toolchain requirements are documented here:
    http://www.x.org/wiki/ModularDevelopersGuide#Required_Tools
    
    Note that autoconf features only found in versions later
    than 2.60 must not be used.
    
    Signed-off-by: Gaetan Nadon <memsize at videotron.ca>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/configure.ac b/configure.ac
index cd26a2b..e9043b6 100644
--- a/configure.ac
+++ b/configure.ac
@@ -25,7 +25,7 @@ dnl          an unwitting cast of miscellaneous others
 dnl
 dnl Process this file with autoconf to create configure.
 
-AC_PREREQ(2.57)
+AC_PREREQ(2.60)
 AC_INIT([xorg-server], 1.11.99.1, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
 RELEASE_DATE="2011-11-20"
 AC_CONFIG_SRCDIR([Makefile.am])
commit 427cb53fddf0c517d1fd1025a87b1104735edd2a
Author: Gaetan Nadon <memsize at videotron.ca>
Date:   Sat Dec 3 21:23:21 2011 -0500

    autoconf: remove redundant AC_PROG_MAKE_SET
    
    Already included during Automake initialization.
    
    After the patch, no change:
    configure:3893: checking whether make sets $(MAKE)
    configure:3915: result: yes
    
    Signed-off-by: Gaetan Nadon <memsize at videotron.ca>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/configure.ac b/configure.ac
index d019366..cd26a2b 100644
--- a/configure.ac
+++ b/configure.ac
@@ -76,7 +76,6 @@ AC_PROG_LN_S
 AC_LIBTOOL_WIN32_DLL
 AC_DISABLE_STATIC
 AC_PROG_LIBTOOL
-AC_PROG_MAKE_SET
 PKG_PROG_PKG_CONFIG
 AC_PROG_LEX
 AC_PROG_YACC
commit c19c55a93ab1bc6db56075ca34d6e1c3f522f622
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Fri Dec 2 00:09:07 2011 -0800

    Fix builds of Xnest & Xephyr with Solaris Studio compilers
    
    Required in order to build with Studio cc now that xorg-macros is
    setting -errwarn=E_FUNC_HAS_NO_RETURN_STMT since a bug in the Solaris
    system headers causes the noreturn attribute to not be correctly
    applied to the exit() prototype in <stdlib.h> when building with
    Studio instead of gcc.
    
    Otherwise compiler exits with errors:
    "Display.c", line 65: Function has no return statement : x_io_error_handler
    "hostx.c", line 341: Function has no return statement : x_io_error_handler
    
    Uses Studio-specific pragma instead of adding another exit() prototype
    with a noreturn attribute to avoid causing gcc to warn about having
    a redundant prototype for the exit() function.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Mikhail Gusarov <dottedmag at dottedmag.net>

diff --git a/hw/kdrive/ephyr/hostx.c b/hw/kdrive/ephyr/hostx.c
index 47a6681..ebe4e52 100644
--- a/hw/kdrive/ephyr/hostx.c
+++ b/hw/kdrive/ephyr/hostx.c
@@ -332,6 +332,11 @@ hostx_set_title (char *title)
   ephyrTitle = title;
 }
 
+#ifdef __SUNPRO_C
+/* prevent "Function has no return statement" error for x_io_error_handler */
+#pragma does_not_return(exit)
+#endif
+
 static int _X_NORETURN
 x_io_error_handler (Display *dpy) {
     ErrorF("Lost connection to X server: %s\n", strerror(errno));
diff --git a/hw/xnest/Display.c b/hw/xnest/Display.c
index 7acad75..3176b60 100644
--- a/hw/xnest/Display.c
+++ b/hw/xnest/Display.c
@@ -55,6 +55,11 @@ Pixmap xnestScreenSaverPixmap;
 XlibGC xnestBitmapGC;
 unsigned long xnestEventMask;
 
+#ifdef __SUNPRO_C
+/* prevent "Function has no return statement" error for x_io_error_handler */
+#pragma does_not_return(exit)
+#endif
+
 static int _X_NORETURN
 x_io_error_handler (Display *dpy) {
     ErrorF("Lost connection to X server: %s\n", strerror(errno));
commit e4dcf580f007d6adcf5b0c639865d7aaab1a319d
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Thu Dec 1 23:45:42 2011 -0800

    LoaderOpen returns either a valid pointer or NULL, so don't check for < 0
    
    Fixes Sun cc warning that was recently elevated to error by the
    stricter default CFLAGS changes to xorg-macros:
    
    "loadmod.c", line 914: improper pointer/integer combination: op "<"
    
    Should have been changed when commit ab7f057ce9df4e905b12 changed the
    LoaderOpen return type from int to void *.
    
    Changes log message when file is found but dlopen() fails from:
     (EE) LoadModule: Module dbe does not have a dbeModuleData data object.
     (EE) Failed to load module "dbe" (invalid module, 0)
    to:
     (EE) Failed to load module "dbe" (loader failed, 7)
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Adam Jackson <ajax at redhat.com>

diff --git a/hw/xfree86/loader/loadmod.c b/hw/xfree86/loader/loadmod.c
index c697d74..5b9f8d1 100644
--- a/hw/xfree86/loader/loadmod.c
+++ b/hw/xfree86/loader/loadmod.c
@@ -911,7 +911,7 @@ doLoadModule(const char *module, const char *path, const char **subdirlist,
 	goto LoadModule_fail;
     }
     ret->handle = LoaderOpen(found, errmaj, errmin);
-    if (ret->handle < 0)
+    if (ret->handle == NULL)
 	goto LoadModule_fail;
     ret->path = strdup(found);
 
commit 8b6a75009746db4b8e2e180210ac097e35136bcd
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Wed Nov 30 23:01:34 2011 -0800

    Fix gcc warnings about redundant declarations of fallback functions
    
    Ensure ffs, strndup, strlcat, etc. aren't defined by our headers
    if they're already defined in the system headers.
    
    This does export the HAVE_FFS, HAVE_STRNDUP, etc. definitions to drivers,
    but if you built the Xserver with a libc that had those, and then build
    the drivers with a less capable libc, you're going to have problems anyway,
    and this should solve some reported problems with conflicts between our
    strndup definition and gcc magic for it.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Adam Jackson <ajax at redhat.com>

diff --git a/hw/xfree86/xaa/xaaTables.c b/hw/xfree86/xaa/xaaTables.c
index c7fa28a..dbeb4a2 100644
--- a/hw/xfree86/xaa/xaaTables.c
+++ b/hw/xfree86/xaa/xaaTables.c
@@ -1,3 +1,6 @@
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
 #include "xaalocal.h"
 /*
  * This is a table of 24-bit values, indexed with an 8-bit byte value, then
diff --git a/include/dix.h b/include/dix.h
index 34661f3..f98c87b 100644
--- a/include/dix.h
+++ b/include/dix.h
@@ -529,7 +529,9 @@ extern _X_EXPORT void
 ScreenRestructured (ScreenPtr pScreen);
 #endif
 
+#ifndef HAVE_FFS
 extern _X_EXPORT int ffs(int i);
+#endif
 
 
 /*
diff --git a/include/xorg-server.h.in b/include/xorg-server.h.in
index b10b994..8086f32 100644
--- a/include/xorg-server.h.in
+++ b/include/xorg-server.h.in
@@ -37,6 +37,27 @@
 /* Support SHM */
 #undef HAS_SHM
 
+/* Define to 1 if you have the `ffs' function. */
+#undef HAVE_FFS
+
+/* Define to 1 if you have the `strcasecmp' function. */
+#undef HAVE_STRCASECMP
+
+/* Define to 1 if you have the `strcasestr' function. */
+#undef HAVE_STRCASESTR
+
+/* Define to 1 if you have the `strlcat' function. */
+#undef HAVE_STRLCAT
+
+/* Define to 1 if you have the `strlcpy' function. */
+#undef HAVE_STRLCPY
+
+/* Define to 1 if you have the `strncasecmp' function. */
+#undef HAVE_STRNCASECMP
+
+/* Define to 1 if you have the `strndup' function. */
+#undef HAVE_STRNDUP
+
 /* Support IPv6 for TCP connections */
 #undef IPv6
 
commit d829a7c5cb42c979b58f3547136df5b05d906423
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Wed Nov 30 22:20:09 2011 -0800

    Move to autoconf standard function name checks & defines
    
    Replace multiple methods of checking for functions with AC_CHECK_FUNCS
    Replace multiple methods of selecting fallback funcs with AC_REPLACE_FUNCS
    Replace HAS_* and NEED_* #defines with autogenerated HAVE_*
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Adam Jackson <ajax at redhat.com>
    Reviewed-by: Mikhail Gusarov <dottedmag at dottedmag.net>
    Reviewed-by: Gaetan Nadon <memsize at videotron.ca>

diff --git a/configure.ac b/configure.ac
index 7e4871f..d019366 100644
--- a/configure.ac
+++ b/configure.ac
@@ -213,31 +213,14 @@ AC_CHECK_FUNC([dlopen], [],
 AC_SUBST(DLOPEN_LIBS)
 
 dnl Checks for library functions.
-AC_CHECK_FUNCS([vsnprintf walkcontext backtrace \
-		getzoneid shmctl64 strcasestr ffs vasprintf])
-AC_CHECK_FUNCS([strndup], [HAVE_STRNDUP=yes], [HAVE_STRNDUP=no])
-AM_CONDITIONAL(NEED_STRNDUP, [test x$HAVE_STRNDUP = xno])
-dnl Old HAS_* names used in os/*.c.
-AC_CHECK_FUNC([getdtablesize],
-	AC_DEFINE(HAS_GETDTABLESIZE, 1, [Have the 'getdtablesize' function.]))
-AC_CHECK_FUNC([getifaddrs],
-	AC_DEFINE(HAS_GETIFADDRS, 1, [Have the 'getifaddrs' function.]))
-AC_CHECK_FUNC([getpeereid],
-	AC_DEFINE(HAS_GETPEEREID, 1, [Have the 'getpeereid' function.]))
-AC_CHECK_FUNC([getpeerucred],
-	AC_DEFINE(HAS_GETPEERUCRED, 1, [Have the 'getpeerucred' function.]))
-AC_CHECK_FUNC([strlcat], HAVE_STRLCAT=yes, HAVE_STRLCAT=no)
-AM_CONDITIONAL(NEED_STRLCAT, [test x$HAVE_STRLCAT = xno])	
-AC_CHECK_FUNC([strlcpy], AC_DEFINE(HAS_STRLCPY, 1, [Have the 'strlcpy' function]))
-
-AM_CONDITIONAL(NEED_VSNPRINTF, [test x$HAVE_VSNPRINTF = xno])
-
-dnl Check for mmap support for Xvfb
-AC_CHECK_FUNC([mmap], AC_DEFINE(HAS_MMAP, 1, [Have the 'mmap' function.]))
-
-dnl Find the math libary
+AC_CHECK_FUNCS([backtrace ffs \
+	getdtablesize getifaddrs getpeereid getpeerucred getzoneid \
+	mmap shmctl64 strncasecmp vasprintf vsnprintf walkcontext])
+AC_REPLACE_FUNCS([strcasecmp strcasestr strlcat strlcpy strndup])
+
+dnl Find the math libary, then check for cbrt function in it.
 AC_CHECK_LIB(m, sqrt)
-AC_CHECK_LIB(m, cbrt, AC_DEFINE(HAVE_CBRT, 1, [Have the 'cbrt' function]))
+AC_CHECK_FUNCS([cbrt])
 
 AC_CHECK_HEADERS([ndbm.h dbm.h rpcsvc/dbm.h])
 
@@ -1238,13 +1221,6 @@ XKB_LIB='$(top_builddir)/xkb/libxkb.la'
 XKB_STUB_LIB='$(top_builddir)/xkb/libxkbstubs.la'
 REQUIRED_MODULES="$REQUIRED_MODULES xkbfile"
 
-AC_CHECK_FUNC(strcasecmp, [], AC_DEFINE([NEED_STRCASECMP], 1,
-                                        [Do not have 'strcasecmp'.]))
-AC_CHECK_FUNC(strncasecmp, [], AC_DEFINE([NEED_STRNCASECMP], 1,
-                                        [Do not have 'strncasecmp'.]))
-AC_CHECK_FUNC(strcasestr, [], AC_DEFINE([NEED_STRCASESTR], 1,
-                                       [Do not have 'strcasestr'.]))
-
 PKG_CHECK_MODULES([XDMCP], [xdmcp], [have_libxdmcp="yes"], [have_libxdmcp="no"])
 if test "x$have_libxdmcp" = xyes; then
 	AC_CHECK_LIB(Xdmcp, XdmcpWrap, [have_xdmcpwrap="yes"], [have_xdmcpwrap="no"], [$XDMCP_LIBS])
diff --git a/hw/dmx/config/Makefile.am b/hw/dmx/config/Makefile.am
index 7518143..06588e7 100644
--- a/hw/dmx/config/Makefile.am
+++ b/hw/dmx/config/Makefile.am
@@ -21,10 +21,7 @@ BUILT_SOURCES = parser.c parser.h scanner.c
 MAINTAINERCLEANFILES = $(BUILT_SOURCES)
 
 libdmxconfig_a_SOURCES = $(LIBSRCS)
-
-if NEED_STRLCAT
 libdmxconfig_a_SOURCES += $(top_srcdir)/os/strlcpy.c
-endif
 
 if GLX
 GLX_DEFS = @GL_CFLAGS@
diff --git a/hw/vfb/InitOutput.c b/hw/vfb/InitOutput.c
index 9a9905d..e1af5a4 100644
--- a/hw/vfb/InitOutput.c
+++ b/hw/vfb/InitOutput.c
@@ -48,12 +48,12 @@ from The Open Group.
 #include "mipointer.h"
 #include "micmap.h"
 #include <sys/types.h>
-#ifdef HAS_MMAP
+#ifdef HAVE_MMAP
 #include <sys/mman.h>
 #ifndef MAP_FILE
 #define MAP_FILE 0
 #endif
-#endif /* HAS_MMAP */
+#endif /* HAVE_MMAP */
 #include <sys/stat.h>
 #include <errno.h>
 #ifndef WIN32
@@ -93,7 +93,7 @@ typedef struct
     unsigned int lineBias;
     CloseScreenProcPtr closeScreen;
 
-#ifdef HAS_MMAP
+#ifdef HAVE_MMAP
     int mmap_fd;
     char mmap_file[MAXPATHLEN];
 #endif
@@ -114,7 +114,7 @@ static vfbScreenInfo defaultScreenInfo = {
     .lineBias = VFB_DEFAULT_LINEBIAS,
 };
 static Bool vfbPixmapDepths[33];
-#ifdef HAS_MMAP
+#ifdef HAVE_MMAP
 static char *pfbdir = NULL;
 #endif
 typedef enum { NORMAL_MEMORY_FB, SHARED_MEMORY_FB, MMAPPED_FILE_FB } fbMemType;
@@ -158,7 +158,7 @@ ddxGiveUp(enum ExitCode error)
 
     switch (fbmemtype)
     {
-#ifdef HAS_MMAP
+#ifdef HAVE_MMAP
     case MMAPPED_FILE_FB: 
 	for (i = 0; i < vfbNumScreens; i++)
 	{
@@ -170,10 +170,10 @@ ddxGiveUp(enum ExitCode error)
 	    }
 	}
 	break;
-#else /* HAS_MMAP */
+#else /* HAVE_MMAP */
     case MMAPPED_FILE_FB:
         break;
-#endif /* HAS_MMAP */
+#endif /* HAVE_MMAP */
 	
 #ifdef HAS_SHM
     case SHARED_MEMORY_FB:
@@ -241,7 +241,7 @@ ddxUseMsg(void)
     ErrorF("-blackpixel n          pixel value for black\n");
     ErrorF("-whitepixel n          pixel value for white\n");
 
-#ifdef HAS_MMAP
+#ifdef HAVE_MMAP
     ErrorF("-fbdir directory       put framebuffers in mmap'ed files in directory\n");
 #endif
 
@@ -370,7 +370,7 @@ ddxProcessArgument(int argc, char *argv[], int i)
 	return 2;
     }
 
-#ifdef HAS_MMAP
+#ifdef HAVE_MMAP
     if (strcmp (argv[i], "-fbdir") == 0)	/* -fbdir directory */
     {
 	CHECK_FOR_REQUIRED_ARGUMENTS(1);
@@ -378,7 +378,7 @@ ddxProcessArgument(int argc, char *argv[], int i)
 	fbmemtype = MMAPPED_FILE_FB;
 	return 2;
     }
-#endif /* HAS_MMAP */
+#endif /* HAVE_MMAP */
 
 #ifdef HAS_SHM
     if (strcmp (argv[i], "-shmem") == 0)	/* -shmem */
@@ -523,7 +523,7 @@ vfbSaveScreen(ScreenPtr pScreen, int on)
     return TRUE;
 }
 
-#ifdef HAS_MMAP
+#ifdef HAVE_MMAP
 
 /* this flushes any changes to the screens out to the mmapped file */
 static void
@@ -608,7 +608,7 @@ vfbAllocateMmappedFramebuffer(vfbScreenInfoPtr pvfb)
 	pvfb->pXWDHeader = NULL;
     }
 }
-#endif /* HAS_MMAP */
+#endif /* HAVE_MMAP */
 
 
 #ifdef HAS_SHM
@@ -672,7 +672,7 @@ vfbAllocateFramebufferMemory(vfbScreenInfoPtr pvfb)
     pvfb->pXWDHeader = NULL; 
     switch (fbmemtype)
     {
-#ifdef HAS_MMAP
+#ifdef HAVE_MMAP
     case MMAPPED_FILE_FB:  vfbAllocateMmappedFramebuffer(pvfb); break;
 #else
     case MMAPPED_FILE_FB: break;
diff --git a/hw/xwin/win.h b/hw/xwin/win.h
index e2e946f..ac26d01 100644
--- a/hw/xwin/win.h
+++ b/hw/xwin/win.h
@@ -143,12 +143,12 @@
 #undef HANDLE
 #endif
 
-#ifdef HAS_MMAP
+#ifdef HAVE_MMAP
 #include <sys/mman.h>
 #ifndef MAP_FILE
 #define MAP_FILE 0
 #endif /* MAP_FILE */
-#endif /* HAS_MMAP */
+#endif /* HAVE_MMAP */
 
 #include <X11/X.h>
 #include <X11/Xproto.h>
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index d5129fe..3fb6413 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -51,27 +51,9 @@
 /* Support XDM-AUTH*-1 */
 #undef HASXDMAUTH
 
-/* Define to 1 if you have the `getdtablesize' function. */
-#undef HAS_GETDTABLESIZE
-
-/* Define to 1 if you have the `getifaddrs' function. */
-#undef HAS_GETIFADDRS
-
-/* Define to 1 if you have the `getpeereid' function. */
-#undef HAS_GETPEEREID
-
-/* Define to 1 if you have the `getpeerucred' function. */
-#undef HAS_GETPEERUCRED
-
-/* Define to 1 if you have the `mmap' function. */
-#undef HAS_MMAP
-
 /* Support SHM */
 #undef HAS_SHM
 
-/* Have the 'strlcpy' function */
-#undef HAS_STRLCPY
-
 /* Define to 1 if you have the <asm/mtrr.h> header file. */
 #undef HAVE_ASM_MTRR_H
 
@@ -81,7 +63,7 @@
 /* Define to 1 if you have the <byteswap.h> header file. */
 #undef HAVE_BYTESWAP_H
 
-/* Define to 1 if you have cbrt */
+/* Define to 1 if you have the `cbrt' function. */
 #undef HAVE_CBRT
 
 /* Define to 1 if you have the <dbm.h> header file. */
@@ -100,6 +82,21 @@
 /* Define to 1 if you have the <fcntl.h> header file. */
 #undef HAVE_FCNTL_H
 
+/* Define to 1 if you have the `ffs' function. */
+#undef HAVE_FFS
+
+/* Define to 1 if you have the `getdtablesize' function. */
+#undef HAVE_GETDTABLESIZE
+
+/* Define to 1 if you have the `getifaddrs' function. */
+#undef HAVE_GETIFADDRS
+
+/* Define to 1 if you have the `getpeereid' function. */
+#undef HAVE_GETPEEREID
+
+/* Define to 1 if you have the `getpeerucred' function. */
+#undef HAVE_GETPEERUCRED
+
 /* Define to 1 if you have the `getzoneid' function. */
 #undef HAVE_GETZONEID
 
@@ -133,6 +130,9 @@
 /* Define to 1 if you have the <linux/fb.h> header file. */
 #undef HAVE_LINUX_FB_H
 
+/* Define to 1 if you have the `mmap' function. */
+#undef HAVE_MMAP
+
 /* Define to 1 if you have the <ndbm.h> header file. */
 #undef HAVE_NDBM_H
 
@@ -163,6 +163,21 @@
 /* Define to 1 if you have the <stdlib.h> header file. */
 #undef HAVE_STDLIB_H
 
+/* Define to 1 if you have the `strcasecmp' function. */
+#undef HAVE_STRCASECMP
+
+/* Define to 1 if you have the `strcasestr' function. */
+#undef HAVE_STRCASESTR
+
+/* Define to 1 if you have the `strncasecmp' function. */
+#undef HAVE_STRNCASECMP
+
+/* Define to 1 if you have the `strlcat' function. */
+#undef HAVE_STRLCAT
+
+/* Define to 1 if you have the `strlcpy' function. */
+#undef HAVE_STRLCPY
+
 /* Define to 1 if you have the <strings.h> header file. */
 #undef HAVE_STRINGS_H
 
@@ -402,18 +417,6 @@
 /* Define to 64-bit byteswap macro */
 #undef bswap_64
 
-/* Need the strcasecmp function. */
-#undef NEED_STRCASECMP
-
-/* Need the strncasecmp function. */
-#undef NEED_STRNCASECMP
-
-/* Need the strcasestr function. */
-#undef NEED_STRCASESTR
-
-/* Define to 1 if you have the `ffs' function. */
-#undef HAVE_FFS
-
 /* The compiler supported TLS storage class, prefering initial-exec if tls_model is supported */
 #undef TLS
 
diff --git a/include/os.h b/include/os.h
index 2298381..1fd5367 100644
--- a/include/os.h
+++ b/include/os.h
@@ -472,22 +472,22 @@ extern _X_EXPORT void ddxGiveUp(enum ExitCode error);
 extern _X_EXPORT int TimeSinceLastInputEvent(void);
 
 /* strcasecmp.c */
-#if NEED_STRCASECMP
+#ifndef HAVE_STRCASECMP
 #define strcasecmp xstrcasecmp
 extern _X_EXPORT int xstrcasecmp(const char *s1, const char *s2);
 #endif
 
-#if NEED_STRNCASECMP
+#ifndef HAVE_STRNCASECMP
 #define strncasecmp xstrncasecmp
 extern _X_EXPORT int xstrncasecmp(const char *s1, const char *s2, size_t n);
 #endif
 
-#if NEED_STRCASESTR
+#ifndef HAVE_STRCASESTR
 #define strcasestr xstrcasestr
 extern _X_EXPORT char *xstrcasestr(const char *s, const char *find);
 #endif
 
-#ifndef HAS_STRLCPY
+#ifndef HAVE_STRLCPY
 extern _X_EXPORT size_t strlcpy(char *dst, const char *src, size_t siz);
 extern _X_EXPORT size_t strlcat(char *dst, const char *src, size_t siz);
 #endif
diff --git a/include/xkb-config.h.in b/include/xkb-config.h.in
index d3cdd19..7b6a671 100644
--- a/include/xkb-config.h.in
+++ b/include/xkb-config.h.in
@@ -29,7 +29,4 @@
 /* XKB output dir for compiled keymaps. */
 #undef XKM_OUTPUT_DIR
 
-/* Do not have `strcasecmp'. */
-#undef NEED_STRCASECMP
-
 #endif /* _XKB_CONFIG_H_ */
diff --git a/mi/mibitblt.c b/mi/mibitblt.c
index 49e17bd..2dfff14 100644
--- a/mi/mibitblt.c
+++ b/mi/mibitblt.c
@@ -63,7 +63,7 @@ SOFTWARE.
 #include <X11/Xmd.h>
 #include "servermd.h"
 
-#ifndef HAS_FFS
+#ifndef HAVE_FFS
 extern int ffs(int);
 #endif
 
diff --git a/os/Makefile.am b/os/Makefile.am
index 8dd8095..8891485 100644
--- a/os/Makefile.am
+++ b/os/Makefile.am
@@ -4,7 +4,6 @@ AM_CFLAGS = $(DIX_CFLAGS) $(SHA1_CFLAGS)
 
 SECURERPC_SRCS = rpcauth.c
 XDMCP_SRCS = xdmcp.c
-STRLCAT_SRCS = strlcat.c strlcpy.c
 XORG_SRCS = log.c
 
 libos_la_SOURCES = 	\
@@ -20,14 +19,12 @@ libos_la_SOURCES = 	\
 	osdep.h		\
 	osinit.c	\
 	utils.c		\
-	strcasecmp.c	\
-	strcasestr.c	\
 	xdmauth.c	\
 	xsha1.c		\
 	xstrans.c	\
 	xprintf.c	\
 	$(XORG_SRCS)
-libos_la_LIBADD = @SHA1_LIBS@ $(DLOPEN_LIBS)
+libos_la_LIBADD = @SHA1_LIBS@ $(DLOPEN_LIBS) $(LTLIBOBJS)
 
 if SECURE_RPC
 libos_la_SOURCES += $(SECURERPC_SRCS)
@@ -37,16 +34,7 @@ if XDMCP
 libos_la_SOURCES += $(XDMCP_SRCS)
 endif
 
-if NEED_STRLCAT
-libos_la_SOURCES += $(STRLCAT_SRCS)
-endif
-
-if NEED_STRNDUP
-libos_la_SOURCES += $(STRNDUP_SRCS)
-endif
-
-EXTRA_DIST = $(SECURERPC_SRCS) $(INTERNALMALLOC_SRCS) \
-     $(XDMCP_SRCS) $(STRLCAT_SRCS)
+EXTRA_DIST = $(SECURERPC_SRCS) $(XDMCP_SRCS)
 
 if SPECIAL_DTRACE_OBJECTS
 # Generate dtrace object code for probes in libos & libdix
diff --git a/os/access.c b/os/access.c
index 1598940..0800c7f 100644
--- a/os/access.c
+++ b/os/access.c
@@ -106,7 +106,7 @@ SOFTWARE.
 #include <netinet/in.h>
 #endif /* TCPCONN || STREAMSCONN */
 
-#ifdef HAS_GETPEERUCRED
+#ifdef HAVE_GETPEERUCRED
 # include <ucred.h>
 # ifdef sun
 #  include <zone.h>
@@ -146,7 +146,7 @@ SOFTWARE.
 #endif
 #endif
 
-#ifdef HAS_GETIFADDRS
+#ifdef HAVE_GETIFADDRS
 #include <ifaddrs.h>
 #endif
 
@@ -495,7 +495,7 @@ in6_fillscopeid(struct sockaddr_in6 *sin6)
 void
 DefineSelf (int fd)
 {
-#ifndef HAS_GETIFADDRS
+#ifndef HAVE_GETIFADDRS
     char 		*cp, *cplim;
 # ifdef USE_SIOCGLIFCONF
     struct sockaddr_storage buf[16];
@@ -510,7 +510,7 @@ DefineSelf (int fd)
     register struct ifreq *ifr;
 # endif
     void *		bufptr = buf;   
-#else /* HAS_GETIFADDRS */
+#else /* HAVE_GETIFADDRS */
     struct ifaddrs *	ifap, *ifr;
 #endif
     int 		len;
@@ -518,7 +518,7 @@ DefineSelf (int fd)
     int 		family;
     register HOST 	*host;
     
-#ifndef HAS_GETIFADDRS
+#ifndef HAVE_GETIFADDRS
 
     len = sizeof(buf);
 
@@ -689,7 +689,7 @@ DefineSelf (int fd)
     }
     if (bufptr != buf)
         free(bufptr);    
-#else /* HAS_GETIFADDRS */
+#else /* HAVE_GETIFADDRS */
     if (getifaddrs(&ifap) < 0) {
 	ErrorF("Warning: getifaddrs returns %s\n", strerror(errno));
 	return;
@@ -777,7 +777,7 @@ DefineSelf (int fd)
 		
     } /* for */
     freeifaddrs(ifap);
-#endif /* HAS_GETIFADDRS */
+#endif /* HAVE_GETIFADDRS */
 
     /*
      * add something of FamilyLocalHost
@@ -798,7 +798,7 @@ DefineSelf (int fd)
 	}
     }
 }
-#endif /* hpux && !HAS_IFREQ */
+#endif /* hpux && !HAVE_IFREQ */
 
 #ifdef XDMCP
 void
@@ -1091,14 +1091,14 @@ LocalClientCred(ClientPtr client, int *pUid, int *pGid)
 int
 GetLocalClientCreds(ClientPtr client, LocalClientCredRec **lccp)
 {
-#if defined(HAS_GETPEEREID) || defined(HAS_GETPEERUCRED) || defined(SO_PEERCRED)
+#if defined(HAVE_GETPEEREID) || defined(HAVE_GETPEERUCRED) || defined(SO_PEERCRED)
     int fd;
     XtransConnInfo ci;
     LocalClientCredRec *lcc;
-#ifdef HAS_GETPEEREID
+#ifdef HAVE_GETPEEREID
     uid_t uid;
     gid_t gid;
-#elif defined(HAS_GETPEERUCRED)
+#elif defined(HAVE_GETPEERUCRED)
     ucred_t *peercred = NULL;
     const gid_t *gids;
 #elif defined(SO_PEERCRED)
@@ -1109,7 +1109,7 @@ GetLocalClientCreds(ClientPtr client, LocalClientCredRec **lccp)
     if (client == NULL)
 	return -1;
     ci = ((OsCommPtr)client->osPrivate)->trans_conn;
-#if !(defined(sun) && defined(HAS_GETPEERUCRED))
+#if !(defined(sun) && defined(HAVE_GETPEERUCRED))
     /* Most implementations can only determine peer credentials for Unix 
      * domain sockets - Solaris getpeerucred can work with a bit more, so 
      * we just let it tell us if the connection type is supported or not
@@ -1125,7 +1125,7 @@ GetLocalClientCreds(ClientPtr client, LocalClientCredRec **lccp)
     lcc = *lccp;
         
     fd = _XSERVTransGetConnectionNumber(ci);
-#ifdef HAS_GETPEEREID
+#ifdef HAVE_GETPEEREID
     if (getpeereid(fd, &uid, &gid) == -1) {
 	FreeLocalClientCreds(lcc);
 	return -1;
@@ -1134,7 +1134,7 @@ GetLocalClientCreds(ClientPtr client, LocalClientCredRec **lccp)
     lcc->egid = gid;
     lcc->fieldsSet = LCC_UID_SET | LCC_GID_SET;
     return 0;
-#elif defined(HAS_GETPEERUCRED)
+#elif defined(HAVE_GETPEERUCRED)
     if (getpeerucred(fd, &peercred) < 0) {
 	FreeLocalClientCreds(lcc);
     	return -1;
diff --git a/os/connection.c b/os/connection.c
index c5fc5a0..6f480de 100644
--- a/os/connection.c
+++ b/os/connection.c
@@ -114,7 +114,7 @@ SOFTWARE.
 #define Pid_t pid_t
 
 
-#ifdef HAS_GETPEERUCRED
+#ifdef HAVE_GETPEERUCRED
 # include <ucred.h>
 # include <zone.h>
 #endif
@@ -122,7 +122,7 @@ SOFTWARE.
 #ifdef XSERVER_DTRACE
 # include <sys/types.h>
 typedef const char *string;
-# ifndef HAS_GETPEERUCRED
+# ifndef HAVE_GETPEERUCRED
 #  define zoneid_t int
 # endif
 # include "../dix/Xserver-dtrace.h"
@@ -282,7 +282,7 @@ InitConnectionLimits(void)
     lastfdesc = sysconf(_SC_OPEN_MAX) - 1;
 #endif
 
-#ifdef HAS_GETDTABLESIZE
+#ifdef HAVE_GETDTABLESIZE
     if (lastfdesc < 0)
 	lastfdesc = getdtablesize() - 1;
 #endif
diff --git a/os/osdep.h b/os/osdep.h
index 087e36d..72bd7d7 100644
--- a/os/osdep.h
+++ b/os/osdep.h
@@ -103,12 +103,6 @@ SOFTWARE.
 /* MAXSELECT is the number of fds that select() can handle */
 #define MAXSELECT (sizeof(fd_set) * NBBY)
 
-#ifndef HAS_GETDTABLESIZE
-#if !defined(SVR4) && !defined(SYSV)
-#define HAS_GETDTABLESIZE
-#endif
-#endif
-
 #include <stddef.h>
 
 #if defined(XDMCP) || defined(HASXDMAUTH)
diff --git a/os/strcasecmp.c b/os/strcasecmp.c
index ad6da6a..cf100ba 100644
--- a/os/strcasecmp.c
+++ b/os/strcasecmp.c
@@ -34,7 +34,7 @@
 #include <ctype.h>
 #include "dix.h"
 
-#ifdef NEED_STRCASECMP
+#ifndef HAVE_STRCASECMP
 int
 xstrcasecmp(const char *str1, const char *str2)
 {
@@ -50,7 +50,7 @@ xstrcasecmp(const char *str1, const char *str2)
 }
 #endif
 
-#ifdef NEED_STRNCASECMP
+#ifndef HAVE_STRNCASECMP
 int
 xstrncasecmp(const char *s1, const char *s2, size_t n)
 {
diff --git a/os/strcasestr.c b/os/strcasestr.c
index f89b2f2..a20a6cc 100644
--- a/os/strcasestr.c
+++ b/os/strcasestr.c
@@ -41,7 +41,7 @@
 /*
  * Find the first occurrence of find in s, ignore case.
  */
-#ifdef NEED_STRCASESTR
+#ifndef HAVE_STRCASESTR
 char *
 xstrcasestr(const char *s, const char *find)
 {
diff --git a/os/strlcpy.c b/os/strlcpy.c
index 2e55b2e..7ffb64c 100644
--- a/os/strlcpy.c
+++ b/os/strlcpy.c
@@ -22,6 +22,7 @@
 #include <string.h>
 #include "os.h"
 
+#ifndef HAVE_STRLCPY
 /*
  * Copy src to string dst of size siz.  At most siz-1 characters
  * will be copied.  Always NUL terminates (unless siz == 0).
@@ -52,3 +53,4 @@ strlcpy(char *dst, const char *src, size_t siz)
 
 	return s - src - 1;	/* count does not include NUL */
 }
+#endif
commit 4be68b03128e958d2a6dc1b7feb3587329b9561b
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Wed Nov 30 19:39:51 2011 -0800

    Remove unused function checks from configure.ac & include/*.h.in
    
    The code that used getisax to check for MMX support was moved to pixman
    and removed from the X server by commit eb2d7fe02f9cbc.
    
    The code that used HAVE_MKSTEMP was deleted by the Xprint removal in
    commit 1c8bd318fbaf.
    
    All alloca calls were removed by the patch series end in commit 5e363500c8,
    and used custom X checks instead of the autoconf HAVE_ALLOCA anyway.
    
    I can find no record of HAVE_GETUID, HAVE_GETEUID, HAVE_LINK, HAVE_MEMMOVE,
    HAVE_MEMSET, HAVE_STRCHR, HAVE_STRRCHR, HAVE_GETOPT, HAVE_GETOPT_LONG,
    HAVE_DOPRNT, or HAVE_VPRINTF ever being used, and the calls to those
    functions are not wrapped in #ifdefs.
    (Most of those are in our baseline requirements of C89 & Unix98 anyway.)
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Adam Jackson <ajax at redhat.com>
    Reviewed-by: Mikhail Gusarov <dottedmag at dottedmag.net>
    Reviewed-by: Gaetan Nadon <memsize at videotron.ca>

diff --git a/configure.ac b/configure.ac
index e4fcba4..7e4871f 100644
--- a/configure.ac
+++ b/configure.ac
@@ -213,11 +213,8 @@ AC_CHECK_FUNC([dlopen], [],
 AC_SUBST(DLOPEN_LIBS)
 
 dnl Checks for library functions.
-AC_FUNC_VPRINTF
-AC_CHECK_FUNCS([geteuid getuid link memmove memset mkstemp strchr strrchr \
-		strtol getopt getopt_long vsnprintf walkcontext backtrace \
-		getisax getzoneid shmctl64 strcasestr ffs vasprintf])
-AC_FUNC_ALLOCA
+AC_CHECK_FUNCS([vsnprintf walkcontext backtrace \
+		getzoneid shmctl64 strcasestr ffs vasprintf])
 AC_CHECK_FUNCS([strndup], [HAVE_STRNDUP=yes], [HAVE_STRNDUP=no])
 AM_CONDITIONAL(NEED_STRNDUP, [test x$HAVE_STRNDUP = xno])
 dnl Old HAS_* names used in os/*.c.
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index e1d3a9e..d5129fe 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -94,24 +94,12 @@
 /* Define to 1 if you have the <dlfcn.h> header file. */
 #undef HAVE_DLFCN_H
 
-/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */
-#undef HAVE_DOPRNT
-
 /* Have execinfo.h */
 #undef HAVE_EXECINFO_H
 
 /* Define to 1 if you have the <fcntl.h> header file. */
 #undef HAVE_FCNTL_H
 
-/* Define to 1 if you have the `geteuid' function. */
-#undef HAVE_GETEUID
-
-/* Define to 1 if you have the `getisax' function. */
-#undef HAVE_GETISAX
-
-/* Define to 1 if you have the `getuid' function. */
-#undef HAVE_GETUID
-
 /* Define to 1 if you have the `getzoneid' function. */
 #undef HAVE_GETZONEID
 
@@ -136,9 +124,6 @@
 /* Define to 1 if you have the libdispatch (GCD) available */
 #undef HAVE_LIBDISPATCH
 
-/* Define to 1 if you have the `link' function. */
-#undef HAVE_LINK
-
 /* Define to 1 if you have the <linux/agpgart.h> header file. */
 #undef HAVE_LINUX_AGPGART_H
 
@@ -148,9 +133,6 @@
 /* Define to 1 if you have the <linux/fb.h> header file. */
 #undef HAVE_LINUX_FB_H
 
-/* Define to 1 if you have the `mkstemp' function. */
-#undef HAVE_MKSTEMP
-
 /* Define to 1 if you have the <ndbm.h> header file. */
 #undef HAVE_NDBM_H
 
@@ -181,9 +163,6 @@
 /* Define to 1 if you have the <stdlib.h> header file. */
 #undef HAVE_STDLIB_H
 
-/* Define to 1 if you have the `strchr' function. */
-#undef HAVE_STRCHR
-
 /* Define to 1 if you have the <strings.h> header file. */
 #undef HAVE_STRINGS_H
 
@@ -193,12 +172,6 @@
 /* Define to 1 if you have the `strndup' function. */
 #undef HAVE_STRNDUP
 
-/* Define to 1 if you have the `strrchr' function. */
-#undef HAVE_STRRCHR
-
-/* Define to 1 if you have the `strtol' function. */
-#undef HAVE_STRTOL
-
 /* Define to 1 if SYSV IPC is available */
 #undef HAVE_SYSV_IPC
 
@@ -234,9 +207,6 @@
 /* Have /dev/urandom */
 #undef HAVE_URANDOM
 
-/* Define to 1 if you have the `vprintf' function. */
-#undef HAVE_VPRINTF
-
 /* Define to 1 if you have the `vasprintf' function. */
 #undef HAVE_VASPRINTF
 
diff --git a/include/xwin-config.h.in b/include/xwin-config.h.in
index 13b51ca..8122f55 100644
--- a/include/xwin-config.h.in
+++ b/include/xwin-config.h.in
@@ -20,9 +20,6 @@
 /* Define to 1 if unsigned long is 64 bits. */
 #undef _XSERVER64
 
-/* Do we require our own snprintf? */
-#undef NEED_SNPRINTF
-
 /* Short vendor name */
 #undef XVENDORNAMESHORT
 
commit 84207def93e4489df8dca8e044ce544be8a3f845
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Nov 28 20:38:58 2011 -0800

    Disable building of tests requiring DDX functions when Xorg is not built
    
    Some test cases require linking with some sort of DDX - ideally we'd
    have a stub ddx for testing, but for now, since we link with the Xorg
    ddx, disable those tests when configured with --disable-xorg
    
    Fixes https://bugs.freedesktop.org/show_bug.cgi?id=43320
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Dan Nicholson <dbn.lists at gmail.com>
    Reviewed-by: Jeremy Huddleston <jeremyhu at apple.com>

diff --git a/test/Makefile.am b/test/Makefile.am
index 62c398c..48393d3 100644
--- a/test/Makefile.am
+++ b/test/Makefile.am
@@ -1,21 +1,32 @@
 if ENABLE_UNIT_TESTS
-SUBDIRS= . xi2
-noinst_PROGRAMS = xkb input xtest list misc fixes xfree86 string
+SUBDIRS= .
+noinst_PROGRAMS = list string
+if XORG
+# Tests that require at least some DDX functions in order to fully link
+# For now, requires xf86 ddx, could be adjusted to use another
+SUBDIRS += xi2
+noinst_PROGRAMS += xkb input xtest misc fixes xfree86
+endif
 check_LTLIBRARIES = libxservertest.la
 
 TESTS=$(noinst_PROGRAMS)
 TESTS_ENVIRONMENT = $(XORG_MALLOC_DEBUG_ENV)
 
 AM_CFLAGS = $(DIX_CFLAGS) @XORG_CFLAGS@
-INCLUDES = $(XORG_INCS) -I$(top_srcdir)/hw/xfree86/parser \
-	-I$(top_srcdir)/miext/cw -I$(top_srcdir)/hw/xfree86/ddc \
+INCLUDES = $(XORG_INCS) -I$(top_srcdir)/miext/cw
+if XORG
+INCLUDES += -I$(top_srcdir)/hw/xfree86/parser \
+	-I$(top_srcdir)/hw/xfree86/ddc \
 	-I$(top_srcdir)/hw/xfree86/i2c -I$(top_srcdir)/hw/xfree86/modes \
 	-I$(top_srcdir)/hw/xfree86/ramdac
+endif
 TEST_LDADD=libxservertest.la $(XORG_SYS_LIBS) $(XSERVER_SYS_LIBS)
 
+if XORG
 if SPECIAL_DTRACE_OBJECTS
 TEST_LDADD += $(OS_LIB) $(DIX_LIB)
 endif
+endif
 
 xkb_LDADD=$(TEST_LDADD)
 input_LDADD=$(TEST_LDADD)
@@ -25,9 +36,10 @@ misc_LDADD=$(TEST_LDADD)
 fixes_LDADD=$(TEST_LDADD)
 xfree86_LDADD=$(TEST_LDADD)
 
+libxservertest_la_LIBADD = $(XSERVER_LIBS)
+if XORG
 nodist_libxservertest_la_SOURCES = $(top_builddir)/hw/xfree86/sdksyms.c
-libxservertest_la_LIBADD = \
-            $(XSERVER_LIBS) \
+libxservertest_la_LIBADD += \
             $(top_builddir)/hw/xfree86/loader/libloader.la \
             $(top_builddir)/hw/xfree86/os-support/libxorgos.la \
             $(top_builddir)/hw/xfree86/common/libcommon.la \
@@ -37,7 +49,9 @@ libxservertest_la_LIBADD = \
             $(top_builddir)/hw/xfree86/ramdac/libramdac.la \
             $(top_builddir)/hw/xfree86/ddc/libddc.la \
             $(top_builddir)/hw/xfree86/i2c/libi2c.la \
-            $(top_builddir)/hw/xfree86/dixmods/libxorgxkb.la \
+            $(top_builddir)/hw/xfree86/dixmods/libxorgxkb.la
+endif
+libxservertest_la_LIBADD += \
             $(top_builddir)/mi/libmi.la \
             $(top_builddir)/os/libos.la \
             @XORG_LIBS@
commit fd976e4051e15ab2d01ec0bf89ff26926d4ed04e
Author: Gaetan Nadon <memsize at videotron.ca>
Date:   Thu Dec 1 16:24:12 2011 -0500

    config: conftest needs an include directive to locate X11/Xfuncproto.h
    
    The compiler option -fvisibility=hidden is erroneously missing
    due to a faulty configuration test. The gcc command is unable to
    locate X11/Xfuncproto.h unless the build occurs on a
    system where X11 development headers are installed.
    
    configure:21294: checking for symbol visibility support
    configure:21323: gcc -std=gnu99 -c -g -O2 -fvisibility=hidden  conftest.c >&5
    conftest.c:144:28: fatal error: X11/Xfuncproto.h: No such file or directory
    
    The solution is to add an include directive to obtain the location
    of X11/Xfuncproto.h which may or may not be the system installed headers.
    
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Signed-off-by: Gaetan Nadon <memsize at videotron.ca>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/configure.ac b/configure.ac
index e4fcba4..3d5414f 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1558,7 +1558,8 @@ if test "x$XORG" = xyes; then
 	    fi
 	    if test x$have_visibility != xno; then
 		save_CFLAGS="$CFLAGS"
-		CFLAGS="$CFLAGS $VISIBILITY_CFLAGS"
+		proto_inc=`$PKG_CONFIG --cflags xproto`
+		CFLAGS="$CFLAGS $VISIBILITY_CFLAGS $proto_inc"
 		AC_TRY_COMPILE(
 		    [#include <X11/Xfuncproto.h>
 		     extern _X_HIDDEN int hidden_int;
commit feebf6746374aa04b12e9e3e51313a3a82c03530
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Wed Nov 23 00:30:02 2011 -0800

    Limit the number of screens Xvfb will attempt to allocate memory for
    
    Commit f9e3a2955d2ca7 removing the MAXSCREEN limit left the screen
    number too unlimited, and allowed any positive int for a screen number:
    
    Xvfb :1 -screen 2147483647 1024x1024x8
    
    Fatal server error:
    Not enough memory for screen 2147483647
    
    Found by Parfait 0.3.7:
    Error: Integer overflow (CWE 190)
       Integer parameter of memory allocation function realloc() may overflow due to multiplication with constant value 1112
            at line 293 of hw/vfb/InitOutput.c in function 'ddxProcessArgument'.
    
    Since the X11 connection setup only has a CARD8 for number of SCREENS,
    limit to 255 screens, which is also low enough to avoid overflow on the
    sizeof(*vfbScreens) * (screenNum + 1) calculation for realloc.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>

diff --git a/hw/vfb/InitOutput.c b/hw/vfb/InitOutput.c
index 3e5d051..9a9905d 100644
--- a/hw/vfb/InitOutput.c
+++ b/hw/vfb/InitOutput.c
@@ -280,7 +280,9 @@ ddxProcessArgument(int argc, char *argv[], int i)
 	int screenNum;
 	CHECK_FOR_REQUIRED_ARGUMENTS(2);
 	screenNum = atoi(argv[i+1]);
-	if (screenNum < 0)
+	/* The protocol only has a CARD8 for number of screens in the
+	   connection setup block, so don't allow more than that. */
+	if ((screenNum < 0) || (screenNum >= 255))
 	{
 	    ErrorF("Invalid screen number %d\n", screenNum);
 	    UseMsg();
commit fb22a408c69a84f81905147de9e82cf66ffb6eb2
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Nov 8 10:13:15 2011 -0800

    Save major/minor opcodes in ClientRec for RecordAReply
    
    The record extension needs the major and minor opcodes in the reply
    hook, but the request buffer may have been freed by the time the hook
    is invoked. Saving the request major and minor codes as the request is
    executed avoids fetching from the defunct request buffer.
    
    This patch also eliminates the public MinorOpcodeOfRequest function,
    inlining it into Dispatch. Usages of that function have been replaced
    with direct access to the new ClientRec field.
    
    Signed-off-by: Keith Packard <keithp at keithp.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>

diff --git a/Xext/security.c b/Xext/security.c
index 0a63aa2..6fc1eaf 100644
--- a/Xext/security.c
+++ b/Xext/security.c
@@ -148,9 +148,7 @@ SecurityLabelInitial(void)
 static _X_INLINE const char *
 SecurityLookupRequestName(ClientPtr client)
 {
-    int major = ((xReq *)client->requestBuffer)->reqType;
-    int minor = MinorOpcodeOfRequest(client);
-    return LookupRequestName(major, minor);
+    return LookupRequestName(client->majorOp, client->minorOp);
 }
 
 
diff --git a/Xext/xselinux_hooks.c b/Xext/xselinux_hooks.c
index f1d8e5d..0d4c9ab 100644
--- a/Xext/xselinux_hooks.c
+++ b/Xext/xselinux_hooks.c
@@ -263,8 +263,8 @@ SELinuxAudit(void *auditdata,
     if (client) {
 	REQUEST(xReq);
 	if (stuff) {
-	    major = stuff->reqType;
-	    minor = MinorOpcodeOfRequest(client);
+	    major = client->majorOp;
+	    minor = client->minorOp;
 	}
     }
     if (audit->id)
diff --git a/dix/dispatch.c b/dix/dispatch.c
index 6e33615..b39271f 100644
--- a/dix/dispatch.c
+++ b/dix/dispatch.c
@@ -337,8 +337,6 @@ DisableLimitedSchedulingLatency(void)
 	SmartScheduleLatencyLimited = 0;
 }
 
-#define MAJOROP ((xReq *)client->requestBuffer)->reqType
-
 void
 Dispatch(void)
 {
@@ -419,21 +417,28 @@ Dispatch(void)
 	        }
 
 		client->sequence++;
+		client->majorOp = ((xReq *)client->requestBuffer)->reqType;
+		client->minorOp = 0;
+		if (client->majorOp >= EXTENSION_BASE) {
+		    ExtensionEntry *ext = GetExtensionEntry(client->majorOp);
+		    if (ext)
+			client->minorOp = ext->MinorOpcode(client);
+		}
 #ifdef XSERVER_DTRACE
-		XSERVER_REQUEST_START(LookupMajorName(MAJOROP), MAJOROP,
+		XSERVER_REQUEST_START(LookupMajorName(client->majorOp), client->majorOp,
 			      ((xReq *)client->requestBuffer)->length,
 			      client->index, client->requestBuffer);
 #endif
 		if (result > (maxBigRequestSize << 2))
 		    result = BadLength;
 		else {
-		    result = XaceHookDispatch(client, MAJOROP);
+		    result = XaceHookDispatch(client, client->majorOp);
 		    if (result == Success)
-			result = (* client->requestVector[MAJOROP])(client);
+			result = (* client->requestVector[client->majorOp])(client);
 		    XaceHookAuditEnd(client, result);
 		}
 #ifdef XSERVER_DTRACE
-		XSERVER_REQUEST_DONE(LookupMajorName(MAJOROP), MAJOROP,
+		XSERVER_REQUEST_DONE(LookupMajorName(client->majorOp), client->majorOp,
 			      client->sequence, client->index, result);
 #endif
 
@@ -444,8 +449,8 @@ Dispatch(void)
 		}
 		else if (result != Success)
 		{
-		    SendErrorToClient(client, MAJOROP,
-				      MinorOpcodeOfRequest(client),
+		    SendErrorToClient(client, client->majorOp,
+				      client->minorOp,
 				      client->errorValue, result);
 		    break;
 		}
@@ -466,8 +471,6 @@ Dispatch(void)
     SmartScheduleLatencyLimited = 0;
 }
 
-#undef MAJOROP
-
 static int  VendorRelease = VENDOR_RELEASE;
 static char *VendorString = VENDOR_NAME;
 
diff --git a/dix/extension.c b/dix/extension.c
index 53aaf05..cc516b6 100644
--- a/dix/extension.c
+++ b/dix/extension.c
@@ -228,20 +228,6 @@ StandardMinorOpcode(ClientPtr client)
     return ((xReq *)client->requestBuffer)->data;
 }
 
-unsigned short
-MinorOpcodeOfRequest(ClientPtr client)
-{
-    unsigned char major;
-
-    major = ((xReq *)client->requestBuffer)->reqType;
-    if (major < EXTENSION_BASE)
-	return 0;
-    major -= EXTENSION_BASE;
-    if (major >= NumExtensions)
-	return 0;
-    return (*extensions[major]->MinorOpcode)(client);
-}
-
 void
 CloseDownExtensions(void)
 {
diff --git a/include/dixstruct.h b/include/dixstruct.h
index 6cc9614..0a85f40 100644
--- a/include/dixstruct.h
+++ b/include/dixstruct.h
@@ -122,6 +122,7 @@ typedef struct _Client {
     
     DeviceIntPtr clientPtr;
     ClientIdPtr  clientIds;
+    unsigned short majorOp, minorOp;
 }           ClientRec;
 
 /*
diff --git a/include/extension.h b/include/extension.h
index ee6260e..17accaf 100644
--- a/include/extension.h
+++ b/include/extension.h
@@ -52,8 +52,6 @@ _XFUNCPROTOBEGIN
 
 extern _X_EXPORT unsigned short StandardMinorOpcode(ClientPtr /*client*/);
 
-extern _X_EXPORT unsigned short MinorOpcodeOfRequest(ClientPtr /*client*/);
-
 extern _X_EXPORT Bool EnableDisableExtension(const char *name, Bool enable);
 
 extern _X_EXPORT void EnableDisableExtensionError(const char *name, Bool enable);
diff --git a/record/record.c b/record/record.c
index db77b64..b956b4a 100644
--- a/record/record.c
+++ b/record/record.c
@@ -552,7 +552,7 @@ RecordARequest(ClientPtr client)
 	    }
 	    else /* extension, check minor opcode */
 	    {
-		int minorop = MinorOpcodeOfRequest(client);
+		int minorop = client->minorOp;
 		int numMinOpInfo;
 		RecordMinorOpPtr pMinorOpInfo = pRCAP->pRequestMinOpInfo;
 
@@ -609,12 +609,9 @@ RecordAReply(CallbackListPtr *pcbl, pointer nulldata, pointer calldata)
     RecordContextPtr pContext;
     RecordClientsAndProtocolPtr pRCAP;
     int eci;
-    int majorop;
     ReplyInfoRec *pri = (ReplyInfoRec *)calldata;
     ClientPtr client = pri->client;
-    REQUEST(xReq);
 
-    majorop = stuff->reqType;
     for (eci = 0; eci < numEnabledContexts; eci++)
     {
 	pContext = ppAllContexts[eci];
@@ -622,6 +619,7 @@ RecordAReply(CallbackListPtr *pcbl, pointer nulldata, pointer calldata)
 					  NULL);
 	if (pRCAP)
 	{
+	    int majorop = client->majorOp;
 	    if (pContext->continuedReply)
 	    {
 		RecordAProtocolElement(pContext, client, XRecordFromServer,
@@ -642,7 +640,7 @@ RecordAReply(CallbackListPtr *pcbl, pointer nulldata, pointer calldata)
 		}
 		else /* extension, check minor opcode */
 		{
-		    int minorop = MinorOpcodeOfRequest(client);
+		    int minorop = client->minorOp;
 		    int numMinOpInfo;
 		    RecordMinorOpPtr pMinorOpInfo = pRCAP->pReplyMinOpInfo;
 		    		    assert (pMinorOpInfo);
commit 05f09354a30a4f5edd421220e1aa97be754c71bb
Merge: 3197b77 08ec4da
Author: Keith Packard <keithp at keithp.com>
Date:   Thu Dec 1 14:44:52 2011 +0000

    Merge remote-tracking branch 'jcristau/for-keith'

commit 3197b773c81e58cd4aa412eccaee49526012ed6f
Merge: 2dc5ba4 dfcec1d
Author: Keith Packard <keithp at keithp.com>
Date:   Thu Dec 1 14:36:58 2011 +0000

    Merge remote-tracking branch 'whot/for-keith'

commit 2dc5ba4a1b127e3ed286718ab0a6c20438361192
Author: Matt Turner <mattst88 at gmail.com>
Date:   Tue Nov 29 23:52:19 2011 -0500

    Remove another if (E != NULL) check around free(E)
    
    I wonder if there are any other patterns we haven't seen yet?
    
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Signed-off-by: Matt Turner <mattst88 at gmail.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/fbdevhw/fbdevhw.c b/hw/xfree86/fbdevhw/fbdevhw.c
index d7b4d3c..2019741 100644
--- a/hw/xfree86/fbdevhw/fbdevhw.c
+++ b/hw/xfree86/fbdevhw/fbdevhw.c
@@ -98,8 +98,6 @@ fbdevHWFreeRec(ScrnInfoPtr pScrn)
 {
 	if (fbdevHWPrivateIndex < 0)
 		return;
-	if (FBDEVHWPTR(pScrn) == NULL)
-		return;
 	free(FBDEVHWPTR(pScrn));
 	FBDEVHWPTRLVAL(pScrn) = NULL;
 }
commit dfcec1d3f9d7bac5cde9eb034341428ee0ad3728
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Nov 11 08:55:14 2011 +1000

    test: remove unneeded printf statements from misc.c
    
    Leftover from debugging, is not really needeed in a test.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/test/misc.c b/test/misc.c
index d98449b..1f6cb9a 100644
--- a/test/misc.c
+++ b/test/misc.c
@@ -76,7 +76,6 @@ static void dix_update_desktop_dimensions(void)
 
 #define assert_dimensions(_x, _y, _w, _h) \
     update_desktop_dimensions();          \
-    printf("%d %d %d %d\n", screenInfo.x, screenInfo.y, screenInfo.width, screenInfo.height); \
     assert(screenInfo.x == _x);           \
     assert(screenInfo.y == _y);           \
     assert(screenInfo.width == _w);       \
@@ -88,8 +87,6 @@ static void dix_update_desktop_dimensions(void)
     screenInfo.screens[idx]->width = _w;  \
     screenInfo.screens[idx]->height = _h; \
 
-    printf("Testing\n");
-
     /* single screen */
     screenInfo.numScreens = 1;
     set_screen(0, x, y, w, h);
commit 9c38422fc4cf853c3104fada2a3851c79df2a66f
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Nov 9 14:37:26 2011 +1000

    include: add BUG_WARN macro for internal bug cases.
    
    There are plenty of cases that can only be triggered by a real bug in the
    server and doing the ErrorF dance manually everywhere is a tad painful and
    the error message is usually used only to find the spot in the file anyway.
    
    Plus, reading BUG_WARN somewhere is a good indicator to the casual reader
    that this isn't intended behaviour.
    
    Note that this is intentionally different to the BUG_ON behaviour on the
    kernel, we do not FatalError the server. It's just a warning + stacktrace.
    If the bug is really fatal, call FatalError.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/include/misc.h b/include/misc.h
index 2e8dd1b..ef86fa5 100644
--- a/include/misc.h
+++ b/include/misc.h
@@ -359,4 +359,11 @@ typedef struct _CharInfo *CharInfoPtr; /* also in fonts/include/font.h */
 extern _X_EXPORT unsigned long globalSerialNumber;
 extern _X_EXPORT unsigned long serverGeneration;
 
+#define BUG_WARN(cond)                                                    \
+          do { if (cond) {                                                \
+              ErrorF("BUG: triggered 'if (" #cond ")'\nBUG: %s:%d in %s()\n",     \
+                      __FILE__, __LINE__, __func__);                      \
+              xorg_backtrace();                                           \
+          } } while(0)
+
 #endif /* MISC_H */
commit 61ef4daf6450da573b9de72ba7b200566821b916
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Nov 4 15:49:23 2011 +1000

    Xi: add FreeInputMask function
    
    Does what it says on the box, complements MakeInputMask.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index f530310..20495e7 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1678,6 +1678,13 @@ MakeInputMasks(WindowPtr pWin)
     return TRUE;
 }
 
+static void
+FreeInputMask(OtherInputMasks **imask)
+{
+    free(*imask);
+    *imask = NULL;
+}
+
 void
 RecalculateDeviceDeliverableEvents(WindowPtr pWin)
 {
@@ -1737,8 +1744,9 @@ InputClientGone(WindowPtr pWin, XID id)
 		FreeInputClient(&other);
 	    } else if (!(other->next)) {
 		if (ShouldFreeInputMasks(pWin, TRUE)) {
-		    wOtherInputMasks(pWin)->inputClients = other->next;
-		    free(wOtherInputMasks(pWin));
+		    OtherInputMasks *mask = wOtherInputMasks(pWin);
+		    mask->inputClients = other->next;
+		    FreeInputMask(&mask);
 		    pWin->optional->inputMasks = (OtherInputMasks *) NULL;
 		    CheckWindowOptionalNeed(pWin);
 		    FreeInputClient(&other);
commit ee9346bb31efce4036df1b8dd8f1a5dc43ae955a
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Nov 3 15:45:34 2011 +1000

    Xi: add helper functions to alloc/free InputClientPtrs
    
    Currently not needed since the InputClientRec is a self-contained struct. As
    part of the touch rework that won't be the case in the future and a function
    to allocate/free memory appropriately is required.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 53db036..f530310 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1628,6 +1628,19 @@ SelectForWindow(DeviceIntPtr dev, WindowPtr pWin, ClientPtr client,
     return Success;
 }
 
+static void
+FreeInputClient(InputClientsPtr *other)
+{
+    free(*other);
+    *other = NULL;
+}
+
+static InputClientsPtr
+AllocInputClient(void)
+{
+    return calloc(1, sizeof(InputClients));
+}
+
 int
 AddExtensionClient(WindowPtr pWin, ClientPtr client, Mask mask, int mskidx)
 {
@@ -1635,7 +1648,7 @@ AddExtensionClient(WindowPtr pWin, ClientPtr client, Mask mask, int mskidx)
 
     if (!pWin->optional && !MakeWindowOptional(pWin))
 	return BadAlloc;
-    others = calloc(1, sizeof(InputClients));
+    others = AllocInputClient();
     if (!others)
 	return BadAlloc;
     if (!pWin->optional->inputMasks && !MakeInputMasks(pWin))
@@ -1649,7 +1662,7 @@ AddExtensionClient(WindowPtr pWin, ClientPtr client, Mask mask, int mskidx)
     return Success;
 
 bail:
-    free(others);
+    FreeInputClient(&others);
     return BadAlloc;
 }
 
@@ -1721,14 +1734,14 @@ InputClientGone(WindowPtr pWin, XID id)
 	if (other->resource == id) {
 	    if (prev) {
 		prev->next = other->next;
-		free(other);
+		FreeInputClient(&other);
 	    } else if (!(other->next)) {
 		if (ShouldFreeInputMasks(pWin, TRUE)) {
 		    wOtherInputMasks(pWin)->inputClients = other->next;
 		    free(wOtherInputMasks(pWin));
 		    pWin->optional->inputMasks = (OtherInputMasks *) NULL;
 		    CheckWindowOptionalNeed(pWin);
-		    free(other);
+		    FreeInputClient(&other);
 		} else {
 		    other->resource = FakeClientID(0);
 		    if (!AddResource(other->resource, RT_INPUTCLIENT,
@@ -1737,7 +1750,7 @@ InputClientGone(WindowPtr pWin, XID id)
 		}
 	    } else {
 		wOtherInputMasks(pWin)->inputClients = other->next;
-		free(other);
+		FreeInputClient(&other);
 	    }
 	    RecalculateDeviceDeliverableEvents(pWin);
 	    return Success;
commit 4acf999c294868a44e559d212c6d88a4978256b2
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Nov 4 15:37:32 2011 +1000

    dix: use a single return statement in CheckPassiveGrabsOnWindow
    
    No functional change.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 35b446b..4847db0 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -3788,14 +3788,13 @@ CheckPassiveGrabsOnWindow(
         }
 
         if (!activate)
-        {
-            return grab;
-        }
+            break;
         else if (!GetXIType(event) && !GetCoreType(event))
         {
             ErrorF("Event type %d in CheckPassiveGrabsOnWindow is neither"
                    " XI 1.x nor core\n", event->any.type);
-            return NULL;
+            grab = NULL;
+            break;
         }
 
         /* The only consumers of corestate are Xi 1.x and core events, which
@@ -3861,9 +3860,10 @@ CheckPassiveGrabsOnWindow(
         }
 
         free(xE);
-        return grab;
+        break;
     }
-    return NULL;
+
+    return grab;
 #undef CORE_MATCH
 #undef XI_MATCH
 #undef XI2_MATCH
commit b371795f01c1d7fc338cfe18b8a567ed9f402846
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Nov 3 14:54:06 2011 +1000

    dix: rename GetWindowXI2Mask to WindowXI2MaskIsset
    
    And let it return a boolean value, that's all the callers need anyway.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/events.c b/dix/events.c
index 5e0dc5f..35b446b 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -469,10 +469,11 @@ GetXI2MaskByte(unsigned char xi2mask[][XI2MASKSIZE], DeviceIntPtr dev, int event
 
 
 /**
- * Return the windows complete XI2 mask for the given XI2 event type.
+ * @return TRUE if the mask is set for this event from this device on the
+ * window, or FALSE otherwise.
  */
-Mask
-GetWindowXI2Mask(DeviceIntPtr dev, WindowPtr win, xEvent* ev)
+Bool
+WindowXI2MaskIsset(DeviceIntPtr dev, WindowPtr win, xEvent* ev)
 {
     OtherInputMasks *inputMasks = wOtherInputMasks(win);
     int filter;
@@ -484,7 +485,7 @@ GetWindowXI2Mask(DeviceIntPtr dev, WindowPtr win, xEvent* ev)
     evtype = ((xGenericEvent*)ev)->evtype;
     filter = GetEventFilter(dev, ev);
 
-    return (GetXI2MaskByte(inputMasks->xi2mask, dev, evtype) & filter);
+    return !!(GetXI2MaskByte(inputMasks->xi2mask, dev, evtype) & filter);
 }
 
 Mask
@@ -2075,7 +2076,7 @@ GetClientsForDelivery(DeviceIntPtr dev, WindowPtr win,
     {
         OtherInputMasks *inputMasks = wOtherInputMasks(win);
         /* Has any client selected for the event? */
-        if (!GetWindowXI2Mask(dev, win, events))
+        if (!WindowXI2MaskIsset(dev, win, events))
             goto out;
         *clients = inputMasks->inputClients;
     } else {
@@ -4632,7 +4633,7 @@ DeviceEnterLeaveEvent(
         TryClientEvents(rClient(grab), mouse, (xEvent*)event, 1, mask,
                         filter, grab);
     } else {
-        if (!GetWindowXI2Mask(mouse, pWin, (xEvent*)event))
+        if (!WindowXI2MaskIsset(mouse, pWin, (xEvent*)event))
             goto out;
         DeliverEventsToWindow(mouse, pWin, (xEvent*)event, 1, filter,
                               NullGrab);
diff --git a/include/input.h b/include/input.h
index 87bb2aa..8e7b47a 100644
--- a/include/input.h
+++ b/include/input.h
@@ -535,7 +535,7 @@ extern _X_EXPORT void FreeInputAttributes(InputAttributes *attrs);
 /* misc event helpers */
 extern Mask GetEventMask(DeviceIntPtr dev, xEvent* ev, InputClientsPtr clients);
 extern Mask GetEventFilter(DeviceIntPtr dev, xEvent *event);
-extern Mask GetWindowXI2Mask(DeviceIntPtr dev, WindowPtr win, xEvent* ev);
+extern Bool WindowXI2MaskIsset(DeviceIntPtr dev, WindowPtr win, xEvent* ev);
 void FixUpEventFromWindow(SpritePtr pSprite,
                           xEvent *xE,
                           WindowPtr pWin,
commit bedb8fd90de8e2db33d5e3b1d859f24bf34efc9a
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Nov 3 14:25:51 2011 +1000

    Xi: use single return code from XIPassiveGrabDevice
    
    Some failures returned status but the actual return code was "ret". Use
    "ret" consistently and move status to the local block is used in.
    
    [the goto isn't necessary yet, but for a future patch]
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xi/xipassivegrab.c b/Xi/xipassivegrab.c
index 6be27f3..2f13a95 100644
--- a/Xi/xipassivegrab.c
+++ b/Xi/xipassivegrab.c
@@ -80,7 +80,6 @@ ProcXIPassiveGrabDevice(ClientPtr client)
     DeviceIntPtr dev, mod_dev;
     xXIPassiveGrabDeviceReply rep;
     int i, ret = Success;
-    uint8_t status;
     uint32_t *modifiers;
     xXIGrabModifierInfo *modifiers_failed;
     GrabMask mask;
@@ -145,32 +144,36 @@ ProcXIPassiveGrabDevice(ClientPtr client)
 
     if (stuff->cursor != None)
     {
-        status = dixLookupResourceByType(&tmp, stuff->cursor,
-                                         RT_CURSOR, client, DixUseAccess);
-	if (status != Success)
-	{
-	    client->errorValue = stuff->cursor;
-	    return status;
-	}
+        ret = dixLookupResourceByType(&tmp, stuff->cursor,
+                                      RT_CURSOR, client, DixUseAccess);
+        if (ret != Success)
+        {
+            client->errorValue = stuff->cursor;
+            goto out;
+        }
     }
 
-    status = dixLookupWindow((WindowPtr*)&tmp, stuff->grab_window, client, DixSetAttrAccess);
-    if (status != Success)
-	return status;
+    ret = dixLookupWindow((WindowPtr*)&tmp, stuff->grab_window, client, DixSetAttrAccess);
+    if (ret != Success)
+        goto out;
 
-    status = CheckGrabValues(client, &param);
-    if (status != Success)
-        return status;
+    ret = CheckGrabValues(client, &param);
+    if (ret != Success)
+        goto out;
 
     modifiers = (uint32_t*)&stuff[1] + stuff->mask_len;
     modifiers_failed = calloc(stuff->num_modifiers, sizeof(xXIGrabModifierInfo));
-    if (!modifiers_failed)
-        return BadAlloc;
+    if (!modifiers_failed) {
+        ret = BadAlloc;
+        goto out;
+    }
 
     mod_dev = (IsFloating(dev)) ? dev : GetMaster(dev, MASTER_KEYBOARD);
 
     for (i = 0; i < stuff->num_modifiers; i++, modifiers++)
     {
+        uint8_t status = Success;
+
         param.modifiers = *modifiers;
         switch(stuff->grab_type)
         {
@@ -208,6 +211,7 @@ ProcXIPassiveGrabDevice(ClientPtr client)
         WriteToClient(client, rep.length * 4, (char*)modifiers_failed);
 
     free(modifiers_failed);
+out:
     return ret;
 }
 
commit 2aad1a2b42b7def7812abfa2462b6bcc6382e03a
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Nov 2 14:07:19 2011 +1000

    include: fix mask size calculation
    
    Same bug as inputproto-2.0.1-9-gb1149ab, if the XI2LASTEVENT was a multiple
    of 8, the mask was one bit too short.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Daniel Stone <daniel at fooishbar.org>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/include/inputstr.h b/include/inputstr.h
index 0a21287..f482a22 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -72,7 +72,7 @@ extern _X_EXPORT int CountBits(const uint8_t *mask, int len);
  * this number here is bumped.
  */
 #define XI2LASTEVENT    17 /* XI_RawMotion */
-#define XI2MASKSIZE     ((XI2LASTEVENT + 7)/8) /* no of bits for masks */
+#define XI2MASKSIZE     ((XI2LASTEVENT >> 3) + 1) /* no of bytes for masks */
 
 /**
  * Scroll types for ::SetScrollValuator and the scroll type in the
commit 08ec4da6a7617637914bee1636858474213cf39d
Author: Julien Cristau <jcristau at debian.org>
Date:   Sat Nov 5 13:00:07 2011 +0100

    Fix ShmPutImage for XYBitmap
    
    We can't call CopyArea in that case because the image has depth 1, which
    might not match the target drawable, so we might overrun the shm
    segment.  Commit 11817a881cb93a89788105d1e575a468f2a8d27c apparently
    fixed a similar bug for XYPixmap, but missed the bitmap case.
    
    Fixes: http://bugs.debian.org/629611
    
    Thanks to Alan Curry for diagnosing this and providing a test case.
    
    Reported-and-tested-by: Alan Curry <pacman at kosh.dhis.org>
    Reviewed-by: Peter Harris <pharris at opentext.com>
    Signed-off-by: Julien Cristau <jcristau at debian.org>

diff --git a/Xext/shm.c b/Xext/shm.c
index 9c8beb2..7ca027a 100644
--- a/Xext/shm.c
+++ b/Xext/shm.c
@@ -481,7 +481,7 @@ doShmPutImage(DrawablePtr dst, GCPtr pGC,
 {
     PixmapPtr pPixmap;
 
-    if (format == ZPixmap || depth == 1) {
+    if (format == ZPixmap || (format == XYPixmap && depth == 1)) {
 	pPixmap = GetScratchPixmapHeader(dst->pScreen, w, h, depth,
 					 BitsPerPixel(depth),
 					 PixmapBytePad(w, depth),


More information about the Xquartz-changes mailing list