aboutsummaryrefslogtreecommitdiff
path: root/xorg-server/hw/xwin/glx/gen_gl_wrappers.py
blob: 683b9d9034bbb0957c30687159713791e98e7e23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
#!/usr/bin/python3
#
# python script to generate cdecl to stdcall wrappers for GL functions
# adapted from genheaders.py
#
# Copyright (c) 2013 The Khronos Group Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and/or associated documentation files (the
# "Materials"), to deal in the Materials without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Materials, and to
# permit persons to whom the Materials are furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Materials.
#
# THE MATERIALS ARE 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
# MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.

import sys, time, pdb, string, cProfile
from reg import *

# Default input / log files
errFilename = None
diagFilename = 'diag.txt'
regFilename = 'gl.xml'
outFilename = 'gen_gl_wrappers.c'

protect=True
prefix="gl"
preresolve=False
wrapper=False
shim=False
thunk=False
thunkdefs=False
staticwrappers=False
nodebug=False

#exclude base WGL API
WinGDI={key: 1 for key in [
     "wglCopyContext"
    ,"wglCreateContext"
    ,"wglCreateLayerContext"
    ,"wglDeleteContext"
    ,"wglGetCurrentContext"
    ,"wglGetCurrentDC"
    ,"wglGetProcAddress"
    ,"wglMakeCurrent"
    ,"wglShareLists"
    ,"wglUseFontBitmapsA"
    ,"wglUseFontBitmapsW"
    ,"wglUseFontBitmaps"
    ,"SwapBuffers"
    ,"wglUseFontOutlinesA"
    ,"wglUseFontOutlinesW"
    ,"wglUseFontOutlines"
    ,"wglDescribeLayerPlane"
    ,"wglSetLayerPaletteEntries"
    ,"wglGetLayerPaletteEntries"
    ,"wglRealizeLayerPalette"
    ,"wglSwapLayerBuffers"
    ,"wglSwapMultipleBuffers"
    ,"ChoosePixelFormat"
    ,"DescribePixelFormat"
    ,"GetEnhMetaFilePixelFormat"
    ,"GetPixelFormat"
    ,"SetPixelFormat"
]}

if __name__ == '__main__':
    i = 1
    while (i < len(sys.argv)):
        arg = sys.argv[i]
        i = i + 1
        if (arg == '-noprotect'):
            print('Disabling inclusion protection in output headers', file=sys.stderr)
            protect = False
        elif (arg == '-registry'):
            regFilename = sys.argv[i]
            i = i+1
            print('Using registry', regFilename, file=sys.stderr)
        elif (arg == '-outfile'):
            outFilename = sys.argv[i]
            i = i+1
        elif (arg == '-preresolve'):
            preresolve=True
        elif (arg == '-wrapper'):
            wrapper=True
        elif (arg == '-shim'):
            shim=True
        elif (arg == '-thunk'):
            thunk=True
        elif (arg == '-thunkdefs'):
            thunkdefs=True
        elif (arg == '-staticwrappers'):
            staticwrappers=True
        elif (arg == '-prefix'):
            prefix = sys.argv[i]
            i = i+1
        elif (arg == '-nodebug'):
            nodebug = True
        elif (arg[0:1] == '-'):
            print('Unrecognized argument:', arg, file=sys.stderr)
            exit(1)

print('Generating', outFilename, file=sys.stderr)

# Load & parse registry
reg = Registry()
tree = etree.parse(regFilename)
reg.loadElementTree(tree)

allVersions = '.*'

genOpts = CGeneratorOptions(
        apiname           = prefix,
        profile           = 'compatibility',
        versions          = allVersions,
        emitversions      = allVersions,
        defaultExtensions = prefix,                   # Default extensions for GL
        protectFile       = protect,
        protectFeature    = protect,
        protectProto      = protect,
        )

# create error/warning & diagnostic files
if (errFilename):
    errWarn = open(errFilename,'w')
else:
    errWarn = sys.stderr
diag = open(diagFilename, 'w')

