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 func.name.startswith('bdrv_')
102    assert not func.name.startswith('bdrv_co_')
103    assert func.return_type == 'int'
104    assert func.args[0].type in ['BlockDriverState *', 'BdrvChild *']
105
106    name = 'bdrv_co_' + func.name[5:]
107    bs = 'bs' if func.args[0].type == 'BlockDriverState *' else 'child->bs'
108    struct_name = snake_to_camel(name)
109
110    return f"""\
111/*
112 * Wrappers for {name}
113 */
114
115typedef struct {struct_name} {{
116    BdrvPollCo poll_state;
117{ func.gen_block('    {decl};') }
118}} {struct_name};
119
120static void coroutine_fn {name}_entry(void *opaque)
121{{
122    {struct_name} *s = opaque;
123
124    s->poll_state.ret = {name}({ func.gen_list('s->{name}') });
125    s->poll_state.in_progress = false;
126
127    aio_wait_kick();
128}}
129
130int {func.name}({ func.gen_list('{decl}') })
131{{
132    if (qemu_in_coroutine()) {{
133        return {name}({ func.gen_list('{name}') });
134    }} else {{
135        {struct_name} s = {{
136            .poll_state.bs = {bs},
137            .poll_state.in_progress = true,
138
139{ func.gen_block('            .{name} = {name},') }
140        }};
141
142        s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
143
144        return bdrv_poll_co(&s.poll_state);
145    }}
146}}"""
147
148
149def gen_wrappers(input_code: str) -> str:
150    res = ''
151    for func in func_decl_iter(input_code):
152        res += '\n\n\n'
153        res += gen_wrapper(func)
154
155    return res
156
157
158if __name__ == '__main__':
159    if len(sys.argv) < 3:
160        exit(f'Usage: {sys.argv[0]} OUT_FILE.c IN_FILE.[ch]...')
161
162    with open(sys.argv[1], 'w', encoding='utf-8') as f_out:
163        f_out.write(gen_header())
164        for fname in sys.argv[2:]:
165            with open(fname, encoding='utf-8') as f_in:
166                f_out.write(gen_wrappers(f_in.read()))
167                f_out.write('\n')
168