2 # Mesa 3-D graphics library
4 # Copyright (C) 2010 LunarG Inc.
6 # Permission is hereby granted, free of charge, to any person obtaining a
7 # copy of this software and associated documentation files (the "Software"),
8 # to deal in the Software without restriction, including without limitation
9 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 # and/or sell copies of the Software, and to permit persons to whom the
11 # Software is furnished to do so, subject to the following conditions:
13 # The above copyright notice and this permission notice shall be included
14 # in all copies or substantial portions of the Software.
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 # DEALINGS IN THE SOFTWARE.
25 # Chia-I Wu <olv@lunarg.com>
27 from __future__
import print_function
30 # make it possible to import glapi
32 GLAPI
= os
.path
.join(".", os
.path
.dirname(sys
.argv
[0]), "glapi/gen")
33 sys
.path
.append(GLAPI
)
36 from optparse
import OptionParser
41 # number of dynamic entries
42 ABI_NUM_DYNAMIC_ENTRIES
= 256
44 class ABIEntry(object):
45 """Represent an ABI entry."""
47 _match_c_param
= re
.compile(
48 '^(?P<type>[\w\s*]+?)(?P<name>\w+)(\[(?P<array>\d+)\])?$')
50 def __init__(self
, cols
, attrs
, xml_data
= None):
53 self
.slot
= attrs
['slot']
54 self
.hidden
= attrs
['hidden']
55 self
.alias
= attrs
['alias']
56 self
.handcode
= attrs
['handcode']
57 self
.xml_data
= xml_data
59 def c_prototype(self
):
60 return '%s %s(%s)' % (self
.c_return(), self
.name
, self
.c_params())
70 """Return the parameter list used in the entry prototype."""
72 for t
, n
, a
in self
.params
:
73 sep
= '' if t
.endswith('*') else ' '
74 arr
= '[%d]' % a
if a
else ''
75 c_params
.append(t
+ sep
+ n
+ arr
)
77 c_params
.append('void')
79 return ", ".join(c_params
)
82 """Return the argument list used in the entry invocation."""
84 for t
, n
, a
in self
.params
:
87 return ", ".join(c_args
)
89 def _parse(self
, cols
):
99 elif len(cols
) == 1 and cols
[0] == 'void':
103 params
.append(self
._parse
_param
(val
))
109 def _parse_param(self
, c_param
):
110 m
= self
._match
_c
_param
.match(c_param
)
112 raise Exception('unrecognized param ' + c_param
)
114 c_type
= m
.group('type').strip()
115 c_name
= m
.group('name')
116 c_array
= m
.group('array')
117 c_array
= int(c_array
) if c_array
else 0
119 return (c_type
, c_name
, c_array
)
122 return self
.c_prototype()
124 def __cmp__(self
, other
):
125 # compare slot, alias, and then name
126 res
= cmp(self
.slot
, other
.slot
)
130 elif not other
.alias
:
134 res
= cmp(self
.name
, other
.name
)
138 def abi_parse_xml(xml
):
139 """Parse a GLAPI XML file for ABI entries."""
140 api
= gl_XML
.parse_GL_API(xml
, glX_XML
.glx_item_factory())
143 for func
in api
.functionIterateByOffset():
144 # make sure func.name appear first
145 entry_points
= func
.entry_points
[:]
146 entry_points
.remove(func
.name
)
147 entry_points
.insert(0, func
.name
)
149 for name
in entry_points
:
152 'hidden': not func
.is_static_entry_point(name
),
153 'alias': None if name
== func
.name
else func
.name
,
154 'handcode': bool(func
.has_different_protocol(name
)),
160 alias
= entry_dict
[attrs
['alias']]
162 raise Exception('failed to alias %s' % attrs
['alias'])
164 raise Exception('recursive alias %s' % ent
.name
)
165 attrs
['alias'] = alias
166 if attrs
['handcode']:
167 attrs
['handcode'] = func
.static_glx_name(name
)
169 attrs
['handcode'] = None
171 if entry_dict
.has_key(name
):
172 raise Exception('%s is duplicated' % (name
))
175 cols
.append(func
.return_type
)
177 params
= func
.get_parameter_string(name
)
178 cols
.extend([p
.strip() for p
in params
.split(',')])
180 ent
= ABIEntry(cols
, attrs
, func
)
181 entry_dict
[ent
.name
] = ent
183 entries
= entry_dict
.values()
188 def abi_parse_line(line
):
189 cols
= [col
.strip() for col
in line
.split(',')]
198 # extract attributes from the first column
199 vals
= cols
[0].split(':')
202 if val
.startswith('slot='):
203 attrs
['slot'] = int(val
[5:])
204 elif val
== 'hidden':
205 attrs
['hidden'] = True
206 elif val
.startswith('alias='):
207 attrs
['alias'] = val
[6:]
208 elif val
.startswith('handcode='):
209 attrs
['handcode'] = val
[9:]
213 raise Exception('unknown attribute %s' % val
)
218 def abi_parse(filename
):
219 """Parse a CSV file for ABI entries."""
220 fp
= open(filename
) if filename
!= '-' else sys
.stdin
221 lines
= [line
.strip() for line
in fp
.readlines()
222 if not line
.startswith('#') and line
.strip()]
227 attrs
, cols
= abi_parse_line(line
)
229 # post-process attributes
232 alias
= entry_dict
[attrs
['alias']]
234 raise Exception('failed to alias %s' % attrs
['alias'])
236 raise Exception('recursive alias %s' % ent
.name
)
238 attrs
['alias'] = alias
243 if attrs
['slot'] < 0:
245 elif attrs
['slot'] != slot
:
246 raise Exception('invalid slot in %s' % (line
))
248 ent
= ABIEntry(cols
, attrs
)
249 if entry_dict
.has_key(ent
.name
):
250 raise Exception('%s is duplicated' % (ent
.name
))
251 entry_dict
[ent
.name
] = ent
253 entries
= entry_dict
.values()
258 def abi_sanity_check(entries
):
263 last_slot
= entries
[-1].slot
265 for slot
in xrange(last_slot
+ 1):
266 if entries
[i
].slot
!= slot
:
267 raise Exception('entries are not ordered by slots')
269 raise Exception('first entry of slot %d aliases %s'
270 % (slot
, entries
[i
].alias
.name
))
272 while i
< len(entries
) and entries
[i
].slot
== slot
:
274 if not handcode
and ent
.handcode
:
275 handcode
= ent
.handcode
276 elif ent
.handcode
!= handcode
:
277 raise Exception('two aliases with handcode %s != %s',
278 ent
.handcode
, handcode
)
280 if ent
.name
in all_names
:
281 raise Exception('%s is duplicated' % (ent
.name
))
282 if ent
.alias
and ent
.alias
.name
not in all_names
:
283 raise Exception('failed to alias %s' % (ent
.alias
.name
))
284 all_names
.append(ent
.name
)
287 raise Exception('there are %d invalid entries' % (len(entries
) - 1))
289 class ABIPrinter(object):
292 def __init__(self
, entries
):
293 self
.entries
= entries
295 # sort entries by their names
296 self
.entries_sorted_by_names
= self
.entries
[:]
297 self
.entries_sorted_by_names
.sort(lambda x
, y
: cmp(x
.name
, y
.name
))
299 self
.indent
= ' ' * 3
300 self
.noop_warn
= 'noop_warn'
301 self
.noop_generic
= 'noop_generic'
302 self
.current_get
= 'entry_current_get'
304 self
.api_defines
= []
305 self
.api_headers
= ['"KHR/khrplatform.h"']
306 self
.api_call
= 'KHRONOS_APICALL'
307 self
.api_entry
= 'KHRONOS_APIENTRY'
308 self
.api_attrs
= 'KHRONOS_APIATTRIBUTES'
312 self
.lib_need_table_size
= True
313 self
.lib_need_noop_array
= True
314 self
.lib_need_stubs
= True
315 self
.lib_need_all_entries
= True
316 self
.lib_need_non_hidden_entries
= False
319 return '/* This file is automatically generated by mapi_abi.py. Do not modify. */'
321 def c_public_includes(self
):
322 """Return includes of the client API headers."""
323 defines
= ['#define ' + d
for d
in self
.api_defines
]
324 includes
= ['#include ' + h
for h
in self
.api_headers
]
325 return "\n".join(defines
+ includes
)
327 def need_entry_point(self
, ent
):
328 """Return True if an entry point is needed for the entry."""
329 # non-handcode hidden aliases may share the entry they alias
330 use_alias
= (ent
.hidden
and ent
.alias
and not ent
.handcode
)
333 def c_public_declarations(self
, prefix
):
334 """Return the declarations of public entry points."""
336 for ent
in self
.entries
:
337 if not self
.need_entry_point(ent
):
339 export
= self
.api_call
if not ent
.hidden
else ''
340 decls
.append(self
._c
_decl
(ent
, prefix
, True, export
) + ';')
342 return "\n".join(decls
)
344 def c_mapi_table(self
):
345 """Return defines of the dispatch table size."""
346 num_static_entries
= self
.entries
[-1].slot
+ 1
347 return ('#define MAPI_TABLE_NUM_STATIC %d\n' + \
348 '#define MAPI_TABLE_NUM_DYNAMIC %d') % (
349 num_static_entries
, ABI_NUM_DYNAMIC_ENTRIES
)
351 def _c_function(self
, ent
, prefix
, mangle
=False, stringify
=False):
352 """Return the function name of an entry."""
354 True: { True: '%s_STR(%s)', False: '%s(%s)' },
355 False: { True: '"%s%s"', False: '%s%s' },
357 fmt
= formats
[prefix
.isupper()][stringify
]
359 if mangle
and ent
.hidden
:
360 name
= '_dispatch_stub_' + str(ent
.slot
)
361 return fmt
% (prefix
, name
)
363 def _c_function_call(self
, ent
, prefix
):
364 """Return the function name used for calling."""
366 # _c_function does not handle this case
367 formats
= { True: '%s(%s)', False: '%s%s' }
368 fmt
= formats
[prefix
.isupper()]
369 name
= fmt
% (prefix
, ent
.handcode
)
370 elif self
.need_entry_point(ent
):
371 name
= self
._c
_function
(ent
, prefix
, True)
373 name
= self
._c
_function
(ent
.alias
, prefix
, True)
376 def _c_decl(self
, ent
, prefix
, mangle
=False, export
=''):
377 """Return the C declaration for the entry."""
378 decl
= '%s %s %s(%s)' % (ent
.c_return(), self
.api_entry
,
379 self
._c
_function
(ent
, prefix
, mangle
), ent
.c_params())
381 decl
= export
+ ' ' + decl
383 decl
+= ' ' + self
.api_attrs
387 def _c_cast(self
, ent
):
388 """Return the C cast for the entry."""
389 cast
= '%s (%s *)(%s)' % (
390 ent
.c_return(), self
.api_entry
, ent
.c_params())
394 def c_public_dispatches(self
, prefix
, no_hidden
):
395 """Return the public dispatch functions."""
397 for ent
in self
.entries
:
398 if ent
.hidden
and no_hidden
:
401 if not self
.need_entry_point(ent
):
404 export
= self
.api_call
if not ent
.hidden
else ''
406 proto
= self
._c
_decl
(ent
, prefix
, True, export
)
407 cast
= self
._c
_cast
(ent
)
413 stmt1
+= 'const struct _glapi_table *_tbl = %s();' % (
416 stmt2
+= 'mapi_func _func = ((const mapi_func *) _tbl)[%d];' % (
419 stmt3
+= '%s((%s) _func)(%s);' % (ret
, cast
, ent
.c_args())
421 disp
= '%s\n{\n%s\n%s\n%s\n}' % (proto
, stmt1
, stmt2
, stmt3
)
424 disp
= '#if 0\n' + disp
+ '\n#endif'
426 dispatches
.append(disp
)
428 return '\n\n'.join(dispatches
)
430 def c_public_initializer(self
, prefix
):
431 """Return the initializer for public dispatch functions."""
433 for ent
in self
.entries
:
437 name
= '%s(mapi_func) %s' % (self
.indent
,
438 self
._c
_function
_call
(ent
, prefix
))
441 return ',\n'.join(names
)
443 def c_stub_string_pool(self
):
444 """Return the string pool for use by stubs."""
445 # sort entries by their names
446 sorted_entries
= self
.entries
[:]
447 sorted_entries
.sort(lambda x
, y
: cmp(x
.name
, y
.name
))
452 for ent
in sorted_entries
:
454 pool
.append('%s' % (ent
.name
))
455 count
+= len(ent
.name
) + 1
457 pool_str
= self
.indent
+ '"' + \
458 ('\\0"\n' + self
.indent
+ '"').join(pool
) + '";'
459 return (pool_str
, offsets
)
461 def c_stub_initializer(self
, prefix
, pool_offsets
):
462 """Return the initializer for struct mapi_stub array."""
464 for ent
in self
.entries_sorted_by_names
:
465 stubs
.append('%s{ (void *) %d, %d, NULL }' % (
466 self
.indent
, pool_offsets
[ent
], ent
.slot
))
468 return ',\n'.join(stubs
)
470 def c_noop_functions(self
, prefix
, warn_prefix
):
471 """Return the noop functions."""
473 for ent
in self
.entries
:
477 proto
= self
._c
_decl
(ent
, prefix
, False, 'static')
481 for t
, n
, a
in ent
.params
:
482 stmt1
+= "%s(void) %s;" % (space
, n
)
488 stmt1
+= self
.indent
+ '%s(%s);' % (self
.noop_warn
,
489 self
._c
_function
(ent
, warn_prefix
, False, True))
492 stmt2
= self
.indent
+ 'return (%s) 0;' % (ent
.ret
)
493 noop
= '%s\n{\n%s\n%s\n}' % (proto
, stmt1
, stmt2
)
495 noop
= '%s\n{\n%s\n}' % (proto
, stmt1
)
499 return '\n\n'.join(noops
)
501 def c_noop_initializer(self
, prefix
, use_generic
):
502 """Return an initializer for the noop dispatch table."""
503 entries
= [self
._c
_function
(ent
, prefix
)
504 for ent
in self
.entries
if not ent
.alias
]
506 entries
= [self
.noop_generic
] * len(entries
)
508 entries
.extend([self
.noop_generic
] * ABI_NUM_DYNAMIC_ENTRIES
)
510 pre
= self
.indent
+ '(mapi_func) '
511 return pre
+ (',\n' + pre
).join(entries
)
513 def c_asm_gcc(self
, prefix
, no_hidden
):
516 for ent
in self
.entries
:
517 if ent
.hidden
and no_hidden
:
520 if not self
.need_entry_point(ent
):
523 name
= self
._c
_function
(ent
, prefix
, True, True)
529 asm
.append('".hidden "%s"\\n"' % (name
))
531 if ent
.alias
and not (ent
.alias
.hidden
and no_hidden
):
532 asm
.append('".globl "%s"\\n"' % (name
))
533 asm
.append('".set "%s", "%s"\\n"' % (name
,
534 self
._c
_function
(ent
.alias
, prefix
, True, True)))
536 asm
.append('STUB_ASM_ENTRY(%s)"\\n"' % (name
))
537 asm
.append('"\\t"STUB_ASM_CODE("%d")"\\n"' % (ent
.slot
))
543 return "\n".join(asm
)
545 def output_for_lib(self
):
546 print(self
.c_notice())
553 print('#ifdef MAPI_TMP_DEFINES')
554 print(self
.c_public_includes())
556 print(self
.c_public_declarations(self
.prefix_lib
))
557 print('#undef MAPI_TMP_DEFINES')
558 print('#endif /* MAPI_TMP_DEFINES */')
560 if self
.lib_need_table_size
:
562 print('#ifdef MAPI_TMP_TABLE')
563 print(self
.c_mapi_table())
564 print('#undef MAPI_TMP_TABLE')
565 print('#endif /* MAPI_TMP_TABLE */')
567 if self
.lib_need_noop_array
:
569 print('#ifdef MAPI_TMP_NOOP_ARRAY')
570 print('#ifdef DEBUG')
572 print(self
.c_noop_functions(self
.prefix_noop
, self
.prefix_warn
))
574 print('const mapi_func table_%s_array[] = {' % (self
.prefix_noop
))
575 print(self
.c_noop_initializer(self
.prefix_noop
, False))
578 print('#else /* DEBUG */')
580 print('const mapi_func table_%s_array[] = {' % (self
.prefix_noop
))
581 print(self
.c_noop_initializer(self
.prefix_noop
, True))
584 print('#endif /* DEBUG */')
585 print('#undef MAPI_TMP_NOOP_ARRAY')
586 print('#endif /* MAPI_TMP_NOOP_ARRAY */')
588 if self
.lib_need_stubs
:
589 pool
, pool_offsets
= self
.c_stub_string_pool()
591 print('#ifdef MAPI_TMP_PUBLIC_STUBS')
592 print('static const char public_string_pool[] =')
595 print('static const struct mapi_stub public_stubs[] = {')
596 print(self
.c_stub_initializer(self
.prefix_lib
, pool_offsets
))
598 print('#undef MAPI_TMP_PUBLIC_STUBS')
599 print('#endif /* MAPI_TMP_PUBLIC_STUBS */')
601 if self
.lib_need_all_entries
:
603 print('#ifdef MAPI_TMP_PUBLIC_ENTRIES')
604 print(self
.c_public_dispatches(self
.prefix_lib
, False))
606 print('static const mapi_func public_entries[] = {')
607 print(self
.c_public_initializer(self
.prefix_lib
))
609 print('#undef MAPI_TMP_PUBLIC_ENTRIES')
610 print('#endif /* MAPI_TMP_PUBLIC_ENTRIES */')
613 print('#ifdef MAPI_TMP_STUB_ASM_GCC')
615 print(self
.c_asm_gcc(self
.prefix_lib
, False))
617 print('#undef MAPI_TMP_STUB_ASM_GCC')
618 print('#endif /* MAPI_TMP_STUB_ASM_GCC */')
620 if self
.lib_need_non_hidden_entries
:
622 for ent
in self
.entries
:
628 print('#ifdef MAPI_TMP_PUBLIC_ENTRIES_NO_HIDDEN')
629 print(self
.c_public_dispatches(self
.prefix_lib
, True))
631 print('/* does not need public_entries */')
632 print('#undef MAPI_TMP_PUBLIC_ENTRIES_NO_HIDDEN')
633 print('#endif /* MAPI_TMP_PUBLIC_ENTRIES_NO_HIDDEN */')
636 print('#ifdef MAPI_TMP_STUB_ASM_GCC_NO_HIDDEN')
638 print(self
.c_asm_gcc(self
.prefix_lib
, True))
640 print('#undef MAPI_TMP_STUB_ASM_GCC_NO_HIDDEN')
641 print('#endif /* MAPI_TMP_STUB_ASM_GCC_NO_HIDDEN */')
643 class GLAPIPrinter(ABIPrinter
):
644 """OpenGL API Printer"""
646 def __init__(self
, entries
):
648 self
._override
_for
_api
(ent
)
649 super(GLAPIPrinter
, self
).__init
__(entries
)
651 self
.api_defines
= ['GL_GLEXT_PROTOTYPES']
652 self
.api_headers
= ['"GL/gl.h"', '"GL/glext.h"']
653 self
.api_call
= 'GLAPI'
654 self
.api_entry
= 'APIENTRY'
657 self
.lib_need_table_size
= False
658 self
.lib_need_noop_array
= False
659 self
.lib_need_stubs
= False
660 self
.lib_need_all_entries
= False
661 self
.lib_need_non_hidden_entries
= True
663 self
.prefix_lib
= 'GLAPI_PREFIX'
664 self
.prefix_noop
= 'noop'
665 self
.prefix_warn
= self
.prefix_lib
667 self
.c_header
= self
._get
_c
_header
()
669 def _override_for_api(self
, ent
):
670 """Override attributes of an entry if necessary for this
672 # By default, no override is necessary.
675 def _get_c_header(self
):
676 header
= """#ifndef _GLAPI_TMP_H_
677 #define _GLAPI_TMP_H_
678 #ifdef USE_MGL_NAMESPACE
679 #define GLAPI_PREFIX(func) mgl##func
680 #define GLAPI_PREFIX_STR(func) "mgl"#func
682 #define GLAPI_PREFIX(func) gl##func
683 #define GLAPI_PREFIX_STR(func) "gl"#func
684 #endif /* USE_MGL_NAMESPACE */
686 typedef int GLclampx;
687 #endif /* _GLAPI_TMP_H_ */"""
691 class ES1APIPrinter(GLAPIPrinter
):
692 """OpenGL ES 1.x API Printer"""
694 def __init__(self
, entries
):
695 super(ES1APIPrinter
, self
).__init
__(entries
)
696 self
.prefix_lib
= 'gl'
697 self
.prefix_warn
= 'gl'
699 def _override_for_api(self
, ent
):
700 if ent
.xml_data
is None:
701 raise Exception('ES2 API printer requires XML input')
702 ent
.hidden
= (ent
.name
not in \
703 ent
.xml_data
.entry_points_for_api_version('es1')) \
707 def _get_c_header(self
):
708 header
= """#ifndef _GLAPI_TMP_H_
709 #define _GLAPI_TMP_H_
710 typedef int GLclampx;
711 #endif /* _GLAPI_TMP_H_ */"""
715 class ES2APIPrinter(GLAPIPrinter
):
716 """OpenGL ES 2.x API Printer"""
718 def __init__(self
, entries
):
719 super(ES2APIPrinter
, self
).__init
__(entries
)
720 self
.prefix_lib
= 'gl'
721 self
.prefix_warn
= 'gl'
723 def _override_for_api(self
, ent
):
724 if ent
.xml_data
is None:
725 raise Exception('ES2 API printer requires XML input')
726 ent
.hidden
= (ent
.name
not in \
727 ent
.xml_data
.entry_points_for_api_version('es2')) \
730 # This is hella ugly. The same-named function in desktop OpenGL is
731 # hidden, but it needs to be exposed by libGLESv2 for OpenGL ES 3.0.
732 # There's no way to express in the XML that a function should be be
733 # hidden in one API but exposed in another.
734 if ent
.name
== 'GetInternalformativ':
739 def _get_c_header(self
):
740 header
= """#ifndef _GLAPI_TMP_H_
741 #define _GLAPI_TMP_H_
742 typedef int GLclampx;
743 #endif /* _GLAPI_TMP_H_ */"""
747 class SharedGLAPIPrinter(GLAPIPrinter
):
748 """Shared GLAPI API Printer"""
750 def __init__(self
, entries
):
751 super(SharedGLAPIPrinter
, self
).__init
__(entries
)
753 self
.lib_need_table_size
= True
754 self
.lib_need_noop_array
= True
755 self
.lib_need_stubs
= True
756 self
.lib_need_all_entries
= True
757 self
.lib_need_non_hidden_entries
= False
759 self
.prefix_lib
= 'shared'
760 self
.prefix_warn
= 'gl'
762 def _override_for_api(self
, ent
):
766 def _get_c_header(self
):
767 header
= """#ifndef _GLAPI_TMP_H_
768 #define _GLAPI_TMP_H_
769 typedef int GLclampx;
770 #endif /* _GLAPI_TMP_H_ */"""
775 printers
= ['glapi', 'es1api', 'es2api', 'shared-glapi']
777 parser
= OptionParser(usage
='usage: %prog [options] <filename>')
778 parser
.add_option('-p', '--printer', dest
='printer',
779 help='printer to use: %s' % (", ".join(printers
)))
781 options
, args
= parser
.parse_args()
782 if not args
or options
.printer
not in printers
:
786 return (args
[0], options
)
790 'glapi': GLAPIPrinter
,
791 'es1api': ES1APIPrinter
,
792 'es2api': ES2APIPrinter
,
793 'shared-glapi': SharedGLAPIPrinter
,
796 filename
, options
= parse_args()
798 if filename
.endswith('.xml'):
799 entries
= abi_parse_xml(filename
)
801 entries
= abi_parse(filename
)
802 abi_sanity_check(entries
)
804 printer
= printers
[options
.printer
](entries
)
805 printer
.output_for_lib()
807 if __name__
== '__main__':