summaryrefslogtreecommitdiff
path: root/host/libs/virglrenderer/gen_entries.py
blob: f0959c46bc5fe0af630210ecdf8c05213265a84b (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
#!/usr/bin/env python

# Copyright 2015 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Utility functions used to parse a list of DLL entry points.
# Expected format:
#
#   <empty-line>   -> ignored
#   #<comment>     -> ignored
#   %<verbatim>    -> verbatim output for header files.
#   !<prefix>      -> prefix name for header files.
#   <return-type> <function-name> <signature> ; -> entry point declaration.
#
# Anything else is an error.

import argparse
import re
import sys

re_func = re.compile(r"""^(.*[\* ])([A-Za-z_][A-Za-z0-9_]*)\((.*)\);$""")
re_param = re.compile(r"""^(.*[\* ])([A-Za-z_][A-Za-z0-9_]*)$""")


class Entry:
    """Small class used to model a single DLL entry point."""

    def __init__(self, func_name, return_type, parameters):
        """Initialize Entry instance. |func_name| is the function name,
           |return_type| its return type, and |parameters| is a list of
           (type,name) tuples from the entry's signature.
        """
        self.func_name = func_name
        self.return_type = return_type
        self.parameters = ""
        self.vartypes = []
        self.varnames = []
        self.call = ""
        comma = ""
        for param in parameters:
            self.vartypes.append(param[0])
            self.varnames.append(param[1])
            self.parameters += "%s%s %s" % (comma, param[0], param[1])
            self.call += "%s%s" % (comma, param[1])
            comma = ", "


def banner_command(argv):
    """Return sanitized command-line description.
       |argv| must be a list of command-line parameters, e.g. sys.argv.
       Return a string corresponding to the command, with platform-specific
       paths removed."""

    # Remove path from first parameter
    argv = argv[:]
    argv[0] = "host/commands/gen-entries.py"
    return " ".join(argv)


def parse_entries_file(lines):
    """Parse an .entries file and return a tuple of:
        entries: list of Entry instances from the file.
        prefix_name: prefix name from the file, or None.
        verbatim: list of verbatim lines from the file.
        errors: list of errors in the file, prefixed by line number.
    """
    entries = []
    verbatim = []
    errors = []
    lineno = 0
    prefix_name = None
    for line in lines:
        lineno += 1
        line = line.strip()
        if len(line) == 0:  # Ignore empty lines
            continue
        if line[0] == "#":  # Ignore comments
            continue
        if line[0] == "!":  # Prefix name
            prefix_name = line[1:]
            continue
        if line[0] == "%":  # Verbatim line copy
            verbatim.append(line[1:])
            continue
        # Must be a function signature.
        m = re_func.match(line)
        if not m:
            errors.append("%d: '%s'" % (lineno, line))
            continue

        return_type, func_name, parameters = m.groups()
        return_type = return_type.strip()
        parameters = parameters.strip()
        params = []
        failure = False
        if parameters != "void":
            for parameter in parameters.split(','):
                parameter = parameter.strip()
                m = re_param.match(parameter)
                if not m:
                    errors.append("%d: parameter '%s'" % (lineno, parameter))
                    failure = True
                    break
                else:
                    param_type, param_name = m.groups()
                    params.append((param_type.strip(), param_name.strip()))

        if not failure:
            entries.append(Entry(func_name, return_type, params))

    return (entries, prefix_name, verbatim, errors)


def gen_functions_header(entries, prefix_name, verbatim, filename, with_args):
    """Generate a C header containing a macro listing all entry points.
       |entries| is a list of Entry instances.
       |prefix_name| is a prefix-name, it will be converted to upper-case.
       |verbatim| is a list of verbatim lines that must appear before the
       macro declaration. Useful to insert #include <> statements.
       |filename| is the name of the original file.
    """
    prefix_name = prefix_name.upper()

    print("// Auto-generated with: " + banner_command(sys.argv))
    print("// DO NOT EDIT THIS FILE")
    print("")
    print(f"#ifndef {prefix_name}_FUNCTIONS_H")
    print(f"#define {prefix_name}_FUNCTIONS_H")
    print("")
    for line in verbatim:
        print(line)

    print(f"#define LIST_{prefix_name}_FUNCTIONS(X) \\")
    for entry in entries:
        if with_args:
            print(f"  X({entry.return_type}, {entry.func_name}, "
                  f"({entry.parameters}), ({entry.call})) \\")
        else:
            print(f"  X({entry.return_type}, {entry.func_name}, "
                  f"({entry.parameters})) \\")

    print("")
    print("")
    print(f"#endif  // {prefix_name}_FUNCTIONS_H")


def gen_dll_wrapper(entries, prefix_name, verbatim, filename):
    """Generate a C source file that contains functions that act as wrappers
       for entry points located in another shared library. This allows the
       code that calls these functions to perform lazy-linking to system
       libraries.
       |entries|, |prefix_name|, |verbatim| and |filename| are the same as
       for gen_functions_header() above.
    """
    upper_name = prefix_name.upper()

    ENTRY_PREFIX = "__dll_"

    print("// Auto-generated with: " + banner_command(sys.argv))
    print("// DO NOT EDIT THIS FILE")
    print("")
    print("#include <dlfcn.h>")
    for line in verbatim:
        print(line)

    print("")
    print("///")
    print("///  W R A P P E R   P O I N T E R S")
    print("///")
    print("")
    for entry in entries:
        ptr_name = ENTRY_PREFIX + entry.func_name
        print(f"static {entry.return_type} "
              f"(*{ptr_name})({entry.parameters}) = 0;")

    print("")
    print("///")
    print("///  W R A P P E R   F U N C T I O N S")
    print("///")
    print("")

    for entry in entries:
        print(f"{entry.return_type} {entry.func_name}({entry.parameters}) {{")
        ptr_name = ENTRY_PREFIX + entry.func_name
        if entry.return_type != "void":
            print(f"  return {ptr_name}({entry.call});")
        else:
            print("  {ptr_name}({entry.call});")
        print("}\n")

    print("")
    print("///")
    print("///  I N I T I A L I Z A T I O N   F U N C T I O N")
    print("///")
    print("")

    print(f"int {prefix_name}_dynlink_init(void* lib) {{")
    for entry in entries:
        ptr_name = ENTRY_PREFIX + entry.func_name
        print(f"  {ptr_name} = ({entry.return_type}(*)({entry.parameters})) "
              f"dlsym(lib, \"{entry.func_name}\");")
        print(f"  if (!{ptr_name}) return -1;")
    print("  return 0;")
    print("}")


def gen_windows_def_file(entries):
    """Generate a windows DLL .def file. |entries| is a list of Entry instances.
    """
    print("EXPORTS")
    for entry in entries:
        print("    " + entry.func_name)


def gen_unix_sym_file(entries):
    """Generate an ELF linker version file. |entries| is a list of Entry
       instances.
    """
    print("VERSION {")
    print("\tglobal:")
    for entry in entries:
        print(f"\t\t{entry.func_name};")
    print("\tlocal:")
    print("\t\t*;")
    print("};")


def gen_symbols(entries, underscore):
    """Generate a list of symbols from |entries|, a list of Entry instances.
       |underscore| is a boolean. If True, then prepend an underscore to each
       symbol name.
    """
    prefix = ""
    if underscore:
        prefix = "_"
    for entry in entries:
        print(prefix + entry.func_name)


def parse_file(filename, lines, mode):
    """Generate one of possible outputs from |filename|. |lines| must be a list
       of text lines from the file, and |mode| is one of the --mode option
       values.
    """
    entries, prefix_name, verbatim, errors = parse_entries_file(lines)
    if errors:
        for error in errors:
            print(f"ERROR: {filename}:{error}", file=sys.stderr)
        sys.exit(1)

    if not prefix_name:
        prefix_name = "unknown"

    if mode == 'def':
        gen_windows_def_file(entries)
    elif mode == 'sym':
        gen_unix_sym_file(entries)
    elif mode == 'wrapper':
        gen_dll_wrapper(entries, prefix_name, verbatim, filename)
    elif mode == 'symbols':
        gen_symbols(entries, False)
    elif mode == '_symbols':
        gen_symbols(entries, True)
    elif mode == 'functions':
        gen_functions_header(entries, prefix_name, verbatim, filename, False)
    elif mode == 'funcargs':
        gen_functions_header(entries, prefix_name, verbatim, filename, True)


# List of valid --mode option values.
mode_list = [
    'def', 'sym', 'wrapper', 'symbols', '_symbols', 'functions', 'funcargs'
]

# Argument parsing.
parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="""\
A script used to parse an .entries input file containing a list of function
declarations, and generate various output files depending on the value of
the --mode option, which can be:

  def        Generate a windows DLL .def file.
  sym        Generate a Unix .so linker script.
  wrapper    Generate a C source file containing wrapper functions.
  symbols    Generate a simple list of symbols, one per line.
  _symbols   Generate a simple list of symbols, prefixed with _.
  functions  Generate a C header containing a macro listing all functions.
  funcargs   Like 'functions', but adds function call arguments to listing.

""")
parser.add_argument("--mode", help="Output mode", choices=mode_list)
parser.add_argument("--output", help="output file")
parser.add_argument("file", help=".entries file path")

args = parser.parse_args()

if not args.mode:
    print("ERROR: Please use --mode=<name>, see --help.", file=sys.stderr)
    sys.exit(1)

if args.output:
    sys.stdout = open(args.output, "w+")

if args.file == '--':
    parse_file("<stdin>", sys.stdin, args.mode)
else:
    parse_file(args.file, open(args.file), args.mode)