Skip to contentSkip to conversation

qapi: remove the 'middle' mode

PATCH Superseded Marc-André Lureau 5 participants 31 messages Aug 17, 2016 – Sep 9, 2016 Kbuild

v5 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v5 cover qapi: remove the 'middle' mode

Hi,

Although some QMP commands are still not fully qapi'fied, it is possible to use more qapi common and generated code by dropping the 'middle' mode and use qmp_dispatch().

v5:
- replace the dynamic unregister commands approach by a few preliminary patches to make the json schema #ifdef conditional and per-target
- fix "check invalid arguments" patch based on Markus version
- patch reordering

v4:
- export all marshaller functions (so we can keep calling them after middle mode is removed), remove 'export-marshal' patch
- get rid of unnecessary lambda in python code (leftover), remove second mcgen(), and outdated comment
- remove disabled commands at run-time to avoid any regression. It's now on my TODO list to fix qapi generator in 2.8 to have conditionals
- move qmp-commands.txt to doc/
- split the last patch, remove trailing ws
- add QEMU_VERSION_{MAJOR,MINOR,MICRO} patch, simplifying qmp_query_version() (could be applied outside this series)
- update commit title/messages/order

v3:
- add a reference to docs/qmp-spec.txt in qmp_capabilities doc
- remove 'props' from device_add doc, improve example
- replace a g_strcmp0 with more appropriate g_str_equal
- add 'export-marshal' command generator key patch
- call qmp_marshal_query_version() directly (also get rid of the need to do a make clean, since the qapi json is modified)
- add patch to check invalid arguments on no-args (the old dispatch code checks that), and a test
- patch reordering to fix intermediate builds
- commit messages improvements
- split some misc doc fixes in last patch
- add some r-b and rebase

v2:
- rebased on master
- add Since: 0.13 to qmp_capabilities and device_add documentation
- fix device_add doc
- add missing spaces after ',' in get_qmp_greeting()
- fix some grammar in monitor.c while touching it

Marc-André Lureau (20):
tests: do qmp introspect validation per target qapi.py: add a simple #ifdef conditional
build-sys: make qemu qapi per-target
build-sys: use config headers to generate qapi
qapi: configure the schema
build-sys: define QEMU_VERSION_{MAJOR,MINOR,MICRO}
qapi-schema: use generated marshaller for 'qmp_capabilities'
qapi-schema: add 'device_add'
monitor: simplify invalid_qmp_mode()
monitor: register gen:false commands manually
qapi: export the marshallers
monitor: use qmp_find_command() (using generated qapi code)
monitor: implement 'qmp_query_commands' without qmp_cmds
monitor: remove mhandler.cmd_new
qapi: remove the "middle" mode
qapi: check invalid arguments on no-args commands
monitor: use qmp_dispatch()
build-sys: remove qmp-commands-old.h qmp-commands.hx: fix some styling
Replace qmp-commands.hx by doc/qmp-commands.txt

 hmp.c                                    |    2 +
 monitor.c                                |  415 ++--------
 qmp.c                                    |   48 +-
 stubs/qapi-event.c                       |   74 ++
 tests/qmp-introspect-test.c              |   50 ++
 tests/test-qmp-commands.c                |   15 +
 tests/test-qmp-input-strict.c            |    2 -
 vl.c                                     |    1 +
 Makefile                                 |   61 +-
 Makefile.objs                            |    7 +-
 Makefile.target                          |   32 +-
 scripts/create_config                    |    6 +
 scripts/qapi-commands.py                 |   81 +-
 scripts/qapi.py                          |   43 +-
 stubs/Makefile.objs                      |    1 +
 tests/Makefile.include                   |    2 +
 .gitignore                               |    1 -
 MAINTAINERS                              |    1 -
 docs/qapi-code-gen.txt                   |    6 +-
 qmp-commands.hx => docs/qmp-commands.txt | 1278 +-----------------------------
 docs/writing-qmp-commands.txt            |   46 +-
 hmp-commands-info.hx                     |  120 +--
 hmp-commands.hx                          |  208 ++---
 qapi-schema.json                         |   91 +++
 qapi.mak                                 |   14 +
 qapi/event.json                          |    8 +
 trace-events                             |    1 -
 27 files changed, 667 insertions(+), 1947 deletions(-)
 create mode 100644 stubs/qapi-event.c
 create mode 100644 tests/qmp-introspect-test.c
 rename qmp-commands.hx => docs/qmp-commands.txt (82%)
 create mode 100644 qapi.mak
Signature · 1 line
2.9.0
#1 lore raw

PATCH v5 1/20 tests: do qmp introspect validation per target

The following commits will move the qmp schema to be per target, and can't be linked. Instead of validating it directly, query it from the target via qmp.

---
 tests/qmp-introspect-test.c   | 50 +++++++++++++++++++++++++++++++++++++++++++
 tests/test-qmp-input-strict.c |  2 --
 tests/Makefile.include        |  2 ++
 3 files changed, 52 insertions(+), 2 deletions(-)
 create mode 100644 tests/qmp-introspect-test.c
