xref: /openbmc/qemu/scripts/qapi/commands.py (revision 69430111)
1"""
2QAPI command marshaller generator
3
4Copyright IBM, Corp. 2011
5Copyright (C) 2014-2018 Red Hat, Inc.
6
7Authors:
8 Anthony Liguori <aliguori@us.ibm.com>
9 Michael Roth <mdroth@linux.vnet.ibm.com>
10 Markus Armbruster <armbru@redhat.com>
11
12This work is licensed under the terms of the GNU GPL, version 2.
13See the COPYING file in the top-level directory.
14"""
15
16from typing import (
17    Dict,
18    List,
19    Optional,
20    Set,
21)
22
23from .common import c_name, mcgen
24from .gen import (
25    QAPIGenC,
26    QAPIGenCCode,
27    QAPISchemaModularCVisitor,
28    build_params,
29    ifcontext,
30)
31from .schema import (
32    QAPISchema,
33    QAPISchemaFeature,
34    QAPISchemaObjectType,
35    QAPISchemaType,
36)
37from .source import QAPISourceInfo
38
39
40def gen_command_decl(name: str,
41                     arg_type: Optional[QAPISchemaObjectType],
42                     boxed: bool,
43                     ret_type: Optional[QAPISchemaType]) -> str:
44    return mcgen('''
45%(c_type)s qmp_%(c_name)s(%(params)s);
46''',
47                 c_type=(ret_type and ret_type.c_type()) or 'void',
48                 c_name=c_name(name),
49                 params=build_params(arg_type, boxed, 'Error **errp'))
50
51
52def gen_call(name: str,
53             arg_type: Optional[QAPISchemaObjectType],
54             boxed: bool,
55             ret_type: Optional[QAPISchemaType]) -> str:
56    ret = ''
57
58    argstr = ''
59    if boxed:
60        assert arg_type
61        argstr = '&arg, '
62    elif arg_type:
63        assert not arg_type.variants
64        for memb in arg_type.members:
65            if memb.optional:
66                argstr += 'arg.has_%s, ' % c_name(memb.name)
67            argstr += 'arg.%s, ' % c_name(memb.name)
68
69    lhs = ''
70    if ret_type:
71        lhs = 'retval = '
72
73    ret = mcgen('''
74
75    %(lhs)sqmp_%(c_name)s(%(args)s&err);
76    error_propagate(errp, err);
77''',
78                c_name=c_name(name), args=argstr, lhs=lhs)
79    if ret_type:
80        ret += mcgen('''
81    if (err) {
82        goto out;
83    }
84
85    qmp_marshal_output_%(c_name)s(retval, ret, errp);
86''',
87                     c_name=ret_type.c_name())
88    return ret
89
90
91def gen_marshal_output(ret_type: QAPISchemaType) -> str:
92    return mcgen('''
93
94static void qmp_marshal_output_%(c_name)s(%(c_type)s ret_in,
95                                QObject **ret_out, Error **errp)
96{
97    Visitor *v;
98
99    v = qobject_output_visitor_new(ret_out);
100    if (visit_type_%(c_name)s(v, "unused", &ret_in, errp)) {
101        visit_complete(v, ret_out);
102    }
103    visit_free(v);
104    v = qapi_dealloc_visitor_new();
105    visit_type_%(c_name)s(v, "unused", &ret_in, NULL);
106    visit_free(v);
107}
108''',
109                 c_type=ret_type.c_type(), c_name=ret_type.c_name())
110
111
112def build_marshal_proto(name: str) -> str:
113    return ('void qmp_marshal_%s(QDict *args, QObject **ret, Error **errp)'
114            % c_name(name))
115
116
117def gen_marshal_decl(name: str) -> str:
118    return mcgen('''
119%(proto)s;
120''',
121                 proto=build_marshal_proto(name))
122
123
124def gen_marshal(name: str,
125                arg_type: Optional[QAPISchemaObjectType],
126                boxed: bool,
127                ret_type: Optional[QAPISchemaType]) -> str:
128    have_args = boxed or (arg_type and not arg_type.is_empty())
129
130    ret = mcgen('''
131
132%(proto)s
133{
134    Error *err = NULL;
135    bool ok = false;
136    Visitor *v;
137''',
138                proto=build_marshal_proto(name))
139
140    if ret_type:
141        ret += mcgen('''
142    %(c_type)s retval;
143''',
144                     c_type=ret_type.c_type())
145
146    if have_args:
147        ret += mcgen('''
148    %(c_name)s arg = {0};
149''',
150                     c_name=arg_type.c_name())
151
152    ret += mcgen('''
153
154    v = qobject_input_visitor_new(QOBJECT(args));
155    if (!visit_start_struct(v, NULL, NULL, 0, errp)) {
156        goto out;
157    }
158''')
159
160    if have_args:
161        ret += mcgen('''
162    if (visit_type_%(c_arg_type)s_members(v, &arg, errp)) {
163        ok = visit_check_struct(v, errp);
164    }
165''',
166                     c_arg_type=arg_type.c_name())
167    else:
168        ret += mcgen('''
169    ok = visit_check_struct(v, errp);
170''')
171
172    ret += mcgen('''
173    visit_end_struct(v, NULL);
174    if (!ok) {
175        goto out;
176    }
177''')
178
179    ret += gen_call(name, arg_type, boxed, ret_type)
180
181    ret += mcgen('''
182
183out:
184    visit_free(v);
185''')
186
187    ret += mcgen('''
188    v = qapi_dealloc_visitor_new();
189    visit_start_struct(v, NULL, NULL, 0, NULL);
190''')
191
192    if have_args:
193        ret += mcgen('''
194    visit_type_%(c_arg_type)s_members(v, &arg, NULL);
195''',
196                     c_arg_type=arg_type.c_name())
197
198    ret += mcgen('''
199    visit_end_struct(v, NULL);
200    visit_free(v);
201''')
202
203    ret += mcgen('''
204}
205''')
206    return ret
207
208
209def gen_register_command(name: str,
210                         success_response: bool,
211                         allow_oob: bool,
212                         allow_preconfig: bool,
213                         coroutine: bool) -> str:
214    options = []
215
216    if not success_response:
217        options += ['QCO_NO_SUCCESS_RESP']
218    if allow_oob:
219        options += ['QCO_ALLOW_OOB']
220    if allow_preconfig:
221        options += ['QCO_ALLOW_PRECONFIG']
222    if coroutine:
223        options += ['QCO_COROUTINE']
224
225    if not options:
226        options = ['QCO_NO_OPTIONS']
227
228    ret = mcgen('''
229    qmp_register_command(cmds, "%(name)s",
230                         qmp_marshal_%(c_name)s, %(opts)s);
231''',
232                name=name, c_name=c_name(name),
233                opts=" | ".join(options))
234    return ret
235
236
237def gen_registry(registry: str, prefix: str) -> str:
238    ret = mcgen('''
239
240void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds)
241{
242    QTAILQ_INIT(cmds);
243
244''',
245                c_prefix=c_name(prefix, protect=False))
246    ret += registry
247    ret += mcgen('''
248}
249''')
250    return ret
251
252
253class QAPISchemaGenCommandVisitor(QAPISchemaModularCVisitor):
254    def __init__(self, prefix: str):
255        super().__init__(
256            prefix, 'qapi-commands',
257            ' * Schema-defined QAPI/QMP commands', None, __doc__)
258        self._regy = QAPIGenCCode(None)
259        self._visited_ret_types: Dict[QAPIGenC, Set[QAPISchemaType]] = {}
260
261    def _begin_user_module(self, name: str) -> None:
262        self._visited_ret_types[self._genc] = set()
263        commands = self._module_basename('qapi-commands', name)
264        types = self._module_basename('qapi-types', name)
265        visit = self._module_basename('qapi-visit', name)
266        self._genc.add(mcgen('''
267#include "qemu/osdep.h"
268#include "qapi/visitor.h"
269#include "qapi/qmp/qdict.h"
270#include "qapi/qobject-output-visitor.h"
271#include "qapi/qobject-input-visitor.h"
272#include "qapi/dealloc-visitor.h"
273#include "qapi/error.h"
274#include "%(visit)s.h"
275#include "%(commands)s.h"
276
277''',
278                             commands=commands, visit=visit))
279        self._genh.add(mcgen('''
280#include "%(types)s.h"
281
282''',
283                             types=types))
284
285    def visit_end(self) -> None:
286        self._add_system_module('init', ' * QAPI Commands initialization')
287        self._genh.add(mcgen('''
288#include "qapi/qmp/dispatch.h"
289
290void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds);
291''',
292                             c_prefix=c_name(self._prefix, protect=False)))
293        self._genc.preamble_add(mcgen('''
294#include "qemu/osdep.h"
295#include "%(prefix)sqapi-commands.h"
296#include "%(prefix)sqapi-init-commands.h"
297''',
298                                      prefix=self._prefix))
299        self._genc.add(gen_registry(self._regy.get_content(), self._prefix))
300
301    def visit_command(self,
302                      name: str,
303                      info: QAPISourceInfo,
304                      ifcond: List[str],
305                      features: List[QAPISchemaFeature],
306                      arg_type: Optional[QAPISchemaObjectType],
307                      ret_type: Optional[QAPISchemaType],
308                      gen: bool,
309                      success_response: bool,
310                      boxed: bool,
311                      allow_oob: bool,
312                      allow_preconfig: bool,
313                      coroutine: bool) -> None:
314        if not gen:
315            return
316        # FIXME: If T is a user-defined type, the user is responsible
317        # for making this work, i.e. to make T's condition the
318        # conjunction of the T-returning commands' conditions.  If T
319        # is a built-in type, this isn't possible: the
320        # qmp_marshal_output_T() will be generated unconditionally.
321        if ret_type and ret_type not in self._visited_ret_types[self._genc]:
322            self._visited_ret_types[self._genc].add(ret_type)
323            with ifcontext(ret_type.ifcond,
324                           self._genh, self._genc, self._regy):
325                self._genc.add(gen_marshal_output(ret_type))
326        with ifcontext(ifcond, self._genh, self._genc, self._regy):
327            self._genh.add(gen_command_decl(name, arg_type, boxed, ret_type))
328            self._genh.add(gen_marshal_decl(name))
329            self._genc.add(gen_marshal(name, arg_type, boxed, ret_type))
330            self._regy.add(gen_register_command(name, success_response,
331                                                allow_oob, allow_preconfig,
332                                                coroutine))
333
334
335def gen_commands(schema: QAPISchema,
336                 output_dir: str,
337                 prefix: str) -> None:
338    vis = QAPISchemaGenCommandVisitor(prefix)
339    schema.visit(vis)
340    vis.write(output_dir)
341