gitlab-ci: Make more custom runner jobs manual, and don't allow failure
[qemu.git] / scripts / block-coroutine-wrapper.py
blob85dbeb9ecf9c84abe042157ceace70ebb7a38d00
1 #! /usr/bin/env python3
2 """Generate coroutine wrappers for block subsystem.
4 The program parses one or several concatenated c files from stdin,
5 searches for functions with the 'generated_co_wrapper' specifier
6 and generates corresponding wrappers on stdout.
8 Usage: block-coroutine-wrapper.py generated-file.c FILE.[ch]...
10 Copyright (c) 2020 Virtuozzo International GmbH.
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 """
26 import sys
27 import re
28 from typing import Iterator
31 def 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"""\
37 * File is generated by scripts/block-coroutine-wrapper.py
39 {copyright}
42 #include "qemu/osdep.h"
43 #include "block/coroutines.h"
44 #include "block/block-gen.h"
45 #include "block/block_int.h"\
46 """
49 class ParamDecl:
50 param_re = re.compile(r'(?P<decl>'
51 r'(?P<type>.*[ *])'
52 r'(?P<name>[a-z][a-z0-9_]*)'
53 r')')
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')
64 class 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(',')]
70 def gen_list(self, format: str) -> str:
71 return ', '.join(format.format_map(arg.__dict__) for arg in self.args)
73 def gen_block(self, format: str) -> str:
74 return '\n'.join(format.format_map(arg.__dict__) for arg in self.args)
77 # Match wrappers declared with a generated_co_wrapper mark
78 func_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)
83 def 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'))
90 def 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)
100 def 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 *']
105 subsystem, subname = func.name.split('_', 1)
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)
111 return f"""\
113 * Wrappers for {name}
116 typedef struct {struct_name} {{
117 BdrvPollCo poll_state;
118 { func.gen_block(' {decl};') }
119 }} {struct_name};
121 static void coroutine_fn {name}_entry(void *opaque)
123 {struct_name} *s = opaque;
125 s->poll_state.ret = {name}({ func.gen_list('s->{name}') });
126 s->poll_state.in_progress = false;
128 aio_wait_kick();
131 int {func.name}({ func.gen_list('{decl}') })
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,
140 { func.gen_block(' .{name} = {name},') }
143 s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
145 return bdrv_poll_co(&s.poll_state);
147 }}"""
150 def 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)
156 return res
159 if __name__ == '__main__':
160 if len(sys.argv) < 3:
161 exit(f'Usage: {sys.argv[0]} OUT_FILE.c IN_FILE.[ch]...')
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')