xref: /openbmc/qemu/scripts/qapi/commands.py (revision ec9697ab3fe2174a865d0ac2bbc572cbd5981d94)
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    if have_args:
130        assert arg_type is not None
131        arg_type_c_name = arg_type.c_name()
132
133    ret = mcgen('''
134
135%(proto)s
136{
137    Error *err = NULL;
138    bool ok = false;
139    Visitor *v;
140''',
141                proto=build_marshal_proto(name))
142
143    if ret_type:
144        ret += mcgen('''
145    %(c_type)s retval;
146''',
147                     c_type=ret_type.c_type())
148
149    if have_args:
150        ret += mcgen('''
151    %(c_name)s arg = {0};
152''',
153                     c_name=arg_type_c_name)
154
155    ret += mcgen('''
156
157    v = qobject_input_visitor_new(QOBJECT(args));
158    if (!visit_start_struct(v, NULL, NULL, 0, errp)) {
159        goto out;
160    }
161''')
162
163    if have_args:
164        ret += mcgen('''
165    if (visit_type_%(c_arg_type)s_members(v, &arg, errp)) {
166        ok = visit_check_struct(v, errp);
167    }
168''',
169                     c_arg_type=arg_type_c_name)
170    else:
171        ret += mcgen('''
172    ok = visit_check_struct(v, errp);
173''')
174
175    ret += mcgen('''
176    visit_end_struct(v, NULL);
177    if (!ok) {
178        goto out;
179    }
180''')
181
182    ret += gen_call(name, arg_type, boxed, ret_type)
183
184    ret += mcgen('''
185
186out:
187    visit_free(v);
188''')
189
190    ret += mcgen('''
191    v = qapi_dealloc_visitor_new();
192    visit_start_struct(v, NULL, NULL, 0, NULL);
193''')
194
195    if have_args:
196        ret += mcgen('''
197    visit_type_%(c_arg_type)s_members(v, &arg, NULL);
198''',
199                     c_arg_type=arg_type_c_name)
200
201    ret += mcgen('''
202    visit_end_struct(v, NULL);
203    visit_free(v);
204''')
205
206    ret += mcgen('''
207}
208''')
209    return ret
210
211
212def gen_register_command(name: str,
213                         success_response: bool,
214                         allow_oob: bool,
215                         allow_preconfig: bool,
216                         coroutine: bool) -> str:
217    options = []
218
219    if not success_response:
220        options += ['QCO_NO_SUCCESS_RESP']
221    if allow_oob:
222        options += ['QCO_ALLOW_OOB']
223    if allow_preconfig:
224        options += ['QCO_ALLOW_PRECONFIG']
225    if coroutine:
226        options += ['QCO_COROUTINE']
227
228    if not options:
229        options = ['QCO_NO_OPTIONS']
230
231    ret = mcgen('''
232    qmp_register_command(cmds, "%(name)s",
233                         qmp_marshal_%(c_name)s, %(opts)s);
234''',
235                name=name, c_name=c_name(name),
236                opts=" | ".join(options))
237    return ret
238
239
240def gen_registry(registry: str, prefix: str) -> str:
241    ret = mcgen('''
242
243void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds)
244{
245    QTAILQ_INIT(cmds);
246
247''',
248                c_prefix=c_name(prefix, protect=False))
249    ret += registry
250    ret += mcgen('''
251}
252''')
253    return ret
254
255
256class QAPISchemaGenCommandVisitor(QAPISchemaModularCVisitor):
257    def __init__(self, prefix: str):
258        super().__init__(
259            prefix, 'qapi-commands',
260            ' * Schema-defined QAPI/QMP commands', None, __doc__)
261        self._regy = QAPIGenCCode(None)
262        self._visited_ret_types: Dict[QAPIGenC, Set[QAPISchemaType]] = {}
263
264    def _begin_user_module(self, name: str) -> None:
265        self._visited_ret_types[self._genc] = set()
266        commands = self._module_basename('qapi-commands', name)
267        types = self._module_basename('qapi-types', name)
268        visit = self._module_basename('qapi-visit', name)
269        self._genc.add(mcgen('''
270#include "qemu/osdep.h"
271#include "qapi/visitor.h"
272#include "qapi/qmp/qdict.h"
273#include "qapi/qobject-output-visitor.h"
274#include "qapi/qobject-input-visitor.h"
275#include "qapi/dealloc-visitor.h"
276#include "qapi/error.h"
277#include "%(visit)s.h"
278#include "%(commands)s.h"
279
280''',
281                             commands=commands, visit=visit))
282        self._genh.add(mcgen('''
283#include "%(types)s.h"
284
285''',
286                             types=types))
287
288    def visit_end(self) -> None:
289        self._add_system_module('init', ' * QAPI Commands initialization')
290        self._genh.add(mcgen('''
291#include "qapi/qmp/dispatch.h"
292
293void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds);
294''',
295                             c_prefix=c_name(self._prefix, protect=False)))
296        self._genc.preamble_add(mcgen('''
297#include "qemu/osdep.h"
298#include "%(prefix)sqapi-commands.h"
299#include "%(prefix)sqapi-init-commands.h"
300''',
301                                      prefix=self._prefix))
302        self._genc.add(gen_registry(self._regy.get_content(), self._prefix))
303
304    def visit_command(self,
305                      name: str,
306                      info: QAPISourceInfo,
307                      ifcond: List[str],
308                      features: List[QAPISchemaFeature],
309                      arg_type: Optional[QAPISchemaObjectType],
310                      ret_type: Optional[QAPISchemaType],
311                      gen: bool,
312                      success_response: bool,
313                      boxed: bool,
314                      allow_oob: bool,
315                      allow_preconfig: bool,
316                      coroutine: bool) -> None:
317        if not gen:
318            return
319        # FIXME: If T is a user-defined type, the user is responsible
320        # for making this work, i.e. to make T's condition the
321        # conjunction of the T-returning commands' conditions.  If T
322        # is a built-in type, this isn't possible: the
323        # qmp_marshal_output_T() will be generated unconditionally.
324        if ret_type and ret_type not in self._visited_ret_types[self._genc]:
325            self._visited_ret_types[self._genc].add(ret_type)
326            with ifcontext(ret_type.ifcond,
327                           self._genh, self._genc, self._regy):
328                self._genc.add(gen_marshal_output(ret_type))
329        with ifcontext(ifcond, self._genh, self._genc, self._regy):
330            self._genh.add(gen_command_decl(name, arg_type, boxed, ret_type))
331            self._genh.add(gen_marshal_decl(name))
332            self._genc.add(gen_marshal(name, arg_type, boxed, ret_type))
333            self._regy.add(gen_register_command(name, success_response,
334                                                allow_oob, allow_preconfig,
335                                                coroutine))
336
337
338def gen_commands(schema: QAPISchema,
339                 output_dir: str,
340                 prefix: str) -> None:
341    vis = QAPISchemaGenCommandVisitor(prefix)
342    schema.visit(vis)
343    vis.write(output_dir)
344