Skip to contentSkip to conversation

qapi implicit types (continuing the qapi cleanup theme)

PATCH In review Eric Blake 3 participants 27 messages Feb 20, 2016 – Feb 22, 2016

Subsystems (3)
lore
Share & tools
lore

Eric Blake

author
#0 lore raw

cover qapi implicit types (continuing the qapi cleanup theme)

I don't know what letter and or number to assign this batch, so I'll just call it v1 of 'qapi-implicit' :) It does, however, incorporate reviews on several patches that were in subset E v9 [1], and some that were posted (but not yet reviewed) in subset F v6 [2]; the remaining patches are new but provide the promised work at cleaning up the generated code for simple unions, so that their implicit wrapper type is now unboxed without any special-case handling.

1-7: general cleanups, including a bug fix in patch 1 8: add the framework for doing inline visits of implicit types 9-11: add is_empty() helper, including a bug fix in patch 10 12-13: use the framework for simple unions
14: use the framework for anonymous bases of flat unions 15-17: tail-end cleanups

[1] https://lists.gnu.org/archive/html/qemu-devel/2016-01/msg03504.html
[2] https://lists.gnu.org/archive/html/qemu-devel/2015-12/msg04389.html

Based on current qemu.git master.

Also available as a tag at this location:
git fetch git://repo.or.cz/qemu/ericb.git qapi-implicitv1

and will soon be part of my branch at:
http://repo.or.cz/qemu/ericb.git/shortlog/refs/heads/qapi

Backport diff based on patches that were previously posted:

001/17:[down] 'chardev: Properly initialize ChardevCommon components' 002/17:[down] 'chardev: Shorten references into ChardevBackend' 003/17:[down] 'util: Shorten references into SocketAddress' 004/17:[down] 'ui: Shorten references into InputEvent' 005/17:[----] [--] 'qapi: Avoid use of 'data' member of qapi unions' 006/17:[down] 'chardev: Drop useless ChardevDummy type' 007/17:[0002] [FC] 'qapi: Drop useless 'data' member of unions' 008/17:[down] 'qapi-visit: Factor out gen_visit_fields_call()' 009/17:[0003] [FC] 'qapi: Add type.is_empty() helper' 010/17:[----] [--] 'qapi: Fix command with named empty argument type' 011/17:[down] 'qapi-visit: Simplify visit of empty branch in union' 012/17:[down] 'qapi: Don't special-case simple union wrappers' 013/17:[down] 'qapi-visit: Move error check into gen_visit_fields_call()' 014/17:[0052] [FC] 'qapi: Allow anonymous base for flat union' 015/17:[----] [--] 'qapi: Use anonymous base in SchemaInfo' 016/17:[----] [--] 'qapi: Use anonymous base in CpuInfo' 017/17:[down] 'qapi: Make c_type() more OO-like'

Remaining qapi cleanups that are still on my queue, and have had patches posted to list:
- visitor cleanup: add documentation, optimize list visits, add visit_type_null(), prevent leaked memory after visit_type_FOO (reviewed as tail of subset E v9) [3]
- add a JSON output visitor (unreviewed at v2) [4]
- support boxed parameters for events and commands, use it to introspect netdev_add (unreviewed subset F, at v6) [5]

[3] https://lists.gnu.org/archive/html/qemu-devel/2016-01/msg03504.html
[4] https://lists.gnu.org/archive/html/qemu-devel/2015-12/msg03929.html
[5] https://lists.gnu.org/archive/html/qemu-devel/2015-12/msg04389.html

We'll see how much of that actually makes it in by 2.6 soft freeze.

Eric Blake (17):
chardev: Properly initialize ChardevCommon components
chardev: Shorten references into ChardevBackend
util: Shorten references into SocketAddress
ui: Shorten references into InputEvent
qapi: Avoid use of 'data' member of qapi unions
chardev: Drop useless ChardevDummy type
qapi: Drop useless 'data' member of unions
qapi-visit: Factor out gen_visit_fields_call()
qapi: Add type.is_empty() helper
qapi: Fix command with named empty argument type
qapi-visit: Simplify visit of empty branch in union
qapi: Don't special-case simple union wrappers
qapi-visit: Move error check into gen_visit_fields_call()
qapi: Allow anonymous base for flat union
qapi: Use anonymous base in SchemaInfo
qapi: Use anonymous base in CpuInfo
qapi: Make c_type() more OO-like

 scripts/qapi.py                            |  66 ++++++---
 scripts/qapi-commands.py                   |   6 +-
 scripts/qapi-event.py                      |   7 +-
 scripts/qapi-types.py                      |  45 +++---
 scripts/qapi-visit.py                      |  55 +++----
 include/sysemu/char.h                      |  10 ++
 backends/baum.c                            |   2 +-
 backends/msmouse.c                         |   2 +-
 block/nbd.c                                |  16 ++-
 block/qcow2.c                              |   6 +-
 block/vmdk.c                               |   8 +-
 blockdev.c                                 |  49 ++++---
 hmp.c                                      |   8 +-
 hw/char/escc.c                             |  12 +-
 hw/input/hid.c                             |  36 +++--
 hw/input/ps2.c                             |  27 ++--
 hw/input/virtio-input-hid.c                |  33 +++--
 hw/mem/pc-dimm.c                           |   4 +-
 net/dump.c                                 |   2 +-
 net/hub.c                                  |   2 +-
 net/l2tpv3.c                               |   2 +-
 net/net.c                                  |   4 +-
 net/netmap.c                               |   2 +-
 net/slirp.c                                |   2 +-
 net/socket.c                               |   2 +-
 net/tap.c                                  |   4 +-
 net/vhost-user.c                           |   2 +-
 numa.c                                     |   4 +-
 qemu-char.c                                | 223 ++++++++++++++++-------------
 qemu-nbd.c                                 |  13 +-
 replay/replay-input.c                      |  63 ++++----
 spice-qemu-char.c                          |  22 +--
 tests/test-io-channel-socket.c             |  58 ++++----
 tests/test-qmp-commands.c                  |   7 +-
 tests/test-qmp-input-visitor.c             |  25 ++--
 tests/test-qmp-output-visitor.c            |  24 ++--
 tpm.c                                      |   2 +-
 ui/console.c                               |  22 +--
 ui/input-keymap.c                          |  10 +-
 ui/input-legacy.c                          |  26 ++--
 ui/input.c                                 |  72 +++++-----
 ui/vnc-auth-sasl.c                         |   3 +-
 ui/vnc.c                                   |  62 ++++----
 util/qemu-sockets.c                        |  44 +++---
 docs/qapi-code-gen.txt                     |  28 ++--
 qapi-schema.json                           |  35 ++---
 qapi/introspect.json                       |  12 +-
 tests/Makefile                             |   1 -
 tests/qapi-schema/flat-union-bad-base.err  |   2 +-
 tests/qapi-schema/flat-union-bad-base.json |   5 +-
 tests/qapi-schema/qapi-schema-test.json    |  10 +-
 tests/qapi-schema/qapi-schema-test.out     |  15 +-
 tests/qapi-schema/union-clash-data.err     |   0
 tests/qapi-schema/union-clash-data.exit    |   1 -
 tests/qapi-schema/union-clash-data.json    |   7 -
 tests/qapi-schema/union-clash-data.out     |   9 --
 56 files changed, 655 insertions(+), 564 deletions(-)
 delete mode 100644 tests/qapi-schema/union-clash-data.err
 delete mode 100644 tests/qapi-schema/union-clash-data.exit
 delete mode 100644 tests/qapi-schema/union-clash-data.json
 delete mode 100644 tests/qapi-schema/union-clash-data.out
Signature · 1 line
2.5.0
author
#1 lore raw

PATCH 1/17 chardev: Properly initialize ChardevCommon components

Commit d0d7708b forgot to parse logging for spice chardevs and virtual consoles. This requires making qemu_chr_parse_common() non-static. While at it, use a temporary variable to make the code shorter, as well as reduce the churn when a later patch alters the layout of simple unions.

CC Daniel P. Berrange <[email protected]>
---
 include/sysemu/char.h | 10 ++++++++++
 qemu-char.c           |  2 +-
 spice-qemu-char.c     | 12 ++++++++----
 ui/console.c          | 20 +++++++++++---------
 4 files changed, 30 insertions(+), 14 deletions(-)
include/sysemu/char.h +10 -0
index e035d1c..e46884f 100644
@@ -115,6 +115,16 @@ CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
                                     Error **errp);
 
 /**
+ * @qemu_chr_parse_common:
+ *
+ * Parse the common options available to all character backends.
+ *
+ * @opts the options that still need parsing
+ * @backend a new backend
+ */
+void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend);
+
+/**
  * @qemu_chr_new:
  *
  * Create a new character backend from a URI.
qemu-char.c +1 -1
index ad11b75..fc8ffda 100644
@@ -3490,7 +3490,7 @@ fail:
     return NULL;
 }
 
-static void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
+void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
 {
     const char *logfile = qemu_opt_get(opts, "logfile");
 
spice-qemu-char.c +8 -4
index 7c1f438..21885c5 100644
@@ -366,26 +366,30 @@ static void qemu_chr_parse_spice_vmc(QemuOpts *opts, ChardevBackend *backend,
                                      Error **errp)
 {
     const char *name = qemu_opt_get(opts, "name");
+    ChardevSpiceChannel *spicevmc;
 
     if (name == NULL) {
         error_setg(errp, "chardev: spice channel: no name given");
         return;
     }
-    backend->u.spicevmc = g_new0(ChardevSpiceChannel, 1);
-    backend->u.spicevmc->type = g_strdup(name);
+    spicevmc = backend->u.spicevmc = g_new0(ChardevSpiceChannel, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevSpiceChannel_base(spicevmc));
+    spicevmc->type = g_strdup(name);
 }
 
 static void qemu_chr_parse_spice_port(QemuOpts *opts, ChardevBackend *backend,
                                       Error **errp)
 {
     const char *name = qemu_opt_get(opts, "name");
+    ChardevSpicePort *spiceport;
 
     if (name == NULL) {
         error_setg(errp, "chardev: spice port: no name given");
         return;
     }
-    backend->u.spiceport = g_new0(ChardevSpicePort, 1);
-    backend->u.spiceport->fqdn = g_strdup(name);
+    spiceport = backend->u.spiceport = g_new0(ChardevSpicePort, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevSpicePort_base(spiceport));
+    spiceport->fqdn = g_strdup(name);
 }
 
 static void register_types(void)
ui/console.c +11 -9
index b739ae9..7db0fd2 100644
@@ -2060,31 +2060,33 @@ static void qemu_chr_parse_vc(QemuOpts *opts, ChardevBackend *backend,
                               Error **errp)
 {
     int val;
+    ChardevVC *vc;
 
-    backend->u.vc = g_new0(ChardevVC, 1);
+    vc = backend->u.vc = g_new0(ChardevVC, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevVC_base(vc));
 
     val = qemu_opt_get_number(opts, "width", 0);
     if (val != 0) {
-        backend->u.vc->has_width = true;
-        backend->u.vc->width = val;
+        vc->has_width = true;
+        vc->width = val;
     }
 
     val = qemu_opt_get_number(opts, "height", 0);
     if (val != 0) {
-        backend->u.vc->has_height = true;
-        backend->u.vc->height = val;
+        vc->has_height = true;
+        vc->height = val;
     }
 
     val = qemu_opt_get_number(opts, "cols", 0);
     if (val != 0) {
-        backend->u.vc->has_cols = true;
-        backend->u.vc->cols = val;
+        vc->has_cols = true;
+        vc->cols = val;
     }
 
     val = qemu_opt_get_number(opts, "rows", 0);
     if (val != 0) {
-        backend->u.vc->has_rows = true;
-        backend->u.vc->rows = val;
+        vc->has_rows = true;
+        vc->rows = val;
     }
 }
 
Signature · 1 line
2.5.0
Reviewed-by on v1 1/17
#2 lore raw

Re: [Qemu-devel] [PATCH 01/17] chardev: Properly initialize ChardevCommon components

Quoted 6 lines · Eric Blake

Commit d0d7708b forgot to parse logging for spice chardevs and virtual consoles. This requires making qemu_chr_parse_common() non-static. While at it, use a temporary variable to make the code shorter, as well as reduce the churn when a later patch alters the layout of simple unions.

Quoted 8 lines
CC Daniel P. Berrange <[email protected]>
---
 include/sysemu/char.h | 10 ++++++++++
 qemu-char.c           |  2 +-
 spice-qemu-char.c     | 12 ++++++++----
 ui/console.c          | 20 +++++++++++---------
 4 files changed, 30 insertions(+), 14 deletions(-)

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
#3 lore raw

Re: [Qemu-devel] [PATCH 01/17] chardev: Properly initialize ChardevCommon components

In reply to Eric Blake
Quoted 125 lines · Eric Blake

Commit d0d7708b forgot to parse logging for spice chardevs and virtual consoles. This requires making qemu_chr_parse_common() non-static. While at it, use a temporary variable to make the code shorter, as well as reduce the churn when a later patch alters the layout of simple unions.

CC Daniel P. Berrange <[email protected]>
---
 include/sysemu/char.h | 10 ++++++++++
 qemu-char.c           |  2 +-
 spice-qemu-char.c     | 12 ++++++++----
 ui/console.c          | 20 +++++++++++---------
 4 files changed, 30 insertions(+), 14 deletions(-)
include/sysemu/char.h +10 -0
index e035d1c..e46884f 100644
@@ -115,6 +115,16 @@ CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
                                     Error **errp);
 
 /**
+ * @qemu_chr_parse_common:
+ *
+ * Parse the common options available to all character backends.
+ *
+ * @opts the options that still need parsing
+ * @backend a new backend
+ */
+void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend);
+
+/**
  * @qemu_chr_new:
  *
  * Create a new character backend from a URI.
qemu-char.c +1 -1
index ad11b75..fc8ffda 100644
@@ -3490,7 +3490,7 @@ fail:
     return NULL;
 }
 
-static void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
+void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
 {
     const char *logfile = qemu_opt_get(opts, "logfile");
 
spice-qemu-char.c +8 -4
index 7c1f438..21885c5 100644
@@ -366,26 +366,30 @@ static void qemu_chr_parse_spice_vmc(QemuOpts *opts, ChardevBackend *backend,
                                      Error **errp)
 {
     const char *name = qemu_opt_get(opts, "name");
+    ChardevSpiceChannel *spicevmc;
 
     if (name == NULL) {
         error_setg(errp, "chardev: spice channel: no name given");
         return;
     }
-    backend->u.spicevmc = g_new0(ChardevSpiceChannel, 1);
-    backend->u.spicevmc->type = g_strdup(name);
+    spicevmc = backend->u.spicevmc = g_new0(ChardevSpiceChannel, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevSpiceChannel_base(spicevmc));
+    spicevmc->type = g_strdup(name);
 }
 
 static void qemu_chr_parse_spice_port(QemuOpts *opts, ChardevBackend *backend,
                                       Error **errp)
 {
     const char *name = qemu_opt_get(opts, "name");
+    ChardevSpicePort *spiceport;
 
     if (name == NULL) {
         error_setg(errp, "chardev: spice port: no name given");
         return;
     }
-    backend->u.spiceport = g_new0(ChardevSpicePort, 1);
-    backend->u.spiceport->fqdn = g_strdup(name);
+    spiceport = backend->u.spiceport = g_new0(ChardevSpicePort, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevSpicePort_base(spiceport));
+    spiceport->fqdn = g_strdup(name);
 }
 
 static void register_types(void)
ui/console.c +9 -7
index b739ae9..7db0fd2 100644
@@ -2060,31 +2060,33 @@ static void qemu_chr_parse_vc(QemuOpts *opts, ChardevBackend *backend,
                               Error **errp)
 {
     int val;
+    ChardevVC *vc;
 
-    backend->u.vc = g_new0(ChardevVC, 1);
+    vc = backend->u.vc = g_new0(ChardevVC, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevVC_base(vc));
 
     val = qemu_opt_get_number(opts, "width", 0);
     if (val != 0) {
-        backend->u.vc->has_width = true;
-        backend->u.vc->width = val;
+        vc->has_width = true;
+        vc->width = val;
     }
 
     val = qemu_opt_get_number(opts, "height", 0);
     if (val != 0) {
-        backend->u.vc->has_height = true;
-        backend->u.vc->height = val;
+        vc->has_height = true;
+        vc->height = val;
     }
 
     val = qemu_opt_get_number(opts, "cols", 0);
     if (val != 0) {
-        backend->u.vc->has_cols = true;
-        backend->u.vc->cols = val;
+        vc->has_cols = true;
+        vc->cols = val;
     }

ui/console.c static void qemu_chr_parse_vc(QemuOpts *opts, ChardevBackend *backend, · line 2092

Quoted 10 lines
ui/console.c +2 -2
 
     val = qemu_opt_get_number(opts, "rows", 0);
     if (val != 0) {
-        backend->u.vc->has_rows = true;
-        backend->u.vc->rows = val;
+        vc->has_rows = true;
+        vc->rows = val;
     }
 }
 

I've picked up this patch and will send a pull request ASAP.

Paolo

author
#4 lore raw

PATCH 2/17 chardev: Shorten references into ChardevBackend

In reply to Eric Blake

An upcoming patch will alter how simple unions, like ChardevBackend, are laid out, which will impact all lines of the form 'backend->u.XXX'. To minimize the impact of that patch, use a temporary variable to reduce the number of lines needing modification when an internal reference within ChardevBackend changes layout.

---
 qemu-char.c | 122 ++++++++++++++++++++++++++++++++----------------------------
 1 file changed, 66 insertions(+), 56 deletions(-)
qemu-char.c +66 -56
index fc8ffda..5ea1d34 100644
@@ -724,7 +724,7 @@ static CharDriverState *qemu_chr_open_mux(const char *id,
     ChardevMux *mux = backend->u.mux;
     CharDriverState *chr, *drv;
     MuxDriver *d;
-    ChardevCommon *common = qapi_ChardevMux_base(backend->u.mux);
+    ChardevCommon *common = qapi_ChardevMux_base(mux);
 
     drv = qemu_chr_find(mux->chardev);
     if (drv == NULL) {
@@ -1043,7 +1043,7 @@ static CharDriverState *qemu_chr_open_pipe(const char *id,
     char *filename_in;
     char *filename_out;
     const char *filename = opts->device;
-    ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.pipe);
+    ChardevCommon *common = qapi_ChardevHostdev_base(opts);
 
 
     filename_in = g_strdup_printf("%s.in", filename);
@@ -1123,7 +1123,7 @@ static CharDriverState *qemu_chr_open_stdio(const char *id,
     ChardevStdio *opts = backend->u.stdio;
     CharDriverState *chr;
     struct sigaction act;
-    ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio);
+    ChardevCommon *common = qapi_ChardevStdio_base(opts);
 
     if (is_daemonized()) {
         error_setg(errp, "cannot use stdio with -daemonize");
@@ -2141,7 +2141,7 @@ static CharDriverState *qemu_chr_open_pipe(const char *id,
     const char *filename = opts->device;
     CharDriverState *chr;
     WinCharState *s;
-    ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.pipe);
+    ChardevCommon *common = qapi_ChardevHostdev_base(opts);
 
     chr = qemu_chr_alloc(common, errp);
     if (!chr) {
@@ -3216,7 +3216,7 @@ static CharDriverState *qemu_chr_open_ringbuf(const char *id,
                                               Error **errp)
 {
     ChardevRingbuf *opts = backend->u.ringbuf;
-    ChardevCommon *common = qapi_ChardevRingbuf_base(backend->u.ringbuf);
+    ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
     CharDriverState *chr;
     RingBufCharDriver *d;
 
@@ -3506,26 +3506,29 @@ static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
                                     Error **errp)
 {
     const char *path = qemu_opt_get(opts, "path");
+    ChardevFile *file;
 
     if (path == NULL) {
         error_setg(errp, "chardev: file: no filename given");
         return;
     }
-    backend->u.file = g_new0(ChardevFile, 1);
-    qemu_chr_parse_common(opts, qapi_ChardevFile_base(backend->u.file));
-    backend->u.file->out = g_strdup(path);
+    file = backend->u.file = g_new0(ChardevFile, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
+    file->out = g_strdup(path);
 
-    backend->u.file->has_append = true;
-    backend->u.file->append = qemu_opt_get_bool(opts, "append", false);
+    file->has_append = true;
+    file->append = qemu_opt_get_bool(opts, "append", false);
 }
 
 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
                                  Error **errp)
 {
-    backend->u.stdio = g_new0(ChardevStdio, 1);
-    qemu_chr_parse_common(opts, qapi_ChardevStdio_base(backend->u.stdio));
-    backend->u.stdio->has_signal = true;
-    backend->u.stdio->signal = qemu_opt_get_bool(opts, "signal", true);
+    ChardevStdio *stdio;
+
+    stdio = backend->u.stdio = g_new0(ChardevStdio, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
+    stdio->has_signal = true;
+    stdio->signal = qemu_opt_get_bool(opts, "signal", true);
 }
 
 #ifdef HAVE_CHARDEV_SERIAL
@@ -3533,14 +3536,15 @@ static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
                                   Error **errp)
 {
     const char *device = qemu_opt_get(opts, "path");
+    ChardevHostdev *serial;
 
     if (device == NULL) {
         error_setg(errp, "chardev: serial/tty: no device path given");
         return;
     }
-    backend->u.serial = g_new0(ChardevHostdev, 1);
-    qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.serial));
-    backend->u.serial->device = g_strdup(device);
+    serial = backend->u.serial = g_new0(ChardevHostdev, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
+    serial->device = g_strdup(device);
 }
 #endif
 
@@ -3549,14 +3553,15 @@ static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
                                     Error **errp)
 {
     const char *device = qemu_opt_get(opts, "path");
+    ChardevHostdev *parallel;
 
     if (device == NULL) {
         error_setg(errp, "chardev: parallel: no device path given");
         return;
     }
-    backend->u.parallel = g_new0(ChardevHostdev, 1);
-    qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.parallel));
-    backend->u.parallel->device = g_strdup(device);
+    parallel = backend->u.parallel = g_new0(ChardevHostdev, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
+    parallel->device = g_strdup(device);
 }
 #endif
 
@@ -3564,28 +3569,30 @@ static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
                                 Error **errp)
 {
     const char *device = qemu_opt_get(opts, "path");
+    ChardevHostdev *dev;
 
     if (device == NULL) {
         error_setg(errp, "chardev: pipe: no device path given");
         return;
     }
-    backend->u.pipe = g_new0(ChardevHostdev, 1);
-    qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.pipe));
-    backend->u.pipe->device = g_strdup(device);
+    dev = backend->u.pipe = g_new0(ChardevHostdev, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
+    dev->device = g_strdup(device);
 }
 
 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
                                    Error **errp)
 {
     int val;
+    ChardevRingbuf *ringbuf;
 
-    backend->u.ringbuf = g_new0(ChardevRingbuf, 1);
-    qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(backend->u.ringbuf));
+    ringbuf = backend->u.ringbuf = g_new0(ChardevRingbuf, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
 
     val = qemu_opt_get_size(opts, "size", 0);
     if (val != 0) {
-        backend->u.ringbuf->has_size = true;
-        backend->u.ringbuf->size = val;
+        ringbuf->has_size = true;
+        ringbuf->size = val;
     }
 }
 
@@ -3593,14 +3600,15 @@ static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
                                Error **errp)
 {
     const char *chardev = qemu_opt_get(opts, "chardev");
+    ChardevMux *mux;
 
     if (chardev == NULL) {
         error_setg(errp, "chardev: mux: no chardev given");
         return;
     }
-    backend->u.mux = g_new0(ChardevMux, 1);
-    qemu_chr_parse_common(opts, qapi_ChardevMux_base(backend->u.mux));
-    backend->u.mux->chardev = g_strdup(chardev);
+    mux = backend->u.mux = g_new0(ChardevMux, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
+    mux->chardev = g_strdup(chardev);
 }
 
 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
@@ -3616,6 +3624,7 @@ static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
     const char *port = qemu_opt_get(opts, "port");
     const char *tls_creds = qemu_opt_get(opts, "tls-creds");
     SocketAddress *addr;
+    ChardevSocket *sock;
 
     if (!path) {
         if (!host) {
@@ -3633,20 +3642,20 @@ static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
         }
     }
 
-    backend->u.socket = g_new0(ChardevSocket, 1);
-    qemu_chr_parse_common(opts, qapi_ChardevSocket_base(backend->u.socket));
+    sock = backend->u.socket = g_new0(ChardevSocket, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
 
-    backend->u.socket->has_nodelay = true;
-    backend->u.socket->nodelay = do_nodelay;
-    backend->u.socket->has_server = true;
-    backend->u.socket->server = is_listen;
-    backend->u.socket->has_telnet = true;
-    backend->u.socket->telnet = is_telnet;
-    backend->u.socket->has_wait = true;
-    backend->u.socket->wait = is_waitconnect;
-    backend->u.socket->has_reconnect = true;
-    backend->u.socket->reconnect = reconnect;
-    backend->u.socket->tls_creds = g_strdup(tls_creds);
+    sock->has_nodelay = true;
+    sock->nodelay = do_nodelay;
+    sock->has_server = true;
+    sock->server = is_listen;
+    sock->has_telnet = true;
+    sock->telnet = is_telnet;
+    sock->has_wait = true;
+    sock->wait = is_waitconnect;
+    sock->has_reconnect = true;
+    sock->reconnect = reconnect;
+    sock->tls_creds = g_strdup(tls_creds);
 
     addr = g_new0(SocketAddress, 1);
     if (path) {
@@ -3665,7 +3674,7 @@ static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
         addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
         addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
     }
-    backend->u.socket->addr = addr;
+    sock->addr = addr;
 }
 
 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
@@ -3677,6 +3686,7 @@ static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
     const char *localport = qemu_opt_get(opts, "localport");
     bool has_local = false;
     SocketAddress *addr;
+    ChardevUdp *udp;
 
     if (host == NULL || strlen(host) == 0) {
         host = "localhost";
@@ -3696,8 +3706,8 @@ static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
         has_local = true;
     }
 
-    backend->u.udp = g_new0(ChardevUdp, 1);
-    qemu_chr_parse_common(opts, qapi_ChardevUdp_base(backend->u.udp));
+    udp = backend->u.udp = g_new0(ChardevUdp, 1);
+    qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
 
     addr = g_new0(SocketAddress, 1);
     addr->type = SOCKET_ADDRESS_KIND_INET;
@@ -3708,16 +3718,16 @@ static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
     addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
     addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
     addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
-    backend->u.udp->remote = addr;
+    udp->remote = addr;
 
     if (has_local) {
-        backend->u.udp->has_local = true;
+        udp->has_local = true;
         addr = g_new0(SocketAddress, 1);
         addr->type = SOCKET_ADDRESS_KIND_INET;
         addr->u.inet = g_new0(InetSocketAddress, 1);
         addr->u.inet->host = g_strdup(localaddr);
         addr->u.inet->port = g_strdup(localport);
-        backend->u.udp->local = addr;
+        udp->local = addr;
     }
 }
 
@@ -4128,7 +4138,7 @@ static CharDriverState *qmp_chardev_open_file(const char *id,
                                               Error **errp)
 {
     ChardevFile *file = backend->u.file;
-    ChardevCommon *common = qapi_ChardevFile_base(backend->u.file);
+    ChardevCommon *common = qapi_ChardevFile_base(file);
     HANDLE out;
 
     if (file->has_in) {
@@ -4151,7 +4161,7 @@ static CharDriverState *qmp_chardev_open_serial(const char *id,
                                                 Error **errp)
 {
     ChardevHostdev *serial = backend->u.serial;
-    ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.serial);
+    ChardevCommon *common = qapi_ChardevHostdev_base(serial);
     return qemu_chr_open_win_path(serial->device, common, errp);
 }
 
@@ -4175,7 +4185,7 @@ static CharDriverState *qmp_chardev_open_file(const char *id,
                                               Error **errp)
 {
     ChardevFile *file = backend->u.file;
-    ChardevCommon *common = qapi_ChardevFile_base(backend->u.file);
+    ChardevCommon *common = qapi_ChardevFile_base(file);
     int flags, in = -1, out;
 
     flags = O_WRONLY | O_CREAT | O_BINARY;
@@ -4209,7 +4219,7 @@ static CharDriverState *qmp_chardev_open_serial(const char *id,
                                                 Error **errp)
 {
     ChardevHostdev *serial = backend->u.serial;
-    ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.serial);
+    ChardevCommon *common = qapi_ChardevHostdev_base(serial);
     int fd;
 
     fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
@@ -4228,7 +4238,7 @@ static CharDriverState *qmp_chardev_open_parallel(const char *id,
                                                   Error **errp)
 {
     ChardevHostdev *parallel = backend->u.parallel;
-    ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.parallel);
+    ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
     int fd;
 
     fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
@@ -4280,7 +4290,7 @@ static CharDriverState *qmp_chardev_open_socket(const char *id,
     bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;
     bool is_waitconnect = sock->has_wait    ? sock->wait    : false;
     int64_t reconnect   = sock->has_reconnect ? sock->reconnect : 0;
-    ChardevCommon *common = qapi_ChardevSocket_base(backend->u.socket);
+    ChardevCommon *common = qapi_ChardevSocket_base(sock);
 
     chr = qemu_chr_alloc(common, errp);
     if (!chr) {
@@ -4380,7 +4390,7 @@ static CharDriverState *qmp_chardev_open_udp(const char *id,
                                              Error **errp)
 {
     ChardevUdp *udp = backend->u.udp;
-    ChardevCommon *common = qapi_ChardevUdp_base(backend->u.udp);
+    ChardevCommon *common = qapi_ChardevUdp_base(udp);
     QIOChannelSocket *sioc = qio_channel_socket_new();
 
     if (qio_channel_socket_dgram_sync(sioc,
Signature · 1 line
2.5.0
Reviewed-by on v1 2/17
#5 lore raw

Re: [Qemu-devel] [PATCH 02/17] chardev: Shorten references into ChardevBackend

Quoted 10 lines · Eric Blake

An upcoming patch will alter how simple unions, like ChardevBackend, are laid out, which will impact all lines of the form 'backend->u.XXX'. To minimize the impact of that patch, use a temporary variable to reduce the number of lines needing modification when an internal reference within ChardevBackend changes layout.

---
 qemu-char.c | 122 ++++++++++++++++++++++++++++++++----------------------------
 1 file changed, 66 insertions(+), 56 deletions(-)

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
author
#6 lore raw

PATCH 3/17 util: Shorten references into SocketAddress

In reply to Eric Blake

An upcoming patch will alter how simple unions, like SocketAddress, are laid out, which will impact all lines of the form 'addr->u.XXX'. To minimize the impact of that patch, use C99 initialization or a temporary variable to reduce the number of lines needing modification when an internal reference within SocketAddress changes layout.

---
 block/nbd.c                    | 14 ++++++++------
 qemu-char.c                    | 43 ++++++++++++++++++++++++------------------
 qemu-nbd.c                     |  9 +++++----
 tests/test-io-channel-socket.c | 26 ++++++++++++++++---------
 ui/vnc.c                       | 39 +++++++++++++++++++-------------------
 util/qemu-sockets.c            | 11 ++++++-----
 6 files changed, 81 insertions(+), 61 deletions(-)
block/nbd.c +8 -6
index db57b49..9f333c9 100644
@@ -204,18 +204,20 @@ static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options, char **export,
     saddr = g_new0(SocketAddress, 1);
 
     if (qdict_haskey(options, "path")) {
+        UnixSocketAddress *q_unix;
         saddr->type = SOCKET_ADDRESS_KIND_UNIX;
-        saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
-        saddr->u.q_unix->path = g_strdup(qdict_get_str(options, "path"));
+        q_unix = saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
+        q_unix->path = g_strdup(qdict_get_str(options, "path"));
         qdict_del(options, "path");
     } else {
+        InetSocketAddress *inet;
         saddr->type = SOCKET_ADDRESS_KIND_INET;
-        saddr->u.inet = g_new0(InetSocketAddress, 1);
-        saddr->u.inet->host = g_strdup(qdict_get_str(options, "host"));
+        inet = saddr->u.inet = g_new0(InetSocketAddress, 1);
+        inet->host = g_strdup(qdict_get_str(options, "host"));
         if (!qdict_get_try_str(options, "port")) {
-            saddr->u.inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
+            inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
         } else {
-            saddr->u.inet->port = g_strdup(qdict_get_str(options, "port"));
+            inet->port = g_strdup(qdict_get_str(options, "port"));
         }
         qdict_del(options, "host");
         qdict_del(options, "port");
qemu-char.c +25 -18

65 lines not on this page · raw message

qemu-nbd.c +5 -4
index 933ca4a..2ee7f40 100644
@@ -380,13 +380,14 @@ static SocketAddress *nbd_build_socket_address(const char *sockpath,
         saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
         saddr->u.q_unix->path = g_strdup(sockpath);
     } else {
+        InetSocketAddress *inet;
         saddr->type = SOCKET_ADDRESS_KIND_INET;
-        saddr->u.inet = g_new0(InetSocketAddress, 1);
-        saddr->u.inet->host = g_strdup(bindto);
+        inet = saddr->u.inet = g_new0(InetSocketAddress, 1);
+        inet->host = g_strdup(bindto);
         if (port) {
-            saddr->u.inet->port = g_strdup(port);
+            inet->port = g_strdup(port);
         } else  {
-            saddr->u.inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
+            inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
         }
     }
 
tests/test-io-channel-socket.c +17 -9
index 0697363..afe46d5 100644
@@ -1,7 +1,7 @@
 /*
  * QEMU I/O channel sockets test
  *
- * Copyright (c) 2015 Red Hat, Inc.
+ * Copyright (c) 2015-2016 Red Hat, Inc.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -284,13 +284,17 @@ static void test_io_channel_ipv4(bool async)
 
     listen_addr->type = SOCKET_ADDRESS_KIND_INET;
     listen_addr->u.inet = g_new0(InetSocketAddress, 1);
-    listen_addr->u.inet->host = g_strdup("127.0.0.1");
-    listen_addr->u.inet->port = NULL; /* Auto-select */
+    *listen_addr->u.inet = (InetSocketAddress) {
+        .host = g_strdup("127.0.0.1"),
+        .port = NULL, /* Auto-select */
+    };
 
     connect_addr->type = SOCKET_ADDRESS_KIND_INET;
     connect_addr->u.inet = g_new0(InetSocketAddress, 1);
