xref: /openbmc/qemu/scripts/qapi/commands.py (revision 167d913f34aa469fa30b0c51a04d8d2b9a5f1fa5)
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    QAPISchemaModularCVisitor,
27    build_params,
28    ifcontext,
29    gen_special_features,
30)
31from .schema import (
32    QAPISchema,
33    QAPISchemaFeature,
34    QAPISchemaIfCond,
35    QAPISchemaObjectType,
36    QAPISchemaType,
37)
38from .source import QAPISourceInfo
39
40
41def gen_command_decl(name: str,
42                     arg_type: Optional[QAPISchemaObjectType],
43                     boxed: bool,
44                     ret_type: Optional[QAPISchemaType]) -> str:
45    return mcgen('''
46%(c_type)s qmp_%(c_name)s(%(params)s);
47''',
48                 c_type=(ret_type and ret_type.c_type()) or 'void',
49                 c_name=c_name(name),
50                 params=build_params(arg_type, boxed, 'Error **errp'))
51
52
53def gen_call(name: str,
54             arg_type: Optional[QAPISchemaObjectType],
55             boxed: bool,
56             ret_type: Optional[QAPISchemaType]) -> str:
57    ret = ''
58
59    argstr = ''
60    if boxed:
61        assert arg_type
62        argstr = '&arg, '
63    elif arg_type:
64        assert not arg_type.variants
65        for memb in arg_type.members:
66            if memb.optional:
67                argstr += 'arg.has_%s, ' % c_name(memb.name)
68            argstr += 'arg.%s, ' % c_name(memb.name)
69
70    lhs = ''
71    if ret_type:
72        lhs = 'retval = '
73
74    ret = mcgen('''
75
76    %(lhs)sqmp_%(c_name)s(%(args)s&err);
77''',
78                c_name=c_name(name), args=argstr, lhs=lhs)
79
80    ret += mcgen('''
81    if (err) {
82        error_propagate(errp, err);
83        goto out;
84    }
85''')
86
87    if ret_type:
88        ret += mcgen('''
89
90    qmp_marshal_output_%(c_name)s(retval, ret, errp);
91''',
92                     c_name=ret_type.c_name())
93    return ret
94
95
96def gen_marshal_output(ret_type: QAPISchemaType) -> str:
97    return mcgen('''
98
99static void qmp_marshal_output_%(c_name)s(%(c_type)s ret_in,
100                                QObject **ret_out, Error **errp)
101{
102    Visitor *v;
103
104    v = qobject_output_visitor_new_qmp(ret_out);
105    if (visit_type_%(c_name)s(v, "unused", &ret_in, errp)) {
106        visit_complete(v, ret_out);
107    }
108    visit_free(v);
109    v = qapi_dealloc_visitor_new();
110    visit_type_%(c_name)s(v, "unused", &ret_in, NULL);
111    visit_free(v);
112}
113''',
114                 c_type=ret_type.c_type(), c_name=ret_type.c_name())
115
116
117def build_marshal_proto(name: str) -> str:
118    return ('void qmp_marshal_%s(QDict *args, QObject **ret, Error **errp)'
119            % c_name(name))
120
121
122def gen_marshal_decl(name: str) -> str:
123    return mcgen('''
124%(proto)s;
125''',
126                 proto=build_marshal_proto(name))
127
128
129def gen_marshal(name: str,
130                arg_type: Optional[QAPISchemaObjectType],
131                boxed: bool,
132                ret_type: Optional[QAPISchemaType]) -> str:
133    have_args = boxed or (arg_type and not arg_type.is_empty())
134    if have_args:
135        assert arg_type is not None
136        arg_type_c_name = arg_type.c_name()
137
138    ret = mcgen('''
139
140%(proto)s
141{
142    Error *err = NULL;
143    bool ok = false;
144    Visitor *v;
145''',
146                proto=build_marshal_proto(name))
147
148    if ret_type:
149        ret += mcgen('''
150    %(c_type)s retval;
151''',
152                     c_type=ret_type.c_type())
153
154    if have_args:
155        ret += mcgen('''
156    %(c_name)s arg = {0};
157''',
158                     c_name=arg_type_c_name)
159
160    ret += mcgen('''
161
162    v = qobject_input_visitor_new_qmp(QOBJECT(args));
163    if (!visit_start_struct(v, NULL, NULL, 0, errp)) {
164        goto out;
165    }
166''')
167
168    if have_args:
169        ret += mcgen('''
170    if (visit_type_%(c_arg_type)s_members(v, &arg, errp)) {
171        ok = visit_check_struct(v, errp);
172    }
173''',
174                     c_arg_type=arg_type_c_name)
175    else:
176        ret += mcgen('''
177    ok = visit_check_struct(v, errp);
178''')
179
180    ret += mcgen('''
181    visit_end_struct(v, NULL);
182    if (!ok) {
183        goto out;
184    }
185''')
186
187    ret += gen_call(name, arg_type, boxed, ret_type)
188
189    ret += mcgen('''
190
191out:
192    visit_free(v);
193''')
194
195    ret += mcgen('''
196    v = qapi_dealloc_visitor_new();
197    visit_start_struct(v, NULL, NULL, 0, NULL);
198''')
199
200    if have_args:
201        ret += mcgen('''
202    visit_type_%(c_arg_type)s_members(v, &arg, NULL);
203''',
204                     c_arg_type=arg_type_c_name)
205
206    ret += mcgen('''
207    visit_end_struct(v, NULL);
208    visit_free(v);
209''')
210
211    ret += mcgen('''
212}
213''')
214    return ret
215
216
217def gen_register_command(name: str,
218                         features: List[QAPISchemaFeature],
219                         success_response: bool,
220                         allow_oob: bool,
221                         allow_preconfig: bool,
222                         coroutine: bool) -> str:
223    options = []
224
225    if not success_response:
226        options += ['QCO_NO_SUCCESS_RESP']
227    if allow_oob:
228        options += ['QCO_ALLOW_OOB']
229    if allow_preconfig:
230        options += ['QCO_ALLOW_PRECONFIG']
231    if coroutine:
232        options += ['QCO_COROUTINE']
233
234    ret = mcgen('''
235    qmp_register_command(cmds, "%(name)s",
236                         qmp_marshal_%(c_name)s, %(opts)s, %(feats)s);
237''',
238                name=name, c_name=c_name(name),
239                opts=' | '.join(options) or 0,
240                feats=gen_special_features(features))
241    return ret
242
243
244class QAPISchemaGenCommandVisitor(QAPISchemaModularCVisitor):
245    def __init__(self, prefix: str):
246        super().__init__(
247            prefix, 'qapi-commands',
248            ' * Schema-defined QAPI/QMP commands', None, __doc__)
249        self._visited_ret_types: Dict[QAPIGenC, Set[QAPISchemaType]] = {}
250
251    def _begin_user_module(self, name: str) -> None:
252        self._visited_ret_types[self._genc] = set()
253        commands = self._module_basename('qapi-commands', name)
254        types = self._module_basename('qapi-types', name)
255        visit = self._module_basename('qapi-visit', name)
256        self._genc.add(mcgen('''
257#include "qemu/osdep.h"
258#include "qapi/compat-policy.h"
259#include "qapi/visitor.h"
260#include "qapi/qmp/qdict.h"
261#include "qapi/dealloc-visitor.h"
262#include "qapi/error.h"
263#include "%(visit)s.h"
264#include "%(commands)s.h"
265
266''',
267                             commands=commands, visit=visit))
268        self._genh.add(mcgen('''
269#include "%(types)s.h"
270
271''',
272                             types=types))
273
274    def visit_begin(self, schema: QAPISchema) -> None:
275        self._add_module('./init', ' * QAPI Commands initialization')
276        self._genh.add(mcgen('''
277#include "qapi/qmp/dispatch.h"
278
279void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds);
280''',
281                             c_prefix=c_name(self._prefix, protect=False)))
282        self._genc.add(mcgen('''
283#include "qemu/osdep.h"
284#include "%(prefix)sqapi-commands.h"
285#include "%(prefix)sqapi-init-commands.h"
286
287void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds)
288{
289    QTAILQ_INIT(cmds);
290
291''',
292                             prefix=self._prefix,
293                             c_prefix=c_name(self._prefix, protect=False)))
294
295    def visit_end(self) -> None:
296        with self._temp_module('./init'):
297            self._genc.add(mcgen('''
298}
299'''))
300
301    def visit_command(self,
302                      name: str,
303                      info: Optional[QAPISourceInfo],
304                      ifcond: QAPISchemaIfCond,
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):
325                self._genc.add(gen_marshal_output(ret_type))
326        with ifcontext(ifcond, self._genh, self._genc):
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        with self._temp_module('./init'):
331            with ifcontext(ifcond, self._genh, self._genc):
332                self._genc.add(gen_register_command(
333                    name, features, success_response, allow_oob,
334                    allow_preconfig, coroutine))
335
336
337def gen_commands(schema: QAPISchema,
338                 output_dir: str,
339                 prefix: str) -> None:
340    vis = QAPISchemaGenCommandVisitor(prefix)
341    schema.visit(vis)
342    vis.write(output_dir)
343