tests/qmp-introspect-test.c new file +50 -0
new file mode 100644
index 0000000..cafb311
@@ -0,0 +1,50 @@
+/*
+ * Per-target QAPI introspection test cases
+ *
+ * Copyright (c) 2016 Red Hat Inc.
+ *
+ * Authors:
+ *  Marc-André Lureau <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include "qemu/osdep.h"
+#include "qemu-common.h"
+#include "qapi/qmp/qstring.h"
+#include "qapi/qmp-input-visitor.h"
+#include "qapi/error.h"
+#include "qapi-visit.h"
+#include "libqtest.h"
+
+const char common_args[] = "-nodefaults -machine none";
+
+static void test_qmp_introspect_validate(void)
+{
+    SchemaInfoList *schema;
+    QDict *resp;
+    Visitor *v;
+
+    qtest_start(common_args);
+
+    resp = qmp("{'execute': 'query-qmp-schema'}");
+    v = qmp_input_visitor_new(qdict_get(resp, "return"), true);
+    visit_type_SchemaInfoList(v, NULL, &schema, &error_abort);
+    g_assert(schema);
+
+    qapi_free_SchemaInfoList(schema);
+    visit_free(v);
+    QDECREF(resp);
+
+    qtest_end();
+}
+
+int main(int argc, char **argv)
+{
+    g_test_init(&argc, &argv, NULL);
+
+    qtest_add_func("qmp-introspect/validate", test_qmp_introspect_validate);
+
+    return g_test_run();
+}
tests/test-qmp-input-strict.c +0 -2
index 814550a..003a90e 100644
@@ -21,7 +21,6 @@
 #include "qapi/qmp/types.h"
 #include "qapi/qmp/qjson.h"
 #include "test-qmp-introspect.h"
-#include "qmp-introspect.h"
 #include "qapi-visit.h"
 
 typedef struct TestInputVisitorData {
@@ -283,7 +282,6 @@ static void test_validate_qmp_introspect(TestInputVisitorData *data,
                                            const void *unused)
 {
     do_test_validate_qmp_introspect(data, test_qmp_schema_json);
-    do_test_validate_qmp_introspect(data, qmp_schema_json);
 }
 
 static void validate_test_add(const char *testpath,
tests/Makefile.include +2 -0
index 14be491..983b5b4 100644
@@ -119,6 +119,7 @@ check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
 # really in libqtest, not in the testcases themselves.
 
 check-qtest-generic-y = tests/device-introspect-test$(EXESUF)
+check-qtest-generic-y = tests/qmp-introspect-test$(EXESUF)
 gcov-files-generic-y = qdev-monitor.c qmp.c
 
 gcov-files-ipack-y += hw/ipack/ipack.c
@@ -565,6 +566,7 @@ libqos-imx-obj-y = $(libqos-obj-y) tests/libqos/i2c-imx.o
 libqos-usb-obj-y = $(libqos-pc-obj-y) tests/libqos/usb.o
 libqos-virtio-obj-y = $(libqos-pc-obj-y) tests/libqos/virtio.o tests/libqos/virtio-pci.o tests/libqos/virtio-mmio.o tests/libqos/malloc-generic.o
 
+tests/qmp-introspect-test$(EXESUF): tests/qmp-introspect-test.o
 tests/device-introspect-test$(EXESUF): tests/device-introspect-test.o
 tests/rtc-test$(EXESUF): tests/rtc-test.o
 tests/m48t59-test$(EXESUF): tests/m48t59-test.o
Signature · 1 line
2.9.0
#2 lore raw

PATCH v5 2/20 qapi.py: add a simple #ifdef conditional

In reply to Marc-André Lureau

Learn to parse #define files provided with -f option, and skip undefined #ifdef blocks in the schema.

This is a very simple pre-processing, without stacking support or evaluation (it could be implemented if needed).

---
 scripts/qapi.py | 43 ++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 40 insertions(+), 3 deletions(-)
scripts/qapi.py +40 -3
index 21bc32f..d0b8a66 100644
@@ -76,6 +76,7 @@ struct_types = []
 union_types = []
 events = []
 all_names = {}
+defs = []
 
 #
 # Parsing the schema into expressions
@@ -177,6 +178,7 @@ class QAPISchemaParser(object):
                 self.exprs.append(expr_elem)
 
     def accept(self):
+        ok = True
         while True:
             self.tok = self.src[self.cursor]
             self.pos = self.cursor
@@ -184,7 +186,19 @@ class QAPISchemaParser(object):
             self.val = None
 
             if self.tok == '#':
-                self.cursor = self.src.find('\n', self.cursor)
+                end = self.src.find('\n', self.cursor)
+                line = self.src[self.cursor:end+1]
+                self.cursor = end
+                sline = line.split()
+                if len(defs) and len(sline) >= 1 \
+                   and sline[0] in ['ifdef', 'endif']:
+                    if sline[0] == 'ifdef':
+                        ok = sline[1] in defs
+                    elif sline[0] == 'endif':
+                        ok = True
+                    continue
+            elif not ok:
+                continue
             elif self.tok in "{}:,[]":
                 return
             elif self.tok == "'":
@@ -1707,15 +1721,36 @@ def gen_params(arg_type, boxed, extra):
 #
 # Common command line parsing
 #
+def defile(filename):
+    f = open(filename, 'r')
+    while 1:
+        line = f.readline()
+        if not line:
+            break
+        while line[-2:] == '\\\n':
+            nextline = f.readline()
+            if not nextline:
+                break
+            line = line + nextline
+        tmp = line.strip()
+        if tmp[:1] != '#':
+            continue
+        tmp = tmp[1:]
+        words = tmp.split()
+        if words[0] != "define":
+            continue
+        defs.append(words[1])
+    f.close()
 
 
 def parse_command_line(extra_options="", extra_long_options=[]):
 
     try:
         opts, args = getopt.gnu_getopt(sys.argv[1:],
-                                       "chp:o:" + extra_options,
+                                       "chp:o:f:" + extra_options,
                                        ["source", "header", "prefix=",
-                                        "output-dir="] + extra_long_options)
+                                        "output-dir=", "--defile="] +
+                                       extra_long_options)
     except getopt.GetoptError as err:
         print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
         sys.exit(1)
@@ -1742,6 +1777,8 @@ def parse_command_line(extra_options="", extra_long_options=[]):
             do_c = True
         elif o in ("-h", "--header"):
             do_h = True
+        elif o in ("-f", "--defile"):
+            defile(a)
         else:
             extra_opts.append(oa)
 
Signature · 1 line
2.9.0
#3 lore raw

Re: [Qemu-devel] [PATCH v5 02/20] qapi.py: add a simple #ifdef conditional

Quoted 9 lines · Marc-André Lureau

Learn to parse #define files provided with -f option, and skip undefined #ifdef blocks in the schema.

This is a very simple pre-processing, without stacking support or evaluation (it could be implemented if needed).

---
 scripts/qapi.py | 43 ++++++++++++++++++++++++++++++++++++++++---

Missing: update of docs/qapi-code-gen.txt.

Quoted 33 lines
 1 file changed, 40 insertions(+), 3 deletions(-)
scripts/qapi.py +8 -1
index 21bc32f..d0b8a66 100644
@@ -76,6 +76,7 @@ struct_types = []
 union_types = []
 events = []
 all_names = {}
+defs = []
 
 #
 # Parsing the schema into expressions
@@ -177,6 +178,7 @@ class QAPISchemaParser(object):
                 self.exprs.append(expr_elem)
 
     def accept(self):
+        ok = True
         while True:
             self.tok = self.src[self.cursor]
             self.pos = self.cursor
@@ -184,7 +186,19 @@ class QAPISchemaParser(object):
             self.val = None
 
             if self.tok == '#':
-                self.cursor = self.src.find('\n', self.cursor)
+                end = self.src.find('\n', self.cursor)
+                line = self.src[self.cursor:end+1]
+                self.cursor = end
+                sline = line.split()
+                if len(defs) and len(sline) >= 1 \
+                   and sline[0] in ['ifdef', 'endif']:

scripts/qapi.py class QAPISchemaParser(object): · line 204

Quoted 10 lines
scripts/qapi.py +7 -0
+                    if sline[0] == 'ifdef':
+                        ok = sline[1] in defs
+                    elif sline[0] == 'endif':
+                        ok = True
+                    continue
+            elif not ok:
+                continue
             elif self.tok in "{}:,[]":
                 return
             elif self.tok == "'":

Oww, you're abusing comments! That's horrible :)

Can we make this real syntax, like everything else, including 'include'?

Unfortunately, the natural

{ 'ifdef': 'CONFIG_FOO'
'then': ... # ignored unless CONFIG_FOO
'else': ... # ignored if CONFIG_FOO (optional)
}

is awkward, because the ... have to be a single JSON value, but a QAPI schema isn't a single JSON value, it's a *sequence* of JSON values. A top-level stanza

    JSON-value1 JSON-value2 ...

would become

    [ JSON-value1, JSON-value2, ... ]

within a conditional. Blech.

Could sacrifice the nesting and do

    { 'ifdef': 'CONFIG_FOO' }
    ...
    { 'endif' }

Widens the gap between syntax and semantics. Editors can no longer easily jump over the conditional (e.g. Emacs forward-sexp). Nested conditionals becomes as confusing as in C. Not exactly elegant, either.

Yet another option is to add 'ifdef' keys to the definitions themselves, i.e.

{ 'command': 'query-gic-capabilities', 'returns': ['GICCapability'],
'ifdef': 'TARGET_ARM' }

Quoted 7 lines
scripts/qapi.py +1 -0
@@ -1707,15 +1721,36 @@ def gen_params(arg_type, boxed, extra):
 #
 # Common command line parsing
 #
+def defile(filename):
 

From The Collaborative International Dictionary of English v.0.48 [gcide]:

Defile \De*file"\ (d[-e]*f[imac]l"), v. t. [OE. defoulen,
-foilen, to tread down, OF. defouler; de- + fouler to trample (see Full, v. t.), and OE. defoulen to foul (influenced in form by the older verb defoilen). See File to defile, Foul, Defoul.]
1. To make foul or impure; to make filthy; to dirty; to befoul; to pollute.
[1913 Webster]

They that touch pitch will be defiled. --Shak.
[1913 Webster]

2. To soil or sully; to tarnish, as reputation; to taint.

      [1913 Webster]

            He is . . . among the greatest prelates of this age,
            however his character may be defiled by . . . dirty
            hands.                                --Swift.
      [1913 Webster]

3. To injure in purity of character; to corrupt.

      [1913 Webster]

            Defile not yourselves with the idols of Egypt.
                                                  --Ezek. xx. 7.
      [1913 Webster]

4. To corrupt the chastity of; to debauch; to violate; to

      rape.
      [1913 Webster]

            The husband murder'd and the wife defiled. --Prior.
      [1913 Webster]

5. To make ceremonially unclean; to pollute.

      [1913 Webster]

            That which dieth of itself, or is torn with beasts,
            he shall not eat to defile therewith. --Lev. xxii.
                                                  8.
      [1913 Webster]

Fitting in a way; you're defiling the poor, innocent comment syntax ;)

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1726

Quoted 2 lines
scripts/qapi.py +2 -0
+    f = open(filename, 'r')
+    while 1:

while True:

Quoted 7 lines
scripts/qapi.py +7 -0
+        line = f.readline()
+        if not line:
+            break
+        while line[-2:] == '\\\n':
+            nextline = f.readline()
+            if not nextline:
+                break

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1743

Quoted 10 lines
scripts/qapi.py +10 -0
+            line = line + nextline
+        tmp = line.strip()
+        if tmp[:1] != '#':
+            continue
+        tmp = tmp[1:]
+        words = tmp.split()
+        if words[0] != "define":
+            continue
+        defs.append(words[1])
+    f.close()

This parses Yet Another Language. Worse, Yet Another Undocumented Language. Why not JSON?

Hmm, peeking ahead to PATCH 04... aha! This is for reading config-host.h and config-target.h. So, this actually doesn't parse YAUL, it parses C. Sloppily, of course.

I guess we could instead parse config-host.mak and config-target.mak sloppily. Not sure which idea is more disgusting :)

Could we punt evaluating conditionals to the C compiler? Instead of emitting TEXT when CONFIG_FOO is defined, emit

    #ifdef CONFIG_FOO
    TEXT
    #endif

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1752

Quoted 11 lines

def parse_command_line(extra_options="", extra_long_options=[]):

try:
opts, args = getopt.gnu_getopt(sys.argv[1:],

scripts/qapi.py +2 -2
-                                       "chp:o:" + extra_options,
+                                       "chp:o:f:" + extra_options,
                                        ["source", "header", "prefix=",
-                                        "output-dir="] + extra_long_options)
+                                        "output-dir=", "--defile="] +

https://docs.python.org/3/library/getopt.html on the third argument:
"The leading '--' characters should not be included in the option name."

Quoted 12 lines
scripts/qapi.py +3 -0
+                                       extra_long_options)
     except getopt.GetoptError as err:
         print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
         sys.exit(1)
@@ -1742,6 +1777,8 @@ def parse_command_line(extra_options="", extra_long_options=[]):
             do_c = True
         elif o in ("-h", "--header"):
             do_h = True
+        elif o in ("-f", "--defile"):
+            defile(a)
         else:
             extra_opts.append(oa)
#4 lore raw

Re: [Qemu-devel] [PATCH v5 02/20] qapi.py: add a simple #ifdef conditional

Hi

Quoted 51 lines · Markus Armbruster
Quoted 9 lines · Marc-André Lureau

Learn to parse #define files provided with -f option, and skip undefined #ifdef blocks in the schema.

This is a very simple pre-processing, without stacking support or evaluation (it could be implemented if needed).

---
 scripts/qapi.py | 43 ++++++++++++++++++++++++++++++++++++++++---

Missing: update of docs/qapi-code-gen.txt.

Quoted 37 lines
 1 file changed, 40 insertions(+), 3 deletions(-)
scripts/qapi.py +12 -1
index 21bc32f..d0b8a66 100644
@@ -76,6 +76,7 @@ struct_types = []
 union_types = []
 events = []
 all_names = {}
+defs = []
 
 #
 # Parsing the schema into expressions
@@ -177,6 +178,7 @@ class QAPISchemaParser(object):
                 self.exprs.append(expr_elem)
 
     def accept(self):
+        ok = True
         while True:
             self.tok = self.src[self.cursor]
             self.pos = self.cursor
@@ -184,7 +186,19 @@ class QAPISchemaParser(object):
             self.val = None
 
             if self.tok == '#':
-                self.cursor = self.src.find('\n', self.cursor)
+                end = self.src.find('\n', self.cursor)
+                line = self.src[self.cursor:end+1]
+                self.cursor = end
+                sline = line.split()
+                if len(defs) and len(sline) >= 1 \
+                   and sline[0] in ['ifdef', 'endif']:
+                    if sline[0] == 'ifdef':
+                        ok = sline[1] in defs
+                    elif sline[0] == 'endif':
+                        ok = True
Quoted 9 lines

scripts/qapi.py class QAPISchemaParser(object): · line 204

Quoted 6 lines
scripts/qapi.py +3 -0
+                    continue
+            elif not ok:
+                continue
             elif self.tok in "{}:,[]":
                 return
             elif self.tok == "'":

Oww, you're abusing comments! That's horrible :)

Can we make this real syntax, like everything else, including 'include'?

Quoted 2 lines

We already abuse json, which doesn't support comments either. :) Even without comments, our syntax is wrong and confuse most editors/validators.

Quoted 29 lines

Unfortunately, the natural

{ 'ifdef': 'CONFIG_FOO'
'then': ... # ignored unless CONFIG_FOO
'else': ... # ignored if CONFIG_FOO (optional)
}

is awkward, because the ... have to be a single JSON value, but a QAPI schema isn't a single JSON value, it's a *sequence* of JSON values. A top-level stanza

    JSON-value1 JSON-value2 ...

would become

    [ JSON-value1, JSON-value2, ... ]

within a conditional. Blech.

Could sacrifice the nesting and do

    { 'ifdef': 'CONFIG_FOO' }
    ...
    { 'endif' }

Widens the gap between syntax and semantics. Editors can no longer easily jump over the conditional (e.g. Emacs forward-sexp). Nested conditionals becomes as confusing as in C. Not exactly elegant, either.

Quoted 6 lines

Yet another option is to add 'ifdef' keys to the definitions themselves, i.e.

{ 'command': 'query-gic-capabilities', 'returns': ['GICCapability'],
'ifdef': 'TARGET_ARM' }

That's the worst of all options imho, as it makes it hard to filter out unions/enums, ex:

@ -3446,8 +3466,10 @@
'testdev': 'ChardevCommon', 'stdio' : 'ChardevStdio', 'console': 'ChardevCommon',
+#ifdef CONFIG_SPICE
'spicevmc' : 'ChardevSpiceChannel', 'spiceport' : 'ChardevSpicePort',
+#endif

                                        'vc'     : 'ChardevVC',
                                        'ringbuf': 'ChardevRingbuf',

I think #ifdef is the most straightforward/easy thing to do. My experience with doc generations tells me that is really not an issue to reserve the #\w* lines for pre-processing.

And it's a natural fit with the rest of qemu #if conditionals.

Quoted 50 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1724

Quoted 5 lines
scripts/qapi.py +1 -0
@@ -1707,15 +1721,36 @@ def gen_params(arg_type, boxed, extra):
 #
 # Common command line parsing
 #
+def defile(filename):

From The Collaborative International Dictionary of English v.0.48 [gcide]:

Defile \De*file"\ (d[-e]*f[imac]l"), v. t. [OE. defoulen,
-foilen, to tread down, OF. defouler; de- + fouler to trample (see Full, v. t.), and OE. defoulen to foul (influenced in form by the older verb defoilen). See File to defile, Foul, Defoul.]
1. To make foul or impure; to make filthy; to dirty; to befoul; to pollute.
[1913 Webster]

They that touch pitch will be defiled. --Shak.
[1913 Webster]

   2. To soil or sully; to tarnish, as reputation; to taint.
      [1913 Webster]

            He is . . . among the greatest prelates of this age,
            however his character may be defiled by . . . dirty
            hands.                                --Swift.
      [1913 Webster]

   3. To injure in purity of character; to corrupt.
      [1913 Webster]

            Defile not yourselves with the idols of Egypt.
                                                  --Ezek. xx. 7.
      [1913 Webster]

   4. To corrupt the chastity of; to debauch; to violate; to
      rape.
      [1913 Webster]

            The husband murder'd and the wife defiled. --Prior.
      [1913 Webster]

   5. To make ceremonially unclean; to pollute.
      [1913 Webster]

            That which dieth of itself, or is torn with beasts,
            he shall not eat to defile therewith. --Lev. xxii.
                                                  8.
      [1913 Webster]
Quoted 2 lines

Fitting in a way; you're defiling the poor, innocent comment syntax ;)

ok

Quoted 24 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1726

Quoted 3 lines
scripts/qapi.py +2 -0
+    f = open(filename, 'r')
+    while 1:

while True:

Quoted 7 lines
scripts/qapi.py +7 -0
+        line = f.readline()
+        if not line:
+            break
+        while line[-2:] == '\\\n':
+            nextline = f.readline()
+            if not nextline:
+                break

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1743

Quoted 10 lines
scripts/qapi.py +10 -0
+            line = line + nextline
+        tmp = line.strip()
+        if tmp[:1] != '#':
+            continue
+        tmp = tmp[1:]
+        words = tmp.split()
+        if words[0] != "define":
+            continue
+        defs.append(words[1])
+    f.close()
Quoted 8 lines

This parses Yet Another Language. Worse, Yet Another Undocumented Language. Why not JSON?

Hmm, peeking ahead to PATCH 04... aha! This is for reading config-host.h and config-target.h. So, this actually doesn't parse YAUL, it parses C. Sloppily, of course.

Yes

Quoted 4 lines

I guess we could instead parse config-host.mak and config-target.mak sloppily. Not sure which idea is more disgusting :)

Quoted 8 lines

Could we punt evaluating conditionals to the C compiler? Instead of emitting TEXT when CONFIG_FOO is defined, emit

    #ifdef CONFIG_FOO
    TEXT
    #endif

I don't follow you

Quoted 10 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra):

Quoted 10 lines
scripts/qapi.py +1 -2
 def parse_command_line(extra_options="", extra_long_options=[]):
 
     try:
         opts, args = getopt.gnu_getopt(sys.argv[1:],
-                                       "chp:o:" + extra_options,
+                                       "chp:o:f:" + extra_options,
                                        ["source", "header", "prefix=",
-                                        "output-dir="] +
Quoted 6 lines

extra_long_options)

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1752

Quoted 1 line
scripts/qapi.py +1 -0
+                                        "output-dir=", "--defile="] +

https://docs.python.org/3/library/getopt.html on the third argument:
"The leading '--' characters should not be included in the option name."

ok

Quoted 15 lines

scripts/qapi.py def parse_command_line(extra_options="",

Quoted 6 lines
scripts/qapi.py +1 -0
+                                       extra_long_options)
     except getopt.GetoptError as err:
         print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
         sys.exit(1)
@@ -1742,6 +1777,8 @@ def parse_command_line(extra_options="",

extra_long_options=[]):

scripts/qapi.py def parse_command_line(extra_options="", extra_long_options=[]): · line 1783

Quoted 7 lines
scripts/qapi.py +2 -0
             do_c = True
         elif o in ("-h", "--header"):
             do_h = True
+        elif o in ("-f", "--defile"):
+            defile(a)
         else:
             extra_opts.append(oa)
Quoted 1 line

--

Marc-André Lureau

#5 lore raw

Re: [Qemu-devel] [PATCH v5 02/20] qapi.py: add a simple #ifdef conditional

QAPI language design issues, copying Eric.

Quoted 64 lines · Marc-André Lureau

Hi

Quoted 60 lines · Markus Armbruster
Quoted 9 lines · Marc-André Lureau

Learn to parse #define files provided with -f option, and skip undefined #ifdef blocks in the schema.

This is a very simple pre-processing, without stacking support or evaluation (it could be implemented if needed).

---
 scripts/qapi.py | 43 ++++++++++++++++++++++++++++++++++++++++---

Missing: update of docs/qapi-code-gen.txt.

Quoted 33 lines
 1 file changed, 40 insertions(+), 3 deletions(-)
scripts/qapi.py +8 -1
index 21bc32f..d0b8a66 100644
@@ -76,6 +76,7 @@ struct_types = []
 union_types = []
 events = []
 all_names = {}
+defs = []
 
 #
 # Parsing the schema into expressions
@@ -177,6 +178,7 @@ class QAPISchemaParser(object):
                 self.exprs.append(expr_elem)
 
     def accept(self):
+        ok = True
         while True:
             self.tok = self.src[self.cursor]
             self.pos = self.cursor
@@ -184,7 +186,19 @@ class QAPISchemaParser(object):
             self.val = None
 
             if self.tok == '#':
-                self.cursor = self.src.find('\n', self.cursor)
+                end = self.src.find('\n', self.cursor)
+                line = self.src[self.cursor:end+1]
+                self.cursor = end
+                sline = line.split()
+                if len(defs) and len(sline) >= 1 \
+                   and sline[0] in ['ifdef', 'endif']:

scripts/qapi.py class QAPISchemaParser(object): · line 204

Quoted 10 lines
scripts/qapi.py +7 -0
+                    if sline[0] == 'ifdef':
+                        ok = sline[1] in defs
+                    elif sline[0] == 'endif':
+                        ok = True
+                    continue
+            elif not ok:
+                continue
             elif self.tok in "{}:,[]":
                 return
             elif self.tok == "'":

Oww, you're abusing comments! That's horrible :)

Quoted 5 lines
Quoted 3 lines

Can we make this real syntax, like everything else, including 'include'?

We already abuse json, which doesn't support comments either. :) Even without comments, our syntax is wrong and confuse most editors/validators.

True. Python mode works okay for me, though.

Perhaps we've outgrown the JSON syntax. Or perhaps we've just messed up by taking too many liberties with it, with too little thought. Not exactly an excuse for taking *more* liberties :)

Quoted 43 lines
Quoted 29 lines

Unfortunately, the natural

{ 'ifdef': 'CONFIG_FOO'
'then': ... # ignored unless CONFIG_FOO
'else': ... # ignored if CONFIG_FOO (optional)
}

is awkward, because the ... have to be a single JSON value, but a QAPI schema isn't a single JSON value, it's a *sequence* of JSON values. A top-level stanza

    JSON-value1 JSON-value2 ...

would become

    [ JSON-value1, JSON-value2, ... ]

within a conditional. Blech.

Could sacrifice the nesting and do

    { 'ifdef': 'CONFIG_FOO' }
    ...
    { 'endif' }

Widens the gap between syntax and semantics. Editors can no longer easily jump over the conditional (e.g. Emacs forward-sexp). Nested conditionals becomes as confusing as in C. Not exactly elegant, either.

Quoted 6 lines

Yet another option is to add 'ifdef' keys to the definitions themselves, i.e.

{ 'command': 'query-gic-capabilities', 'returns': ['GICCapability'],
'ifdef': 'TARGET_ARM' }

That's the worst of all options imho, as it makes it hard to filter out unions/enums, ex:

@ -3446,8 +3466,10 @@
'testdev': 'ChardevCommon', 'stdio' : 'ChardevStdio', 'console': 'ChardevCommon',

Review

Quoted 6 lines
(quoted diff) +2 -0
+#ifdef CONFIG_SPICE
                                        'spicevmc' : 'ChardevSpiceChannel',
                                        'spiceport' : 'ChardevSpicePort',
+#endif
                                        'vc'     : 'ChardevVC',
                                        'ringbuf': 'ChardevRingbuf',

Point taken.

Fixable the same way as always when a definition needs to grow additional properties, but the syntax only provides a single value: make that single value an object, and the old non-object value syntactic sugar for the equivalent object value. We've previously discussed this technique in the context of giving command arguments default values. I'm not saying this is what we should do here, only pointing out it's possible.

Quoted 3 lines

I think #ifdef is the most straightforward/easy thing to do. My experience with doc generations tells me that is really not an issue to reserve the #\w* lines for pre-processing.

Two justifications for doc generators recognizing magic comments: 1. If you create a machine processing comments (e.g. formatting them nicely for a medium richer than ASCII text, you fundamentally define a comment language, embedded in a host language's comments, and 2. what else can you do when you can't change the host language?

Neither applies to adding conditional compilation directives to the QAPI schema language. Letting a language grow into its comments is, to be frank, disgusting.

Besides, if we truly want the C preprocessor, we should use the C preprocessor. Not implement a half-assed clone of the half-assed hack of a macro processor the C preprocessor is.

Quoted 1 line

And it's a natural fit with the rest of qemu #if conditionals.

It's an awfully unnatural fit with the QAPI schema comment syntax.

##
# @Frobs
#
# Collection of frobs that need to be frobnicated, except when

# ifdef CONFIG_NOFROB
{ 'struct': 'Frobs'
  ...
}

I stand by 'horrible'.

Quoted 50 lines
Quoted 50 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1724

Quoted 5 lines
scripts/qapi.py +1 -0
@@ -1707,15 +1721,36 @@ def gen_params(arg_type, boxed, extra):
 #
 # Common command line parsing
 #
+def defile(filename):

From The Collaborative International Dictionary of English v.0.48 [gcide]:

Defile \De*file"\ (d[-e]*f[imac]l"), v. t. [OE. defoulen,
-foilen, to tread down, OF. defouler; de- + fouler to trample (see Full, v. t.), and OE. defoulen to foul (influenced in form by the older verb defoilen). See File to defile, Foul, Defoul.]
1. To make foul or impure; to make filthy; to dirty; to befoul; to pollute.
[1913 Webster]

They that touch pitch will be defiled. --Shak.
[1913 Webster]

   2. To soil or sully; to tarnish, as reputation; to taint.
      [1913 Webster]

            He is . . . among the greatest prelates of this age,
            however his character may be defiled by . . . dirty
            hands.                                --Swift.
      [1913 Webster]

   3. To injure in purity of character; to corrupt.
      [1913 Webster]

            Defile not yourselves with the idols of Egypt.
                                                  --Ezek. xx. 7.
      [1913 Webster]

   4. To corrupt the chastity of; to debauch; to violate; to
      rape.
      [1913 Webster]

            The husband murder'd and the wife defiled. --Prior.
      [1913 Webster]

   5. To make ceremonially unclean; to pollute.
      [1913 Webster]

            That which dieth of itself, or is torn with beasts,
            he shall not eat to defile therewith. --Lev. xxii.
                                                  8.
      [1913 Webster]
Quoted 4 lines
Quoted 2 lines

Fitting in a way; you're defiling the poor, innocent comment syntax ;)

ok

Seriously: can we give this function a better name?

Quoted 43 lines
Quoted 24 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1726

Quoted 3 lines
scripts/qapi.py +2 -0
+    f = open(filename, 'r')
+    while 1:

while True:

Quoted 7 lines
scripts/qapi.py +7 -0
+        line = f.readline()
+        if not line:
+            break
+        while line[-2:] == '\\\n':
+            nextline = f.readline()
+            if not nextline:
+                break

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1743

Quoted 10 lines
scripts/qapi.py +10 -0
+            line = line + nextline
+        tmp = line.strip()
+        if tmp[:1] != '#':
+            continue
+        tmp = tmp[1:]
+        words = tmp.split()
+        if words[0] != "define":
+            continue
+        defs.append(words[1])
+    f.close()
Quoted 8 lines

This parses Yet Another Language. Worse, Yet Another Undocumented Language. Why not JSON?

Hmm, peeking ahead to PATCH 04... aha! This is for reading config-host.h and config-target.h. So, this actually doesn't parse YAUL, it parses C. Sloppily, of course.

Yes

Quoted 7 lines

I guess we could instead parse config-host.mak and config-target.mak sloppily. Not sure which idea is more disgusting :)

Could we punt evaluating conditionals to the C compiler? Instead of emitting TEXT when CONFIG_FOO is defined, emit

Quoted 6 lines
Quoted 5 lines
    #ifdef CONFIG_FOO
    TEXT
    #endif

I don't follow you

Let me try to explain with an example. Say we make query-gic-capabilities conditional on TARGET_ARM in the schema. In your syntax:

    #ifdef TARGET_ARM
    { 'command': 'query-gic-capabilities', 'returns': ['GICCapability'] }
    #endif

Now consider qmp-commands.h. If we evaluate conditionals at QAPI generation time, we generate it per target. For targets with TARGET_ARM defined, it contains

    GICCapabilityList *qmp_query_gic_capabilities(Error **errp);
    void qmp_marshal_query_gic_capabilities(QDict *args, QObject **ret, Error **errp);

For the others, it doesn't contain this text.

If we evaluate conditionals at C compile time, we generate qmp-commands.h *once*, and it has

    #ifdef TARGET_ARM
    GICCapabilityList *qmp_query_gic_capabilities(Error **errp);
    void qmp_marshal_query_gic_capabilities(QDict *args, QObject **ret, Error **errp);
    #endif

It needs to be compiled per target, of course.

The QAPI generator doesn't interpret the conditional text in any way, it just passes it through to the C compiler.

Makes supporting complex conditions easy (we discussed this before, I think). A schema snippet

    #if defined(TARGET_I386) && !defined(TARGET_X86_64)
    ...
    #endif

could generate

    #if defined(TARGET_I386) && !defined(TARGET_X86_64)
    whatever is generated for ...
    #endif

To do this at QAPI generation time, you need to build an expression evaluator into qapi.py.

Also saves us the trouble of reading config-*.h or config-*.mak.

Quoted 34 lines
Quoted 8 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra):

Quoted 8 lines
scripts/qapi.py +1 -2
 def parse_command_line(extra_options="", extra_long_options=[]):
 
     try:
         opts, args = getopt.gnu_getopt(sys.argv[1:],
-                                       "chp:o:" + extra_options,
+                                       "chp:o:f:" + extra_options,
                                        ["source", "header", "prefix=",
-                                        "output-dir="] +
Quoted 6 lines

extra_long_options)

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1752

Quoted 1 line
scripts/qapi.py +1 -0
+                                        "output-dir=", "--defile="] +

https://docs.python.org/3/library/getopt.html on the third argument:
"The leading '--' characters should not be included in the option name."

ok

Quoted 15 lines

scripts/qapi.py def parse_command_line(extra_options="", extra_long_options=[]): · line 1783

Quoted 13 lines
scripts/qapi.py +3 -0
+                                       extra_long_options)
     except getopt.GetoptError as err:
         print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
         sys.exit(1)
@@ -1742,6 +1777,8 @@ def parse_command_line(extra_options="", extra_long_options=[]):
             do_c = True
         elif o in ("-h", "--header"):
             do_h = True
+        elif o in ("-f", "--defile"):
+            defile(a)
         else:
             extra_opts.append(oa)

--

Marc-André Lureau

#6 lore raw

Re: [Qemu-devel] [PATCH v5 02/20] qapi.py: add a simple #ifdef conditional

Hi

Quoted 74 lines · Markus Armbruster

QAPI language design issues, copying Eric.

Quoted 3 lines · Marc-André Lureau

Hi

On Tue, Sep 6, 2016 at 5:00 PM Markus Armbruster <[email protected]>

Quoted 61 lines · wrote:
Quoted 61 lines
Quoted 9 lines · Marc-André Lureau

Learn to parse #define files provided with -f option, and skip undefined #ifdef blocks in the schema.

This is a very simple pre-processing, without stacking support or evaluation (it could be implemented if needed).

---
 scripts/qapi.py | 43 ++++++++++++++++++++++++++++++++++++++++---

Missing: update of docs/qapi-code-gen.txt.

Quoted 33 lines
 1 file changed, 40 insertions(+), 3 deletions(-)
scripts/qapi.py +8 -1
index 21bc32f..d0b8a66 100644
@@ -76,6 +76,7 @@ struct_types = []
 union_types = []
 events = []
 all_names = {}
+defs = []
 
 #
 # Parsing the schema into expressions
@@ -177,6 +178,7 @@ class QAPISchemaParser(object):
                 self.exprs.append(expr_elem)
 
     def accept(self):
+        ok = True
         while True:
             self.tok = self.src[self.cursor]
             self.pos = self.cursor
@@ -184,7 +186,19 @@ class QAPISchemaParser(object):
             self.val = None
 
             if self.tok == '#':
-                self.cursor = self.src.find('\n', self.cursor)
+                end = self.src.find('\n', self.cursor)
+                line = self.src[self.cursor:end+1]
+                self.cursor = end
+                sline = line.split()
+                if len(defs) and len(sline) >= 1 \
+                   and sline[0] in ['ifdef', 'endif']:

scripts/qapi.py class QAPISchemaParser(object): · line 204

Quoted 10 lines
scripts/qapi.py +7 -0
+                    if sline[0] == 'ifdef':
+                        ok = sline[1] in defs
+                    elif sline[0] == 'endif':
+                        ok = True
+                    continue
+            elif not ok:
+                continue
             elif self.tok in "{}:,[]":
                 return
             elif self.tok == "'":

Oww, you're abusing comments! That's horrible :)

Quoted 5 lines
Quoted 3 lines

Can we make this real syntax, like everything else, including 'include'?

We already abuse json, which doesn't support comments either. :) Even without comments, our syntax is wrong and confuse most

Quoted 8 lines

editors/validators.

True. Python mode works okay for me, though.

Perhaps we've outgrown the JSON syntax. Or perhaps we've just messed up by taking too many liberties with it, with too little thought. Not exactly an excuse for taking *more* liberties :)

It depends, json is very limited. Doing everything is json is not convenient and not necessary. Why not having preprocessor?

Quoted 53 lines
Quoted 39 lines
Quoted 29 lines

Unfortunately, the natural

{ 'ifdef': 'CONFIG_FOO'
'then': ... # ignored unless CONFIG_FOO
'else': ... # ignored if CONFIG_FOO (optional)
}

is awkward, because the ... have to be a single JSON value, but a QAPI schema isn't a single JSON value, it's a *sequence* of JSON values. A top-level stanza

    JSON-value1 JSON-value2 ...

would become

    [ JSON-value1, JSON-value2, ... ]

within a conditional. Blech.

Could sacrifice the nesting and do

    { 'ifdef': 'CONFIG_FOO' }
    ...
    { 'endif' }

Widens the gap between syntax and semantics. Editors can no longer easily jump over the conditional (e.g. Emacs forward-sexp). Nested conditionals becomes as confusing as in C. Not exactly elegant, either.

Quoted 6 lines

Yet another option is to add 'ifdef' keys to the definitions themselves, i.e.

{ 'command': 'query-gic-capabilities', 'returns': ['GICCapability'],
'ifdef': 'TARGET_ARM' }

That's the worst of all options imho, as it makes it hard to filter out unions/enums, ex:

Quoted 6 lines

@ -3446,8 +3466,10 @@
'testdev': 'ChardevCommon', 'stdio' : 'ChardevStdio', 'console': 'ChardevCommon',
+#ifdef CONFIG_SPICE
'spicevmc' :

'ChardevSpiceChannel',

Quoted 4 lines

'spiceport' : 'ChardevSpicePort',
+#endif

                                        'vc'     : 'ChardevVC',
                                        'ringbuf': 'ChardevRingbuf',

Point taken.

Quoted 8 lines

Fixable the same way as always when a definition needs to grow additional properties, but the syntax only provides a single value: make that single value an object, and the old non-object value syntactic sugar for the equivalent object value. We've previously discussed this technique in the context of giving command arguments default values. I'm not saying this is what we should do here, only pointing out it's possible.

Ok, but let's find something, if possible simple and convenient, no?

Quoted 12 lines
Quoted 2 lines

I think #ifdef is the most straightforward/easy thing to do. My

experience

Quoted 2 lines

with doc generations tells me that is really not an issue to reserve the #\w* lines for pre-processing.

Two justifications for doc generators recognizing magic comments: 1. If you create a machine processing comments (e.g. formatting them nicely for a medium richer than ASCII text, you fundamentally define a comment language, embedded in a host language's comments, and 2. what else can you do when you can't change the host language?

Quoted 8 lines

Neither applies to adding conditional compilation directives to the QAPI schema language. Letting a language grow into its comments is, to be frank, disgusting.

Besides, if we truly want the C preprocessor, we should use the C preprocessor. Not implement a half-assed clone of the half-assed hack of a macro processor the C preprocessor is.

That's possible, although not so easy. First we have to convert all comments syntax. And then we have to generate files and change the build sys etc. Doable, but not so great imho. Right now we just need simple #ifdef conditions that can be easily handled when parsing, far from a full C preprocessor.

Quoted 9 lines
Quoted 1 line

And it's a natural fit with the rest of qemu #if conditionals.

It's an awfully unnatural fit with the QAPI schema comment syntax.

##
# @Frobs
#
# Collection of frobs that need to be frobnicated, except when

Quoted 7 lines
# ifdef CONFIG_NOFROB
{ 'struct': 'Frobs'
  ...
}

I stand by 'horrible'.

Ok. let's switch the comment syntax to a regular js/c style then?

Quoted 52 lines
Quoted 8 lines
Quoted 8 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1724

Quoted 6 lines
scripts/qapi.py +1 -0
@@ -1707,15 +1721,36 @@ def gen_params(arg_type, boxed, extra):
 #
 # Common command line parsing
 #
+def defile(filename):

From The Collaborative International Dictionary of English v.0.48

[gcide]:

Quoted 43 lines
Quoted 43 lines

Defile \De*file"\ (d[-e]*f[imac]l"), v. t. [OE. defoulen,
-foilen, to tread down, OF. defouler; de- + fouler to trample (see Full, v. t.), and OE. defoulen to foul (influenced in form by the older verb defoilen). See File to defile, Foul, Defoul.]
1. To make foul or impure; to make filthy; to dirty; to befoul; to pollute.
[1913 Webster]

They that touch pitch will be defiled. --Shak.
[1913 Webster]

   2. To soil or sully; to tarnish, as reputation; to taint.
      [1913 Webster]

            He is . . . among the greatest prelates of this age,
            however his character may be defiled by . . . dirty
            hands.                                --Swift.
      [1913 Webster]

   3. To injure in purity of character; to corrupt.
      [1913 Webster]

            Defile not yourselves with the idols of Egypt.
                                                  --Ezek. xx. 7.
      [1913 Webster]

   4. To corrupt the chastity of; to debauch; to violate; to
      rape.
      [1913 Webster]

            The husband murder'd and the wife defiled. --Prior.
      [1913 Webster]

   5. To make ceremonially unclean; to pollute.
      [1913 Webster]

            That which dieth of itself, or is torn with beasts,
            he shall not eat to defile therewith. --Lev. xxii.
                                                  8.
      [1913 Webster]
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

Fitting in a way; you're defiling the poor, innocent comment syntax ;)

ok

Seriously: can we give this function a better name?

yes load_define_file?

Quoted 72 lines
Quoted 44 lines
Quoted 25 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1726

Quoted 4 lines
scripts/qapi.py +2 -0
+    f = open(filename, 'r')
+    while 1:

while True:

Quoted 7 lines
scripts/qapi.py +7 -0
+        line = f.readline()
+        if not line:
+            break
+        while line[-2:] == '\\\n':
+            nextline = f.readline()
+            if not nextline:
+                break

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1743

Quoted 10 lines
scripts/qapi.py +10 -0
+            line = line + nextline
+        tmp = line.strip()
+        if tmp[:1] != '#':
+            continue
+        tmp = tmp[1:]
+        words = tmp.split()
+        if words[0] != "define":
+            continue
+        defs.append(words[1])
+    f.close()
Quoted 8 lines

This parses Yet Another Language. Worse, Yet Another Undocumented Language. Why not JSON?

Hmm, peeking ahead to PATCH 04... aha! This is for reading config-host.h and config-target.h. So, this actually doesn't parse YAUL, it parses C. Sloppily, of course.

Yes

Quoted 7 lines

I guess we could instead parse config-host.mak and config-target.mak sloppily. Not sure which idea is more disgusting :)

Could we punt evaluating conditionals to the C compiler? Instead of emitting TEXT when CONFIG_FOO is defined, emit

Quoted 6 lines
Quoted 5 lines
    #ifdef CONFIG_FOO
    TEXT
    #endif

I don't follow you

Let me try to explain with an example. Say we make query-gic-capabilities conditional on TARGET_ARM in the schema. In your syntax:

    #ifdef TARGET_ARM
    { 'command': 'query-gic-capabilities', 'returns': ['GICCapability'] }
    #endif

Now consider qmp-commands.h. If we evaluate conditionals at QAPI generation time, we generate it per target. For targets with TARGET_ARM defined, it contains

GICCapabilityList *qmp_query_gic_capabilities(Error **errp); void qmp_marshal_query_gic_capabilities(QDict *args, QObject **ret,
Error **errp);

For the others, it doesn't contain this text.

If we evaluate conditionals at C compile time, we generate qmp-commands.h *once*, and it has

Quoted 8 lines
    #ifdef TARGET_ARM
    GICCapabilityList *qmp_query_gic_capabilities(Error **errp);
    void qmp_marshal_query_gic_capabilities(QDict *args, QObject **ret,
Error **errp);
    #endif

It needs to be compiled per target, of course.

Doable for commands, but not easily doable for introspect.c. I tried to implement that at first, it was really complicated. I think we should also consider simplicity here.

Quoted 11 lines

The QAPI generator doesn't interpret the conditional text in any way, it just passes it through to the C compiler.

Makes supporting complex conditions easy (we discussed this before, I think). A schema snippet

    #if defined(TARGET_I386) && !defined(TARGET_X86_64)
    ...
    #endif
Quoted 9 lines

could generate

    #if defined(TARGET_I386) && !defined(TARGET_X86_64)
    whatever is generated for ...
    #endif

To do this at QAPI generation time, you need to build an expression evaluator into qapi.py.

That's relatively easy, I've done that a couple of time, I can do it here too. Only it was not needed so far.

Quoted 4 lines

Also saves us the trouble of reading config-*.h or config-*.mak.

If needed we could generate a simpler file, like a python config file, or

generating command line arguments, etc.. with just the values we need for qapi generation. But reading the config-*.h is quite straightforward.

Quoted 37 lines
Quoted 7 lines
Quoted 7 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra):

Quoted 7 lines
scripts/qapi.py +1 -1
 def parse_command_line(extra_options="", extra_long_options=[]):
 
     try:
         opts, args = getopt.gnu_getopt(sys.argv[1:],
-                                       "chp:o:" + extra_options,
+                                       "chp:o:f:" + extra_options,
                                        ["source", "header",

"prefix=",

Quoted 12 lines
Quoted 7 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1716

Quoted 1 line
scripts/qapi.py +0 -1
-                                        "output-dir="] +

extra_long_options)

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1752

Quoted 1 line
scripts/qapi.py +1 -0
+                                        "output-dir=", "--defile="] +

https://docs.python.org/3/library/getopt.html on the third argument:
"The leading '--' characters should not be included in the option name."

ok

Quoted 1 line
Quoted 5 lines
Quoted 5 lines

scripts/qapi.py def parse_command_line(extra_options="",

Quoted 5 lines
scripts/qapi.py +1 -0
+                                       extra_long_options)
     except getopt.GetoptError as err:
         print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
         sys.exit(1)
@@ -1742,6 +1777,8 @@ def parse_command_line(extra_options="",

extra_long_options=[]):

Quoted 10 lines
Quoted 9 lines

scripts/qapi.py def parse_command_line(extra_options="", extra_long_options=[]): · line 1783

Quoted 7 lines
scripts/qapi.py +2 -0
             do_c = True
         elif o in ("-h", "--header"):
             do_h = True
+        elif o in ("-f", "--defile"):
+            defile(a)
         else:
             extra_opts.append(oa)

--

Marc-André Lureau

Signature · 1 line
Marc-André Lureau
#7 lore raw

Re: [Qemu-devel] [PATCH v5 02/20] qapi.py: add a simple #ifdef conditional

Quoted 82 lines · Marc-André Lureau

Hi

Quoted 78 lines · Markus Armbruster

QAPI language design issues, copying Eric.

Quoted 3 lines · Marc-André Lureau

Hi

On Tue, Sep 6, 2016 at 5:00 PM Markus Armbruster <[email protected]>

Quoted 61 lines · wrote:
Quoted 61 lines
Quoted 9 lines · Marc-André Lureau

Learn to parse #define files provided with -f option, and skip undefined #ifdef blocks in the schema.

This is a very simple pre-processing, without stacking support or evaluation (it could be implemented if needed).

---
 scripts/qapi.py | 43 ++++++++++++++++++++++++++++++++++++++++---

Missing: update of docs/qapi-code-gen.txt.

Quoted 33 lines
 1 file changed, 40 insertions(+), 3 deletions(-)
scripts/qapi.py +8 -1
index 21bc32f..d0b8a66 100644
@@ -76,6 +76,7 @@ struct_types = []
 union_types = []
 events = []
 all_names = {}
+defs = []
 
 #
 # Parsing the schema into expressions
@@ -177,6 +178,7 @@ class QAPISchemaParser(object):
                 self.exprs.append(expr_elem)
 
     def accept(self):
+        ok = True
         while True:
             self.tok = self.src[self.cursor]
             self.pos = self.cursor
@@ -184,7 +186,19 @@ class QAPISchemaParser(object):
             self.val = None
 
             if self.tok == '#':
-                self.cursor = self.src.find('\n', self.cursor)
+                end = self.src.find('\n', self.cursor)
+                line = self.src[self.cursor:end+1]
+                self.cursor = end
+                sline = line.split()
+                if len(defs) and len(sline) >= 1 \
+                   and sline[0] in ['ifdef', 'endif']:

scripts/qapi.py class QAPISchemaParser(object): · line 204

Quoted 10 lines
scripts/qapi.py +7 -0
+                    if sline[0] == 'ifdef':
+                        ok = sline[1] in defs
+                    elif sline[0] == 'endif':
+                        ok = True
+                    continue
+            elif not ok:
+                continue
             elif self.tok in "{}:,[]":
                 return
             elif self.tok == "'":

Oww, you're abusing comments! That's horrible :)

Quoted 5 lines
Quoted 3 lines

Can we make this real syntax, like everything else, including 'include'?

We already abuse json, which doesn't support comments either. :) Even without comments, our syntax is wrong and confuse most

editors/validators.

True. Python mode works okay for me, though.

Quoted 7 lines
Quoted 4 lines

Perhaps we've outgrown the JSON syntax. Or perhaps we've just messed up by taking too many liberties with it, with too little thought. Not exactly an excuse for taking *more* liberties :)

It depends, json is very limited. Doing everything is json is not convenient and not necessary. Why not having preprocessor?

In language design, a preprocessor transforming text is a cop out.

With a simple and regular syntax such as JSON, syntax tree transformations are at least as easy to grasp, and make more sense. Compare the C preprocessor (text-transforming water pistol, tacked on, way too complex for what it can do) to Lisp macros (syntax-transforming auto-cannon, compile-time language identical to run-time language) to C++ templates (syntax-transforming auto-cannon, completely separate compile-time language, fully understood by about three people, one has since died, one has forgotten everything, and one has gone crazy).

I'm not asking for Lisp macros here. Sometimes, the most practical solution is to cop out. I just want us to think before we cop out.

Quoted 62 lines
Quoted 53 lines
Quoted 39 lines
Quoted 29 lines

Unfortunately, the natural

{ 'ifdef': 'CONFIG_FOO'
'then': ... # ignored unless CONFIG_FOO
'else': ... # ignored if CONFIG_FOO (optional)
}

is awkward, because the ... have to be a single JSON value, but a QAPI schema isn't a single JSON value, it's a *sequence* of JSON values. A top-level stanza

    JSON-value1 JSON-value2 ...

would become

    [ JSON-value1, JSON-value2, ... ]

within a conditional. Blech.

Could sacrifice the nesting and do

    { 'ifdef': 'CONFIG_FOO' }
    ...
    { 'endif' }

Widens the gap between syntax and semantics. Editors can no longer easily jump over the conditional (e.g. Emacs forward-sexp). Nested conditionals becomes as confusing as in C. Not exactly elegant, either.

Quoted 6 lines

Yet another option is to add 'ifdef' keys to the definitions themselves, i.e.

{ 'command': 'query-gic-capabilities', 'returns': ['GICCapability'],
'ifdef': 'TARGET_ARM' }

That's the worst of all options imho, as it makes it hard to filter out unions/enums, ex:

Quoted 6 lines

@ -3446,8 +3466,10 @@
'testdev': 'ChardevCommon', 'stdio' : 'ChardevStdio', 'console': 'ChardevCommon',
+#ifdef CONFIG_SPICE
'spicevmc' :

'ChardevSpiceChannel',

Quoted 4 lines

'spiceport' : 'ChardevSpicePort',
+#endif

                                        'vc'     : 'ChardevVC',
                                        'ringbuf': 'ChardevRingbuf',

Point taken.

Quoted 8 lines

Fixable the same way as always when a definition needs to grow additional properties, but the syntax only provides a single value: make that single value an object, and the old non-object value syntactic sugar for the equivalent object value. We've previously discussed this technique in the context of giving command arguments default values. I'm not saying this is what we should do here, only pointing out it's possible.

Quoted 1 line

Ok, but let's find something, if possible simple and convenient, no?

I agree it needs to be simple, both the interface (QAPI language) and the implementation. However, I don't like "first past the post". I prefer to explore the design space a bit.

So let me explore the "add 'ifdef' keys to definitions" corner of the QAPI language design space.

Easily done for top-level definitions, because they're all JSON objects. Could even add it to the include directive if we wanted to.

Less easily done for enumeration, struct, union and alternate members. Note that command and event arguments specified inline are a special case of struct members.

The "can't specify additional stuff for struct members" problem isn't new. We hacked around it to specify "optional": encode it into the member name. Doesn't scale. We need to solve the problem to be able to specify default values, and we already decided how: have an JSON object instead of a mere JSON string, make the string syntax sugar for { 'type': STRING }. See commit 6b5abc7 and the discussion in qemu-devel leading up to it. For consistency, we'll do it for union and alternate members, too.

That leaves just enumeration members. The same technique applies.

If I remember correctly, we only need conditional commands right now, to avoid regressing query-commands. The more complicated member work could be done later.

Quoted 20 lines
Quoted 11 lines
Quoted 1 line

I think #ifdef is the most straightforward/easy thing to do. My

experience

Quoted 2 lines

with doc generations tells me that is really not an issue to reserve the #\w* lines for pre-processing.

Two justifications for doc generators recognizing magic comments: 1. If you create a machine processing comments (e.g. formatting them nicely for a medium richer than ASCII text, you fundamentally define a comment language, embedded in a host language's comments, and 2. what else can you do when you can't change the host language?

Quoted 8 lines

Neither applies to adding conditional compilation directives to the QAPI schema language. Letting a language grow into its comments is, to be frank, disgusting.

Besides, if we truly want the C preprocessor, we should use the C preprocessor. Not implement a half-assed clone of the half-assed hack of a macro processor the C preprocessor is.

Quoted 5 lines

That's possible, although not so easy. First we have to convert all comments syntax. And then we have to generate files and change the build sys etc. Doable, but not so great imho. Right now we just need simple #ifdef conditions that can be easily handled when parsing, far from a full C preprocessor.

Things always start that way. Trouble is they rarely stay that way.

Quoted 14 lines
Quoted 14 lines
Quoted 1 line

And it's a natural fit with the rest of qemu #if conditionals.

It's an awfully unnatural fit with the QAPI schema comment syntax.

##
# @Frobs
#
# Collection of frobs that need to be frobnicated, except when

# ifdef CONFIG_NOFROB
{ 'struct': 'Frobs'
  ...
}
Quoted 4 lines
Quoted 2 lines

I stand by 'horrible'.

Ok. let's switch the comment syntax to a regular js/c style then?

Switching to JavaScript comment syntax is an option. Painful loss of git-blame information, though.

Quoted 54 lines
Quoted 54 lines
Quoted 7 lines
Quoted 7 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1724

Quoted 5 lines
scripts/qapi.py +1 -0
@@ -1707,15 +1721,36 @@ def gen_params(arg_type, boxed, extra):
 #
 # Common command line parsing
 #
+def defile(filename):

From The Collaborative International Dictionary of English v.0.48

[gcide]:

Quoted 46 lines
Quoted 45 lines

Defile \De*file"\ (d[-e]*f[imac]l"), v. t. [OE. defoulen,
-foilen, to tread down, OF. defouler; de- + fouler to trample (see Full, v. t.), and OE. defoulen to foul (influenced in form by the older verb defoilen). See File to defile, Foul, Defoul.]
1. To make foul or impure; to make filthy; to dirty; to befoul; to pollute.
[1913 Webster]

They that touch pitch will be defiled. --Shak.
[1913 Webster]

   2. To soil or sully; to tarnish, as reputation; to taint.
      [1913 Webster]

            He is . . . among the greatest prelates of this age,
            however his character may be defiled by . . . dirty
            hands.                                --Swift.
      [1913 Webster]

   3. To injure in purity of character; to corrupt.
      [1913 Webster]

            Defile not yourselves with the idols of Egypt.
                                                  --Ezek. xx. 7.
      [1913 Webster]

   4. To corrupt the chastity of; to debauch; to violate; to
      rape.
      [1913 Webster]

            The husband murder'd and the wife defiled. --Prior.
      [1913 Webster]

   5. To make ceremonially unclean; to pollute.
      [1913 Webster]

            That which dieth of itself, or is torn with beasts,
            he shall not eat to defile therewith. --Lev. xxii.
                                                  8.
      [1913 Webster]

Fitting in a way; you're defiling the poor, innocent comment syntax ;)

Quoted 6 lines
Quoted 4 lines
Quoted 1 line

ok

Seriously: can we give this function a better name?

yes load_define_file?

read_config_h?

Quoted 76 lines
Quoted 76 lines
Quoted 42 lines
Quoted 23 lines

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1726

Quoted 2 lines
scripts/qapi.py +2 -0
+    f = open(filename, 'r')
+    while 1:

while True:

Quoted 7 lines
scripts/qapi.py +7 -0
+        line = f.readline()
+        if not line:
+            break
+        while line[-2:] == '\\\n':
+            nextline = f.readline()
+            if not nextline:
+                break

scripts/qapi.py def gen_params(arg_type, boxed, extra): · line 1743

Quoted 10 lines
scripts/qapi.py +10 -0
+            line = line + nextline
+        tmp = line.strip()
+        if tmp[:1] != '#':
+            continue
+        tmp = tmp[1:]
+        words = tmp.split()
+        if words[0] != "define":
+            continue
+        defs.append(words[1])
+    f.close()
Quoted 8 lines

This parses Yet Another Language. Worse, Yet Another Undocumented Language. Why not JSON?

Hmm, peeking ahead to PATCH 04... aha! This is for reading config-host.h and config-target.h. So, this actually doesn't parse YAUL, it parses C. Sloppily, of course.

Yes

Quoted 7 lines

I guess we could instead parse config-host.mak and config-target.mak sloppily. Not sure which idea is more disgusting :)

Could we punt evaluating conditionals to the C compiler? Instead of emitting TEXT when CONFIG_FOO is defined, emit

Quoted 6 lines
Quoted 5 lines
    #ifdef CONFIG_FOO
    TEXT
    #endif

I don't follow you

Let me try to explain with an example. Say we make query-gic-capabilities conditional on TARGET_ARM in the schema. In your syntax:

    #ifdef TARGET_ARM
    { 'command': 'query-gic-capabilities', 'returns': ['GICCapability'] }
    #endif

Now consider qmp-commands.h. If we evaluate conditionals at QAPI generation time, we generate it per target. For targets with TARGET_ARM defined, it contains

GICCapabilityList *qmp_query_gic_capabilities(Error **errp); void qmp_marshal_query_gic_capabilities(QDict *args, QObject **ret,
Error **errp);

For the others, it doesn't contain this text.

If we evaluate conditionals at C compile time, we generate qmp-commands.h *once*, and it has

    #ifdef TARGET_ARM
    GICCapabilityList *qmp_query_gic_capabilities(Error **errp);
    void qmp_marshal_query_gic_capabilities(QDict *args, QObject **ret,
Error **errp);
    #endif
Quoted 6 lines
Quoted 2 lines

It needs to be compiled per target, of course.

Doable for commands, but not easily doable for introspect.c. I tried to implement that at first, it was really complicated. I think we should also consider simplicity here.

Of course.

I'd like to have a look at qapi-introspect.py myself.

Quoted 16 lines
Quoted 16 lines

The QAPI generator doesn't interpret the conditional text in any way, it just passes it through to the C compiler.

Makes supporting complex conditions easy (we discussed this before, I think). A schema snippet

    #if defined(TARGET_I386) && !defined(TARGET_X86_64)
    ...
    #endif

could generate

    #if defined(TARGET_I386) && !defined(TARGET_X86_64)
    whatever is generated for ...
    #endif
Quoted 6 lines
Quoted 3 lines

To do this at QAPI generation time, you need to build an expression evaluator into qapi.py.

That's relatively easy, I've done that a couple of time, I can do it here too. Only it was not needed so far.

See "Trouble is they rarely stay that way" above.

Quoted 5 lines
Quoted 1 line

Also saves us the trouble of reading config-*.h or config-*.mak.

If needed we could generate a simpler file, like a python config file, or
generating command line arguments, etc.. with just the values we need for qapi generation.

Yes.

Quoted 1 line

But reading the config-*.h is quite straightforward.

Until somebody gets clever in configure, and things break.

We can ignore this detail for now.

[...]

#8 lore raw

Re: [Qemu-devel] [PATCH v5 02/20] qapi.py: add a simple #ifdef conditional

Quoted 14 lines · Markus Armbruster
Quoted 12 lines · Marc-André Lureau

Hi

Quoted 8 lines · Markus Armbruster

QAPI language design issues, copying Eric.

Quoted 3 lines · Marc-André Lureau

Hi

On Tue, Sep 6, 2016 at 5:00 PM Markus Armbruster <[email protected]>

wrote:

[...]

Quoted 58 lines
Quoted 33 lines
Quoted 24 lines
Quoted 10 lines
Quoted 6 lines

Yet another option is to add 'ifdef' keys to the definitions themselves, i.e.

{ 'command': 'query-gic-capabilities', 'returns': ['GICCapability'],
'ifdef': 'TARGET_ARM' }

That's the worst of all options imho, as it makes it hard to filter out unions/enums, ex:

Quoted 6 lines

@ -3446,8 +3466,10 @@
'testdev': 'ChardevCommon', 'stdio' : 'ChardevStdio', 'console': 'ChardevCommon',
+#ifdef CONFIG_SPICE
'spicevmc' :

'ChardevSpiceChannel',

Quoted 4 lines

'spiceport' : 'ChardevSpicePort',
+#endif

                                        'vc'     : 'ChardevVC',
                                        'ringbuf': 'ChardevRingbuf',

Point taken.

Quoted 8 lines

Fixable the same way as always when a definition needs to grow additional properties, but the syntax only provides a single value: make that single value an object, and the old non-object value syntactic sugar for the equivalent object value. We've previously discussed this technique in the context of giving command arguments default values. I'm not saying this is what we should do here, only pointing out it's possible.

Quoted 1 line

Ok, but let's find something, if possible simple and convenient, no?

I agree it needs to be simple, both the interface (QAPI language) and the implementation. However, I don't like "first past the post". I prefer to explore the design space a bit.

So let me explore the "add 'ifdef' keys to definitions" corner of the QAPI language design space.

Easily done for top-level definitions, because they're all JSON objects. Could even add it to the include directive if we wanted to.

Less easily done for enumeration, struct, union and alternate members. Note that command and event arguments specified inline are a special case of struct members.

The "can't specify additional stuff for struct members" problem isn't new. We hacked around it to specify "optional": encode it into the member name. Doesn't scale. We need to solve the problem to be able to specify default values, and we already decided how: have an JSON object instead of a mere JSON string, make the string syntax sugar for { 'type': STRING }. See commit 6b5abc7 and the discussion in qemu-devel leading up to it. For consistency, we'll do it for union and alternate members, too.

Quoted 5 lines

That leaves just enumeration members. The same technique applies.

If I remember correctly, we only need conditional commands right now, to avoid regressing query-commands. The more complicated member work could be done later.

To gauge whether this idea is practical, I implemented key 'if' for commands. It's just a sketch, and has a number of issues, which I marked FIXME.

I ported qmp-commands.hx's #if to qapi-schema.json. The TARGET_FOO are poisoned, so I commented them out. There's a CONFIG_SPICE left, which will do for testing.

I also turned key 'gen': false into 'if': false. Possibly a bad idea.

Anyway, diffstat isn't bad:

 docs/qapi-code-gen.txt                     | 14 ++++++-----
 qapi-schema.json                           | 15 ++++++++---
 qapi/introspect.json                       |  2 +-
 scripts/qapi-commands.py                   | 12 +++++++--
 scripts/qapi-introspect.py                 | 22 ++++++++++------
 scripts/qapi.py                            | 40 ++++++++++++++++++++++--------
 tests/qapi-schema/type-bypass-bad-gen.err  |  2 +-
 tests/qapi-schema/type-bypass-bad-gen.json |  4 +--
 8 files changed, 77 insertions(+), 34 deletions(-)
docs/qapi-code-gen.txt +8 -6
index de298dc..93e99d8 100644
@@ -423,7 +423,7 @@ part of a Client JSON Protocol command.  The 'data' member is optional
 and defaults to {} (an empty dictionary).  If present, it must be the
 string name of a complex type, or a dictionary that declares an
 anonymous type with the same semantics as a 'struct' expression, with
-one exception noted below when 'gen' is used.
+one exception noted below when 'if': false is used.
 
 The 'returns' member describes what will appear in the "return" member
 of a Client JSON Protocol reply on successful completion of a command.
@@ -431,8 +431,8 @@ The member is optional from the command declaration; if absent, the
 "return" member will be an empty dictionary.  If 'returns' is present,
 it must be the string name of a complex or built-in type, a
 one-element array containing the name of a complex or built-in type,
-with one exception noted below when 'gen' is used.  Although it is
-permitted to have the 'returns' member name a built-in type or an
+with one exception noted below when 'if':false is used.  Although it
+is permitted to have the 'returns' member name a built-in type or an
 array of built-in types, any command that does this cannot be extended
 to return additional information in the future; thus, new commands
 should strongly consider returning a dictionary-based type or an array
@@ -475,16 +475,18 @@ arguments for the user's function out of an input QDict, calls the
 user's function, and if it succeeded, builds an output QObject from
 its return value.
 
+FIXME document 'if'
+
 In rare cases, QAPI cannot express a type-safe representation of a
 corresponding Client JSON Protocol command.  You then have to suppress
-generation of a marshalling function by including a key 'gen' with
+generation of a marshalling function by including a key 'if' with
 boolean value false, and instead write your own function.  Please try
 to avoid adding new commands that rely on this, and instead use
 type-safe unions.  For an example of this usage:
 
  { 'command': 'netdev_add',
-   'data': {'type': 'str', 'id': 'str'},
-   'gen': false }
+   'if': false,
+   'data': {'type': 'str', 'id': 'str'} }
 
 Normally, the QAPI schema is used to describe synchronous exchanges,
 where a response is expected.  But in some cases, the action of a
qapi-schema.json +11 -4
index c4f3674..ad0559e 100644
@@ -1269,7 +1269,9 @@
 #
 # Since: 0.14.0
 ##
-{ 'command': 'query-spice', 'returns': 'SpiceInfo' }
+{ 'command': 'query-spice',
+  'if': 'defined(CONFIG_SPICE)',
+  'returns': 'SpiceInfo' }
 
 ##
 # @BalloonInfo:
@@ -2355,6 +2357,7 @@
 # Since: 2.5
 ##
 { 'command': 'dump-skeys',
+#  'if': 'defined(TARGET_S390X)',
   'data': { 'filename': 'str' } }
 
 ##
@@ -2380,8 +2383,8 @@
 #          If @type is not a valid network backend, DeviceNotFound
 ##
 { 'command': 'netdev_add',
-  'data': {'type': 'str', 'id': 'str'},
-  'gen': false }                # so we can get the additional arguments
+  'if': false,                  # so we can get the additional arguments
+  'data': {'type': 'str', 'id': 'str'} }
 
 ##
 # @netdev_del:
@@ -4455,6 +4458,7 @@
 # Since: 2.1
 ##
 { 'command': 'rtc-reset-reinjection' }
+#  'if': 'defined(TARGET_I386)'
 
 # Rocker ethernet network switch
 { 'include': 'qapi/rocker.json' }
@@ -4525,7 +4529,10 @@
 #
 # Since: 2.6
 ##
-{ 'command': 'query-gic-capabilities', 'returns': ['GICCapability'] }
+{ 'command': 'query-gic-capabilities',
+#  'if': 'defined(TARGET_ARM)',
+  'returns': ['GICCapability']
+}
 
 ##
 # CpuInstanceProperties
qapi/introspect.json +1 -1
index 3fd81fb..b8f421a 100644
@@ -46,7 +46,7 @@
 ##
 { 'command': 'query-qmp-schema',
   'returns': [ 'SchemaInfo' ],
-  'gen': false }                # just to simplify qmp_query_json()
+  'if': false }                 # just to simplify qmp_query_json()
 
 ##
 # @SchemaMetaType
scripts/qapi-commands.py +10 -2
index a06a2c4..f34e4cc 100644
@@ -215,9 +215,13 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._visited_ret_types = None
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
-        if not gen:
+                      genif, success_response, boxed):
+        if genif is False:
             return
+        pp_if = gen_pp_if(genif)
+        pp_endif = gen_pp_endif(genif)
+        self.decl += pp_if
+        self.defn += pp_if      # FIXME blank lines are off
         self.decl += gen_command_decl(name, arg_type, boxed, ret_type)
         if ret_type and ret_type not in self._visited_ret_types:
             self._visited_ret_types.add(ret_type)
@@ -226,7 +230,11 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
             self.decl += gen_marshal_decl(name)
         self.defn += gen_marshal(name, arg_type, boxed, ret_type)
         if not middle_mode:
+            self._regy += pp_if
             self._regy += gen_register_command(name, success_response)
+            self._regy += pp_endif
+        self.decl += pp_endif
+        self.defn += pp_endif
 
 
 middle_mode = False
scripts/qapi-introspect.py +14 -8
index 541644e..0d8cec7 100644
@@ -30,8 +30,6 @@ def to_json(obj, level=0):
         ret = '{' + ', '.join(elts) + '}'
     else:
         assert False                # not implemented
-    if level == 1:
-        ret = '\n' + ret
     return ret
 
 
@@ -69,8 +67,15 @@ class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):
 extern const char %(c_name)s[];
 ''',
                           c_name=c_name(name))
-        lines = to_json(jsons).split('\n')
-        c_string = '\n    '.join([to_c_string(line) for line in lines])
+        c_string = '"["'
+        for i in jsons:
+            js, genif = i
+            # FIXME blank lines are off
+            c_string += gen_pp_if(genif or True)
+            c_string += '\n    ' + to_c_string(to_json(js) + ', ')
+            c_string += gen_pp_endif(genif or True)
+        # FIXME trailing comma (JSON sucks)
+        c_string += '\n    "]"'
         self.defn = mcgen('''
 const char %(c_name)s[] = %(c_string)s;
 ''',
@@ -111,12 +116,12 @@ const char %(c_name)s[] = %(c_string)s;
             return '[' + self._use_type(typ.element_type) + ']'
         return self._name(typ.name)
 
-    def _gen_json(self, name, mtype, obj):
+    def _gen_json(self, name, mtype, obj, genif=True):
         if mtype not in ('command', 'event', 'builtin', 'array'):
             name = self._name(name)
         obj['name'] = name
         obj['meta-type'] = mtype
-        self._jsons.append(obj)
+        self._jsons.append((obj, genif))
 
     def _gen_member(self, member):
         ret = {'name': member.name, 'type': self._use_type(member.type)}
@@ -154,12 +159,13 @@ const char %(c_name)s[] = %(c_string)s;
                                     for m in variants.variants]})
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      genif, success_response, boxed):
         arg_type = arg_type or self._schema.the_empty_object_type
         ret_type = ret_type or self._schema.the_empty_object_type
         self._gen_json(name, 'command',
                        {'arg-type': self._use_type(arg_type),
-                        'ret-type': self._use_type(ret_type)})
+                        'ret-type': self._use_type(ret_type)},
+                       genif)
 
     def visit_event(self, name, info, arg_type, boxed):
         arg_type = arg_type or self._schema.the_empty_object_type
scripts/qapi.py +30 -10
index 21bc32f..6c0cf9f 100644
@@ -698,7 +698,13 @@ def check_keys(expr_elem, meta, required, optional=[]):
             raise QAPIExprError(info,
                                 "Unknown key '%s' in %s '%s'"
                                 % (key, meta, name))
-        if (key == 'gen' or key == 'success-response') and value is not False:
+        if (key == 'if'
+            and value is not False and not isinstance(value, str)):
+            # FIXME update error message
+            raise QAPIExprError(info,
+                                "'%s' of %s '%s' should only use false value"
+                                % (key, meta, name))
+        if (key == 'success-response') and value is not False:
             raise QAPIExprError(info,
                                 "'%s' of %s '%s' should only use false value"
                                 % (key, meta, name))
@@ -737,7 +743,7 @@ def check_exprs(exprs):
             add_struct(expr, info)
         elif 'command' in expr:
             check_keys(expr_elem, 'command', [],
-                       ['data', 'returns', 'gen', 'success-response', 'boxed'])
+                       ['data', 'returns', 'if', 'success-response', 'boxed'])
             add_name(expr['command'], info, 'command')
         elif 'event' in expr:
             check_keys(expr_elem, 'event', [], ['data', 'boxed'])
@@ -838,7 +844,7 @@ class QAPISchemaVisitor(object):
         pass
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      genif, success_response, boxed):
         pass
 
     def visit_event(self, name, info, arg_type, boxed):
@@ -1180,8 +1186,8 @@ class QAPISchemaAlternateType(QAPISchemaType):
 
 
 class QAPISchemaCommand(QAPISchemaEntity):
-    def __init__(self, name, info, arg_type, ret_type, gen, success_response,
-                 boxed):
+    def __init__(self, name, info, arg_type, ret_type,
+                 genif, success_response, boxed):
         QAPISchemaEntity.__init__(self, name, info)
         assert not arg_type or isinstance(arg_type, str)
         assert not ret_type or isinstance(ret_type, str)
@@ -1189,7 +1195,7 @@ class QAPISchemaCommand(QAPISchemaEntity):
         self.arg_type = None
         self._ret_type_name = ret_type
         self.ret_type = None
-        self.gen = gen
+        self.genif = genif
         self.success_response = success_response
         self.boxed = boxed
 
@@ -1216,7 +1222,7 @@ class QAPISchemaCommand(QAPISchemaEntity):
     def visit(self, visitor):
         visitor.visit_command(self.name, self.info,
                               self.arg_type, self.ret_type,
-                              self.gen, self.success_response, self.boxed)
+                              self.genif, self.success_response, self.boxed)
 
 
 class QAPISchemaEvent(QAPISchemaEntity):
@@ -1419,17 +1425,20 @@ class QAPISchema(object):
         name = expr['command']
         data = expr.get('data')
         rets = expr.get('returns')
-        gen = expr.get('gen', True)
+        genif = expr.get('if', True)
         success_response = expr.get('success-response', True)
         boxed = expr.get('boxed', False)
         if isinstance(data, OrderedDict):
+            # TODO apply genif to the implicit object type
             data = self._make_implicit_object_type(
                 name, info, 'arg', self._make_members(data, info))
         if isinstance(rets, list):
+            # TODO apply genif to the implicit array type
+            # TODO disjunction of all the genif
             assert len(rets) == 1
             rets = self._make_array_type(rets[0], info)
-        self._def_entity(QAPISchemaCommand(name, info, data, rets, gen,
-                                           success_response, boxed))
+        self._def_entity(QAPISchemaCommand(name, info, data, rets,
+                                           genif, success_response, boxed))
 
     def _def_event(self, expr, info):
         name = expr['event']
@@ -1704,6 +1713,17 @@ def gen_params(arg_type, boxed, extra):
     return ret
 
 
+def gen_pp_if(cond):
+    if cond is True:
+        return ''
+    return '\n#if ' + cond + '\n'
+
+
+def gen_pp_endif(cond):
+    if cond is True:
+        return ''
+    return '\n#endif  /* ' + cond + ' */\n'
+
 #
 # Common command line parsing
 #
