genapi.py 5.33 KB
Newer Older
Rahix's avatar
Rahix committed
1
2
3
4
5
6
import argparse
import contextlib
import os
import re
import subprocess

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
api_src_fmt = """\
#define API(id, def) __GENERATE_API $ __GEN_ID_##id $ def $
#include "{header}"
"""


"""Generated Client file"""
api_func_start_fmt = """\
/* Autogenerated stub for {id} */
void {cdecl}({cargs})
{{
    const int size = {total_size};
    void*buffer;

    buffer = api_call_start({id}, size);
    /* TODO: Check if buffer is no NULL */
"""

serialise_arg_fmt = """    *({type}*)(buffer + {offset}) = {arg};"""

bother_dispatcher_fmt = """
    printf("Sending call {id}\\nBUF: ");
    for (int i = 0; i < size; i++) {{
        printf("0x%02x ", ((char*)buffer)[i]);
    }}
    printf("\\n");

    api_call_bother_dispatcher(buffer);
}}
"""


"""Generated Service file"""
api_dispatch_call_start = """\
void __api_dispatch_call(uint32_t id, void*buffer)
{
    switch (id) {"""

dispatch_case_fmt = """\
        case {id}:
            {cdecl}("""

deserialise_arg_fmt = """\
                *({type}*)(buffer + {offset})"""

insert_switch_case_break_str = """
            );
            break;"""

switch_add_default_fmt = """\
        default:
            printf("Error: API function %x is unknown!!\\n", {id});
        break;
    }}
}}"""

def api_func_iter (header:str):
    # Parse the header for API definitions
    matcher = re.compile(
        r"__GENERATE_API \$ __GEN_ID_(?P<id>\w+) \$ void (?P<decl>.+?)\((?P<args>.*?)\) \$",
        re.DOTALL | re.MULTILINE,
    )

    # Run the preprocessor on the header file to get the API definitions.
    #
    # For this, we first need a source to include the header which contains
    # an alternative definition of the `API` macro that marks definitions in
    # a way we can find later on.
    api_src = api_src_fmt.format(
        header=os.path.relpath(header)
    )

    # Evaluate the preprocessor
    source = subprocess.check_output(
        ["gcc", "-E", "-"], input=api_src.encode()
    ).decode()

    return matcher.finditer(source)


def include_header (header:str, file):
    print('#include "{}"\n'.format(
        os.path.basename(header)
    ), file=file)


def destructure_args (api_args:str):
    api_args_names = []
    api_args_types = []
    api_args_sizes = []

    args_matcher = re.compile(r"(?P<type>\w+(?:\*+|\s+))(?P<name>\w+),")

    # Destructure args
    for arg in args_matcher.finditer(api_args + ","):
        arg_type = arg.group("type").strip()
        arg_name = arg.group("name")

        api_args_names.append(arg_name)
        api_args_types.append(arg_type)
        api_args_sizes.append("sizeof({})".format(arg_type))

    return (api_args_names, api_args_types, api_args_sizes)


def serialise_arg (ty:str, api_args_sizes:list, arg_idx:int, arg:str, file):
    print(
        serialise_arg_fmt.format(
            type=ty,
            offset=" + ".join(api_args_sizes[:arg_idx]) if arg_idx > 0 else "0",
            arg=arg,
        ),
        file=file,
    )

def deserialise_arg (ty:str, api_args_sizes:list, arg_idx:int, file):
    if arg_idx != 0:
        print(",", file=file)

    print(
        deserialise_arg_fmt.format(
            type=ty,
            offset=" + ".join(api_args_sizes[:arg_idx]) if arg_idx > 0 else "0",
        ),
        file=file,
        end="",
    )


def insert_switch_case_break (file):
    print(insert_switch_case_break_str,
            file=file,
    )


def bother_dispatcher (api_id:str, file):
    print(bother_dispatcher_fmt.format(
            id=api_id
        ),
        file=file,
    )


def switch_add_default (api_id:str, file):
    print(switch_add_default_fmt.format(
        id=api_id,
    ), file=file)


Rahix's avatar
Rahix committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171

def main():
    parser = argparse.ArgumentParser(
        description="Generate the API stubs from a header file."
    )
    parser.add_argument(
        "-H", "--header", required=True, help="The header to base the definitions on."
    )
    parser.add_argument(
        "-c", "--client", required=True, help="The output client-side c source file."
    )
    parser.add_argument(
        "-s", "--server", required=True, help="The output server-side c source file."
    )
    args = parser.parse_args()

172
173
174
175
    # Open output files
    cx = contextlib.ExitStack()
    f_client = cx.enter_context(open(args.client, "w"))
    f_server = cx.enter_context(open(args.server, "w"))
Rahix's avatar
Rahix committed
176

177
178
    include_header (args.header, f_client)
    include_header (args.header, f_server)
Rahix's avatar
Rahix committed
179

180
    print(api_dispatch_call_start, file=f_server)
Rahix's avatar
Rahix committed
181

182
183
184
185
    for api_func in api_func_iter (args.header):
        api_id = api_func.group("id")
        api_decl = api_func.group("decl")
        api_args = api_func.group("args")
Rahix's avatar
Rahix committed
186

187
188
        (api_args_names, api_args_types, api_args_sizes) = \
                destructure_args (api_args)
Rahix's avatar
Rahix committed
189

190
191
192
193
194
195
196
197
        print(api_func_start_fmt.format(
                id=api_id,
                cdecl=api_decl,
                cargs=api_args,
                total_size=" + ".join(api_args_sizes),
            ),
            file=f_client,
        )
Rahix's avatar
Rahix committed
198

199
200
201
        print(dispatch_case_fmt.format(id=api_id, cdecl=api_decl),
            file=f_server,
        )
Rahix's avatar
Rahix committed
202

203
204
205
        for i, (arg, ty) in enumerate(zip(api_args_names, api_args_types)):
            serialise_arg (ty, api_args_sizes, i, arg, f_client)
            deserialise_arg (ty, api_args_sizes, i, f_server)
Rahix's avatar
Rahix committed
206

207
208
        insert_switch_case_break (f_server)
        bother_dispatcher (api_id, f_client)
Rahix's avatar
Rahix committed
209

210
    switch_add_default (api_id, f_server)
Rahix's avatar
Rahix committed
211

Rahix's avatar
Rahix committed
212
213
214

if __name__ == "__main__":
    main()