class PreResolveOutputGenerator(OutputGenerator):
    def __init__(self,
                 errFile = sys.stderr,
                 warnFile = sys.stderr,
                 diagFile = sys.stdout):
        OutputGenerator.__init__(self, errFile, warnFile, diagFile)
        self.wrappers={}
    def beginFile(self, genOpts):
        self.outFile.write('/* Automatically generated from %s - DO NOT EDIT */\n\n'%regFilename)
    def endFile(self):
        self.outFile.write('\nvoid ' + prefix + 'ResolveExtensionProcs(void)\n{\n')
        for funcname in self.wrappers.keys():
            self.outFile.write( '  PRERESOLVE(PFN' + funcname.upper() + 'PROC, "' + funcname + '");\n')
        self.outFile.write('}\n\n')
    def beginFeature(self, interface, emit):
        OutputGenerator.beginFeature(self, interface, emit)
    def endFeature(self):
        OutputGenerator.endFeature(self)
    def genType(self, typeinfo, name):
        OutputGenerator.genType(self, typeinfo, name)
    def genEnum(self, enuminfo, name):
        OutputGenerator.genEnum(self, enuminfo, name)
    def genCmd(self, cmd, name):
        OutputGenerator.genCmd(self, cmd, name)

        if name in WinGDI:
            return

        self.outFile.write('RESOLVE_DECL(PFN' + name.upper() + 'PROC);\n')
        self.wrappers[name]=1

class WrapperOutputGenerator(OutputGenerator):
    def __init__(self,
                 errFile = sys.stderr,
                 warnFile = sys.stderr,
                 diagFile = sys.stdout):
        OutputGenerator.__init__(self, errFile, warnFile, diagFile)
    def beginFile(self, genOpts):
        self.outFile.write('/* Automatically generated from %s - DO NOT EDIT */\n\n'%regFilename)
    def endFile(self):
        pass
    def beginFeature(self, interface, emit):
        OutputGenerator.beginFeature(self, interface, emit)
        self.OldVersion = self.featureName.startswith('GL_VERSION_1_0') or self.featureName.startswith('GL_VERSION_1_1')
    def endFeature(self):
        OutputGenerator.endFeature(self)
    def genType(self, typeinfo, name):
        OutputGenerator.genType(self, typeinfo, name)
    def genEnum(self, enuminfo, name):
        OutputGenerator.genEnum(self, enuminfo, name)
    def genCmd(self, cmd, name):
        OutputGenerator.genCmd(self, cmd, name)

        if name in WinGDI:
            return

        proto=noneStr(cmd.elem.find('proto'))
        rettype=noneStr(proto.text)
        if rettype.lower()!="void ":
            plist = ([t for t in proto.itertext()])
            rettype = ''.join(plist[:-1])
        rettype=rettype.strip()
        if staticwrappers: self.outFile.write("static ")
        self.outFile.write("%s %sWrapper("%(rettype, name))
        params = cmd.elem.findall('param')
        plist=[]
        for param in params:
            paramlist = ([t for t in param.itertext()])
            paramtype = ''.join(paramlist[:-1])
            paramname = paramlist[-1]
            plist.append((paramtype, paramname))
        Comma=""
        if len(plist):
            for ptype, pname in plist:
                self.outFile.write("%s%s%s_"%(Comma, ptype, pname))
                Comma=", "
        else:
            self.outFile.write("void")

        self.outFile.write(")\n{\n")

        # for GL 1.0 and 1.1 functions, generate stdcall wrappers which call the function directly
        if self.OldVersion:
            if not nodebug:
                self.outFile.write('  if (glxWinDebugSettings.enable%scallTrace) ErrorF("%s\\n");\n'%(prefix.upper(), name))
                self.outFile.write("  glWinDirectProcCalls++;\n")
                self.outFile.write("\n")

            if rettype.lower()=="void":
                self.outFile.write("  %s( "%(name))
            else:
                self.outFile.write("  return %s( "%(name))

            Comma=""
            for ptype, pname in plist:
                self.outFile.write("%s%s_"%(Comma, pname))
                Comma=", "

        # for GL 1.2+ functions, generate stdcall wrappers which use wglGetProcAddress()
        else:
            if rettype.lower()=="void":
                self.outFile.write('  RESOLVE(PFN%sPROC, "%s");\n'%(name.upper(), name))

                if not nodebug:
                    self.outFile.write("\n")
                    self.outFile.write('  if (glxWinDebugSettings.enable%scallTrace) ErrorF("%s\\n");\n'%(prefix.upper(), name))
                    self.outFile.write("\n")

                self.outFile.write("  RESOLVED_PROC(PFN%sPROC)( """%(name.upper()))
            else:
                self.outFile.write('  RESOLVE_RET(PFN%sPROC, "%s", FALSE);\n'%(name.upper(), name))

                if not nodebug:
                    self.outFile.write("\n")
                    self.outFile.write('  if (glxWinDebugSettings.enable%scallTrace) ErrorF("%s\\n");\n'%(prefix.upper(), name))
                    self.outFile.write("\n")

                self.outFile.write("  return RESOLVED_PROC(PFN%sPROC)("%(name.upper()))

            Comma=""
            for ptype, pname in plist:
                self.outFile.write("%s%s_"%(Comma, pname))
                Comma=", "
        self.outFile.write(" );\n}\n\n")