tests/qapi-schema/type-bypass-bad-gen.err +1 -1
index a83c3c6..cca25f1 100644
@@ -1 +1 @@
-tests/qapi-schema/type-bypass-bad-gen.json:2: 'gen' of command 'foo' should only use false value
+tests/qapi-schema/type-bypass-bad-gen.json:2: 'if' of command 'foo' should only use false value
tests/qapi-schema/type-bypass-bad-gen.json +2 -2
index e8dec34..637b11f 100644
@@ -1,2 +1,2 @@
-# 'gen' should only appear with value false
-{ 'command': 'foo', 'gen': 'whatever' }
+# 'if' should only appear with value false FIXME or str
+{ 'command': 'foo', 'if': null }
#9 lore raw

Re: [Qemu-devel] [PATCH v5 02/20] qapi.py: add a simple #ifdef conditional

Hi

Quoted 82 lines · Markus Armbruster
Quoted 5 lines · Markus Armbruster
Quoted 3 lines · Marc-André Lureau

Hi

On Tue, Sep 6, 2016 at 7:58 PM Markus Armbruster <[email protected]>

Quoted 9 lines · wrote:
Quoted 9 lines
Quoted 9 lines

QAPI language design issues, copying Eric.

Quoted 3 lines · Marc-André Lureau