-    connect_addr->u.inet->host = g_strdup("127.0.0.1");
-    connect_addr->u.inet->port = NULL; /* Filled in later */
+    *connect_addr->u.inet = (InetSocketAddress) {
+        .host = g_strdup("127.0.0.1"),
+        .port = NULL, /* Filled in later */
+    };
 
     test_io_channel(async, listen_addr, connect_addr, false);
 
@@ -318,13 +322,17 @@ static void test_io_channel_ipv6(bool async)
 
     listen_addr->type = SOCKET_ADDRESS_KIND_INET;
     listen_addr->u.inet = g_new0(InetSocketAddress, 1);
-    listen_addr->u.inet->host = g_strdup("::1");
-    listen_addr->u.inet->port = NULL; /* Auto-select */
+    *listen_addr->u.inet = (InetSocketAddress) {
+        .host = g_strdup("::1"),
+        .port = NULL, /* Auto-select */
+    };
 
     connect_addr->type = SOCKET_ADDRESS_KIND_INET;
     connect_addr->u.inet = g_new0(InetSocketAddress, 1);
-    connect_addr->u.inet->host = g_strdup("::1");
-    connect_addr->u.inet->port = NULL; /* Filled in later */
+    *connect_addr->u.inet = (InetSocketAddress) {
+        .host = g_strdup("::1"),
+        .port = NULL, /* Filled in later */
+    };
 
     test_io_channel(async, listen_addr, connect_addr, false);
 