class ThunkOutputGenerator(OutputGenerator):
    def __init__(self,
                 errFile = sys.stderr,
                 warnFile = sys.stderr,
                 diagFile = sys.stdout):
        OutputGenerator.__init__(self, errFile, warnFile, diagFile)
    def beginFile(self, genOpts):
        self.outFile.write('/* Automatically generated from %s - DO NOT EDIT */\n\n'%regFilename)
    def endFile(self):
        pass
    def beginFeature(self, interface, emit):
        OutputGenerator.beginFeature(self, interface, emit)
        self.OldVersion = self.featureName.startswith('GL_VERSION_1_0') or self.featureName.startswith('GL_VERSION_1_1')
    def endFeature(self):
        OutputGenerator.endFeature(self)
    def genType(self, typeinfo, name):
        OutputGenerator.genType(self, typeinfo, name)
    def genEnum(self, enuminfo, name):
        OutputGenerator.genEnum(self, enuminfo, name)
    def genCmd(self, cmd, name):
        OutputGenerator.genCmd(self, cmd, name)

        proto=noneStr(cmd.elem.find('proto'))
        rettype=noneStr(proto.text)
        if rettype.lower()!="void ":
            plist = ([t for t in proto.itertext()])
            rettype = ''.join(plist[:-1])
        rettype=rettype.strip()
        self.outFile.write("%s %sWrapper("%(rettype, name))
        params = cmd.elem.findall('param')
        plist=[]
        for param in params:
            paramlist = ([t for t in param.itertext()])
            paramtype = ''.join(paramlist[:-1])
            paramname = paramlist[-1]
            plist.append((paramtype, paramname))
        Comma=""
        if len(plist):
            for ptype, pname in plist:
                self.outFile.write("%s%s%s_"%(Comma, ptype, pname))
                Comma=", "
        else:
            self.outFile.write("void")

        self.outFile.write(")\n{\n")

        # for GL 1.0 and 1.1 functions, generate stdcall thunk wrappers which call the function directly
        if self.OldVersion:
            if rettype.lower()=="void":
                self.outFile.write("  %s( "%(name))
            else:
                self.outFile.write("  return %s( "%(name))

            Comma=""
            for ptype, pname in plist:
                self.outFile.write("%s%s_"%(Comma, pname))
                Comma=", "

        # for GL 1.2+ functions, generate wrappers which use wglGetProcAddress()
        else:
            if rettype.lower()=="void":
                self.outFile.write('  RESOLVE(PFN%sPROC, "%s");\n'%(name.upper(), name))
                self.outFile.write("  RESOLVED_PROC(PFN%sPROC)( """%(name.upper()))
            else:
                self.outFile.write('  RESOLVE_RET(PFN%sPROC, "%s", FALSE);\n'%(name.upper(), name))
                self.outFile.write("  return RESOLVED_PROC(PFN%sPROC)("%(name.upper()))

            Comma=""
            for ptype, pname in plist:
                self.outFile.write("%s%s_"%(Comma, pname))
                Comma=", "
        self.outFile.write(" );\n}\n\n")

class ThunkDefsOutputGenerator(OutputGenerator):
    def __init__(self,
                 errFile = sys.stderr,
                 warnFile = sys.stderr,
                 diagFile = sys.stdout):
        OutputGenerator.__init__(self, errFile, warnFile, diagFile)
    def beginFile(self, genOpts):
        self.outFile.write("EXPORTS\n"); # this must be the first line for libtool to realize this is a .def file
        self.outFile.write('; Automatically generated from %s - DO NOT EDIT\n\n'%regFilename)
    def endFile(self):
        pass
    def beginFeature(self, interface, emit):
        OutputGenerator.beginFeature(self, interface, emit)
    def endFeature(self):
        OutputGenerator.endFeature(self)
    def genType(self, typeinfo, name):
        OutputGenerator.genType(self, typeinfo, name)
    def genEnum(self, enuminfo, name):
        OutputGenerator.genEnum(self, enuminfo, name)
    def genCmd(self, cmd, name):
        OutputGenerator.genCmd(self, cmd, name)

        # export the wrapper function with the name of the function it wraps
        self.outFile.write("%s = %sWrapper\n"%(name, name))