Hi

On Tue, Sep 6, 2016 at 5:00 PM Markus Armbruster <[email protected]>

wrote:

[...]

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

Yet another option is to add 'ifdef' keys to the definitions themselves, i.e.

{ 'command': 'query-gic-capabilities', 'returns':

['GICCapability'],

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 2 lines
      'ifdef': 'TARGET_ARM' }

That's the worst of all options imho, as it makes it hard to filter

out

Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 8 lines

unions/enums, ex:

@ -3446,8 +3466,10 @@
'testdev': 'ChardevCommon', 'stdio' : 'ChardevStdio', 'console': 'ChardevCommon',
+#ifdef CONFIG_SPICE
'spicevmc' :

'ChardevSpiceChannel',

Quoted 1 line

'spiceport' :

'ChardevSpicePort',

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 3 lines

+#endif

                                        'vc'     : 'ChardevVC',
                                        'ringbuf': 'ChardevRingbuf',

Point taken.

Fixable the same way as always when a definition needs to grow additional properties, but the syntax only provides a single value:

make

Quoted 34 lines
Quoted 8 lines
Quoted 6 lines

that single value an object, and the old non-object value syntactic sugar for the equivalent object value. We've previously discussed this technique in the context of giving command arguments default values. I'm not saying this is what we should do here, only pointing out it's possible.

Ok, but let's find something, if possible simple and convenient, no?

I agree it needs to be simple, both the interface (QAPI language) and the implementation. However, I don't like "first past the post". I prefer to explore the design space a bit.

So let me explore the "add 'ifdef' keys to definitions" corner of the QAPI language design space.

Easily done for top-level definitions, because they're all JSON objects. Could even add it to the include directive if we wanted to.

Less easily done for enumeration, struct, union and alternate members. Note that command and event arguments specified inline are a special case of struct members.

The "can't specify additional stuff for struct members" problem isn't new. We hacked around it to specify "optional": encode it into the member name. Doesn't scale. We need to solve the problem to be able to specify default values, and we already decided how: have an JSON object instead of a mere JSON string, make the string syntax sugar for { 'type': STRING }. See commit 6b5abc7 and the discussion in qemu-devel leading up to it. For consistency, we'll do it for union and alternate members, too.

That leaves just enumeration members. The same technique applies.

Quoted 8 lines
Quoted 3 lines

If I remember correctly, we only need conditional commands right now, to avoid regressing query-commands. The more complicated member work could be done later.

To gauge whether this idea is practical, I implemented key 'if' for commands. It's just a sketch, and has a number of issues, which I marked FIXME.

Tbh, I think it is scratching the surface doing it only for commands. Furthermore, it's pushing the burdden of conditional generation at a different level, at the C level, which is probably not so nice if some day it targets a different language.

If the main issue is using #\w* for preprocessing, we could use something else like #! (oh no someone else did it, there are many ex where comments are not just comments), or .\w* (.ifdef / .endif etc).

As you said, the main goal of this patch was to disable commands from the qapi-dispatch that are currently disabled with the middle mode.

Do you think it would be reasonable to accept this simple approach for now, until we find a better more suitable solution? After all, this is internal, we can iterate. Or should we drop this patch for this series? I don't like seeing it delayed by weeks...

Quoted 368 lines

I ported qmp-commands.hx's #if to qapi-schema.json. The TARGET_FOO are poisoned, so I commented them out. There's a CONFIG_SPICE left, which will do for testing.

I also turned key 'gen': false into 'if': false. Possibly a bad idea.

Anyway, diffstat isn't bad:

 docs/qapi-code-gen.txt                     | 14 ++++++-----
 qapi-schema.json                           | 15 ++++++++---
 qapi/introspect.json                       |  2 +-
 scripts/qapi-commands.py                   | 12 +++++++--
 scripts/qapi-introspect.py                 | 22 ++++++++++------
 scripts/qapi.py                            | 40
++++++++++++++++++++++--------
 tests/qapi-schema/type-bypass-bad-gen.err  |  2 +-
 tests/qapi-schema/type-bypass-bad-gen.json |  4 +--
 8 files changed, 77 insertions(+), 34 deletions(-)
docs/qapi-code-gen.txt +0 -0
index de298dc..93e99d8 100644
@@ -423,7 +423,7 @@ part of a Client JSON Protocol command.  The 'data'

member is optional
and defaults to {} (an empty dictionary). If present, it must be the string name of a complex type, or a dictionary that declares an anonymous type with the same semantics as a 'struct' expression, with

docs/qapi-code-gen.txt +1 -1
-one exception noted below when 'gen' is used.
+one exception noted below when 'if': false is used.
 
 The 'returns' member describes what will appear in the "return" member
 of a Client JSON Protocol reply on successful completion of a command.
@@ -431,8 +431,8 @@ The member is optional from the command declaration;

if absent, the
"return" member will be an empty dictionary. If 'returns' is present, it must be the string name of a complex or built-in type, a one-element array containing the name of a complex or built-in type,

docs/qapi-code-gen.txt +2 -2
-with one exception noted below when 'gen' is used.  Although it is
-permitted to have the 'returns' member name a built-in type or an
+with one exception noted below when 'if':false is used.  Although it
+is permitted to have the 'returns' member name a built-in type or an
 array of built-in types, any command that does this cannot be extended
 to return additional information in the future; thus, new commands
 should strongly consider returning a dictionary-based type or an array
@@ -475,16 +475,18 @@ arguments for the user's function out of an input

QDict, calls the
user's function, and if it succeeded, builds an output QObject from its return value.

docs/qapi-code-gen.txt +5 -3
+FIXME document 'if'
+
 In rare cases, QAPI cannot express a type-safe representation of a
 corresponding Client JSON Protocol command.  You then have to suppress
-generation of a marshalling function by including a key 'gen' with
+generation of a marshalling function by including a key 'if' with
 boolean value false, and instead write your own function.  Please try
 to avoid adding new commands that rely on this, and instead use
 type-safe unions.  For an example of this usage:
 
  { 'command': 'netdev_add',
-   'data': {'type': 'str', 'id': 'str'},
-   'gen': false }
+   'if': false,
+   'data': {'type': 'str', 'id': 'str'} }
 
 Normally, the QAPI schema is used to describe synchronous exchanges,
 where a response is expected.  But in some cases, the action of a
qapi-schema.json +11 -4
index c4f3674..ad0559e 100644
@@ -1269,7 +1269,9 @@
 #
 # Since: 0.14.0
 ##
-{ 'command': 'query-spice', 'returns': 'SpiceInfo' }
+{ 'command': 'query-spice',
+  'if': 'defined(CONFIG_SPICE)',
+  'returns': 'SpiceInfo' }
 
 ##
 # @BalloonInfo:
@@ -2355,6 +2357,7 @@
 # Since: 2.5
 ##
 { 'command': 'dump-skeys',
+#  'if': 'defined(TARGET_S390X)',
   'data': { 'filename': 'str' } }
 
 ##
@@ -2380,8 +2383,8 @@
 #          If @type is not a valid network backend, DeviceNotFound
 ##
 { 'command': 'netdev_add',
-  'data': {'type': 'str', 'id': 'str'},
-  'gen': false }                # so we can get the additional arguments
+  'if': false,                  # so we can get the additional arguments
+  'data': {'type': 'str', 'id': 'str'} }
 
 ##
 # @netdev_del:
@@ -4455,6 +4458,7 @@
 # Since: 2.1
 ##
 { 'command': 'rtc-reset-reinjection' }
+#  'if': 'defined(TARGET_I386)'
 
 # Rocker ethernet network switch
 { 'include': 'qapi/rocker.json' }
@@ -4525,7 +4529,10 @@
 #
 # Since: 2.6
 ##
-{ 'command': 'query-gic-capabilities', 'returns': ['GICCapability'] }
+{ 'command': 'query-gic-capabilities',
+#  'if': 'defined(TARGET_ARM)',
+  'returns': ['GICCapability']
+}
 
 ##
 # CpuInstanceProperties
qapi/introspect.json +1 -1
index 3fd81fb..b8f421a 100644
@@ -46,7 +46,7 @@
 ##
 { 'command': 'query-qmp-schema',
   'returns': [ 'SchemaInfo' ],
-  'gen': false }                # just to simplify qmp_query_json()
+  'if': false }                 # just to simplify qmp_query_json()
 
 ##
 # @SchemaMetaType
scripts/qapi-commands.py +10 -2
index a06a2c4..f34e4cc 100644
@@ -215,9 +215,13 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._visited_ret_types = None
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
-        if not gen:
+                      genif, success_response, boxed):
+        if genif is False:
             return
+        pp_if = gen_pp_if(genif)
+        pp_endif = gen_pp_endif(genif)
+        self.decl += pp_if
+        self.defn += pp_if      # FIXME blank lines are off
         self.decl += gen_command_decl(name, arg_type, boxed, ret_type)
         if ret_type and ret_type not in self._visited_ret_types:
             self._visited_ret_types.add(ret_type)
@@ -226,7 +230,11 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
             self.decl += gen_marshal_decl(name)
         self.defn += gen_marshal(name, arg_type, boxed, ret_type)
         if not middle_mode:
+            self._regy += pp_if
             self._regy += gen_register_command(name, success_response)
+            self._regy += pp_endif
+        self.decl += pp_endif
+        self.defn += pp_endif
 
 
 middle_mode = False
scripts/qapi-introspect.py +14 -8
index 541644e..0d8cec7 100644
@@ -30,8 +30,6 @@ def to_json(obj, level=0):
         ret = '{' + ', '.join(elts) + '}'
     else:
         assert False                # not implemented
-    if level == 1:
-        ret = '\n' + ret
     return ret
 
 
