xref: /openbmc/qemu/scripts/qapi/events.py (revision 6f03770d)
1"""
2QAPI event generator
3
4Copyright (c) 2014 Wenchao Xia
5Copyright (c) 2015-2018 Red Hat Inc.
6
7Authors:
8 Wenchao Xia <wenchaoqemu@gmail.com>
9 Markus Armbruster <armbru@redhat.com>
10
11This work is licensed under the terms of the GNU GPL, version 2.
12See the COPYING file in the top-level directory.
13"""
14
15from typing import List, Optional, Sequence
16
17from .common import c_enum_const, c_name, mcgen
18from .gen import QAPISchemaModularCVisitor, build_params, ifcontext
19from .schema import (
20    QAPISchema,
21    QAPISchemaEnumMember,
22    QAPISchemaFeature,
23    QAPISchemaObjectType,
24)
25from .source import QAPISourceInfo
26from .types import gen_enum, gen_enum_lookup
27
28
29def build_event_send_proto(name: str,
30                           arg_type: Optional[QAPISchemaObjectType],
31                           boxed: bool) -> str:
32    return 'void qapi_event_send_%(c_name)s(%(param)s)' % {
33        'c_name': c_name(name.lower()),
34        'param': build_params(arg_type, boxed)}
35
36
37def gen_event_send_decl(name: str,
38                        arg_type: Optional[QAPISchemaObjectType],
39                        boxed: bool) -> str:
40    return mcgen('''
41
42%(proto)s;
43''',
44                 proto=build_event_send_proto(name, arg_type, boxed))
45
46
47def gen_param_var(typ: QAPISchemaObjectType) -> str:
48    """
49    Generate a struct variable holding the event parameters.
50
51    Initialize it with the function arguments defined in `gen_event_send`.
52    """
53    assert not typ.variants
54    ret = mcgen('''
55    %(c_name)s param = {
56''',
57                c_name=typ.c_name())
58    sep = '        '
59    for memb in typ.members:
60        ret += sep
61        sep = ', '
62        if memb.optional:
63            ret += 'has_' + c_name(memb.name) + sep
64        if memb.type.name == 'str':
65            # Cast away const added in build_params()
66            ret += '(char *)'
67        ret += c_name(memb.name)
68    ret += mcgen('''
69
70    };
71''')
72    if not typ.is_implicit():
73        ret += mcgen('''
74    %(c_name)s *arg = &param;
75''',
76                     c_name=typ.c_name())
77    return ret
78
79
80def gen_event_send(name: str,
81                   arg_type: Optional[QAPISchemaObjectType],
82                   boxed: bool,
83                   event_enum_name: str,
84                   event_emit: str) -> str:
85    # FIXME: Our declaration of local variables (and of 'errp' in the
86    # parameter list) can collide with exploded members of the event's
87    # data type passed in as parameters.  If this collision ever hits in
88    # practice, we can rename our local variables with a leading _ prefix,
89    # or split the code into a wrapper function that creates a boxed
90    # 'param' object then calls another to do the real work.
91    have_args = boxed or (arg_type and not arg_type.is_empty())
92
93    ret = mcgen('''
94
95%(proto)s
96{
97    QDict *qmp;
98''',
99                proto=build_event_send_proto(name, arg_type, boxed))
100
101    if have_args:
102        assert arg_type is not None
103        ret += mcgen('''
104    QObject *obj;
105    Visitor *v;
106''')
107        if not boxed:
108            ret += gen_param_var(arg_type)
109
110    ret += mcgen('''
111
112    qmp = qmp_event_build_dict("%(name)s");
113
114''',
115                 name=name)
116
117    if have_args:
118        assert arg_type is not None
119        ret += mcgen('''
120    v = qobject_output_visitor_new(&obj);
121''')
122        if not arg_type.is_implicit():
123            ret += mcgen('''
124    visit_type_%(c_name)s(v, "%(name)s", &arg, &error_abort);
125''',
126                         name=name, c_name=arg_type.c_name())
127        else:
128            ret += mcgen('''
129
130    visit_start_struct(v, "%(name)s", NULL, 0, &error_abort);
131    visit_type_%(c_name)s_members(v, &param, &error_abort);
132    visit_check_struct(v, &error_abort);
133    visit_end_struct(v, NULL);
134''',
135                         name=name, c_name=arg_type.c_name())
136        ret += mcgen('''
137
138    visit_complete(v, &obj);
139    qdict_put_obj(qmp, "data", obj);
140''')
141
142    ret += mcgen('''
143    %(event_emit)s(%(c_enum)s, qmp);
144
145''',
146                 event_emit=event_emit,
147                 c_enum=c_enum_const(event_enum_name, name))
148
149    if have_args:
150        ret += mcgen('''
151    visit_free(v);
152''')
153    ret += mcgen('''
154    qobject_unref(qmp);
155}
156''')
157    return ret
158
159
160class QAPISchemaGenEventVisitor(QAPISchemaModularCVisitor):
161
162    def __init__(self, prefix: str):
163        super().__init__(
164            prefix, 'qapi-events',
165            ' * Schema-defined QAPI/QMP events', None, __doc__)
166        self._event_enum_name = c_name(prefix + 'QAPIEvent', protect=False)
167        self._event_enum_members: List[QAPISchemaEnumMember] = []
168        self._event_emit_name = c_name(prefix + 'qapi_event_emit')
169
170    def _begin_user_module(self, name: str) -> None:
171        events = self._module_basename('qapi-events', name)
172        types = self._module_basename('qapi-types', name)
173        visit = self._module_basename('qapi-visit', name)
174        self._genc.add(mcgen('''
175#include "qemu/osdep.h"
176#include "%(prefix)sqapi-emit-events.h"
177#include "%(events)s.h"
178#include "%(visit)s.h"
179#include "qapi/error.h"
180#include "qapi/qmp/qdict.h"
181#include "qapi/qobject-output-visitor.h"
182#include "qapi/qmp-event.h"
183
184''',
185                             events=events, visit=visit,
186                             prefix=self._prefix))
187        self._genh.add(mcgen('''
188#include "qapi/util.h"
189#include "%(types)s.h"
190''',
191                             types=types))
192
193    def visit_end(self) -> None:
194        self._add_module('./emit', ' * QAPI Events emission')
195        self._genc.preamble_add(mcgen('''
196#include "qemu/osdep.h"
197#include "%(prefix)sqapi-emit-events.h"
198''',
199                                      prefix=self._prefix))
200        self._genh.preamble_add(mcgen('''
201#include "qapi/util.h"
202'''))
203        self._genh.add(gen_enum(self._event_enum_name,
204                                self._event_enum_members))
205        self._genc.add(gen_enum_lookup(self._event_enum_name,
206                                       self._event_enum_members))
207        self._genh.add(mcgen('''
208
209void %(event_emit)s(%(event_enum)s event, QDict *qdict);
210''',
211                             event_emit=self._event_emit_name,
212                             event_enum=self._event_enum_name))
213
214    def visit_event(self,
215                    name: str,
216                    info: Optional[QAPISourceInfo],
217                    ifcond: Sequence[str],
218                    features: List[QAPISchemaFeature],
219                    arg_type: Optional[QAPISchemaObjectType],
220                    boxed: bool) -> None:
221        with ifcontext(ifcond, self._genh, self._genc):
222            self._genh.add(gen_event_send_decl(name, arg_type, boxed))
223            self._genc.add(gen_event_send(name, arg_type, boxed,
224                                          self._event_enum_name,
225                                          self._event_emit_name))
226        # Note: we generate the enum member regardless of @ifcond, to
227        # keep the enumeration usable in target-independent code.
228        self._event_enum_members.append(QAPISchemaEnumMember(name, None))
229
230
231def gen_events(schema: QAPISchema,
232               output_dir: str,
233               prefix: str) -> None:
234    vis = QAPISchemaGenEventVisitor(prefix)
235    schema.visit(vis)
236    vis.write(output_dir)
237