class ShimOutputGenerator(OutputGenerator):
    def __init__(self,
                 errFile = sys.stderr,
                 warnFile = sys.stderr,
                 diagFile = sys.stdout):
        OutputGenerator.__init__(self, errFile, warnFile, diagFile)
    def beginFile(self, genOpts):
        self.outFile.write('/* Automatically generated from %s - DO NOT EDIT */\n\n'%regFilename)
    def endFile(self):
        pass
    def beginFeature(self, interface, emit):
        OutputGenerator.beginFeature(self, interface, emit)
        self.OldVersion = self.featureName.startswith('GL_VERSION_1_0') or self.featureName.startswith('GL_VERSION_1_1') or self.featureName.startswith('GL_VERSION_1_2') or self.featureName.startswith('GL_ARB_imaging') or self.featureName.startswith('GL_ARB_multitexture') or self.featureName.startswith('GL_ARB_texture_compression')
    def endFeature(self):
        OutputGenerator.endFeature(self)
    def genType(self, typeinfo, name):
        OutputGenerator.genType(self, typeinfo, name)
    def genEnum(self, enuminfo, name):
        OutputGenerator.genEnum(self, enuminfo, name)
    def genCmd(self, cmd, name):
        OutputGenerator.genCmd(self, cmd, name)

        if not self.OldVersion:
            return

        # for GL functions which are in the ABI, generate a shim which calls the function via GetProcAddress
        proto=noneStr(cmd.elem.find('proto'))
        rettype=noneStr(proto.text)
        if rettype.lower()!="void ":
            plist = ([t for t in proto.itertext()])
            rettype = ''.join(plist[:-1])
        rettype=rettype.strip()
        self.outFile.write("%s %s("%(rettype, name))
        params = cmd.elem.findall('param')
        plist=[]
        for param in params:
            paramlist = ([t for t in param.itertext()])
            paramtype = ''.join(paramlist[:-1])
            paramname = paramlist[-1]
            plist.append((paramtype, paramname))
        Comma=""
        if len(plist):
            for ptype, pname in plist:
                self.outFile.write("%s%s%s_"%(Comma, ptype, pname))
                Comma=", "
        else:
            self.outFile.write("void")

        self.outFile.write(")\n{\n")

        self.outFile.write('  typedef %s (* PFN%sPROC)(' % (rettype, name.upper()))

        if len(plist):
            Comma=""
            for ptype, pname in plist:
                self.outFile.write("%s %s %s_"%(Comma, ptype, pname))
                Comma=", "
        else:
            self.outFile.write("void")

        self.outFile.write(');\n')

        if rettype.lower()=="void":
            self.outFile.write('  RESOLVE(PFN%sPROC, "%s");\n'%(name.upper(), name))
            self.outFile.write('  RESOLVED_PROC(')
        else:
            self.outFile.write('  RESOLVE_RET(PFN%sPROC, "%s", 0);\n'%(name.upper(), name))
            self.outFile.write('  return RESOLVED_PROC(')

        Comma=""
        for ptype, pname in plist:
            self.outFile.write("%s%s_"%(Comma, pname))
            Comma=", "

        self.outFile.write(" );\n}\n\n")

def genHeaders():
    outFile = open(outFilename,"w")

    if preresolve:
        gen = PreResolveOutputGenerator(errFile=errWarn,
                                        warnFile=errWarn,
                                        diagFile=diag)
        gen.outFile=outFile
        reg.setGenerator(gen)
        reg.apiGen(genOpts)

    if wrapper:
        gen = WrapperOutputGenerator(errFile=errWarn,
                                     warnFile=errWarn,
                                     diagFile=diag)
        gen.outFile=outFile
        reg.setGenerator(gen)
        reg.apiGen(genOpts)

    if shim:
        gen = ShimOutputGenerator(errFile=errWarn,
                                  warnFile=errWarn,
                                  diagFile=diag)
        gen.outFile=outFile
        reg.setGenerator(gen)
        reg.apiGen(genOpts)

    if thunk:
        gen = ThunkOutputGenerator(errFile=errWarn,
                                   warnFile=errWarn,
                                   diagFile=diag)
        gen.outFile=outFile
        reg.setGenerator(gen)
        reg.apiGen(genOpts)


    if thunkdefs:
        gen = ThunkDefsOutputGenerator(errFile=errWarn,
                                       warnFile=errWarn,
                                       diagFile=diag)
        gen.outFile=outFile
        reg.setGenerator(gen)
        reg.apiGen(genOpts)

    outFile.close()

genHeaders()