@@ -69,8 +67,15 @@ class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):
 extern const char %(c_name)s[];
 ''',
                           c_name=c_name(name))
-        lines = to_json(jsons).split('\n')
-        c_string = '\n    '.join([to_c_string(line) for line in lines])
+        c_string = '"["'
+        for i in jsons:
+            js, genif = i
+            # FIXME blank lines are off
+            c_string += gen_pp_if(genif or True)
+            c_string += '\n    ' + to_c_string(to_json(js) + ', ')
+            c_string += gen_pp_endif(genif or True)
+        # FIXME trailing comma (JSON sucks)
+        c_string += '\n    "]"'
         self.defn = mcgen('''
 const char %(c_name)s[] = %(c_string)s;
 ''',
@@ -111,12 +116,12 @@ const char %(c_name)s[] = %(c_string)s;
             return '[' + self._use_type(typ.element_type) + ']'
         return self._name(typ.name)
 
-    def _gen_json(self, name, mtype, obj):
+    def _gen_json(self, name, mtype, obj, genif=True):
         if mtype not in ('command', 'event', 'builtin', 'array'):
             name = self._name(name)
         obj['name'] = name
         obj['meta-type'] = mtype
-        self._jsons.append(obj)
+        self._jsons.append((obj, genif))
 
     def _gen_member(self, member):
         ret = {'name': member.name, 'type': self._use_type(member.type)}
@@ -154,12 +159,13 @@ const char %(c_name)s[] = %(c_string)s;
                                     for m in variants.variants]})
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      genif, success_response, boxed):
         arg_type = arg_type or self._schema.the_empty_object_type
         ret_type = ret_type or self._schema.the_empty_object_type
         self._gen_json(name, 'command',
                        {'arg-type': self._use_type(arg_type),
-                        'ret-type': self._use_type(ret_type)})
+                        'ret-type': self._use_type(ret_type)},
+                       genif)
 
     def visit_event(self, name, info, arg_type, boxed):
         arg_type = arg_type or self._schema.the_empty_object_type
scripts/qapi.py +0 -0
index 21bc32f..6c0cf9f 100644
@@ -698,7 +698,13 @@ def check_keys(expr_elem, meta, required,

optional=[]):

             raise QAPIExprError(info,
                                 "Unknown key '%s' in %s '%s'"
                                 % (key, meta, name))

- if (key == 'gen' or key == 'success-response') and value is not
False:

scripts/qapi.py +5 -0
+        if (key == 'if'
+            and value is not False and not isinstance(value, str)):
+            # FIXME update error message
+            raise QAPIExprError(info,
+                                "'%s' of %s '%s' should only use false

value"

scripts/qapi.py +2 -0
+                                % (key, meta, name))
+        if (key == 'success-response') and value is not False:
             raise QAPIExprError(info,
                                 "'%s' of %s '%s' should only use false

value"

                                 % (key, meta, name))
scripts/qapi.py +1 -1
@@ -737,7 +743,7 @@ def check_exprs(exprs):
             add_struct(expr, info)
         elif 'command' in expr:
             check_keys(expr_elem, 'command', [],
-                       ['data', 'returns', 'gen', 'success-response',
 'boxed'])
+                       ['data', 'returns', 'if', 'success-response',
 'boxed'])
             add_name(expr['command'], info, 'command')

elif 'event' in expr:
check_keys(expr_elem, 'event', [], ['data', 'boxed'])

scripts/qapi.py +3 -3
@@ -838,7 +844,7 @@ class QAPISchemaVisitor(object):
         pass
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      genif, success_response, boxed):
         pass
 
     def visit_event(self, name, info, arg_type, boxed):
@@ -1180,8 +1186,8 @@ class QAPISchemaAlternateType(QAPISchemaType):
 
 
 class QAPISchemaCommand(QAPISchemaEntity):
-    def __init__(self, name, info, arg_type, ret_type, gen,
 success_response,
-                 boxed):
+    def __init__(self, name, info, arg_type, ret_type,
+                 genif, success_response, boxed):
         QAPISchemaEntity.__init__(self, name, info)
         assert not arg_type or isinstance(arg_type, str)

assert not ret_type or isinstance(ret_type, str)

scripts/qapi.py +2 -2
@@ -1189,7 +1195,7 @@ class QAPISchemaCommand(QAPISchemaEntity):
         self.arg_type = None
         self._ret_type_name = ret_type
         self.ret_type = None
-        self.gen = gen
+        self.genif = genif
         self.success_response = success_response
         self.boxed = boxed
 
@@ -1216,7 +1222,7 @@ class QAPISchemaCommand(QAPISchemaEntity):
     def visit(self, visitor):
         visitor.visit_command(self.name, self.info,
                               self.arg_type, self.ret_type,
-                              self.gen, self.success_response, self.boxed)
+                              self.genif, self.success_response,
 self.boxed)
 
 

class QAPISchemaEvent(QAPISchemaEntity):

scripts/qapi.py +6 -3
@@ -1419,17 +1425,20 @@ class QAPISchema(object):
         name = expr['command']
         data = expr.get('data')
         rets = expr.get('returns')
-        gen = expr.get('gen', True)
+        genif = expr.get('if', True)
         success_response = expr.get('success-response', True)
         boxed = expr.get('boxed', False)
         if isinstance(data, OrderedDict):
+            # TODO apply genif to the implicit object type
             data = self._make_implicit_object_type(
                 name, info, 'arg', self._make_members(data, info))
         if isinstance(rets, list):
+            # TODO apply genif to the implicit array type
+            # TODO disjunction of all the genif
             assert len(rets) == 1
             rets = self._make_array_type(rets[0], info)
-        self._def_entity(QAPISchemaCommand(name, info, data, rets, gen,
-                                           success_response, boxed))
+        self._def_entity(QAPISchemaCommand(name, info, data, rets,
+                                           genif, success_response,
 boxed))
 
     def _def_event(self, expr, info):

name = expr['event']

scripts/qapi.py +11 -0
@@ -1704,6 +1713,17 @@ def gen_params(arg_type, boxed, extra):
     return ret
 
 
+def gen_pp_if(cond):
+    if cond is True:
+        return ''
+    return '\n#if ' + cond + '\n'
+
+
+def gen_pp_endif(cond):
+    if cond is True:
+        return ''
+    return '\n#endif  /* ' + cond + ' */\n'
+
 #
 # Common command line parsing
 #
tests/qapi-schema/type-bypass-bad-gen.err +0 -1
index a83c3c6..cca25f1 100644
@@ -1 +1 @@
-tests/qapi-schema/type-bypass-bad-gen.json:2: 'gen' of command 'foo'

should only use false value +tests/qapi-schema/type-bypass-bad-gen.json:2: 'if' of command 'foo' should only use false value

tests/qapi-schema/type-bypass-bad-gen.json +2 -2
index e8dec34..637b11f 100644
@@ -1,2 +1,2 @@
-# 'gen' should only appear with value false
-{ 'command': 'foo', 'gen': 'whatever' }
+# 'if' should only appear with value false FIXME or str
+{ 'command': 'foo', 'if': null }
Signature · 1 line
Marc-André Lureau
#10 lore raw

Re: [Qemu-devel] [PATCH v5 02/20] qapi.py: add a simple #ifdef conditional

In reply to Markus Armbruster
Quoted 5 lines · Markus Armbruster
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Yet another option is to add 'ifdef' keys to the definitions themselves, i.e.

{ 'command': 'query-gic-capabilities', 'returns': ['GICCapability'],
'ifdef': 'TARGET_ARM' }

Seems like it might be useful; could even be expanded to:

{ 'command': 'query-arm-x86', 'returns': ['Foo'],
'ifdef': [ 'TARGET_ARM', 'TARGET_X86' ] }

unless you are okay with it instead being:

{ 'command': 'query-arm-x86', 'returns': ['Foo'],
'ifdef': 'TARGET_ARM || TARGET_X86' }

Either way, we need to make sure that whatever we put here is easy to translate into the appropriate generated code; and keeping in mind that while '#if A || B' makes sense to the preprocessor, '#ifdef A || B' does not.

Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 8 lines

Fixable the same way as always when a definition needs to grow additional properties, but the syntax only provides a single value: make that single value an object, and the old non-object value syntactic sugar for the equivalent object value. We've previously discussed this technique in the context of giving command arguments default values. I'm not saying this is what we should do here, only pointing out it's possible.

Quoted 5 lines
Quoted 5 lines
Quoted 1 line

Ok, but let's find something, if possible simple and convenient, no?

I agree it needs to be simple, both the interface (QAPI language) and the implementation. However, I don't like "first past the post". I prefer to explore the design space a bit.

Another nice thing about expanding it by changing 'name':'typestr' to be sugar for 'name':{'type':'typestr'} is that QMP introspection is already prepared to expose a dictionary of attributes (type being one, and ifdef'ness being another) per member, so we already would have a nice mapping between qapi JSON files (a member name tied to a dictionary) and the generated output.

Quoted 11 lines
Quoted 11 lines

So let me explore the "add 'ifdef' keys to definitions" corner of the QAPI language design space.

Easily done for top-level definitions, because they're all JSON objects. Could even add it to the include directive if we wanted to.

Less easily done for enumeration, struct, union and alternate members. Note that command and event arguments specified inline are a special case of struct members.

and ideally, whatever we can do for a named struct, we can also do for an anonymous inlined struct for the command and event arguments.

Quoted 4 lines

I ported qmp-commands.hx's #if to qapi-schema.json. The TARGET_FOO are poisoned, so I commented them out. There's a CONFIG_SPICE left, which will do for testing.

Obviously, we'd have to find a way to work around the poisoned ifdef names, but the idea makes some sense to me.

Quoted 2 lines

I also turned key 'gen': false into 'if': false. Possibly a bad idea.

Maybe, maybe not. We have so few that it's easy to convert them all in one go, at which point you are just giving directives to the code
generator: if the 'if' key is present, it controls what gets omitted (either the omitted code is gated by #if (or #ifdef) of the gate string, or 'if':false means the generator omits the code altogether).

docs/qapi-code-gen.txt arguments for the user's function out of an input QDict, calls the · line 479

Quoted 6 lines
docs/qapi-code-gen.txt +2 -0
@@ -475,16 +475,18 @@ arguments for the user's function out of an input QDict, calls the
 user's function, and if it succeeded, builds an output QObject from
 its return value.
 
+FIXME document 'if'
+

And in particular, what the string must look like (will it be fed to generated #if or to generated #ifdef? What if you have more than one conditional?)

qapi-schema.json line 1274

Quoted 9 lines
qapi-schema.json +4 -1
+++ b/qapi-schema.json
@@ -1269,7 +1269,9 @@
 #
 # Since: 0.14.0
 ##
-{ 'command': 'query-spice', 'returns': 'SpiceInfo' }
+{ 'command': 'query-spice',
+  'if': 'defined(CONFIG_SPICE)',
+  'returns': 'SpiceInfo' }

So the idea here is that qemu built without SPICE support would completely lack the query-spice command. This is currently detectable during 'query-commands' but NOT detectable during 'query-qmp-schema'; but after the patch, we could begin to make the introspection likewise hide the unused command. Sounds useful.

qapi-schema.json line 2361

Quoted 9 lines
qapi-schema.json +1 -0
 ##
 # @BalloonInfo:
@@ -2355,6 +2357,7 @@
 # Since: 2.5
 ##
 { 'command': 'dump-skeys',
+#  'if': 'defined(TARGET_S390X)',
   'data': { 'filename': 'str' } }

And here you ran into the poisoned variable problem. Obviously something to be solved if we like the overall idea.

Quoted 13 lines
scripts/qapi-introspect.py +1 -2
+++ b/scripts/qapi-introspect.py
@@ -30,8 +30,6 @@ def to_json(obj, level=0):
         ret = '{' + ', '.join(elts) + '}'
     else:
         assert False                # not implemented
-    if level == 1:
-        ret = '\n' + ret
     return ret
 
 
@@ -69,8 +67,15 @@ class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):
 extern const char %(c_name)s[];
 ''',

scripts/qapi-introspect.py class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor): · line 76

Quoted 10 lines
scripts/qapi-introspect.py +7 -2
                           c_name=c_name(name))
-        lines = to_json(jsons).split('\n')
-        c_string = '\n    '.join([to_c_string(line) for line in lines])
+        c_string = '"["'
+        for i in jsons:
+            js, genif = i
+            # FIXME blank lines are off
+            c_string += gen_pp_if(genif or True)
+            c_string += '\n    ' + to_c_string(to_json(js) + ', ')
+            c_string += gen_pp_endif(genif or True)

And this change to introspection output shows the true power - by having the conditional expression be part of the .json QAPI file, we can now reflect the conditions through ALL parts of the generated code, instead of having discrepancies between query-commands vs. query-qmp-schema.

At any rate, for a quick day's hack, I like this approach for feeling like it fits in with the QAPI language, rather than being bolted on as additional non-JSON syntax.

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#11 lore raw

PATCH v5 3/20 build-sys: make qemu qapi per-target

In reply to Marc-André Lureau

The qapi schema has per-target definitions. Generate the marshaller, events and introspection per target. Keep the types, visitors and headers generic to keep common code unaware. However, having per-target events requires block events stubs.

The following patch will use config headers to conditionally remove disabled features from the schema.

---
 stubs/qapi-event.c  | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 Makefile            | 54 +++++++++++++++-----------------------
 Makefile.objs       |  7 +----
 Makefile.target     | 23 +++++++++++++++++
 stubs/Makefile.objs |  1 +
 qapi.mak            | 14 ++++++++++
 6 files changed, 133 insertions(+), 40 deletions(-)
 create mode 100644 stubs/qapi-event.c
 create mode 100644 qapi.mak
stubs/qapi-event.c new file +74 -0
new file mode 100644
index 0000000..73b5424
@@ -0,0 +1,74 @@
+#include "qemu/osdep.h"
+#include "qapi-event.h"
+
+void qapi_event_send_device_tray_moved(const char *device, bool tray_open,
+                                       Error **errp)
+{
+}
+
+void qapi_event_send_quorum_report_bad(QuorumOpType type, bool has_error,
+                                       const char *error, const char *node_name,
+                                       int64_t sector_num,
+                                       int64_t sectors_count, Error **errp)
+{
+}
+
+void qapi_event_send_quorum_failure(const char *reference, int64_t sector_num,
+                                    int64_t sectors_count, Error **errp)
+{
+}
+
+void qapi_event_send_block_job_cancelled(BlockJobType type, const char *device,
+                                         int64_t len, int64_t offset,
+                                         int64_t speed, Error **errp)
+{
+}
+
+void qapi_event_send_block_job_completed(BlockJobType type, const char *device,
+                                         int64_t len, int64_t offset,
+                                         int64_t speed, bool has_error,
+                                         const char *error, Error **errp)
+{
+}
+
+void qapi_event_send_block_job_error(const char *device,
+                                     IoOperationType operation,
+                                     BlockErrorAction action, Error **errp)
+{
+}
+
+void qapi_event_send_block_job_ready(BlockJobType type, const char *device,
+                                     int64_t len, int64_t offset, int64_t speed,
+                                     Error **errp)
+{
+}
+
+void qapi_event_send_block_io_error(const char *device,
+                                    IoOperationType operation,
+                                    BlockErrorAction action, bool has_nospace,
+                                    bool nospace, const char *reason,
+                                    Error **errp)
+{
+}
+
+void qapi_event_send_block_image_corrupted(const char *device,
+                                           bool has_node_name,
+                                           const char *node_name,
+                                           const char *msg, bool has_offset,
+                                           int64_t offset, bool has_size,
+                                           int64_t size, bool fatal,
+                                           Error **errp)
+{
+}
+
+void qapi_event_send_block_write_threshold(const char *node_name,
+                                           uint64_t amount_exceeded,
+                                           uint64_t write_threshold,
+                                           Error **errp)
+{
+}
+
+void qapi_event_send_device_deleted(bool has_device, const char *device,
+                                    const char *path, Error **errp)
+{
+}
Makefile +20 -34

88 lines not on this page · raw message

Makefile.objs +1 -6
index 6d5ddcf..7addab8 100644
@@ -2,7 +2,7 @@
 # Common libraries for tools and emulators
 stub-obj-y = stubs/ crypto/
 util-obj-y = util/ qobject/ qapi/
-util-obj-y += qmp-introspect.o qapi-types.o qapi-visit.o qapi-event.o
+util-obj-y += qapi-types.o qapi-visit.o
 
 #######################################################################
 # block-obj-y is code used by both qemu system emulation and qemu-img
@@ -78,11 +78,6 @@ common-obj-$(CONFIG_SECCOMP) += qemu-seccomp.o
 
 common-obj-$(CONFIG_FDT) += device_tree.o
 
-######################################################################
-# qapi
-
-common-obj-y += qmp-marshal.o
-common-obj-y += qmp-introspect.o
 common-obj-y += qmp.o hmp.o
 endif
 
Makefile.target +23 -0
index a440bcb..6b672eb 100644
@@ -6,6 +6,7 @@ include ../config-host.mak
 include config-target.mak
 include config-devices.mak
 include $(SRC_PATH)/rules.mak
+include $(SRC_PATH)/qapi.mak
 
 $(call set-vpath, $(SRC_PATH):$(BUILD_DIR))
 ifdef CONFIG_LINUX
@@ -157,6 +158,28 @@ obj-y += hw/$(TARGET_BASE_ARCH)/
 endif
 
 GENERATED_HEADERS += hmp-commands.h hmp-commands-info.h qmp-commands-old.h
+GENERATED_HEADERS += qmp-introspect.h
+GENERATED_SOURCES += qmp-introspect.c qmp-marshal.c qapi-event.c
+
+qmp-marshal.c :\
+$(qapi-modules) $(qapi-commands-py)
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py \
+		$(qapi-gen-type) -o "." -m $<, \
+		"  GEN   $(TARGET_DIR)$@")
+
+qapi-event.c :\
+$(qapi-modules) $(qapi-event-py)
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-event.py \
+		$(qapi-gen-type) -o "." $<, \
+		"  GEN   $@")
+
+qmp-introspect.h qmp-introspect.c :\
+$(qapi-modules) $(qapi-introspect-py)
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-introspect.py \
+		$(qapi-gen-type) -o "." $<, \
+		"  GEN   $(TARGET_DIR)$@")
+
+obj-y += qmp-marshal.o qmp-introspect.o qapi-event.o
 
 endif # CONFIG_SOFTMMU
 
stubs/Makefile.objs +1 -0
index 55edd15..aa2cbef 100644
@@ -45,3 +45,4 @@ stub-obj-y += iohandler.o
 stub-obj-y += smbios_type_38.o
 stub-obj-y += ipmi.o
 stub-obj-y += pc_madt_cpu_entry.o
+stub-obj-y += qapi-event.o
qapi.mak new file +14 -0
new file mode 100644
index 0000000..4e26714
@@ -0,0 +1,14 @@
+qapi-gen-type = $(subst .,-,$(suffix $@))
+
+qapi-modules = $(SRC_PATH)/qapi-schema.json $(SRC_PATH)/qapi/common.json \
+       $(SRC_PATH)/qapi/block.json $(SRC_PATH)/qapi/block-core.json \
+       $(SRC_PATH)/qapi/event.json $(SRC_PATH)/qapi/introspect.json \
+       $(SRC_PATH)/qapi/crypto.json $(SRC_PATH)/qapi/rocker.json \
+       $(SRC_PATH)/qapi/trace.json
+
+qapi-py = $(SRC_PATH)/scripts/qapi.py $(SRC_PATH)/scripts/ordereddict.py
+
+qapi-types-py = $(SRC_PATH)/scripts/qapi-types.py $(qapi-py)
+qapi-visit-py = $(SRC_PATH)/scripts/qapi-visit.py $(qapi-py)
+qapi-commands-py = $(SRC_PATH)/scripts/qapi-commands.py $(qapi-py)
+qapi-introspect-py = $(SRC_PATH)/scripts/qapi-introspect.py $(qapi-py)
Signature · 1 line
2.9.0
#12 lore raw

PATCH v5 4/20 build-sys: use config headers to generate qapi

In reply to Marc-André Lureau

Configure the marshaller, events and introspection with config host and target headers. Keep the types, visitors, and command header generic since it will only use what is actually needed, but needs all declarations to be compatible with the various targets.

---
 Makefile        | 15 +++++++++------
 Makefile.target | 12 +++++++-----
 2 files changed, 16 insertions(+), 11 deletions(-)
Makefile +9 -6
index 83d27fb..f83b208 100644
@@ -267,20 +267,23 @@ qemu-img-cmds.h: $(SRC_PATH)/qemu-img-cmds.hx $(SRC_PATH)/scripts/hxtool
 qemu-ga$(EXESUF): LIBS = $(LIBS_QGA)
 qemu-ga$(EXESUF): QEMU_CFLAGS += -I qga/qapi-generated
 
+qapi-hconfig = config-host.h
+qapi-flags = $(patsubst %,-f %,$(qapi-hconfig))
+
 qga/qapi-generated/qga-qapi-types.c qga/qapi-generated/qga-qapi-types.h :\
-$(SRC_PATH)/qga/qapi-schema.json $(qapi-types-py)
+$(SRC_PATH)/qga/qapi-schema.json $(qapi-types-py) $(qapi-hconfig)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-types.py \
-		$(qapi-gen-type) -o qga/qapi-generated -p "qga-" $<, \
+		$(qapi-flags) $(qapi-gen-type) -o qga/qapi-generated -p "qga-" $<, \
 		"  GEN   $@")
 qga/qapi-generated/qga-qapi-visit.c qga/qapi-generated/qga-qapi-visit.h :\
-$(SRC_PATH)/qga/qapi-schema.json $(qapi-visit-py)
+$(SRC_PATH)/qga/qapi-schema.json $(qapi-visit-py) $(qapi-hconfig)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-visit.py \
-		$(qapi-gen-type) -o qga/qapi-generated -p "qga-" $<, \
+		$(qapi-flags) $(qapi-gen-type) -o qga/qapi-generated -p "qga-" $<, \
 		"  GEN   $@")
 qga/qapi-generated/qga-qmp-commands.h qga/qapi-generated/qga-qmp-marshal.c :\
-$(SRC_PATH)/qga/qapi-schema.json $(qapi-commands-py)
+$(SRC_PATH)/qga/qapi-schema.json $(qapi-commands-py) $(qapi-hconfig)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py \
-		$(qapi-gen-type) -o qga/qapi-generated -p "qga-" $<, \
+		$(qapi-flags) $(qapi-gen-type) -o qga/qapi-generated -p "qga-" $<, \
 		"  GEN   $@")
 
 qapi-types.c qapi-types.h :\
Makefile.target +7 -5
index 6b672eb..c6c20bf 100644
@@ -160,23 +160,25 @@ endif
 GENERATED_HEADERS += hmp-commands.h hmp-commands-info.h qmp-commands-old.h
 GENERATED_HEADERS += qmp-introspect.h
 GENERATED_SOURCES += qmp-introspect.c qmp-marshal.c qapi-event.c
+qapi-hconfig = ../config-host.h config-target.h
+qapi-flags = $(patsubst %,-f %,$(qapi-hconfig))
 
 qmp-marshal.c :\
-$(qapi-modules) $(qapi-commands-py)
+$(qapi-modules) $(qapi-commands-py) $(qapi-hconfig)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py \
-		$(qapi-gen-type) -o "." -m $<, \
+		$(qapi-flags) $(qapi-gen-type) -o "." -m $<, \
 		"  GEN   $(TARGET_DIR)$@")
 
 qapi-event.c :\
 $(qapi-modules) $(qapi-event-py)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-event.py \
-		$(qapi-gen-type) -o "." $<, \
+		$(qapi-flags) $(qapi-gen-type) -o "." $<, \
 		"  GEN   $@")
 
 qmp-introspect.h qmp-introspect.c :\
-$(qapi-modules) $(qapi-introspect-py)
+$(qapi-modules) $(qapi-introspect-py) $(qapi-hconfig)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-introspect.py \
-		$(qapi-gen-type) -o "." $<, \
+		$(qapi-flags) $(qapi-gen-type) -o "." $<, \
 		"  GEN   $(TARGET_DIR)$@")
 
 obj-y += qmp-marshal.o qmp-introspect.o qapi-event.o
Signature · 1 line
2.9.0
#13 lore raw

PATCH v5 5/20 qapi: configure the schema

In reply to Marc-André Lureau

Make parts of the qapi schema conditional based on host and target config. Remove the no longer needed fallback commands implementations.

---
 hmp.c                |  2 ++
 monitor.c            | 22 ----------------------
 qmp.c                | 32 --------------------------------
 hmp-commands-info.hx |  2 ++
 qapi-schema.json     | 30 ++++++++++++++++++++++++++++++
 qapi/event.json      |  8 ++++++++
 qmp-commands.hx      |  7 ++++---
 7 files changed, 46 insertions(+), 57 deletions(-)
hmp.c +2 -0
index cc2056e..339f5c6 100644
@@ -570,6 +570,7 @@ void hmp_info_blockstats(Monitor *mon, const QDict *qdict)
     qapi_free_BlockStatsList(stats_list);
 }
 
+#ifdef CONFIG_VNC
 void hmp_info_vnc(Monitor *mon, const QDict *qdict)
 {
     VncInfo *info;
@@ -615,6 +616,7 @@ void hmp_info_vnc(Monitor *mon, const QDict *qdict)
 out:
     qapi_free_VncInfo(info);
 }
+#endif
 
 #ifdef CONFIG_SPICE
 void hmp_info_spice(Monitor *mon, const QDict *qdict)
monitor.c +0 -22
index 5c00373..289fa5e 100644
@@ -4306,28 +4306,6 @@ QemuOptsList qemu_mon_opts = {
     },
 };
 
-#ifndef TARGET_I386
-void qmp_rtc_reset_reinjection(Error **errp)
-{
-    error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
-}
-#endif
-
-#ifndef TARGET_S390X
-void qmp_dump_skeys(const char *filename, Error **errp)
-{
-    error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
-}
-#endif
-
-#ifndef TARGET_ARM
-GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
-{
-    error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
-    return NULL;
-}
-#endif
-
 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
 {
     MachineState *ms = MACHINE(qdev_get_machine());
qmp.c +0 -32
index b6d531e..01671ad 100644
@@ -145,38 +145,6 @@ void qmp_cpu_add(int64_t id, Error **errp)
     }
 }
 
