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