1#!/usr/bin/env python
2
3# (C) Copyright IBM Corporation 2004, 2005
4# (C) Copyright Apple Inc. 2011
5# Copyright (C) 2015 Intel Corporation
6# All Rights Reserved.
7#
8# Permission is hereby granted, free of charge, to any person obtaining a
9# copy of this software and associated documentation files (the "Software"),
10# to deal in the Software without restriction, including without limitation
11# on the rights to use, copy, modify, merge, publish, distribute, sub
12# license, and/or sell copies of the Software, and to permit persons to whom
13# the Software is furnished to do so, subject to the following conditions:
14#
15# The above copyright notice and this permission notice (including the next
16# paragraph) shall be included in all copies or substantial portions of the
17# Software.
18#
19# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.  IN NO EVENT SHALL
22# IBM AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
25# IN THE SOFTWARE.
26#
27# Authors:
28#    Jeremy Huddleston <jeremyhu@apple.com>
29#
30# Based on code ogiginally by:
31#    Ian Romanick <idr@us.ibm.com>
32
33import argparse
34
35import license
36import gl_XML, glX_XML
37
38header = """/* GLXEXT is the define used in the xserver when the GLX extension is being
39 * built.  Hijack this to determine whether this file is being built for the
40 * server or the client.
41 */
42#ifdef HAVE_DIX_CONFIG_H
43#include <dix-config.h>
44#endif
45
46#if (defined(GLXEXT) && defined(HAVE_BACKTRACE)) \\
47	|| (!defined(GLXEXT) && defined(DEBUG) && !defined(__CYGWIN__) && !defined(__MINGW32__) && !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__DragonFly__))
48#define USE_BACKTRACE
49#endif
50
51#ifdef USE_BACKTRACE
52#include <execinfo.h>
53#endif
54
55#ifndef _WIN32
56#include <dlfcn.h>
57#endif
58#include <stdlib.h>
59#include <stdio.h>
60
61#include "main/glheader.h"
62
63#include "glapi.h"
64#include "glapitable.h"
65
66#ifdef GLXEXT
67#include "os.h"
68#endif
69
70static void
71__glapi_gentable_NoOp(void) {
72    const char *fstr = "Unknown";
73
74    /* Silence potential GCC warning for some #ifdef paths.
75     */
76    (void) fstr;
77#if defined(USE_BACKTRACE)
78#if !defined(GLXEXT)
79    if (getenv("MESA_DEBUG") || getenv("LIBGL_DEBUG"))
80#endif
81    {
82        void *frames[2];
83
84        if(backtrace(frames, 2) == 2) {
85            Dl_info info;
86            dladdr(frames[1], &info);
87            if(info.dli_sname)
88                fstr = info.dli_sname;
89        }
90
91#if !defined(GLXEXT)
92        fprintf(stderr, "Call to unimplemented API: %s\\n", fstr);
93#endif
94    }
95#endif
96#if defined(GLXEXT)
97    LogMessage(X_ERROR, "GLX: Call to unimplemented API: %s\\n", fstr);
98#endif
99}
100
101static void
102__glapi_gentable_set_remaining_noop(struct _glapi_table *disp) {
103    GLuint entries = _glapi_get_dispatch_table_size();
104    void **dispatch = (void **) disp;
105    unsigned i;
106
107    /* ISO C is annoying sometimes */
108    union {_glapi_proc p; void *v;} p;
109    p.p = __glapi_gentable_NoOp;
110
111    for(i=0; i < entries; i++)
112        if(dispatch[i] == NULL)
113            dispatch[i] = p.v;
114}
115
116"""
117
118footer = """
119struct _glapi_table *
120_glapi_create_table_from_handle(void *handle, const char *symbol_prefix) {
121    struct _glapi_table *disp = calloc(_glapi_get_dispatch_table_size(), sizeof(_glapi_proc));
122    char symboln[512];
123
124    if(!disp)
125        return NULL;
126
127    if(symbol_prefix == NULL)
128        symbol_prefix = "";
129
130    /* Note: This code relies on _glapi_table_func_names being sorted by the
131     * entry point index of each function.
132     */
133    for (int func_index = 0; func_index < GLAPI_TABLE_COUNT; ++func_index) {
134        const char *name = _glapi_table_func_names[func_index];
135        void ** procp = &((void **)disp)[func_index];
136
137        snprintf(symboln, sizeof(symboln), \"%s%s\", symbol_prefix, name);
138#ifdef _WIN32
139        *procp = GetProcAddress(handle, symboln);
140#else
141        *procp = dlsym(handle, symboln);
142#endif
143    }
144    __glapi_gentable_set_remaining_noop(disp);
145
146    return disp;
147}
148"""
149
150
151class PrintCode(gl_XML.gl_print_base):
152
153    def __init__(self):
154        gl_XML.gl_print_base.__init__(self)
155
156        self.name = "gl_gentable.py (from Mesa)"
157        self.license = license.bsd_license_template % ( \
158"""Copyright (C) 1999-2001  Brian Paul   All Rights Reserved.
159(C) Copyright IBM Corporation 2004, 2005
160(C) Copyright Apple Inc 2011""", "BRIAN PAUL, IBM")
161
162        return
163
164
165    def get_stack_size(self, f):
166        size = 0
167        for p in f.parameterIterator():
168            if p.is_padding:
169                continue
170
171            size += p.get_stack_size()
172
173        return size
174
175
176    def printRealHeader(self):
177        print header
178        return
179
180
181    def printRealFooter(self):
182        print footer
183        return
184
185
186    def printBody(self, api):
187
188        # Determine how many functions have a defined offset.
189        func_count = 0
190        for f in api.functions_by_name.itervalues():
191            if f.offset != -1:
192                func_count += 1
193
194        # Build the mapping from offset to function name.
195        funcnames = [None] * func_count
196        for f in api.functions_by_name.itervalues():
197            if f.offset != -1:
198                if not (funcnames[f.offset] is None):
199                    raise Exception("Function table has more than one function with same offset (offset %d, func %s)" % (f.offset, f.name))
200                funcnames[f.offset] = f.name
201
202        # Check that the table has no gaps.  We expect a function at every offset,
203        # and the code which generates the table relies on this.
204        for i in xrange(0, func_count):
205            if funcnames[i] is None:
206                raise Exception("Function table has no function at offset %d" % (i))
207
208        print "#define GLAPI_TABLE_COUNT %d" % func_count
209        print "static const char * const _glapi_table_func_names[GLAPI_TABLE_COUNT] = {"
210        for i in xrange(0, func_count):
211            print "    /* %5d */ \"%s\"," % (i, funcnames[i])
212        print "};"
213
214        return
215
216
217def _parser():
218    """Parse arguments and return a namespace object."""
219    parser = argparse.ArgumentParser()
220    parser.add_argument('-f',
221                        dest='filename',
222                        default='gl_API.xml',
223                        help='An XML file description of an API')
224
225    return parser.parse_args()
226
227
228def main():
229    """Main function."""
230    args = _parser()
231
232    printer = PrintCode()
233
234    api = gl_XML.parse_GL_API(args.filename, glX_XML.glx_item_factory())
235    printer.Print(api)
236
237
238if __name__ == '__main__':
239    main()
240