-#ifndef CONFIG_VNC
-/* If VNC support is enabled, the "true" query-vnc command is
-   defined in the VNC subsystem */
-VncInfo *qmp_query_vnc(Error **errp)
-{
-    error_setg(errp, QERR_FEATURE_DISABLED, "vnc");
-    return NULL;
-};
-
-VncInfo2List *qmp_query_vnc_servers(Error **errp)
-{
-    error_setg(errp, QERR_FEATURE_DISABLED, "vnc");
-    return NULL;
-};
-#endif
-
-#ifndef CONFIG_SPICE
-/*
- * qmp-commands.hx ensures that QMP command query-spice exists only
- * #ifdef CONFIG_SPICE.  Necessary for an accurate query-commands
- * result.  However, the QAPI schema is blissfully unaware of that,
- * and the QAPI code generator happily generates a dead
- * qmp_marshal_query_spice() that calls qmp_query_spice().  Provide it
- * one, or else linking fails.  FIXME Educate the QAPI schema on
- * CONFIG_SPICE.
- */
-SpiceInfo *qmp_query_spice(Error **errp)
-{
-    abort();
-};
-#endif
-
 void qmp_cont(Error **errp)
 {
     Error *local_err = NULL;
hmp-commands-info.hx +2 -0
index 74446c6..be6e13a 100644
@@ -430,6 +430,7 @@ STEXI
 Show which guest mouse is receiving events.
 ETEXI
 
+#if defined(CONFIG_VNC)
     {
         .name       = "vnc",
         .args_type  = "",
@@ -437,6 +438,7 @@ ETEXI
         .help       = "show the vnc server status",
         .mhandler.cmd = hmp_info_vnc,
     },
+#endif
 
 STEXI
 @item info vnc
qapi-schema.json +30 -0
index 5658723..caad127 100644
@@ -973,6 +973,8 @@
 { 'enum': 'NetworkAddressFamily',
   'data': [ 'ipv4', 'ipv6', 'unix', 'unknown' ] }
 
+#ifdef CONFIG_VNC
+
 ##
 # @VncBasicInfo
 #
@@ -1146,6 +1148,10 @@
 ##
 { 'command': 'query-vnc-servers', 'returns': ['VncInfo2'] }
 
+#endif CONFIG_VNC
+
+#ifdef CONFIG_SPICE
+
 ##
 # @SpiceBasicInfo
 #
@@ -1271,6 +1277,8 @@
 ##
 { 'command': 'query-spice', 'returns': 'SpiceInfo' }
 
+#endif CONFIG_SPICE
+
 ##
 # @BalloonInfo:
 #
@@ -2000,6 +2008,8 @@
 ##
 { 'command': 'expire_password', 'data': {'protocol': 'str', 'time': 'str'} }
 
+#ifdef CONFIG_VNC
+
 ##
 # @change-vnc-password:
 #
@@ -2014,6 +2024,8 @@
 ##
 { 'command': 'change-vnc-password', 'data': {'password': 'str'} }
 
+#endif
+
 ##
 # @change:
 #
@@ -2343,6 +2355,8 @@
 { 'command': 'query-dump-guest-memory-capability',
   'returns': 'DumpGuestMemoryCapability' }
 
+#ifdef TARGET_S390X
+
 ##
 # @dump-skeys
 #
@@ -2357,6 +2371,8 @@
 { 'command': 'dump-skeys',
   'data': { 'filename': 'str' } }
 
+#endif TARGET_S390X
+
 ##
 # @netdev_add:
 #
@@ -3371,6 +3387,8 @@
   'base': 'ChardevCommon' }
 
 
+#ifdef CONFIG_SPICE
+
 ##
 # @ChardevSpiceChannel:
 #
@@ -3395,6 +3413,8 @@
 { 'struct': 'ChardevSpicePort', 'data': { 'fqdn'  : 'str' },
   'base': 'ChardevCommon' }
 
+#endif CONFIG_SPICE
+
 ##
 # @ChardevVC:
 #
@@ -3446,8 +3466,10 @@
                                        'testdev': 'ChardevCommon',
                                        'stdio'  : 'ChardevStdio',
                                        'console': 'ChardevCommon',
+#ifdef CONFIG_SPICE
                                        'spicevmc' : 'ChardevSpiceChannel',
                                        'spiceport' : 'ChardevSpicePort',
+#endif
                                        'vc'     : 'ChardevVC',
                                        'ringbuf': 'ChardevRingbuf',
                                        # next one is just for compatibility
@@ -4200,6 +4222,8 @@
 { 'enum': 'GuestPanicAction',
   'data': [ 'pause' ] }
 
+#ifdef TARGET_I386
+
 ##
 # @rtc-reset-reinjection
 #
@@ -4212,6 +4236,8 @@
 ##
 { 'command': 'rtc-reset-reinjection' }
 
+#endif TARGET_I386
+
 # Rocker ethernet network switch
 { 'include': 'qapi/rocker.json' }
 
@@ -4271,6 +4297,8 @@
             'emulated': 'bool',
             'kernel': 'bool' } }
 
+#ifdef TARGET_ARM
+
 ##
 # @query-gic-capabilities:
 #
@@ -4283,6 +4311,8 @@
 ##
 { 'command': 'query-gic-capabilities', 'returns': ['GICCapability'] }
 
+#endif TARGET_ARM
+
 ##
 # CpuInstanceProperties
 #
qapi/event.json +8 -0
index 8642052..712045f 100644
@@ -138,6 +138,8 @@
 { 'event': 'NIC_RX_FILTER_CHANGED',
   'data': { '*name': 'str', 'path': 'str' } }
 
+#ifdef CONFIG_VNC
+
 ##
 # @VNC_CONNECTED
 #
@@ -187,6 +189,10 @@
   'data': { 'server': 'VncServerInfo',
             'client': 'VncClientInfo' } }
 
+#endif CONFIG_VNC
+
+#ifdef CONFIG_SPICE
+
 ##
 # @SPICE_CONNECTED
 #
@@ -242,6 +248,8 @@
 ##
 { 'event': 'SPICE_MIGRATE_COMPLETED' }
 
+#endif
+
 ##
 # @MIGRATION
 #
qmp-commands.hx +4 -3
index 6866264..0eb0d9c 100644
@@ -3347,7 +3347,7 @@ Example:
    }
 
 EQMP
-
+#if defined(CONFIG_VNC)
     {
         .name       = "query-vnc",
         .args_type  = "",
@@ -3358,7 +3358,7 @@ EQMP
         .args_type  = "",
         .mhandler.cmd_new = qmp_marshal_query_vnc_servers,
     },
-
+#endif
 SQMP
 query-spice
 -----------
@@ -3911,12 +3911,13 @@ EQMP
         .args_type  = "",
         .mhandler.cmd_new = qmp_marshal_nbd_server_stop,
     },
-
+#if defined(CONFIG_VNC)
     {
         .name       = "change-vnc-password",
         .args_type  = "password:s",
         .mhandler.cmd_new = qmp_marshal_change_vnc_password,
     },
+#endif
     {
         .name       = "qom-list-types",
         .args_type  = "implements:s?,abstract:b?",
Signature · 1 line
2.9.0
#14 lore raw

PATCH v5 6/20 build-sys: define QEMU_VERSION_{MAJOR, MINOR, MICRO}

In reply to Marc-André Lureau

There are better chances to find what went wrong at build time than a later assert in qmp_query_version

---
 qmp.c                 | 16 +++-------------
 scripts/create_config |  6 ++++++
 2 files changed, 9 insertions(+), 13 deletions(-)
qmp.c +3 -13
index 01671ad..03d1374 100644
@@ -51,21 +51,11 @@ NameInfo *qmp_query_name(Error **errp)
 VersionInfo *qmp_query_version(Error **errp)
 {
     VersionInfo *info = g_new0(VersionInfo, 1);
-    const char *version = QEMU_VERSION;
-    const char *tmp;
-    int err;
 
     info->qemu = g_new0(VersionTriple, 1);
-    err = qemu_strtoll(version, &tmp, 10, &info->qemu->major);
-    assert(err == 0);
-    tmp++;
-
-    err = qemu_strtoll(tmp, &tmp, 10, &info->qemu->minor);
-    assert(err == 0);
-    tmp++;
-
-    err = qemu_strtoll(tmp, &tmp, 10, &info->qemu->micro);
-    assert(err == 0);
+    info->qemu->major = QEMU_VERSION_MAJOR;
+    info->qemu->minor = QEMU_VERSION_MINOR;
+    info->qemu->micro = QEMU_VERSION_MICRO;
     info->package = g_strdup(QEMU_PKGVERSION);
 
     return info;
scripts/create_config +6 -0
index 1dd6a35..e6929dd 100755
@@ -7,7 +7,13 @@ while read line; do
 case $line in
  VERSION=*) # configuration
     version=${line#*=}
+    major=$(echo "$version" | cut -d. -f1)
+    minor=$(echo "$version" | cut -d. -f2)
+    micro=$(echo "$version" | cut -d. -f3)
     echo "#define QEMU_VERSION \"$version\""
+    echo "#define QEMU_VERSION_MAJOR $major"
+    echo "#define QEMU_VERSION_MINOR $minor"
+    echo "#define QEMU_VERSION_MICRO $micro"
     ;;
  qemu_*dir=*) # qemu-specific directory configuration
     name=${line%=*}
Signature · 1 line
2.9.0
#15 lore raw

PATCH v5 7/20 qapi-schema: use generated marshaller for 'qmp_capabilities'

In reply to Marc-André Lureau

qapi'fy the 'qmp_capabilities' command, makes the command visible in query-qmp-schema.

---
 monitor.c        |  4 ++--
 qapi-schema.json | 21 +++++++++++++++++++++
 qmp-commands.hx  |  2 +-
 3 files changed, 24 insertions(+), 3 deletions(-)
monitor.c +2 -2
index 289fa5e..4a6f97d 100644
@@ -617,7 +617,7 @@ static void monitor_qapi_event_init(void)
     qmp_event_set_func_emit(monitor_qapi_event_queue);
 }
 
-static void qmp_capabilities(QDict *params, QObject **ret_data, Error **errp)
+void qmp_qmp_capabilities(Error **errp)
 {
     cur_mon->qmp.in_command_mode = true;
 }
@@ -3656,7 +3656,7 @@ static int monitor_can_read(void *opaque)
 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
                              Error **errp)
 {
-    bool is_cap = cmd->mhandler.cmd_new == qmp_capabilities;
+    bool is_cap = cmd->mhandler.cmd_new == qmp_marshal_qmp_capabilities;
 
     if (is_cap && mon->qmp.in_command_mode) {
         error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
qapi-schema.json +21 -0
index caad127..1eb8db5 100644
@@ -20,6 +20,27 @@
 # QAPI introspection
 { 'include': 'qapi/introspect.json' }
 
+##
+# @qmp_capabilities:
+#
+# Enable QMP capabilities.
+#
+# Arguments: None.
+#
+# Example:
+#
+# -> { "execute": "qmp_capabilities" }
+# <- { "return": {} }
+#
+# Notes: This command is valid exactly when first connecting: it must be
+# issued before any other command will be accepted, and will fail once the
+# monitor is accepting other commands. (see qemu docs/qmp-spec.txt)
+#
+# Since: 0.13
+#
+##
+{ 'command': 'qmp_capabilities' }
+
 ##
 # @LostTickPolicy:
 #
qmp-commands.hx +1 -1
index 0eb0d9c..5336ec2 100644
@@ -2209,7 +2209,7 @@ EQMP
         .args_type  = "",
         .params     = "",
         .help       = "enable QMP capabilities",
-        .mhandler.cmd_new = qmp_capabilities,
+        .mhandler.cmd_new = qmp_marshal_qmp_capabilities,
     },
 
 SQMP
Signature · 1 line
2.9.0
#16 lore raw

PATCH v5 8/20 qapi-schema: add 'device_add'

In reply to Marc-André Lureau

Even though device_add is not fully qapi'fied, we may add it to the json schema with 'gen': false, so registration and documentation can be generated.

---
 qapi-schema.json | 40 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 40 insertions(+)
qapi-schema.json +40 -0
index 1eb8db5..a2fe8c2 100644
@@ -2212,6 +2212,46 @@
 ##
 { 'command': 'xen-set-global-dirty-log', 'data': { 'enable': 'bool' } }
 
+##
+# @device_add:
+#
+# @driver: the name of the new device's driver
+#
+# @bus: #optional the device's parent bus (device tree path)
+#
+# @id: the device's ID, must be unique
+#
+# Additional arguments depend on the type.
+#
+# Add a device.
+#
+# Notes:
+# 1. For detailed information about this command, please refer to the
+#    'docs/qdev-device-use.txt' file.
+#
+# 2. It's possible to list device properties by running QEMU with the
+#    "-device DEVICE,help" command-line argument, where DEVICE is the
+#    device's name
+#
+# Example:
+#
+# -> { "execute": "device_add",
+#      "arguments": { "driver": "e1000", "id": "net1",
+#                     "bus": "pci.0",
+#                     "mac": "52:54:00:12:34:56" } }
+# <- { "return": {} }
+#
+# TODO This command effectively bypasses QAPI completely due to its
+# "additional arguments" business.  It shouldn't have been added to
+# the schema in this form.  It should be qapified properly, or
+# replaced by a properly qapified command.
+#
+# Since: 0.13
+##
+{ 'command': 'device_add',
+  'data': {'driver': 'str', 'id': 'str'},
+  'gen': false } # so we can get the additional arguments
+
 ##
 # @device_del:
 #
Signature · 1 line
2.9.0
#17 lore raw

PATCH v5 9/20 monitor: simplify invalid_qmp_mode()

In reply to Marc-André Lureau

handle_qmp_command() will switch to use qmp_dispatch(). It won't have a pointer to the marshaller function anymore, but only the name of the command to invoke. Simplify invalid_qmp_mode() so it can just be called with the command name.

---
 monitor.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
monitor.c +5 -5
index 4a6f97d..aad44c7 100644
@@ -3653,21 +3653,21 @@ static int monitor_can_read(void *opaque)
     return (mon->suspend_cnt == 0) ? 1 : 0;
 }
 
-static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
+static bool invalid_qmp_mode(const Monitor *mon, const char *cmd,
                              Error **errp)
 {
-    bool is_cap = cmd->mhandler.cmd_new == qmp_marshal_qmp_capabilities;
+    bool is_cap = g_str_equal(cmd, "qmp_capabilities");
 
     if (is_cap && mon->qmp.in_command_mode) {
         error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
                   "Capabilities negotiation is already complete, command "
-                  "'%s' ignored", cmd->name);
+                  "'%s' ignored", cmd);
         return true;
     }
     if (!is_cap && !mon->qmp.in_command_mode) {
         error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
                   "Expecting capabilities negotiation with "
-                  "'qmp_capabilities' before command '%s'", cmd->name);
+                  "'qmp_capabilities' before command '%s'", cmd);
         return true;
     }
     return false;
@@ -3958,7 +3958,7 @@ static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
                   "The command %s has not been found", cmd_name);
         goto err_out;
     }
-    if (invalid_qmp_mode(mon, cmd, &local_err)) {
+    if (invalid_qmp_mode(mon, cmd_name, &local_err)) {
         goto err_out;
     }
 
Signature · 1 line
2.9.0
#18 lore raw

PATCH v5 10/20 monitor: register gen:false commands manually

In reply to Marc-André Lureau

Since a few commands are using 'gen': false, they are not registered automatically by the generator. Register manually instead.

This is in preparation for removal of qapi 'middle' mode generation.

Note that qmp_init_marshal() function isn't run yet, so the commands aren't actually registered, until module_call_init(MODULE_INIT_QAPI) is added in a later patch.

---
 monitor.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
monitor.c +13 -0
index aad44c7..598b389 100644
@@ -79,6 +79,7 @@
 #include "sysemu/block-backend.h"
 #include "sysemu/qtest.h"
 #include "qemu/cutils.h"
+#include "qapi/qmp/dispatch.h"
 
 /* for hmp_info_irq/pic */
 #if defined(TARGET_SPARC)
@@ -1007,6 +1008,18 @@ static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
     *ret_data = qobject_from_json(qmp_schema_json);
 }
 
+static void qmp_init_marshal(void)
+{
+    qmp_register_command("query-qmp-schema", qmp_query_qmp_schema,
+                         QCO_NO_OPTIONS);
+    qmp_register_command("device_add", qmp_device_add,
+                         QCO_NO_OPTIONS);
+    qmp_register_command("netdev_add", qmp_netdev_add,
+                         QCO_NO_OPTIONS);
+}
+
+qapi_init(qmp_init_marshal);
+
 /* set the current CPU defined by the user */
 int monitor_set_cpu(int cpu_index)
 {
Signature · 1 line
2.9.0
#19 lore raw

PATCH v5 11/20 qapi: export the marshallers

In reply to Marc-André Lureau

Make it possible to call marshallers manually, without going through qmp_dispatch(). (this is currently only possible in middle-mode, but it's also useful in general)

---
 scripts/qapi-commands.py | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)
scripts/qapi-commands.py +2 -6
index a06a2c4..b150db9 100644
@@ -84,10 +84,7 @@ static void qmp_marshal_output_%(c_name)s(%(c_type)s ret_in, QObject **ret_out,
 
 
 def gen_marshal_proto(name):
-    ret = 'void qmp_marshal_%s(QDict *args, QObject **ret, Error **errp)' % c_name(name)
-    if not middle_mode:
-        ret = 'static ' + ret
-    return ret
+    return 'void qmp_marshal_%s(QDict *args, QObject **ret, Error **errp)' % c_name(name)
 
 
 def gen_marshal_decl(name):
@@ -222,8 +219,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         if ret_type and ret_type not in self._visited_ret_types:
             self._visited_ret_types.add(ret_type)
             self.defn += gen_marshal_output(ret_type)
-        if middle_mode:
-            self.decl += gen_marshal_decl(name)
+        self.decl += gen_marshal_decl(name)
         self.defn += gen_marshal(name, arg_type, boxed, ret_type)
         if not middle_mode:
             self._regy += gen_register_command(name, success_response)
Signature · 1 line
2.9.0
#20 lore raw

PATCH v5 12/20 monitor: use qmp_find_command() (using generated qapi code)

In reply to Marc-André Lureau

Stop using the so-called 'middle' mode. Instead, use qmp_find_command() from generated qapi commands registry. Update and fix the documentation too.

---
 monitor.c                     |  10 ++-
 vl.c                          |   1 +
 Makefile                      |   2 +-
 Makefile.target               |   2 +-
 docs/writing-qmp-commands.txt |   8 +--
 qmp-commands.hx               | 143 ------------------------------------------
 6 files changed, 12 insertions(+), 154 deletions(-)
monitor.c +7 -3
index 598b389..e72804a 100644
@@ -3941,6 +3941,7 @@ static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
     QObject *obj, *data;
     QDict *input, *args;
     const mon_cmd_t *cmd;
+    QmpCommand *qcmd;
     const char *cmd_name;
     Monitor *mon = cur_mon;
 
@@ -3966,7 +3967,8 @@ static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
     cmd_name = qdict_get_str(input, "execute");
     trace_handle_qmp_command(mon, cmd_name);
     cmd = qmp_find_cmd(cmd_name);
-    if (!cmd) {
+    qcmd = qmp_find_command(cmd_name);
+    if (!qcmd || !cmd) {
         error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
                   "The command %s has not been found", cmd_name);
         goto err_out;
@@ -3988,7 +3990,7 @@ static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
         goto err_out;
     }
 
-    cmd->mhandler.cmd_new(args, &data, &local_err);
+    qcmd->fn(args, &data, &local_err);
 
 err_out:
     monitor_protocol_emitter(mon, data, local_err);
@@ -4060,7 +4062,9 @@ static QObject *get_qmp_greeting(void)
     QObject *ver = NULL;
 
     qmp_marshal_query_version(NULL, &ver, NULL);
-    return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
+
+    return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': []}}",
+                              ver);
 }
 
 static void monitor_qmp_event(void *opaque, int event)
vl.c +1 -0
index b3c80d5..04dc336 100644
@@ -2973,6 +2973,7 @@ int main(int argc, char **argv, char **envp)
     qemu_init_exec_dir(argv[0]);
 
     module_call_init(MODULE_INIT_QOM);
+    module_call_init(MODULE_INIT_QAPI);
 
     qemu_add_opts(&qemu_drive_opts);
     qemu_add_drive_opts(&qemu_legacy_drive_opts);
Makefile +1 -1
index f83b208..fc2e53a 100644
@@ -306,7 +306,7 @@ $(qapi-modules) $(qapi-event-py)
 qmp-commands.h :\
 $(qapi-modules) $(qapi-commands-py)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py \
-		$(qapi-gen-type) -o "." -m $<, \
+		$(qapi-gen-type) -o "." $<, \
 		"  GEN   $@")
 
 QGALIB_GEN=$(addprefix qga/qapi-generated/, qga-qapi-types.h qga-qapi-visit.h qga-qmp-commands.h)
Makefile.target +1 -1
index c6c20bf..0ba50ae 100644
@@ -166,7 +166,7 @@ qapi-flags = $(patsubst %,-f %,$(qapi-hconfig))
 qmp-marshal.c :\
 $(qapi-modules) $(qapi-commands-py) $(qapi-hconfig)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py \
-		$(qapi-flags) $(qapi-gen-type) -o "." -m $<, \
+		$(qapi-flags) $(qapi-gen-type) -o "." $<, \
 		"  GEN   $(TARGET_DIR)$@")
 
 qapi-event.c :\
docs/writing-qmp-commands.txt +2 -6
index 59aa77a..0a66e0e 100644
@@ -127,7 +127,6 @@ following at the bottom:
     {
         .name       = "hello-world",
         .args_type  = "",
-        .mhandler.cmd_new = qmp_marshal_hello_world,
     },
 
 You're done. Now build qemu, run it as suggested in the "Testing" section,
@@ -179,7 +178,6 @@ The last step is to update the qmp-commands.hx file:
     {
         .name       = "hello-world",
         .args_type  = "message:s?",
-        .mhandler.cmd_new = qmp_marshal_hello_world,
     },
 
 Notice that the "args_type" member got our "message" argument. The character
@@ -454,12 +452,11 @@ There are a number of things to be noticed:
 6. You have to include the "qmp-commands.h" header file in qemu-timer.c,
    otherwise qemu won't build
 
-The last step is to add the correspoding entry in the qmp-commands.hx file:
+The last step is to add the corresponding entry in the qmp-commands.hx file:
 
     {
         .name       = "query-alarm-clock",
         .args_type  = "",
-        .mhandler.cmd_new = qmp_marshal_query_alarm_clock,
     },
 
 Time to test the new command. Build qemu, run it as described in the "Testing"
@@ -518,7 +515,7 @@ in the monitor.c file. The entry for the "info alarmclock" follows:
         .args_type  = "",
         .params     = "",
         .help       = "show information about the alarm clock",
-        .mhandler.info = hmp_info_alarm_clock,
+        .mhandler.cmd = hmp_info_alarm_clock,
     },
 
 To test this, run qemu and type "info alarmclock" in the user monitor.