ui/vnc.c +20 -19
index b6bbea5..b955e4e 100644
@@ -3530,12 +3530,13 @@ void vnc_display_open(const char *id, Error **errp)
             }
         } else {
             unsigned long long baseport;
+            InetSocketAddress *inet;
             saddr->type = SOCKET_ADDRESS_KIND_INET;
-            saddr->u.inet = g_new0(InetSocketAddress, 1);
+            inet = saddr->u.inet = g_new0(InetSocketAddress, 1);
             if (vnc[0] == '[' && vnc[hlen - 1] == ']') {
-                saddr->u.inet->host = g_strndup(vnc + 1, hlen - 2);
+                inet->host = g_strndup(vnc + 1, hlen - 2);
             } else {
-                saddr->u.inet->host = g_strndup(vnc, hlen);
+                inet->host = g_strndup(vnc, hlen);
             }
             if (parse_uint_full(h + 1, &baseport, 10) < 0) {
                 error_setg(errp, "can't convert to a number: %s", h + 1);
@@ -3546,32 +3547,32 @@ void vnc_display_open(const char *id, Error **errp)
                 error_setg(errp, "port %s out of range", h + 1);
                 goto fail;
             }
-            saddr->u.inet->port = g_strdup_printf(
+            inet->port = g_strdup_printf(
                 "%d", (int)baseport + 5900);
 
             if (to) {
-                saddr->u.inet->has_to = true;
-                saddr->u.inet->to = to + 5900;
+                inet->has_to = true;
+                inet->to = to + 5900;
             }
-            saddr->u.inet->ipv4 = ipv4;
-            saddr->u.inet->has_ipv4 = has_ipv4;
-            saddr->u.inet->ipv6 = ipv6;
-            saddr->u.inet->has_ipv6 = has_ipv6;
+            inet->ipv4 = ipv4;
+            inet->has_ipv4 = has_ipv4;
+            inet->ipv6 = ipv6;
+            inet->has_ipv6 = has_ipv6;
 
             if (vs->ws_enabled) {
                 wsaddr->type = SOCKET_ADDRESS_KIND_INET;
-                wsaddr->u.inet = g_new0(InetSocketAddress, 1);
-                wsaddr->u.inet->host = g_strdup(saddr->u.inet->host);
-                wsaddr->u.inet->port = g_strdup(websocket);
+                inet = wsaddr->u.inet = g_new0(InetSocketAddress, 1);
+                inet->host = g_strdup(saddr->u.inet->host);
+                inet->port = g_strdup(websocket);
 
                 if (to) {
-                    wsaddr->u.inet->has_to = true;
-                    wsaddr->u.inet->to = to;
+                    inet->has_to = true;
+                    inet->to = to;
                 }
-                wsaddr->u.inet->ipv4 = ipv4;
-                wsaddr->u.inet->has_ipv4 = has_ipv4;
-                wsaddr->u.inet->ipv6 = ipv6;
-                wsaddr->u.inet->has_ipv6 = has_ipv6;
+                inet->ipv4 = ipv4;
+                inet->has_ipv4 = has_ipv4;
+                inet->ipv6 = ipv6;
+                inet->has_ipv6 = has_ipv6;
             }
         }
     } else {
util/qemu-sockets.c +6 -5
index 557da20..ad7c00c 100644
@@ -1003,6 +1003,7 @@ socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
     char host[NI_MAXHOST];
     char serv[NI_MAXSERV];
     SocketAddress *addr;
+    InetSocketAddress *inet;
     int ret;
 
     ret = getnameinfo((struct sockaddr *)sa, salen,
@@ -1017,13 +1018,13 @@ socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
 
     addr = g_new0(SocketAddress, 1);
     addr->type = SOCKET_ADDRESS_KIND_INET;
-    addr->u.inet = g_new0(InetSocketAddress, 1);
-    addr->u.inet->host = g_strdup(host);
-    addr->u.inet->port = g_strdup(serv);
+    inet = addr->u.inet = g_new0(InetSocketAddress, 1);
+    inet->host = g_strdup(host);
+    inet->port = g_strdup(serv);
     if (sa->ss_family == AF_INET) {
-        addr->u.inet->has_ipv4 = addr->u.inet->ipv4 = true;
+        inet->has_ipv4 = inet->ipv4 = true;
     } else {
-        addr->u.inet->has_ipv6 = addr->u.inet->ipv6 = true;
+        inet->has_ipv6 = inet->ipv6 = true;
     }
 
     return addr;
Signature · 1 line
2.5.0
Reviewed-by on v1 3/17
#7 lore raw

Re: [Qemu-devel] [PATCH 03/17] util: Shorten references into SocketAddress

Quoted 7 lines · Eric Blake

An upcoming patch will alter how simple unions, like SocketAddress, are laid out, which will impact all lines of the form 'addr->u.XXX'. To minimize the impact of that patch, use C99 initialization or a temporary variable to reduce the number of lines needing modification when an internal reference within SocketAddress changes layout.

Quoted 8 lines
---
 block/nbd.c                    | 14 ++++++++------
 qemu-char.c                    | 43 ++++++++++++++++++++++++------------------
 qemu-nbd.c                     |  9 +++++----
 tests/test-io-channel-socket.c | 26 ++++++++++++++++---------
 ui/vnc.c                       | 39 +++++++++++++++++++-------------------
 util/qemu-sockets.c            | 11 ++++++-----
 6 files changed, 81 insertions(+), 61 deletions(-)

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
author
#8 lore raw

PATCH 4/17 ui: Shorten references into InputEvent

In reply to Eric Blake

An upcoming patch will alter how simple unions, like InputEvent, are laid out, which will impact all lines of the form 'evt->u.XXX'. To minimize the impact of that patch, use a temporary variable to reduce the number of lines needing modification when an internal reference within InputEvent changes layout.

There was one instance in hid.c:hid_pointer_event() where the code was referring to evt->u.rel inside the case label where evt->u.abs is the correct name; thankfully, both members of the union have the same type, so it happened to work, but it is now cleaner.

---
 hw/char/escc.c              | 12 +++++-----
 hw/input/hid.c              | 36 +++++++++++++++++-------------
 hw/input/ps2.c              | 27 ++++++++++++++---------
 hw/input/virtio-input-hid.c | 33 ++++++++++++++++-----------
 replay/replay-input.c       | 31 ++++++++++++++++----------
 ui/input-legacy.c           | 26 +++++++++++++---------
 ui/input.c                  | 54 ++++++++++++++++++++++++++-------------------
 7 files changed, 130 insertions(+), 89 deletions(-)
hw/char/escc.c +7 -5
index 98a1c21..c7a24ac 100644
@@ -842,14 +842,16 @@ static void sunkbd_handle_event(DeviceState *dev, QemuConsole *src,
 {
     ChannelState *s = (ChannelState *)dev;
     int qcode, keycode;
+    InputKeyEvent *key;
 
     assert(evt->type == INPUT_EVENT_KIND_KEY);
-    qcode = qemu_input_key_value_to_qcode(evt->u.key->key);
+    key = evt->u.key;
+    qcode = qemu_input_key_value_to_qcode(key->key);
     trace_escc_sunkbd_event_in(qcode, QKeyCode_lookup[qcode],
-                               evt->u.key->down);
+                               key->down);
 
     if (qcode == Q_KEY_CODE_CAPS_LOCK) {
-        if (evt->u.key->down) {
+        if (key->down) {
             s->caps_lock_mode ^= 1;
             if (s->caps_lock_mode == 2) {
                 return; /* Drop second press */
@@ -863,7 +865,7 @@ static void sunkbd_handle_event(DeviceState *dev, QemuConsole *src,
     }
 
     if (qcode == Q_KEY_CODE_NUM_LOCK) {
-        if (evt->u.key->down) {
+        if (key->down) {
             s->num_lock_mode ^= 1;
             if (s->num_lock_mode == 2) {
                 return; /* Drop second press */
@@ -877,7 +879,7 @@ static void sunkbd_handle_event(DeviceState *dev, QemuConsole *src,
     }
 
     keycode = qcode_to_keycode[qcode];
-    if (!evt->u.key->down) {
+    if (!key->down) {
         keycode |= 0x80;
     }
     trace_escc_sunkbd_event_out(keycode);
hw/input/hid.c +21 -15
index b41efbb..5db4d68 100644
@@ -116,37 +116,42 @@ static void hid_pointer_event(DeviceState *dev, QemuConsole *src,
     };
     HIDState *hs = (HIDState *)dev;
     HIDPointerEvent *e;
+    InputMoveEvent *move;
+    InputBtnEvent *btn;
 
     assert(hs->n < QUEUE_LENGTH);
     e = &hs->ptr.queue[(hs->head + hs->n) & QUEUE_MASK];
 
     switch (evt->type) {
     case INPUT_EVENT_KIND_REL:
-        if (evt->u.rel->axis == INPUT_AXIS_X) {
-            e->xdx += evt->u.rel->value;
-        } else if (evt->u.rel->axis == INPUT_AXIS_Y) {
-            e->ydy += evt->u.rel->value;
+        move = evt->u.rel;
+        if (move->axis == INPUT_AXIS_X) {
+            e->xdx += move->value;
+        } else if (move->axis == INPUT_AXIS_Y) {
+            e->ydy += move->value;
         }
         break;
 
     case INPUT_EVENT_KIND_ABS:
-        if (evt->u.rel->axis == INPUT_AXIS_X) {
-            e->xdx = evt->u.rel->value;
-        } else if (evt->u.rel->axis == INPUT_AXIS_Y) {
-            e->ydy = evt->u.rel->value;
+        move = evt->u.abs;
+        if (move->axis == INPUT_AXIS_X) {
+            e->xdx = move->value;
+        } else if (move->axis == INPUT_AXIS_Y) {
+            e->ydy = move->value;
         }
         break;
 
     case INPUT_EVENT_KIND_BTN:
-        if (evt->u.btn->down) {
-            e->buttons_state |= bmap[evt->u.btn->button];
-            if (evt->u.btn->button == INPUT_BUTTON_WHEELUP) {
+        btn = evt->u.btn;
+        if (btn->down) {
+            e->buttons_state |= bmap[btn->button];
+            if (btn->button == INPUT_BUTTON_WHEELUP) {
                 e->dz--;
-            } else if (evt->u.btn->button == INPUT_BUTTON_WHEELDOWN) {
+            } else if (btn->button == INPUT_BUTTON_WHEELDOWN) {
                 e->dz++;
             }
         } else {
-            e->buttons_state &= ~bmap[evt->u.btn->button];
+            e->buttons_state &= ~bmap[btn->button];
         }
         break;
 
@@ -223,9 +228,10 @@ static void hid_keyboard_event(DeviceState *dev, QemuConsole *src,
     HIDState *hs = (HIDState *)dev;
     int scancodes[3], i, count;
     int slot;
+    InputKeyEvent *key = evt->u.key;
 
-    count = qemu_input_key_value_to_scancode(evt->u.key->key,
-                                             evt->u.key->down,
+    count = qemu_input_key_value_to_scancode(key->key,
+                                             key->down,
                                              scancodes);
     if (hs->n + count > QUEUE_LENGTH) {
         fprintf(stderr, "usb-kbd: warning: key event queue full\n");
hw/input/ps2.c +16 -11
index b6f0e8d..7bab7c2 100644
@@ -182,10 +182,11 @@ static void ps2_keyboard_event(DeviceState *dev, QemuConsole *src,
 {
     PS2KbdState *s = (PS2KbdState *)dev;
     int scancodes[3], i, count;
+    InputKeyEvent *key = evt->u.key;
 
     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
-    count = qemu_input_key_value_to_scancode(evt->u.key->key,
-                                             evt->u.key->down,
+    count = qemu_input_key_value_to_scancode(key->key,
+                                             key->down,
                                              scancodes);
     for (i = 0; i < count; i++) {
         ps2_put_keycode(s, scancodes[i]);
@@ -389,6 +390,8 @@ static void ps2_mouse_event(DeviceState *dev, QemuConsole *src,
         [INPUT_BUTTON_RIGHT]  = MOUSE_EVENT_RBUTTON,
     };
     PS2MouseState *s = (PS2MouseState *)dev;
+    InputMoveEvent *move;
+    InputBtnEvent *btn;
 
     /* check if deltas are recorded when disabled */
     if (!(s->mouse_status & MOUSE_STATUS_ENABLED))
@@ -396,23 +399,25 @@ static void ps2_mouse_event(DeviceState *dev, QemuConsole *src,
 
     switch (evt->type) {
     case INPUT_EVENT_KIND_REL:
-        if (evt->u.rel->axis == INPUT_AXIS_X) {
-            s->mouse_dx += evt->u.rel->value;
-        } else if (evt->u.rel->axis == INPUT_AXIS_Y) {
-            s->mouse_dy -= evt->u.rel->value;
+        move = evt->u.rel;
+        if (move->axis == INPUT_AXIS_X) {
+            s->mouse_dx += move->value;
+        } else if (move->axis == INPUT_AXIS_Y) {
+            s->mouse_dy -= move->value;
         }
         break;
 
     case INPUT_EVENT_KIND_BTN:
-        if (evt->u.btn->down) {
-            s->mouse_buttons |= bmap[evt->u.btn->button];
-            if (evt->u.btn->button == INPUT_BUTTON_WHEELUP) {
+        btn = evt->u.btn;
+        if (btn->down) {
+            s->mouse_buttons |= bmap[btn->button];
+            if (btn->button == INPUT_BUTTON_WHEELUP) {
                 s->mouse_dz--;
-            } else if (evt->u.btn->button == INPUT_BUTTON_WHEELDOWN) {
+            } else if (btn->button == INPUT_BUTTON_WHEELDOWN) {
                 s->mouse_dz++;
             }
         } else {
-            s->mouse_buttons &= ~bmap[evt->u.btn->button];
+            s->mouse_buttons &= ~bmap[btn->button];
         }
         break;
 
hw/input/virtio-input-hid.c +20 -13
index c4af0be..7053f75 100644
@@ -191,46 +191,53 @@ static void virtio_input_handle_event(DeviceState *dev, QemuConsole *src,
     VirtIOInput *vinput = VIRTIO_INPUT(dev);
     virtio_input_event event;
     int qcode;
+    InputKeyEvent *key;
+    InputMoveEvent *move;
+    InputBtnEvent *btn;
 
     switch (evt->type) {
     case INPUT_EVENT_KIND_KEY:
-        qcode = qemu_input_key_value_to_qcode(evt->u.key->key);
+        key = evt->u.key;
+        qcode = qemu_input_key_value_to_qcode(key->key);
         if (qcode && keymap_qcode[qcode]) {
             event.type  = cpu_to_le16(EV_KEY);
             event.code  = cpu_to_le16(keymap_qcode[qcode]);
-            event.value = cpu_to_le32(evt->u.key->down ? 1 : 0);
+            event.value = cpu_to_le32(key->down ? 1 : 0);
             virtio_input_send(vinput, &event);
         } else {
-            if (evt->u.key->down) {
+            if (key->down) {
                 fprintf(stderr, "%s: unmapped key: %d [%s]\n", __func__,
                         qcode, QKeyCode_lookup[qcode]);
             }
         }
         break;
     case INPUT_EVENT_KIND_BTN:
-        if (keymap_button[evt->u.btn->button]) {
+        btn = evt->u.btn;
+        if (keymap_button[btn->button]) {
             event.type  = cpu_to_le16(EV_KEY);
-            event.code  = cpu_to_le16(keymap_button[evt->u.btn->button]);
-            event.value = cpu_to_le32(evt->u.btn->down ? 1 : 0);
+            event.code  = cpu_to_le16(keymap_button[btn->button]);
+            event.value = cpu_to_le32(btn->down ? 1 : 0);
             virtio_input_send(vinput, &event);
         } else {
-            if (evt->u.btn->down) {
+            if (btn->down) {
                 fprintf(stderr, "%s: unmapped button: %d [%s]\n", __func__,
-                        evt->u.btn->button,
-                        InputButton_lookup[evt->u.btn->button]);
+                        btn->button,
+                        InputButton_lookup[btn->button]);
             }
         }
         break;
     case INPUT_EVENT_KIND_REL:
+        move = evt->u.rel;
         event.type  = cpu_to_le16(EV_REL);
-        event.code  = cpu_to_le16(axismap_rel[evt->u.rel->axis]);
-        event.value = cpu_to_le32(evt->u.rel->value);
+        event.code  = cpu_to_le16(axismap_rel[move->axis]);
+        event.value = cpu_to_le32(move->value);
         virtio_input_send(vinput, &event);
         break;
     case INPUT_EVENT_KIND_ABS:
+        move = evt->u.abs;
         event.type  = cpu_to_le16(EV_ABS);
-        event.code  = cpu_to_le16(axismap_abs[evt->u.abs->axis]);
-        event.value = cpu_to_le32(evt->u.abs->value);
+        event.code  = cpu_to_le16(axismap_abs[move->axis]);
+        event.value = cpu_to_le32(move->value);
         virtio_input_send(vinput, &event);
         break;
     default:
replay/replay-input.c +19 -12
index 93616be..c38af50 100644
@@ -47,20 +47,24 @@ static InputEvent *qapi_clone_InputEvent(InputEvent *src)
 
 void replay_save_input_event(InputEvent *evt)
 {
+    InputKeyEvent *key;
+    InputBtnEvent *btn;
+    InputMoveEvent *move;
     replay_put_dword(evt->type);
 
     switch (evt->type) {
     case INPUT_EVENT_KIND_KEY:
-        replay_put_dword(evt->u.key->key->type);
+        key = evt->u.key;
+        replay_put_dword(key->key->type);
 
-        switch (evt->u.key->key->type) {
+        switch (key->key->type) {
         case KEY_VALUE_KIND_NUMBER:
-            replay_put_qword(evt->u.key->key->u.number);
-            replay_put_byte(evt->u.key->down);
+            replay_put_qword(key->key->u.number);
+            replay_put_byte(key->down);
             break;
         case KEY_VALUE_KIND_QCODE:
-            replay_put_dword(evt->u.key->key->u.qcode);
-            replay_put_byte(evt->u.key->down);
+            replay_put_dword(key->key->u.qcode);
+            replay_put_byte(key->down);
             break;
         case KEY_VALUE_KIND__MAX:
             /* keep gcc happy */
@@ -68,16 +72,19 @@ void replay_save_input_event(InputEvent *evt)
         }
         break;
     case INPUT_EVENT_KIND_BTN:
-        replay_put_dword(evt->u.btn->button);
-        replay_put_byte(evt->u.btn->down);
+        btn = evt->u.btn;
+        replay_put_dword(btn->button);
+        replay_put_byte(btn->down);
         break;
     case INPUT_EVENT_KIND_REL:
-        replay_put_dword(evt->u.rel->axis);
-        replay_put_qword(evt->u.rel->value);
+        move = evt->u.rel;
+        replay_put_dword(move->axis);
+        replay_put_qword(move->value);
         break;
     case INPUT_EVENT_KIND_ABS:
-        replay_put_dword(evt->u.abs->axis);
-        replay_put_qword(evt->u.abs->value);
+        move = evt->u.abs;
+        replay_put_dword(move->axis);
+        replay_put_qword(move->value);
         break;
     case INPUT_EVENT_KIND__MAX:
         /* keep gcc happy */
ui/input-legacy.c +16 -10
index c97eac1..5119fe8 100644
@@ -110,12 +110,13 @@ static void legacy_kbd_event(DeviceState *dev, QemuConsole *src,
 {
     QEMUPutKbdEntry *entry = (QEMUPutKbdEntry *)dev;
     int scancodes[3], i, count;
+    InputKeyEvent *key = evt->u.key;
 
     if (!entry || !entry->put_kbd) {
         return;
     }
-    count = qemu_input_key_value_to_scancode(evt->u.key->key,
-                                             evt->u.key->down,
+    count = qemu_input_key_value_to_scancode(key->key,
+                                             key->down,
                                              scancodes);
     for (i = 0; i < count; i++) {
         entry->put_kbd(entry->opaque, scancodes[i]);
@@ -150,23 +151,26 @@ static void legacy_mouse_event(DeviceState *dev, QemuConsole *src,
         [INPUT_BUTTON_RIGHT]  = MOUSE_EVENT_RBUTTON,
     };
     QEMUPutMouseEntry *s = (QEMUPutMouseEntry *)dev;
+    InputBtnEvent *btn;
+    InputMoveEvent *move;
 
     switch (evt->type) {
     case INPUT_EVENT_KIND_BTN:
-        if (evt->u.btn->down) {
-            s->buttons |= bmap[evt->u.btn->button];
+        btn = evt->u.btn;
+        if (btn->down) {
+            s->buttons |= bmap[btn->button];
         } else {
-            s->buttons &= ~bmap[evt->u.btn->button];
+            s->buttons &= ~bmap[btn->button];
         }
-        if (evt->u.btn->down && evt->u.btn->button == INPUT_BUTTON_WHEELUP) {
+        if (btn->down && btn->button == INPUT_BUTTON_WHEELUP) {
             s->qemu_put_mouse_event(s->qemu_put_mouse_event_opaque,
                                     s->axis[INPUT_AXIS_X],
                                     s->axis[INPUT_AXIS_Y],
                                     -1,
                                     s->buttons);
         }
-        if (evt->u.btn->down &&
-            evt->u.btn->button == INPUT_BUTTON_WHEELDOWN) {
+        if (btn->down &&
+            btn->button == INPUT_BUTTON_WHEELDOWN) {
             s->qemu_put_mouse_event(s->qemu_put_mouse_event_opaque,
                                     s->axis[INPUT_AXIS_X],
                                     s->axis[INPUT_AXIS_Y],
@@ -175,10 +179,12 @@ static void legacy_mouse_event(DeviceState *dev, QemuConsole *src,
         }
         break;
     case INPUT_EVENT_KIND_ABS:
-        s->axis[evt->u.abs->axis] = evt->u.abs->value;
+        move = evt->u.abs;
+        s->axis[move->axis] = move->value;
         break;
     case INPUT_EVENT_KIND_REL:
-        s->axis[evt->u.rel->axis] += evt->u.rel->value;
+        move = evt->u.rel;
+        s->axis[move->axis] += move->value;
         break;
     default:
         break;
ui/input.c +31 -23

93 lines not on this page · raw message

Signature · 1 line
2.5.0
Reviewed-by on v1 4/17
#9 lore raw

Re: [Qemu-devel] [PATCH 04/17] ui: Shorten references into InputEvent

Quoted 12 lines · Eric Blake

An upcoming patch will alter how simple unions, like InputEvent, are laid out, which will impact all lines of the form 'evt->u.XXX'. To minimize the impact of that patch, use a temporary variable to reduce the number of lines needing modification when an internal reference within InputEvent changes layout.

There was one instance in hid.c:hid_pointer_event() where the code was referring to evt->u.rel inside the case label where evt->u.abs is the correct name; thankfully, both members of the union have the same type, so it happened to work, but it is now cleaner.

Quoted 9 lines
---
 hw/char/escc.c              | 12 +++++-----
 hw/input/hid.c              | 36 +++++++++++++++++-------------
 hw/input/ps2.c              | 27 ++++++++++++++---------
 hw/input/virtio-input-hid.c | 33 ++++++++++++++++-----------
 replay/replay-input.c       | 31 ++++++++++++++++----------
 ui/input-legacy.c           | 26 +++++++++++++---------
 ui/input.c                  | 54 ++++++++++++++++++++++++++-------------------
 7 files changed, 130 insertions(+), 89 deletions(-)

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
author
#10 lore raw

PATCH 5/17 qapi: Avoid use of 'data' member of qapi unions

In reply to Eric Blake

qapi code generators currently create a 'void *data' member as part of the anonymous union embedded in the C struct corresponding to a qapi union. However, directly assigning to this member of the union feels a bit fishy, when we can directly use the rest of the struct instead.

---
v1: no change
Previously posted as part of qapi cleanup series F:
v6: rebase to latest

---
 blockdev.c | 31 +++++++++++++++++--------------
 ui/input.c |  2 +-
 2 files changed, 18 insertions(+), 15 deletions(-)
blockdev.c +17 -14
index 1f73478..09b9586 100644
@@ -1204,15 +1204,11 @@ void hmp_commit(Monitor *mon, const QDict *qdict)
     }
 }
 
-static void blockdev_do_action(TransactionActionKind type, void *data,
-                               Error **errp)
+static void blockdev_do_action(TransactionAction *action, Error **errp)
 {
-    TransactionAction action;
     TransactionActionList list;
 
-    action.type = type;
-    action.u.data = data;
-    list.value = &action;
+    list.value = action;
     list.next = NULL;
     qmp_transaction(&list, false, NULL, errp);
 }
@@ -1238,8 +1234,11 @@ void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
         .has_mode = has_mode,
         .mode = mode,
     };
-    blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
-                       &snapshot, errp);
+    TransactionAction action = {
+        .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
+        .u.blockdev_snapshot_sync = &snapshot,
+    };
+    blockdev_do_action(&action, errp);
 }
 
 void qmp_blockdev_snapshot(const char *node, const char *overlay,
@@ -1249,9 +1248,11 @@ void qmp_blockdev_snapshot(const char *node, const char *overlay,
         .node = (char *) node,
         .overlay = (char *) overlay
     };
-
-    blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
-                       &snapshot_data, errp);
+    TransactionAction action = {
+        .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
+        .u.blockdev_snapshot = &snapshot_data,
+    };
+    blockdev_do_action(&action, errp);
 }
 
 void qmp_blockdev_snapshot_internal_sync(const char *device,
@@ -1262,9 +1263,11 @@ void qmp_blockdev_snapshot_internal_sync(const char *device,
         .device = (char *) device,
         .name = (char *) name
     };
-
-    blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
-                       &snapshot, errp);
+    TransactionAction action = {
+        .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
+        .u.blockdev_snapshot_internal_sync = &snapshot,
+    };
+    blockdev_do_action(&action, errp);
 }
 
 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
ui/input.c +1 -1
index e15c618..1e81c25 100644
@@ -472,7 +472,7 @@ InputEvent *qemu_input_event_new_move(InputEventKind kind,
     InputMoveEvent *move = g_new0(InputMoveEvent, 1);
 
     evt->type = kind;
-    evt->u.data = move;
+    evt->u.rel = move; /* also would work as evt->u.abs */
     move->axis = axis;
     move->value = value;
     return evt;
Signature · 1 line
2.5.0
Reviewed-by on v1 5/17
#11 lore raw

Re: [Qemu-devel] [PATCH 05/17] qapi: Avoid use of 'data' member of qapi unions

Quoted 8 lines · Eric Blake

qapi code generators currently create a 'void *data' member as part of the anonymous union embedded in the C struct corresponding to a qapi union. However, directly assigning to this member of the union feels a bit fishy, when we can directly use the rest of the struct instead.

Quoted 8 lines

---
v1: no change
Previously posted as part of qapi cleanup series F:
v6: rebase to latest

---
 blockdev.c | 31 +++++++++++++++++--------------
 ui/input.c |  2 +-
 2 files changed, 18 insertions(+), 15 deletions(-)

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
author
#12 lore raw

PATCH 6/17 chardev: Drop useless ChardevDummy type

In reply to Eric Blake

Commit d0d7708b made ChardevDummy be an empty wrapper type around ChardevCommon. But there is no technical reason for this indirection, so simplify the code by directly using the base type.

Also change the fallback assignment to assign u.null rather than u.data, since a future patch will remove the data member of the C struct generated for QAPI unions.

---
 backends/baum.c    |  2 +-
 backends/msmouse.c |  2 +-
 qemu-char.c        |  6 +++---
 qapi-schema.json   | 15 ++++++---------
 4 files changed, 11 insertions(+), 14 deletions(-)
backends/baum.c +1 -1
index 374562a..c11320e 100644
@@ -567,7 +567,7 @@ static CharDriverState *chr_baum_init(const char *id,
                                       ChardevReturn *ret,
                                       Error **errp)
 {
-    ChardevCommon *common = qapi_ChardevDummy_base(backend->u.braille);
+    ChardevCommon *common = backend->u.braille;
     BaumDriverState *baum;
     CharDriverState *chr;
     brlapi_handle_t *handle;
backends/msmouse.c +1 -1
index 9a82efd..5e1833c 100644
@@ -68,7 +68,7 @@ static CharDriverState *qemu_chr_open_msmouse(const char *id,
                                               ChardevReturn *ret,
                                               Error **errp)
 {
-    ChardevCommon *common = qapi_ChardevDummy_base(backend->u.msmouse);
+    ChardevCommon *common = backend->u.msmouse;
     CharDriverState *chr;
 
     chr = qemu_chr_alloc(common, errp);
qemu-char.c +3 -3
index cfc82bc..6a0fc74 100644
@@ -420,7 +420,7 @@ static CharDriverState *qemu_chr_open_null(const char *id,
                                            Error **errp)
 {
     CharDriverState *chr;
-    ChardevCommon *common = qapi_ChardevDummy_base(backend->u.null);
+    ChardevCommon *common = backend->u.null;
 
     chr = qemu_chr_alloc(common, errp);
     if (!chr) {
@@ -1366,7 +1366,7 @@ static CharDriverState *qemu_chr_open_pty(const char *id,
     PtyCharDriver *s;
     int master_fd, slave_fd;
     char pty_name[PATH_MAX];
-    ChardevCommon *common = qapi_ChardevDummy_base(backend->u.pty);
+    ChardevCommon *common = backend->u.pty;
 
     master_fd = qemu_openpty_raw(&slave_fd, pty_name);
     if (master_fd < 0) {
@@ -3817,7 +3817,7 @@ CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
     } else {
         ChardevCommon *cc = g_new0(ChardevCommon, 1);
         qemu_chr_parse_common(opts, cc);
-        backend->u.data = cc;
+        backend->u.null = cc; /* Any ChardevCommon member would work */
     }
 
     ret = qmp_chardev_add(bid ? bid : id, backend, errp);
qapi-schema.json +6 -9
index 8d04897..f64d4ab 100644
@@ -3271,23 +3271,20 @@
 #
 # Since: 1.4 (testdev since 2.2)
 ##
-{ 'struct': 'ChardevDummy', 'data': { },
-  'base': 'ChardevCommon' }
-
 { 'union': 'ChardevBackend', 'data': { 'file'   : 'ChardevFile',
                                        'serial' : 'ChardevHostdev',
                                        'parallel': 'ChardevHostdev',
                                        'pipe'   : 'ChardevHostdev',
                                        'socket' : 'ChardevSocket',
                                        'udp'    : 'ChardevUdp',
-                                       'pty'    : 'ChardevDummy',
-                                       'null'   : 'ChardevDummy',
+                                       'pty'    : 'ChardevCommon',
+                                       'null'   : 'ChardevCommon',
                                        'mux'    : 'ChardevMux',
-                                       'msmouse': 'ChardevDummy',
-                                       'braille': 'ChardevDummy',
-                                       'testdev': 'ChardevDummy',
+                                       'msmouse': 'ChardevCommon',
+                                       'braille': 'ChardevCommon',
+                                       'testdev': 'ChardevCommon',
                                        'stdio'  : 'ChardevStdio',
-                                       'console': 'ChardevDummy',
+                                       'console': 'ChardevCommon',
                                        'spicevmc' : 'ChardevSpiceChannel',
                                        'spiceport' : 'ChardevSpicePort',
                                        'vc'     : 'ChardevVC',
Signature · 1 line
2.5.0
Reviewed-by on v1 6/17
#13 lore raw

Re: [Qemu-devel] [PATCH 06/17] chardev: Drop useless ChardevDummy type

Quoted 8 lines · Eric Blake

Commit d0d7708b made ChardevDummy be an empty wrapper type around ChardevCommon. But there is no technical reason for this indirection, so simplify the code by directly using the base type.

Also change the fallback assignment to assign u.null rather than u.data, since a future patch will remove the data member of the C struct generated for QAPI unions.

Quoted 7 lines
---
 backends/baum.c    |  2 +-
 backends/msmouse.c |  2 +-
 qemu-char.c        |  6 +++---
 qapi-schema.json   | 15 ++++++---------
 4 files changed, 11 insertions(+), 14 deletions(-)

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
author
#14 lore raw

PATCH 7/17 qapi: Drop useless 'data' member of unions

In reply to Eric Blake

Now that we no longer have any clients of the 'void *data' member injected into unions, we can drop it. Update the testsuite to drop the negative test union-clash-data, and replace it with a positive test in qapi-schema-test that proves that we no longer have a name collision.

---
v1: drop patch that forced :empty as base to all structs Previously posted as part of qapi cleanup subset F:
v6: rebase to earlier changes

---
 scripts/qapi-types.py                   | 9 ---------
 tests/Makefile                          | 1 -
 tests/qapi-schema/qapi-schema-test.json | 2 +-
 tests/qapi-schema/qapi-schema-test.out  | 4 ++--
 tests/qapi-schema/union-clash-data.err  | 0
 tests/qapi-schema/union-clash-data.exit | 1 -
 tests/qapi-schema/union-clash-data.json | 7 -------
 tests/qapi-schema/union-clash-data.out  | 9 ---------
 8 files changed, 3 insertions(+), 30 deletions(-)
 delete mode 100644 tests/qapi-schema/union-clash-data.err
 delete mode 100644 tests/qapi-schema/union-clash-data.exit
 delete mode 100644 tests/qapi-schema/union-clash-data.json
 delete mode 100644 tests/qapi-schema/union-clash-data.out
scripts/qapi-types.py +0 -9
index eac90d2..b68e85a 100644
@@ -116,17 +116,8 @@ static inline %(base)s *qapi_%(c_name)s_base(const %(c_name)s *obj)
 
 
 def gen_variants(variants):
-    # FIXME: What purpose does data serve, besides preventing a union that
-    # has a branch named 'data'? We use it in qapi-visit.py to decide
-    # whether to bypass the switch statement if visiting the discriminator
-    # failed; but since we 0-initialize structs, and cannot tell what
-    # branch of the union is in use if the discriminator is invalid, there
-    # should not be any data leaks even without a data pointer.  Or, if
-    # 'data' is merely added to guarantee we don't have an empty union,
-    # shouldn't we enforce that at .json parse time?
     ret = mcgen('''
     union { /* union tag is @%(c_name)s */
-        void *data;
 ''',
                 c_name=c_name(variants.tag_member.name))
 
tests/Makefile +0 -1
index 04e34b5..cd4bbd4 100644
@@ -358,7 +358,6 @@ qapi-schema += unicode-str.json
 qapi-schema += union-base-no-discriminator.json
 qapi-schema += union-branch-case.json
 qapi-schema += union-clash-branches.json
-qapi-schema += union-clash-data.json
 qapi-schema += union-empty.json
 qapi-schema += union-invalid-base.json
 qapi-schema += union-optional-branch.json
tests/qapi-schema/qapi-schema-test.json +1 -1
index 632964a..b5d0c53 100644
@@ -115,7 +115,7 @@
             'number': ['number'],
             'boolean': ['bool'],
             'string': ['str'],
-            'sizes': ['size'],
+            'data': ['size'],
             'any': ['any'] } }
 
 # testing commands
tests/qapi-schema/qapi-schema-test.out +2 -2
index f5e2a73..225e2db 100644
@@ -139,9 +139,9 @@ object UserDefNativeListUnion
     case number: :obj-numberList-wrapper
     case boolean: :obj-boolList-wrapper
     case string: :obj-strList-wrapper
-    case sizes: :obj-sizeList-wrapper
+    case data: :obj-sizeList-wrapper
     case any: :obj-anyList-wrapper
-enum UserDefNativeListUnionKind ['integer', 's8', 's16', 's32', 's64', 'u8', 'u16', 'u32', 'u64', 'number', 'boolean', 'string', 'sizes', 'any']
+enum UserDefNativeListUnionKind ['integer', 's8', 's16', 's32', 's64', 'u8', 'u16', 'u32', 'u64', 'number', 'boolean', 'string', 'data', 'any']
 object UserDefOne
     base UserDefZero
     member string: str optional=False
tests/qapi-schema/union-clash-data.err deleted +0 -0
deleted file mode 100644
index e69de29..0000000
tests/qapi-schema/union-clash-data.exit deleted +0 -1
deleted file mode 100644
index 573541a..0000000
@@ -1 +0,0 @@
-0
tests/qapi-schema/union-clash-data.json deleted +0 -7
deleted file mode 100644
index 7308e69..0000000
@@ -1,7 +0,0 @@
-# Union branch 'data'
-# FIXME: this parses, but then fails to compile due to a duplicate 'data'
-# (one from the branch name, another as a filler to avoid an empty union).
-# we should either detect the collision at parse time, or change the
-# generated struct to allow this to compile.
-{ 'union': 'TestUnion',
-  'data': { 'data': 'int' } }
tests/qapi-schema/union-clash-data.out deleted +0 -9
deleted file mode 100644
index f5752f4..0000000
@@ -1,9 +0,0 @@
-object :empty
-object :obj-int-wrapper
-    member data: int optional=False
-enum QType ['none', 'qnull', 'qint', 'qstring', 'qdict', 'qlist', 'qfloat', 'qbool']
-    prefix QTYPE
-object TestUnion
-    member type: TestUnionKind optional=False
-    case data: :obj-int-wrapper
-enum TestUnionKind ['data']
Signature · 1 line
2.5.0
Reviewed-by on v1 7/17
#15 lore raw

Re: [Qemu-devel] [PATCH 07/17] qapi: Drop useless 'data' member of unions

Quoted 12 lines · Eric Blake

Now that we no longer have any clients of the 'void *data' member injected into unions, we can drop it. Update the testsuite to drop the negative test union-clash-data, and replace it with a positive test in qapi-schema-test that proves that we no longer have a name collision.

---
v1: drop patch that forced :empty as base to all structs Previously posted as part of qapi cleanup subset F:
v6: rebase to earlier changes

Quoted 14 lines
---
 scripts/qapi-types.py                   | 9 ---------
 tests/Makefile                          | 1 -
 tests/qapi-schema/qapi-schema-test.json | 2 +-
 tests/qapi-schema/qapi-schema-test.out  | 4 ++--
 tests/qapi-schema/union-clash-data.err  | 0
 tests/qapi-schema/union-clash-data.exit | 1 -
 tests/qapi-schema/union-clash-data.json | 7 -------
 tests/qapi-schema/union-clash-data.out  | 9 ---------
 8 files changed, 3 insertions(+), 30 deletions(-)
 delete mode 100644 tests/qapi-schema/union-clash-data.err
 delete mode 100644 tests/qapi-schema/union-clash-data.exit
 delete mode 100644 tests/qapi-schema/union-clash-data.json
 delete mode 100644 tests/qapi-schema/union-clash-data.out

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
author
#16 lore raw

PATCH 8/17 qapi-visit: Factor out gen_visit_fields_call()

In reply to Eric Blake

Upcoming patches will be adding several contexts where we want to handle the visit of an implicit type (an anonymous base type, or an anonymous branch of a flat union) by directly inlining the visit of each of the implicit type's member fields. The work is made easier by factoring out a new helper method, gen_visit_fields_call(), so that the caller doesn't need to care whether the type it is visiting is implicit or normal.

For now, the only implicit type we encounter are the branches of a simple union; the initial implementation of the helper method is hard-coded to that usage, but it gets us one step closer to completely dropping the hack of simple_union_type().

Generated output is unchanged.

---
 scripts/qapi-visit.py | 48 ++++++++++++++++++++++++++----------------------
 1 file changed, 26 insertions(+), 22 deletions(-)
scripts/qapi-visit.py +26 -22
index 2308268..ab773f6 100644
@@ -31,7 +31,7 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_type)sobj, Error **
 
 
 def gen_visit_fields_decl(typ):
-    if typ.name in struct_fields_seen:
+    if typ.is_implicit() or typ.name in struct_fields_seen:
         return ''
     struct_fields_seen.add(typ.name)
     return mcgen('''
@@ -41,6 +41,25 @@ static void visit_type_%(c_type)s_fields(Visitor *v, %(c_type)s *obj, Error **er
                  c_type=typ.c_name())
 
 
+def gen_visit_fields_call(typ, c_name):
+    ret = ''
+    assert isinstance(typ, QAPISchemaObjectType)
+    if typ.is_implicit():
+        # TODO ugly special case for simple union
+        assert len(typ.members) == 1
+        assert not typ.variants
+        ret += mcgen('''
+    visit_type_%(c_type)s(v, "data", %(c_name)s, &err);
+''',
+                     c_type=typ.members[0].type.c_name(), c_name=c_name)
+    else:
+        ret += mcgen('''
+    visit_type_%(c_type)s_fields(v, %(c_name)s, &err);
+''',
+                     c_type=typ.c_name(), c_name=c_name)
+    return ret
+
+
 def gen_visit_struct_fields(name, base, members, variants):
     ret = ''
 
@@ -48,9 +67,7 @@ def gen_visit_struct_fields(name, base, members, variants):
         ret += gen_visit_fields_decl(base)
     if variants:
         for var in variants.variants:
-            # Ugly special case for simple union TODO get rid of it
-            if not var.simple_union_type():
-                ret += gen_visit_fields_decl(var.type)
+            ret += gen_visit_fields_decl(var.type)
 
     struct_fields_seen.add(name)
     ret += mcgen('''
@@ -63,10 +80,7 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s *obj, Error **er
                  c_name=c_name(name))
 
     if base:
-        ret += mcgen('''
-    visit_type_%(c_type)s_fields(v, (%(c_type)s *)obj, &err);
-''',
-                     c_type=base.c_name())
+        ret += gen_visit_fields_call(base, '(%s *)obj' % base.c_name())
         ret += gen_err_check()
 
     ret += gen_visit_fields(members, prefix='obj->')
@@ -78,26 +92,16 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s *obj, Error **er
                      c_name=c_name(variants.tag_member.name))
 
         for var in variants.variants:
-            # TODO ugly special case for simple union
-            simple_union_type = var.simple_union_type()
             ret += mcgen('''
     case %(case)s:
 ''',
                          case=c_enum_const(variants.tag_member.type.name,
                                            var.name,
                                            variants.tag_member.type.prefix))
-            if simple_union_type:
-                ret += mcgen('''
-        visit_type_%(c_type)s(v, "data", &obj->u.%(c_name)s, &err);
-''',
-                             c_type=simple_union_type.c_name(),
-                             c_name=c_name(var.name))
-            else:
-                ret += mcgen('''
-        visit_type_%(c_type)s_fields(v, &obj->u.%(c_name)s, &err);
-''',
-                             c_type=var.type.c_name(),
-                             c_name=c_name(var.name))
+            push_indent()
+            ret += gen_visit_fields_call(var.type,
+                                         '&obj->u.' + c_name(var.name))
+            pop_indent()
             ret += mcgen('''
         break;
 ''')
Signature · 1 line
2.5.0
author
#17 lore raw

PATCH 9/17 qapi: Add type.is_empty() helper

In reply to Eric Blake

And use it in qapi-types and qapi-event. Down the road, we may want to lift our artificial restriction of no variants at the top level of an event, at which point, inlining our check for whether members is empty will no longer be sufficient, but adding a check for variants adds verbosity; in the meantime, add some asserts in places where we don't handle variants.

More immediately, the new .is_empty() helper will help fix a bug in qapi-visit in the next patch, where the generator did not handle an explicit empty type in the same was as a missing type.

No change to generated code.

---
v1: add some asserts
Previously posted as part of qapi cleanup subset E:
v9: improve commit message
v8: no change
v7: rebase to context change
v6: new patch

---
 scripts/qapi.py       | 5 +++++
 scripts/qapi-event.py | 7 ++++---
 scripts/qapi-types.py | 2 +-
 3 files changed, 10 insertions(+), 4 deletions(-)
scripts/qapi.py +5 -0
index 8497777..8a4f952 100644
@@ -962,6 +962,7 @@ class QAPISchemaObjectType(QAPISchemaType):
             assert isinstance(self.base, QAPISchemaObjectType)
             self.base.check(schema)
             self.base.check_clash(schema, self.info, seen)
+            assert not self.base.variants
         for m in self.local_members:
             m.check(schema)
             m.check_clash(self.info, seen)
@@ -983,6 +984,10 @@ class QAPISchemaObjectType(QAPISchemaType):
         # See QAPISchema._make_implicit_object_type()
         return self.name[0] == ':'
 
+    def is_empty(self):
+        assert self.members is not None
+        return not self.members and not self.variants
+
     def c_name(self):
         assert not self.is_implicit()
         return QAPISchemaType.c_name(self)
scripts/qapi-event.py +4 -3
index 544ae12..8be3b44 100644
@@ -39,7 +39,7 @@ def gen_event_send(name, arg_type):
 ''',
                 proto=gen_event_send_proto(name, arg_type))
 
-    if arg_type and arg_type.members:
+    if arg_type and not arg_type.is_empty():
         ret += mcgen('''
     QmpOutputVisitor *qov;
     Visitor *v;
@@ -58,7 +58,8 @@ def gen_event_send(name, arg_type):
 ''',
                  name=name)
 
-    if arg_type and arg_type.members:
+    if arg_type and not arg_type.is_empty():
+        assert not arg_type.variants
         ret += mcgen('''
     qov = qmp_output_visitor_new();
     v = qmp_output_get_visitor(qov);
@@ -88,7 +89,7 @@ out_obj:
 ''',
                  c_enum=c_enum_const(event_enum_name, name))
 
-    if arg_type and arg_type.members:
+    if arg_type and not arg_type.is_empty():
         ret += mcgen('''
 out:
     qmp_output_visitor_cleanup(qov);
scripts/qapi-types.py +1 -1
index b68e85a..1eb5622 100644
@@ -90,7 +90,7 @@ struct %(c_name)s {
     # potential issues with attempting to malloc space for zero-length
     # structs in C, and also incompatibility with C++ (where an empty
     # struct is size 1).
-    if not (base and base.members) and not members and not variants:
+    if (not base or base.is_empty()) and not members and not variants:
         ret += mcgen('''
     char qapi_dummy_field_for_empty_struct;
 ''')
Signature · 1 line
2.5.0
author
#18 lore raw

PATCH 10/17 qapi: Fix command with named empty argument type

In reply to Eric Blake

The generator special-cased

{ 'command':'foo', 'data': {} }

to avoid emitting a visitor variable, but failed to see that

{ 'struct':'NamedEmptyType, 'data': {} }
{ 'command':'foo', 'data':'NamedEmptyType' }

needs the same treatment. There, the generator happily generates a visitor to get no arguments, and a visitor to destroy no arguments; and the compiler isn't happy with that, as demonstrated by the updated qapi-schema-test.json:

tests/test-qmp-marshal.c: In function ‘qmp_marshal_user_def_cmd0’:
tests/test-qmp-marshal.c:264:14: error: variable ‘v’ set but not used [-Werror=unused-but-set-variable]

       Visitor *v;
                ^

No change to generated code except for the testsuite addition.

---
v1: enhance commit message
Previously posted as part of qapi cleanup subset E:
v9: no change
v8: no change
v7: no change
v6: new patch

---
 scripts/qapi-commands.py                | 6 +++---
 tests/test-qmp-commands.c               | 5 +++++
 tests/qapi-schema/qapi-schema-test.json | 2 ++
 tests/qapi-schema/qapi-schema-test.out  | 2 ++
 4 files changed, 12 insertions(+), 3 deletions(-)
scripts/qapi-commands.py +3 -3
index f831621..854b389 100644
@@ -65,7 +65,7 @@ def gen_marshal_vars(arg_type, ret_type):
 ''',
                      c_type=ret_type.c_type())
 
-    if arg_type:
+    if arg_type and not arg_type.is_empty():
         ret += mcgen('''
     QmpInputVisitor *qiv = qmp_input_visitor_new_strict(QOBJECT(args));
     QapiDeallocVisitor *qdv;
@@ -97,7 +97,7 @@ def gen_marshal_vars(arg_type, ret_type):
 def gen_marshal_input_visit(arg_type, dealloc=False):
     ret = ''
 
-    if not arg_type:
+    if not arg_type or arg_type.is_empty():
         return ret
 
     if dealloc:
@@ -177,7 +177,7 @@ def gen_marshal(name, arg_type, ret_type):
 
     # 'goto out' produced by gen_marshal_input_visit->gen_visit_fields()
     # for each arg_type member, and by gen_call() for ret_type
-    if (arg_type and arg_type.members) or ret_type:
+    if (arg_type and not arg_type.is_empty()) or ret_type:
         ret += mcgen('''
 
 out:
tests/test-qmp-commands.c +5 -0
index d6171f2..650ba46 100644
@@ -13,6 +13,11 @@ void qmp_user_def_cmd(Error **errp)
 {
 }
 
+Empty2 *qmp_user_def_cmd0(Error **errp)
+{
+    return g_new0(Empty2, 1);
+}
+
 void qmp_user_def_cmd1(UserDefOne * ud1, Error **errp)
 {
 }
tests/qapi-schema/qapi-schema-test.json +2 -0
index b5d0c53..33e8517 100644
@@ -18,6 +18,8 @@
 { 'struct': 'Empty1', 'data': { } }
 { 'struct': 'Empty2', 'base': 'Empty1', 'data': { } }
 
+{ 'command': 'user_def_cmd0', 'data': 'Empty2', 'returns': 'Empty2' }
+
 # for testing override of default naming heuristic
 { 'enum': 'QEnumTwo',
   'prefix': 'QENUM_TWO',
tests/qapi-schema/qapi-schema-test.out +2 -0
index 225e2db..6b97fa5 100644
@@ -203,6 +203,8 @@ command guest-sync :obj-guest-sync-arg -> any
    gen=True success_response=True
 command user_def_cmd None -> None
    gen=True success_response=True
+command user_def_cmd0 Empty2 -> Empty2
+   gen=True success_response=True
 command user_def_cmd1 :obj-user_def_cmd1-arg -> None
    gen=True success_response=True
 command user_def_cmd2 :obj-user_def_cmd2-arg -> UserDefTwo
Signature · 1 line
2.5.0
author
#19 lore raw

PATCH 11/17 qapi-visit: Simplify visit of empty branch in union

In reply to Eric Blake

Now that we have is_empty() and gen_visit_fields_call(), it's fairly easy to skip the visit of a variant type that has no members. Only one such instance exists at the moment (CpuInfoOther), but the idea of a union where some branches add no fields beyond the base type is common enough that we may add syntax for other cases, as in
{ 'union':'U', 'base':'B', 'discriminator':'D',

    'data': { 'default': {}, 'extra':'Type' } }

Note that the Abort type is another example of an empty type, but it is only used by a simple union rather than a flat union; and with simple unions, the wrapper type providing the 'data' QMP key is not empty.

---
 scripts/qapi-visit.py | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
scripts/qapi-visit.py +3 -1
index ab773f6..127c84e0 100644
@@ -44,7 +44,9 @@ static void visit_type_%(c_type)s_fields(Visitor *v, %(c_type)s *obj, Error **er
 def gen_visit_fields_call(typ, c_name):
     ret = ''
     assert isinstance(typ, QAPISchemaObjectType)
-    if typ.is_implicit():
+    if typ.is_empty():
+        pass
+    elif typ.is_implicit():
         # TODO ugly special case for simple union
         assert len(typ.members) == 1
         assert not typ.variants
Signature · 1 line
2.5.0
author
#20 lore raw

PATCH 12/17 qapi: Don't special-case simple union wrappers

In reply to Eric Blake

Simple unions were carrying a special case that hid their 'data' QMP member from the resulting C struct, via the hack method QAPISchemaObjectTypeVariant.simple_union_type(). But using the work we started by unboxing flat union and alternate branches, we expose the simple union's implicit type in qapi-types.h as an anonymous type, and drop our last use of the hack.

| struct ImageInfoSpecific {
|     ImageInfoSpecificKind type;
|     union { /* union tag is @type */
|         void *data;
|-        ImageInfoSpecificQCow2 *qcow2;
|-        ImageInfoSpecificVmdk *vmdk;
|+        struct {
|+            ImageInfoSpecificQCow2 *data;
|+        } qcow2;
|+        struct {
|+            ImageInfoSpecificVmdk *data;
|+        } vmdk;
|     } u;
| };

All clients of simple unions have to adjust from using su->u.member to now using su->u.member.data; while this touches a number of files in the tree, some earlier cleanup patches helped minimize the change to the initialization of a temporary variable rather than every single field access. The generated qapi-visit.c code is included in the files affected by the layout change, with a diff that looks like:

|@@ -4510,10 +4567,16 @@ static void visit_type_ImageInfoSpecific
|     }
|     switch (obj->type) {
|     case IMAGE_INFO_SPECIFIC_KIND_QCOW2:
|-        visit_type_ImageInfoSpecificQCow2(v, "data", &obj->u.qcow2, &err);
|+        visit_type_ImageInfoSpecificQCow2(v, "data", &obj->u.qcow2.data, &err);
|+        if (err) {
|+            goto out;
|+        }
|         break;
|     case IMAGE_INFO_SPECIFIC_KIND_VMDK:
|-        visit_type_ImageInfoSpecificVmdk(v, "data", &obj->u.vmdk, &err);
|+        visit_type_ImageInfoSpecificVmdk(v, "data", &obj->u.vmdk.data, &err);
|+        if (err) {
|+            goto out;
|+        }
|         break;
|     default:
|         abort();
|     }
|
| out:
|     error_propagate(errp, err);

The added error checks there are a side effect of visiting all fields of each implicit struct (there is only one such field for simple unions); but do not change semantics, and will be important when later patches allow for flat unions with anonymous branches with more than one field. That future work will look like:
{ 'union': 'Foo', 'base': 'Base', 'discriminator': 'type',
'data': { 'branch1': { 'anonymous': 'str', 'number': 'int' },

            'branch2': 'Named' } }
---
 scripts/qapi.py                 | 10 -----
 scripts/qapi-types.py           | 22 ++++++++---
 scripts/qapi-visit.py           | 15 +++-----
 backends/baum.c                 |  2 +-
 backends/msmouse.c              |  2 +-
 block/nbd.c                     |  6 +--
 block/qcow2.c                   |  6 +--
 block/vmdk.c                    |  8 ++--
 blockdev.c                      | 24 ++++++------
 hmp.c                           |  8 ++--
 hw/char/escc.c                  |  2 +-
 hw/input/hid.c                  |  8 ++--
 hw/input/ps2.c                  |  6 +--
 hw/input/virtio-input-hid.c     |  8 ++--
 hw/mem/pc-dimm.c                |  4 +-
 net/dump.c                      |  2 +-
 net/hub.c                       |  2 +-
 net/l2tpv3.c                    |  2 +-
 net/net.c                       |  4 +-
 net/netmap.c                    |  2 +-
 net/slirp.c                     |  2 +-
 net/socket.c                    |  2 +-
 net/tap.c                       |  4 +-
 net/vhost-user.c                |  2 +-
 numa.c                          |  4 +-
 qemu-char.c                     | 82 +++++++++++++++++++++--------------------
 qemu-nbd.c                      |  6 +--
 replay/replay-input.c           | 44 +++++++++++-----------
 spice-qemu-char.c               | 14 ++++---
 tests/test-io-channel-socket.c  | 40 ++++++++++----------
 tests/test-qmp-commands.c       |  2 +-
 tests/test-qmp-input-visitor.c  | 25 +++++++------
 tests/test-qmp-output-visitor.c | 24 ++++++------
 tpm.c                           |  2 +-
 ui/console.c                    |  4 +-
 ui/input-keymap.c               | 10 ++---
 ui/input-legacy.c               |  8 ++--
 ui/input.c                      | 34 ++++++++---------
 ui/vnc-auth-sasl.c              |  3 +-
 ui/vnc.c                        | 29 ++++++++-------
 util/qemu-sockets.c             | 35 +++++++++---------
 41 files changed, 262 insertions(+), 257 deletions(-)
scripts/qapi.py +0 -10
index 8a4f952..1dc8801 100644
@@ -1115,16 +1115,6 @@ class QAPISchemaObjectTypeVariant(QAPISchemaObjectTypeMember):
     def __init__(self, name, typ):
         QAPISchemaObjectTypeMember.__init__(self, name, typ, False)
 
-    # This function exists to support ugly simple union special cases
-    # TODO get rid of them, and drop the function
-    def simple_union_type(self):
-        if (self.type.is_implicit() and
-                isinstance(self.type, QAPISchemaObjectType)):
-            assert len(self.type.members) == 1
-            assert not self.type.variants
-            return self.type.members[0].type
-        return None
-
 
 class QAPISchemaAlternateType(QAPISchemaType):
     def __init__(self, name, info, variants):
scripts/qapi-types.py +16 -6
index 1eb5622..36ff770 100644
@@ -122,14 +122,24 @@ def gen_variants(variants):
                 c_name=c_name(variants.tag_member.name))
 
     for var in variants.variants:
-        # Ugly special case for simple union TODO get rid of it
-        simple_union_type = var.simple_union_type()
-        typ = simple_union_type or var.type
-        ret += mcgen('''
+        if (isinstance(var.type, QAPISchemaObjectType) and
+                var.type.is_implicit()):
+            ret += mcgen('''
+        struct {
+''')
+            push_indent(8)
+            ret += gen_struct_fields(var.type.members)
+            pop_indent(8)
+            ret += mcgen('''
+        } %(c_name)s;
+''',
+                         c_name=c_name(var.name))
+        else:
+            ret += mcgen('''
         %(c_type)s %(c_name)s;
 ''',
-                     c_type=typ.c_type(is_unboxed=not simple_union_type),
-                     c_name=c_name(var.name))
+                         c_type=var.type.c_type(is_unboxed=True),
+                         c_name=c_name(var.name))
 
     ret += mcgen('''
     } u;
scripts/qapi-visit.py +6 -9
index 127c84e0..3aca6a7 100644
@@ -41,24 +41,20 @@ static void visit_type_%(c_type)s_fields(Visitor *v, %(c_type)s *obj, Error **er
                  c_type=typ.c_name())
 
 
-def gen_visit_fields_call(typ, c_name):
+def gen_visit_fields_call(typ, direct_name, implicit_name=None):
     ret = ''
     assert isinstance(typ, QAPISchemaObjectType)
     if typ.is_empty():
         pass
     elif typ.is_implicit():
-        # TODO ugly special case for simple union
-        assert len(typ.members) == 1
+        assert implicit_name
         assert not typ.variants
-        ret += mcgen('''
-    visit_type_%(c_type)s(v, "data", %(c_name)s, &err);
-''',
-                     c_type=typ.members[0].type.c_name(), c_name=c_name)
+        ret += gen_visit_fields(typ.members, prefix=implicit_name)
     else:
         ret += mcgen('''
     visit_type_%(c_type)s_fields(v, %(c_name)s, &err);
 ''',
-                     c_type=typ.c_name(), c_name=c_name)
+                     c_type=typ.c_name(), c_name=direct_name)
     return ret
 
 
@@ -102,7 +98,8 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s *obj, Error **er
                                            variants.tag_member.type.prefix))
             push_indent()
             ret += gen_visit_fields_call(var.type,
-                                         '&obj->u.' + c_name(var.name))
+                                         '&obj->u.' + c_name(var.name),
+                                         'obj->u.' + c_name(var.name) + '.')
             pop_indent()
             ret += mcgen('''
         break;
backends/baum.c +1 -1
index c11320e..eef3467 100644
@@ -567,7 +567,7 @@ static CharDriverState *chr_baum_init(const char *id,
                                       ChardevReturn *ret,
                                       Error **errp)
 {
-    ChardevCommon *common = backend->u.braille;
+    ChardevCommon *common = backend->u.braille.data;
     BaumDriverState *baum;
     CharDriverState *chr;
     brlapi_handle_t *handle;
backends/msmouse.c +1 -1
index 5e1833c..8dea5a1 100644
@@ -68,7 +68,7 @@ static CharDriverState *qemu_chr_open_msmouse(const char *id,
                                               ChardevReturn *ret,
                                               Error **errp)
 {
-    ChardevCommon *common = backend->u.msmouse;
+    ChardevCommon *common = backend->u.msmouse.data;
     CharDriverState *chr;
 
     chr = qemu_chr_alloc(common, errp);
block/nbd.c +3 -3
index 9f333c9..836424c 100644
@@ -206,13 +206,13 @@ static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options, char **export,
     if (qdict_haskey(options, "path")) {
         UnixSocketAddress *q_unix;
         saddr->type = SOCKET_ADDRESS_KIND_UNIX;
-        q_unix = saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
+        q_unix = saddr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
         q_unix->path = g_strdup(qdict_get_str(options, "path"));
         qdict_del(options, "path");
     } else {
         InetSocketAddress *inet;
         saddr->type = SOCKET_ADDRESS_KIND_INET;
-        inet = saddr->u.inet = g_new0(InetSocketAddress, 1);
+        inet = saddr->u.inet.data = g_new0(InetSocketAddress, 1);
         inet->host = g_strdup(qdict_get_str(options, "host"));
         if (!qdict_get_try_str(options, "port")) {
             inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
@@ -321,7 +321,7 @@ static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
             error_setg(errp, "TLS only supported over IP sockets");
             goto error;
         }
-        hostname = saddr->u.inet->host;
+        hostname = saddr->u.inet.data->host;
     }
 
     /* establish TCP connection, return error if it fails
block/qcow2.c +3 -3
index 8babecd..31f35f4 100644
@@ -2809,15 +2809,15 @@ static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
 
     *spec_info = (ImageInfoSpecific){
         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
-        .u.qcow2 = g_new(ImageInfoSpecificQCow2, 1),
+        .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
     };
     if (s->qcow_version == 2) {
-        *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
+        *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
             .compat             = g_strdup("0.10"),
             .refcount_bits      = s->refcount_bits,
         };
     } else if (s->qcow_version == 3) {
-        *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
+        *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
             .compat             = g_strdup("1.1"),
             .lazy_refcounts     = s->compatible_features &
                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
block/vmdk.c +4 -4
index a8db5d9..0fc2ce2 100644
@@ -2183,18 +2183,18 @@ static ImageInfoSpecific *vmdk_get_specific_info(BlockDriverState *bs)
 
     *spec_info = (ImageInfoSpecific){
         .type = IMAGE_INFO_SPECIFIC_KIND_VMDK,
-        {
-            .vmdk = g_new0(ImageInfoSpecificVmdk, 1),
+        .u = {
+            .vmdk.data = g_new0(ImageInfoSpecificVmdk, 1),
         },
     };
 
-    *spec_info->u.vmdk = (ImageInfoSpecificVmdk) {
+    *spec_info->u.vmdk.data = (ImageInfoSpecificVmdk) {
         .create_type = g_strdup(s->create_type),
         .cid = s->cid,
         .parent_cid = s->parent_cid,
     };
 
-    next = &spec_info->u.vmdk->extents;
+    next = &spec_info->u.vmdk.data->extents;
     for (i = 0; i < s->num_extents; i++) {
         *next = g_new0(ImageInfoList, 1);
         (*next)->value = vmdk_get_extent_info(&s->extents[i]);
blockdev.c +12 -12
index 09b9586..9b37fa5 100644
@@ -1236,7 +1236,7 @@ void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
     };
     TransactionAction action = {
         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
-        .u.blockdev_snapshot_sync = &snapshot,
+        .u.blockdev_snapshot_sync.data = &snapshot,
     };
     blockdev_do_action(&action, errp);
 }
@@ -1250,7 +1250,7 @@ void qmp_blockdev_snapshot(const char *node, const char *overlay,
     };
     TransactionAction action = {
         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
-        .u.blockdev_snapshot = &snapshot_data,
+        .u.blockdev_snapshot.data = &snapshot_data,
     };
     blockdev_do_action(&action, errp);
 }
@@ -1265,7 +1265,7 @@ void qmp_blockdev_snapshot_internal_sync(const char *device,
     };
     TransactionAction action = {
         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
-        .u.blockdev_snapshot_internal_sync = &snapshot,
+        .u.blockdev_snapshot_internal_sync.data = &snapshot,
     };
     blockdev_do_action(&action, errp);
 }
@@ -1504,7 +1504,7 @@ static void internal_snapshot_prepare(BlkActionState *common,
 
     g_assert(common->action->type ==
              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
-    internal = common->action->u.blockdev_snapshot_internal_sync;
+    internal = common->action->u.blockdev_snapshot_internal_sync.data;
     state = DO_UPCAST(InternalSnapshotState, common, common);
 
     /* 1. parse input */
@@ -1654,7 +1654,7 @@ static void external_snapshot_prepare(BlkActionState *common,
     switch (action->type) {
     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
         {
-            BlockdevSnapshot *s = action->u.blockdev_snapshot;
+            BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
             device = s->node;
             node_name = s->node;
             new_image_file = NULL;
@@ -1663,7 +1663,7 @@ static void external_snapshot_prepare(BlkActionState *common,
         break;
     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
         {
-            BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
+            BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
             device = s->has_device ? s->device : NULL;
             node_name = s->has_node_name ? s->node_name : NULL;
             new_image_file = s->snapshot_file;
@@ -1712,7 +1712,7 @@ static void external_snapshot_prepare(BlkActionState *common,
     }
 
     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
-        BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
+        BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
         const char *format = s->has_format ? s->format : "qcow2";
         enum NewImageMode mode;
         const char *snapshot_node_name =
@@ -1845,7 +1845,7 @@ static void drive_backup_prepare(BlkActionState *common, Error **errp)
     Error *local_err = NULL;
 
     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
-    backup = common->action->u.drive_backup;
+    backup = common->action->u.drive_backup.data;
 
     blk = blk_by_name(backup->device);
     if (!blk) {
@@ -1927,7 +1927,7 @@ static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
     Error *local_err = NULL;
 
     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
-    backup = common->action->u.blockdev_backup;
+    backup = common->action->u.blockdev_backup.data;
 
     blk = blk_by_name(backup->device);
     if (!blk) {
@@ -2013,7 +2013,7 @@ static void block_dirty_bitmap_add_prepare(BlkActionState *common,
         return;
     }
 
-    action = common->action->u.block_dirty_bitmap_add;
+    action = common->action->u.block_dirty_bitmap_add.data;
     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
     qmp_block_dirty_bitmap_add(action->node, action->name,
                                action->has_granularity, action->granularity,
@@ -2032,7 +2032,7 @@ static void block_dirty_bitmap_add_abort(BlkActionState *common)
     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
                                              common, common);
 
-    action = common->action->u.block_dirty_bitmap_add;
+    action = common->action->u.block_dirty_bitmap_add.data;
     /* Should not be able to fail: IF the bitmap was added via .prepare(),
      * then the node reference and bitmap name must have been valid.
      */
@@ -2052,7 +2052,7 @@ static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
         return;
     }
 
-    action = common->action->u.block_dirty_bitmap_clear;
+    action = common->action->u.block_dirty_bitmap_clear.data;
     state->bitmap = block_dirty_bitmap_lookup(action->node,
                                               action->name,
                                               &state->bs,
hmp.c +4 -4
index bfbd667..fac9074 100644
@@ -857,7 +857,7 @@ void hmp_info_tpm(Monitor *mon, const QDict *qdict)
 
         switch (ti->options->type) {
         case TPM_TYPE_OPTIONS_KIND_PASSTHROUGH:
-            tpo = ti->options->u.passthrough;
+            tpo = ti->options->u.passthrough.data;
             monitor_printf(mon, "%s%s%s%s",
                            tpo->has_path ? ",path=" : "",
                            tpo->has_path ? tpo->path : "",
@@ -1736,14 +1736,14 @@ void hmp_sendkey(Monitor *mon, const QDict *qdict)
                 goto err_out;
             }
             keylist->value->type = KEY_VALUE_KIND_NUMBER;
-            keylist->value->u.number = value;
+            keylist->value->u.number.data = value;
         } else {
             int idx = index_from_key(keys, keyname_len);
             if (idx == Q_KEY_CODE__MAX) {
                 goto err_out;
             }
             keylist->value->type = KEY_VALUE_KIND_QCODE;
-            keylist->value->u.qcode = idx;
+            keylist->value->u.qcode.data = idx;
         }
 
         if (!separator) {
@@ -1960,7 +1960,7 @@ void hmp_info_memory_devices(Monitor *mon, const QDict *qdict)
         if (value) {
             switch (value->type) {
             case MEMORY_DEVICE_INFO_KIND_DIMM:
-                di = value->u.dimm;
+                di = value->u.dimm.data;
 
                 monitor_printf(mon, "Memory device [%s]: \"%s\"\n",
                                MemoryDeviceInfoKind_lookup[value->type],
hw/char/escc.c +1 -1
index c7a24ac..7bf09a0 100644
@@ -845,7 +845,7 @@ static void sunkbd_handle_event(DeviceState *dev, QemuConsole *src,
     InputKeyEvent *key;
 
     assert(evt->type == INPUT_EVENT_KIND_KEY);
-    key = evt->u.key;
+    key = evt->u.key.data;
     qcode = qemu_input_key_value_to_qcode(key->key);
     trace_escc_sunkbd_event_in(qcode, QKeyCode_lookup[qcode],
                                key->down);
hw/input/hid.c +4 -4
index 5db4d68..bf8e24f 100644
@@ -124,7 +124,7 @@ static void hid_pointer_event(DeviceState *dev, QemuConsole *src,
 
     switch (evt->type) {
     case INPUT_EVENT_KIND_REL:
-        move = evt->u.rel;
+        move = evt->u.rel.data;
         if (move->axis == INPUT_AXIS_X) {
             e->xdx += move->value;
         } else if (move->axis == INPUT_AXIS_Y) {
@@ -133,7 +133,7 @@ static void hid_pointer_event(DeviceState *dev, QemuConsole *src,
         break;
 
     case INPUT_EVENT_KIND_ABS:
-        move = evt->u.abs;
+        move = evt->u.abs.data;
         if (move->axis == INPUT_AXIS_X) {
             e->xdx = move->value;
         } else if (move->axis == INPUT_AXIS_Y) {
@@ -142,7 +142,7 @@ static void hid_pointer_event(DeviceState *dev, QemuConsole *src,
         break;
 
     case INPUT_EVENT_KIND_BTN:
-        btn = evt->u.btn;
+        btn = evt->u.btn.data;
         if (btn->down) {
             e->buttons_state |= bmap[btn->button];
             if (btn->button == INPUT_BUTTON_WHEELUP) {
@@ -228,7 +228,7 @@ static void hid_keyboard_event(DeviceState *dev, QemuConsole *src,
     HIDState *hs = (HIDState *)dev;
     int scancodes[3], i, count;
     int slot;
-    InputKeyEvent *key = evt->u.key;
+    InputKeyEvent *key = evt->u.key.data;
 
     count = qemu_input_key_value_to_scancode(key->key,
                                              key->down,
hw/input/ps2.c +3 -3
index 7bab7c2..4edd9d2 100644
@@ -182,7 +182,7 @@ static void ps2_keyboard_event(DeviceState *dev, QemuConsole *src,
 {
     PS2KbdState *s = (PS2KbdState *)dev;
     int scancodes[3], i, count;
-    InputKeyEvent *key = evt->u.key;
+    InputKeyEvent *key = evt->u.key.data;
 
     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
     count = qemu_input_key_value_to_scancode(key->key,
@@ -399,7 +399,7 @@ static void ps2_mouse_event(DeviceState *dev, QemuConsole *src,
 
     switch (evt->type) {
     case INPUT_EVENT_KIND_REL:
-        move = evt->u.rel;
+        move = evt->u.rel.data;
         if (move->axis == INPUT_AXIS_X) {
             s->mouse_dx += move->value;
         } else if (move->axis == INPUT_AXIS_Y) {
@@ -408,7 +408,7 @@ static void ps2_mouse_event(DeviceState *dev, QemuConsole *src,
         break;
 
     case INPUT_EVENT_KIND_BTN:
-        btn = evt->u.btn;
+        btn = evt->u.btn.data;
         if (btn->down) {
             s->mouse_buttons |= bmap[btn->button];
             if (btn->button == INPUT_BUTTON_WHEELUP) {
hw/input/virtio-input-hid.c +4 -4
index 7053f75..2aec423 100644
@@ -197,7 +197,7 @@ static void virtio_input_handle_event(DeviceState *dev, QemuConsole *src,
 
     switch (evt->type) {
     case INPUT_EVENT_KIND_KEY:
-        key = evt->u.key;
+        key = evt->u.key.data;
         qcode = qemu_input_key_value_to_qcode(key->key);
         if (qcode && keymap_qcode[qcode]) {
             event.type  = cpu_to_le16(EV_KEY);
@@ -212,7 +212,7 @@ static void virtio_input_handle_event(DeviceState *dev, QemuConsole *src,
         }
         break;
     case INPUT_EVENT_KIND_BTN:
-        btn = evt->u.btn;
+        btn = evt->u.btn.data;
         if (keymap_button[btn->button]) {
             event.type  = cpu_to_le16(EV_KEY);
             event.code  = cpu_to_le16(keymap_button[btn->button]);
@@ -227,14 +227,14 @@ static void virtio_input_handle_event(DeviceState *dev, QemuConsole *src,
         }
         break;
     case INPUT_EVENT_KIND_REL:
-        move = evt->u.rel;
+        move = evt->u.rel.data;
         event.type  = cpu_to_le16(EV_REL);
         event.code  = cpu_to_le16(axismap_rel[move->axis]);
         event.value = cpu_to_le32(move->value);
         virtio_input_send(vinput, &event);
         break;
     case INPUT_EVENT_KIND_ABS:
-        move = evt->u.abs;
+        move = evt->u.abs.data;
         event.type  = cpu_to_le16(EV_ABS);
         event.code  = cpu_to_le16(axismap_abs[move->axis]);
         event.value = cpu_to_le32(move->value);
hw/mem/pc-dimm.c +2 -2
index 1aa12c6..13354fc 100644
@@ -180,7 +180,7 @@ int qmp_pc_dimm_device_list(Object *obj, void *opaque)
                                                NULL);
             di->memdev = object_get_canonical_path(OBJECT(dimm->hostmem));
 
-            info->u.dimm = di;
+            info->u.dimm.data = di;
             elem->value = info;
             elem->next = NULL;
             **prev = elem;
@@ -206,7 +206,7 @@ ram_addr_t get_current_ram_size(void)
         if (value) {
             switch (value->type) {
             case MEMORY_DEVICE_INFO_KIND_DIMM:
-                size += value->u.dimm->size;
+                size += value->u.dimm.data->size;
                 break;
             default:
                 break;
net/dump.c +1 -1
index 61dec9d..94ac32a 100644
@@ -189,7 +189,7 @@ int net_init_dump(const NetClientOptions *opts, const char *name,
     DumpNetClient *dnc;
 
     assert(opts->type == NET_CLIENT_OPTIONS_KIND_DUMP);
-    dump = opts->u.dump;
+    dump = opts->u.dump.data;
 
     assert(peer);
 
net/hub.c +1 -1
index b6d44fd..6d90c6e 100644
@@ -288,7 +288,7 @@ int net_init_hubport(const NetClientOptions *opts, const char *name,
 
     assert(opts->type == NET_CLIENT_OPTIONS_KIND_HUBPORT);
     assert(!peer);
-    hubport = opts->u.hubport;
+    hubport = opts->u.hubport.data;
 
     net_hub_add_port(hubport->hubid, name);
     return 0;
net/l2tpv3.c +1 -1
index 824161c..5c668f7 100644
@@ -546,7 +546,7 @@ int net_init_l2tpv3(const NetClientOptions *opts,
     s->header_mismatch = false;
 
     assert(opts->type == NET_CLIENT_OPTIONS_KIND_L2TPV3);
-    l2tpv3 = opts->u.l2tpv3;
+    l2tpv3 = opts->u.l2tpv3.data;
 
     if (l2tpv3->has_ipv6 && l2tpv3->ipv6) {
         s->ipv6 = l2tpv3->ipv6;
net/net.c +2 -2
index aebf753..648047b 100644
@@ -894,7 +894,7 @@ static int net_init_nic(const NetClientOptions *opts, const char *name,
     const NetLegacyNicOptions *nic;
 
     assert(opts->type == NET_CLIENT_OPTIONS_KIND_NIC);
-    nic = opts->u.nic;
+    nic = opts->u.nic.data;
 
     idx = nic_get_free_idx();
     if (idx == -1 || nb_nics >= MAX_NICS) {
@@ -1026,7 +1026,7 @@ static int net_client_init1(const void *object, int is_netdev, Error **errp)
 
         /* Do not add to a vlan if it's a nic with a netdev= parameter. */
         if (opts->type != NET_CLIENT_OPTIONS_KIND_NIC ||
-            !opts->u.nic->has_netdev) {
+            !opts->u.nic.data->has_netdev) {
             peer = net_hub_add_port(net->has_vlan ? net->vlan : 0, NULL);
         }
     }
net/netmap.c +1 -1
index 9710321..9f7dc53 100644
@@ -403,7 +403,7 @@ static NetClientInfo net_netmap_info = {
 int net_init_netmap(const NetClientOptions *opts,
                     const char *name, NetClientState *peer, Error **errp)
 {
-    const NetdevNetmapOptions *netmap_opts = opts->u.netmap;
+    const NetdevNetmapOptions *netmap_opts = opts->u.netmap.data;
     struct nm_desc *nmd;
     NetClientState *nc;
     Error *err = NULL;
net/slirp.c +1 -1
index 6b51fbc..6866913 100644
@@ -747,7 +747,7 @@ int net_init_slirp(const NetClientOptions *opts, const char *name,
     const char **dnssearch;
 
     assert(opts->type == NET_CLIENT_OPTIONS_KIND_USER);
-    user = opts->u.user;
+    user = opts->u.user.data;
 
     vnet = user->has_net ? g_strdup(user->net) :
            user->has_ip  ? g_strdup_printf("%s/24", user->ip) :
net/socket.c +1 -1
index e32e3cb..d7d0dec 100644
@@ -707,7 +707,7 @@ int net_init_socket(const NetClientOptions *opts, const char *name,
     const NetdevSocketOptions *sock;
 
     assert(opts->type == NET_CLIENT_OPTIONS_KIND_SOCKET);
-    sock = opts->u.socket;
+    sock = opts->u.socket.data;
 
     if (sock->has_fd + sock->has_listen + sock->has_connect + sock->has_mcast +
         sock->has_udp != 1) {
net/tap.c +2 -2
index cfb6831..b477352 100644
@@ -565,7 +565,7 @@ int net_init_bridge(const NetClientOptions *opts, const char *name,
     int fd, vnet_hdr;
 
     assert(opts->type == NET_CLIENT_OPTIONS_KIND_BRIDGE);
-    bridge = opts->u.bridge;
+    bridge = opts->u.bridge.data;
 
     helper = bridge->has_helper ? bridge->helper : DEFAULT_BRIDGE_HELPER;
     br     = bridge->has_br     ? bridge->br     : DEFAULT_BRIDGE_INTERFACE;
@@ -728,7 +728,7 @@ int net_init_tap(const NetClientOptions *opts, const char *name,
     char ifname[128];
 
     assert(opts->type == NET_CLIENT_OPTIONS_KIND_TAP);
-    tap = opts->u.tap;
+    tap = opts->u.tap.data;
     queues = tap->has_queues ? tap->queues : 1;
     vhostfdname = tap->has_vhostfd ? tap->vhostfd : NULL;
 
net/vhost-user.c +1 -1
index 451dbbf..61f1cb4 100644
@@ -303,7 +303,7 @@ int net_init_vhost_user(const NetClientOptions *opts, const char *name,
     CharDriverState *chr;
 
     assert(opts->type == NET_CLIENT_OPTIONS_KIND_VHOST_USER);
-    vhost_user_opts = opts->u.vhost_user;
+    vhost_user_opts = opts->u.vhost_user.data;
 
     chr = net_vhost_parse_chardev(vhost_user_opts, errp);
     if (!chr) {
numa.c +2 -2
index 4c4f7f5..ce2a25a 100644
@@ -229,7 +229,7 @@ static int parse_numa(void *opaque, QemuOpts *opts, Error **errp)
 
     switch (object->type) {
     case NUMA_OPTIONS_KIND_NODE:
-        numa_node_parse(object->u.node, opts, &err);
+        numa_node_parse(object->u.node.data, opts, &err);
         if (err) {
             goto error;
         }
@@ -489,7 +489,7 @@ static void numa_stat_memory_devices(uint64_t node_mem[])
         if (value) {
             switch (value->type) {
             case MEMORY_DEVICE_INFO_KIND_DIMM:
-                node_mem[value->u.dimm->node] += value->u.dimm->size;
+                node_mem[value->u.dimm.data->node] += value->u.dimm.data->size;
                 break;
             default:
                 break;
qemu-char.c +42 -40

282 lines not on this page · raw message

qemu-nbd.c +3 -3
index 2ee7f40..b8c05fc 100644
@@ -377,12 +377,12 @@ static SocketAddress *nbd_build_socket_address(const char *sockpath,
     saddr = g_new0(SocketAddress, 1);
     if (sockpath) {
         saddr->type = SOCKET_ADDRESS_KIND_UNIX;
-        saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
-        saddr->u.q_unix->path = g_strdup(sockpath);
+        saddr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
+        saddr->u.q_unix.data->path = g_strdup(sockpath);
     } else {
         InetSocketAddress *inet;
         saddr->type = SOCKET_ADDRESS_KIND_INET;
-        inet = saddr->u.inet = g_new0(InetSocketAddress, 1);
+        inet = saddr->u.inet.data = g_new0(InetSocketAddress, 1);
         inet->host = g_strdup(bindto);
         if (port) {
             inet->port = g_strdup(port);
replay/replay-input.c +22 -22

91 lines not on this page · raw message

spice-qemu-char.c +8 -6
index 21885c5..351fcaa 100644
@@ -305,9 +305,10 @@ static CharDriverState *qemu_chr_open_spice_vmc(const char *id,
                                                 ChardevReturn *ret,
                                                 Error **errp)
 {
-    const char *type = backend->u.spicevmc->type;
+    ChardevSpiceChannel *spicevmc = backend->u.spicevmc.data;
+    const char *type = spicevmc->type;
     const char **psubtype = spice_server_char_device_recognized_subtypes();
-    ChardevCommon *common = qapi_ChardevSpiceChannel_base(backend->u.spicevmc);
+    ChardevCommon *common = qapi_ChardevSpiceChannel_base(spicevmc);
 
     for (; *psubtype != NULL; ++psubtype) {
         if (strcmp(type, *psubtype) == 0) {
@@ -329,8 +330,9 @@ static CharDriverState *qemu_chr_open_spice_port(const char *id,
                                                  ChardevReturn *ret,
                                                  Error **errp)
 {
-    const char *name = backend->u.spiceport->fqdn;
-    ChardevCommon *common = qapi_ChardevSpicePort_base(backend->u.spiceport);
+    ChardevSpicePort *spiceport = backend->u.spiceport.data;
+    const char *name = spiceport->fqdn;
+    ChardevCommon *common = qapi_ChardevSpicePort_base(spiceport);
     CharDriverState *chr;
     SpiceCharDriver *s;
 
@@ -372,7 +374,7 @@ static void qemu_chr_parse_spice_vmc(QemuOpts *opts, ChardevBackend *backend,
         error_setg(errp, "chardev: spice channel: no name given");
         return;
     }
-    spicevmc = backend->u.spicevmc = g_new0(ChardevSpiceChannel, 1);
+    spicevmc = backend->u.spicevmc.data = g_new0(ChardevSpiceChannel, 1);
     qemu_chr_parse_common(opts, qapi_ChardevSpiceChannel_base(spicevmc));
     spicevmc->type = g_strdup(name);
 }
@@ -387,7 +389,7 @@ static void qemu_chr_parse_spice_port(QemuOpts *opts, ChardevBackend *backend,
         error_setg(errp, "chardev: spice port: no name given");
         return;
     }
-    spiceport = backend->u.spiceport = g_new0(ChardevSpicePort, 1);
+    spiceport = backend->u.spiceport.data = g_new0(ChardevSpicePort, 1);
     qemu_chr_parse_common(opts, qapi_ChardevSpicePort_base(spiceport));
     spiceport->fqdn = g_strdup(name);
 }
tests/test-io-channel-socket.c +20 -20
index afe46d5..494fabf 100644
@@ -120,8 +120,8 @@ static void test_io_channel_setup_sync(SocketAddress *listen_addr,
         SocketAddress *laddr = qio_channel_socket_get_local_address(
             lioc, &error_abort);
 
-        g_free(connect_addr->u.inet->port);
-        connect_addr->u.inet->port = g_strdup(laddr->u.inet->port);
+        g_free(connect_addr->u.inet.data->port);
+        connect_addr->u.inet.data->port = g_strdup(laddr->u.inet.data->port);
 
         qapi_free_SocketAddress(laddr);
     }
@@ -181,8 +181,8 @@ static void test_io_channel_setup_async(SocketAddress *listen_addr,
         SocketAddress *laddr = qio_channel_socket_get_local_address(
             lioc, &error_abort);
 
-        g_free(connect_addr->u.inet->port);
-        connect_addr->u.inet->port = g_strdup(laddr->u.inet->port);
+        g_free(connect_addr->u.inet.data->port);
+        connect_addr->u.inet.data->port = g_strdup(laddr->u.inet.data->port);
 
         qapi_free_SocketAddress(laddr);
     }
@@ -283,15 +283,15 @@ static void test_io_channel_ipv4(bool async)
     SocketAddress *connect_addr = g_new0(SocketAddress, 1);
 
     listen_addr->type = SOCKET_ADDRESS_KIND_INET;
-    listen_addr->u.inet = g_new0(InetSocketAddress, 1);
-    *listen_addr->u.inet = (InetSocketAddress) {
+    listen_addr->u.inet.data = g_new0(InetSocketAddress, 1);
+    *listen_addr->u.inet.data = (InetSocketAddress) {
         .host = g_strdup("127.0.0.1"),
         .port = NULL, /* Auto-select */
     };
 
     connect_addr->type = SOCKET_ADDRESS_KIND_INET;
-    connect_addr->u.inet = g_new0(InetSocketAddress, 1);
-    *connect_addr->u.inet = (InetSocketAddress) {
+    connect_addr->u.inet.data = g_new0(InetSocketAddress, 1);
+    *connect_addr->u.inet.data = (InetSocketAddress) {
         .host = g_strdup("127.0.0.1"),
         .port = NULL, /* Filled in later */
     };
@@ -321,15 +321,15 @@ static void test_io_channel_ipv6(bool async)
     SocketAddress *connect_addr = g_new0(SocketAddress, 1);
 
     listen_addr->type = SOCKET_ADDRESS_KIND_INET;
-    listen_addr->u.inet = g_new0(InetSocketAddress, 1);
-    *listen_addr->u.inet = (InetSocketAddress) {
+    listen_addr->u.inet.data = g_new0(InetSocketAddress, 1);
+    *listen_addr->u.inet.data = (InetSocketAddress) {
         .host = g_strdup("::1"),
         .port = NULL, /* Auto-select */
     };
 
     connect_addr->type = SOCKET_ADDRESS_KIND_INET;
-    connect_addr->u.inet = g_new0(InetSocketAddress, 1);
-    *connect_addr->u.inet = (InetSocketAddress) {
+    connect_addr->u.inet.data = g_new0(InetSocketAddress, 1);
+    *connect_addr->u.inet.data = (InetSocketAddress) {
         .host = g_strdup("::1"),
         .port = NULL, /* Filled in later */
     };
@@ -361,12 +361,12 @@ static void test_io_channel_unix(bool async)
 
 #define TEST_SOCKET "test-io-channel-socket.sock"
     listen_addr->type = SOCKET_ADDRESS_KIND_UNIX;
-    listen_addr->u.q_unix = g_new0(UnixSocketAddress, 1);
-    listen_addr->u.q_unix->path = g_strdup(TEST_SOCKET);
+    listen_addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
+    listen_addr->u.q_unix.data->path = g_strdup(TEST_SOCKET);
 
     connect_addr->type = SOCKET_ADDRESS_KIND_UNIX;
-    connect_addr->u.q_unix = g_new0(UnixSocketAddress, 1);
-    connect_addr->u.q_unix->path = g_strdup(TEST_SOCKET);
+    connect_addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
+    connect_addr->u.q_unix.data->path = g_strdup(TEST_SOCKET);
 
     test_io_channel(async, listen_addr, connect_addr, true);
 
@@ -410,12 +410,12 @@ static void test_io_channel_unix_fd_pass(void)
     fdsend[2] = testfd;
 
     listen_addr->type = SOCKET_ADDRESS_KIND_UNIX;
-    listen_addr->u.q_unix = g_new0(UnixSocketAddress, 1);
-    listen_addr->u.q_unix->path = g_strdup(TEST_SOCKET);
+    listen_addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
+    listen_addr->u.q_unix.data->path = g_strdup(TEST_SOCKET);
 
     connect_addr->type = SOCKET_ADDRESS_KIND_UNIX;
-    connect_addr->u.q_unix = g_new0(UnixSocketAddress, 1);
-    connect_addr->u.q_unix->path = g_strdup(TEST_SOCKET);
+    connect_addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
+    connect_addr->u.q_unix.data->path = g_strdup(TEST_SOCKET);
 
     test_io_channel_setup_sync(listen_addr, connect_addr, &src, &dst);
 
tests/test-qmp-commands.c +1 -1
index 650ba46..14a9ebb 100644
@@ -69,7 +69,7 @@ __org_qemu_x_Union1 *qmp___org_qemu_x_command(__org_qemu_x_EnumList *a,
     __org_qemu_x_Union1 *ret = g_new0(__org_qemu_x_Union1, 1);
 
     ret->type = ORG_QEMU_X_UNION1_KIND___ORG_QEMU_X_BRANCH;
-    ret->u.__org_qemu_x_branch = strdup("blah1");
+    ret->u.__org_qemu_x_branch.data = strdup("blah1");
 
     /* Also test that 'wchar-t' was munged to 'q_wchar_t' */
     if (b && b->value && !b->value->has_q_wchar_t) {
tests/test-qmp-input-visitor.c +13 -12
index b05da5b..5941e90 100644
@@ -477,63 +477,64 @@ static void test_native_list_integer_helper(TestInputVisitorData *data,
     switch (kind) {
     case USER_DEF_NATIVE_LIST_UNION_KIND_INTEGER: {
         intList *elem = NULL;
-        for (i = 0, elem = cvalue->u.integer; elem; elem = elem->next, i++) {
+        for (i = 0, elem = cvalue->u.integer.data;
+             elem; elem = elem->next, i++) {
             g_assert_cmpint(elem->value, ==, i);
         }
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_S8: {
         int8List *elem = NULL;
-        for (i = 0, elem = cvalue->u.s8; elem; elem = elem->next, i++) {
+        for (i = 0, elem = cvalue->u.s8.data; elem; elem = elem->next, i++) {
             g_assert_cmpint(elem->value, ==, i);
         }
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_S16: {
         int16List *elem = NULL;
-        for (i = 0, elem = cvalue->u.s16; elem; elem = elem->next, i++) {
+        for (i = 0, elem = cvalue->u.s16.data; elem; elem = elem->next, i++) {
             g_assert_cmpint(elem->value, ==, i);
         }
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_S32: {
         int32List *elem = NULL;
-        for (i = 0, elem = cvalue->u.s32; elem; elem = elem->next, i++) {
+        for (i = 0, elem = cvalue->u.s32.data; elem; elem = elem->next, i++) {
             g_assert_cmpint(elem->value, ==, i);
         }
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_S64: {
         int64List *elem = NULL;
-        for (i = 0, elem = cvalue->u.s64; elem; elem = elem->next, i++) {
+        for (i = 0, elem = cvalue->u.s64.data; elem; elem = elem->next, i++) {
             g_assert_cmpint(elem->value, ==, i);
         }
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_U8: {
         uint8List *elem = NULL;
-        for (i = 0, elem = cvalue->u.u8; elem; elem = elem->next, i++) {
+        for (i = 0, elem = cvalue->u.u8.data; elem; elem = elem->next, i++) {
             g_assert_cmpint(elem->value, ==, i);
         }
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_U16: {
         uint16List *elem = NULL;
-        for (i = 0, elem = cvalue->u.u16; elem; elem = elem->next, i++) {
+        for (i = 0, elem = cvalue->u.u16.data; elem; elem = elem->next, i++) {
             g_assert_cmpint(elem->value, ==, i);
         }
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_U32: {
         uint32List *elem = NULL;
-        for (i = 0, elem = cvalue->u.u32; elem; elem = elem->next, i++) {
+        for (i = 0, elem = cvalue->u.u32.data; elem; elem = elem->next, i++) {
             g_assert_cmpint(elem->value, ==, i);
         }
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_U64: {
         uint64List *elem = NULL;
-        for (i = 0, elem = cvalue->u.u64; elem; elem = elem->next, i++) {
+        for (i = 0, elem = cvalue->u.u64.data; elem; elem = elem->next, i++) {
             g_assert_cmpint(elem->value, ==, i);
         }
         break;
@@ -635,7 +636,7 @@ static void test_visitor_in_native_list_bool(TestInputVisitorData *data,
     g_assert(cvalue != NULL);
     g_assert_cmpint(cvalue->type, ==, USER_DEF_NATIVE_LIST_UNION_KIND_BOOLEAN);
 
-    for (i = 0, elem = cvalue->u.boolean; elem; elem = elem->next, i++) {
+    for (i = 0, elem = cvalue->u.boolean.data; elem; elem = elem->next, i++) {
         g_assert_cmpint(elem->value, ==, (i % 3 == 0) ? 1 : 0);
     }
 
@@ -668,7 +669,7 @@ static void test_visitor_in_native_list_string(TestInputVisitorData *data,
     g_assert(cvalue != NULL);
     g_assert_cmpint(cvalue->type, ==, USER_DEF_NATIVE_LIST_UNION_KIND_STRING);
 
-    for (i = 0, elem = cvalue->u.string; elem; elem = elem->next, i++) {
+    for (i = 0, elem = cvalue->u.string.data; elem; elem = elem->next, i++) {
         gchar str[8];
         sprintf(str, "%d", i);
         g_assert_cmpstr(elem->value, ==, str);
@@ -705,7 +706,7 @@ static void test_visitor_in_native_list_number(TestInputVisitorData *data,
     g_assert(cvalue != NULL);
     g_assert_cmpint(cvalue->type, ==, USER_DEF_NATIVE_LIST_UNION_KIND_NUMBER);
 
-    for (i = 0, elem = cvalue->u.number; elem; elem = elem->next, i++) {
+    for (i = 0, elem = cvalue->u.number.data; elem; elem = elem->next, i++) {
         GString *double_expected = g_string_new("");
         GString *double_actual = g_string_new("");
 
tests/test-qmp-output-visitor.c +12 -12
index a7f8b45..dc35752 100644
@@ -493,7 +493,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
     int i;
     switch (cvalue->type) {
     case USER_DEF_NATIVE_LIST_UNION_KIND_INTEGER: {
-        intList **list = &cvalue->u.integer;
+        intList **list = &cvalue->u.integer.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(intList, 1);
             (*list)->value = i;
@@ -503,7 +503,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_S8: {
-        int8List **list = &cvalue->u.s8;
+        int8List **list = &cvalue->u.s8.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(int8List, 1);
             (*list)->value = i;
@@ -513,7 +513,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_S16: {
-        int16List **list = &cvalue->u.s16;
+        int16List **list = &cvalue->u.s16.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(int16List, 1);
             (*list)->value = i;
@@ -523,7 +523,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_S32: {
-        int32List **list = &cvalue->u.s32;
+        int32List **list = &cvalue->u.s32.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(int32List, 1);
             (*list)->value = i;
@@ -533,7 +533,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_S64: {
-        int64List **list = &cvalue->u.s64;
+        int64List **list = &cvalue->u.s64.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(int64List, 1);
             (*list)->value = i;
@@ -543,7 +543,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_U8: {
-        uint8List **list = &cvalue->u.u8;
+        uint8List **list = &cvalue->u.u8.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(uint8List, 1);
             (*list)->value = i;
@@ -553,7 +553,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_U16: {
-        uint16List **list = &cvalue->u.u16;
+        uint16List **list = &cvalue->u.u16.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(uint16List, 1);
             (*list)->value = i;
@@ -563,7 +563,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_U32: {
-        uint32List **list = &cvalue->u.u32;
+        uint32List **list = &cvalue->u.u32.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(uint32List, 1);
             (*list)->value = i;
@@ -573,7 +573,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_U64: {
-        uint64List **list = &cvalue->u.u64;
+        uint64List **list = &cvalue->u.u64.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(uint64List, 1);
             (*list)->value = i;
@@ -583,7 +583,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_BOOLEAN: {
-        boolList **list = &cvalue->u.boolean;
+        boolList **list = &cvalue->u.boolean.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(boolList, 1);
             (*list)->value = (i % 3 == 0);
@@ -593,7 +593,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_STRING: {
-        strList **list = &cvalue->u.string;
+        strList **list = &cvalue->u.string.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(strList, 1);
             (*list)->value = g_strdup_printf("%d", i);
@@ -603,7 +603,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
         break;
     }
     case USER_DEF_NATIVE_LIST_UNION_KIND_NUMBER: {
-        numberList **list = &cvalue->u.number;
+        numberList **list = &cvalue->u.number.data;
         for (i = 0; i < 32; i++) {
             *list = g_new0(numberList, 1);
             (*list)->value = (double)i / 3;
tpm.c +1 -1
index 9ed708e..9a7c711 100644
@@ -262,7 +262,7 @@ static TPMInfo *qmp_query_tpm_inst(TPMBackend *drv)
     case TPM_TYPE_PASSTHROUGH:
         res->options->type = TPM_TYPE_OPTIONS_KIND_PASSTHROUGH;
         tpo = g_new0(TPMPassthroughOptions, 1);
-        res->options->u.passthrough = tpo;
+        res->options->u.passthrough.data = tpo;
         if (drv->path) {
             tpo->path = g_strdup(drv->path);
             tpo->has_path = true;
ui/console.c +2 -2
index 7db0fd2..76bc8e1 100644
@@ -2020,7 +2020,7 @@ static VcHandler *vc_handler = text_console_init;
 static CharDriverState *vc_init(const char *id, ChardevBackend *backend,
                                 ChardevReturn *ret, Error **errp)
 {
-    return vc_handler(backend->u.vc, errp);
+    return vc_handler(backend->u.vc.data, errp);
 }
 
 void register_vc_handler(VcHandler *handler)
@@ -2062,7 +2062,7 @@ static void qemu_chr_parse_vc(QemuOpts *opts, ChardevBackend *backend,
     int val;
     ChardevVC *vc;
 
-    vc = backend->u.vc = g_new0(ChardevVC, 1);
+    vc = backend->u.vc.data = g_new0(ChardevVC, 1);
     qemu_chr_parse_common(opts, qapi_ChardevVC_base(vc));
 
     val = qemu_opt_get_number(opts, "width", 0);
ui/input-keymap.c +5 -5
index fd2c09d..f1e700d 100644
@@ -141,10 +141,10 @@ static int number_to_qcode[0x100];
 int qemu_input_key_value_to_number(const KeyValue *value)
 {
     if (value->type == KEY_VALUE_KIND_QCODE) {
-        return qcode_to_number[value->u.qcode];
+        return qcode_to_number[value->u.qcode.data];
     } else {
         assert(value->type == KEY_VALUE_KIND_NUMBER);
-        return value->u.number;
+        return value->u.number.data;
     }
 }
 
@@ -168,10 +168,10 @@ int qemu_input_key_number_to_qcode(uint8_t nr)
 int qemu_input_key_value_to_qcode(const KeyValue *value)
 {
     if (value->type == KEY_VALUE_KIND_QCODE) {
-        return value->u.qcode;
+        return value->u.qcode.data;
     } else {
         assert(value->type == KEY_VALUE_KIND_NUMBER);
-        return qemu_input_key_number_to_qcode(value->u.number);
+        return qemu_input_key_number_to_qcode(value->u.number.data);
     }
 }
 
@@ -182,7 +182,7 @@ int qemu_input_key_value_to_scancode(const KeyValue *value, bool down,
     int count = 0;
 
     if (value->type == KEY_VALUE_KIND_QCODE &&
-        value->u.qcode == Q_KEY_CODE_PAUSE) {
+        value->u.qcode.data == Q_KEY_CODE_PAUSE) {
         /* specific case */
         int v = down ? 0 : 0x80;
         codes[count++] = 0xe1;
ui/input-legacy.c +4 -4
index 5119fe8..d1df7b9 100644
@@ -110,7 +110,7 @@ static void legacy_kbd_event(DeviceState *dev, QemuConsole *src,
 {
     QEMUPutKbdEntry *entry = (QEMUPutKbdEntry *)dev;
     int scancodes[3], i, count;
-    InputKeyEvent *key = evt->u.key;
+    InputKeyEvent *key = evt->u.key.data;
 
     if (!entry || !entry->put_kbd) {
         return;
@@ -156,7 +156,7 @@ static void legacy_mouse_event(DeviceState *dev, QemuConsole *src,
 
     switch (evt->type) {
     case INPUT_EVENT_KIND_BTN:
-        btn = evt->u.btn;
+        btn = evt->u.btn.data;
         if (btn->down) {
             s->buttons |= bmap[btn->button];
         } else {
@@ -179,11 +179,11 @@ static void legacy_mouse_event(DeviceState *dev, QemuConsole *src,
         }
         break;
     case INPUT_EVENT_KIND_ABS:
-        move = evt->u.abs;
+        move = evt->u.abs.data;
         s->axis[move->axis] = move->value;
         break;
     case INPUT_EVENT_KIND_REL:
-        move = evt->u.rel;
+        move = evt->u.rel.data;
         s->axis[move->axis] += move->value;
         break;
     default:
ui/input.c +17 -17
index 1e81c25..79b1650 100644
@@ -168,7 +168,7 @@ void qmp_x_input_send_event(bool has_console, int64_t console,
 
 static void qemu_input_transform_abs_rotate(InputEvent *evt)
 {
-    InputMoveEvent *move = evt->u.abs;
+    InputMoveEvent *move = evt->u.abs.data;
     switch (graphic_rotate) {
     case 90:
         if (move->axis == INPUT_AXIS_X) {
@@ -205,16 +205,16 @@ static void qemu_input_event_trace(QemuConsole *src, InputEvent *evt)
     }
     switch (evt->type) {
     case INPUT_EVENT_KIND_KEY:
-        key = evt->u.key;
+        key = evt->u.key.data;
         switch (key->key->type) {
         case KEY_VALUE_KIND_NUMBER:
-            qcode = qemu_input_key_number_to_qcode(key->key->u.number);
+            qcode = qemu_input_key_number_to_qcode(key->key->u.number.data);
             name = QKeyCode_lookup[qcode];
-            trace_input_event_key_number(idx, key->key->u.number,
+            trace_input_event_key_number(idx, key->key->u.number.data,
                                          name, key->down);
             break;
         case KEY_VALUE_KIND_QCODE:
-            name = QKeyCode_lookup[key->key->u.qcode];
+            name = QKeyCode_lookup[key->key->u.qcode.data];
             trace_input_event_key_qcode(idx, name, key->down);
             break;
         case KEY_VALUE_KIND__MAX:
@@ -223,17 +223,17 @@ static void qemu_input_event_trace(QemuConsole *src, InputEvent *evt)
         }
         break;
     case INPUT_EVENT_KIND_BTN:
-        btn = evt->u.btn;
+        btn = evt->u.btn.data;
         name = InputButton_lookup[btn->button];
         trace_input_event_btn(idx, name, btn->down);
         break;
     case INPUT_EVENT_KIND_REL:
-        move = evt->u.rel;
+        move = evt->u.rel.data;
         name = InputAxis_lookup[move->axis];
         trace_input_event_rel(idx, name, move->value);
         break;
     case INPUT_EVENT_KIND_ABS:
-        move = evt->u.abs;
+        move = evt->u.abs.data;
         name = InputAxis_lookup[move->axis];
         trace_input_event_abs(idx, name, move->value);
         break;
@@ -368,10 +368,10 @@ void qemu_input_event_sync(void)
 InputEvent *qemu_input_event_new_key(KeyValue *key, bool down)
 {
     InputEvent *evt = g_new0(InputEvent, 1);
-    evt->u.key = g_new0(InputKeyEvent, 1);
+    evt->u.key.data = g_new0(InputKeyEvent, 1);
     evt->type = INPUT_EVENT_KIND_KEY;
-    evt->u.key->key = key;
-    evt->u.key->down = down;
+    evt->u.key.data->key = key;
+    evt->u.key.data->down = down;
     return evt;
 }
 
@@ -393,7 +393,7 @@ void qemu_input_event_send_key_number(QemuConsole *src, int num, bool down)
 {
     KeyValue *key = g_new0(KeyValue, 1);
     key->type = KEY_VALUE_KIND_NUMBER;
-    key->u.number = num;
+    key->u.number.data = num;
     qemu_input_event_send_key(src, key, down);
 }
 
@@ -401,7 +401,7 @@ void qemu_input_event_send_key_qcode(QemuConsole *src, QKeyCode q, bool down)
 {
     KeyValue *key = g_new0(KeyValue, 1);
     key->type = KEY_VALUE_KIND_QCODE;
-    key->u.qcode = q;
+    key->u.qcode.data = q;
     qemu_input_event_send_key(src, key, down);
 }
 
@@ -418,10 +418,10 @@ void qemu_input_event_send_key_delay(uint32_t delay_ms)
 InputEvent *qemu_input_event_new_btn(InputButton btn, bool down)
 {
     InputEvent *evt = g_new0(InputEvent, 1);
-    evt->u.btn = g_new0(InputBtnEvent, 1);
+    evt->u.btn.data = g_new0(InputBtnEvent, 1);
     evt->type = INPUT_EVENT_KIND_BTN;
-    evt->u.btn->button = btn;
-    evt->u.btn->down = down;
+    evt->u.btn.data->button = btn;
+    evt->u.btn.data->down = down;
     return evt;
 }
 
@@ -472,7 +472,7 @@ InputEvent *qemu_input_event_new_move(InputEventKind kind,
     InputMoveEvent *move = g_new0(InputMoveEvent, 1);
 
     evt->type = kind;
-    evt->u.rel = move; /* also would work as evt->u.abs */
+    evt->u.rel.data = move; /* also would work as evt->u.abs.data */
     move->axis = axis;
     move->value = value;
     return evt;
ui/vnc-auth-sasl.c +2 -1
index 13a59f5..56e45e3 100644
@@ -513,7 +513,8 @@ vnc_socket_ip_addr_string(QIOChannelSocket *ioc,
         error_setg(errp, "Not an inet socket type");
         return NULL;
     }
-    ret = g_strdup_printf("%s;%s", addr->u.inet->host, addr->u.inet->port);
+    ret = g_strdup_printf("%s;%s", addr->u.inet.data->host,
+                          addr->u.inet.data->port);
     qapi_free_SocketAddress(addr);
     return ret;
 }
ui/vnc.c +15 -14
index b955e4e..344fc34 100644
@@ -112,9 +112,9 @@ static void vnc_init_basic_info(SocketAddress *addr,
 {
     switch (addr->type) {
     case SOCKET_ADDRESS_KIND_INET:
-        info->host = g_strdup(addr->u.inet->host);
-        info->service = g_strdup(addr->u.inet->port);
-        if (addr->u.inet->ipv6) {
+        info->host = g_strdup(addr->u.inet.data->host);
+        info->service = g_strdup(addr->u.inet.data->port);
+        if (addr->u.inet.data->ipv6) {
             info->family = NETWORK_ADDRESS_FAMILY_IPV6;
         } else {
             info->family = NETWORK_ADDRESS_FAMILY_IPV4;
@@ -123,7 +123,7 @@ static void vnc_init_basic_info(SocketAddress *addr,
 
     case SOCKET_ADDRESS_KIND_UNIX:
         info->host = g_strdup("");
-        info->service = g_strdup(addr->u.q_unix->path);
+        info->service = g_strdup(addr->u.q_unix.data->path);
         info->family = NETWORK_ADDRESS_FAMILY_UNIX;
         break;
 
@@ -385,9 +385,9 @@ VncInfo *qmp_query_vnc(Error **errp)
 
         switch (addr->type) {
         case SOCKET_ADDRESS_KIND_INET:
-            info->host = g_strdup(addr->u.inet->host);
-            info->service = g_strdup(addr->u.inet->port);
-            if (addr->u.inet->ipv6) {
+            info->host = g_strdup(addr->u.inet.data->host);
+            info->service = g_strdup(addr->u.inet.data->port);
+            if (addr->u.inet.data->ipv6) {
                 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
             } else {
                 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
@@ -396,7 +396,7 @@ VncInfo *qmp_query_vnc(Error **errp)
 
         case SOCKET_ADDRESS_KIND_UNIX:
             info->host = g_strdup("");
-            info->service = g_strdup(addr->u.q_unix->path);
+            info->service = g_strdup(addr->u.q_unix.data->path);
             info->family = NETWORK_ADDRESS_FAMILY_UNIX;
             break;
 
@@ -3189,7 +3189,8 @@ char *vnc_display_local_addr(const char *id)
         qapi_free_SocketAddress(addr);
         return NULL;
     }
-    ret = g_strdup_printf("%s;%s", addr->u.inet->host, addr->u.inet->port);
+    ret = g_strdup_printf("%s;%s", addr->u.inet.data->host,
+                          addr->u.inet.data->port);
     qapi_free_SocketAddress(addr);
 
     return ret;
@@ -3521,8 +3522,8 @@ void vnc_display_open(const char *id, Error **errp)
 
         if (strncmp(vnc, "unix:", 5) == 0) {
             saddr->type = SOCKET_ADDRESS_KIND_UNIX;
-            saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
-            saddr->u.q_unix->path = g_strdup(vnc + 5);
+            saddr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
+            saddr->u.q_unix.data->path = g_strdup(vnc + 5);
 
             if (vs->ws_enabled) {
                 error_setg(errp, "UNIX sockets not supported with websock");
@@ -3532,7 +3533,7 @@ void vnc_display_open(const char *id, Error **errp)
             unsigned long long baseport;
             InetSocketAddress *inet;
             saddr->type = SOCKET_ADDRESS_KIND_INET;
-            inet = saddr->u.inet = g_new0(InetSocketAddress, 1);
+            inet = saddr->u.inet.data = g_new0(InetSocketAddress, 1);
             if (vnc[0] == '[' && vnc[hlen - 1] == ']') {
                 inet->host = g_strndup(vnc + 1, hlen - 2);
             } else {
@@ -3561,8 +3562,8 @@ void vnc_display_open(const char *id, Error **errp)
 
             if (vs->ws_enabled) {
                 wsaddr->type = SOCKET_ADDRESS_KIND_INET;
-                inet = wsaddr->u.inet = g_new0(InetSocketAddress, 1);
-                inet->host = g_strdup(saddr->u.inet->host);
+                inet = wsaddr->u.inet.data = g_new0(InetSocketAddress, 1);
+                inet->host = g_strdup(saddr->u.inet.data->host);
                 inet->port = g_strdup(websocket);
 
                 if (to) {
util/qemu-sockets.c +18 -17
index ad7c00c..ad0d21d 100644
@@ -901,8 +901,8 @@ SocketAddress *socket_parse(const char *str, Error **errp)
             goto fail;
         } else {
             addr->type = SOCKET_ADDRESS_KIND_UNIX;
-            addr->u.q_unix = g_new(UnixSocketAddress, 1);
-            addr->u.q_unix->path = g_strdup(str + 5);
+            addr->u.q_unix.data = g_new(UnixSocketAddress, 1);
+            addr->u.q_unix.data->path = g_strdup(str + 5);
         }
     } else if (strstart(str, "fd:", NULL)) {
         if (str[3] == '\0') {
@@ -910,13 +910,13 @@ SocketAddress *socket_parse(const char *str, Error **errp)
             goto fail;
         } else {
             addr->type = SOCKET_ADDRESS_KIND_FD;
-            addr->u.fd = g_new(String, 1);
-            addr->u.fd->str = g_strdup(str + 3);
+            addr->u.fd.data = g_new(String, 1);
+            addr->u.fd.data->str = g_strdup(str + 3);
         }
     } else {
         addr->type = SOCKET_ADDRESS_KIND_INET;
-        addr->u.inet = inet_parse(str, errp);
-        if (addr->u.inet == NULL) {
+        addr->u.inet.data = inet_parse(str, errp);
+        if (addr->u.inet.data == NULL) {
             goto fail;
         }
     }
@@ -934,15 +934,15 @@ int socket_connect(SocketAddress *addr, Error **errp,
 
     switch (addr->type) {
     case SOCKET_ADDRESS_KIND_INET:
-        fd = inet_connect_saddr(addr->u.inet, errp, callback, opaque);
+        fd = inet_connect_saddr(addr->u.inet.data, errp, callback, opaque);
         break;
 
     case SOCKET_ADDRESS_KIND_UNIX:
-        fd = unix_connect_saddr(addr->u.q_unix, errp, callback, opaque);
+        fd = unix_connect_saddr(addr->u.q_unix.data, errp, callback, opaque);
         break;
 
     case SOCKET_ADDRESS_KIND_FD:
-        fd = monitor_get_fd(cur_mon, addr->u.fd->str, errp);
+        fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
         if (fd >= 0 && callback) {
             qemu_set_nonblock(fd);
             callback(fd, NULL, opaque);
@@ -961,15 +961,15 @@ int socket_listen(SocketAddress *addr, Error **errp)
 
     switch (addr->type) {
     case SOCKET_ADDRESS_KIND_INET:
-        fd = inet_listen_saddr(addr->u.inet, 0, false, errp);
+        fd = inet_listen_saddr(addr->u.inet.data, 0, false, errp);
         break;
 
     case SOCKET_ADDRESS_KIND_UNIX:
-        fd = unix_listen_saddr(addr->u.q_unix, false, errp);
+        fd = unix_listen_saddr(addr->u.q_unix.data, false, errp);
         break;
 
     case SOCKET_ADDRESS_KIND_FD:
-        fd = monitor_get_fd(cur_mon, addr->u.fd->str, errp);
+        fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
         break;
 
     default:
@@ -984,7 +984,8 @@ int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
 
     switch (remote->type) {
     case SOCKET_ADDRESS_KIND_INET:
-        fd = inet_dgram_saddr(remote->u.inet, local ? local->u.inet : NULL, errp);
+        fd = inet_dgram_saddr(remote->u.inet.data,
+                              local ? local->u.inet.data : NULL, errp);
         break;
 
     default:
@@ -1018,7 +1019,7 @@ socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
 
     addr = g_new0(SocketAddress, 1);
     addr->type = SOCKET_ADDRESS_KIND_INET;
-    inet = addr->u.inet = g_new0(InetSocketAddress, 1);
+    inet = addr->u.inet.data = g_new0(InetSocketAddress, 1);
     inet->host = g_strdup(host);
     inet->port = g_strdup(serv);
     if (sa->ss_family == AF_INET) {
@@ -1042,10 +1043,10 @@ socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
 
     addr = g_new0(SocketAddress, 1);
     addr->type = SOCKET_ADDRESS_KIND_UNIX;
-    addr->u.q_unix = g_new0(UnixSocketAddress, 1);
+    addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
     if (su->sun_path[0]) {
-        addr->u.q_unix->path = g_strndup(su->sun_path,
-                                         sizeof(su->sun_path));
+        addr->u.q_unix.data->path = g_strndup(su->sun_path,
+                                              sizeof(su->sun_path));
     }
 
     return addr;
Signature · 1 line
2.5.0
Reviewed-by on v1 12/17
#21 lore raw

Re: [Qemu-devel] [PATCH 12/17] qapi: Don't special-case simple union wrappers

Quoted 99 lines · Eric Blake

Simple unions were carrying a special case that hid their 'data' QMP member from the resulting C struct, via the hack method QAPISchemaObjectTypeVariant.simple_union_type(). But using the work we started by unboxing flat union and alternate branches, we expose the simple union's implicit type in qapi-types.h as an anonymous type, and drop our last use of the hack.

| struct ImageInfoSpecific {
|     ImageInfoSpecificKind type;
|     union { /* union tag is @type */
|         void *data;
|-        ImageInfoSpecificQCow2 *qcow2;
|-        ImageInfoSpecificVmdk *vmdk;
|+        struct {
|+            ImageInfoSpecificQCow2 *data;
|+        } qcow2;
|+        struct {
|+            ImageInfoSpecificVmdk *data;
|+        } vmdk;
|     } u;
| };

All clients of simple unions have to adjust from using su->u.member to now using su->u.member.data; while this touches a number of files in the tree, some earlier cleanup patches helped minimize the change to the initialization of a temporary variable rather than every single field access. The generated qapi-visit.c code is included in the files affected by the layout change, with a diff that looks like:

|@@ -4510,10 +4567,16 @@ static void visit_type_ImageInfoSpecific
|     }
|     switch (obj->type) {
|     case IMAGE_INFO_SPECIFIC_KIND_QCOW2:
|-        visit_type_ImageInfoSpecificQCow2(v, "data", &obj->u.qcow2, &err);
|+        visit_type_ImageInfoSpecificQCow2(v, "data", &obj->u.qcow2.data, &err);
|+        if (err) {
|+            goto out;
|+        }
|         break;
|     case IMAGE_INFO_SPECIFIC_KIND_VMDK:
|-        visit_type_ImageInfoSpecificVmdk(v, "data", &obj->u.vmdk, &err);
|+        visit_type_ImageInfoSpecificVmdk(v, "data", &obj->u.vmdk.data, &err);
|+        if (err) {
|+            goto out;
|+        }
|         break;
|     default:
|         abort();
|     }
|
| out:
|     error_propagate(errp, err);

The added error checks there are a side effect of visiting all fields of each implicit struct (there is only one such field for simple unions); but do not change semantics, and will be important when later patches allow for flat unions with anonymous branches with more than one field. That future work will look like:
{ 'union': 'Foo', 'base': 'Base', 'discriminator': 'type',
'data': { 'branch1': { 'anonymous': 'str', 'number': 'int' },

            'branch2': 'Named' } }
---
 scripts/qapi.py                 | 10 -----
 scripts/qapi-types.py           | 22 ++++++++---
 scripts/qapi-visit.py           | 15 +++-----
 backends/baum.c                 |  2 +-
 backends/msmouse.c              |  2 +-
 block/nbd.c                     |  6 +--
 block/qcow2.c                   |  6 +--
 block/vmdk.c                    |  8 ++--
 blockdev.c                      | 24 ++++++------
 hmp.c                           |  8 ++--
 hw/char/escc.c                  |  2 +-
 hw/input/hid.c                  |  8 ++--
 hw/input/ps2.c                  |  6 +--
 hw/input/virtio-input-hid.c     |  8 ++--
 hw/mem/pc-dimm.c                |  4 +-
 net/dump.c                      |  2 +-
 net/hub.c                       |  2 +-
 net/l2tpv3.c                    |  2 +-
 net/net.c                       |  4 +-
 net/netmap.c                    |  2 +-
 net/slirp.c                     |  2 +-
 net/socket.c                    |  2 +-
 net/tap.c                       |  4 +-
 net/vhost-user.c                |  2 +-
 numa.c                          |  4 +-
 qemu-char.c                     | 82 +++++++++++++++++++++--------------------
 qemu-nbd.c                      |  6 +--
 replay/replay-input.c           | 44 +++++++++++-----------
 spice-qemu-char.c               | 14 ++++---
 tests/test-io-channel-socket.c  | 40 ++++++++++----------
 tests/test-qmp-commands.c       |  2 +-
 tests/test-qmp-input-visitor.c  | 25 +++++++------
 tests/test-qmp-output-visitor.c | 24 ++++++------
 tpm.c                           |  2 +-
Quoted 8 lines
 ui/console.c                    |  4 +-
 ui/input-keymap.c               | 10 ++---
 ui/input-legacy.c               |  8 ++--
 ui/input.c                      | 34 ++++++++---------
 ui/vnc-auth-sasl.c              |  3 +-
 ui/vnc.c                        | 29 ++++++++-------
 util/qemu-sockets.c             | 35 +++++++++---------
 41 files changed, 262 insertions(+), 257 deletions(-)

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
author
#22 lore raw

PATCH 13/17 qapi-visit: Move error check into gen_visit_fields_call()

In reply to Eric Blake

When first introduced, neither branch of gen_visit_fields_call() would output a goto. But now that the implicit struct visit always ends with a goto, we should do the same for regular struct visits, so that callers don't have to worry about whether they are creating two identical goto's in a row.

Generated code gets slightly larger; if desired, we could patch qapi.py:gen_visit_fields() to have a mode where it skips the final goto and leave it up to the callers when to use that mode, but that adds more maintenance burden when the compiler should be smart enough to not bloat the .o file just because the .c file got larger.

---
 scripts/qapi-visit.py | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
scripts/qapi-visit.py +4 -4
index 3aca6a7..5d861ba 100644
@@ -55,6 +55,7 @@ def gen_visit_fields_call(typ, direct_name, implicit_name=None):
     visit_type_%(c_type)s_fields(v, %(c_name)s, &err);
 ''',
                      c_type=typ.c_name(), c_name=direct_name)
+        ret += gen_err_check()
     return ret
 
 
@@ -79,7 +80,6 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s *obj, Error **er
 
     if base:
         ret += gen_visit_fields_call(base, '(%s *)obj' % base.c_name())
-        ret += gen_err_check()
 
     ret += gen_visit_fields(members, prefix='obj->')
 
@@ -111,9 +111,9 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s *obj, Error **er
     }
 ''')
 
-    # 'goto out' produced for base, by gen_visit_fields() for each member,
-    # and if variants were present
-    if base or members or variants:
+    # 'goto out' produced for non-empty base, by gen_visit_fields() for
+    # each member, and if variants were present
+    if (base and not base.is_empty()) or members or variants:
         ret += mcgen('''
 
 out:
Signature · 1 line
2.5.0
author
#23 lore raw

PATCH 14/17 qapi: Allow anonymous base for flat union

In reply to Eric Blake

Rather than requiring all flat unions to explicitly create a separate base struct, we can allow the qapi schema to specify the common fields via an inline dictionary. This is similar to how commands can specify an inline anonymous type for its 'data', and matches the fact that our code base already has several flat unions that had to create a separate base type that is used nowhere but in the union.

The patch also has to tweak things to avoid calling base.c_name() on an implicit type (since implicit types do not have a name); we already have qapi_FOO_base() which does the trick nicely.

Now that anonymous bases are legal, we need to rework the flat-union-bad-base negative test (as previously written, it forms what is now valid QAPI; tweak it to now provide coverage of a new error message path), and add a positive test in qapi-schema-test to use an anonymous base.

Note that this patch only allows anonymous bases for flat unions; simple unions are enough syntactic sugar that we do not want to burden them further. Meanwhile, it would be easy to modify qapi.py to also allow an anonymous base for structs; however, there is less of a compelling technical reason to do so, since you can always write the struct to directly contain any members that the anonymous base would have mentioned.

---
v1: rebase and rework to use gen_visit_fields_call(), test new error Previously posted as part of qapi cleanup subset F:
v6: avoid redundant error check in gen_visit_union(), rebase to earlier gen_err_check() improvements

---
 scripts/qapi.py                            | 11 +++++++++--
 scripts/qapi-types.py                      | 12 +++++++-----
 scripts/qapi-visit.py                      |  6 +++---
 docs/qapi-code-gen.txt                     | 28 ++++++++++++++--------------
 tests/qapi-schema/flat-union-bad-base.err  |  2 +-
 tests/qapi-schema/flat-union-bad-base.json |  5 ++---
 tests/qapi-schema/qapi-schema-test.json    |  6 +-----
 tests/qapi-schema/qapi-schema-test.out     |  9 ++++-----
 8 files changed, 41 insertions(+), 38 deletions(-)
scripts/qapi.py +9 -2
index 1dc8801..b8366e8 100644
@@ -329,6 +329,8 @@ class QAPISchemaParser(object):
 
 
 def find_base_fields(base):
+    if isinstance(base, dict):
+        return base
     base_struct_define = find_struct(base)
     if not base_struct_define:
         return None
@@ -562,9 +564,9 @@ def check_union(expr, expr_info):
 
     # Else, it's a flat union.
     else:
-        # The object must have a string member 'base'.
+        # The object must have a string or dictionary 'base'.
         check_type(expr_info, "'base' for union '%s'" % name,
-                   base, allow_metas=['struct'])
+                   base, allow_dict=True, allow_metas=['struct'])
         if not base:
             raise QAPIExprError(expr_info,
                                 "Flat union '%s' must have a base"
@@ -1039,6 +1041,8 @@ class QAPISchemaMember(object):
             owner = owner[5:]
             if owner.endswith('-arg'):
                 return '(parameter of %s)' % owner[:-4]
+            elif owner.endswith('-base'):
+                return '(base of %s)' % owner[:-5]
             else:
                 assert owner.endswith('-wrapper')
                 # Unreachable and not implemented
@@ -1323,6 +1327,9 @@ class QAPISchema(object):
         base = expr.get('base')
         tag_name = expr.get('discriminator')
         tag_member = None
+        if isinstance(base, dict):
+            base = (self._make_implicit_object_type(
+                    name, info, 'base', self._make_members(base, info)))
         if tag_name:
             variants = [self._make_variant(key, value)
                         for (key, value) in data.iteritems()]
scripts/qapi-types.py +7 -5
index 36ff770..5e07c22 100644
@@ -72,13 +72,15 @@ struct %(c_name)s {
 ''',
                  c_name=c_name(name))
 
-    if base:
-        ret += mcgen('''
+    if base and not base.is_empty():
+        if not base.is_implicit():
+            ret += mcgen('''
     /* Members inherited from %(c_name)s: */
 ''',
-                     c_name=base.c_name())
+                         c_name=base.c_name())
         ret += gen_struct_fields(base.members)
-        ret += mcgen('''
+        if not base.is_implicit():
+            ret += mcgen('''
     /* Own members: */
 ''')
     ret += gen_struct_fields(members)
@@ -238,7 +240,7 @@ class QAPISchemaGenTypeVisitor(QAPISchemaVisitor):
     def visit_object_type(self, name, info, base, members, variants):
         self._fwdecl += gen_fwd_object_or_array(name)
         self.decl += gen_object(name, base, members, variants)
-        if base:
+        if base and not base.is_implicit():
             self.decl += gen_upcast(name, base)
         self._gen_type_cleanup(name)
 
scripts/qapi-visit.py +3 -3
index 5d861ba..ca7b00d 100644
@@ -41,13 +41,12 @@ static void visit_type_%(c_type)s_fields(Visitor *v, %(c_type)s *obj, Error **er
                  c_type=typ.c_name())
 
 
-def gen_visit_fields_call(typ, direct_name, implicit_name=None):
+def gen_visit_fields_call(typ, direct_name, implicit_name):
     ret = ''
     assert isinstance(typ, QAPISchemaObjectType)
     if typ.is_empty():
         pass
     elif typ.is_implicit():
-        assert implicit_name
         assert not typ.variants
         ret += gen_visit_fields(typ.members, prefix=implicit_name)
     else:
@@ -79,7 +78,8 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s *obj, Error **er
                  c_name=c_name(name))
 
     if base:
-        ret += gen_visit_fields_call(base, '(%s *)obj' % base.c_name())
+        ret += gen_visit_fields_call(base, 'qapi_%s_base(obj)' % c_name(name),
+                                     'obj->')
 
     ret += gen_visit_fields(members, prefix='obj->')
 
docs/qapi-code-gen.txt +14 -14
index 999f3b9..c77c6d4 100644
@@ -283,7 +283,7 @@ better than open-coding the field to be type 'str'.
 === Union types ===
 
 Usage: { 'union': STRING, 'data': DICT }
-or:    { 'union': STRING, 'data': DICT, 'base': STRUCT-NAME,
+or:    { 'union': STRING, 'data': DICT, 'base': STRUCT-NAME-OR-DICT,
          'discriminator': ENUM-MEMBER-OF-BASE }
 
 Union types are used to let the user choose between several different
@@ -319,13 +319,16 @@ an implicit C enum 'NameKind' is created, corresponding to the union
 the union can be named 'max', as this would collide with the implicit
 enum.  The value for each branch can be of any type.
 
-A flat union definition specifies a struct as its base, and
-avoids nesting on the wire.  All branches of the union must be
-complex types, and the top-level fields of the union dictionary on
-the wire will be combination of fields from both the base type and the
-appropriate branch type (when merging two dictionaries, there must be
-no keys in common).  The 'discriminator' field must be the name of an
-enum-typed member of the base struct.
+A flat union definition avoids nesting on the wire, and specifies a
+set of common fields that occur in all variants of the union.  The
+'base' key must specifiy either a type name (the type must be a
+struct, not a union), or a dictionary representing an anonymous type.
+All branches of the union must be complex types, and the top-level
+fields of the union dictionary on the wire will be combination of
+fields from both the base type and the appropriate branch type (when
+merging two dictionaries, there must be no keys in common).  The
+'discriminator' field must be the name of an enum-typed member of the
+base struct.
 
 The following example enhances the above simple union example by
 adding a common field 'readonly', renaming the discriminator to
@@ -333,10 +336,8 @@ something more applicable, and reducing the number of {} required on
 the wire:
 
  { 'enum': 'BlockdevDriver', 'data': [ 'file', 'qcow2' ] }
- { 'struct': 'BlockdevCommonOptions',
-   'data': { 'driver': 'BlockdevDriver', 'readonly': 'bool' } }
  { 'union': 'BlockdevOptions',
-   'base': 'BlockdevCommonOptions',
+   'base': { 'driver': 'BlockdevDriver', 'readonly': 'bool' },
    'discriminator': 'driver',
    'data': { 'file': 'FileOptions',
              'qcow2': 'Qcow2Options' } }
@@ -354,7 +355,7 @@ code generator can ensure that branches exist for all values of the
 enum (although the order of the keys need not match the declaration of
 the enum).  In the resulting generated C data types, a flat union is
 represented as a struct with the base member fields included directly,
-and then a union of structures for each branch of the struct.
+and then a union of pointers to structures for each branch of the struct.
 
 A simple union can always be re-written as a flat union where the base
 class has a single member named 'type', and where each branch of the
@@ -365,10 +366,9 @@ union has a struct with a single member named 'data'.  That is,
 is identical on the wire to:
 
  { 'enum': 'Enum', 'data': ['one', 'two'] }
- { 'struct': 'Base', 'data': { 'type': 'Enum' } }
  { 'struct': 'Branch1', 'data': { 'data': 'str' } }
  { 'struct': 'Branch2', 'data': { 'data': 'int' } }
- { 'union': 'Flat', 'base': 'Base', 'discriminator': 'type',
+ { 'union': 'Flat': 'base': { 'type': 'Enum' }, 'discriminator': 'type',
    'data': { 'one': 'Branch1', 'two': 'Branch2' } }
 
 
tests/qapi-schema/flat-union-bad-base.err +1 -1
index 79b8a71..bee24a2 100644
@@ -1 +1 @@
-tests/qapi-schema/flat-union-bad-base.json:9: 'base' for union 'TestUnion' should be a type name
+tests/qapi-schema/flat-union-bad-base.json:8: 'string' (member of TestTypeA) collides with 'string' (base of TestUnion)
tests/qapi-schema/flat-union-bad-base.json +2 -3
index e2e622b..74dd421 100644
@@ -1,5 +1,4 @@
-# we require the base to be an existing struct
-# TODO: should we allow an anonymous inline base type?
+# we allow anonymous base, but enforce no duplicate keys
 { 'enum': 'TestEnum',
   'data': [ 'value1', 'value2' ] }
 { 'struct': 'TestTypeA',
@@ -7,7 +6,7 @@
 { 'struct': 'TestTypeB',
   'data': { 'integer': 'int' } }
 { 'union': 'TestUnion',
-  'base': { 'enum1': 'TestEnum', 'kind': 'str' },
+  'base': { 'enum1': 'TestEnum', 'string': 'str' },
   'discriminator': 'enum1',
   'data': { 'value1': 'TestTypeA',
             'value2': 'TestTypeB' } }
tests/qapi-schema/qapi-schema-test.json +1 -5
index 33e8517..a6989d8 100644
@@ -75,14 +75,10 @@
   'base': 'UserDefZero',
   'data': { 'string': 'str', 'enum1': 'EnumOne' } }
 
-{ 'struct': 'UserDefUnionBase2',
-  'base': 'UserDefZero',
-  'data': { 'string': 'str', 'enum1': 'QEnumTwo' } }
-
 # this variant of UserDefFlatUnion defaults to a union that uses fields with
 # allocated types to test corner cases in the cleanup/dealloc visitor
 { 'union': 'UserDefFlatUnion2',
-  'base': 'UserDefUnionBase2',
+  'base': { 'string': 'str', 'enum1': 'QEnumTwo' },
   'discriminator': 'enum1',
   'data': { 'value1' : 'UserDefC', # intentional forward reference
             'value2' : 'UserDefB' } }
tests/qapi-schema/qapi-schema-test.out +4 -5
index 6b97fa5..4ba347e 100644
@@ -8,6 +8,9 @@ object :obj-EVENT_D-arg
     member b: str optional=False
     member c: str optional=True
     member enum3: EnumOne optional=True
+object :obj-UserDefFlatUnion2-base
+    member string: str optional=False
+    member enum1: QEnumTwo optional=False
 object :obj-__org.qemu_x-command-arg
     member a: __org.qemu_x-EnumList optional=False
     member b: __org.qemu_x-StructList optional=False
@@ -121,7 +124,7 @@ object UserDefFlatUnion
     case value2: UserDefB
     case value3: UserDefB
 object UserDefFlatUnion2
-    base UserDefUnionBase2
+    base :obj-UserDefFlatUnion2-base
     tag enum1
     case value1: UserDefC
     case value2: UserDefB
@@ -166,10 +169,6 @@ object UserDefUnionBase
     base UserDefZero
     member string: str optional=False
     member enum1: EnumOne optional=False
-object UserDefUnionBase2
-    base UserDefZero
-    member string: str optional=False
-    member enum1: QEnumTwo optional=False
 object UserDefZero
     member integer: int optional=False
 object WrapAlternate
Signature · 1 line
2.5.0
author
#24 lore raw

PATCH 15/17 qapi: Use anonymous base in SchemaInfo

In reply to Eric Blake

Now that the generator supports it, we might as well use an anonymous base rather than breaking out a single-use SchemaInfoBase structure.

Oddly enough, this change does not affect the resulting introspection output (because we already inline the members of a base type into an object, and had no independent use of the base type reachable from a command).

---
v1: no change
Previously posted as part of qapi cleanup subset F:
v6: new patch

---
 qapi/introspect.json | 12 +-----------
 1 file changed, 1 insertion(+), 11 deletions(-)
qapi/introspect.json +1 -11
index 9e9369e..3fd81fb 100644
@@ -75,16 +75,6 @@
             'command', 'event' ] }
 
 ##
-# @SchemaInfoBase
-#
-# Members common to any @SchemaInfo.
-#
-# Since: 2.5
-##
-{ 'struct': 'SchemaInfoBase',
-  'data': { 'name': 'str', 'meta-type': 'SchemaMetaType' } }
-
-##
 # @SchemaInfo
 #
 # @name: the entity's name, inherited from @base.
@@ -103,7 +93,7 @@
 # Since: 2.5
 ##
 { 'union': 'SchemaInfo',
-  'base': 'SchemaInfoBase',
+  'base': { 'name': 'str', 'meta-type': 'SchemaMetaType' },
   'discriminator': 'meta-type',
   'data': {
       'builtin': 'SchemaInfoBuiltin',
Signature · 1 line
2.5.0
author
#25 lore raw

PATCH 16/17 qapi: Use anonymous base in CpuInfo

In reply to Eric Blake

Now that the generator supports it, we might as well use an anonymous base rather than breaking out a single-use CpuInfoBase structure.

---
v1: no change
Previously posted as part of qapi cleanup subset F:
v6: new patch

---
 scripts/qapi.py  |  2 +-
 qapi-schema.json | 20 ++++++--------------
 2 files changed, 7 insertions(+), 15 deletions(-)
scripts/qapi.py +1 -1
index b8366e8..c5c4bcb 100644
@@ -62,8 +62,8 @@ returns_whitelist = [
 # Whitelist of entities allowed to violate case conventions
 case_whitelist = [
     # From QMP:
+    ':obj-CpuInfo-base',    # CPU, visible through query-cpu
     'ACPISlotType',         # DIMM, visible through query-acpi-ospm-status
-    'CpuInfoBase',          # CPU, visible through query-cpu
     'CpuInfoMIPS',          # PC, visible through query-cpu
     'CpuInfoTricore',       # PC, visible through query-cpu
     'InputAxis',            # TODO: drop when x-input-send-event is fixed
qapi-schema.json +6 -14
index f64d4ab..f02e6a1 100644
@@ -753,9 +753,9 @@
   'data': ['x86', 'sparc', 'ppc', 'mips', 'tricore', 'other' ] }
 
 ##
-# @CpuInfoBase:
+# @CpuInfo:
 #
-# Common information about a virtual CPU
+# Information about a virtual CPU
 #
 # @CPU: the index of the virtual CPU
 #
@@ -776,18 +776,10 @@
 # Notes: @halted is a transient state that changes frequently.  By the time the
 #        data is sent to the client, the guest may no longer be halted.
 ##
-{ 'struct': 'CpuInfoBase',
-  'data': {'CPU': 'int', 'current': 'bool', 'halted': 'bool',
-           'qom_path': 'str', 'thread_id': 'int', 'arch': 'CpuInfoArch' } }
-
-##
-# @CpuInfo:
-#
-# Information about a virtual CPU
-#
-# Since: 0.14.0
-##
-{ 'union': 'CpuInfo', 'base': 'CpuInfoBase', 'discriminator': 'arch',
+{ 'union': 'CpuInfo',
+  'base': {'CPU': 'int', 'current': 'bool', 'halted': 'bool',
+           'qom_path': 'str', 'thread_id': 'int', 'arch': 'CpuInfoArch' },
+  'discriminator': 'arch',
   'data': { 'x86': 'CpuInfoX86',
             'sparc': 'CpuInfoSPARC',
             'ppc': 'CpuInfoPPC',
Signature · 1 line
2.5.0
author
#26 lore raw

PATCH 17/17 qapi: Make c_type() more OO-like

In reply to Eric Blake

QAPISchemaType.c_type() was a bit awkward. Rather than having two optional orthogonal boolean flags that should never both be true, and where all callers pass a compile-time constant, provide three different method names that can be overridden as needed, and where the caller just uses the right variant. It requires slightly more Python, but is arguably easier to read.

---
 scripts/qapi.py       | 38 +++++++++++++++++++++++++++++---------
 scripts/qapi-types.py |  2 +-
 2 files changed, 30 insertions(+), 10 deletions(-)
scripts/qapi.py +29 -9
index c5c4bcb..c15aa4a 100644
@@ -826,8 +826,17 @@ class QAPISchemaVisitor(object):
 
 
 class QAPISchemaType(QAPISchemaEntity):
-    def c_type(self, is_param=False, is_unboxed=False):
-        return c_name(self.name) + pointer_suffix
+    # Normal usage of the type, such as declaring a local variable
+    def c_type(self):
+        pass
+
+    # Use of a type in a parameter list
+    def c_param_type(self):
+        return self.c_type()
+
+    # Use of a type in a struct declaration
+    def c_unboxed_type(self):
+        return self.c_type()
 
     def c_null(self):
         return 'NULL'
@@ -859,8 +868,11 @@ class QAPISchemaBuiltinType(QAPISchemaType):
     def c_name(self):
         return self.name
 
-    def c_type(self, is_param=False, is_unboxed=False):
-        if is_param and self.name == 'str':
+    def c_type(self):
+        return self._c_type_name
+
+    def c_param_type(self):
+        if self.name == 'str':
             return 'const ' + self._c_type_name
         return self._c_type_name
 
@@ -893,7 +905,7 @@ class QAPISchemaEnumType(QAPISchemaType):
         # See QAPISchema._make_implicit_enum_type()
         return self.name.endswith('Kind')
 
-    def c_type(self, is_param=False, is_unboxed=False):
+    def c_type(self):
         return c_name(self.name)
 
     def member_names(self):
@@ -925,6 +937,9 @@ class QAPISchemaArrayType(QAPISchemaType):
     def is_implicit(self):
         return True
 
+    def c_type(self):
+        return c_name(self.name) + pointer_suffix
+
     def json_type(self):
         return 'array'
 
@@ -994,12 +1009,14 @@ class QAPISchemaObjectType(QAPISchemaType):
         assert not self.is_implicit()
         return QAPISchemaType.c_name(self)
 
-    def c_type(self, is_param=False, is_unboxed=False):
+    def c_type(self):
         assert not self.is_implicit()
-        if is_unboxed:
-            return c_name(self.name)
         return c_name(self.name) + pointer_suffix
 
+    def c_unboxed_type(self):
+        assert not self.is_implicit()
+        return c_name(self.name)
+
     def json_type(self):
         return 'object'
 
@@ -1140,6 +1157,9 @@ class QAPISchemaAlternateType(QAPISchemaType):
         for v in self.variants.variants:
             v.check_clash(self.info, seen)
 
+    def c_type(self):
+        return c_name(self.name) + pointer_suffix
+
     def json_type(self):
         return 'value'
 
@@ -1634,7 +1654,7 @@ def gen_params(arg_type, extra):
         sep = ', '
         if memb.optional:
             ret += 'bool has_%s, ' % c_name(memb.name)
-        ret += '%s %s' % (memb.type.c_type(is_param=True), c_name(memb.name))
+        ret += '%s %s' % (memb.type.c_param_type(), c_name(memb.name))
     if extra:
         ret += sep + extra
     return ret
scripts/qapi-types.py +1 -1
index 5e07c22..7d4bfaf 100644
@@ -140,7 +140,7 @@ def gen_variants(variants):
             ret += mcgen('''
         %(c_type)s %(c_name)s;
 ''',
-                         c_type=var.type.c_type(is_unboxed=True),
+                         c_type=var.type.c_unboxed_type(),
                          c_name=c_name(var.name))
 
     ret += mcgen('''
Signature · 1 line
2.5.0