1#! /usr/bin/env python3
2"""Generate coroutine wrappers for block subsystem.
3
4The program parses one or several concatenated c files from stdin,
5searches for functions with the 'generated_co_wrapper' specifier
6and generates corresponding wrappers on stdout.
7
8Usage: block-coroutine-wrapper.py generated-file.c FILE.[ch]...
9
10Copyright (c) 2020 Virtuozzo International GmbH.
11
12This program is free software; you can redistribute it and/or modify
13it under the terms of the GNU General Public License as published by
14the Free Software Foundation; either version 2 of the License, or
15(at your option) any later version.
16
17This program is distributed in the hope that it will be useful,
18but WITHOUT ANY WARRANTY; without even the implied warranty of
19MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20GNU General Public License for more details.
21
22You should have received a copy of the GNU General Public License
23along with this program.  If not, see <http://www.gnu.org/licenses/>.
24"""
25
26import sys
27import re
28from typing import Iterator
29
30
31def gen_header():
32    copyright = re.sub('^.*Copyright', 'Copyright', __doc__, flags=re.DOTALL)
33    copyright = re.sub('^(?=.)', ' * ', copyright.strip(), flags=re.MULTILINE)
34    copyright = re.sub('^$', ' *', copyright, flags=re.MULTILINE)
35    return f"""\
36/*
37 * File is generated by scripts/block-coroutine-wrapper.py
38 *
39{copyright}
40 */
41
42#include "qemu/osdep.h"
43#include "block/coroutines.h"
44#include "block/block-gen.h"
45#include "block/block_int.h"\
46"""
47
48
49class ParamDecl:
50    param_re = re.compile(r'(?P<decl>'
51                          r'(?P<type>.*[ *])'
52                          r'(?P<name>[a-z][a-z0-9_]*)'
53                          r')')
54
55    def __init__(self, param_decl: str) -> None:
56        m = self.param_re.match(param_decl.strip())
57        if m is None:
58            raise ValueError(f'Wrong parameter declaration: "{param_decl}"')
59        self.decl = m.group('decl')
60        self.type = m.group('type')
61        self.name = m.group('name')
62
63
64class FuncDecl:
65    def __init__(self, return_type: str, name: str, args: str) -> None:
66        self.return_type = return_type.strip()
67        self.name = name.strip()
68        self.args = [ParamDecl(arg.strip()) for arg in args.split(',')]
69
70    def gen_list(self, format: str) -> str:
71        return ', '.join(format.format_map(arg.__dict__) for arg in self.args)
72
73    def gen_block(self, format: str) -> str:
74        return '\n'.join(format.format_map(arg.__dict__) for arg in self.args)
75
76
77# Match wrappers declared with a generated_co_wrapper mark
78func_decl_re = re.compile(r'^int\s*generated_co_wrapper\s*'
79                          r'(?P<wrapper_name>[a-z][a-z0-9_]*)'
80                          r'\((?P<args>[^)]*)\);$', re.MULTILINE)
81
82
83def func_decl_iter(text: str) -> Iterator:
84    for m in func_decl_re.finditer(text):
85        yield FuncDecl(return_type='int',
86                       name=m.group('wrapper_name'),
87                       args=m.group('args'))
88
89
90def snake_to_camel(func_name: str) -> str:
91    """
92    Convert underscore names like 'some_function_name' to camel-case like
93    'SomeFunctionName'
94    """
95    words = func_name.split('_')
96    words = [w[0].upper() + w[1:] for w in words]
97    return ''.join(words)
98
99
100def gen_wrapper(func: FuncDecl) -> str:
101    assert not '_co_' in func.name
102    assert func.return_type == 'int'
103    assert func.args[0].type in ['BlockDriverState *', 'BdrvChild *']
104
105    subsystem, subname = func.name.split('_', 1)
106
107    name = f'{subsystem}_co_{subname}'
108    bs = 'bs' if func.args[0].type == 'BlockDriverState *' else 'child->bs'
109    struct_name = snake_to_camel(name)
110
111    return f"""\
112/*
113 * Wrappers for {name}
114 */
115
116typedef struct {struct_name} {{
117    BdrvPollCo poll_state;
118{ func.gen_block('    {decl};') }
119}} {struct_name};
120
121static void coroutine_fn {name}_entry(void *opaque)
122{{
123    {struct_name} *s = opaque;
124
125    s->poll_state.ret = {name}({ func.gen_list('s->{name}') });
126    s->poll_state.in_progress = false;
127
128    aio_wait_kick();
129}}
130
131int {func.name}({ func.gen_list('{decl}') })
132{{
133    if (qemu_in_coroutine()) {{
134        return {name}({ func.gen_list('{name}') });
135    }} else {{
136        {struct_name} s = {{
137            .poll_state.bs = {bs},
138            .poll_state.in_progress = true,
139
140{ func.gen_block('            .{name} = {name},') }
141        }};
142
143        s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
144
145        return bdrv_poll_co(&s.poll_state);
146    }}
147}}"""
148
149
150def gen_wrappers(input_code: str) -> str:
151    res = ''
152    for func in func_decl_iter(input_code):
153        res += '\n\n\n'
154        res += gen_wrapper(func)
155
156    return res
157
158
159if __name__ == '__main__':
160    if len(sys.argv) < 3:
161        exit(f'Usage: {sys.argv[0]} OUT_FILE.c IN_FILE.[ch]...')
162
163    with open(sys.argv[1], 'w', encoding='utf-8') as f_out:
164        f_out.write(gen_header())
165        for fname in sys.argv[2:]:
166            with open(fname, encoding='utf-8') as f_in:
167                f_out.write(gen_wrappers(f_in.read()))
168                f_out.write('\n')
169