OSDN Git Service

glx: Fix use after free case when destroying screens
[android-x86/external-mesa.git] / src / glx / glxext.c
1 /*
2  * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
3  * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice including the dates of first publication and
13  * either this permission notice or a reference to
14  * http://oss.sgi.com/projects/FreeB/
15  * shall be included in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
22  * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  *
25  * Except as contained in this notice, the name of Silicon Graphics, Inc.
26  * shall not be used in advertising or otherwise to promote the sale, use or
27  * other dealings in this Software without prior written authorization from
28  * Silicon Graphics, Inc.
29  */
30
31 /**
32  * \file glxext.c
33  * GLX protocol interface boot-strap code.
34  *
35  * Direct rendering support added by Precision Insight, Inc.
36  *
37  * \author Kevin E. Martin <kevin@precisioninsight.com>
38  */
39
40 #include <assert.h>
41 #include "glxclient.h"
42 #include <X11/extensions/Xext.h>
43 #include <X11/extensions/extutil.h>
44 #include <X11/extensions/dri2proto.h>
45 #ifdef GLX_USE_APPLEGL
46 #include "apple_glx.h"
47 #include "apple_visual.h"
48 #endif
49 #include "glxextensions.h"
50 #include "glcontextmodes.h"
51
52 #ifdef USE_XCB
53 #include <X11/Xlib-xcb.h>
54 #include <xcb/xcb.h>
55 #include <xcb/glx.h>
56 #endif
57
58
59 #ifdef DEBUG
60 void __glXDumpDrawBuffer(__GLXcontext * ctx);
61 #endif
62
63 /*
64 ** You can set this cell to 1 to force the gl drawing stuff to be
65 ** one command per packet
66 */
67 _X_HIDDEN int __glXDebug = 0;
68
69 /* Extension required boiler plate */
70
71 static const char __glXExtensionName[] = GLX_EXTENSION_NAME;
72 static __GLXdisplayPrivate *glx_displays;
73
74 static /* const */ char *error_list[] = {
75    "GLXBadContext",
76    "GLXBadContextState",
77    "GLXBadDrawable",
78    "GLXBadPixmap",
79    "GLXBadContextTag",
80    "GLXBadCurrentWindow",
81    "GLXBadRenderRequest",
82    "GLXBadLargeRequest",
83    "GLXUnsupportedPrivateRequest",
84    "GLXBadFBConfig",
85    "GLXBadPbuffer",
86    "GLXBadCurrentDrawable",
87    "GLXBadWindow",
88 };
89
90 #ifdef GLX_USE_APPLEGL
91 static char *__glXErrorString(Display *dpy, int code, XExtCodes *codes, 
92                               char *buf, int n);
93 #endif
94
95 static
96 XEXT_GENERATE_ERROR_STRING(__glXErrorString, __glXExtensionName,
97                            __GLX_NUMBER_ERRORS, error_list)
98
99 static int
100 __glXCloseDisplay(Display * dpy, XExtCodes * codes);
101 static Bool
102 __glXWireToEvent(Display *dpy, XEvent *event, xEvent *wire);
103 static Status
104 __glXEventToWire(Display *dpy, XEvent *event, xEvent *wire);
105
106 /*
107  * GLX events are a bit funky.  We don't stuff the X event code into
108  * our user exposed (via XNextEvent) structure.  Instead we use the GLX
109  * private event code namespace (and hope it doesn't conflict).  Clients
110  * have to know that bit 15 in the event type field means they're getting
111  * a GLX event, and then handle the various sub-event types there, rather
112  * than simply checking the event code and handling it directly.
113  */
114
115 static Bool
116 __glXWireToEvent(Display *dpy, XEvent *event, xEvent *wire)
117 {
118    __GLXdisplayPrivate *glx_dpy = __glXInitialize(dpy);
119
120    if (glx_dpy == NULL)
121       return False;
122
123    switch ((wire->u.u.type & 0x7f) - glx_dpy->codes->first_event) {
124    case GLX_PbufferClobber:
125    {
126       GLXPbufferClobberEvent *aevent = (GLXPbufferClobberEvent *)event;
127       xGLXPbufferClobberEvent *awire = (xGLXPbufferClobberEvent *)wire;
128       aevent->event_type = awire->type;
129       aevent->serial = awire->sequenceNumber;
130       aevent->event_type = awire->event_type;
131       aevent->draw_type = awire->draw_type;
132       aevent->drawable = awire->drawable;
133       aevent->buffer_mask = awire->buffer_mask;
134       aevent->aux_buffer = awire->aux_buffer;
135       aevent->x = awire->x;
136       aevent->y = awire->y;
137       aevent->width = awire->width;
138       aevent->height = awire->height;
139       aevent->count = awire->count;
140       return True;
141    }
142    /* No easy symbol to test for this, as GLX_BufferSwapComplete is
143     * defined in the local glx.h header, but the
144     * xGLXBufferSwapComplete typedef is only available in new versions
145     * of the external glxproto.h header, which doesn't have any
146     * testable versioning define.
147     *
148     * I'll use the related DRI2 define, in the hope that we won't
149     * receive these events unless we know how to ask for them:
150     */
151 #ifdef X_DRI2SwapBuffers
152    case GLX_BufferSwapComplete:
153    {
154       GLXBufferSwapComplete *aevent = (GLXBufferSwapComplete *)event;
155       xGLXBufferSwapComplete *awire = (xGLXBufferSwapComplete *)wire;
156       aevent->event_type = awire->event_type;
157       aevent->drawable = awire->drawable;
158       aevent->ust = ((CARD64)awire->ust_hi << 32) | awire->ust_lo;
159       aevent->msc = ((CARD64)awire->msc_hi << 32) | awire->msc_lo;
160       aevent->sbc = ((CARD64)awire->sbc_hi << 32) | awire->sbc_lo;
161       return True;
162    }
163 #endif
164    default:
165       /* client doesn't support server event */
166       break;
167    }
168
169    return False;
170 }
171
172 /* We don't actually support this.  It doesn't make sense for clients to
173  * send each other GLX events.
174  */
175 static Status
176 __glXEventToWire(Display *dpy, XEvent *event, xEvent *wire)
177 {
178    __GLXdisplayPrivate *glx_dpy = __glXInitialize(dpy);
179
180    if (glx_dpy == NULL)
181       return False;
182
183    switch (event->type) {
184    case GLX_DAMAGED:
185       break;
186    case GLX_SAVED:
187       break;
188    case GLX_EXCHANGE_COMPLETE_INTEL:
189       break;
190    case GLX_COPY_COMPLETE_INTEL:
191       break;
192    case GLX_FLIP_COMPLETE_INTEL:
193       break;
194    default:
195       /* client doesn't support server event */
196       break;
197    }
198
199    return Success;
200 }
201
202 /************************************************************************/
203 /*
204 ** Free the per screen configs data as well as the array of
205 ** __glXScreenConfigs.
206 */
207 static void
208 FreeScreenConfigs(__GLXdisplayPrivate * priv)
209 {
210    __GLXscreenConfigs *psc;
211    GLint i, screens;
212
213    /* Free screen configuration information */
214    screens = ScreenCount(priv->dpy);
215    for (i = 0; i < screens; i++) {
216       psc = priv->screenConfigs[i];
217       if (psc->configs) {
218          _gl_context_modes_destroy(psc->configs);
219          if (psc->effectiveGLXexts)
220             Xfree(psc->effectiveGLXexts);
221          psc->configs = NULL;   /* NOTE: just for paranoia */
222       }
223       if (psc->visuals) {
224          _gl_context_modes_destroy(psc->visuals);
225          psc->visuals = NULL;   /* NOTE: just for paranoia */
226       }
227       Xfree((char *) psc->serverGLXexts);
228
229 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
230       if (psc->driScreen) {
231          psc->driScreen->destroyScreen(psc);
232       } else {
233          Xfree(psc);
234       }
235 #else
236       Xfree(psc);
237 #endif
238    }
239    XFree((char *) priv->screenConfigs);
240    priv->screenConfigs = NULL;
241 }
242
243 /*
244 ** Release the private memory referred to in a display private
245 ** structure.  The caller will free the extension structure.
246 */
247 static int
248 __glXCloseDisplay(Display * dpy, XExtCodes * codes)
249 {
250    __GLXdisplayPrivate *priv, **prev;
251    GLXContext gc;
252
253    _XLockMutex(_Xglobal_lock);
254    prev = &glx_displays;
255    for (priv = glx_displays; priv; prev = &priv->next, priv = priv->next) {
256       if (priv->dpy == dpy) {
257          (*prev)->next = priv->next;
258          break;
259       }
260    }
261    _XUnlockMutex(_Xglobal_lock);
262
263    gc = __glXGetCurrentContext();
264    if (dpy == gc->currentDpy) {
265       gc->vtable->destroy(gc);
266       __glXSetCurrentContextNull();
267    }
268
269    FreeScreenConfigs(priv);
270    if (priv->serverGLXvendor)
271       Xfree((char *) priv->serverGLXvendor);
272    if (priv->serverGLXversion)
273       Xfree((char *) priv->serverGLXversion);
274
275    __glxHashDestroy(priv->drawHash);
276
277 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
278    /* Free the direct rendering per display data */
279    if (priv->driswDisplay)
280       (*priv->driswDisplay->destroyDisplay) (priv->driswDisplay);
281    priv->driswDisplay = NULL;
282
283    if (priv->driDisplay)
284       (*priv->driDisplay->destroyDisplay) (priv->driDisplay);
285    priv->driDisplay = NULL;
286
287    if (priv->dri2Display)
288       (*priv->dri2Display->destroyDisplay) (priv->dri2Display);
289    priv->dri2Display = NULL;
290 #endif
291
292    Xfree((char *) priv);
293
294    return 1;
295 }
296
297 /*
298 ** Query the version of the GLX extension.  This procedure works even if
299 ** the client extension is not completely set up.
300 */
301 static Bool
302 QueryVersion(Display * dpy, int opcode, int *major, int *minor)
303 {
304 #ifdef USE_XCB
305    xcb_connection_t *c = XGetXCBConnection(dpy);
306    xcb_glx_query_version_reply_t *reply = xcb_glx_query_version_reply(c,
307                                                                       xcb_glx_query_version
308                                                                       (c,
309                                                                        GLX_MAJOR_VERSION,
310                                                                        GLX_MINOR_VERSION),
311                                                                       NULL);
312
313    if (reply->major_version != GLX_MAJOR_VERSION) {
314       free(reply);
315       return GL_FALSE;
316    }
317    *major = reply->major_version;
318    *minor = min(reply->minor_version, GLX_MINOR_VERSION);
319    free(reply);
320    return GL_TRUE;
321 #else
322    xGLXQueryVersionReq *req;
323    xGLXQueryVersionReply reply;
324
325    /* Send the glXQueryVersion request */
326    LockDisplay(dpy);
327    GetReq(GLXQueryVersion, req);
328    req->reqType = opcode;
329    req->glxCode = X_GLXQueryVersion;
330    req->majorVersion = GLX_MAJOR_VERSION;
331    req->minorVersion = GLX_MINOR_VERSION;
332    _XReply(dpy, (xReply *) & reply, 0, False);
333    UnlockDisplay(dpy);
334    SyncHandle();
335
336    if (reply.majorVersion != GLX_MAJOR_VERSION) {
337       /*
338        ** The server does not support the same major release as this
339        ** client.
340        */
341       return GL_FALSE;
342    }
343    *major = reply.majorVersion;
344    *minor = min(reply.minorVersion, GLX_MINOR_VERSION);
345    return GL_TRUE;
346 #endif /* USE_XCB */
347 }
348
349 /* 
350  * We don't want to enable this GLX_OML_swap_method in glxext.h, 
351  * because we can't support it.  The X server writes it out though,
352  * so we should handle it somehow, to avoid false warnings.
353  */
354 enum {
355     IGNORE_GLX_SWAP_METHOD_OML = 0x8060
356 };
357
358
359 /*
360  * getVisualConfigs uses the !tagged_only path.
361  * getFBConfigs uses the tagged_only path.
362  */
363 _X_HIDDEN void
364 __glXInitializeVisualConfigFromTags(__GLcontextModes * config, int count,
365                                     const INT32 * bp, Bool tagged_only,
366                                     Bool fbconfig_style_tags)
367 {
368    int i;
369
370    if (!tagged_only) {
371       /* Copy in the first set of properties */
372       config->visualID = *bp++;
373
374       config->visualType = _gl_convert_from_x_visual_type(*bp++);
375
376       config->rgbMode = *bp++;
377
378       config->redBits = *bp++;
379       config->greenBits = *bp++;
380       config->blueBits = *bp++;
381       config->alphaBits = *bp++;
382       config->accumRedBits = *bp++;
383       config->accumGreenBits = *bp++;
384       config->accumBlueBits = *bp++;
385       config->accumAlphaBits = *bp++;
386
387       config->doubleBufferMode = *bp++;
388       config->stereoMode = *bp++;
389
390       config->rgbBits = *bp++;
391       config->depthBits = *bp++;
392       config->stencilBits = *bp++;
393       config->numAuxBuffers = *bp++;
394       config->level = *bp++;
395
396 #ifdef GLX_USE_APPLEGL
397        /* AppleSGLX supports pixmap and pbuffers with all config. */
398        config->drawableType = GLX_WINDOW_BIT | GLX_PIXMAP_BIT | GLX_PBUFFER_BIT;
399        /* Unfortunately this can create an ABI compatibility problem. */
400        count -= 18;
401 #else
402       count -= __GLX_MIN_CONFIG_PROPS;
403 #endif
404    }
405
406    /*
407     ** Additional properties may be in a list at the end
408     ** of the reply.  They are in pairs of property type
409     ** and property value.
410     */
411
412 #define FETCH_OR_SET(tag) \
413     config-> tag = ( fbconfig_style_tags ) ? *bp++ : 1
414
415    for (i = 0; i < count; i += 2) {
416       long int tag = *bp++;
417       
418       switch (tag) {
419       case GLX_RGBA:
420          FETCH_OR_SET(rgbMode);
421          break;
422       case GLX_BUFFER_SIZE:
423          config->rgbBits = *bp++;
424          break;
425       case GLX_LEVEL:
426          config->level = *bp++;
427          break;
428       case GLX_DOUBLEBUFFER:
429          FETCH_OR_SET(doubleBufferMode);
430          break;
431       case GLX_STEREO:
432          FETCH_OR_SET(stereoMode);
433          break;
434       case GLX_AUX_BUFFERS:
435          config->numAuxBuffers = *bp++;
436          break;
437       case GLX_RED_SIZE:
438          config->redBits = *bp++;
439          break;
440       case GLX_GREEN_SIZE:
441          config->greenBits = *bp++;
442          break;
443       case GLX_BLUE_SIZE:
444          config->blueBits = *bp++;
445          break;
446       case GLX_ALPHA_SIZE:
447          config->alphaBits = *bp++;
448          break;
449       case GLX_DEPTH_SIZE:
450          config->depthBits = *bp++;
451          break;
452       case GLX_STENCIL_SIZE:
453          config->stencilBits = *bp++;
454          break;
455       case GLX_ACCUM_RED_SIZE:
456          config->accumRedBits = *bp++;
457          break;
458       case GLX_ACCUM_GREEN_SIZE:
459          config->accumGreenBits = *bp++;
460          break;
461       case GLX_ACCUM_BLUE_SIZE:
462          config->accumBlueBits = *bp++;
463          break;
464       case GLX_ACCUM_ALPHA_SIZE:
465          config->accumAlphaBits = *bp++;
466          break;
467       case GLX_VISUAL_CAVEAT_EXT:
468          config->visualRating = *bp++;
469          break;
470       case GLX_X_VISUAL_TYPE:
471          config->visualType = *bp++;
472          break;
473       case GLX_TRANSPARENT_TYPE:
474          config->transparentPixel = *bp++;
475          break;
476       case GLX_TRANSPARENT_INDEX_VALUE:
477          config->transparentIndex = *bp++;
478          break;
479       case GLX_TRANSPARENT_RED_VALUE:
480          config->transparentRed = *bp++;
481          break;
482       case GLX_TRANSPARENT_GREEN_VALUE:
483          config->transparentGreen = *bp++;
484          break;
485       case GLX_TRANSPARENT_BLUE_VALUE:
486          config->transparentBlue = *bp++;
487          break;
488       case GLX_TRANSPARENT_ALPHA_VALUE:
489          config->transparentAlpha = *bp++;
490          break;
491       case GLX_VISUAL_ID:
492          config->visualID = *bp++;
493          break;
494       case GLX_DRAWABLE_TYPE:
495          config->drawableType = *bp++;
496 #ifdef GLX_USE_APPLEGL
497          /* AppleSGLX supports pixmap and pbuffers with all config. */
498          config->drawableType |= GLX_WINDOW_BIT | GLX_PIXMAP_BIT | GLX_PBUFFER_BIT;              
499 #endif
500          break;
501       case GLX_RENDER_TYPE:
502          config->renderType = *bp++;
503          break;
504       case GLX_X_RENDERABLE:
505          config->xRenderable = *bp++;
506          break;
507       case GLX_FBCONFIG_ID:
508          config->fbconfigID = *bp++;
509          break;
510       case GLX_MAX_PBUFFER_WIDTH:
511          config->maxPbufferWidth = *bp++;
512          break;
513       case GLX_MAX_PBUFFER_HEIGHT:
514          config->maxPbufferHeight = *bp++;
515          break;
516       case GLX_MAX_PBUFFER_PIXELS:
517          config->maxPbufferPixels = *bp++;
518          break;
519 #ifndef GLX_USE_APPLEGL
520       case GLX_OPTIMAL_PBUFFER_WIDTH_SGIX:
521          config->optimalPbufferWidth = *bp++;
522          break;
523       case GLX_OPTIMAL_PBUFFER_HEIGHT_SGIX:
524          config->optimalPbufferHeight = *bp++;
525          break;
526       case GLX_VISUAL_SELECT_GROUP_SGIX:
527          config->visualSelectGroup = *bp++;
528          break;
529       case GLX_SWAP_METHOD_OML:
530          config->swapMethod = *bp++;
531          break;
532 #endif
533       case GLX_SAMPLE_BUFFERS_SGIS:
534          config->sampleBuffers = *bp++;
535          break;
536       case GLX_SAMPLES_SGIS:
537          config->samples = *bp++;
538          break;
539 #ifdef GLX_USE_APPLEGL
540       case IGNORE_GLX_SWAP_METHOD_OML:
541          /* We ignore this tag.  See the comment above this function. */
542          ++bp;
543          break;
544 #else
545       case GLX_BIND_TO_TEXTURE_RGB_EXT:
546          config->bindToTextureRgb = *bp++;
547          break;
548       case GLX_BIND_TO_TEXTURE_RGBA_EXT:
549          config->bindToTextureRgba = *bp++;
550          break;
551       case GLX_BIND_TO_MIPMAP_TEXTURE_EXT:
552          config->bindToMipmapTexture = *bp++;
553          break;
554       case GLX_BIND_TO_TEXTURE_TARGETS_EXT:
555          config->bindToTextureTargets = *bp++;
556          break;
557       case GLX_Y_INVERTED_EXT:
558          config->yInverted = *bp++;
559          break;
560 #endif
561       case GLX_USE_GL:
562          if (fbconfig_style_tags)
563             bp++;
564          break;
565       case None:
566          i = count;
567          break;
568       default:
569          if(getenv("LIBGL_DIAGNOSTIC")) {
570              long int tagvalue = *bp++;
571              fprintf(stderr, "WARNING: unknown GLX tag from server: "
572                      "tag 0x%lx value 0x%lx\n", tag, tagvalue);
573          } else {
574              /* Ignore the unrecognized tag's value */
575              bp++;
576          }
577          break;
578       }
579    }
580
581    config->renderType =
582       (config->rgbMode) ? GLX_RGBA_BIT : GLX_COLOR_INDEX_BIT;
583
584    config->haveAccumBuffer = ((config->accumRedBits +
585                                config->accumGreenBits +
586                                config->accumBlueBits +
587                                config->accumAlphaBits) > 0);
588    config->haveDepthBuffer = (config->depthBits > 0);
589    config->haveStencilBuffer = (config->stencilBits > 0);
590 }
591
592 static __GLcontextModes *
593 createConfigsFromProperties(Display * dpy, int nvisuals, int nprops,
594                             int screen, GLboolean tagged_only)
595 {
596    INT32 buf[__GLX_TOTAL_CONFIG], *props;
597    unsigned prop_size;
598    __GLcontextModes *modes, *m;
599    int i;
600
601    if (nprops == 0)
602       return NULL;
603
604    /* FIXME: Is the __GLX_MIN_CONFIG_PROPS test correct for FBconfigs? */
605
606    /* Check number of properties */
607    if (nprops < __GLX_MIN_CONFIG_PROPS || nprops > __GLX_MAX_CONFIG_PROPS)
608       return NULL;
609
610    /* Allocate memory for our config structure */
611    modes = _gl_context_modes_create(nvisuals, sizeof(__GLcontextModes));
612    if (!modes)
613       return NULL;
614
615    prop_size = nprops * __GLX_SIZE_INT32;
616    if (prop_size <= sizeof(buf))
617       props = buf;
618    else
619       props = Xmalloc(prop_size);
620
621    /* Read each config structure and convert it into our format */
622    m = modes;
623    for (i = 0; i < nvisuals; i++) {
624       _XRead(dpy, (char *) props, prop_size);
625 #ifdef GLX_USE_APPLEGL
626        /* Older X servers don't send this so we default it here. */
627       m->drawableType = GLX_WINDOW_BIT;
628 #else
629       /* 
630        * The XQuartz 2.3.2.1 X server doesn't set this properly, so
631        * set the proper bits here.
632        * AppleSGLX supports windows, pixmaps, and pbuffers with all config.
633        */
634       m->drawableType = GLX_WINDOW_BIT | GLX_PIXMAP_BIT | GLX_PBUFFER_BIT;
635 #endif
636        __glXInitializeVisualConfigFromTags(m, nprops, props,
637                                           tagged_only, GL_TRUE);
638       m->screen = screen;
639       m = m->next;
640    }
641
642    if (props != buf)
643       Xfree(props);
644
645    return modes;
646 }
647
648 static GLboolean
649 getVisualConfigs(__GLXscreenConfigs *psc,
650                  __GLXdisplayPrivate *priv, int screen)
651 {
652    xGLXGetVisualConfigsReq *req;
653    xGLXGetVisualConfigsReply reply;
654    Display *dpy = priv->dpy;
655
656    LockDisplay(dpy);
657
658    psc->visuals = NULL;
659    GetReq(GLXGetVisualConfigs, req);
660    req->reqType = priv->majorOpcode;
661    req->glxCode = X_GLXGetVisualConfigs;
662    req->screen = screen;
663
664    if (!_XReply(dpy, (xReply *) & reply, 0, False))
665       goto out;
666
667    psc->visuals = createConfigsFromProperties(dpy,
668                                               reply.numVisuals,
669                                               reply.numProps,
670                                               screen, GL_FALSE);
671
672  out:
673    UnlockDisplay(dpy);
674    return psc->visuals != NULL;
675 }
676
677 static GLboolean
678 getFBConfigs(__GLXscreenConfigs *psc, __GLXdisplayPrivate *priv, int screen)
679 {
680    xGLXGetFBConfigsReq *fb_req;
681    xGLXGetFBConfigsSGIXReq *sgi_req;
682    xGLXVendorPrivateWithReplyReq *vpreq;
683    xGLXGetFBConfigsReply reply;
684    Display *dpy = priv->dpy;
685
686    psc->serverGLXexts =
687       __glXQueryServerString(dpy, priv->majorOpcode, screen, GLX_EXTENSIONS);
688
689    LockDisplay(dpy);
690
691    psc->configs = NULL;
692    if (atof(priv->serverGLXversion) >= 1.3) {
693       GetReq(GLXGetFBConfigs, fb_req);
694       fb_req->reqType = priv->majorOpcode;
695       fb_req->glxCode = X_GLXGetFBConfigs;
696       fb_req->screen = screen;
697    }
698    else if (strstr(psc->serverGLXexts, "GLX_SGIX_fbconfig") != NULL) {
699       GetReqExtra(GLXVendorPrivateWithReply,
700                   sz_xGLXGetFBConfigsSGIXReq +
701                   sz_xGLXVendorPrivateWithReplyReq, vpreq);
702       sgi_req = (xGLXGetFBConfigsSGIXReq *) vpreq;
703       sgi_req->reqType = priv->majorOpcode;
704       sgi_req->glxCode = X_GLXVendorPrivateWithReply;
705       sgi_req->vendorCode = X_GLXvop_GetFBConfigsSGIX;
706       sgi_req->screen = screen;
707    }
708    else
709       goto out;
710
711    if (!_XReply(dpy, (xReply *) & reply, 0, False))
712       goto out;
713
714    psc->configs = createConfigsFromProperties(dpy,
715                                               reply.numFBConfigs,
716                                               reply.numAttribs * 2,
717                                               screen, GL_TRUE);
718
719  out:
720    UnlockDisplay(dpy);
721    return psc->configs != NULL;
722 }
723
724 _X_HIDDEN Bool
725 glx_screen_init(__GLXscreenConfigs *psc,
726                 int screen, __GLXdisplayPrivate * priv)
727 {
728    /* Initialize per screen dynamic client GLX extensions */
729    psc->ext_list_first_time = GL_TRUE;
730    psc->scr = screen;
731    psc->dpy = priv->dpy;
732    psc->display = priv;
733
734    getVisualConfigs(psc, priv, screen);
735    getFBConfigs(psc, priv, screen);
736
737    return GL_TRUE;
738 }
739
740 /*
741 ** Allocate the memory for the per screen configs for each screen.
742 ** If that works then fetch the per screen configs data.
743 */
744 static Bool
745 AllocAndFetchScreenConfigs(Display * dpy, __GLXdisplayPrivate * priv)
746 {
747    __GLXscreenConfigs *psc;
748    GLint i, screens;
749
750    /*
751     ** First allocate memory for the array of per screen configs.
752     */
753    screens = ScreenCount(dpy);
754    priv->screenConfigs = Xmalloc(screens * sizeof *priv->screenConfigs);
755    if (!priv->screenConfigs)
756       return GL_FALSE;
757
758    priv->serverGLXversion =
759       __glXQueryServerString(dpy, priv->majorOpcode, 0, GLX_VERSION);
760    if (priv->serverGLXversion == NULL) {
761       FreeScreenConfigs(priv);
762       return GL_FALSE;
763    }
764
765    for (i = 0; i < screens; i++, psc++) {
766       psc = NULL;
767 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
768       if (priv->dri2Display)
769          psc = (*priv->dri2Display->createScreen) (i, priv);
770       if (psc == NULL && priv->driDisplay)
771          psc = (*priv->driDisplay->createScreen) (i, priv);
772       if (psc == NULL && priv->driswDisplay)
773          psc = (*priv->driswDisplay->createScreen) (i, priv);
774 #endif
775       if (psc == NULL)
776          psc = indirect_create_screen(i, priv);
777       priv->screenConfigs[i] = psc;
778    }
779    SyncHandle();
780    return GL_TRUE;
781 }
782
783 /*
784 ** Initialize the client side extension code.
785 */
786 _X_HIDDEN __GLXdisplayPrivate *
787 __glXInitialize(Display * dpy)
788 {
789    __GLXdisplayPrivate *dpyPriv;
790 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
791    Bool glx_direct, glx_accel;
792 #endif
793    int i;
794
795    _XLockMutex(_Xglobal_lock);
796
797    for (dpyPriv = glx_displays; dpyPriv; dpyPriv = dpyPriv->next) {
798       if (dpyPriv->dpy == dpy) {
799          _XUnlockMutex(_Xglobal_lock);
800          return dpyPriv;
801       }
802    }
803
804    dpyPriv = Xcalloc(1, sizeof *dpyPriv);
805    if (!dpyPriv)
806       return NULL;
807
808    dpyPriv->codes = XInitExtension(dpy, __glXExtensionName);
809    if (!dpyPriv->codes) {
810       Xfree(dpyPriv);
811       _XUnlockMutex(_Xglobal_lock);
812       return NULL;
813    }
814
815    dpyPriv->dpy = dpy;
816    dpyPriv->majorOpcode = dpyPriv->codes->major_opcode;
817    dpyPriv->serverGLXvendor = 0x0;
818    dpyPriv->serverGLXversion = 0x0;
819
820    /* See if the versions are compatible */
821    if (!QueryVersion(dpy, dpyPriv->majorOpcode,
822                      &dpyPriv->majorVersion, &dpyPriv->minorVersion)) {
823       Xfree(dpyPriv);
824       _XUnlockMutex(_Xglobal_lock);
825       return NULL;
826    }
827
828    for (i = 0; i < __GLX_NUMBER_EVENTS; i++) {
829       XESetWireToEvent(dpy, dpyPriv->codes->first_event + i, __glXWireToEvent);
830       XESetEventToWire(dpy, dpyPriv->codes->first_event + i, __glXEventToWire);
831    }
832
833    XESetCloseDisplay(dpy, dpyPriv->codes->extension, __glXCloseDisplay);
834    XESetErrorString (dpy, dpyPriv->codes->extension,__glXErrorString);
835
836 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
837    glx_direct = (getenv("LIBGL_ALWAYS_INDIRECT") == NULL);
838    glx_accel = (getenv("LIBGL_ALWAYS_SOFTWARE") == NULL);
839
840    dpyPriv->drawHash = __glxHashCreate();
841
842    /*
843     ** Initialize the direct rendering per display data and functions.
844     ** Note: This _must_ be done before calling any other DRI routines
845     ** (e.g., those called in AllocAndFetchScreenConfigs).
846     */
847    if (glx_direct && glx_accel) {
848       dpyPriv->dri2Display = dri2CreateDisplay(dpy);
849       dpyPriv->driDisplay = driCreateDisplay(dpy);
850    }
851    if (glx_direct)
852       dpyPriv->driswDisplay = driswCreateDisplay(dpy);
853 #endif
854
855 #ifdef GLX_USE_APPLEGL
856    if (apple_init_glx(dpy)) {
857       Xfree(dpyPriv);
858       return NULL;
859    }
860 #endif
861    if (!AllocAndFetchScreenConfigs(dpy, dpyPriv)) {
862       Xfree(dpyPriv);
863       return NULL;
864    }
865
866    if (dpyPriv->majorVersion == 1 && dpyPriv->minorVersion >= 1)
867       __glXClientInfo(dpy, dpyPriv->majorOpcode);
868
869    dpyPriv->next = glx_displays;
870    glx_displays = dpyPriv;
871
872     _XUnlockMutex(_Xglobal_lock);
873
874    return dpyPriv;
875 }
876
877 /*
878 ** Setup for sending a GLX command on dpy.  Make sure the extension is
879 ** initialized.  Try to avoid calling __glXInitialize as its kinda slow.
880 */
881 _X_HIDDEN CARD8
882 __glXSetupForCommand(Display * dpy)
883 {
884    GLXContext gc;
885    __GLXdisplayPrivate *priv;
886
887    /* If this thread has a current context, flush its rendering commands */
888    gc = __glXGetCurrentContext();
889    if (gc->currentDpy) {
890       /* Flush rendering buffer of the current context, if any */
891       (void) __glXFlushRenderBuffer(gc, gc->pc);
892
893       if (gc->currentDpy == dpy) {
894          /* Use opcode from gc because its right */
895          return gc->majorOpcode;
896       }
897       else {
898          /*
899           ** Have to get info about argument dpy because it might be to
900           ** a different server
901           */
902       }
903    }
904
905    /* Forced to lookup extension via the slow initialize route */
906    priv = __glXInitialize(dpy);
907    if (!priv) {
908       return 0;
909    }
910    return priv->majorOpcode;
911 }
912
913 /**
914  * Flush the drawing command transport buffer.
915  *
916  * \param ctx  Context whose transport buffer is to be flushed.
917  * \param pc   Pointer to first unused buffer location.
918  *
919  * \todo
920  * Modify this function to use \c ctx->pc instead of the explicit
921  * \c pc parameter.
922  */
923 _X_HIDDEN GLubyte *
924 __glXFlushRenderBuffer(__GLXcontext * ctx, GLubyte * pc)
925 {
926    Display *const dpy = ctx->currentDpy;
927 #ifdef USE_XCB
928    xcb_connection_t *c = XGetXCBConnection(dpy);
929 #else
930    xGLXRenderReq *req;
931 #endif /* USE_XCB */
932    const GLint size = pc - ctx->buf;
933
934    if ((dpy != NULL) && (size > 0)) {
935 #ifdef USE_XCB
936       xcb_glx_render(c, ctx->currentContextTag, size,
937                      (const uint8_t *) ctx->buf);
938 #else
939       /* Send the entire buffer as an X request */
940       LockDisplay(dpy);
941       GetReq(GLXRender, req);
942       req->reqType = ctx->majorOpcode;
943       req->glxCode = X_GLXRender;
944       req->contextTag = ctx->currentContextTag;
945       req->length += (size + 3) >> 2;
946       _XSend(dpy, (char *) ctx->buf, size);
947       UnlockDisplay(dpy);
948       SyncHandle();
949 #endif
950    }
951
952    /* Reset pointer and return it */
953    ctx->pc = ctx->buf;
954    return ctx->pc;
955 }
956
957
958 /**
959  * Send a portion of a GLXRenderLarge command to the server.  The advantage of
960  * this function over \c __glXSendLargeCommand is that callers can use the
961  * data buffer in the GLX context and may be able to avoid allocating an
962  * extra buffer.  The disadvantage is the clients will have to do more
963  * GLX protocol work (i.e., calculating \c totalRequests, etc.).
964  *
965  * \sa __glXSendLargeCommand
966  *
967  * \param gc             GLX context
968  * \param requestNumber  Which part of the whole command is this?  The first
969  *                       request is 1.
970  * \param totalRequests  How many requests will there be?
971  * \param data           Command data.
972  * \param dataLen        Size, in bytes, of the command data.
973  */
974 _X_HIDDEN void
975 __glXSendLargeChunk(__GLXcontext * gc, GLint requestNumber,
976                     GLint totalRequests, const GLvoid * data, GLint dataLen)
977 {
978    Display *dpy = gc->currentDpy;
979 #ifdef USE_XCB
980    xcb_connection_t *c = XGetXCBConnection(dpy);
981    xcb_glx_render_large(c, gc->currentContextTag, requestNumber,
982                         totalRequests, dataLen, data);
983 #else
984    xGLXRenderLargeReq *req;
985
986    if (requestNumber == 1) {
987       LockDisplay(dpy);
988    }
989
990    GetReq(GLXRenderLarge, req);
991    req->reqType = gc->majorOpcode;
992    req->glxCode = X_GLXRenderLarge;
993    req->contextTag = gc->currentContextTag;
994    req->length += (dataLen + 3) >> 2;
995    req->requestNumber = requestNumber;
996    req->requestTotal = totalRequests;
997    req->dataBytes = dataLen;
998    Data(dpy, data, dataLen);
999
1000    if (requestNumber == totalRequests) {
1001       UnlockDisplay(dpy);
1002       SyncHandle();
1003    }
1004 #endif /* USE_XCB */
1005 }
1006
1007
1008 /**
1009  * Send a command that is too large for the GLXRender protocol request.
1010  *
1011  * Send a large command, one that is too large for some reason to
1012  * send using the GLXRender protocol request.  One reason to send
1013  * a large command is to avoid copying the data.
1014  *
1015  * \param ctx        GLX context
1016  * \param header     Header data.
1017  * \param headerLen  Size, in bytes, of the header data.  It is assumed that
1018  *                   the header data will always be small enough to fit in
1019  *                   a single X protocol packet.
1020  * \param data       Command data.
1021  * \param dataLen    Size, in bytes, of the command data.
1022  */
1023 _X_HIDDEN void
1024 __glXSendLargeCommand(__GLXcontext * ctx,
1025                       const GLvoid * header, GLint headerLen,
1026                       const GLvoid * data, GLint dataLen)
1027 {
1028    GLint maxSize;
1029    GLint totalRequests, requestNumber;
1030
1031    /*
1032     ** Calculate the maximum amount of data can be stuffed into a single
1033     ** packet.  sz_xGLXRenderReq is added because bufSize is the maximum
1034     ** packet size minus sz_xGLXRenderReq.
1035     */
1036    maxSize = (ctx->bufSize + sz_xGLXRenderReq) - sz_xGLXRenderLargeReq;
1037    totalRequests = 1 + (dataLen / maxSize);
1038    if (dataLen % maxSize)
1039       totalRequests++;
1040
1041    /*
1042     ** Send all of the command, except the large array, as one request.
1043     */
1044    assert(headerLen <= maxSize);
1045    __glXSendLargeChunk(ctx, 1, totalRequests, header, headerLen);
1046
1047    /*
1048     ** Send enough requests until the whole array is sent.
1049     */
1050    for (requestNumber = 2; requestNumber <= (totalRequests - 1);
1051         requestNumber++) {
1052       __glXSendLargeChunk(ctx, requestNumber, totalRequests, data, maxSize);
1053       data = (const GLvoid *) (((const GLubyte *) data) + maxSize);
1054       dataLen -= maxSize;
1055       assert(dataLen > 0);
1056    }
1057
1058    assert(dataLen <= maxSize);
1059    __glXSendLargeChunk(ctx, requestNumber, totalRequests, data, dataLen);
1060 }
1061
1062 /************************************************************************/
1063
1064 #ifdef DEBUG
1065 _X_HIDDEN void
1066 __glXDumpDrawBuffer(__GLXcontext * ctx)
1067 {
1068    GLubyte *p = ctx->buf;
1069    GLubyte *end = ctx->pc;
1070    GLushort opcode, length;
1071
1072    while (p < end) {
1073       /* Fetch opcode */
1074       opcode = *((GLushort *) p);
1075       length = *((GLushort *) (p + 2));
1076       printf("%2x: %5d: ", opcode, length);
1077       length -= 4;
1078       p += 4;
1079       while (length > 0) {
1080          printf("%08x ", *((unsigned *) p));
1081          p += 4;
1082          length -= 4;
1083       }
1084       printf("\n");
1085    }
1086 }
1087 #endif