@@ -605,7 +602,6 @@ To test this you have to add the corresponding qmp-commands.hx entry:
     {
         .name       = "query-alarm-methods",
         .args_type  = "",
-        .mhandler.cmd_new = qmp_marshal_query_alarm_methods,
     },
 
 Now Build qemu, run it as explained in the "Testing" section and try our new
qmp-commands.hx +0 -143

968 lines not on this page · raw message

Signature · 1 line
2.9.0
#21 lore raw

PATCH v5 13/20 monitor: implement 'qmp_query_commands' without qmp_cmds

In reply to Marc-André Lureau

One step towards getting rid of the static qmp_cmds table.

---
 monitor.c | 29 ++++++++++++++++++-----------
 1 file changed, 18 insertions(+), 11 deletions(-)
monitor.c +18 -11
index e72804a..dad49b6 100644
@@ -957,21 +957,28 @@ static void hmp_info_help(Monitor *mon, const QDict *qdict)
     help_cmd(mon, "info");
 }
 
-CommandInfoList *qmp_query_commands(Error **errp)
+static void query_commands_cb(QmpCommand *cmd, void *opaque)
 {
-    CommandInfoList *info, *cmd_list = NULL;
-    const mon_cmd_t *cmd;
-
-    for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
-        info = g_malloc0(sizeof(*info));
-        info->value = g_malloc0(sizeof(*info->value));
-        info->value->name = g_strdup(cmd->name);
+    CommandInfoList *info, **list = opaque;
 
-        info->next = cmd_list;
-        cmd_list = info;
+    if (!cmd->enabled) {
+        return;
     }
 
-    return cmd_list;
+    info = g_malloc0(sizeof(*info));
+    info->value = g_malloc0(sizeof(*info->value));
+    info->value->name = g_strdup(cmd->name);
+    info->next = *list;
+    *list = info;
+}
+
+CommandInfoList *qmp_query_commands(Error **errp)
+{
+    CommandInfoList *list = NULL;
+
+    qmp_for_each_command(query_commands_cb, &list);
+
+    return list;
 }
 
 EventInfoList *qmp_query_events(Error **errp)
Signature · 1 line
2.9.0
#22 lore raw

PATCH v5 14/20 monitor: remove mhandler.cmd_new

In reply to Marc-André Lureau

This is no longer necessary now that we aren't using middle mode anymore.

---
 monitor.c                     |  13 +--
 docs/writing-qmp-commands.txt |   4 +-
 hmp-commands-info.hx          | 118 ++++++++++++------------
 hmp-commands.hx               | 208 +++++++++++++++++++++---------------------
 4 files changed, 170 insertions(+), 173 deletions(-)
monitor.c +5 -8
index dad49b6..f07fc31 100644
@@ -130,13 +130,10 @@ typedef struct mon_cmd_t {
     const char *args_type;
     const char *params;
     const char *help;
-    union {
-        void (*cmd)(Monitor *mon, const QDict *qdict);
-        void (*cmd_new)(QDict *params, QObject **ret_data, Error **errp);
-    } mhandler;
-    /* @sub_table is a list of 2nd level of commands. If it do not exist,
-     * mhandler should be used. If it exist, sub_table[?].mhandler should be
-     * used, and mhandler of 1st level plays the role of help function.
+    void (*cmd)(Monitor *mon, const QDict *qdict);
+    /* @sub_table is a list of 2nd level of commands. If it does not exist,
+     * cmd should be used. If it exists, sub_table[?].cmd should be
+     * used, and cmd of 1st level plays the role of help function.
      */
     struct mon_cmd_t *sub_table;
     void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
@@ -2974,7 +2971,7 @@ static void handle_hmp_command(Monitor *mon, const char *cmdline)
         return;
     }
 
-    cmd->mhandler.cmd(mon, qdict);
+    cmd->cmd(mon, qdict);
     QDECREF(qdict);
 }
 
docs/writing-qmp-commands.txt +2 -2
index 0a66e0e..c425393 100644
@@ -335,7 +335,7 @@ we should add it to the hmp-commands.hx file:
         .args_type  = "message:s?",
         .params     = "hello-world [message]",
         .help       = "Print message to the standard output",
-        .mhandler.cmd = hmp_hello_world,
+        .cmd        = hmp_hello_world,
     },
 
 STEXI
@@ -515,7 +515,7 @@ in the monitor.c file. The entry for the "info alarmclock" follows:
         .args_type  = "",
         .params     = "",
         .help       = "show information about the alarm clock",
-        .mhandler.cmd = hmp_info_alarm_clock,
+        .cmd        = hmp_info_alarm_clock,
     },
 
 To test this, run qemu and type "info alarmclock" in the user monitor.
hmp-commands-info.hx +59 -59

452 lines not on this page · raw message

hmp-commands.hx +104 -104

826 lines not on this page · raw message

Signature · 1 line
2.9.0
#23 lore raw

PATCH v5 15/20 qapi: remove the "middle" mode

In reply to Marc-André Lureau

Now that the register function is always generated, we can remove the so-called "middle" mode from the generator script.

---
 scripts/qapi-commands.py | 15 +++------------
 1 file changed, 3 insertions(+), 12 deletions(-)
scripts/qapi-commands.py +3 -12
index b150db9..eac64ce 100644
@@ -206,8 +206,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._visited_ret_types = set()
 
     def visit_end(self):
-        if not middle_mode:
-            self.defn += gen_registry(self._regy)
+        self.defn += gen_registry(self._regy)
         self._regy = None
         self._visited_ret_types = None
 
@@ -221,18 +220,10 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
             self.defn += gen_marshal_output(ret_type)
         self.decl += gen_marshal_decl(name)
         self.defn += gen_marshal(name, arg_type, boxed, ret_type)
