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