summaryrefslogtreecommitdiff
path: root/src/waffle/dispatch/gen_dispatch.py
blob: 5b4336cc9ba10031ec8bc199343cf421bb8b0a4b (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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright © 2013 Intel Corporation
#
# 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.

import sys
import argparse
import xml.etree.ElementTree as ET
import re

class GLFunction(object):
    def __init__(self, ret_type, name):
        self.name = name
        self.ptr_type = 'PFN' + name.upper()
        self.ret_type = ret_type
        self.providers = []
        self.args = []
        self.args_list = ''
        self.args_decl = 'void'

    def add_arg(self, type, name):
        self.args.append((type, name))
        if self.args_decl == 'void':
            self.args_list = name
            self.args_decl = type + ' ' + name
        else:
            self.args_list += ', ' + name
            self.args_decl += ', ' + type + ' ' + name

    def add_provider(self, condition, loader, human_name):
        self.providers.append((condition, loader, human_name))

class Generator(object):
    def __init__(self):
        self.enums = {}
        self.functions = {}
        self.max_enum_name_len = 1
        self.copyright_comment = None
        self.typedefs = ''
        self.out_file = None

    def all_text_until_element_name(self, element, element_name):
        text = ''

        if element.text is not None:
            text += element.text

        for child in element:
            if child.tag == element_name:
                break
            if child.text:
                text += child.text
            if child.tail:
                text += child.tail
        return text

    def out(self, text):
        self.out_file.write(text)

    def outln(self, text):
        self.out_file.write(text + '\n')

    def parse_typedefs(self, reg):
        for t in reg.findall('types/type'):
            if 'name' in t.attrib and t.attrib['name'] not in {'GLhandleARB'}:
                continue

            if t.text is not None:
                self.typedefs += t.text

            for child in t:
                if child.text:
                    self.typedefs += child.text
                if child.tail:
                    self.typedefs += child.tail
            self.typedefs += '\n'

    def parse_enums(self, reg):
        for enum in reg.findall('enums/enum'):
            name = enum.get('name')
            self.max_enum_name_len = max(self.max_enum_name_len, len(name))
            self.enums[name] = enum.get('value')

    def get_function_return_type(self, proto):
        # Everything up to the start of the name element is the return type.
        return self.all_text_until_element_name(proto, 'name').strip()

    def parse_function_definitions(self, reg):
        for command in reg.findall('commands/command'):
            proto = command.find('proto')
            name = proto.find('name').text
            ret_type = self.get_function_return_type(proto)

            func = GLFunction(ret_type, name)

            for arg in command.findall('param'):
                func.add_arg(self.all_text_until_element_name(arg, 'name').strip(),
                             arg.find('name').text)

            self.functions[name] = func

    def drop_weird_glx_functions(self):
        # Drop a few ancient SGIX GLX extensions that use types not defined
        # anywhere in Xlib.  In glxext.h, they're protected by #ifdefs for the
        # headers that defined them.
        weird_functions = [name for name, func in self.functions.iteritems()
                           if 'VLServer' in func.args_decl
                           or 'DMparams' in func.args_decl]

        for name in weird_functions:
            del self.functions[name]

    def process_require_statements(self, feature, condition, loader, human_name):
        for command in feature.findall('require/command'):
            name = command.get('name')
            func = self.functions[name]
            func.add_provider(condition, loader.format(name), human_name)

    def parse_function_providers(self, reg):
        for feature in reg.findall('feature'):
            api = feature.get('api') # string gl, gles1, gles2, glx
            if api == 'gl':
                m = re.match('GL_VERSION_([0-9])_([0-9])', feature.get('name'))
                human_name = 'Desktop OpenGL {0}.{1}'.format(m.group(1), m.group(2))
                gl_ver = int(m.group(1)) * 10 + int(m.group(2))
                condition = 'is_desktop_gl()'

                # Everything in GL 1.2 is guaranteed to be present as
                # public symbols in the Linux libGL ABI.  Everything
                # else is supposed to not be present, so you have to
                # glXGetProcAddress() it.
                if gl_ver <= 12:
                    loader = 'waffle_dl_sym(WAFFLE_DL_OPENGL, "{0}")'
                else:
                    loader = 'waffle_get_proc_address("{0}")'
                    condition += ' && has_gl_version({0})'.format(gl_ver)
            else:
                human_name = ''
                condition = 'true'
                loader = 'waffle_dl_sym(WAFFLE_DL_OPENGL, "{0}")'

            self.process_require_statements(feature, condition, loader, human_name)

        for extension in reg.findall('extensions/extension'):
            extname = extension.get('name')
            # 'supported' is a set of strings like gl, gles1, gles2, or glx, which are
            # separated by '|'
            apis = extension.get('supported').split('|')
            if 'glx' in apis:
                human_name = 'GLX extension \\"{0}\\"'.format(extname)
                condition = 'has_glx_extension("{0}")'.format(extname)
                loader = 'waffle_get_proc_address("{0}")'
                self.process_require_statements(extension, condition, loader, human_name)
            if 'gl' in apis:
                human_name = 'GL extension \\"{0}\\"'.format(extname)
                condition = 'has_gl_extension("{0}")'.format(extname)
                loader = 'waffle_get_proc_address("{0}")'
                self.process_require_statements(extension, condition, loader, human_name)

    def parse(self, file):
        reg = ET.parse(file)
        if reg.find('comment') != None:
            self.copyright_comment = reg.find('comment').text
        else:
            self.copyright_comment = ''
        self.parse_typedefs(reg)
        self.parse_enums(reg)
        self.parse_function_definitions(reg)
        self.parse_function_providers(reg)

    def write_copyright_comment_body(self):
        for line in self.copyright_comment.splitlines():
            if '-----' in line:
                break
            self.outln(' * ' + line)

    def write_enums(self):
        for name, value in self.enums.iteritems():
            self.outln('#define ' + name.ljust(self.max_enum_name_len + 3) + value + '')

    def write_function_ptr_typedefs(self):
        for func in self.functions.values():
            self.outln('typedef {0} (*{1})({2});'.format(func.ret_type, func.ptr_type,
                                                         func.args_decl))

    def write_dispatch_defines(self):
        for func in self.functions.values():
            self.outln('#define {0} waffle_dispatch_{0}'.format(func.name))

    def write_header(self, file):
        self.out_file = open(file, 'w')

        self.outln('/* GL dispatch header for waffle users.')
        self.outln(' * This is code-generated from the GL API XML files from Khronos.')
        self.write_copyright_comment_body()
        self.outln(' */')
        self.outln('')

        self.outln('#pragma once')

        self.outln('#include <inttypes.h>')
        self.outln('#include <stddef.h>')
        self.outln('')

        if 'gl_dispatch.h' not in file:
            self.outln('#include "gl_dispatch.h"')
        else:
            # Add some ridiculous inttypes.h redefinitions that are from
            # khrplatform.h and not included in the XML.
            self.outln('typedef int8_t khronos_int8_t;')
            self.outln('typedef int16_t khronos_int16_t;')
            self.outln('typedef int32_t khronos_int32_t;')
            self.outln('typedef int64_t khronos_int64_t;')
            self.outln('typedef uint8_t khronos_uint8_t;')
            self.outln('typedef uint16_t khronos_uint16_t;')
            self.outln('typedef uint32_t khronos_uint32_t;')
            self.outln('typedef uint64_t khronos_uint64_t;')
            self.outln('typedef float khronos_float_t;')
            self.outln('typedef intptr_t khronos_intptr_t;')
            self.outln('typedef ptrdiff_t khronos_ssize_t;')

        if 'glx_dispatch.h' in file:
            self.outln('#include <X11/Xlib.h>')
            self.outln('#include <X11/Xutil.h>')

        self.out(self.typedefs)
        self.outln('')
        self.write_enums()
        self.outln('')
        self.write_dispatch_defines()
        self.outln('')
        self.write_function_ptr_typedefs()

        for func in self.functions.values():
            self.outln('{0} waffle_dispatch_{1}({2});'.format(func.ret_type, func.name,
                                                              func.args_decl))

    def write_function_ptr_resolver(self, func):
        self.outln('static {0}'.format(func.ptr_type))
        self.outln('waffle_dispatch_{0}_resolver(void)'.format(func.name))
        self.outln('{')

        self.outln('    waffle_dispatch_platform_autoinit();')
        self.outln('')
        # Walk the sources of aliases of this function and see if we
        # have any.  If so, get the function pointer and return.
        for provider in func.providers:
            condition = provider[0]
            loader = provider[1]
            self.outln('    if ({0})'.format(condition))
            self.outln('        return {0};'.format(loader))
        self.outln('')

        # If the function isn't provided by any known extension, print
        # something useful for the poor application developer before
        # aborting.  (In non-waffle-dispatch GL usage, the app
        # developer would call into some blank stub function and
        # segfault).
        self.outln('    printf("No provider of \\"{0}\\" found.  Requires one of:\\n");'.format(func.name))
        if len(func.providers) == 0:
            self.outln('    printf("    unknown\\n");')
        else:
            for provider in func.providers:
                self.outln('    printf("    {0}\\n");'.format(provider[2]))

        self.outln('    abort();')

        self.outln('}')
        self.outln('')

    def write_dispatch_table_stub(self, func):
        dispatch_table_entry = 'dispatch_table->p{0}'.format(func.name)

        self.outln('WAFFLE_API {0}'.format(func.ret_type))
        self.outln('waffle_dispatch_{0}({1})'.format(func.name, func.args_decl))
        self.outln('{')
        self.outln('    if (!{0})'.format(dispatch_table_entry))
        self.outln('        {0} = waffle_dispatch_{1}_resolver();'.format(dispatch_table_entry, func.name))
        self.outln('')
        if func.ret_type == 'void':
            self.outln('    {0}({1});'.format(dispatch_table_entry, func.args_list))
        else:
            self.outln('    return {0}({1});'.format(dispatch_table_entry, func.args_list))
        self.outln('}')
        self.outln('')

    def write_ifunc_stub(self, func):
        self.outln('WAFFLE_API void *waffle_ifunc_dispatch_{0}() __attribute__((ifunc("waffle_dispatch_{0}_resolver")));'.format(func.name))
        self.outln('')


    def write_source(self, file):
        self.out_file = open(file, 'w')

        self.outln('/* GL dispatch code for waffle.')
        self.outln(' * This is code-generated from the GL API XML files from Khronos.')
        self.write_copyright_comment_body()
        self.outln(' */')
        self.outln('')
        self.outln('#include <stdlib.h>')
        self.outln('#include <stdio.h>')
        self.outln('')
        self.outln('#include "waffle.h"')
        self.outln('#include "dispatch_common.h"')
        if 'glx_dispatch.c' in file:
            self.outln('#include "glx_dispatch.h"')
        else:
            self.outln('#include "gl_dispatch.h"')
        self.outln('')

        self.outln('struct dispatch_table {')
        for func in self.functions.values():
            self.outln('    {0} p{1};'.format(func.ptr_type, func.name))
        self.outln('};')
        self.outln('')

        self.outln('/* XXX: Make this thread-local and swapped on makecurrent. */')
        self.outln('static struct dispatch_table local_dispatch_table;')
        self.outln('static struct dispatch_table *dispatch_table = &local_dispatch_table;')
        self.outln('')

        for func in self.functions.values():
            self.write_function_ptr_resolver(func)
            self.write_dispatch_table_stub(func)
            self.write_ifunc_stub(func)

argparser = argparse.ArgumentParser(description='Generate GL dispatch wrappers.')
argparser.add_argument('--output-c', help='private .c file to be built into libwaffle')
argparser.add_argument('--output-h', help='public .h file to be installed')
argparser.add_argument('files', metavar='file.xml', nargs='+', help='GL API XML files to be parsed')
args = argparser.parse_args()

generator = Generator()
for file in args.files:
    generator.parse(file)
generator.drop_weird_glx_functions()
generator.write_header(args.output_h)
generator.write_source(args.output_c)