-        if not middle_mode:
-            self._regy += gen_register_command(name, success_response)
+        self._regy += gen_register_command(name, success_response)
 
 
-middle_mode = False
-
-(input_file, output_dir, do_c, do_h, prefix, opts) = \
-    parse_command_line("m", ["middle"])
-
-for o, a in opts:
-    if o in ("-m", "--middle"):
-        middle_mode = True
+(input_file, output_dir, do_c, do_h, prefix, opts) = parse_command_line()
 
 c_comment = '''
 /*
Signature · 1 line
2.9.0
#24 lore raw

PATCH v5 16/20 qapi: check invalid arguments on no-args commands

In reply to Marc-André Lureau

The generated marshal functions do not visit arguments from commands that take no arguments. Thus they fail to catch invalid members. Visit the arguments, if provided, to throw an error in case of invalid members.

Currently, qmp_check_client_args() checks for invalid arguments and correctly catches this case. When switching to qmp_dispatch() we want to keep that behaviour. The commands using 'O' may have arbitrary arguments, and must have 'gen': false in the qapi schema to skip the generated checks.

Old/new diff:
void qmp_marshal_stop(QDict *args, QObject **ret, Error **errp)

 {
     Error *err = NULL;

+ Visitor *v = NULL;

- (void)args;
+ if (args) {

+        v = qmp_input_visitor_new(QOBJECT(args), true);
+        visit_start_struct(v, NULL, NULL, 0, &err);
+        if (err) {

+ goto out;
+ }
+
+ if (!err) {
+ visit_check_struct(v, &err);

+        }
+        visit_end_struct(v, NULL);
+        if (err) {

+ goto out;
+ }
+ }

     qmp_stop(&err);
+
+out:
     error_propagate(errp, err);

+ visit_free(v);
+ if (args) {
+ v = qapi_dealloc_visitor_new();
+ visit_start_struct(v, NULL, NULL, 0, NULL);
+
+ visit_end_struct(v, NULL);
+ visit_free(v);
+ }
}

The new code closely resembles code for a command with arguments. Differences:
- the visit of the argument and its cleanup struct don't visit any members (because there are none).
- the visit of the argument struct and its cleanup are conditional.

---
 tests/test-qmp-commands.c | 15 ++++++++++++
 scripts/qapi-commands.py  | 58 +++++++++++++++++++++++++++++++++++------------
 2 files changed, 58 insertions(+), 15 deletions(-)
tests/test-qmp-commands.c +15 -0
index 261fd9e..81cbe54 100644
@@ -106,6 +106,7 @@ static void test_dispatch_cmd(void)
 static void test_dispatch_cmd_failure(void)
 {
     QDict *req = qdict_new();
+    QDict *args = qdict_new();
     QObject *resp;
 
     qdict_put_obj(req, "execute", QOBJECT(qstring_from_str("user_def_cmd2")));
@@ -114,6 +115,20 @@ static void test_dispatch_cmd_failure(void)
     assert(resp != NULL);
     assert(qdict_haskey(qobject_to_qdict(resp), "error"));
 
+    qobject_decref(resp);
+    QDECREF(req);
+
+    /* check that with extra arguments it throws an error */
+    req = qdict_new();
+    qdict_put(args, "a", qint_from_int(66));
+    qdict_put(req, "arguments", args);
+
+    qdict_put_obj(req, "execute", QOBJECT(qstring_from_str("user_def_cmd")));
+
+    resp = qmp_dispatch(QOBJECT(req));
+    assert(resp != NULL);
+    assert(qdict_haskey(qobject_to_qdict(resp), "error"));
+
     qobject_decref(resp);
     QDECREF(req);
 }
scripts/qapi-commands.py +43 -15

101 lines not on this page · raw message

Signature · 1 line
2.9.0
#25 lore raw

PATCH v5 17/20 monitor: use qmp_dispatch()

In reply to Marc-André Lureau

Replace the old manual dispatch and validation code by the generic one provided by qapi common code.

Note that it is now possible to call the following commands that used to be disabled by compile-time conditionals:
- dump-skeys
- query-spice
- rtc-reset-reinjection
- query-gic-capabilities

Their fallback functions return an appropriate "feature disabled" error.

---
 monitor.c    | 326 +++++++----------------------------------------------------
 trace-events |   1 -
 2 files changed, 34 insertions(+), 293 deletions(-)
monitor.c +34 -292
index f07fc31..81926c7 100644
@@ -166,7 +166,6 @@ struct MonFdset {
 };
 
 typedef struct {
-    QObject *id;
     JSONMessageParser parser;
     /*
      * When a client connects, we're in capabilities negotiation mode.
@@ -229,8 +228,6 @@ static int mon_refcount;
 static mon_cmd_t mon_cmds[];
 static mon_cmd_t info_cmds[];
 
-static const mon_cmd_t qmp_cmds[];
-
 Monitor *cur_mon;
 
 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
@@ -401,49 +398,6 @@ static void monitor_json_emitter(Monitor *mon, const QObject *data)
     QDECREF(json);
 }
 
-static QDict *build_qmp_error_dict(Error *err)
-{
-    QObject *obj;
-
-    obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
-                             QapiErrorClass_lookup[error_get_class(err)],
-                             error_get_pretty(err));
-
-    return qobject_to_qdict(obj);
-}
-
-static void monitor_protocol_emitter(Monitor *mon, QObject *data,
-                                     Error *err)
-{
-    QDict *qmp;
-
-    trace_monitor_protocol_emitter(mon);
-
-    if (!err) {
-        /* success response */
-        qmp = qdict_new();
-        if (data) {
-            qobject_incref(data);
-            qdict_put_obj(qmp, "return", data);
-        } else {
-            /* return an empty QDict by default */
-            qdict_put(qmp, "return", qdict_new());
-        }
-    } else {
-        /* error response */
-        qmp = build_qmp_error_dict(err);
-    }
-
-    if (mon->qmp.id) {
-        qdict_put_obj(qmp, "id", mon->qmp.id);
-        mon->qmp.id = NULL;
-    }
-
-    monitor_json_emitter(mon, QOBJECT(qmp));
-    QDECREF(qmp);
-}
-
-
 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
     /* Limit guest-triggerable events to 1 per second */
     [QAPI_EVENT_RTC_CHANGE]        = { 1000 * SCALE_MS },
@@ -2180,11 +2134,6 @@ static mon_cmd_t mon_cmds[] = {
     { NULL, NULL, },
 };
 
-static const mon_cmd_t qmp_cmds[] = {
-#include "qmp-commands-old.h"
-    { /* NULL */ },
-};
-
 /*******************************************************************/
 
 static const char *pch;
@@ -2535,11 +2484,6 @@ static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
     return NULL;
 }
 
-static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
-{
-    return search_dispatch_table(qmp_cmds, cmdname);
-}
-
 /*
  * Parse command name from @cmdp according to command table @table.
  * If blank, return NULL.
@@ -3690,199 +3634,6 @@ static bool invalid_qmp_mode(const Monitor *mon, const char *cmd,
     return false;
 }
 
-/*
- * Argument validation rules:
- *
- * 1. The argument must exist in cmd_args qdict
- * 2. The argument type must be the expected one
- *
- * Special case: If the argument doesn't exist in cmd_args and
- *               the QMP_ACCEPT_UNKNOWNS flag is set, then the
- *               checking is skipped for it.
- */
-static void check_client_args_type(const QDict *client_args,
-                                   const QDict *cmd_args, int flags,
-                                   Error **errp)
-{
-    const QDictEntry *ent;
-
-    for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
-        QObject *obj;
-        QString *arg_type;
-        const QObject *client_arg = qdict_entry_value(ent);
-        const char *client_arg_name = qdict_entry_key(ent);
-
-        obj = qdict_get(cmd_args, client_arg_name);
-        if (!obj) {
-            if (flags & QMP_ACCEPT_UNKNOWNS) {
-                /* handler accepts unknowns */
-                continue;
-            }
-            /* client arg doesn't exist */
-            error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
-            return;
-        }
-
-        arg_type = qobject_to_qstring(obj);
-        assert(arg_type != NULL);
-
-        /* check if argument's type is correct */
-        switch (qstring_get_str(arg_type)[0]) {
-        case 'F':
-        case 'B':
-        case 's':
-            if (qobject_type(client_arg) != QTYPE_QSTRING) {
-                error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
-                           client_arg_name, "string");
-                return;
-            }
-        break;
-        case 'i':
-        case 'l':
-        case 'M':
-        case 'o':
-            if (qobject_type(client_arg) != QTYPE_QINT) {
-                error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
-                           client_arg_name, "int");
-                return;
-            }
-            break;
-        case 'T':
-            if (qobject_type(client_arg) != QTYPE_QINT &&
-                qobject_type(client_arg) != QTYPE_QFLOAT) {
-                error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
-                           client_arg_name, "number");
-                return;
-            }
-            break;
-        case 'b':
-        case '-':
-            if (qobject_type(client_arg) != QTYPE_QBOOL) {
-                error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
-                           client_arg_name, "bool");
-                return;
-            }
-            break;
-        case 'O':
-            assert(flags & QMP_ACCEPT_UNKNOWNS);
-            break;
-        case 'q':
-            /* Any QObject can be passed.  */
-            break;
-        case '/':
-        case '.':
-            /*
-             * These types are not supported by QMP and thus are not
-             * handled here. Fall through.
-             */
-        default:
-            abort();
-        }
-    }
-}
-
-/*
- * - Check if the client has passed all mandatory args
- * - Set special flags for argument validation
- */
-static void check_mandatory_args(const QDict *cmd_args,
-                                 const QDict *client_args, int *flags,
-                                 Error **errp)
-{
-    const QDictEntry *ent;
-
-    for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
-        const char *cmd_arg_name = qdict_entry_key(ent);
-        QString *type = qobject_to_qstring(qdict_entry_value(ent));
-        assert(type != NULL);
-
-        if (qstring_get_str(type)[0] == 'O') {
-            assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
-            *flags |= QMP_ACCEPT_UNKNOWNS;
-        } else if (qstring_get_str(type)[0] != '-' &&
-                   qstring_get_str(type)[1] != '?' &&
-                   !qdict_haskey(client_args, cmd_arg_name)) {
-            error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
-            return;
-        }
-    }
-}
-
-static QDict *qdict_from_args_type(const char *args_type)
-{
-    int i;
-    QDict *qdict;
-    QString *key, *type, *cur_qs;
-
-    assert(args_type != NULL);
-
-    qdict = qdict_new();
-
-    if (args_type == NULL || args_type[0] == '\0') {
-        /* no args, empty qdict */
-        goto out;
-    }
-
-    key = qstring_new();
-    type = qstring_new();
-
-    cur_qs = key;
-
-    for (i = 0;; i++) {
-        switch (args_type[i]) {
-            case ',':
-            case '\0':
-                qdict_put(qdict, qstring_get_str(key), type);
-                QDECREF(key);
-                if (args_type[i] == '\0') {
-                    goto out;
-                }
-                type = qstring_new(); /* qdict has ref */
-                cur_qs = key = qstring_new();
-                break;
-            case ':':
-                cur_qs = type;
-                break;
-            default:
-                qstring_append_chr(cur_qs, args_type[i]);
-                break;
-        }
-    }
-
-out:
-    return qdict;
-}
-
-/*
- * Client argument checking rules:
- *
- * 1. Client must provide all mandatory arguments
- * 2. Each argument provided by the client must be expected
- * 3. Each argument provided by the client must have the type expected
- *    by the command
- */
-static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
-                                  Error **errp)
-{
-    Error *err = NULL;
-    int flags;
-    QDict *cmd_args;
-
-    cmd_args = qdict_from_args_type(cmd->args_type);
-
-    flags = 0;
-    check_mandatory_args(cmd_args, client_args, &flags, &err);
-    if (err) {
-        goto out;
-    }
-
-    check_client_args_type(client_args, cmd_args, flags, &err);
-
-out:
-    error_propagate(errp, err);
-    QDECREF(cmd_args);
-}
-
 /*
  * Input object checking rules
  *
@@ -3941,67 +3692,58 @@ static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
 
 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
 {
-    Error *local_err = NULL;
-    QObject *obj, *data;
-    QDict *input, *args;
-    const mon_cmd_t *cmd;
-    QmpCommand *qcmd;
+    QObject *req, *rsp = NULL, *id = NULL;
+    QDict *qdict = NULL;
     const char *cmd_name;
     Monitor *mon = cur_mon;
+    Error *err = NULL;
 
-    args = input = NULL;
-    data = NULL;
-
-    obj = json_parser_parse(tokens, NULL);
-    if (!obj) {
-        // FIXME: should be triggered in json_parser_parse()
-        error_setg(&local_err, QERR_JSON_PARSING);
+    req = json_parser_parse_err(tokens, NULL, &err);
+    if (err || !req || qobject_type(req) != QTYPE_QDICT) {
+        if (!err) {
+            error_setg(&err, QERR_JSON_PARSING);
+        }
         goto err_out;
     }
 
-    input = qmp_check_input_obj(obj, &local_err);
-    if (!input) {
-        qobject_decref(obj);
+    qdict = qmp_check_input_obj(req, &err);
+    if (!qdict) {
         goto err_out;
     }
 
-    mon->qmp.id = qdict_get(input, "id");
-    qobject_incref(mon->qmp.id);
+    id = qdict_get(qdict, "id");
+    qobject_incref(id);
+    qdict_del(qdict, "id");
 
-    cmd_name = qdict_get_str(input, "execute");
+    cmd_name = qdict_get_str(qdict, "execute");
     trace_handle_qmp_command(mon, cmd_name);
-    cmd = qmp_find_cmd(cmd_name);
-    qcmd = qmp_find_command(cmd_name);
-    if (!qcmd || !cmd) {
-        error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
-                  "The command %s has not been found", cmd_name);
-        goto err_out;
-    }
-    if (invalid_qmp_mode(mon, cmd_name, &local_err)) {
+
+    if (invalid_qmp_mode(mon, cmd_name, &err)) {
         goto err_out;
     }
 
-    obj = qdict_get(input, "arguments");
-    if (!obj) {
-        args = qdict_new();
-    } else {
-        args = qobject_to_qdict(obj);
-        QINCREF(args);
-    }
+    rsp = qmp_dispatch(req);
 
-    qmp_check_client_args(cmd, args, &local_err);
-    if (local_err) {
-        goto err_out;
+err_out:
+    if (err) {
+        qdict = qdict_new();
+        qdict_put_obj(qdict, "error", qmp_build_error_object(err));
+        error_free(err);
+        rsp = QOBJECT(qdict);
     }
 
-    qcmd->fn(args, &data, &local_err);
+    if (rsp) {
+        if (id) {
+            qdict_put_obj(qobject_to_qdict(rsp), "id", id);
+            id = NULL;
+        }
 
-err_out:
-    monitor_protocol_emitter(mon, data, local_err);
-    qobject_decref(data);
-    error_free(local_err);
-    QDECREF(input);
-    QDECREF(args);
+        monitor_json_emitter(mon, rsp);
+    }
+
+    qobject_decref(id);
+    qobject_decref(rsp);
+    qobject_decref(req);
 }
 
 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
trace-events +0 -1
index 616cc52..8d59631 100644
@@ -98,7 +98,6 @@ qemu_co_mutex_unlock_return(void *mutex, void *self) "mutex %p self %p"
 
 # monitor.c
 handle_qmp_command(void *mon, const char *cmd_name) "mon %p cmd_name \"%s\""
-monitor_protocol_emitter(void *mon) "mon %p"
 monitor_protocol_event_handler(uint32_t event, void *qdict) "event=%d data=%p"
 monitor_protocol_event_emit(uint32_t event, void *data) "event=%d data=%p"
 monitor_protocol_event_queue(uint32_t event, void *qdict, uint64_t rate) "event=%d data=%p rate=%" PRId64
Signature · 1 line
2.9.0
#26 lore raw

Re: [Qemu-devel] [PATCH v5 17/20] monitor: use qmp_dispatch()

Hi

----- Original Message -----

Quoted 11 lines

Replace the old manual dispatch and validation code by the generic one provided by qapi common code.

Note that it is now possible to call the following commands that used to be disabled by compile-time conditionals:
- dump-skeys
- query-spice
- rtc-reset-reinjection
- query-gic-capabilities

Their fallback functions return an appropriate "feature disabled" error.

This is no longer valid, I dropped that comment.

Quoted 429 lines
---
 monitor.c    | 326
 +++++++----------------------------------------------------
 trace-events |   1 -
 2 files changed, 34 insertions(+), 293 deletions(-)
monitor.c +0 -46
index f07fc31..81926c7 100644
@@ -166,7 +166,6 @@ struct MonFdset {
 };
 
 typedef struct {
-    QObject *id;
     JSONMessageParser parser;
     /*
      * When a client connects, we're in capabilities negotiation mode.
@@ -229,8 +228,6 @@ static int mon_refcount;
 static mon_cmd_t mon_cmds[];
 static mon_cmd_t info_cmds[];
 
-static const mon_cmd_t qmp_cmds[];
-
 Monitor *cur_mon;
 
 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
@@ -401,49 +398,6 @@ static void monitor_json_emitter(Monitor *mon, const
 QObject *data)
     QDECREF(json);
 }
 
-static QDict *build_qmp_error_dict(Error *err)
-{
-    QObject *obj;
-
-    obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
-                             QapiErrorClass_lookup[error_get_class(err)],
-                             error_get_pretty(err));
-
-    return qobject_to_qdict(obj);
-}
-
-static void monitor_protocol_emitter(Monitor *mon, QObject *data,
-                                     Error *err)
-{
-    QDict *qmp;
-
-    trace_monitor_protocol_emitter(mon);
-
-    if (!err) {
-        /* success response */
-        qmp = qdict_new();
-        if (data) {
-            qobject_incref(data);
-            qdict_put_obj(qmp, "return", data);
-        } else {
-            /* return an empty QDict by default */
-            qdict_put(qmp, "return", qdict_new());
-        }
-    } else {
-        /* error response */
-        qmp = build_qmp_error_dict(err);
-    }
-
-    if (mon->qmp.id) {
-        qdict_put_obj(qmp, "id", mon->qmp.id);
-        mon->qmp.id = NULL;
-    }
-
-    monitor_json_emitter(mon, QOBJECT(qmp));
-    QDECREF(qmp);
-}
-
-
 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
     /* Limit guest-triggerable events to 1 per second */
     [QAPI_EVENT_RTC_CHANGE]        = { 1000 * SCALE_MS },
monitor.c +0 -10
@@ -2180,11 +2134,6 @@ static mon_cmd_t mon_cmds[] = {
     { NULL, NULL, },
 };
 
-static const mon_cmd_t qmp_cmds[] = {
-#include "qmp-commands-old.h"
-    { /* NULL */ },
-};
-
 /*******************************************************************/
 
 static const char *pch;
@@ -2535,11 +2484,6 @@ static const mon_cmd_t *search_dispatch_table(const
 mon_cmd_t *disp_table,
     return NULL;
 }
 
-static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
-{
-    return search_dispatch_table(qmp_cmds, cmdname);
-}
-
 /*
  * Parse command name from @cmdp according to command table @table.

* If blank, return NULL.

monitor.c +0 -193
@@ -3690,199 +3634,6 @@ static bool invalid_qmp_mode(const Monitor *mon,
 const char *cmd,
     return false;
 }
 
-/*
- * Argument validation rules:
- *
- * 1. The argument must exist in cmd_args qdict
- * 2. The argument type must be the expected one
- *
- * Special case: If the argument doesn't exist in cmd_args and
- *               the QMP_ACCEPT_UNKNOWNS flag is set, then the
- *               checking is skipped for it.
- */
-static void check_client_args_type(const QDict *client_args,
-                                   const QDict *cmd_args, int flags,
-                                   Error **errp)
-{
-    const QDictEntry *ent;
-
-    for (ent = qdict_first(client_args); ent;ent =
 qdict_next(client_args,ent)){
-        QObject *obj;
-        QString *arg_type;
-        const QObject *client_arg = qdict_entry_value(ent);
-        const char *client_arg_name = qdict_entry_key(ent);
-
-        obj = qdict_get(cmd_args, client_arg_name);
-        if (!obj) {
-            if (flags & QMP_ACCEPT_UNKNOWNS) {
-                /* handler accepts unknowns */
-                continue;
-            }
-            /* client arg doesn't exist */
-            error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
-            return;
-        }
-
-        arg_type = qobject_to_qstring(obj);
-        assert(arg_type != NULL);
-
-        /* check if argument's type is correct */
-        switch (qstring_get_str(arg_type)[0]) {
-        case 'F':
-        case 'B':
-        case 's':
-            if (qobject_type(client_arg) != QTYPE_QSTRING) {
-                error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
-                           client_arg_name, "string");
-                return;
-            }
-        break;
-        case 'i':
-        case 'l':
-        case 'M':
-        case 'o':
-            if (qobject_type(client_arg) != QTYPE_QINT) {
-                error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
-                           client_arg_name, "int");
-                return;
-            }
-            break;
-        case 'T':
-            if (qobject_type(client_arg) != QTYPE_QINT &&
-                qobject_type(client_arg) != QTYPE_QFLOAT) {
-                error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
-                           client_arg_name, "number");
-                return;
-            }
-            break;
-        case 'b':
-        case '-':
-            if (qobject_type(client_arg) != QTYPE_QBOOL) {
-                error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
-                           client_arg_name, "bool");
-                return;
-            }
-            break;
-        case 'O':
-            assert(flags & QMP_ACCEPT_UNKNOWNS);
-            break;
-        case 'q':
-            /* Any QObject can be passed.  */
-            break;
-        case '/':
-        case '.':
-            /*
-             * These types are not supported by QMP and thus are not
-             * handled here. Fall through.
-             */
-        default:
-            abort();
-        }
-    }
-}
-
-/*
- * - Check if the client has passed all mandatory args
- * - Set special flags for argument validation
- */
-static void check_mandatory_args(const QDict *cmd_args,
-                                 const QDict *client_args, int *flags,
-                                 Error **errp)
-{
-    const QDictEntry *ent;
-
-    for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent))
 {
-        const char *cmd_arg_name = qdict_entry_key(ent);
-        QString *type = qobject_to_qstring(qdict_entry_value(ent));
-        assert(type != NULL);
-
-        if (qstring_get_str(type)[0] == 'O') {
-            assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
-            *flags |= QMP_ACCEPT_UNKNOWNS;
-        } else if (qstring_get_str(type)[0] != '-' &&
-                   qstring_get_str(type)[1] != '?' &&
-                   !qdict_haskey(client_args, cmd_arg_name)) {
-            error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
-            return;
-        }
-    }
-}
-
-static QDict *qdict_from_args_type(const char *args_type)
-{
-    int i;
-    QDict *qdict;
-    QString *key, *type, *cur_qs;
-
-    assert(args_type != NULL);
-
-    qdict = qdict_new();
-
-    if (args_type == NULL || args_type[0] == '\0') {
-        /* no args, empty qdict */
-        goto out;
-    }
-
-    key = qstring_new();
-    type = qstring_new();
-
-    cur_qs = key;
-
-    for (i = 0;; i++) {
-        switch (args_type[i]) {
-            case ',':
-            case '\0':
-                qdict_put(qdict, qstring_get_str(key), type);
-                QDECREF(key);
-                if (args_type[i] == '\0') {
-                    goto out;
-                }
-                type = qstring_new(); /* qdict has ref */
-                cur_qs = key = qstring_new();
-                break;
-            case ':':
-                cur_qs = type;
-                break;
-            default:
-                qstring_append_chr(cur_qs, args_type[i]);
-                break;
-        }
-    }
-
-out:
-    return qdict;
-}
-
-/*
- * Client argument checking rules:
- *
- * 1. Client must provide all mandatory arguments
- * 2. Each argument provided by the client must be expected
- * 3. Each argument provided by the client must have the type expected
- *    by the command
- */
-static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
-                                  Error **errp)
-{
-    Error *err = NULL;
-    int flags;
-    QDict *cmd_args;
-
-    cmd_args = qdict_from_args_type(cmd->args_type);
-
-    flags = 0;
-    check_mandatory_args(cmd_args, client_args, &flags, &err);
-    if (err) {
-        goto out;
-    }
-
-    check_client_args_type(client_args, cmd_args, flags, &err);
-
-out:
-    error_propagate(errp, err);
-    QDECREF(cmd_args);
-}
-

/*
* Input object checking rules
*

monitor.c +34 -43
@@ -3941,67 +3692,58 @@ static QDict *qmp_check_input_obj(QObject *input_obj,
 Error **errp)
 
 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
 {
-    Error *local_err = NULL;
-    QObject *obj, *data;
-    QDict *input, *args;
-    const mon_cmd_t *cmd;
-    QmpCommand *qcmd;
+    QObject *req, *rsp = NULL, *id = NULL;
+    QDict *qdict = NULL;
     const char *cmd_name;
     Monitor *mon = cur_mon;
+    Error *err = NULL;
 
-    args = input = NULL;
-    data = NULL;
-
-    obj = json_parser_parse(tokens, NULL);
-    if (!obj) {
-        // FIXME: should be triggered in json_parser_parse()
-        error_setg(&local_err, QERR_JSON_PARSING);
+    req = json_parser_parse_err(tokens, NULL, &err);
+    if (err || !req || qobject_type(req) != QTYPE_QDICT) {
+        if (!err) {
+            error_setg(&err, QERR_JSON_PARSING);
+        }
         goto err_out;
     }
 
-    input = qmp_check_input_obj(obj, &local_err);
-    if (!input) {
-        qobject_decref(obj);
+    qdict = qmp_check_input_obj(req, &err);
+    if (!qdict) {
         goto err_out;
     }
 
-    mon->qmp.id = qdict_get(input, "id");
-    qobject_incref(mon->qmp.id);
+    id = qdict_get(qdict, "id");
+    qobject_incref(id);
+    qdict_del(qdict, "id");
 
-    cmd_name = qdict_get_str(input, "execute");
+    cmd_name = qdict_get_str(qdict, "execute");
     trace_handle_qmp_command(mon, cmd_name);
-    cmd = qmp_find_cmd(cmd_name);
-    qcmd = qmp_find_command(cmd_name);
-    if (!qcmd || !cmd) {
-        error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
-                  "The command %s has not been found", cmd_name);
-        goto err_out;
-    }
-    if (invalid_qmp_mode(mon, cmd_name, &local_err)) {
+
+    if (invalid_qmp_mode(mon, cmd_name, &err)) {
         goto err_out;
     }
 
-    obj = qdict_get(input, "arguments");
-    if (!obj) {
-        args = qdict_new();
-    } else {
-        args = qobject_to_qdict(obj);
-        QINCREF(args);
-    }
+    rsp = qmp_dispatch(req);
 
-    qmp_check_client_args(cmd, args, &local_err);
-    if (local_err) {
-        goto err_out;
+err_out:
+    if (err) {
+        qdict = qdict_new();
+        qdict_put_obj(qdict, "error", qmp_build_error_object(err));
+        error_free(err);
+        rsp = QOBJECT(qdict);
     }
 
-    qcmd->fn(args, &data, &local_err);
+    if (rsp) {
+        if (id) {
+            qdict_put_obj(qobject_to_qdict(rsp), "id", id);
+            id = NULL;
+        }
 
-err_out:
-    monitor_protocol_emitter(mon, data, local_err);
-    qobject_decref(data);
-    error_free(local_err);
-    QDECREF(input);
-    QDECREF(args);
+        monitor_json_emitter(mon, rsp);
+    }
+
+    qobject_decref(id);
+    qobject_decref(rsp);
+    qobject_decref(req);
 }
 

static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)

trace-events +0 -0
index 616cc52..8d59631 100644
@@ -98,7 +98,6 @@ qemu_co_mutex_unlock_return(void *mutex, void *self) "mutex

%p self %p"

 # monitor.c
 handle_qmp_command(void *mon, const char *cmd_name) "mon %p cmd_name \"%s\""
-monitor_protocol_emitter(void *mon) "mon %p"
 monitor_protocol_event_handler(uint32_t event, void *qdict) "event=%d
 data=%p"
 monitor_protocol_event_emit(uint32_t event, void *data) "event=%d data=%p"
 monitor_protocol_event_queue(uint32_t event, void *qdict, uint64_t rate)
 "event=%d data=%p rate=%" PRId64
--
2.9.0
#27 lore raw

PATCH v5 18/20 build-sys: remove qmp-commands-old.h

In reply to Marc-André Lureau
---
 Makefile.target | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
Makefile.target +2 -5
index 0ba50ae..3b1f59f 100644
@@ -157,7 +157,7 @@ else
 obj-y += hw/$(TARGET_BASE_ARCH)/
 endif
 
-GENERATED_HEADERS += hmp-commands.h hmp-commands-info.h qmp-commands-old.h
+GENERATED_HEADERS += hmp-commands.h hmp-commands-info.h
 GENERATED_HEADERS += qmp-introspect.h
 GENERATED_SOURCES += qmp-introspect.c qmp-marshal.c qapi-event.c
 qapi-hconfig = ../config-host.h config-target.h
@@ -234,13 +234,10 @@ hmp-commands.h: $(SRC_PATH)/hmp-commands.hx $(SRC_PATH)/scripts/hxtool
 hmp-commands-info.h: $(SRC_PATH)/hmp-commands-info.hx $(SRC_PATH)/scripts/hxtool
 	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -h < $< > $@,"  GEN   $(TARGET_DIR)$@")
 
-qmp-commands-old.h: $(SRC_PATH)/qmp-commands.hx $(SRC_PATH)/scripts/hxtool
-	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -h < $< > $@,"  GEN   $(TARGET_DIR)$@")
-
 clean:
 	rm -f *.a *~ $(PROGS)
 	rm -f $(shell find . -name '*.[od]')
-	rm -f hmp-commands.h qmp-commands-old.h gdbstub-xml.c
+	rm -f hmp-commands.h gdbstub-xml.c
 ifdef CONFIG_TRACE_SYSTEMTAP
 	rm -f *.stp
 endif
Signature · 1 line
2.9.0
#28 lore raw

PATCH v5 19/20 qmp-commands.hx: fix some styling

In reply to Marc-André Lureau

Add some missing lines, remove superflous @ in command name, remove trailing spaces.

---
 qmp-commands.hx | 34 ++++++++++++++++++----------------
 1 file changed, 18 insertions(+), 16 deletions(-)
qmp-commands.hx +18 -16
index f395f47..2e0d1e6 100644
@@ -91,7 +91,7 @@ eject
 
 Eject a removable medium.
 
-Arguments: 
+Arguments:
 
 - force: force ejection (json-bool, optional)
 - device: device name (json-string)
@@ -1389,7 +1389,6 @@ EQMP
     },
 
 SQMP
-
 block-dirty-bitmap-add
 ----------------------
 Since 2.4
@@ -1416,7 +1415,6 @@ EQMP
     },
 
 SQMP
-
 block-dirty-bitmap-remove
 -------------------------
 Since 2.4
@@ -1443,7 +1441,6 @@ EQMP
     },
 
 SQMP
-
 block-dirty-bitmap-clear
 ------------------------
 Since 2.4
@@ -2166,7 +2163,7 @@ human-monitor-command
 
 Execute a Human Monitor command.
 
-Arguments: 
+Arguments:
 
 - command-line: the command name and its arguments, just like the
                 Human Monitor's shell (json-string)
@@ -2978,7 +2975,7 @@ Example:
                   },
                   "function":0,
                   "regions":[
-   
+
                   ]
                },
                {
@@ -2995,7 +2992,7 @@ Example:
                   },
                   "function":0,
                   "regions":[
-   
+
                   ]
                },
                {
@@ -3457,8 +3454,8 @@ The main json-object contains the following:
 - "setup-time" amount of setup time in milliseconds _before_ the
                iterations begin but _after_ the QMP command is issued.
                This is designed to provide an accounting of any activities
-               (such as RDMA pinning) which may be expensive, but do not 
-               actually occur during the iterative migration rounds 
+               (such as RDMA pinning) which may be expensive, but do not
+               actually occur during the iterative migration rounds
                themselves. (json-int)
 - "downtime": only present when migration has finished correctly
               total amount in ms for downtime that happened (json-int)
@@ -4369,8 +4366,8 @@ EQMP
     },
 
 SQMP
-@query-named-block-nodes
-------------------------
+query-named-block-nodes
+-----------------------
 
 Return a list of BlockDeviceInfo for all the named block driver nodes
 
@@ -4519,7 +4516,7 @@ EQMP
     },
 
 SQMP
-@query-memory-devices
+query-memory-devices
 --------------------
 
 Return a list of memory devices.
@@ -4537,6 +4534,7 @@ Example:
                         "slot": 0},
                    "type": "dimm"
                  } ] }
+
 EQMP
 
     {
@@ -4545,8 +4543,8 @@ EQMP
     },
 
 SQMP
-@query-acpi-ospm-status
---------------------
+query-acpi-ospm-status
+----------------------
 
 Return list of ACPIOSTInfo for devices that support status reporting
 via ACPI _OST method.
@@ -4558,6 +4556,7 @@ Example:
                  { "slot": "2", "slot-type": "DIMM", "source": 0, "status": 0},
                  { "slot": "3", "slot-type": "DIMM", "source": 0, "status": 0}
    ]}
+
 EQMP
 
 #if defined TARGET_I386
@@ -4579,6 +4578,7 @@ Example:
 
 -> { "execute": "rtc-reset-reinjection" }
 <- { "return": {} }
+
 EQMP
 
     {
@@ -4610,6 +4610,7 @@ Example:
 
 -> { "execute": "trace-event-get-state", "arguments": { "name": "qemu_memalign" } }
 <- { "return": [ { "name": "qemu_memalign", "state": "disabled" } ] }
+
 EQMP
 
     {
@@ -4644,6 +4645,7 @@ Example:
 
 -> { "execute": "trace-event-set-state", "arguments": { "name": "qemu_memalign", "enable": "true" } }
 <- { "return": {} }
+
 EQMP
 
     {
@@ -4652,8 +4654,8 @@ EQMP
     },
 
 SQMP
-@input-send-event
------------------
+input-send-event
+----------------
 
 Send input event to guest.
 
Signature · 1 line
2.9.0
#29 lore raw

PATCH v5 20/20 Replace qmp-commands.hx by doc/qmp-commands.txt

In reply to Marc-André Lureau

The only remaining function of qmp-commands.hx is to let us generate qmp-commands.txt from it. Replace qmp-commands.hx by qmp-commands.txt.

We intend to move the documentation into the QAPI schema and generate qapi-commands.txt from it, but not right now.

---
 Makefile                                 |    6 +-
 .gitignore                               |    1 -
 MAINTAINERS                              |    1 -
 docs/qapi-code-gen.txt                   |    6 +-
 qmp-commands.hx => docs/qmp-commands.txt | 1112 ------------------------------
 docs/writing-qmp-commands.txt            |   38 -
 6 files changed, 4 insertions(+), 1160 deletions(-)
 rename qmp-commands.hx => docs/qmp-commands.txt (87%)
Makefile +1 -5
index fc2e53a..dade87c 100644
@@ -91,7 +91,6 @@ HELPERS-$(CONFIG_LINUX) = qemu-bridge-helper$(EXESUF)
 
 ifdef BUILD_DOCS
 DOCS=qemu-doc.html qemu-tech.html qemu.1 qemu-img.1 qemu-nbd.8 qemu-ga.8
-DOCS+=qmp-commands.txt
 ifdef CONFIG_VIRTFS
 DOCS+=fsdev/virtfs-proxy-helper.1
 endif
@@ -421,7 +420,7 @@ endif
 install-doc: $(DOCS)
 	$(INSTALL_DIR) "$(DESTDIR)$(qemu_docdir)"
 	$(INSTALL_DATA) qemu-doc.html  qemu-tech.html "$(DESTDIR)$(qemu_docdir)"
-	$(INSTALL_DATA) qmp-commands.txt "$(DESTDIR)$(qemu_docdir)"
+	$(INSTALL_DATA) docs/qmp-commands.txt "$(DESTDIR)$(qemu_docdir)"
 ifdef CONFIG_POSIX
 	$(INSTALL_DIR) "$(DESTDIR)$(mandir)/man1"
 	$(INSTALL_DATA) qemu.1 "$(DESTDIR)$(mandir)/man1"
@@ -544,9 +543,6 @@ qemu-monitor.texi: $(SRC_PATH)/hmp-commands.hx $(SRC_PATH)/scripts/hxtool
 qemu-monitor-info.texi: $(SRC_PATH)/hmp-commands-info.hx $(SRC_PATH)/scripts/hxtool
 	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -t < $< > $@,"  GEN   $@")
 
-qmp-commands.txt: $(SRC_PATH)/qmp-commands.hx $(SRC_PATH)/scripts/hxtool
-	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -q < $< > $@,"  GEN   $@")
-
 qemu-img-cmds.texi: $(SRC_PATH)/qemu-img-cmds.hx $(SRC_PATH)/scripts/hxtool
 	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -t < $< > $@,"  GEN   $@")
 
.gitignore +0 -1
index 88ec249..0ab8263 100644
@@ -53,7 +53,6 @@
 /qemu-bridge-helper
 /qemu-monitor.texi
 /qemu-monitor-info.texi
-/qmp-commands.txt
 /vscclient
 /fsdev/virtfs-proxy-helper
 *.[1-9]
MAINTAINERS +0 -1
index b6fb84e..84bdc46 100644
@@ -1237,7 +1237,6 @@ M: Markus Armbruster <[email protected]>
 S: Supported
 F: qmp.c
 F: monitor.c
-F: qmp-commands.hx
 F: docs/*qmp-*
 F: scripts/qmp/
 T: git git://repo.or.cz/qemu/armbru.git qapi-next
docs/qapi-code-gen.txt +3 -3
index de298dc..5d4c2cd 100644
@@ -964,9 +964,9 @@ Example:
 
 Used to generate the marshaling/dispatch functions for the commands
 defined in the schema. The generated code implements
-qmp_marshal_COMMAND() (mentioned in qmp-commands.hx, and registered
-automatically), and declares qmp_COMMAND() that the user must
-implement.  The following files are generated:
+qmp_marshal_COMMAND() (registered automatically), and declares
+qmp_COMMAND() that the user must implement.  The following files are
+generated:
 
 $(prefix)qmp-marshal.c: command marshal/dispatch functions for each
                         QMP command defined in the schema. Functions
docs/qmp-commands.txt renamed from qmp-commands.hx +0 -1112

1,854 lines not on this page · raw message

docs/writing-qmp-commands.txt +0 -38
index c425393..cfa6fe7 100644
@@ -119,16 +119,6 @@ There are a few things to be noticed:
 5. Printing to the terminal is discouraged for QMP commands, we do it here
    because it's the easiest way to demonstrate a QMP command
 
-Now a little hack is needed. As we're still using the old QMP server we need
-to add the new command to its internal dispatch table. This step won't be
-required in the near future. Open the qmp-commands.hx file and add the
-following at the bottom:
-
-    {
-        .name       = "hello-world",
-        .args_type  = "",
-    },
-
 You're done. Now build qemu, run it as suggested in the "Testing" section,
 and then type the following QMP command:
 
@@ -173,20 +163,6 @@ There are two important details to be noticed:
 2. The C implementation signature must follow the schema's argument ordering,
    which is defined by the "data" member
 
-The last step is to update the qmp-commands.hx file:
-
-    {
-        .name       = "hello-world",
-        .args_type  = "message:s?",
-    },
-
-Notice that the "args_type" member got our "message" argument. The character
-"s" stands for "string" and "?" means it's optional. This too must be ordered
-according to the C implementation and schema file. You can look for more
-examples in the qmp-commands.hx file if you need to define more arguments.
-
-Again, this step won't be required in the future.
-
 Time to test our new version of the "hello-world" command. Build qemu, run it as
 described in the "Testing" section and then send two commands:
 
@@ -452,13 +428,6 @@ There are a number of things to be noticed:
 6. You have to include the "qmp-commands.h" header file in qemu-timer.c,
    otherwise qemu won't build
 
-The last step is to add the corresponding entry in the qmp-commands.hx file:
-
-    {
-        .name       = "query-alarm-clock",
-        .args_type  = "",
-    },
-
 Time to test the new command. Build qemu, run it as described in the "Testing"
 section and try this:
 
@@ -597,13 +566,6 @@ iteration of the loop. That's because the alarm timer method in use is the
 first element of the alarm_timers array. Also notice that QAPI lists are handled
 by hand and we return the head of the list.
 
-To test this you have to add the corresponding qmp-commands.hx entry:
-
-    {
-        .name       = "query-alarm-methods",
-        .args_type  = "",
-    },
-
 Now Build qemu, run it as explained in the "Testing" section and try our new
 command:
 
Signature · 1 line
2.9.0
#30 lore raw

Re: [Qemu-devel] [PATCH v5 20/20] Replace qmp-commands.hx by doc/qmp-commands.txt

s,doc/,docs/ in subject. Can touch up on commit.