qapi visitor cleanups (post-introspection cleanups subset E)
Subsystems (3)
Re: [Qemu-devel] [PATCH v9 24/37] qmp: Tighten output visitor rules
In reply to Eric BlakeQuoted 9 lines · Eric Blake
Add a new
qmp_output_visitor_reset(), which must be called before reusing an exising QmpOutputVisitor on a new root object. Tighten assertions to require thatqmp_output_get_qobject()can only be called after pairing a visit_end_* for every visit_start_* (rather than allowing it to return a partially built object), that it must not be called unless at least one visit_type_* or visit_start/visit_endpair has occurred since creation/reset (the accidental return of NULL fixed by commitab8bf1d7would have been much easier to diagnose),
Makes sense.
Quoted 1 line
and that it may only be called once per visit.
Why?
Does it have a side effect?
Quoted 1 line
Meanwhile, nothing was using the return value of
qmp_output_pop().
Well, pop returns the value popped, otherwise it's not a pop.
Quoted 2 lines
Also, adding a parameter will let us diagnose any programming bugs due to mismatched push(struct)/pop(list) or push(list)/pop(struct).
Hmm.
Quoted 3 lines
To keep the semantics of
test_visitor_out_empty, we now have to explicitly request a top-level visit of a NULL object, by implementing the just-added visitortype_null()callback.
The fact that we implement type_null() in the QMP output visitor is mentioned only in passing, and not clearly.
Could the previous patch implement it for both QMP input and output?
Quoted 31 lines
Signed-off-by Eric Blake <[email protected]>---
v9: rebase to added patch, squash in more sanity checks, drop Marc-Andre's R-b
v8: renameqmp_output_resettoqmp_output_visitor_reset
v7: new patch, based on discussion aboutspapr_drc.c--- include/qapi/qmp-output-visitor.h | 1 + include/qapi/visitor-impl.h | 4 ++-- qapi/qmp-output-visitor.c | 50 +++++++++++++++++++++++---------------- tests/test-qmp-output-visitor.c | 2 ++ 4 files changed, 35 insertions(+), 22 deletions(-)include/qapi/qmp-output-visitor.h +1
-0@@ -21,6 +21,7 @@ typedef struct QmpOutputVisitor QmpOutputVisitor;QmpOutputVisitor *qmp_output_visitor_new (void );void qmp_output_visitor_cleanup (QmpOutputVisitor *v); +void qmp_output_visitor_reset (QmpOutputVisitor *v);QObject *qmp_output_get_qobject (QmpOutputVisitor *v);Visitor *qmp_output_get_visitor (QmpOutputVisitor *v);include/qapi/visitor-impl.h +0
-0
include/qapi/visitor-impl.h struct Visitor · line 79
Quoted 7 lines
include/qapi/visitor-impl.h +2
-2@@ -75,8 +75,8 @@ struct Visitor* visitors do not currently visit arbitrary types). */ void (*type_any)(Visitor *v,const char *name,QObject **obj,Error **errp); -/* Must be provided to visit explicit null values (right now, only the -* dealloc and qmp-input visitors support this). */ +/* Must be provided to visit explicit null values (the opts and string +* visitors do not currently visit an explicit null). */
Will need updating.
Quoted 50 lines
include/qapi/visitor-impl.h +0
-0void (*type_null)(Visitor *v,const char *name,Error **errp);/* May be NULL; most useful for input visitors. */ qapi/qmp-output-visitor.c +4
-5@@ -1,6 +1,7 @@/* * Core Definitions for QAPI/QMP Command Registry * +* Copyright (C) 2015-2016 Red Hat, Inc. * Copyright IBM, Corp. 2011 * * Authors: @@ -56,17 +57,15 @@ static void qmp_output_push_obj(QmpOutputVisitor *qov, QObject *value)QTAILQ_INSERT_HEAD (&qov->stack, e, node); } -/* Grab and remove the most recent QObject from the stack */ -static QObject *qmp_output_pop (QmpOutputVisitor *qov) +/* Remove the most recent QObject with given type from the stack */ +static void qmp_output_pop (QmpOutputVisitor *qov,QType type) {QStackEntry *e =QTAILQ_FIRST (&qov->stack); -QObject *value;assert (e);QTAILQ_REMOVE (&qov->stack, e, node); - value = e->value; +assert (qobject_type (e->value) == type);g_free (e); -return value; }/* Grab the most recent QObject from the stack, if any */
qapi/qmp-output-visitor.c +2
-3@@ -88,9 +87,8 @@ static void qmp_output_add_obj(QmpOutputVisitor *qov, const char *name, cur =qmp_output_last (qov);if (!cur) { -/* FIXME we should require the user to reset the visitor, rather -* than throwing away the previous root */ -qobject_decref (qov->root); +/* Don't allow reuse of visitor on more than one root */ +assert (!qov->root); qov->root = value; }else {switch (qobject_type (cur)) {
qapi/qmp-output-visitor.c static void qmp_output_add_obj(QmpOutputVisitor *qov, const char *name, · line 100
Quoted 4 lines
qapi/qmp-output-visitor.c +1
-0@@ -99,6 +97,7 @@ static void qmp_output_add_obj(QmpOutputVisitor *qov, const char *name,qdict_put_obj (qobject_to_qdict (cur), name, value);break ;case QTYPE_QLIST : +assert (!name);
Okay if we put "name must be null when visiting list elements" in the contract.
However, I believe decent error messages will require a non-null name.
I'd specify "may be null" instead of "must be null", and drop the assertion, because one, it's what the code actually needs, and two, it'll be slightly less churn when we fix the error messages.
qapi/qmp-output-visitor.c static void qmp_output_start_struct(Visitor *v, const char *name, void **obj, · line 122
Quoted 9 lines
qapi/qmp-output-visitor.c +1
-1qlist_append_obj (qobject_to_qlist (cur), value);break ;default :@@ -120,7 +119,7 @@ static void qmp_output_start_struct(Visitor *v, const char *name, void **obj,static void qmp_output_end_struct (Visitor *v,Error **errp) {QmpOutputVisitor *qov =to_qov (v); -qmp_output_pop (qov); +qmp_output_pop (qov,QTYPE_QDICT );
Leave qmp_output_pop() unchanged, and do
value = qmp_output_pop(qov);
assert(qobject_type(value) == QTYPE_QLIST);Likewise for the second caller.
Just as simple, and the thing called pop actually pops.
Quoted 28 lines
qapi/qmp-output-visitor.c +7
-4}static void qmp_output_start_list (Visitor *v,const char *name,Error **errp)@@ -151,7 +150,7 @@ static GenericList *qmp_output_next_list(Visitor *v, GenericList **listp,static void qmp_output_end_list (Visitor *v) {QmpOutputVisitor *qov =to_qov (v); -qmp_output_pop (qov); +qmp_output_pop (qov,QTYPE_QLIST ); } static void qmp_output_type_int64(Visitor *v, const char *name, int64_t *obj,@@ -202,18 +201,22 @@ static void qmp_output_type_any(Visitor *v, const char *name, QObject **obj,qmp_output_add_obj (qov, name, *obj); } +static void qmp_output_type_null (Visitor *v,const char *name,Error **errp) +{ +QmpOutputVisitor *qov =to_qov (v); +qmp_output_add_obj (qov, name,qnull ()); +} +/* Finish building, and return the root object. Will not be NULL. */ QObject *qmp_output_get_qobject (QmpOutputVisitor *qov) { -/* FIXME: we should require that a visit occurred, and that it is -* complete (no starts without a matching end) */ -QObject *obj = qov->root;
qapi/qmp-output-visitor.c static void qmp_output_type_any(Visitor *v, const char *name, QObject **obj, · line 216
Quoted 10 lines
qapi/qmp-output-visitor.c +4
-6-if (obj) { -qobject_incref (obj); - }else { - obj =qnull (); - } -return obj; +QObject *root; + +assert (qov->root);/* A visit must have occurred... */ +assert (!qmp_output_last (qov));/* ...with each start paired with end. */
I figure QTAILQ_EMPTY(&qov->stack) would be more obvious.
Apropos QTAILQ: where I learned my trade, you got laughed out of the lab for implementing such a stack with a dynamically allocated linked list.
qapi/qmp-output-visitor.c static void qmp_output_type_any(Visitor *v, const char *name, QObject **obj, · line 218
Quoted 2 lines
qapi/qmp-output-visitor.c +2
-0+ root = qov->root; + qov->root =NULL ;
This line arbitrarily restricts us to a single get. Replace it by qobject_incref(root), and qobject_decref(qmp_output_get_qobject(qov)) is idempotent. Idempotent is lovely.
Quoted 39 lines
qapi/qmp-output-visitor.c +9
-1+return root; }Visitor *qmp_output_get_visitor (QmpOutputVisitor *v)@@ -221,7 +224,7 @@ Visitor *qmp_output_get_visitor(QmpOutputVisitor *v)return &v->visitor; } -void qmp_output_visitor_cleanup (QmpOutputVisitor *v) +void qmp_output_visitor_reset (QmpOutputVisitor *v) {QStackEntry *e, *tmp;@@ -231,6 +234,12 @@ void qmp_output_visitor_cleanup(QmpOutputVisitor *v) }qobject_decref (v->root); + v->root =NULL ; +} + +void qmp_output_visitor_cleanup (QmpOutputVisitor *v) +{ +qmp_output_visitor_reset (v);g_free (v); }@@ -252,6 +261,7 @@ QmpOutputVisitor *qmp_output_visitor_new(void) v->visitor.type_str = qmp_output_type_str; v->visitor.type_number = qmp_output_type_number; v->visitor.type_any = qmp_output_type_any; + v->visitor.type_null = qmp_output_type_null;QTAILQ_INIT (&v->stack);tests/test-qmp-output-visitor.c +0
-0
tests/test-qmp-output-visitor.c static void test_visitor_out_struct_errors(TestOutputVisitorData *data, · line 266
Quoted 7 lines
tests/test-qmp-output-visitor.c +1
-0@@ -260,6 +260,7 @@ static void test_visitor_out_struct_errors(TestOutputVisitorData *data,visit_type_UserDefOne (data->ov,"unused" , &pu, &err);g_assert (err);error_free (err); +qmp_output_visitor_reset (data->qov); } }
That's the only spot that uses visitors for multiple roots? I expected worse...
tests/test-qmp-output-visitor.c static void test_visitor_out_empty(TestOutputVisitorData *data, · line 466
Quoted 8 lines
tests/test-qmp-output-visitor.c +1
-0@@ -459,6 +460,7 @@ static void test_visitor_out_empty(TestOutputVisitorData *data, {QObject *arg; +visit_type_null (data->ov,NULL , &error_abort); arg =qmp_output_get_qobject (data->qov);g_assert (qobject_type (arg) ==QTYPE_QNULL );/* Check that qnull reference counting is sane */
This isn't testing "empty" anymore. Suggest to s/empty/null/.
PATCH v9 25/37 spapr_drc: Expose 'null' in qom-get when there is no fdt
In reply to Eric BlakeNow that the QMP output visitor supports an explicit null output, we should utilize it to make it easier to diagnose the difference between a missing fdt vs. a present-but-empty one.
(Note that this reverts the behavior of commit ab8bf1d, taking us back to the behavior of commit 6c2f9a1 [which in turn stemmed from a crash fix in 1d10b44]; but that this time, the change is intentional and not an accidental side-effect.)
---
v9: improved commit message
v8: rebase to 'name' motion
v7: new patch, based on discussion about spapr_drc.c
--- hw/ppc/spapr_drc.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-)
hw/ppc/spapr_drc.c +1 -5
@@ -259,11 +259,7 @@ static void prop_get_fdt(Object *obj, Visitor *v, const char *name,void *fdt;if (!drc->fdt) { -visit_start_struct (v, name,NULL ,0 , &err); -if (!err) { -visit_end_struct (v, &err); - } -error_propagate (errp, err); +visit_type_null (v,NULL , errp);return ; }
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 25/37] spapr_drc: Expose 'null' in qom-get when there is no fdt
Quoted 4 lines · Eric Blake
Now that the QMP output visitor supports an explicit null output, we should utilize it to make it easier to diagnose the difference between a missing fdt vs. a present-but-empty one.
Please spell out that we change the value from {} to null.
Quoted 23 lines
(Note that this reverts the behavior of commit ab8bf1d, taking us back to the behavior of commit 6c2f9a1 [which in turn stemmed from a crash fix in 1d10b44]; but that this time, the change is intentional and not an accidental side-effect.)
Signed-off-by Eric Blake <[email protected]>Acked-by David Gibson <[email protected]>---
v9: improved commit message
v8: rebase to 'name' motion
v7: new patch, based on discussion aboutspapr_drc.c--- hw/ppc/spapr_drc.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-)hw/ppc/spapr_drc.c +0
-0@@ -259,11 +259,7 @@ static void prop_get_fdt(Object *obj, Visitor *v, const char *name,void *fdt;
hw/ppc/spapr_drc.c static void prop_get_fdt(Object *obj, Visitor *v, const char *name, · line 264
Quoted 10 lines
hw/ppc/spapr_drc.c +1
-5if (!drc->fdt) { -visit_start_struct (v, name,NULL ,0 , &err); -if (!err) { -visit_end_struct (v, &err); - } -error_propagate (errp, err); +visit_type_null (v,NULL , errp);return ; }
Easier to read, always welcome :)
PATCH v9 26/37 qapi: Simplify excess input reporting in input visitors
In reply to Eric BlakeWhen reporting that an unvisited member remains at the end of an input visit for a struct, we were using g_hash_table_find() coupled with a callback function that always returns true, to locate an arbitrary member of the hash table. But if all we need is an arbitrary entry, we can get that from a single-use iterator, without needing a tautological callback function.
---
v9: no change
v8: rebase to earlier changes
v7: retitle, rebase to earlier context changes
v6: new patch, based on comments on RFC against v5 7/46
--- qapi/opts-visitor.c | 12 +++--------- qapi/qmp-input-visitor.c | 14 +++++--------- 2 files changed, 8 insertions(+), 18 deletions(-)
qapi/opts-visitor.c +3 -9
@@ -156,17 +156,11 @@ opts_start_struct(Visitor *v, const char *name, void **obj, } -static gboolean -ghr_true (gpointer ign_key,gpointer ign_value,gpointer ign_user_data) -{ -return TRUE; -} - -static void opts_end_struct (Visitor *v,Error **errp) {OptsVisitor *ov =to_ov (v); +GHashTableIter iter;GQueue *any;if (--ov->depth >0 ) {
@@ -174,8 +168,8 @@ opts_end_struct(Visitor *v, Error **errp) }/* we should have processed all (distinct) QemuOpt instances */ - any =g_hash_table_find (ov->unprocessed_opts, &ghr_true,NULL ); -if (any) { +g_hash_table_iter_init (&iter, ov->unprocessed_opts); +if (g_hash_table_iter_next (&iter,NULL , (void **)&any)) {const QemuOpt *first; first =g_queue_peek_head (any);
qapi/qmp-input-visitor.c +5 -9
@@ -88,12 +88,6 @@ static void qmp_input_push(QmpInputVisitor *qiv, QObject *obj, Error **errp) qiv->nb_stack++; } -/** Only for qmp_input_pop. */ -static gboolean always_true (gpointer key,gpointer val,gpointer user_pkey) -{ - *(const char **)user_pkey = (const char *)key; -return TRUE; -}static void qmp_input_pop (QmpInputVisitor *qiv,Error **errp) {
@@ -102,9 +96,11 @@ static void qmp_input_pop(QmpInputVisitor *qiv, Error **errp)if (qiv->strict) {GHashTable *const top_ht = qiv->stack[qiv->nb_stack -1 ].h;if (top_ht) { -if (g_hash_table_size (top_ht)) { -const char *key; -g_hash_table_find (top_ht, always_true, &key); +GHashTableIter iter; +const char *key; + +g_hash_table_iter_init (&iter, top_ht); +if (g_hash_table_iter_next (&iter, (void **)&key,NULL )) {error_setg (errp,QERR_QMP_EXTRA_MEMBER , key); }g_hash_table_unref (top_ht);
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 26/37] qapi: Simplify excess input reporting in input visitors
Quoted 6 lines · Eric Blake
When reporting that an unvisited member remains at the end of an input visit for a struct, we were using
g_hash_table_find()coupled with a callback function that always returns true, to locate an arbitrary member of the hash table. But if all we need is an arbitrary entry, we can get that from a single-use iterator, without needing a tautological callback function.
Good idea.
Quoted 1 line
Suggested-by Markus Armbruster <[email protected]>
Whoops, it's even mine! I forgot... %-)
Quoted 37 lines
Signed-off-by Eric Blake <[email protected]>Reviewed-by Marc-André Lureau <[email protected]>---
v9: no change
v8: rebase to earlier changes
v7: retitle, rebase to earlier context changes
v6: new patch, based on comments on RFC against v5 7/46--- qapi/opts-visitor.c | 12 +++--------- qapi/qmp-input-visitor.c | 14 +++++--------- 2 files changed, 8 insertions(+), 18 deletions(-)qapi/opts-visitor.c +1
-7@@ -156,17 +156,11 @@ opts_start_struct(Visitor *v, const char *name, void **obj, } -static gboolean -ghr_true (gpointer ign_key,gpointer ign_value,gpointer ign_user_data) -{ -return TRUE; -} - -static void opts_end_struct (Visitor *v,Error **errp) {OptsVisitor *ov =to_ov (v); +GHashTableIter iter;GQueue *any;if (--ov->depth >0 ) {
qapi/opts-visitor.c opts_end_struct(Visitor *v, Error **errp) · line 172
Quoted 7 lines
qapi/opts-visitor.c +2
-2@@ -174,8 +168,8 @@ opts_end_struct(Visitor *v, Error **errp) }/* we should have processed all (distinct) QemuOpt instances */ - any =g_hash_table_find (ov->unprocessed_opts, &ghr_true,NULL ); -if (any) { +g_hash_table_iter_init (&iter, ov->unprocessed_opts); +if (g_hash_table_iter_next (&iter,NULL , (void **)&any)) {
Is this cast kosher?
Quoted 22 lines
qapi/opts-visitor.c +0
-0const QemuOpt *first; first =g_queue_peek_head (any);qapi/qmp-input-visitor.c +0
-6@@ -88,12 +88,6 @@ static void qmp_input_push(QmpInputVisitor *qiv, QObject *obj, Error **errp) qiv->nb_stack++; } -/** Only for qmp_input_pop. */ -static gboolean always_true (gpointer key,gpointer val,gpointer user_pkey) -{ - *(const char **)user_pkey = (const char *)key; -return TRUE; -}static void qmp_input_pop (QmpInputVisitor *qiv,Error **errp) {@@ -102,9 +96,11 @@ static void qmp_input_pop(QmpInputVisitor *qiv, Error **errp)if (qiv->strict) {
qapi/qmp-input-visitor.c static void qmp_input_pop(QmpInputVisitor *qiv, Error **errp) · line 103
Quoted 10 lines
qapi/qmp-input-visitor.c +5
-3GHashTable *const top_ht = qiv->stack[qiv->nb_stack -1 ].h;if (top_ht) { -if (g_hash_table_size (top_ht)) { -const char *key; -g_hash_table_find (top_ht, always_true, &key); +GHashTableIter iter; +const char *key; + +g_hash_table_iter_init (&iter, top_ht); +if (g_hash_table_iter_next (&iter, (void **)&key,NULL )) {
Is this cast kosher?
Quoted 3 lines
qapi/qmp-input-visitor.c +0
-0error_setg (errp,QERR_QMP_EXTRA_MEMBER , key); }g_hash_table_unref (top_ht);
Re: [Qemu-devel] [PATCH v9 26/37] qapi: Simplify excess input reporting in input visitors
Quoted 26 lines · Markus Armbruster
Quoted 6 lines · Eric Blake
When reporting that an unvisited member remains at the end of an input visit for a struct, we were using
g_hash_table_find()coupled with a callback function that always returns true, to locate an arbitrary member of the hash table. But if all we need is an arbitrary entry, we can get that from a single-use iterator, without needing a tautological callback function.Good idea.
Quoted 1 line
Suggested-by Markus Armbruster <[email protected]>Whoops, it's even mine! I forgot... %-)
Quoted 11 lines
Signed-off-by Eric Blake <[email protected]>Reviewed-by Marc-André Lureau <[email protected]>---
GQueue *any; if (--ov->depth > 0) {(quoted diff) +0
-0@@ -174,8 +168,8 @@ opts_end_struct(Visitor *v, Error **errp) }
Quoted 7 lines
qapi/opts-visitor.c opts_end_struct(Visitor *v, Error **errp) · line 172
Quoted 5 lines
qapi/opts-visitor.c +2
-2/* we should have processed all (distinct) QemuOpt instances */ - any =g_hash_table_find (ov->unprocessed_opts, &ghr_true,NULL ); -if (any) { +g_hash_table_iter_init (&iter, ov->unprocessed_opts); +if (g_hash_table_iter_next (&iter,NULL , (void **)&any)) {Is this cast kosher?
You may have a point that it violates some corner of C99, but I'm not the first such user:
hw/i386/intel_iommu.c: while (g_hash_table_iter_next (&bus_it, NULL,
(void**)&vtd_bus)) {qom/object.c: while (g_hash_table_iter_next(&iter, NULL, (gpointer
*)&prop)) {
Conceptually, it seems fine - void* can be assigned to any pointer, and 'any' qualifies as such a pointer. We are then taking the address of that (or void**) to pass by reference.
I suppose a stricter version would be:
void *wrap;
GQueue *any;
if (g_hash_table_iter_next(&iter, NULL, &wrap)) {
any = wrap;...
but is it worth the bother? Put another way, will a compiler ever do the wrong thing to us because C99 might have some corner case? Laszlo, what's your take?
Quoted 11 lines
qapi/qmp-input-visitor.c static void qmp_input_pop(QmpInputVisitor *qiv, Error **errp) · line 103
Quoted 9 lines
qapi/qmp-input-visitor.c +5
-3if (top_ht) { -if (g_hash_table_size (top_ht)) { -const char *key; -g_hash_table_find (top_ht, always_true, &key); +GHashTableIter iter; +const char *key; + +g_hash_table_iter_init (&iter, top_ht); +if (g_hash_table_iter_next (&iter, (void **)&key,NULL )) {Is this cast kosher?
Here, in addition to the above argument, we also needed to cast away const.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v9 26/37] qapi: Simplify excess input reporting in input visitors
Quoted 38 lines · Eric Blake
Quoted 26 lines · Markus Armbruster
Quoted 6 lines · Eric Blake
When reporting that an unvisited member remains at the end of an input visit for a struct, we were using
g_hash_table_find()coupled with a callback function that always returns true, to locate an arbitrary member of the hash table. But if all we need is an arbitrary entry, we can get that from a single-use iterator, without needing a tautological callback function.Good idea.
Quoted 1 line
Suggested-by Markus Armbruster <[email protected]>Whoops, it's even mine! I forgot... %-)
Quoted 11 lines
Signed-off-by Eric Blake <[email protected]>Reviewed-by Marc-André Lureau <[email protected]>---
GQueue *any; if (--ov->depth > 0) {(quoted diff) +0
-0@@ -174,8 +168,8 @@ opts_end_struct(Visitor *v, Error **errp) }Quoted 7 lines
qapi/opts-visitor.c opts_end_struct(Visitor *v, Error **errp) · line 172
Quoted 5 lines
qapi/opts-visitor.c +2
-2/* we should have processed all (distinct) QemuOpt instances */ - any =g_hash_table_find (ov->unprocessed_opts, &ghr_true,NULL ); -if (any) { +g_hash_table_iter_init (&iter, ov->unprocessed_opts); +if (g_hash_table_iter_next (&iter,NULL , (void **)&any)) {Is this cast kosher?
You may have a point that it violates some corner of C99, but I'm not the first such user:
Quoted 8 lines
hw/i386/intel_iommu.c: while (g_hash_table_iter_next(&bus_it, NULL,
(void**)&vtd_bus)) {qom/object.c: while (g_hash_table_iter_next(&iter, NULL, (gpointer
*)&prop)) {Conceptually, it seems fine - void* can be assigned to any pointer, and 'any' qualifies as such a pointer. We are then taking the address of that (or void**) to pass by reference.
Yes, any pointer can be converted to and from void *. Doesn't mean the conversion results in the same bits. It does on machines with a single, uniform pointer format, i.e. any sane machine.
(void **)iter converts iter, not *iter. *iter gets reinterpreted on dereference.
You're right in that this kind of type punning already occurs in QEMU. Also in other programs. We can hope it's common enough to deter optimizers from screwing it up even on sane machines.
Quoted 11 lines
I suppose a stricter version would be:
void *wrap;
GQueue *any;if (g_hash_table_iter_next(&iter, NULL, &wrap)) { any = wrap;...
but is it worth the bother? Put another way, will a compiler ever do the wrong thing to us because C99 might have some corner case? Laszlo, what's your take?
Perhaps Laszlo can confirm or refute my reading of the standard.
Quoted 13 lines
Quoted 11 lines
qapi/qmp-input-visitor.c static void qmp_input_pop(QmpInputVisitor *qiv, Error **errp) · line 103
Quoted 9 lines
qapi/qmp-input-visitor.c +5
-3if (top_ht) { -if (g_hash_table_size (top_ht)) { -const char *key; -g_hash_table_find (top_ht, always_true, &key); +GHashTableIter iter; +const char *key; + +g_hash_table_iter_init (&iter, top_ht); +if (g_hash_table_iter_next (&iter, (void **)&key,NULL )) {Is this cast kosher?
Here, in addition to the above argument, we also needed to cast away const.
Re: [Qemu-devel] [PATCH v9 26/37] qapi: Simplify excess input reporting in input visitors
Quoted 12 lines · Markus Armbruster
Quoted 10 lines · Eric Blake
Quoted 9 lines · Markus Armbruster
Quoted 6 lines · Eric Blake
When reporting that an unvisited member remains at the end of an input visit for a struct, we were using
g_hash_table_find()coupled with a callback function that always returns true, to locate an arbitrary member of the hash table. But if all we need is an arbitrary entry, we can get that from a single-use iterator, without needing a tautological callback function.
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Good idea.
Quoted 1 line
Suggested-by Markus Armbruster <[email protected]>Whoops, it's even mine! I forgot... %-)
Side remark:
https://developer.gnome.org/glib/stable/glib-Hash-Tables.html
g_hash_table_find (): Since: 2.4g_hash_table_iter_next (): Since: 2.16
I can't prove that when I wrote this code, g_hash_table_iter_next() wasn't available, but I may easily have googled & looked at GLib *documentation* that lacked g_hash_table_iter_next(). :)
Quoted 51 lines
Quoted 23 lines
Quoted 12 lines
Quoted 12 lines
Signed-off-by Eric Blake <[email protected]>Reviewed-by Marc-André Lureau <[email protected]>---
GQueue *any; if (--ov->depth > 0) {(quoted diff) +0
-0@@ -174,8 +168,8 @@ opts_end_struct(Visitor *v, Error **errp) }Quoted 7 lines
qapi/opts-visitor.c opts_end_struct(Visitor *v, Error **errp) · line 172
Quoted 5 lines
qapi/opts-visitor.c +2
-2/* we should have processed all (distinct) QemuOpt instances */ - any =g_hash_table_find (ov->unprocessed_opts, &ghr_true,NULL ); -if (any) { +g_hash_table_iter_init (&iter, ov->unprocessed_opts); +if (g_hash_table_iter_next (&iter,NULL , (void **)&any)) {Is this cast kosher?
You may have a point that it violates some corner of C99, but I'm not the first such user:
Quoted 8 lines
hw/i386/intel_iommu.c: while (g_hash_table_iter_next(&bus_it, NULL,
(void**)&vtd_bus)) {qom/object.c: while (g_hash_table_iter_next(&iter, NULL, (gpointer
*)&prop)) {Conceptually, it seems fine - void* can be assigned to any pointer, and 'any' qualifies as such a pointer. We are then taking the address of that (or void**) to pass by reference.
Yes, any pointer can be converted to and from void *. Doesn't mean the conversion results in the same bits. It does on machines with a single, uniform pointer format, i.e. any sane machine.
(void **)iter converts iter, not *iter. *iter gets reinterpreted on dereference.
You're right in that this kind of type punning already occurs in QEMU. Also in other programs. We can hope it's common enough to deter optimizers from screwing it up even on sane machines.
Quoted 8 lines
I suppose a stricter version would be:
void *wrap;
GQueue *any;if (g_hash_table_iter_next(&iter, NULL, &wrap)) { any = wrap;...
Quoted 5 lines
Quoted 3 lines
but is it worth the bother? Put another way, will a compiler ever do the wrong thing to us because C99 might have some corner case? Laszlo, what's your take?
Perhaps Laszlo can confirm or refute my reading of the standard.
The concern is justified; the expression "(void **)&any" does not convert a pointer-to-void to pointer-to-GQueue, it causes the bit pattern to be reinterpreted (it is stored as pointer-to-void and reinterpreted as pointer-to-GQueue).
6.2.5 Types p27 says "A pointer to void shall have the same representation and alignment requirements as a
pointer to a character type. [...] All pointers to structure types shall have the same representation and alignment requirements as each other."
(I'll assume that GQueue is a struct.) But, they need not match each other. At worst, "any" might not even have enough storage for a pointer-to-void.
I'll mention that edk2 is chock-full of the above style cast. I think even the UEFI spec is, in code examples. But, edk2 builds with -fno-strict-aliasing & friends.
... I think it doesn't matter in practice, but if we're trying to prevent compilers from outsmarting us, I'd feel better about "any = wrap".
Thanks
Laszlo
Quoted 14 lines
Quoted 14 lines
Quoted 11 lines
qapi/qmp-input-visitor.c static void qmp_input_pop(QmpInputVisitor *qiv, Error **errp) · line 103
Quoted 10 lines
if (top_ht) {qapi/qmp-input-visitor.c +5
-3-if (g_hash_table_size (top_ht)) { -const char *key; -g_hash_table_find (top_ht, always_true, &key); +GHashTableIter iter; +const char *key; + +g_hash_table_iter_init (&iter, top_ht); +if (g_hash_table_iter_next (&iter, (void **)&key,NULL )) {Quoted 1 line
Is this cast kosher?
Here, in addition to the above argument, we also needed to cast away const.
cover qapi-visit: Unify struct and union visit
In reply to Eric BlakeI got stuck reviewing "[PATCH v9 31/37] qapi-visit: Unify struct and union visit". The result is probably fine, but the patch itself is impenetrable for me. Here's my version. I believe it's really simple to review (but as the author, I'm hopelessly biased).
I based on PATCH 26/37 instead of PATCH 30, because I found the empty struct stuff from PACTH 27-30 not useful for this unification job. If we want it for other reasons (I have no opinion, yet), rebasing it onto this series shouldn't be hard.
Markus Armbruster (3):
qapi-visit: Simplify how we visit common union members
qapi-visit: Clean up code generated around visit_end_union()
qapi-visit: Unify struct and union visit
scripts/qapi-visit.py | 122 +++++++++++++++----------------------------------- 1 file changed, 36 insertions(+), 86 deletions(-)
Signature · 1 line
2.4.3
PATCH 1/3 qapi-visit: Simplify how we visit common union members
For a simple union SU, gen_visit_union() generates a visit of its single tag member, like this:
visit_type_SUKind(v, "type", &(*obj)->type, &err);
For a flat union FU with base B, it generates a visit of its base fields:
visit_type_B_fields(v, (B **)obj, &err);
Instead, we can simply visit the common members using the same fields visit function we use for structs, generated with gen_visit_struct_fields(). This function visits the base if any, then the local members.
For a simple union SU, visit_type_SU_fields() contains exactly the old tag member visit, because there is no base, and the tag member is the only member. For instance, the code generated for qapi-schema-test.json's UserDefNativeListUnion changes like this:
@@ -740,6 +766,19 @@ out:
error_propagate(errp, err);
}
+static void visit_type_UserDefNativeListUnion_fields(Visitor *v, UserDefNativeListUnion **obj, Error **errp)
+{
+ Error *err = NULL;
+
+ visit_type_UserDefNativeListUnionKind(v, "type", &(*obj)->type, &err);
+ if (err) {
+ goto out;
+ }
+
+out:
+ error_propagate(errp, err);
+}
+
void visit_type_UserDefNativeListUnion(Visitor *v, const char *name, UserDefNativeListUnion **obj, Error **errp)
{
Error *err = NULL;
@@ -751,7 +790,7 @@ void visit_type_UserDefNativeListUnion(V
if (!*obj) {
goto out_obj;
}
- visit_type_UserDefNativeListUnionKind(v, "type", &(*obj)->type, &err);
+ visit_type_UserDefNativeListUnion_fields(v, obj, &err);
if (err) {
goto out_obj;
}For a flat union FU, visit_type_FU_fields() contains exactly the old base fields visit, because there is a base, but no members. For instance, the code generated for qapi-schema-test.json's UserDefFlatUnion changes like this:
@@ -616,6 +616,19 @@ out:
static void visit_type_UserDefUnionBase_fields(Visitor *v, UserDefUnionBase **obj, Error **errp);
+static void visit_type_UserDefFlatUnion_fields(Visitor *v, UserDefFlatUnion **obj, Error **errp)
+{
+ Error *err = NULL;
+
+ visit_type_UserDefUnionBase_fields(v, (UserDefUnionBase **)obj, &err);
+ if (err) {
+ goto out;
+ }
+
+out:
+ error_propagate(errp, err);
+}
+
static void visit_type_implicit_UserDefA(Visitor *v, UserDefA **obj, Error **errp)
{
Error *err = NULL;
@@ -651,7 +664,7 @@ void visit_type_UserDefFlatUnion(Visitor
if (!*obj) {
goto out_obj;
}
- visit_type_UserDefUnionBase_fields(v, (UserDefUnionBase **)obj, &err);
+ visit_type_UserDefFlatUnion_fields(v, obj, &err);
if (err) {
goto out_obj;
}As you see, the generated code grows a bit, but in practice, it's lost in the noise: qapi-schema.json's qapi-visit.c gains roughly 1%.
This simplification became possible with commit 441cbac "qapi-visit:
Convert to QAPISchemaVisitor, fixing bugs". It's a step towards unifying gen_struct() and gen_union().
--- scripts/qapi-visit.py | 27 ++++----------------------- 1 file changed, 4 insertions(+), 23 deletions(-)
scripts/qapi-visit.py +4 -23
@@ -238,11 +238,8 @@ out: return ret -def gen_visit_union(name, base, variants): - ret = '' - - if base: - ret += gen_visit_fields_decl(base) +def gen_visit_union(name, base, members, variants): + ret = gen_visit_struct_fields(name, base, members) for var in variants.variants: # Ugly special case for simple union TODO get rid of it
@@ -262,21 +259,9 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error if (!*obj) { goto out_obj; } + visit_type_%(c_name)s_fields(v, obj, &err); ''', c_name=c_name(name)) - - if base: - ret += mcgen(''' - visit_type_%(c_name)s_fields(v, (%(c_name)s **)obj, &err); -''', - c_name=base.c_name()) - else: - ret += mcgen(''' - visit_type_%(c_type)s(v, "%(name)s", &(*obj)->%(c_name)s, &err); -''', - c_type=variants.tag_member.type.c_name(), - c_name=c_name(variants.tag_member.name), - name=variants.tag_member.name) ret += gen_err_check(label='out_obj') ret += mcgen(''' if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) {
@@ -381,11 +366,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor): def visit_object_type(self, name, info, base, members, variants): self.decl += gen_visit_decl(name) if variants: - if members: - # Members other than variants.tag_member not implemented - assert len(members) == 1 - assert members[0] == variants.tag_member - self.defn += gen_visit_union(name, base, variants) + self.defn += gen_visit_union(name, base, members, variants) else: self.defn += gen_visit_struct(name, base, members)
Signature · 1 line
2.4.3
Re: [Qemu-devel] [PATCH 1/3] qapi-visit: Simplify how we visit common union members
Quoted 8 lines · Markus Armbruster
For a simple union SU,
gen_visit_union()generates a visit of its single tag member, like this:visit_type_SUKind(v, "type", &(*obj)->type, &err);For a flat union FU with base B, it generates a visit of its base fields:
Quoted 6 lines
visit_type_B_fields(v, (B **)obj, &err);Instead, we can simply visit the common members using the same fields visit function we use for structs, generated with
gen_visit_struct_fields(). This function visits the base if any, then the local members.
I like how you've split up my gen_struct/gen_union merge into a few more steps. I'll be incorporating your patch into my v10 spin.
Quoted 11 lines
For a simple union SU,
visit_type_SU_fields()contains exactly the old tag member visit, because there is no base, and the tag member is the only member. For instance, the code generated for qapi-schema-test.json's UserDefNativeListUnion changes like this:@@ -740,6 +766,19 @@ out: error_propagate(errp, err); } +static void visit_type_UserDefNativeListUnion_fields(Visitor *v, UserDefNativeListUnion **obj, Error **errp)
I may try to rewrite the commit to pick a shorter example, though :)
Quoted 13 lines
As you see, the generated code grows a bit, but in practice, it's lost in the noise: qapi-schema.json's
qapi-visit.cgains roughly 1%.This simplification became possible with commit 441cbac "qapi-visit:
Convert to QAPISchemaVisitor, fixing bugs". It's a step towards unifyinggen_struct()andgen_union().Signed-off-by Markus Armbruster <[email protected]>--- scripts/qapi-visit.py | 27 ++++----------------------- 1 file changed, 4 insertions(+), 23 deletions(-)
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
PATCH 2/3 qapi-visit: Clean up code generated around visit_end_union()
In reply to Markus ArmbrusterThe generated code can call visit_end_union() without having called visit_start_union(). Example:
if (!*obj) {
goto out_obj;
}
visit_type_BlockdevOptions_fields(v, obj, &err);
if (err) {
goto out_obj; // if we go from here...
}
if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) {
goto out_obj;
}
switch ((*obj)->driver) {
[...]
}
out_obj:
// ... then *obj is true, and ...
error_propagate(errp, err);
err = NULL;
if (*obj) {
// we end up here
visit_end_union(v, !!(*obj)->u.data, &err);
}
error_propagate(errp, err);Harmless only because no visitor implements end_union(). Clean it up anyway.
Messed up since we have visit_end_union (commit cee2ded).
--- scripts/qapi-visit.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-)
scripts/qapi-visit.py +2 -4
@@ -299,12 +299,10 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error default: abort(); } -out_obj: error_propagate(errp, err); err = NULL; - if (*obj) { - visit_end_union(v, !!(*obj)->u.data, &err); - } + visit_end_union(v, !!(*obj)->u.data, &err); +out_obj: error_propagate(errp, err); err = NULL; visit_end_struct(v, &err);
Signature · 1 line
2.4.3
Re: [Qemu-devel] [PATCH 2/3] qapi-visit: Clean up code generated around visit_end_union()
Quoted 26 lines · Markus Armbruster
The generated code can call
visit_end_union()without having calledvisit_start_union(). Example:if (!*obj) { goto out_obj; } visit_type_BlockdevOptions_fields(v, obj, &err); if (err) { goto out_obj; // if we go from here... } if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) { goto out_obj; } switch ((*obj)->driver) { [...] } out_obj: // ... then *obj is true, and ... error_propagate(errp, err); err = NULL; if (*obj) { // we end up here visit_end_union(v, !!(*obj)->u.data, &err); } error_propagate(errp, err);
Quoted 2 lines
Harmless only because no visitor implements
end_union(). Clean it up anyway.
I plan on deleting visit_end_union() anyways (and visit_start_union); see 32/37, plus the FIXME comments added in 21/37. Maybe it's easier to just delete this incorrect and unused callback earlier in the series, using your commit message as additional rationale why it is worthless, and leaving only visit_start_union() cleanups for 32/37.
Quoted 2 lines
Messed up since we have
visit_end_union(commit cee2ded).
Indeed.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH 2/3] qapi-visit: Clean up code generated around visit_end_union()
Quoted 18 lines · Eric Blake
Quoted 17 lines · Markus Armbruster
The generated code can call
visit_end_union()without having calledvisit_start_union(). Example:if (!*obj) { goto out_obj; } visit_type_BlockdevOptions_fields(v, obj, &err); if (err) { goto out_obj; // if we go from here... } if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) { goto out_obj; } switch ((*obj)->driver) { [...] } out_obj:
Quoted 8 lines
Quoted 8 lines
// ... then *obj is true, and ... error_propagate(errp, err); err = NULL; if (*obj) { // we end up here visit_end_union(v, !!(*obj)->u.data, &err); } error_propagate(errp, err);
Tabs crept into my commit message, oops.
Quoted 9 lines
Quoted 3 lines
Harmless only because no visitor implements
end_union(). Clean it up anyway.I plan on deleting
visit_end_union()anyways (andvisit_start_union); see 32/37, plus the FIXME comments added in 21/37. Maybe it's easier to just delete this incorrect and unused callback earlier in the series, using your commit message as additional rationale why it is worthless, and leaving onlyvisit_start_union()cleanups for 32/37.
I could've tried to move PATCH 32 before the unification, but that would've been work, so I went with this straightforward fix instead. Sure, it fixes something that'll go away soon, but I think the churn is quite tolerable: 1 file changed, 2 insertions(+), 4 deletions(-).
Quoted 3 lines
Quoted 1 line
Messed up since we have
visit_end_union(commit cee2ded).Indeed.
PATCH 3/3 qapi-visit: Unify struct and union visit
In reply to Markus Armbrustergen_visit_union() is now just like gen_visit_struct() plus additional code to handle variants. Make that code conditional on variants, so gen_visit_union() does exactly the same for structs as gen_visit_struct(). Rename it to gen_visit_object(), use it for structs, and drop gen_visit_struct().
Output is identical.
--- scripts/qapi-visit.py | 95 ++++++++++++++++++--------------------------------- 1 file changed, 33 insertions(+), 62 deletions(-)
scripts/qapi-visit.py +33 -62
@@ -109,40 +109,6 @@ out: return ret -def gen_visit_struct(name, base, members): - ret = gen_visit_struct_fields(name, base, members) - - # FIXME: if *obj is NULL on entry, and visit_start_struct() assigns to - # *obj, but then visit_type_FOO_fields() fails, we should clean up *obj - # rather than leaving it non-NULL. As currently written, the caller must - # call qapi_free_FOO() to avoid a memory leak of the partial FOO. - ret += mcgen(''' - -void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) -{ - Error *err = NULL; - - visit_start_struct(v, name, (void **)obj, sizeof(%(c_name)s), &err); - if (err) { - goto out; - } - if (!*obj) { - goto out_obj; - } - visit_type_%(c_name)s_fields(v, obj, &err); -out_obj: - error_propagate(errp, err); - err = NULL; - visit_end_struct(v, &err); -out: - error_propagate(errp, err); -} -''', - c_name=c_name(name)) - - return ret - - def gen_visit_list(name, element_type): # FIXME: if *obj is NULL on entry, and the first visit_next_list() # assigns to *obj, while a later one fails, we should clean up *obj
@@ -238,14 +204,19 @@ out: return ret -def gen_visit_union(name, base, members, variants): +def gen_visit_object(name, base, members, variants): ret = gen_visit_struct_fields(name, base, members) - 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_implicit_struct(var.type) + 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_implicit_struct(var.type) + # FIXME: if *obj is NULL on entry, and visit_start_struct() assigns to + # *obj, but then visit_type_FOO_fields() fails, we should clean up *obj + # rather than leaving it non-NULL. As currently written, the caller must + # call qapi_free_FOO() to avoid a memory leak of the partial FOO. ret += mcgen(''' void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp)
@@ -262,46 +233,49 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error visit_type_%(c_name)s_fields(v, obj, &err); ''', c_name=c_name(name)) - ret += gen_err_check(label='out_obj') - ret += mcgen(''' + if variants: + ret += gen_err_check(label='out_obj') + ret += mcgen(''' if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) { goto out_obj; } switch ((*obj)->%(c_name)s) { ''', - c_name=c_name(variants.tag_member.name)) + 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(''' + 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)) - if simple_union_type: - ret += mcgen(''' + case=c_enum_const(variants.tag_member.type.name, + var.name)) + 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(''' + c_type=simple_union_type.c_name(), + c_name=c_name(var.name)) + else: + ret += mcgen(''' visit_type_implicit_%(c_type)s(v, &(*obj)->u.%(c_name)s, &err); ''', - c_type=var.type.c_name(), - c_name=c_name(var.name)) - ret += mcgen(''' + c_type=var.type.c_name(), + c_name=c_name(var.name)) + ret += mcgen(''' break; ''') - ret += mcgen(''' + ret += mcgen(''' default: abort(); } error_propagate(errp, err); err = NULL; visit_end_union(v, !!(*obj)->u.data, &err); +''') + ret += mcgen(''' out_obj: error_propagate(errp, err); err = NULL;
@@ -363,10 +337,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor): def visit_object_type(self, name, info, base, members, variants): self.decl += gen_visit_decl(name) - if variants: - self.defn += gen_visit_union(name, base, members, variants) - else: - self.defn += gen_visit_struct(name, base, members) + self.defn += gen_visit_object(name, base, members, variants) def visit_alternate_type(self, name, info, variants): self.decl += gen_visit_decl(name)
Signature · 1 line
2.4.3
PATCH v9 27/37 qapi: Add type.is_empty() helper
In reply to Eric BlakeAnd 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. 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 but empty type in the same was as a missing type.
---
v9: improve commit message
v8: no change
v7: rebase to context change
v6: new patch
--- scripts/qapi-event.py | 6 +++--- scripts/qapi-types.py | 2 +- scripts/qapi.py | 3 +++ 3 files changed, 7 insertions(+), 4 deletions(-)
scripts/qapi-event.py +3 -3
@@ -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,7 @@ 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(): ret += mcgen(''' qov = qmp_output_visitor_new(); v = qmp_output_get_visitor(qov);
@@ -88,7 +88,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
@@ -76,7 +76,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; ''')
scripts/qapi.py +3 -0
@@ -973,6 +973,9 @@ class QAPISchemaObjectType(QAPISchemaType): # See QAPISchema._make_implicit_object_type() return self.name[0] == ':' + def is_empty(self): + return not self.members and not self.variants + def c_name(self): assert not self.is_implicit() return QAPISchemaType.c_name(self)
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 27/37] qapi: Add type.is_empty() helper
Quoted 26 lines · 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. 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 but empty type in the same was as a missing type.
Signed-off-by Eric Blake <[email protected]>---
v9: improve commit message
v8: no change
v7: rebase to context change
v6: new patch--- scripts/qapi-event.py | 6 +++--- scripts/qapi-types.py | 2 +- scripts/qapi.py | 3 +++ 3 files changed, 7 insertions(+), 4 deletions(-)scripts/qapi-event.py +0
-0
scripts/qapi-event.py def gen_event_send(name, arg_type): · line 42
Quoted 5 lines
scripts/qapi-event.py +1
-1@@ -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():
With .is_empty() expanded and negations folded:
if arg_type and (arg_type.members or arg_type.variants):
Effectively the same, because .variants is None here. Asserted in QAPISchemaEvent.check().
scripts/qapi-event.py def gen_event_send(name, arg_type): · line 61
Quoted 9 lines
scripts/qapi-event.py +1
-1ret += mcgen(''' QmpOutputVisitor *qov; Visitor *v;@@ -58,7 +58,7 @@ 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():
Likewise.
However, we still use arg_type.members:
scripts/qapi-event.py def gen_event_send(name, arg_type): · line 64
Quoted 3 lines
scripts/qapi-event.py +0
-0ret += mcgen(''' qov = qmp_output_visitor_new(); v = qmp_output_get_visitor(qov);
visit_start_struct(v, "%(name)s", NULL, 0, &err);
''',
name=name)
ret += gen_err_check()
ret += gen_visit_fields(arg_type.members, need_cast=True,
label='out_obj')
ret += mcgen('''
out_obj:
visit_end_struct(v, &err);
if (err) {
goto out;
}Your patch makes liberates the guard from the implementation, but not the actual use. That's okay. Should we comment or assert that variants aren't implemented here, even though we already assert in QAPISchemaEvent.check()?
Quoted 14 lines
scripts/qapi-event.py +1
-1@@ -88,7 +88,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 +0
-0
scripts/qapi-types.py struct %(c_name)s { · line 82
Quoted 8 lines
scripts/qapi-types.py +1
-1@@ -76,7 +76,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; ''')
This is similar: effectively the same because base.variants is None.
I'm pretty sure we check base is a plain struct (no variants) somewhere. I think we should also assert not base.variants in QAPISchemaObjectType.check(), for completeness and clarity.
scripts/qapi.py class QAPISchemaObjectType(QAPISchemaType): · line 978
Quoted 11 lines
scripts/qapi.py +3
-0@@ -973,6 +973,9 @@ class QAPISchemaObjectType(QAPISchemaType): # See QAPISchema._make_implicit_object_type() return self.name[0] == ':' + def is_empty(self): + return not self.members and not self.variants +
Works only after .check(). Before .check(), self.members is None. Your uses are all safely after .check().
Suggest to assert self.members is not None.
Quoted 3 lines
scripts/qapi.py +0
-0def c_name(self): assert not self.is_implicit() return QAPISchemaType.c_name(self)
PATCH v9 28/37 qapi: Fix command with named empty argument type
In reply to Eric BlakeThe 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. Without a fix to the generator, the change to qapi-schema-test.json fails to compile with:
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;
^---
v9: no change
v8: no change
v7: no change
v6: new patch
--- scripts/qapi-commands.py | 6 +++--- tests/qapi-schema/qapi-schema-test.json | 2 ++ tests/qapi-schema/qapi-schema-test.out | 2 ++ tests/test-qmp-commands.c | 5 +++++ 4 files changed, 12 insertions(+), 3 deletions(-)
scripts/qapi-commands.py +3 -3
@@ -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/qapi-schema/qapi-schema-test.json +2 -0
@@ -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
@@ -198,6 +198,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
tests/test-qmp-commands.c +5 -0
@@ -12,6 +12,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) { }
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 28/37] qapi: Fix command with named empty argument type
Quoted 33 lines · 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. Without a fix to the generator, the change to qapi-schema-test.json fails to compile with:
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; ^Signed-off-by Eric Blake <[email protected]>Reviewed-by Marc-André Lureau <[email protected]>---
v9: no change
v8: no change
v7: no change
v6: new patch--- scripts/qapi-commands.py | 6 +++--- tests/qapi-schema/qapi-schema-test.json | 2 ++ tests/qapi-schema/qapi-schema-test.out | 2 ++ tests/test-qmp-commands.c | 5 +++++ 4 files changed, 12 insertions(+), 3 deletions(-)scripts/qapi-commands.py +0
-0
scripts/qapi-commands.py def gen_marshal_vars(arg_type, ret_type): · line 68
Quoted 5 lines
scripts/qapi-commands.py +1
-1@@ -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():
This guards generating the variables for getting arguments, first a few common ones, then one or two per argument.
The patch changes it to effectively
if arg_type and (arg_type.members or arg_type.variants)
.variants is None (asserted in QAPISchemaCommand.check()). Thus, the patch effectively just adds and arg_type.members.
Impact: when arg_type has no members, we still generate the common variables before the patch. The patch suppresses them. Whether that makes sense depends on the next hunk, which generates the code using these variables.
scripts/qapi-commands.py def gen_marshal_vars(arg_type, ret_type): · line 101
Quoted 10 lines
scripts/qapi-commands.py +1
-1ret += 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
This guards generating the code for getting arguments: common code, and per-argument code.
Impact: when arg_type has no members, we still generate the common code before the patch. The patch suppresses it. Is that okay? We'll see below.
scripts/qapi-commands.py def gen_marshal(name, arg_type, ret_type): · line 180
Quoted 8 lines
scripts/qapi-commands.py +1
-1if 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:
This guards generating label out. or's left operand is about the arguments. Unlike the guards above, it checks .members even before the patch.
Quoted 35 lines
scripts/qapi-commands.py +0
-0ret += mcgen(''' out:tests/qapi-schema/qapi-schema-test.json +2
-0@@ -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@@ -198,6 +198,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 -> UserDefTwotests/test-qmp-commands.c +0
-0@@ -12,6 +12,11 @@ void qmp_user_def_cmd(Error **errp) {
tests/test-qmp-commands.c void qmp_user_def_cmd(Error **errp) · line 22
Quoted 10 lines
tests/test-qmp-commands.c +5
-0} +Empty2 *qmp_user_def_cmd0 (Error **errp) +{ +return g_new0 (Empty2,1 ); +} +void qmp_user_def_cmd1 (UserDefOne * ud1,Error **errp) { }
Patch's effect on the test case:
tests/new-test-qmp-marshal.c renamed from tests/test-qmp-marshal.c +1 -8
@@ -254,11 +254,8 @@ {Error *err =NULL ;Empty2 *retval; -QmpInputVisitor *qiv =qmp_input_visitor_new_strict (QOBJECT (args)); -QapiDeallocVisitor *qdv; -Visitor *v; - v =qmp_input_get_visitor (qiv); + (void )args; retval =qmp_user_def_cmd0 (&err);if (err) {
@@ -269,10 +266,6 @@ out:error_propagate (errp, err); -qmp_input_visitor_cleanup (qiv); - qdv =qapi_dealloc_visitor_new (); - v =qapi_dealloc_get_visitor (qdv); -qapi_dealloc_visitor_cleanup (qdv); }static void qmp_marshal_user_def_cmd1 (QDict *args,QObject **ret,Error **errp)
We drop a pair of "create a visitor, destroy it without having done anything with it". Okay.
Commit message might mislead readers into assuming the patch merely drops unused variables. It actually drops creating useless visitors. Easy enough to clarify:
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. 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;
^
PATCH v9 29/37 qapi: Eliminate empty visit_type_FOO_fields
In reply to Eric BlakeFor empty structs, such as the 'Abort' helper type used as part of the 'transaction' command, we were emitting a no-op visit_type_FOO_fields(). Optimize things to instead omit calls for empty structs. Generated code changes resemble:
|-static void visit_type_Abort_fields(Visitor *v, Abort **obj, Error **errp)
|-{
|- Error *err = NULL;
|-
|- error_propagate(errp, err);
|-}
|-
| void visit_type_Abort(Visitor *v, const char *name, Abort **obj, Error **errp)
| {
| Error *err = NULL;
|@@ -112,7 +105,6 @@ void visit_type_Abort(Visitor *v, Abort
| if (!*obj) {
| goto out_obj;
| }
|- visit_type_Abort_fields(v, obj, &err);
| out_obj:
| error_propagate(errp, err);Another reason for doing this optimization is that it gets us closer to merging the code for visiting structs and unions:
since flat unions have no local members, they do not need to have a visit_type_UNION_fields() emitted, even when they start sharing the code used to visit structs.
---
v9: no change
v8: rebase to earlier changes
v7: rebase to earlier changes
v6: new patch
--- scripts/qapi-visit.py | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-)
scripts/qapi-visit.py +23 -18
@@ -35,22 +35,22 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_type)sobj, Error ** def gen_visit_fields_decl(typ): - ret = '' - if typ.name not in struct_fields_seen: - ret += mcgen(''' + if typ.is_empty() or typ.name in struct_fields_seen: + return '' + + struct_fields_seen.add(typ.name) + return mcgen(''' static void visit_type_%(c_type)s_fields(Visitor *v, %(c_type)s **obj, Error **errp); ''', - c_type=typ.c_name()) - struct_fields_seen.add(typ.name) - return ret + c_type=typ.c_name()) def gen_visit_implicit_struct(typ): - if typ in implicit_structs_seen: + if typ.is_empty() or typ in implicit_structs_seen: return '' + implicit_structs_seen.add(typ) - ret = gen_visit_fields_decl(typ) ret += mcgen('''
@@ -74,7 +74,10 @@ static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * def gen_visit_struct_fields(name, base, members): ret = '' - if base: + if (not base or base.is_empty()) and not members: + return ret + + if base and not base.is_empty(): ret += gen_visit_fields_decl(base) struct_fields_seen.add(name)
@@ -87,7 +90,7 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s **obj, Error **e ''', c_name=c_name(name)) - if base: + if base and not base.is_empty(): ret += mcgen(''' visit_type_%(c_type)s_fields(v, (%(c_type)s **)obj, &err); ''',
@@ -96,13 +99,9 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s **obj, Error **e ret += gen_visit_fields(members, prefix='(*obj)->') - # 'goto out' produced for base, and by gen_visit_fields() for each member - if base or members: - ret += mcgen(''' + ret += mcgen(''' out: -''') - ret += mcgen(''' error_propagate(errp, err); } ''')
@@ -129,7 +128,14 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error if (!*obj) { goto out_obj; } +''', + name=name, c_name=c_name(name)) + if (base and not base.is_empty()) or members: + ret += mcgen(''' visit_type_%(c_name)s_fields(v, obj, &err); +''', + c_name=c_name(name)) + ret += mcgen(''' out_obj: error_propagate(errp, err); err = NULL;
@@ -137,8 +143,7 @@ out_obj: out: error_propagate(errp, err); } -''', - c_name=c_name(name)) +''') return ret
@@ -300,7 +305,7 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error ''', c_type=simple_union_type.c_name(), c_name=c_name(var.name)) - else: + elif not var.type.is_empty(): ret += mcgen(''' visit_type_implicit_%(c_type)s(v, &(*obj)->u.%(c_name)s, &err); ''',
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 29/37] qapi: Eliminate empty visit_type_FOO_fields
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_type)sobj, Error **
Quoted 46 lines · Eric Blake
For empty structs, such as the 'Abort' helper type used as part of the 'transaction' command, we were emitting a no-op
visit_type_FOO_fields(). Optimize things to instead omit calls for empty structs. Generated code changes resemble:|-static void visit_type_Abort_fields(Visitor *v, Abort **obj, Error **errp) |-{ |- Error *err = NULL; |- |- error_propagate(errp, err); |-} |- | void visit_type_Abort(Visitor *v, const char *name, Abort **obj, Error **errp) | { | Error *err = NULL; |@@ -112,7 +105,6 @@ void visit_type_Abort(Visitor *v, Abort | if (!*obj) { | goto out_obj; | } |- visit_type_Abort_fields(v, obj, &err); | out_obj: | error_propagate(errp, err);Another reason for doing this optimization is that it gets us closer to merging the code for visiting structs and unions:
since flat unions have no local members, they do not need to have avisit_type_UNION_fields()emitted, even when they start sharing the code used to visit structs.Signed-off-by Eric Blake <[email protected]>Reviewed-by Marc-André Lureau <[email protected]>---
v9: no change
v8: rebase to earlier changes
v7: rebase to earlier changes
v6: new patch--- scripts/qapi-visit.py | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-)scripts/qapi-visit.py +0
-0@@ -35,22 +35,22 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_type)sobj, Error **
Two clean ways to skin this cat (at least). One emphasizes that gen_visit_fields_decl() & friends do nothing when the type is empty. The other emphasizes that they generate at most once. Matter of taste.
The two ways differ in how they treat the seen sets:
# visit_type_FOO_implicit() is emitted as needed; track if it has already
# been output. implicit_structs_seen = set()
# visit_type_FOO_fields() is always emitted; track if a forward declaration
# or implementation has already been output. struct_fields_seen = set()
To emphasize do nothing when empty, test empty first. iEmpty types are never added to these seen sets.
To emphasize generate at most once, test the seen set first. Empty types are added normally, even though nothing is output for them.
Quoted 8 lines
scripts/qapi-visit.py +2
-3def gen_visit_fields_decl(typ): - ret = '' - if typ.name not in struct_fields_seen: - ret += mcgen(''' + if typ.is_empty() or typ.name in struct_fields_seen: + return ''
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_type)sobj, Error ** · line 46
Quoted 10 lines
scripts/qapi-visit.py +4
-3+ + struct_fields_seen.add(typ.name) + return mcgen(''' static void visit_type_%(c_type)s_fields(Visitor *v, %(c_type)s **obj, Error **errp); ''', - c_type=typ.c_name()) - struct_fields_seen.add(typ.name) - return ret + c_type=typ.c_name())
Emphasize do nothing when empty:
def gen_visit_fields_decl(typ):
if typ.is_empty():
return ''
if typ.name in struct_fields_seen:
return ''
struct_fields_seen.add(typ.name)
return mcgen('''
static void visit_type_%(c_type)s_fields(Visitor *v, %(c_type)s **obj, Error **errp);
''',
c_type=typ.c_name())Same as yours, except yours merges the conditionals. I left them unmerged to make the
if X not in S:
return ''
S.add(X)
pattern stand out. Matter of taste.
Emphasize generate at most once:
def gen_visit_fields_decl(typ):
if typ.name in struct_fields_seen:
return ''
struct_fields_seen.add(typ.name)
if typ.is_empty():
return ''
return mcgen('''
static void visit_type_%(c_type)s_fields(Visitor *v, %(c_type)s **obj, Error **errp);
''',
c_type=typ.c_name())scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_type)sobj, Error ** · line 55
Quoted 11 lines
scripts/qapi-visit.py +2
-2def gen_visit_implicit_struct(typ): - if typ in implicit_structs_seen: + if typ.is_empty() or typ in implicit_structs_seen: return '' + implicit_structs_seen.add(typ) - ret = gen_visit_fields_decl(typ)
Likewise.
scripts/qapi-visit.py static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * · line 78
Quoted 8 lines
scripts/qapi-visit.py +2
-1ret += mcgen('''@@ -74,7 +74,10 @@ static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * def gen_visit_struct_fields(name, base, members): ret = '' - if base: + if (not base or base.is_empty()) and not members: + return ret
The condition predicts whether the rest of the function won't generate anything useful. Such predictions can be brittle, but this one seems still simple enough.
scripts/qapi-visit.py static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * · line 81
Quoted 3 lines
scripts/qapi-visit.py +2
-0+ + if base and not base.is_empty(): ret += gen_visit_fields_decl(base)
"if base" suffices, because gen_visit_fields_decl(base) returns '' when base.is_empty(). I guess you test it anyway, for symmetry with the next hunk. Okay.
Quoted 16 lines
scripts/qapi-visit.py +1
-2struct_fields_seen.add(name)@@ -87,7 +90,7 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s **obj, Error **e ''', c_name=c_name(name)) - if base: + if base and not base.is_empty(): ret += mcgen(''' visit_type_%(c_type)s_fields(v, (%(c_type)s **)obj, &err); ''',@@ -96,13 +99,9 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s **obj, Error **e ret += gen_visit_fields(members, prefix='(*obj)->') - # 'goto out' produced for base, and by gen_visit_fields() for each member
scripts/qapi-visit.py static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s **obj, Error **e · line 107
Quoted 10 lines
scripts/qapi-visit.py +1
-4- if base or members: - ret += mcgen(''' + ret += mcgen(''' out: -''') - ret += mcgen(''' error_propagate(errp, err); } ''')
The optimization earns a small part of its keep here: we don't need a conditional for the out label anymore.
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 133
Quoted 7 lines
scripts/qapi-visit.py +3
-0@@ -129,7 +128,14 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error if (!*obj) { goto out_obj; } +''', + name=name, c_name=c_name(name)) + if (base and not base.is_empty()) or members:
Duplicates gen_visit_struct_fields()' guard. Could be avoided by testing whether gen_visit_struct_fields() returned anything. Either way is kind of ugly, though. Pick the poison you hate less.
Quoted 19 lines
scripts/qapi-visit.py +5
-2+ ret += mcgen(''' visit_type_%(c_name)s_fields(v, obj, &err); +''', + c_name=c_name(name)) + ret += mcgen(''' out_obj: error_propagate(errp, err); err = NULL;@@ -137,8 +143,7 @@ out_obj: out: error_propagate(errp, err); } -''', - c_name=c_name(name)) +''') return ret
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 311
Quoted 8 lines
scripts/qapi-visit.py +1
-1@@ -300,7 +305,7 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error ''', c_type=simple_union_type.c_name(), c_name=c_name(var.name)) - else: + elif not var.type.is_empty(): ret += mcgen(''' visit_type_implicit_%(c_type)s(v, &(*obj)->u.%(c_name)s, &err); ''',
Similar, for gen_visit_implicit_struct(). The condition is more obvious here.
I'm not sure the optimization is worthwhile by itself. Empty structs are rare. I'm reserving judgement until I see the struct/union unification.
Re: [Qemu-devel] [PATCH v9 29/37] qapi: Eliminate empty visit_type_FOO_fields
Quoted 16 lines · Markus Armbruster
Quoted 6 lines · Eric Blake
For empty structs, such as the 'Abort' helper type used as part of the 'transaction' command, we were emitting a no-op
visit_type_FOO_fields(). Optimize things to instead omit calls for empty structs. Generated code changes resemble:Quoted 6 lines
Another reason for doing this optimization is that it gets us closer to merging the code for visiting structs and unions:
since flat unions have no local members, they do not need to have avisit_type_UNION_fields()emitted, even when they start sharing the code used to visit structs.
Quoted 3 lines
I'm not sure the optimization is worthwhile by itself. Empty structs are rare. I'm reserving judgement until I see the struct/union unification.
We managed to pull off unification without this patch, and your argument about making the generator more verbose with no-ops if it is less maintenance is still resonating with me. I think I'm going to drop this and 30/37 in my next round of patches, with no real loss in functionality.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
PATCH v9 30/37 qapi: Canonicalize missing object to :empty
In reply to Eric BlakeNow that we elide unnecessary visits of empty types, we can start using the special ':empty' type in more places. By using the empty type as the base class of every explicit struct or union, and as the default data for any command or event, we can simplify later logic in qapi-{visit,commands,event} by merely checking whether the type is empty, without also having to worry whether a type was even supplied.
Note that gen_object() in qapi-types still has to check for a base, because it is also called for alternates (which have no base).
No change to generated code.
---
v9: squash in more related changes
v8: rebase to earlier changes
v7: rebase to earlier changes
v6: new patch
--- scripts/qapi-commands.py | 17 +++++++------ scripts/qapi-event.py | 5 ++-- scripts/qapi-types.py | 4 +-- scripts/qapi-visit.py | 12 +++++---- scripts/qapi.py | 25 +++++++++--------- tests/qapi-schema/event-case.out | 2 +- tests/qapi-schema/flat-union-empty.out | 1 + tests/qapi-schema/ident-with-escape.out | 1 + tests/qapi-schema/indented-expr.out | 4 +-- tests/qapi-schema/qapi-schema-test.out | 45 ++++++++++++++++++++++++++++++--- tests/qapi-schema/union-clash-data.out | 2 ++ tests/qapi-schema/union-empty.out | 1 + 12 files changed, 83 insertions(+), 36 deletions(-)
scripts/qapi-commands.py +9 -8
@@ -29,11 +29,11 @@ def gen_call(name, arg_type, ret_type): ret = '' argstr = '' - if arg_type: - for memb in arg_type.members: - if memb.optional: - argstr += 'has_%s, ' % c_name(memb.name) - argstr += '%s, ' % c_name(memb.name) + assert arg_type + for memb in arg_type.members: + if memb.optional: + argstr += 'has_%s, ' % c_name(memb.name) + argstr += '%s, ' % c_name(memb.name) lhs = '' if ret_type:
@@ -65,7 +65,8 @@ def gen_marshal_vars(arg_type, ret_type): ''', c_type=ret_type.c_type()) - if arg_type and not arg_type.is_empty(): + assert arg_type + if not arg_type.is_empty(): ret += mcgen(''' QmpInputVisitor *qiv = qmp_input_visitor_new_strict(QOBJECT(args)); QapiDeallocVisitor *qdv;
@@ -97,7 +98,7 @@ def gen_marshal_vars(arg_type, ret_type): def gen_marshal_input_visit(arg_type, dealloc=False): ret = '' - if not arg_type or arg_type.is_empty(): + if arg_type.is_empty(): return ret if dealloc:
@@ -177,7 +178,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 not arg_type.is_empty()) or ret_type: + if not arg_type.is_empty() or ret_type: ret += mcgen(''' out:
scripts/qapi-event.py +3 -2
@@ -39,7 +39,8 @@ def gen_event_send(name, arg_type): ''', proto=gen_event_send_proto(name, arg_type)) - if arg_type and not arg_type.is_empty(): + assert arg_type + if not arg_type.is_empty(): ret += mcgen(''' QmpOutputVisitor *qov; Visitor *v;
@@ -88,7 +89,7 @@ out_obj: ''', c_enum=c_enum_const(event_enum_name, name)) - if arg_type and not arg_type.is_empty(): + if not arg_type.is_empty(): ret += mcgen(''' out: qmp_output_visitor_cleanup(qov);
scripts/qapi-types.py +2 -2
@@ -58,7 +58,7 @@ struct %(c_name)s { ''', c_name=c_name(name)) - if base: + if base and not base.is_empty(): ret += mcgen(''' /* Members inherited from %(c_name)s: */ ''',
@@ -222,7 +222,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 not base.is_implicit(): self.decl += gen_upcast(name, base) self._gen_type_cleanup(name)
scripts/qapi-visit.py +7 -5
@@ -74,10 +74,11 @@ static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * def gen_visit_struct_fields(name, base, members): ret = '' - if (not base or base.is_empty()) and not members: + assert base + if base.is_empty() and not members: return ret - if base and not base.is_empty(): + if not base.is_empty(): ret += gen_visit_fields_decl(base) struct_fields_seen.add(name)
@@ -90,7 +91,7 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s **obj, Error **e ''', c_name=c_name(name)) - if base and not base.is_empty(): + if not base.is_empty(): ret += mcgen(''' visit_type_%(c_type)s_fields(v, (%(c_type)s **)obj, &err); ''',
@@ -246,7 +247,8 @@ out: def gen_visit_union(name, base, variants): ret = '' - if base: + assert base + if not base.is_empty(): ret += gen_visit_fields_decl(base) for var in variants.variants:
@@ -270,7 +272,7 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error ''', c_name=c_name(name)) - if base: + if not base.is_empty(): ret += mcgen(''' visit_type_%(c_name)s_fields(v, (%(c_name)s **)obj, &err); ''',
scripts/qapi.py +12 -13
@@ -922,11 +922,11 @@ class QAPISchemaArrayType(QAPISchemaType): class QAPISchemaObjectType(QAPISchemaType): def __init__(self, name, info, base, local_members, variants): - # struct has local_members, optional base, and no variants + # struct has local_members, base, and no variants # flat union has base, variants, and no local_members - # simple union has local_members, variants, and no base + # simple union has local_members, variants, and base of :empty QAPISchemaType.__init__(self, name, info) - assert base is None or isinstance(base, str) + assert isinstance(base, str) or name == ':empty' for m in local_members: assert isinstance(m, QAPISchemaObjectTypeMember) m.set_owner(name)
@@ -1264,11 +1264,11 @@ class QAPISchema(object): def _make_implicit_object_type(self, name, info, role, members): if not members: - return None + return ':empty' # See also QAPISchemaObjectTypeMember._pretty_owner() name = ':obj-%s-%s' % (name, role) if not self.lookup_entity(name, QAPISchemaObjectType): - self._def_entity(QAPISchemaObjectType(name, info, None, + self._def_entity(QAPISchemaObjectType(name, info, ':empty', members, None)) return name
@@ -1295,7 +1295,7 @@ class QAPISchema(object): def _def_struct_type(self, expr, info): name = expr['struct'] - base = expr.get('base') + base = expr.get('base', ':empty') data = expr['data'] self._def_entity(QAPISchemaObjectType(name, info, base, self._make_members(data, info),
@@ -1315,7 +1315,7 @@ class QAPISchema(object): def _def_union_type(self, expr, info): name = expr['union'] data = expr['data'] - base = expr.get('base') + base = expr.get('base', ':empty') tag_name = expr.get('discriminator') tag_member = None if tag_name:
@@ -1349,11 +1349,11 @@ class QAPISchema(object): def _def_command(self, expr, info): name = expr['command'] - data = expr.get('data') + data = expr.get('data', {}) rets = expr.get('returns') gen = expr.get('gen', True) success_response = expr.get('success-response', True) - if isinstance(data, OrderedDict): + if isinstance(data, dict): data = self._make_implicit_object_type( name, info, 'arg', self._make_members(data, info)) if isinstance(rets, list):
@@ -1364,8 +1364,8 @@ class QAPISchema(object): def _def_event(self, expr, info): name = expr['event'] - data = expr.get('data') - if isinstance(data, OrderedDict): + data = expr.get('data', {}) + if isinstance(data, dict): data = self._make_implicit_object_type( name, info, 'arg', self._make_members(data, info)) self._def_entity(QAPISchemaEvent(name, info, data))
@@ -1612,8 +1612,7 @@ extern const char *const %(c_name)s_lookup[]; def gen_params(arg_type, extra): - if not arg_type: - return extra + assert arg_type assert not arg_type.variants ret = '' sep = ''
tests/qapi-schema/event-case.out +1 -1
@@ -1,4 +1,4 @@ object :empty enum QType ['none', 'qnull', 'qint', 'qstring', 'qdict', 'qlist', 'qfloat', 'qbool'] prefix QTYPE -event oops None +event oops :empty
tests/qapi-schema/flat-union-empty.out +1 -0
@@ -1,5 +1,6 @@ object :empty object Base + base :empty member type: Empty optional=False enum Empty [] enum QType ['none', 'qnull', 'qint', 'qstring', 'qdict', 'qlist', 'qfloat', 'qbool']
tests/qapi-schema/ident-with-escape.out +1 -0
@@ -1,5 +1,6 @@ object :empty object :obj-fooA-arg + base :empty member bar1: str optional=False enum QType ['none', 'qnull', 'qint', 'qstring', 'qdict', 'qlist', 'qfloat', 'qbool'] prefix QTYPE
tests/qapi-schema/indented-expr.out +2 -2
@@ -1,7 +1,7 @@ object :empty enum QType ['none', 'qnull', 'qint', 'qstring', 'qdict', 'qlist', 'qfloat', 'qbool'] prefix QTYPE -command eins None -> None +command eins :empty -> None gen=True success_response=True -command zwei None -> None +command zwei :empty -> None gen=True success_response=True
tests/qapi-schema/qapi-schema-test.out +42 -3
193 lines not on this page · raw message
tests/qapi-schema/union-clash-data.out +2 -0
@@ -1,9 +1,11 @@ object :empty object :obj-int-wrapper + base :empty member data: int optional=False enum QType ['none', 'qnull', 'qint', 'qstring', 'qdict', 'qlist', 'qfloat', 'qbool'] prefix QTYPE object TestUnion + base :empty member type: TestUnionKind optional=False case data: :obj-int-wrapper enum TestUnionKind ['data']
tests/qapi-schema/union-empty.out +1 -0
@@ -2,5 +2,6 @@ object :empty enum QType ['none', 'qnull', 'qint', 'qstring', 'qdict', 'qlist', 'qfloat', 'qbool'] prefix QTYPE object Union + base :empty member type: UnionKind optional=False enum UnionKind []
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 30/37] qapi: Canonicalize missing object to :empty
Quoted 11 lines · Eric Blake
Now that we elide unnecessary visits of empty types, we can start using the special ':empty' type in more places. By using the empty type as the base class of every explicit struct or union, and as the default data for any command or event, we can simplify later logic in qapi-{visit,commands,event} by merely checking whether the type is empty, without also having to worry whether a type was even supplied.
Note that
gen_object()in qapi-types still has to check for a base, because it is also called for alternates (which have no base).
What about the one in gen_visit_struct()?
if (base and not base.is_empty()) or members:
ret += mcgen('''
visit_type_%(c_name)s_fields(v, obj, &err);
''',
c_name=c_name(name))Quoted 29 lines
No change to generated code.
Signed-off-by Eric Blake <[email protected]>---
v9: squash in more related changes
v8: rebase to earlier changes
v7: rebase to earlier changes
v6: new patch--- scripts/qapi-commands.py | 17 +++++++------ scripts/qapi-event.py | 5 ++-- scripts/qapi-types.py | 4 +-- scripts/qapi-visit.py | 12 +++++---- scripts/qapi.py | 25 +++++++++--------- tests/qapi-schema/event-case.out | 2 +- tests/qapi-schema/flat-union-empty.out | 1 + tests/qapi-schema/ident-with-escape.out | 1 + tests/qapi-schema/indented-expr.out | 4 +-- tests/qapi-schema/qapi-schema-test.out | 45 ++++++++++++++++++++++++++++++--- tests/qapi-schema/union-clash-data.out | 2 ++ tests/qapi-schema/union-empty.out | 1 + 12 files changed, 83 insertions(+), 36 deletions(-)scripts/qapi-commands.py +0
-0
scripts/qapi-commands.py def gen_call(name, arg_type, ret_type): · line 33
Quoted 10 lines
scripts/qapi-commands.py +2
-5@@ -29,11 +29,11 @@ def gen_call(name, arg_type, ret_type): ret = '' argstr = '' - if arg_type: - for memb in arg_type.members: - if memb.optional: - argstr += 'has_%s, ' % c_name(memb.name) - argstr += '%s, ' % c_name(memb.name) + assert arg_type + for memb in arg_type.members:
The assertion doesn't buy us much. If arg_type is true, but of the wrong type, the assertion holds, and arg_type.members throws an error. If it false, then arg_type.members's error is just as useful as an AssertionError.
More of the same below.
Quoted 62 lines
scripts/qapi-commands.py +7
-3+ if memb.optional: + argstr += 'has_%s, ' % c_name(memb.name) + argstr += '%s, ' % c_name(memb.name) lhs = '' if ret_type:@@ -65,7 +65,8 @@ def gen_marshal_vars(arg_type, ret_type): ''', c_type=ret_type.c_type()) - if arg_type and not arg_type.is_empty(): + assert arg_type + if not arg_type.is_empty(): ret += mcgen(''' QmpInputVisitor *qiv = qmp_input_visitor_new_strict(QOBJECT(args)); QapiDeallocVisitor *qdv;@@ -97,7 +98,7 @@ def gen_marshal_vars(arg_type, ret_type): def gen_marshal_input_visit(arg_type, dealloc=False): ret = '' - if not arg_type or arg_type.is_empty(): + if arg_type.is_empty(): return ret if dealloc:@@ -177,7 +178,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 not arg_type.is_empty()) or ret_type: + if not arg_type.is_empty() or ret_type: ret += mcgen(''' out:scripts/qapi-event.py +3
-2@@ -39,7 +39,8 @@ def gen_event_send(name, arg_type): ''', proto=gen_event_send_proto(name, arg_type)) - if arg_type and not arg_type.is_empty(): + assert arg_type + if not arg_type.is_empty(): ret += mcgen(''' QmpOutputVisitor *qov; Visitor *v;@@ -88,7 +89,7 @@ out_obj: ''', c_enum=c_enum_const(event_enum_name, name)) - if arg_type and not arg_type.is_empty(): + if not arg_type.is_empty(): ret += mcgen(''' out: qmp_output_visitor_cleanup(qov);scripts/qapi-types.py +0
-0
scripts/qapi-types.py struct %(c_name)s { · line 64
Quoted 8 lines
scripts/qapi-types.py +1
-1@@ -58,7 +58,7 @@ struct %(c_name)s { ''', c_name=c_name(name)) - if base: + if base and not base.is_empty(): ret += mcgen(''' /* Members inherited from %(c_name)s: */ ''',
Here, you go straight from X to X and not X.is_empty(). Elsewhere, you take two steps: one patch goes from X to X and X.is_empty(), changing ouput when X is an empty struct, and this one to just X.is_empty(), without changing output.
I understand you need to keep checking base because alternates have none.
I suspect that if base is empty, this hunk changes output, unlike the other ones, namely the comments
/* Members inherited from %(c_name)s: */
/* Own members: */go away.
If that's true, it should either be a separate patch, or be mentioned in the commit message. A test case would be nice.
scripts/qapi-types.py class QAPISchemaGenTypeVisitor(QAPISchemaVisitor): · line 225
Quoted 6 lines
scripts/qapi-types.py +1
-1@@ -222,7 +222,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 not base.is_implicit():
Why .is_implicit() instead of .is_empty() here?
Quoted 31 lines
scripts/qapi-types.py +0
-0self.decl += gen_upcast(name, base) self._gen_type_cleanup(name)scripts/qapi-visit.py +4
-3@@ -74,10 +74,11 @@ static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * def gen_visit_struct_fields(name, base, members): ret = '' - if (not base or base.is_empty()) and not members: + assert base + if base.is_empty() and not members: return ret - if base and not base.is_empty(): + if not base.is_empty(): ret += gen_visit_fields_decl(base) struct_fields_seen.add(name)@@ -90,7 +91,7 @@ static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s **obj, Error **e ''', c_name=c_name(name)) - if base and not base.is_empty(): + if not base.is_empty(): ret += mcgen(''' visit_type_%(c_type)s_fields(v, (%(c_type)s **)obj, &err); ''',
scripts/qapi-visit.py out: · line 252
Quoted 7 lines
scripts/qapi-visit.py +2
-1@@ -246,7 +247,8 @@ out: def gen_visit_union(name, base, variants): ret = '' - if base: + assert base + if not base.is_empty(): ret += gen_visit_fields_decl(base)
Here, you go straight from X to X.is_empty(). Elsewhere, you take two
steps: one patch goes from X to X and X.is_empty(), changing ouput when X is an empty struct, and this one to just X.is_empty(), without changing output.
The first step is actually PATCH 29: it changes gen_visit_fields_decl() not to generate anything for an empty type.
I think it should also make this call unconditional.
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 275
Quoted 8 lines
scripts/qapi-visit.py +1
-1for var in variants.variants:@@ -270,7 +272,7 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error ''', c_name=c_name(name)) - if base: + if not base.is_empty():
Another one, let's see what this does.
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 278
Quoted 3 lines
scripts/qapi-visit.py +0
-0ret += mcgen(''' visit_type_%(c_name)s_fields(v, (%(c_name)s **)obj, &err); ''',
c_name=base.c_name())
else:
ret += mcgen('''
visit_type_%(c_type)s(v, "%(name)s", &(*obj)->%(c_name)s, &err); ''',
c_type=variants.tag_member.type.c_name(), c_name=c_name(variants.tag_member.name), name=variants.tag_member.name)
The condition is really flat union (the common members are in the base) vs. simple union (the common member is tag_member). If flat union, we generate the base visit, else the tag_member visit. Together, this generates the visit of common members.
Your change breaks the condition: now simple unions have a base, too. You fix it up to test for empty base instead. Okay.
Quoted 6 lines
scripts/qapi.py +0
-0@@ -922,11 +922,11 @@ class QAPISchemaArrayType(QAPISchemaType):
scripts/qapi.py class QAPISchemaArrayType(QAPISchemaType): · line 929
Quoted 10 lines
scripts/qapi.py +3
-3class QAPISchemaObjectType(QAPISchemaType): def __init__(self, name, info, base, local_members, variants): - # struct has local_members, optional base, and no variants + # struct has local_members, base, and no variants # flat union has base, variants, and no local_members - # simple union has local_members, variants, and no base + # simple union has local_members, variants, and base of :empty QAPISchemaType.__init__(self, name, info) - assert base is None or isinstance(base, str) + assert isinstance(base, str) or name == ':empty'
No longer tight: if name == ':empty', base must be None, else it must be a str.
Quoted 36 lines
scripts/qapi.py +4
-4for m in local_members: assert isinstance(m, QAPISchemaObjectTypeMember) m.set_owner(name)@@ -1264,11 +1264,11 @@ class QAPISchema(object): def _make_implicit_object_type(self, name, info, role, members): if not members: - return None + return ':empty' # See also QAPISchemaObjectTypeMember._pretty_owner() name = ':obj-%s-%s' % (name, role) if not self.lookup_entity(name, QAPISchemaObjectType): - self._def_entity(QAPISchemaObjectType(name, info, None, + self._def_entity(QAPISchemaObjectType(name, info, ':empty', members, None)) return name@@ -1295,7 +1295,7 @@ class QAPISchema(object): def _def_struct_type(self, expr, info): name = expr['struct'] - base = expr.get('base') + base = expr.get('base', ':empty') data = expr['data'] self._def_entity(QAPISchemaObjectType(name, info, base, self._make_members(data, info),@@ -1315,7 +1315,7 @@ class QAPISchema(object): def _def_union_type(self, expr, info): name = expr['union'] data = expr['data'] - base = expr.get('base') + base = expr.get('base', ':empty') tag_name = expr.get('discriminator') tag_member = None if tag_name:
scripts/qapi.py class QAPISchema(object): · line 1352
Quoted 5 lines
scripts/qapi.py +1
-1@@ -1349,11 +1349,11 @@ class QAPISchema(object): def _def_command(self, expr, info): name = expr['command'] - data = expr.get('data') + data = expr.get('data', {})
expr.get('data', {}) returns a str or OrderedDict if expr has the key, else a dict. Unclean.
scripts/qapi.py class QAPISchema(object): · line 1356
Quoted 5 lines
scripts/qapi.py +1
-1rets = expr.get('returns') gen = expr.get('gen', True) success_response = expr.get('success-response', True) - if isinstance(data, OrderedDict): + if isinstance(data, dict):
The test works since OrderedDict is also a dict.
scripts/qapi.py class QAPISchema(object): · line 1358
Quoted 2 lines
scripts/qapi.py +0
-0data = self._make_implicit_object_type( name, info, 'arg', self._make_members(data, info))
I remember screwing up dict vs. OrderedDict once, and it failed when some code really expected an OrderedDict. _make_members() looks like it's okay with dict, but why risk it?
Why not simply data = expr.get('data', ':empty') ?
scripts/qapi.py class QAPISchema(object): · line 1371
Quoted 12 lines
scripts/qapi.py +2
-2if isinstance(rets, list):@@ -1364,8 +1364,8 @@ class QAPISchema(object): def _def_event(self, expr, info): name = expr['event'] - data = expr.get('data') - if isinstance(data, OrderedDict): + data = expr.get('data', {}) + if isinstance(data, dict): data = self._make_implicit_object_type( name, info, 'arg', self._make_members(data, info)) self._def_entity(QAPISchemaEvent(name, info, data))
Same here.
scripts/qapi.py extern const char *const %(c_name)s_lookup[]; · line 1618
Quoted 10 lines
scripts/qapi.py +1
-2@@ -1612,8 +1612,7 @@ extern const char *const %(c_name)s_lookup[]; def gen_params(arg_type, extra): - if not arg_type: - return extra + assert arg_type assert not arg_type.variants ret = '' sep = ''
[Test output diffs snipped...]
Overall, a somewhat scary change, because all users of base need to be checked. The ones you actually changed are easy enough to see for a reviewer. Missed ones aren't. Fortunately, we got a decent test suite.
Not sure this is worth the churn by itself, but let me read further to see it in more context.
Re: [Qemu-devel] [PATCH v9 30/37] qapi: Canonicalize missing object to :empty
Quoted 14 lines · Markus Armbruster
Quoted 11 lines · Eric Blake
Now that we elide unnecessary visits of empty types, we can start using the special ':empty' type in more places. By using the empty type as the base class of every explicit struct or union, and as the default data for any command or event, we can simplify later logic in qapi-{visit,commands,event} by merely checking whether the type is empty, without also having to worry whether a type was even supplied.
Note that
gen_object()in qapi-types still has to check for a base, because it is also called for alternates (which have no base).
Quoted 31 lines
What about the one in
gen_visit_struct()?if (base and not base.is_empty()) or members: ret += mcgen(''' visit_type_%(c_name)s_fields(v, obj, &err); ''', c_name=c_name(name))Quoted 23 lines
No change to generated code.
Signed-off-by Eric Blake <[email protected]>---
v9: squash in more related changes
v8: rebase to earlier changes
v7: rebase to earlier changes
v6: new patch--- scripts/qapi-commands.py | 17 +++++++------ scripts/qapi-event.py | 5 ++-- scripts/qapi-types.py | 4 +-- scripts/qapi-visit.py | 12 +++++---- scripts/qapi.py | 25 +++++++++--------- tests/qapi-schema/event-case.out | 2 +- tests/qapi-schema/flat-union-empty.out | 1 + tests/qapi-schema/ident-with-escape.out | 1 + tests/qapi-schema/indented-expr.out | 4 +-- tests/qapi-schema/qapi-schema-test.out | 45 ++++++++++++++++++++++++++++++--- tests/qapi-schema/union-clash-data.out | 2 ++ tests/qapi-schema/union-empty.out | 1 + 12 files changed, 83 insertions(+), 36 deletions(-)
Missing: update to qapi-introspect.py. At least the expressions like
arg_type or self._schema.the_empty_object_type
need updating.
I got stuck in reviewing PATCH 31. The result is probably fine, but the patch itself is impenetrable for me. I'm playing with the code to see whether I can turn that into a constructive remark.
Re: [Qemu-devel] [PATCH v9 30/37] qapi: Canonicalize missing object to :empty
Quoted 11 lines · Markus Armbruster
Quoted 9 lines · Markus Armbruster
Quoted 7 lines · Eric Blake
Now that we elide unnecessary visits of empty types, we can start using the special ':empty' type in more places. By using the empty type as the base class of every explicit struct or union, and as the default data for any command or event, we can simplify later logic in qapi-{visit,commands,event} by merely checking whether the type is empty, without also having to worry whether a type was even supplied.
You rewrite a command's arg_type from None to ':empty', bit not its ret_type. Deepens the assymmetry between the two.
Quoted 36 lines
Quoted 4 lines
Quoted 3 lines
Note that
gen_object()in qapi-types still has to check for a base, because it is also called for alternates (which have no base).Quoted 31 lines
What about the one in
gen_visit_struct()?if (base and not base.is_empty()) or members: ret += mcgen(''' visit_type_%(c_name)s_fields(v, obj, &err); ''', c_name=c_name(name))Quoted 23 lines
No change to generated code.
Signed-off-by Eric Blake <[email protected]>---
v9: squash in more related changes
v8: rebase to earlier changes
v7: rebase to earlier changes
v6: new patch--- scripts/qapi-commands.py | 17 +++++++------ scripts/qapi-event.py | 5 ++-- scripts/qapi-types.py | 4 +-- scripts/qapi-visit.py | 12 +++++---- scripts/qapi.py | 25 +++++++++--------- tests/qapi-schema/event-case.out | 2 +- tests/qapi-schema/flat-union-empty.out | 1 + tests/qapi-schema/ident-with-escape.out | 1 + tests/qapi-schema/indented-expr.out | 4 +-- tests/qapi-schema/qapi-schema-test.out | 45 ++++++++++++++++++++++++++++++--- tests/qapi-schema/union-clash-data.out | 2 ++ tests/qapi-schema/union-empty.out | 1 + 12 files changed, 83 insertions(+), 36 deletions(-)
Quoted 5 lines
Missing: update to
qapi-introspect.py. At least the expressions like
arg_typeor self._schema.the_empty_object_typeneed updating.
But so far not the ret_type or self._schema.the_empty_object_type.
[...]
PATCH v9 31/37 qapi-visit: Unify struct and union visit
In reply to Eric BlakeWe are finally at the point where gen_visit_struct() and gen_visit_union() can be unified to a generic gen_visit_object().
The generated code for structs and for flat unions is unchanged. For simple unions, a new visit_type_FOO_fields() is created, wrapping the visit of the non-variant tag field:
|+static void visit_type_ChardevBackend_fields(Visitor *v, ChardevBackend **obj, Error **errp)
|+{
|+ Error *err = NULL;
|+
|+ visit_type_ChardevBackendKind(v, "type", &(*obj)->type, &err);
|+ if (err) {
|+ goto out;
|+ }
|+
|+out:
|+ error_propagate(errp, err);
|+}
|+
| void visit_type_ChardevBackend(Visitor *v, const char *name, ChardevBackend **obj, Error **errp)
| {
| Error *err = NULL;
|@@ -2319,7 +2332,7 @@ void visit_type_ChardevBackend(Visitor *
| if (!*obj) {
| goto out_obj;
| }
|- visit_type_ChardevBackendKind(v, "type", &(*obj)->type, &err);
|+ visit_type_ChardevBackend_fields(v, obj, &err);
| if (err) {---
v9: no change
v8: rebase to 'name' motion
v7: rebase to earlier changes
v6: new patch
--- scripts/qapi-visit.py | 133 +++++++++++++++++++------------------------------- 1 file changed, 51 insertions(+), 82 deletions(-)
scripts/qapi-visit.py +51 -82
@@ -109,46 +109,6 @@ out: return ret -def gen_visit_struct(name, base, members): - ret = gen_visit_struct_fields(name, base, members) - - # FIXME: if *obj is NULL on entry, and visit_start_struct() assigns to - # *obj, but then visit_type_FOO_fields() fails, we should clean up *obj - # rather than leaving it non-NULL. As currently written, the caller must - # call qapi_free_FOO() to avoid a memory leak of the partial FOO. - ret += mcgen(''' - -void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) -{ - Error *err = NULL; - - visit_start_struct(v, name, (void **)obj, sizeof(%(c_name)s), &err); - if (err) { - goto out; - } - if (!*obj) { - goto out_obj; - } -''', - name=name, c_name=c_name(name)) - if (base and not base.is_empty()) or members: - ret += mcgen(''' - visit_type_%(c_name)s_fields(v, obj, &err); -''', - c_name=c_name(name)) - ret += mcgen(''' -out_obj: - error_propagate(errp, err); - err = NULL; - visit_end_struct(v, &err); -out: - error_propagate(errp, err); -} -''') - - return ret - - def gen_visit_list(name, element_type): # FIXME: if *obj is NULL on entry, and the first visit_next_list() # assigns to *obj, while a later one fails, we should clean up *obj
@@ -244,18 +204,24 @@ out: return ret -def gen_visit_union(name, base, variants): +def gen_visit_object(name, base, members, variants): ret = '' assert base if not base.is_empty(): ret += gen_visit_fields_decl(base) + if members: + ret += gen_visit_struct_fields(name, base, members) + 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_implicit_struct(var.type) - 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_implicit_struct(var.type) - + # FIXME: if *obj is NULL on entry, and visit_start_struct() assigns to + # *obj, but then visit_type_FOO_fields() fails, we should clean up *obj + # rather than leaving it non-NULL. As currently written, the caller must + # call qapi_free_FOO() to avoid a memory leak of the partial FOO. ret += mcgen(''' void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp)
@@ -272,61 +238,71 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error ''', c_name=c_name(name)) - if not base.is_empty(): + if not base.is_empty() or members: + if members: + type_name = c_name(name) + cast = '' + else: + type_name = base.c_name() + cast = '(%s **)' % type_name ret += mcgen(''' - visit_type_%(c_name)s_fields(v, (%(c_name)s **)obj, &err); + visit_type_%(c_name)s_fields(v, %(cast)sobj, &err); ''', - c_name=base.c_name()) - else: + c_name=type_name, cast=cast) + if variants: + ret += gen_err_check(label='out_obj') + + if variants: ret += mcgen(''' - visit_type_%(c_type)s(v, "%(name)s", &(*obj)->%(c_name)s, &err); -''', - c_type=variants.tag_member.type.c_name(), - c_name=c_name(variants.tag_member.name), - name=variants.tag_member.name) - ret += gen_err_check(label='out_obj') - ret += mcgen(''' if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) { goto out_obj; } switch ((*obj)->%(c_name)s) { ''', - c_name=c_name(variants.tag_member.name)) + 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(''' + 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)) - if simple_union_type: - ret += mcgen(''' + case=c_enum_const(variants.tag_member.type.name, + var.name)) + 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)) - elif not var.type.is_empty(): - ret += mcgen(''' + c_type=simple_union_type.c_name(), + c_name=c_name(var.name)) + elif not var.type.is_empty(): + ret += mcgen(''' visit_type_implicit_%(c_type)s(v, &(*obj)->u.%(c_name)s, &err); ''', - c_type=var.type.c_name(), - c_name=c_name(var.name)) - ret += mcgen(''' + c_type=var.type.c_name(), + c_name=c_name(var.name)) + ret += mcgen(''' break; ''') - ret += mcgen(''' + ret += mcgen(''' default: abort(); } +''') + + ret += mcgen(''' out_obj: +''') + if variants: + ret += mcgen(''' error_propagate(errp, err); err = NULL; if (*obj) { visit_end_union(v, !!(*obj)->u.data, &err); } +''') + ret += mcgen(''' error_propagate(errp, err); err = NULL; visit_end_struct(v, &err);
@@ -387,14 +363,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor): def visit_object_type(self, name, info, base, members, variants): self.decl += gen_visit_decl(name) - if variants: - if members: - # Members other than variants.tag_member not implemented - assert len(members) == 1 - assert members[0] == variants.tag_member - self.defn += gen_visit_union(name, base, variants) - else: - self.defn += gen_visit_struct(name, base, members) + self.defn += gen_visit_object(name, base, members, variants) def visit_alternate_type(self, name, info, variants): self.decl += gen_visit_decl(name)
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 31/37] qapi-visit: Unify struct and union visit
I'm sending this out even though it's unfinished. It's probably more useful for documenting my difficulties and confusion than for improving the code.
Quoted 95 lines · Eric Blake
We are finally at the point where
gen_visit_struct()andgen_visit_union()can be unified to a genericgen_visit_object().The generated code for structs and for flat unions is unchanged. For simple unions, a new
visit_type_FOO_fields()is created, wrapping the visit of the non-variant tag field:|+static void visit_type_ChardevBackend_fields(Visitor *v, ChardevBackend **obj, Error **errp) |+{ |+ Error *err = NULL; |+ |+ visit_type_ChardevBackendKind(v, "type", &(*obj)->type, &err); |+ if (err) { |+ goto out; |+ } |+ |+out: |+ error_propagate(errp, err); |+} |+ | void visit_type_ChardevBackend(Visitor *v, const char *name, ChardevBackend **obj, Error **errp) | { | Error *err = NULL; |@@ -2319,7 +2332,7 @@ void visit_type_ChardevBackend(Visitor * | if (!*obj) { | goto out_obj; | } |- visit_type_ChardevBackendKind(v, "type", &(*obj)->type, &err); |+ visit_type_ChardevBackend_fields(v, obj, &err); | if (err) {Signed-off-by Eric Blake <[email protected]>Reviewed-by Marc-André Lureau <[email protected]>---
v9: no change
v8: rebase to 'name' motion
v7: rebase to earlier changes
v6: new patch--- scripts/qapi-visit.py | 133 +++++++++++++++++++------------------------------- 1 file changed, 51 insertions(+), 82 deletions(-)scripts/qapi-visit.py +0
-40@@ -109,46 +109,6 @@ out: return ret -def gen_visit_struct(name, base, members): - ret = gen_visit_struct_fields(name, base, members) - - # FIXME: if *obj is NULL on entry, and visit_start_struct() assigns to - # *obj, but then visit_type_FOO_fields() fails, we should clean up *obj - # rather than leaving it non-NULL. As currently written, the caller must - # call qapi_free_FOO() to avoid a memory leak of the partial FOO. - ret += mcgen(''' - -void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) -{ - Error *err = NULL; - - visit_start_struct(v, name, (void **)obj, sizeof(%(c_name)s), &err); - if (err) { - goto out; - } - if (!*obj) { - goto out_obj; - } -''', - name=name, c_name=c_name(name)) - if (base and not base.is_empty()) or members: - ret += mcgen(''' - visit_type_%(c_name)s_fields(v, obj, &err); -''', - c_name=c_name(name)) - ret += mcgen(''' -out_obj: - error_propagate(errp, err); - err = NULL; - visit_end_struct(v, &err); -out: - error_propagate(errp, err); -} -''') - - return ret - - def gen_visit_list(name, element_type): # FIXME: if *obj is NULL on entry, and the first visit_next_list() # assigns to *obj, while a later one fails, we should clean up *obj
scripts/qapi-visit.py out: · line 205
Quoted 2 lines
scripts/qapi-visit.py +0
-0@@ -244,18 +204,24 @@ out: return ret
You're merging gen_visit_struct() and gen_visit_union() into gen_visit_object(). Need to review both the change from gen_visit_struct() to gen_visit_object(), and from gen_visit_union() to gen_visit_object(). Diff shows the latter, but not the former. A manual diff of the old gen_visit_struct() and new gen_visit_union() doesn't come out helpful.
Recap differences between structs, flat unions and simple unions:
base members variants
struct may be empty may be empty no
flat union non-empty empty yes
simple union empty just the tag yesscripts/qapi-visit.py out: · line 214
Quoted 10 lines
scripts/qapi-visit.py +3
-1-def gen_visit_union(name, base, variants): +def gen_visit_object(name, base, members, variants): ret = '' assert base if not base.is_empty(): ret += gen_visit_fields_decl(base) + if members: + ret += gen_visit_struct_fields(name, base, members)
Flat unions have no members: the new code does nothing.
Simple unions have a single member: we now generate a visit_type_UNION_fields() for it.
Respective part of gen_visit_struct():
ret = gen_visit_struct_fields(name, base, members)
It looks like you add a gen_visit_fields_decl() when the struct's base is non-empty. You actually don't, because the additional one in gen_visit_object() suppresses the one in gen_visit_struct_fields(). I think.
scripts/qapi-visit.py out: · line 258
Quoted 11 lines
scripts/qapi-visit.py +5
-5+ 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_implicit_struct(var.type) - 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_implicit_struct(var.type) -
Unions always have variants: no change.
Struct's don't: no change.
scripts/qapi-visit.py out: · line 224
Quoted 4 lines
scripts/qapi-visit.py +4
-0+ # FIXME: if *obj is NULL on entry, and visit_start_struct() assigns to + # *obj, but then visit_type_FOO_fields() fails, we should clean up *obj + # rather than leaving it non-NULL. As currently written, the caller must + # call qapi_free_FOO() to avoid a memory leak of the partial FOO.
Comment inherited from gen_visit_struct(). Does it apply to unions as well?
Quoted 23 lines
scripts/qapi-visit.py +10
-4ret += mcgen(''' void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp)@@ -272,61 +238,71 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error ''', c_name=c_name(name)) - if not base.is_empty(): + if not base.is_empty() or members: + if members: + type_name = c_name(name) + cast = '' + else: + type_name = base.c_name() + cast = '(%s **)' % type_name ret += mcgen(''' - visit_type_%(c_name)s_fields(v, (%(c_name)s **)obj, &err); + visit_type_%(c_name)s_fields(v, %(cast)sobj, &err); ''', - c_name=base.c_name()) - else: + c_name=type_name, cast=cast) + if variants:
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 287
Quoted 10 lines
scripts/qapi-visit.py +3
-6+ ret += gen_err_check(label='out_obj') + + if variants: ret += mcgen(''' - visit_type_%(c_type)s(v, "%(name)s", &(*obj)->%(c_name)s, &err); -''', - c_type=variants.tag_member.type.c_name(), - c_name=c_name(variants.tag_member.name), - name=variants.tag_member.name) - ret += gen_err_check(label='out_obj')
Around here, the diff becomes too hard to read for me.
Please have a look at my "[PATCH 0/3] qapi-visit: Unify struct and union visit".
Quoted 86 lines
scripts/qapi-visit.py +26
-26- ret += mcgen(''' if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) { goto out_obj; } switch ((*obj)->%(c_name)s) { ''', - c_name=c_name(variants.tag_member.name)) + 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(''' + 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)) - if simple_union_type: - ret += mcgen(''' + case=c_enum_const(variants.tag_member.type.name, + var.name)) + 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)) - elif not var.type.is_empty(): - ret += mcgen(''' + c_type=simple_union_type.c_name(), + c_name=c_name(var.name)) + elif not var.type.is_empty(): + ret += mcgen(''' visit_type_implicit_%(c_type)s(v, &(*obj)->u.%(c_name)s, &err); ''', - c_type=var.type.c_name(), - c_name=c_name(var.name)) - ret += mcgen(''' + c_type=var.type.c_name(), + c_name=c_name(var.name)) + ret += mcgen(''' break; ''') - ret += mcgen(''' + ret += mcgen(''' default: abort(); } +''') + + ret += mcgen(''' out_obj: +''') + if variants: + ret += mcgen(''' error_propagate(errp, err); err = NULL; if (*obj) { visit_end_union(v, !!(*obj)->u.data, &err); } +''') + ret += mcgen(''' error_propagate(errp, err); err = NULL; visit_end_struct(v, &err);@@ -387,14 +363,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor): def visit_object_type(self, name, info, base, members, variants): self.decl += gen_visit_decl(name) - if variants: - if members: - # Members other than variants.tag_member not implemented - assert len(members) == 1 - assert members[0] == variants.tag_member - self.defn += gen_visit_union(name, base, variants) - else: - self.defn += gen_visit_struct(name, base, members) + self.defn += gen_visit_object(name, base, members, variants) def visit_alternate_type(self, name, info, variants): self.decl += gen_visit_decl(name)
PATCH v9 32/37 qapi: Rework deallocation of partial struct
In reply to Eric BlakeCommit cee2dedb noticed that if you have a partial flat union (such as if an input parse failed due to a missing discriminator), calling the dealloc visitor could result in trying to dereference the NULL pointer. But the fix it proposed requires the use of a 'data' member in the union, which may or may not be the same size as other branches of the union (consider a 32-bit platform where one of the branches is an int64), so it feels fairly dirty. A better fix is to tweak all of the generated visit_type_implicit_FOO() functions to avoid dereferencing NULL in the first place, by not visiting the fields if the struct pointer itself is not present, at which point we no longer even need visit_start_union(). And no one was implementing visit_end_union() callbacks.
While rewriting the code, use patterns that are closer to what is used elsewhere in the generated visitors, by using 'goto' to cleanup labels rather than putting followup code under 'if' conditions. The change keeps the contract that any successful use of visit_start_implicit_struct() will be paired with a matching visit_end_implicit_struct(), even if intermediate processing is skipped. We are safe in checking *obj alone, as as the contract of visit_start_implicit_struct() requires a non-NULL obj.
As an example of the changes to generated code:
|@@ -1331,10 +1331,16 @@ static void visit_type_implicit_Blockdev
| Error *err = NULL;
|
| visit_start_implicit_struct(v, (void **)obj, sizeof(BlockdevOptionsArchipelago), &err);
|- if (!err) {
|- visit_type_BlockdevOptionsArchipelago_fields(v, obj, errp);
|- visit_end_implicit_struct(v);
|+ if (err) {
|+ goto out;
|+ }
|+ if (!*obj) {
|+ goto out_obj;
| }
|+ visit_type_BlockdevOptionsArchipelago_fields(v, obj, &err);
|+out_obj:
|+ visit_end_implicit_struct(v);
|+out:
| error_propagate(errp, err);
| }
...
|@@ -1479,9 +1539,6 @@ void visit_type_BlockdevOptions(Visitor
| if (err) {
| goto out_obj;
| }
|- if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) {
|- goto out_obj;
|- }
| switch ((*obj)->driver) {
| case BLOCKDEV_DRIVER_ARCHIPELAGO:
| visit_type_implicit_BlockdevOptionsArchipelago(v, &(*obj)->u.archipelago, &err);
|@@ -1570,11 +1627,6 @@ void visit_type_BlockdevOptions(Visitor
| out_obj:
| error_propagate(errp, err);
| err = NULL;
|- if (*obj) {
|- visit_end_union(v, !!(*obj)->u.data, &err);
|- }
|- error_propagate(errp, err);
|- err = NULL;
| visit_end_struct(v, &err);---
v9: no change
v8: rebase to 'name' motion
v7: rebase to earlier context changes, simplify 'obj && !*obj' condition based on contract
v6: rebase due to deferring 7/46, and gen_err_check() improvements; rewrite gen_visit_implicit_struct() more like other patterns
--- include/qapi/visitor-impl.h | 5 ----- include/qapi/visitor.h | 12 ------------ qapi/qapi-dealloc-visitor.c | 26 -------------------------- qapi/qapi-visit-core.c | 15 --------------- scripts/qapi-visit.py | 25 +++++++++---------------- 5 files changed, 9 insertions(+), 74 deletions(-)
include/qapi/visitor-impl.h +0 -5
@@ -81,11 +81,6 @@ struct Visitor/* May be NULL; most useful for input visitors. */ void (*optional)(Visitor *v,const char *name,bool *present); - -/* FIXME - needs to be removed */ -bool (*start_union)(Visitor *v,bool data_present,Error **errp); -/* FIXME - needs to be removed */ -void (*end_union)(Visitor *v,bool data_present,Error **errp); };/**
include/qapi/visitor.h +0 -12
@@ -274,16 +274,4 @@ void visit_type_any(Visitor *v, const char *name, QObject **obj, Error **errp);*/ void visit_type_null (Visitor *v,const char *name,Error **errp); -/** -* Mark the start of visiting the branches of a union. Return true if -* @data_present. -* FIXME: Should not be needed -*/ -bool visit_start_union (Visitor *v,bool data_present,Error **errp); -/** -* Mark the end of union branches, after visit_start_union(). -* FIXME: Should not be needed -*/ -void visit_end_union (Visitor *v,bool data_present,Error **errp); -#endif
qapi/qapi-dealloc-visitor.c +0 -26
@@ -171,31 +171,6 @@ static void qapi_dealloc_type_enum(Visitor *v, const char *name, int *obj, { } -/* If there's no data present, the dealloc visitor has nothing to free. -* Thus, indicate to visitor code that the subsequent union fields can -* be skipped. This is not an error condition, since the cleanup of the -* rest of an object can continue unhindered, so leave errp unset in -* these cases. -* -* NOTE: In cases where we're attempting to deallocate an object that -* may have missing fields, the field indicating the union type may -* be missing. In such a case, it's possible we don't have enough -* information to differentiate data_present == false from a case where -* data *is* present but happens to be a scalar with a value of 0. -* This is okay, since in the case of the dealloc visitor there's no -* work that needs to done in either situation. -* -* The current inability in QAPI code to more thoroughly verify a union -* type in such cases will likely need to be addressed if we wish to -* implement this interface for other types of visitors in the future, -* however. -*/ -static bool qapi_dealloc_start_union (Visitor *v,bool data_present, -Error **errp) -{ -return data_present; -} -Visitor *qapi_dealloc_get_visitor (QapiDeallocVisitor *v) {return &v->visitor;
@@ -227,7 +202,6 @@ QapiDeallocVisitor *qapi_dealloc_visitor_new(void) v->visitor.type_number = qapi_dealloc_type_number; v->visitor.type_any = qapi_dealloc_type_anything; v->visitor.type_null = qapi_dealloc_type_null; - v->visitor.start_union = qapi_dealloc_start_union;QTAILQ_INIT (&v->stack);
qapi/qapi-visit-core.c +0 -15
@@ -76,21 +76,6 @@ void visit_end_list(Visitor *v) v->end_list (v); } -bool visit_start_union (Visitor *v,bool data_present,Error **errp) -{ -if (v->start_union) { -return v->start_union (v, data_present, errp); - } -return true; -} - -void visit_end_union (Visitor *v,bool data_present,Error **errp) -{ -if (v->end_union) { - v->end_union (v, data_present, errp); - } -} -bool visit_optional (Visitor *v,const char *name,bool *present) {if (v->optional) {
scripts/qapi-visit.py +9 -16
@@ -60,10 +60,16 @@ static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * Error *err = NULL; visit_start_implicit_struct(v, (void **)obj, sizeof(%(c_type)s), &err); - if (!err) { - visit_type_%(c_type)s_fields(v, obj, errp); - visit_end_implicit_struct(v); + if (err) { + goto out; } + if (!*obj) { + goto out_obj; + } + visit_type_%(c_type)s_fields(v, obj, &err); +out_obj: + visit_end_implicit_struct(v); +out: error_propagate(errp, err); } ''',
@@ -254,9 +260,6 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error if variants: ret += mcgen(''' - if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) { - goto out_obj; - } switch ((*obj)->%(c_name)s) { ''', c_name=c_name(variants.tag_member.name))
@@ -293,16 +296,6 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error ret += mcgen(''' out_obj: -''') - if variants: - ret += mcgen(''' - error_propagate(errp, err); - err = NULL; - if (*obj) { - visit_end_union(v, !!(*obj)->u.data, &err); - } -''') - ret += mcgen(''' error_propagate(errp, err); err = NULL; visit_end_struct(v, &err);
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 32/37] qapi: Rework deallocation of partial struct
Quoted 24 lines · Eric Blake
Commit
cee2dedbnoticed that if you have a partial flat union (such as if an input parse failed due to a missing discriminator), calling the dealloc visitor could result in trying to dereference the NULL pointer. But the fix it proposed requires the use of a 'data' member in the union, which may or may not be the same size as other branches of the union (consider a 32-bit platform where one of the branches is an int64), so it feels fairly dirty. A better fix is to tweak all of the generatedvisit_type_implicit_FOO()functions to avoid dereferencing NULL in the first place, by not visiting the fields if the struct pointer itself is not present, at which point we no longer even needvisit_start_union(). And no one was implementingvisit_end_union()callbacks.While rewriting the code, use patterns that are closer to what is used elsewhere in the generated visitors, by using 'goto' to cleanup labels rather than putting followup code under 'if' conditions. The change keeps the contract that any successful use of
visit_start_implicit_struct()will be paired with a matchingvisit_end_implicit_struct(), even if intermediate processing is skipped. We are safe in checking *obj alone, as as the contract ofvisit_start_implicit_struct()requires a non-NULL obj.
Quoted 1 line
As an example of the changes to generated code:
This could be easier to understand if you show the change to the union visit (hunks 2+3) before the change to one of its variant members (hunk 1).
Quoted 19 lines
|@@ -1331,10 +1331,16 @@ static void visit_type_implicit_Blockdev
| Error *err = NULL;
|
| visit_start_implicit_struct(v, (void **)obj, sizeof(BlockdevOptionsArchipelago), &err);
|- if (!err) {
|- visit_type_BlockdevOptionsArchipelago_fields(v, obj, errp);
|- visit_end_implicit_struct(v);
|+ if (err) {
|+ goto out;
|+ }
|+ if (!*obj) {
|+ goto out_obj;
| }
|+ visit_type_BlockdevOptionsArchipelago_fields(v, obj, &err);
|+out_obj:
|+ visit_end_implicit_struct(v);
|+out:
| error_propagate(errp, err);
| }Quoted 8 lines
...
|@@ -1479,9 +1539,6 @@ void visit_type_BlockdevOptions(Visitor | if (err) { | goto out_obj; | } |- if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) { |- goto out_obj; |- }
If v is the dealloc visitor, the condition is !(*obj)->u.data. Else, it's false.
(*obj)->u.data can be null only for a partially initialized obj.
Spelling out the obvious: partially initialized objects may be visited with the dealloc visitor only.
So, this basically boils down to "if we're deallocating a partially initialized object, and the variant part hasn't been initialized, bypass the switch visiting the variant part.
Your patch changes it to visit the variant part unconditionally. The code doing that visit needs to be able to cope with an uninitialized part.
Quoted 1 line
| switch ((*obj)->driver) {
Which variant do we visit? If the tag hasn't been initialized, we arbitrarily visit the first one. Amazingly, this actually works, as we shall see.
Quoted 2 lines
| case
BLOCKDEV_DRIVER_ARCHIPELAGO:
|visit_type_implicit_BlockdevOptionsArchipelago(v, &(*obj)->u.archipelago, &err);
Note that (*obj)->u.archipelago equals (*obj)->u.data by construction of the union's C data type: the variant members are all stored boxed.
So, when (and only when, I think) we visit an uninitialized variant, the visit function's obj parameter points to a null pointer.
break;
[More cases...]Quoted 1 line
|@@ -1570,11 +1627,6 @@ void visit_type_BlockdevOptions(Visitor
default:
abort();
}Quoted 9 lines
| out_obj:
| error_propagate(errp, err);
| err = NULL;
|- if (*obj) {
|- visit_end_union(v, !!(*obj)->u.data, &err);
|- }
|- error_propagate(errp, err);
|- err = NULL;
| visit_end_struct(v, &err);Now let's see how function to visit the variant part changes. Before:
static void visit_type_implicit_BlockdevOptionsArchipelago(Visitor *v, BlockdevOptionsArchipelago **obj, Error **errp)
{
Error *err = NULL;
visit_start_implicit_struct(v, (void **)obj, sizeof(BlockdevOptionsArchipelago), &err);
if (!err) {
visit_type_BlockdevOptionsArchipelago_fields(v, obj, errp);
visit_end_implicit_struct(v);
}
error_propagate(errp, err);
}After:
static void visit_type_implicit_BlockdevOptionsArchipelago(Visitor *v, BlockdevOptionsArchipelago **obj, Error **errp)
{
Error *err = NULL;
visit_start_implicit_struct(v, (void **)obj, sizeof(BlockdevOptionsArchipelago), &err);
if (err) {
goto out;
}
if (!*obj) {
goto out_obj;
}
visit_type_BlockdevOptionsArchipelago_fields(v, obj, &err);
out_obj:
visit_end_implicit_struct(v);
out:
error_propagate(errp, err);
}If err, no change.
Else if !*obj, i.e. we're visiting an uninitialized part with the dealloc visitor, we now skip visiting the fields. We still call visit_start_implicit_struct() and visit_end_implicit_struct().
Else no change.
Taken together: when we visit a partially initialized union...
* The actual visitor must be the dealloc visitor then.
* We now execute visit_end_implicit_struct() and visit_end_implicit_struct(). If the tag has been initialized, we execute them for the part belonging to the tag value. Else, we arbitrarily execute them for the part belonging to the value 0.
* The dealloc visitor's qapi_dealloc_start_implicit_struct() stores its obj argument for later.
It's qapi_dealloc_end_implicit_struct() retrieves the stored obj and frees *obj.
For the calls added by this patch, this is a no-op, because *obj is null.
* In all the cases, the additionally executed code does nothing.
Works. The "arbitrarily execute them for tag value 0" bit is quite ugly, though.
Aside: if we unbox the variant parts, start_implicit_struct() and end_implicit_struct() should go away, and then things become less ugly.
Quoted 139 lines
Signed-off-by Eric Blake <[email protected]>Reviewed-by Marc-André Lureau <[email protected]>---
v9: no change
v8: rebase to 'name' motion
v7: rebase to earlier context changes, simplify 'obj && !*obj' condition based on contract
v6: rebase due to deferring 7/46, andgen_err_check()improvements; rewritegen_visit_implicit_struct()more like other patterns--- include/qapi/visitor-impl.h | 5 ----- include/qapi/visitor.h | 12 ------------ qapi/qapi-dealloc-visitor.c | 26 -------------------------- qapi/qapi-visit-core.c | 15 --------------- scripts/qapi-visit.py | 25 +++++++++---------------- 5 files changed, 9 insertions(+), 74 deletions(-)include/qapi/visitor-impl.h +0
-5@@ -81,11 +81,6 @@ struct Visitor/* May be NULL; most useful for input visitors. */ void (*optional)(Visitor *v,const char *name,bool *present); - -/* FIXME - needs to be removed */ -bool (*start_union)(Visitor *v,bool data_present,Error **errp); -/* FIXME - needs to be removed */ -void (*end_union)(Visitor *v,bool data_present,Error **errp); };/** include/qapi/visitor.h +0
-12@@ -274,16 +274,4 @@ void visit_type_any(Visitor *v, const char *name, QObject **obj, Error **errp);*/ void visit_type_null (Visitor *v,const char *name,Error **errp); -/** -* Mark the start of visiting the branches of a union. Return true if -* @data_present. -* FIXME: Should not be needed -*/ -bool visit_start_union (Visitor *v,bool data_present,Error **errp); -/** -* Mark the end of union branches, after visit_start_union(). -* FIXME: Should not be needed -*/ -void visit_end_union (Visitor *v,bool data_present,Error **errp); -#endif qapi/qapi-dealloc-visitor.c +0
-26@@ -171,31 +171,6 @@ static void qapi_dealloc_type_enum(Visitor *v, const char *name, int *obj, { } -/* If there's no data present, the dealloc visitor has nothing to free. -* Thus, indicate to visitor code that the subsequent union fields can -* be skipped. This is not an error condition, since the cleanup of the -* rest of an object can continue unhindered, so leave errp unset in -* these cases. -* -* NOTE: In cases where we're attempting to deallocate an object that -* may have missing fields, the field indicating the union type may -* be missing. In such a case, it's possible we don't have enough -* information to differentiate data_present == false from a case where -* data *is* present but happens to be a scalar with a value of 0. -* This is okay, since in the case of the dealloc visitor there's no -* work that needs to done in either situation. -* -* The current inability in QAPI code to more thoroughly verify a union -* type in such cases will likely need to be addressed if we wish to -* implement this interface for other types of visitors in the future, -* however. -*/ -static bool qapi_dealloc_start_union (Visitor *v,bool data_present, -Error **errp) -{ -return data_present; -} -Visitor *qapi_dealloc_get_visitor (QapiDeallocVisitor *v) {return &v->visitor;@@ -227,7 +202,6 @@ QapiDeallocVisitor *qapi_dealloc_visitor_new(void) v->visitor.type_number = qapi_dealloc_type_number; v->visitor.type_any = qapi_dealloc_type_anything; v->visitor.type_null = qapi_dealloc_type_null; - v->visitor.start_union = qapi_dealloc_start_union;QTAILQ_INIT (&v->stack);qapi/qapi-visit-core.c +0
-15@@ -76,21 +76,6 @@ void visit_end_list(Visitor *v) v->end_list (v); } -bool visit_start_union (Visitor *v,bool data_present,Error **errp) -{ -if (v->start_union) { -return v->start_union (v, data_present, errp); - } -return true; -} - -void visit_end_union (Visitor *v,bool data_present,Error **errp) -{ -if (v->end_union) { - v->end_union (v, data_present, errp); - } -} -bool visit_optional (Visitor *v,const char *name,bool *present) {if (v->optional) {scripts/qapi-visit.py +2
-3@@ -60,10 +60,16 @@ static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * Error *err = NULL; visit_start_implicit_struct(v, (void **)obj, sizeof(%(c_type)s), &err); - if (!err) { - visit_type_%(c_type)s_fields(v, obj, errp); - visit_end_implicit_struct(v); + if (err) { + goto out; }
scripts/qapi-visit.py static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * · line 75
Quoted 10 lines
scripts/qapi-visit.py +7
-0+ if (!*obj) { + goto out_obj; + } + visit_type_%(c_type)s_fields(v, obj, &err); +out_obj: + visit_end_implicit_struct(v); +out: error_propagate(errp, err); } ''',
Matches the diff in the commit message.
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 265
Quoted 10 lines
scripts/qapi-visit.py +0
-3@@ -254,9 +260,6 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error if variants: ret += mcgen(''' - if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) { - goto out_obj; - } switch ((*obj)->%(c_name)s) { ''', c_name=c_name(variants.tag_member.name))
Likewise.
Quoted 7 lines
scripts/qapi-visit.py +0
-3@@ -293,16 +296,6 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error ret += mcgen(''' out_obj: -''') - if variants: - ret += mcgen('''
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 301
Quoted 10 lines
scripts/qapi-visit.py +0
-7- error_propagate(errp, err); - err = NULL; - if (*obj) { - visit_end_union(v, !!(*obj)->u.data, &err); - } -''') - ret += mcgen(''' error_propagate(errp, err); err = NULL; visit_end_struct(v, &err);
This one's a bit harder to see, but it actually matches, too.
PATCH v9 33/37 qapi: Split visit_end_struct() into pieces
In reply to Eric BlakeAs mentioned in previous patches, we want to call visit_end_struct() functions unconditionally, so that visitors can release resources tied up since the matching visit_start_struct() without also having to worry about error priority if more than one error occurs.
Even though error_propagate() can be safely used to ignore a second error during cleanup caused by a first error, it is simpler if the cleanup cannot set an error, and we instead split the task of checking that an input visitor has no unvisited input as a new function visit_check_struct(), called only if all prior steps are successful.
Generated code has diffs resembling:
|@@ -59,10 +59,12 @@ void visit_type_ACPIOSTInfo(Visitor *v,
| goto out_obj;
| }
| visit_type_ACPIOSTInfo_fields(v, obj, &err);
|+ if (err) {
|+ goto out_obj;
|+ }
|+ visit_check_struct(v, &err);
| out_obj:
|- error_propagate(errp, err);
|- err = NULL;
|- visit_end_struct(v, &err);
|+ visit_end_struct(v);
| out:---
v9: rebase to earlier changes, drop Marc-Andre's R-b
v8: rebase to 'name' motion
v7: rebase to earlier changes
v6: new patch, revised version of RFC based on discussion of v5 7/46
--- hmp.c | 7 ++++--- hw/ppc/spapr_drc.c | 3 ++- hw/virtio/virtio-balloon.c | 12 ++++++------ include/qapi/visitor-impl.h | 4 +++- include/qapi/visitor.h | 13 ++++++++++--- qapi/opts-visitor.c | 17 +++++++++++++++-- qapi/qapi-dealloc-visitor.c | 2 +- qapi/qapi-visit-core.c | 11 +++++++++-- qapi/qmp-input-visitor.c | 34 +++++++++++++++++++--------------- qapi/qmp-output-visitor.c | 2 +- qom/object.c | 5 ++--- scripts/qapi-event.py | 3 ++- scripts/qapi-visit.py | 9 ++++----- tests/test-qmp-input-visitor.c | 3 ++- vl.c | 11 +++++------ 15 files changed, 85 insertions(+), 51 deletions(-)
hmp.c +4 -3
@@ -1687,13 +1687,14 @@ void hmp_object_add(Monitor *mon, const QDict *qdict) }object_add (type, id, pdict, v, &err); - -out_end: -visit_end_struct (v, &err_end); +visit_check_struct (v, &err_end);if (!err && err_end) {qmp_object_del (id,NULL ); }error_propagate (&err, err_end); + +out_end: +visit_end_struct (v); out_clean:opts_visitor_cleanup (ov);
hw/ppc/spapr_drc.c +2 -1
@@ -287,11 +287,12 @@ static void prop_get_fdt(Object *obj, Visitor *v, const char *name,case FDT_END_NODE :/* shouldn't ever see an FDT_END_NODE before FDT_BEGIN_NODE */ g_assert (fdt_depth >0 ); -visit_end_struct (v, &err); +visit_check_struct (v, &err);if (err) {error_propagate (errp, err);return ; } +visit_end_struct (v); fdt_depth--;break ;case FDT_PROP : {
hw/virtio/virtio-balloon.c +6 -6
@@ -136,15 +136,15 @@ static void balloon_stats_get_all(Object *obj, Visitor *v, const char *name, goto out_nested; } } +visit_check_struct (v, &err); out_nested: -error_propagate (errp, err); - err =NULL ; -visit_end_struct (v, &err); +visit_end_struct (v); +if (!err) { +visit_check_struct (v, &err); + } out_end: -error_propagate (errp, err); - err =NULL ; -visit_end_struct (v, &err); +visit_end_struct (v); out:error_propagate (errp, err); }
include/qapi/visitor-impl.h +3 -1
@@ -28,8 +28,10 @@ struct Visitor* currently visit structs). */ void (*start_struct)(Visitor *v,const char *name,void **obj,size_t size,Error **errp); +/* May be NULL; most useful for input visitors. */ +void (*check_struct)(Visitor *v,Error **errp);/* Must be provided if start_struct is present. */ -void (*end_struct)(Visitor *v,Error **errp); +void (*end_struct)(Visitor *v);/* May be NULL; most useful for input visitors. */ void (*start_implicit_struct)(Visitor *v, void **obj, size_t size,
include/qapi/visitor.h +10 -3
@@ -68,12 +68,19 @@ typedef struct GenericListvoid visit_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp);/** +* Prepare for completing a struct visit. +* Should be called prior to visit_end_struct() if all other intermediate +* visit steps were successful, to allow the caller one last chance to +* report errors such as remaining data that was not consumed by the visit. +*/ +void visit_check_struct (Visitor *v,Error **errp); +/** * Complete a struct visit started earlier. * Must be called after any successful use of visit_start_struct(), * even if intermediate processing was skipped due to errors, to allow * the backend to release any resources. */ -void visit_end_struct (Visitor *v,Error **errp); +void visit_end_struct (Visitor *v);/** * Prepare to visit an implicit struct.
@@ -96,8 +103,8 @@ void visit_start_implicit_struct(Visitor *v, void **obj, size_t size,* Must be called after any successful use of visit_start_implicit_struct(), * even if intermediate processing was skipped due to errors, to allow * the backend to release any resources. Unlike visit_end_struct(), this -* does not need to check for errors (detection of unused keys is only -* possible for the overall struct, not a subset). +* does not need a counterpart function to check for errors (detection of +* unused keys is only possible for the overall struct, not a subset). */ void visit_end_implicit_struct (Visitor *v);
qapi/opts-visitor.c +15 -2
@@ -157,13 +157,13 @@ opts_start_struct(Visitor *v, const char *name, void **obj,static void -opts_end_struct (Visitor *v,Error **errp) +opts_check_struct (Visitor *v,Error **errp) {OptsVisitor *ov =to_ov (v);GHashTableIter iter;GQueue *any; -if (--ov->depth >0 ) { +if (ov->depth >0 ) {return ; }
@@ -175,6 +175,18 @@ opts_end_struct(Visitor *v, Error **errp) first =g_queue_peek_head (any);error_setg (errp,QERR_INVALID_PARAMETER , first->name); } +} + + +static void +opts_end_struct (Visitor *v) +{ +OptsVisitor *ov =DO_UPCAST (OptsVisitor, visitor, v); + +if (--ov->depth >0 ) { +return ; + } +g_hash_table_destroy (ov->unprocessed_opts); ov->unprocessed_opts =NULL ;if (ov->fake_id_opt) {
@@ -506,6 +518,7 @@ opts_visitor_new(const QemuOpts *opts) ov =g_malloc0 (sizeof *ov); ov->visitor.start_struct = &opts_start_struct; + ov->visitor.check_struct = &opts_check_struct; ov->visitor.end_struct = &opts_end_struct; ov->visitor.start_list = &opts_start_list;
qapi/qapi-dealloc-visitor.c +1 -1
@@ -65,7 +65,7 @@ static void qapi_dealloc_start_struct(Visitor *v, const char *name, void **obj,qapi_dealloc_push (qov, obj); } -static void qapi_dealloc_end_struct (Visitor *v,Error **errp) +static void qapi_dealloc_end_struct (Visitor *v) {QapiDeallocVisitor *qov =to_qov (v);void **obj =qapi_dealloc_pop (qov);
qapi/qapi-visit-core.c +9 -2
@@ -36,9 +36,16 @@ void visit_start_struct(Visitor *v, const char *name, void **obj, v->start_struct (v, name, obj, size, errp); } -void visit_end_struct (Visitor *v,Error **errp) +void visit_check_struct (Visitor *v,Error **errp) { - v->end_struct (v, errp); +if (v->check_struct) { + v->check_struct (v, errp); + } +} + +void visit_end_struct (Visitor *v) +{ + v->end_struct (v); } void visit_start_implicit_struct(Visitor *v, void **obj, size_t size,
qapi/qmp-input-visitor.c +19 -15
@@ -89,8 +89,10 @@ static void qmp_input_push(QmpInputVisitor *qiv, QObject *obj, Error **errp) } -static void qmp_input_pop (QmpInputVisitor *qiv,Error **errp) +static void qmp_input_check_struct (Visitor *v,Error **errp) { +QmpInputVisitor *qiv =to_qiv (v); +assert (qiv->nb_stack >0 );if (qiv->strict) {
@@ -103,6 +105,19 @@ static void qmp_input_pop(QmpInputVisitor *qiv, Error **errp)if (g_hash_table_iter_next (&iter, (void **)&key,NULL )) {error_setg (errp,QERR_QMP_EXTRA_MEMBER , key); } + } + } +} + +static void qmp_input_pop (Visitor *v) +{ +QmpInputVisitor *qiv =to_qiv (v); + +assert (qiv->nb_stack >0 ); + +if (qiv->strict) { +GHashTable *const top_ht = qiv->stack[qiv->nb_stack -1 ].h; +if (top_ht) {g_hash_table_unref (top_ht); } }
@@ -134,12 +149,6 @@ static void qmp_input_start_struct(Visitor *v, const char *name, void **obj, } } -static void qmp_input_end_struct (Visitor *v,Error **errp) -{ -QmpInputVisitor *qiv =to_qiv (v); - -qmp_input_pop (qiv, errp); -}static void qmp_input_start_implicit_struct (Visitor *v,void **obj,size_t size,Error **errp)
@@ -193,12 +202,6 @@ static GenericList *qmp_input_next_list(Visitor *v, GenericList **list,return entry; } -static void qmp_input_end_list (Visitor *v) -{ -QmpInputVisitor *qiv =to_qiv (v); - -qmp_input_pop (qiv, &error_abort); -}static void qmp_input_get_next_type (Visitor *v,const char *name,QType *type,bool promote_int,Error **errp)
@@ -355,11 +358,12 @@ QmpInputVisitor *qmp_input_visitor_new(QObject *obj) v =g_malloc0 (sizeof (*v)); v->visitor.start_struct = qmp_input_start_struct; - v->visitor.end_struct = qmp_input_end_struct; + v->visitor.check_struct = qmp_input_check_struct; + v->visitor.end_struct = qmp_input_pop; v->visitor.start_implicit_struct = qmp_input_start_implicit_struct; v->visitor.start_list = qmp_input_start_list; v->visitor.next_list = qmp_input_next_list; - v->visitor.end_list = qmp_input_end_list; + v->visitor.end_list = qmp_input_pop; v->visitor.type_enum = input_type_enum; v->visitor.type_int64 = qmp_input_type_int64; v->visitor.type_uint64 = qmp_input_type_uint64;
qapi/qmp-output-visitor.c +1 -1
@@ -116,7 +116,7 @@ static void qmp_output_start_struct(Visitor *v, const char *name, void **obj,qmp_output_push (qov, dict); } -static void qmp_output_end_struct (Visitor *v,Error **errp) +static void qmp_output_end_struct (Visitor *v) {QmpOutputVisitor *qov =to_qov (v);qmp_output_pop (qov,QTYPE_QDICT );
qom/object.c +2 -3
@@ -2034,10 +2034,9 @@ static void property_get_tm(Object *obj, Visitor *v, const char *name,if (err) { goto out_end; } +visit_check_struct (v, &err); out_end: -error_propagate (errp, err); - err =NULL ; -visit_end_struct (v, errp); +visit_end_struct (v); out:error_propagate (errp, err);
scripts/qapi-event.py +2 -1
@@ -71,8 +71,9 @@ def gen_event_send(name, arg_type): ret += gen_visit_fields(arg_type.members, need_cast=True, label='out_obj') ret += mcgen(''' + visit_check_struct(v, &err); out_obj: - visit_end_struct(v, &err); + visit_end_struct(v); if (err) { goto out; }
scripts/qapi-visit.py +4 -5
@@ -255,8 +255,7 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error visit_type_%(c_name)s_fields(v, %(cast)sobj, &err); ''', c_name=type_name, cast=cast) - if variants: - ret += gen_err_check(label='out_obj') + ret += gen_err_check(label='out_obj') if variants: ret += mcgen('''
@@ -293,12 +292,12 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error abort(); } ''') + ret += gen_err_check(label='out_obj') ret += mcgen(''' + visit_check_struct(v, &err); out_obj: - error_propagate(errp, err); - err = NULL; - visit_end_struct(v, &err); + visit_end_struct(v); out: error_propagate(errp, err); }
tests/test-qmp-input-visitor.c +2 -1
@@ -290,7 +290,8 @@ static void test_visitor_in_null(TestInputVisitorData *data, v =visitor_input_test_init (data,"{ 'a': null }" );visit_start_struct (v,NULL ,NULL ,0 , &error_abort);visit_type_null (v,"a" , &error_abort); -visit_end_struct (v, &error_abort); +visit_check_struct (v, &error_abort); +visit_end_struct (v);/* Check that qnull reference counting is sane: * 1 for global use, 1 for our qnull() use, and 1 still owned by 'v'
vl.c +5 -6
@@ -2842,11 +2842,10 @@ static int object_create(void *opaque, QemuOpts *opts, Error **errp)qdict_del (pdict,"qom-type" );visit_type_str (v,"qom-type" , &type, &err);if (err) { - goto out; + goto out_end; }if (!type_predicate (type)) { -visit_end_struct (v,NULL ); - goto out; + goto out_end; }qdict_del (pdict,"id" );
@@ -2856,14 +2855,14 @@ static int object_create(void *opaque, QemuOpts *opts, Error **errp) }object_add (type, id, pdict, v, &err); - -out_end: -visit_end_struct (v, &err_end); +visit_check_struct (v, &err_end);if (!err && err_end) {qmp_object_del (id,NULL ); }error_propagate (&err, err_end); +out_end: +visit_end_struct (v); out:opts_visitor_cleanup (ov);
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 33/37] qapi: Split visit_end_struct() into pieces
Quoted 14 lines · Eric Blake
As mentioned in previous patches, we want to call
visit_end_struct()functions unconditionally, so that visitors can release resources tied up since the matchingvisit_start_struct()without also having to worry about error priority if more than one error occurs.Even though
error_propagate()can be safely used to ignore a second error during cleanup caused by a first error, it is simpler if the cleanup cannot set an error, and we instead split the task of checking that an input visitor has no unvisited input as a new functionvisit_check_struct(), called only if all prior steps are successful.Generated code has diffs resembling:
Quoted 14 lines
|@@ -59,10 +59,12 @@ void visit_type_ACPIOSTInfo(Visitor *v,
| goto out_obj;
| }
| visit_type_ACPIOSTInfo_fields(v, obj, &err);
|+ if (err) {
|+ goto out_obj;
|+ }
|+ visit_check_struct(v, &err);
| out_obj:
|- error_propagate(errp, err);
|- err = NULL;
|- visit_end_struct(v, &err);
|+ visit_end_struct(v);
| out:Basically, split visit_end_struct() into a part that runs only when there have been no errors and a part that runs as before, i.e. when visit_start_struct() succeeded, even when there have been errors since. This second part cannot fail, which simplifies error handling a bit.
To review: skipping the first part when there have been errors is safe.
Quoted 56 lines
Signed-off-by Eric Blake <[email protected]>---
v9: rebase to earlier changes, drop Marc-Andre's R-b
v8: rebase to 'name' motion
v7: rebase to earlier changes
v6: new patch, revised version of RFC based on discussion of v5 7/46--- hmp.c | 7 ++++--- hw/ppc/spapr_drc.c | 3 ++- hw/virtio/virtio-balloon.c | 12 ++++++------ include/qapi/visitor-impl.h | 4 +++- include/qapi/visitor.h | 13 ++++++++++--- qapi/opts-visitor.c | 17 +++++++++++++++-- qapi/qapi-dealloc-visitor.c | 2 +- qapi/qapi-visit-core.c | 11 +++++++++-- qapi/qmp-input-visitor.c | 34 +++++++++++++++++++--------------- qapi/qmp-output-visitor.c | 2 +- qom/object.c | 5 ++--- scripts/qapi-event.py | 3 ++- scripts/qapi-visit.py | 9 ++++----- tests/test-qmp-input-visitor.c | 3 ++- vl.c | 11 +++++------ 15 files changed, 85 insertions(+), 51 deletions(-)hmp.c +4
-3@@ -1687,13 +1687,14 @@ void hmp_object_add(Monitor *mon, const QDict *qdict) }object_add (type, id, pdict, v, &err); - -out_end: -visit_end_struct (v, &err_end); +visit_check_struct (v, &err_end);if (!err && err_end) {qmp_object_del (id,NULL ); }error_propagate (&err, err_end); + +out_end: +visit_end_struct (v); out_clean:opts_visitor_cleanup (ov);hw/ppc/spapr_drc.c +0
-0@@ -287,11 +287,12 @@ static void prop_get_fdt(Object *obj, Visitor *v, const char *name,case FDT_END_NODE :/* shouldn't ever see an FDT_END_NODE before FDT_BEGIN_NODE */ g_assert (fdt_depth >0 );
hw/ppc/spapr_drc.c static void prop_get_fdt(Object *obj, Visitor *v, const char *name, · line 298
Quoted 10 lines
hw/ppc/spapr_drc.c +2
-1-visit_end_struct (v, &err); +visit_check_struct (v, &err);if (err) {error_propagate (errp, err);return ; } +visit_end_struct (v); fdt_depth--;break ;case FDT_PROP : {
No longer calls visit_end_struct() when visit_end_struct() fails. Contradicts the rule to always call it after visit_start_struct() succeded.
Quoted 31 lines
hw/virtio/virtio-balloon.c +6
-6@@ -136,15 +136,15 @@ static void balloon_stats_get_all(Object *obj, Visitor *v, const char *name, goto out_nested; } } +visit_check_struct (v, &err); out_nested: -error_propagate (errp, err); - err =NULL ; -visit_end_struct (v, &err); +visit_end_struct (v); +if (!err) { +visit_check_struct (v, &err); + } out_end: -error_propagate (errp, err); - err =NULL ; -visit_end_struct (v, &err); +visit_end_struct (v); out:error_propagate (errp, err); }include/qapi/visitor-impl.h +0
-0
include/qapi/visitor-impl.h struct Visitor · line 32
Quoted 5 lines
include/qapi/visitor-impl.h +2
-0@@ -28,8 +28,10 @@ struct Visitor* currently visit structs). */ void (*start_struct)(Visitor *v,const char *name,void **obj,size_t size,Error **errp); +/* May be NULL; most useful for input visitors. */ +void (*check_struct)(Visitor *v,Error **errp);
Well, "most useful" is certainly correct since other visitors have had no use for it so far :)
"intended for input visitors"?
Quoted 52 lines
include/qapi/visitor-impl.h +1
-1/* Must be provided if start_struct is present. */ -void (*end_struct)(Visitor *v,Error **errp); +void (*end_struct)(Visitor *v);/* May be NULL; most useful for input visitors. */ void (*start_implicit_struct)(Visitor *v, void **obj, size_t size,include/qapi/visitor.h +10
-3@@ -68,12 +68,19 @@ typedef struct GenericListvoid visit_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp);/** +* Prepare for completing a struct visit. +* Should be called prior to visit_end_struct() if all other intermediate +* visit steps were successful, to allow the caller one last chance to +* report errors such as remaining data that was not consumed by the visit. +*/ +void visit_check_struct (Visitor *v,Error **errp); +/** * Complete a struct visit started earlier. * Must be called after any successful use of visit_start_struct(), * even if intermediate processing was skipped due to errors, to allow * the backend to release any resources. */ -void visit_end_struct (Visitor *v,Error **errp); +void visit_end_struct (Visitor *v);/** * Prepare to visit an implicit struct. @@ -96,8 +103,8 @@ void visit_start_implicit_struct(Visitor *v, void **obj, size_t size,* Must be called after any successful use of visit_start_implicit_struct(), * even if intermediate processing was skipped due to errors, to allow * the backend to release any resources. Unlike visit_end_struct(), this -* does not need to check for errors (detection of unused keys is only -* possible for the overall struct, not a subset). +* does not need a counterpart function to check for errors (detection of +* unused keys is only possible for the overall struct, not a subset). */ void visit_end_implicit_struct (Visitor *v);qapi/opts-visitor.c +1
-1@@ -157,13 +157,13 @@ opts_start_struct(Visitor *v, const char *name, void **obj,static void -opts_end_struct (Visitor *v,Error **errp) +opts_check_struct (Visitor *v,Error **errp)
qapi/opts-visitor.c opts_start_struct(Visitor *v, const char *name, void **obj, · line 169
Quoted 10 lines
qapi/opts-visitor.c +1
-1{OptsVisitor *ov =to_ov (v);GHashTableIter iter;GQueue *any; -if (--ov->depth >0 ) { +if (ov->depth >0 ) {return ; }
Not fully visible in this diff: this function's only possible side effect is setting an error. Therefore, skipping this when there have been errors is safe.
Quoted 69 lines
qapi/opts-visitor.c +13
-0@@ -175,6 +175,18 @@ opts_end_struct(Visitor *v, Error **errp) first =g_queue_peek_head (any);error_setg (errp,QERR_INVALID_PARAMETER , first->name); } +} + + +static void +opts_end_struct (Visitor *v) +{ +OptsVisitor *ov =DO_UPCAST (OptsVisitor, visitor, v); + +if (--ov->depth >0 ) { +return ; + } +g_hash_table_destroy (ov->unprocessed_opts); ov->unprocessed_opts =NULL ;if (ov->fake_id_opt) {@@ -506,6 +518,7 @@ opts_visitor_new(const QemuOpts *opts) ov =g_malloc0 (sizeof *ov); ov->visitor.start_struct = &opts_start_struct; + ov->visitor.check_struct = &opts_check_struct; ov->visitor.end_struct = &opts_end_struct; ov->visitor.start_list = &opts_start_list;qapi/qapi-dealloc-visitor.c +1
-1@@ -65,7 +65,7 @@ static void qapi_dealloc_start_struct(Visitor *v, const char *name, void **obj,qapi_dealloc_push (qov, obj); } -static void qapi_dealloc_end_struct (Visitor *v,Error **errp) +static void qapi_dealloc_end_struct (Visitor *v) {QapiDeallocVisitor *qov =to_qov (v);void **obj =qapi_dealloc_pop (qov);qapi/qapi-visit-core.c +9
-2@@ -36,9 +36,16 @@ void visit_start_struct(Visitor *v, const char *name, void **obj, v->start_struct (v, name, obj, size, errp); } -void visit_end_struct (Visitor *v,Error **errp) +void visit_check_struct (Visitor *v,Error **errp) { - v->end_struct (v, errp); +if (v->check_struct) { + v->check_struct (v, errp); + } +} + +void visit_end_struct (Visitor *v) +{ + v->end_struct (v); } void visit_start_implicit_struct(Visitor *v, void **obj, size_t size,qapi/qmp-input-visitor.c +0
-0@@ -89,8 +89,10 @@ static void qmp_input_push(QmpInputVisitor *qiv, QObject *obj, Error **errp) }
qapi/qmp-input-visitor.c static void qmp_input_push(QmpInputVisitor *qiv, QObject *obj, Error **errp) · line 98
Quoted 10 lines
qapi/qmp-input-visitor.c +3
-1-static void qmp_input_pop (QmpInputVisitor *qiv,Error **errp) +static void qmp_input_check_struct (Visitor *v,Error **errp) { +QmpInputVisitor *qiv =to_qiv (v); +assert (qiv->nb_stack >0 );if (qiv->strict) {
Same argument as for opts_check_struct().
Quoted 21 lines
qapi/qmp-input-visitor.c +13
-0@@ -103,6 +105,19 @@ static void qmp_input_pop(QmpInputVisitor *qiv, Error **errp)if (g_hash_table_iter_next (&iter, (void **)&key,NULL )) {error_setg (errp,QERR_QMP_EXTRA_MEMBER , key); } + } + } +} + +static void qmp_input_pop (Visitor *v) +{ +QmpInputVisitor *qiv =to_qiv (v); + +assert (qiv->nb_stack >0 ); + +if (qiv->strict) { +GHashTable *const top_ht = qiv->stack[qiv->nb_stack -1 ].h; +if (top_ht) {g_hash_table_unref (top_ht); } }
qapi/qmp-input-visitor.c static void qmp_input_start_struct(Visitor *v, const char *name, void **obj, · line 142
Quoted 9 lines
qapi/qmp-input-visitor.c +0
-6@@ -134,12 +149,6 @@ static void qmp_input_start_struct(Visitor *v, const char *name, void **obj, } } -static void qmp_input_end_struct (Visitor *v,Error **errp) -{ -QmpInputVisitor *qiv =to_qiv (v); - -qmp_input_pop (qiv, errp); -}
Order is now funny: the end_struct() method preceeds the start_struct() method. I guess that's okay.
qapi/qmp-input-visitor.c static GenericList *qmp_input_next_list(Visitor *v, GenericList **list, · line 201
Quoted 13 lines
qapi/qmp-input-visitor.c +0
-6static void qmp_input_start_implicit_struct (Visitor *v,void **obj,size_t size,Error **errp)@@ -193,12 +202,6 @@ static GenericList *qmp_input_next_list(Visitor *v, GenericList **list,return entry; } -static void qmp_input_end_list (Visitor *v) -{ -QmpInputVisitor *qiv =to_qiv (v); - -qmp_input_pop (qiv, &error_abort); -}
Likewise.
Quoted 68 lines
qapi/qmp-input-visitor.c +3
-2static void qmp_input_get_next_type (Visitor *v,const char *name,QType *type,bool promote_int,Error **errp)@@ -355,11 +358,12 @@ QmpInputVisitor *qmp_input_visitor_new(QObject *obj) v =g_malloc0 (sizeof (*v)); v->visitor.start_struct = qmp_input_start_struct; - v->visitor.end_struct = qmp_input_end_struct; + v->visitor.check_struct = qmp_input_check_struct; + v->visitor.end_struct = qmp_input_pop; v->visitor.start_implicit_struct = qmp_input_start_implicit_struct; v->visitor.start_list = qmp_input_start_list; v->visitor.next_list = qmp_input_next_list; - v->visitor.end_list = qmp_input_end_list; + v->visitor.end_list = qmp_input_pop; v->visitor.type_enum = input_type_enum; v->visitor.type_int64 = qmp_input_type_int64; v->visitor.type_uint64 = qmp_input_type_uint64;qapi/qmp-output-visitor.c +1
-1@@ -116,7 +116,7 @@ static void qmp_output_start_struct(Visitor *v, const char *name, void **obj,qmp_output_push (qov, dict); } -static void qmp_output_end_struct (Visitor *v,Error **errp) +static void qmp_output_end_struct (Visitor *v) {QmpOutputVisitor *qov =to_qov (v);qmp_output_pop (qov,QTYPE_QDICT );qom/object.c +2
-3@@ -2034,10 +2034,9 @@ static void property_get_tm(Object *obj, Visitor *v, const char *name,if (err) { goto out_end; } +visit_check_struct (v, &err); out_end: -error_propagate (errp, err); - err =NULL ; -visit_end_struct (v, errp); +visit_end_struct (v); out:error_propagate (errp, err);scripts/qapi-event.py +2
-1@@ -71,8 +71,9 @@ def gen_event_send(name, arg_type): ret += gen_visit_fields(arg_type.members, need_cast=True, label='out_obj') ret += mcgen(''' + visit_check_struct(v, &err); out_obj: - visit_end_struct(v, &err); + visit_end_struct(v); if (err) { goto out; }scripts/qapi-visit.py +0
-0
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 258
Quoted 6 lines
scripts/qapi-visit.py +1
-2@@ -255,8 +255,7 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error visit_type_%(c_name)s_fields(v, %(cast)sobj, &err); ''', c_name=type_name, cast=cast) - if variants: - ret += gen_err_check(label='out_obj') + ret += gen_err_check(label='out_obj')
Can't immediately see why we need this change. Care to explain?
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 295
Quoted 8 lines
scripts/qapi-visit.py +1
-0if variants: ret += mcgen('''@@ -293,12 +292,12 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error abort(); } ''') + ret += gen_err_check(label='out_obj')
Yes, because we need to skip...
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 297
Quoted 3 lines
scripts/qapi-visit.py +1
-0ret += mcgen(''' + visit_check_struct(v, &err);
... this one.
Quoted 27 lines
scripts/qapi-visit.py +1
-3out_obj: - error_propagate(errp, err); - err = NULL; - visit_end_struct(v, &err); + visit_end_struct(v); out: error_propagate(errp, err); }tests/test-qmp-input-visitor.c +2
-1@@ -290,7 +290,8 @@ static void test_visitor_in_null(TestInputVisitorData *data, v =visitor_input_test_init (data,"{ 'a': null }" );visit_start_struct (v,NULL ,NULL ,0 , &error_abort);visit_type_null (v,"a" , &error_abort); -visit_end_struct (v, &error_abort); +visit_check_struct (v, &error_abort); +visit_end_struct (v);/* Check that qnull reference counting is sane: * 1 for global use, 1 for our qnull() use, and 1 still owned by 'v' vl.c +0
-0
vl.c static int object_create(void *opaque, QemuOpts *opts, Error **errp) · line 2845
Quoted 5 lines
vl.c +1
-1@@ -2842,11 +2842,10 @@ static int object_create(void *opaque, QemuOpts *opts, Error **errp)qdict_del (pdict,"qom-type" );visit_type_str (v,"qom-type" , &type, &err);if (err) { - goto out; + goto out_end;
Before: visit_end_struct() not called.
After: visit_end_struct() called.
Shouldn't this be fixed in PATCH 05?
Quoted 25 lines
vl.c +4
-5}if (!type_predicate (type)) { -visit_end_struct (v,NULL ); - goto out; + goto out_end; }qdict_del (pdict,"id" );@@ -2856,14 +2855,14 @@ static int object_create(void *opaque, QemuOpts *opts, Error **errp) }object_add (type, id, pdict, v, &err); - -out_end: -visit_end_struct (v, &err_end); +visit_check_struct (v, &err_end);if (!err && err_end) {qmp_object_del (id,NULL ); }error_propagate (&err, err_end); +out_end: +visit_end_struct (v); out:opts_visitor_cleanup (ov);
PATCH v9 34/37 qapi: Simplify semantics of visit_next_list()
In reply to Eric BlakeWe have two uses of list visits in the entire code base: one in spapr_drc (which completely avoids visit_next_list(), feeding in integers from a different source than uint8List), and one in qapi-visit.py (that is, all other list visitors are generated in qapi-visit.c, and share the same paradigm based on a qapi FooList type). What's more, the semantics of the list visit are somewhat baroque, with the following pseudocode when FooList is used:
start()
prev = head
while (cur = next(prev)) {
visit(cur)
prev = &cur
}
Note that these semantics (advance before visit) requires that the first call to next() return the list head, while all other calls return the next element of the list; that is, every visitor implementation is required to track extra state to decide whether to return the input as-is, or to advance. It also requires an argument of 'GenericList **' to next(), solely because the first iteration might need to modify the caller's GenericList head, so that all other calls have to do a layer of dereferencing.
We can greatly simplify things by hoisting the special case into the start() routine, and flipping the order in the loop to visit before advance:
start(head)
element = *head
while (element) {
visit(element)
element = next(element)
}
With the simpler semantics, visitors have less state to track, the argument to next() is reduced to 'GenericList *', and it also becomes obvious whether an input visitor is allocating a FooList during visit_start_list() (rather than the old way of not knowing if an allocation happened until the first visit_next_list()).
The signature of visit_start_list() is chosen to match visit_start_struct(), with the new parameter after 'name'.
The spapr_drc case requires that visit_start_list() has to pay attention to whether visit_next_list() will even be used to visit a FooList qapi struct; this is done by passing NULL for list, similarly to how NULL is passed to visit_start_struct() when a qapi type is not used in those visits. It was easy to provide these semantics for qmp-output and dealloc visitors, and a bit harder for qmp-input (it required hoisting the advance of the current qlist entry out of qmp_input_next_list() into qmp_input_get_object()). But it turned out that the string and opts visitors munge enough state during visit_next_list() to make those conversions simpler if they require a GenericList visit for now; an assertion will remind us to adjust things if we need the semantics in the future.
---
v9: no change
v8: consistent parameter order, fix qmp_input_get_next_type() to not skip list entries
v7: new patch
--- hw/ppc/spapr_drc.c | 2 +- include/qapi/visitor-impl.h | 5 ++-- include/qapi/visitor.h | 45 +++++++++++++++++-------------- qapi/opts-visitor.c | 32 +++++++++------------- qapi/qapi-dealloc-visitor.c | 29 +++++--------------- qapi/qapi-visit-core.c | 7 ++--- qapi/qmp-input-visitor.c | 64 +++++++++++++++++++++----------------------- qapi/qmp-output-visitor.c | 21 +++------------ qapi/string-input-visitor.c | 34 +++++++++++------------ qapi/string-output-visitor.c | 36 ++++++++----------------- scripts/qapi-visit.py | 21 ++++++++------- 11 files changed, 126 insertions(+), 170 deletions(-)
hw/ppc/spapr_drc.c +1 -1
@@ -299,7 +299,7 @@ static void prop_get_fdt(Object *obj, Visitor *v, const char *name,int i; prop =fdt_get_property_by_offset (fdt, fdt_offset, &prop_len); name =fdt_string (fdt,fdt32_to_cpu (prop->nameoff)); -visit_start_list (v, name, &err); +visit_start_list (v, name,NULL , &err);if (err) {error_propagate (errp, err);return ;
include/qapi/visitor-impl.h +3 -2
@@ -40,9 +40,10 @@ struct Visitorvoid (*end_implicit_struct)(Visitor *v);/* Must be set */ -void (*start_list)(Visitor *v,const char *name,Error **errp); +void (*start_list)(Visitor *v,const char *name,GenericList **list, +Error **errp);/* Must be set */ - GenericList *(*next_list)(Visitor *v, GenericList **list, Error **errp); + GenericList *(*next_list)(Visitor *v, GenericList *element, Error **errp);/* Must be set */ void (*end_list)(Visitor *v);
include/qapi/visitor.h +25 -20
63 lines not on this page · raw message
qapi/opts-visitor.c +13 -19
@@ -21,9 +21,8 @@enum ListMode {LM_NONE ,/* not traversing a list of repeated options */ -LM_STARTED ,/* opts_start_list() succeeded */ -LM_IN_PROGRESS ,/* opts_next_list() has been called. +LM_IN_PROGRESS ,/* opts_next_list() ready to be called. * * Generating the next list link will consume the most * recently parsed QemuOpt instance of the repeated
@@ -212,35 +211,32 @@ lookup_distinct(const OptsVisitor *ov, const char *name, Error **errp)static void -opts_start_list (Visitor *v,const char *name,Error **errp) +opts_start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {OptsVisitor *ov =to_ov (v);/* we can't traverse a list in a list */ assert (ov->list_mode ==LM_NONE ); +/* we don't support visits without GenericList, yet */ +assert (list); ov->repeated_opts =lookup_distinct (ov, name, errp); -if (ov->repeated_opts !=NULL ) { - ov->list_mode =LM_STARTED ; +if (ov->repeated_opts) { + ov->list_mode =LM_IN_PROGRESS ; + *list =g_new0 (GenericList,1 ); + }else { + *list =NULL ; } }static GenericList * -opts_next_list (Visitor *v,GenericList **list,Error **errp) +opts_next_list (Visitor *v,GenericList *list,Error **errp) {OptsVisitor *ov =to_ov (v); -GenericList **link;switch (ov->list_mode) { -case LM_STARTED : - ov->list_mode =LM_IN_PROGRESS ; - link = list; -break ; -case LM_SIGNED_INTERVAL :case LM_UNSIGNED_INTERVAL : - link = &(*list)->next; -if (ov->list_mode ==LM_SIGNED_INTERVAL ) {if (ov->range_next.s < ov->range_limit.s) { ++ov->range_next.s;
@@ -261,7 +257,6 @@ opts_next_list(Visitor *v, GenericList **list, Error **errp)g_hash_table_remove (ov->unprocessed_opts, opt->name);return NULL ; } - link = &(*list)->next;break ; }
@@ -269,8 +264,8 @@ opts_next_list(Visitor *v, GenericList **list, Error **errp)abort (); } - *link =g_malloc0 (sizeof **link); -return *link; + list->next =g_new0 (GenericList,1 ); +return list->next; }
@@ -279,8 +274,7 @@ opts_end_list(Visitor *v) {OptsVisitor *ov =to_ov (v); -assert (ov->list_mode ==LM_STARTED || - ov->list_mode ==LM_IN_PROGRESS || +assert (ov->list_mode ==LM_IN_PROGRESS || ov->list_mode ==LM_SIGNED_INTERVAL || ov->list_mode ==LM_UNSIGNED_INTERVAL ); ov->repeated_opts =NULL ;
qapi/qapi-dealloc-visitor.c +6 -23
@@ -20,7 +20,6 @@typedef struct StackEntry {void *value; -bool is_list_head;QTAILQ_ENTRY (StackEntry) node; }StackEntry ;
@@ -41,10 +40,6 @@ static void qapi_dealloc_push(QapiDeallocVisitor *qov, void *value) e->value = value; -/* see if we're just pushing a list head tracker */ -if (value ==NULL ) { - e->is_list_head = true; - }QTAILQ_INSERT_HEAD (&qov->stack, e, node); }
@@ -92,31 +87,19 @@ static void qapi_dealloc_end_implicit_struct(Visitor *v) } } -static void qapi_dealloc_start_list (Visitor *v,const char *name,Error **errp) +static void qapi_dealloc_start_list (Visitor *v,const char *name, +GenericList **list,Error **errp) {QapiDeallocVisitor *qov =to_qov (v);qapi_dealloc_push (qov,NULL ); } -static GenericList *qapi_dealloc_next_list (Visitor *v,GenericList **listp, +static GenericList *qapi_dealloc_next_list (Visitor *v,GenericList *list,Error **errp) { -GenericList *list = *listp; -QapiDeallocVisitor *qov =to_qov (v); -StackEntry *e =QTAILQ_FIRST (&qov->stack); - -if (e && e->is_list_head) { - e->is_list_head = false; -return list; - } - -if (list) { - list = list->next; -g_free (*listp); -return list; - } - -return NULL ; +GenericList *next = list->next; +g_free (list); +return next; }static void qapi_dealloc_end_list (Visitor *v)
qapi/qapi-visit-core.c +4 -3
@@ -67,12 +67,13 @@ void visit_end_implicit_struct(Visitor *v) } } -void visit_start_list (Visitor *v,const char *name,Error **errp) +void visit_start_list (Visitor *v,const char *name,GenericList **list, +Error **errp) { - v->start_list (v, name, errp); + v->start_list (v, name, list, errp); } -GenericList *visit_next_list (Visitor *v,GenericList **list,Error **errp) +GenericList *visit_next_list (Visitor *v,GenericList *list,Error **errp) {assert (list);return v->next_list (v, list, errp);
qapi/qmp-input-visitor.c +31 -33
122 lines not on this page · raw message
qapi/qmp-output-visitor.c +4 -17
@@ -21,7 +21,6 @@typedef struct QStackEntry {QObject *value; -bool is_list_head;QTAILQ_ENTRY (QStackEntry) node; }QStackEntry ;
@@ -51,9 +50,6 @@ static void qmp_output_push_obj(QmpOutputVisitor *qov, QObject *value)assert (qov->root);assert (value); e->value = value; -if (qobject_type (e->value) ==QTYPE_QLIST ) { - e->is_list_head = true; - }QTAILQ_INSERT_HEAD (&qov->stack, e, node); }
@@ -122,7 +118,8 @@ static void qmp_output_end_struct(Visitor *v)qmp_output_pop (qov,QTYPE_QDICT ); } -static void qmp_output_start_list (Visitor *v,const char *name,Error **errp) +static void qmp_output_start_list (Visitor *v,const char *name, +GenericList **listp,Error **errp) {QmpOutputVisitor *qov =to_qov (v);QList *list =qlist_new ();
@@ -131,20 +128,10 @@ static void qmp_output_start_list(Visitor *v, const char *name, Error **errp)qmp_output_push (qov, list); } -static GenericList *qmp_output_next_list (Visitor *v,GenericList **listp, +static GenericList *qmp_output_next_list (Visitor *v,GenericList *list,Error **errp) { -GenericList *list = *listp; -QmpOutputVisitor *qov =to_qov (v); -QStackEntry *e =QTAILQ_FIRST (&qov->stack); - -assert (e); -if (e->is_list_head) { - e->is_list_head = false; -return list; - } - -return list ? list->next :NULL ; +return list->next; }static void qmp_output_end_list (Visitor *v)
qapi/string-input-visitor.c +16 -18
@@ -23,8 +23,6 @@ struct StringInputVisitor {Visitor visitor; -bool head; -GList *ranges;GList *cur_range;int64_t cur;
@@ -123,11 +121,19 @@ error: }static void -start_list (Visitor *v,const char *name,Error **errp) +start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {StringInputVisitor *siv =to_siv (v); +Error *err =NULL ; -parse_str (siv, errp); +/* We don't support visits without a GenericList, yet */ +assert (list); + +parse_str (siv, &err); +if (err) { +error_propagate (errp, err); +return ; + } siv->cur_range =g_list_first (siv->ranges);if (siv->cur_range) {
@@ -135,14 +141,16 @@ start_list(Visitor *v, const char *name, Error **errp)if (r) { siv->cur = r->begin; } + *list =g_new0 (GenericList,1 ); + }else { + *list =NULL ; } }static GenericList * -next_list (Visitor *v,GenericList **list,Error **errp) +next_list (Visitor *v,GenericList *list,Error **errp) {StringInputVisitor *siv =to_siv (v); -GenericList **link;Range *r;if (!siv->ranges || !siv->cur_range) {
@@ -166,22 +174,13 @@ next_list(Visitor *v, GenericList **list, Error **errp) siv->cur = r->begin; } -if (siv->head) { - link = list; - siv->head = false; - }else { - link = &(*list)->next; - } - - *link =g_malloc0 (sizeof **link); -return *link; + list->next =g_new0 (GenericList,1 ); +return list->next; }static void end_list (Visitor *v) { -StringInputVisitor *siv =to_siv (v); - siv->head = true; } static void parse_type_int64(Visitor *v, const char *name, int64_t *obj,
@@ -361,6 +360,5 @@ StringInputVisitor *string_input_visitor_new(const char *str) v->visitor.optional = parse_optional; v->string = str; - v->head = true;return v; }
qapi/string-output-visitor.c +11 -25
@@ -57,7 +57,6 @@ struct StringOutputVisitorVisitor visitor;bool human;GString *string; -bool head;ListMode list_mode;union {int64_t s;
@@ -265,40 +264,29 @@ static void print_type_number(Visitor *v, const char *name, double *obj, }static void -start_list (Visitor *v,const char *name,Error **errp) +start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {StringOutputVisitor *sov =to_sov (v);/* we can't traverse a list in a list */ assert (sov->list_mode ==LM_NONE ); - sov->list_mode =LM_STARTED ; - sov->head = true; +/* We don't support visits without a GenericList, yet */ +assert (list); +/* List handling is only needed if there are at least two elements */ +if (*list && (*list)->next) { + sov->list_mode =LM_STARTED ; + } }static GenericList * -next_list (Visitor *v,GenericList **list,Error **errp) +next_list (Visitor *v,GenericList *list,Error **errp) {StringOutputVisitor *sov =to_sov (v); -GenericList *ret =NULL ; -if (*list) { -if (sov->head) { - ret = *list; - }else { - ret = (*list)->next; - } +GenericList *ret = list->next; -if (sov->head) { -if (ret && ret->next ==NULL ) { - sov->list_mode =LM_NONE ; - } - sov->head = false; - }else { -if (ret && ret->next ==NULL ) { - sov->list_mode =LM_END ; - } - } +if (ret && !ret->next) { + sov->list_mode =LM_END ; } -return ret; }
@@ -312,8 +300,6 @@ end_list(Visitor *v) sov->list_mode ==LM_NONE || sov->list_mode == LM_IN_PROGRESS); sov->list_mode =LM_NONE ; - sov->head = true; - }char *string_output_get_string (StringOutputVisitor *sov)
scripts/qapi-visit.py +12 -9
@@ -125,20 +125,23 @@ def gen_visit_list(name, element_type): void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) { Error *err = NULL; - GenericList *i, **prev; + %(c_name)s *elt; - visit_start_list(v, name, &err); + visit_start_list(v, name, (GenericList **)obj, &err); if (err) { goto out; } - - for (prev = (GenericList **)obj; - !err && (i = visit_next_list(v, prev, &err)) != NULL; - prev = &i) { - %(c_name)s *native_i = (%(c_name)s *)i; - visit_type_%(c_elt_type)s(v, NULL, &native_i->value, &err); + elt = *obj; + while (elt) { + visit_type_%(c_elt_type)s(v, NULL, &elt->value, &err); + if (err) { + break; + } + elt = (%(c_name)s *)visit_next_list(v, (GenericList *)elt, &err); + if (err) { + break; + } } - visit_end_list(v); out: error_propagate(errp, err);
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 34/37] qapi: Simplify semantics of visit_next_list()
Quoted 9 lines · Eric Blake
We have two uses of list visits in the entire code base: one in
spapr_drc(which completely avoidsvisit_next_list(), feeding in integers from a different source than uint8List), and one inqapi-visit.py(that is, all other list visitors are generated inqapi-visit.c, and share the same paradigm based on a qapi FooList type). What's more, the semantics of the list visit are somewhat baroque, with the following pseudocode when FooList is used:
Quoted 4 lines
start()
prev = head
while (cur = next(prev)) {
visit(cur)
Actually, we pass &cur->value to the element visit.
Quoted 16 lines
prev = &cur
}Note that these semantics (advance before visit) requires that the first call to
next()return the list head, while all other calls return the next element of the list; that is, every visitor implementation is required to track extra state to decide whether to return the input as-is, or to advance. It also requires an argument of 'GenericList **' tonext(), solely because the first iteration might need to modify the caller's GenericList head, so that all other calls have to do a layer of dereferencing.We can greatly simplify things by hoisting the special case into the
start()routine, and flipping the order in the loop to visit before advance:
Quoted 6 lines
start(head)
element = *head
while (element) {
visit(element)
element = next(element)
}
@element isn't a list element, it's a list node. Suggest
start(head)
tail = *head
while (tail) {
visit(&tail->value)
tail = next(tail)
}Of course, this pseudo-code just screams to be a for-loop instead:
for (tail = *head; tail; tail = next(tail)) ...
May or may not be an improvement of the real code. The pseudo-code should follow the real code.
Quoted 32 lines
With the simpler semantics, visitors have less state to track, the argument to
next()is reduced to 'GenericList *', and it also becomes obvious whether an input visitor is allocating a FooList duringvisit_start_list()(rather than the old way of not knowing if an allocation happened until the firstvisit_next_list()).The signature of
visit_start_list()is chosen to matchvisit_start_struct(), with the new parameter after 'name'.The
spapr_drccase requires thatvisit_start_list()has to pay attention to whethervisit_next_list()will even be used to visit a FooList qapi struct; this is done by passing NULL for list, similarly to how NULL is passed tovisit_start_struct()when a qapi type is not used in those visits. It was easy to provide these semantics for qmp-output and dealloc visitors, and a bit harder for qmp-input (it required hoisting the advance of the current qlist entry out ofqmp_input_next_list()intoqmp_input_get_object()). But it turned out that the string and opts visitors munge enough state duringvisit_next_list()to make those conversions simpler if they require a GenericList visit for now; an assertion will remind us to adjust things if we need the semantics in the future.Signed-off-by Eric Blake <[email protected]>Reviewed-by Marc-André Lureau <[email protected]>---
v9: no change
v8: consistent parameter order, fixqmp_input_get_next_type()to not skip list entries
v7: new patch
Quoted 13 lines
--- hw/ppc/spapr_drc.c | 2 +- include/qapi/visitor-impl.h | 5 ++-- include/qapi/visitor.h | 45 +++++++++++++++++-------------- qapi/opts-visitor.c | 32 +++++++++------------- qapi/qapi-dealloc-visitor.c | 29 +++++--------------- qapi/qapi-visit-core.c | 7 ++--- qapi/qmp-input-visitor.c | 64 +++++++++++++++++++++----------------------- qapi/qmp-output-visitor.c | 21 +++------------ qapi/string-input-visitor.c | 34 +++++++++++------------ qapi/string-output-visitor.c | 36 ++++++++----------------- scripts/qapi-visit.py | 21 ++++++++------- 11 files changed, 126 insertions(+), 170 deletions(-)
Diffstat suggests it's indeed a simplification.
Quoted 19 lines
hw/ppc/spapr_drc.c +1
-1@@ -299,7 +299,7 @@ static void prop_get_fdt(Object *obj, Visitor *v, const char *name,int i; prop =fdt_get_property_by_offset (fdt, fdt_offset, &prop_len); name =fdt_string (fdt,fdt32_to_cpu (prop->nameoff)); -visit_start_list (v, name, &err); +visit_start_list (v, name,NULL , &err);if (err) {error_propagate (errp, err);return ;include/qapi/visitor-impl.h +0
-0
include/qapi/visitor-impl.h struct Visitor · line 46
Quoted 9 lines
include/qapi/visitor-impl.h +3
-2@@ -40,9 +40,10 @@ struct Visitorvoid (*end_implicit_struct)(Visitor *v);/* Must be set */ -void (*start_list)(Visitor *v,const char *name,Error **errp); +void (*start_list)(Visitor *v,const char *name,GenericList **list, +Error **errp);/* Must be set */ - GenericList *(*next_list)(Visitor *v, GenericList **list, Error **errp); + GenericList *(*next_list)(Visitor *v, GenericList *element, Error **errp);
You rename the parameter here, but not in the implementations.
The parameter isn't a list element, it's a list node. If we want to rename it, what about tail?
include/qapi/visitor.h line 4
Quoted 12 lines
include/qapi/visitor-impl.h +0
-0/* Must be set */ void (*end_list)(Visitor *v);include/qapi/visitor.h +1
-0@@ -1,6 +1,7 @@/* * Core Definitions for QAPI Visitor Classes * +* Copyright (C) 2015 Red Hat, Inc.
It's 2016 now. I'd make it 2012-2016.
Quoted 11 lines
include/qapi/visitor.h +0
-4* Copyright IBM, Corp. 2011 * * Authors: @@ -111,32 +112,36 @@ void visit_end_implicit_struct(Visitor *v);/** * Prepare to visit a list tied to an object key @name. * @name will be NULL if this is visited as part of another list. -* After calling this, the elements must be collected until -* visit_next_list() returns NULL, then visit_end_list() must be -* used to complete the visit. -*/
include/qapi/visitor.h void visit_end_implicit_struct(Visitor *v); · line 115
Quoted 10 lines
include/qapi/visitor.h +1
-9-void visit_start_list (Visitor *v,const char *name,Error **errp); -/** -* Iterate over a GenericList during a list visit. -* @list must not be NULL; on the first call, @list contains the -* address of the list head, and on subsequent calls *@list must be -* the previously returned value. Must be called in a loop until a -* NULL return or error occurs; for each non-NULL return, the caller -* must then call the appropriate visit_type_*() for the element type -* of the list, with that function's name parameter set to NULL. +* Input visitors malloc a qapi List struct into *@list,
QAPI
What's a QAPI list struct? I guess you mean GenericList.
include/qapi/visitor.h void visit_end_implicit_struct(Visitor *v); · line 117
Quoted 2 lines
include/qapi/visitor.h +1
-0or set it to + * NULL if there are no elements in the list;
So start_list() now needs to know whether the list is empty.
visit_start_struct() has an "if @obj is not NULL" clause here. Do we need the equivalent "if @list is not NULL"? Ah, you do that further down! Can we structure the two comments the same way?
include/qapi/visitor.h void visit_end_implicit_struct(Visitor *v); · line 119
Quoted 2 lines
include/qapi/visitor.h +1
-0and output visitors + * expect *@list to point to the start of the list, if any.
Perhaps "to the first list node, if any", and give GenericList a better comment in PATCH 21:
/*
* Generic list node
* Any generated QAPI FOOList struct pointer can be safely cast to
* GenericList * and dereferenced.
*/
Of course, this actually assumes uniform pointer representation, which is not guaranteed by the standard.
Should we mention output visitors don't change *@list? Same for visit_start_struct(), by the way.
What about the dealloc visitor?
include/qapi/visitor.h void visit_end_implicit_struct(Visitor *v); · line 121
Quoted 5 lines
include/qapi/visitor.h +4
-0On + * return, if *@list is non-NULL, the caller should enter a loop + * visiting the current element, then using visit_next_list() to + * advance to the next element, until that returns NULL; then + * visit_end_list() must be used to complete the visit.
For visit_start_struct() this part reads:
The
* caller then makes a series of visit calls for each key expected in
* the object, where those visits set their respective obj parameter
* to the address of a member of the qapi struct, and follows
* everything by a call to visit_end_struct() to clean up resources.
Following that pattern here, I get:
The caller then visits the list elements in turn, where those visits get passed the address of the list element within the QAPI list node. The caller normally uses visit_next_list() to step through the list. When done, it must call visit_end_list() to clean up.
include/qapi/visitor.h void visit_end_implicit_struct(Visitor *v); · line 123
Quoted 8 lines
include/qapi/visitor.h +1
-6* -* Note that for some visitors (qapi-dealloc and qmp-output), when a -* qapi GenericList linked list is not being used (comparable to when -* a NULL obj is used for visit_start_struct()), it is acceptable to -* bypass the use of visit_next_list() and just directly call the -* appropriate visit_type_*() for each element in between the -* visit_start_list() and visit_end_list() calls. +* If supported by a visitor, @list can be NULL to indicate that there
by the visitor
include/qapi/visitor.h void visit_end_implicit_struct(Visitor *v); · line 127
Quoted 4 lines
include/qapi/visitor.h +4
-0+* is no qapi List struct, and that the upcoming visit calls are +* parsing input to or creating output from some other representation; +* in this case, visit_next_list() will not be needed, but +* visit_end_list() is still mandatory.
You first explain normal usage, then add this paragraph to explain special usage. I like that better than the visit_start_struct() comment, where the special usage comes earlier.
Quoted 7 lines
include/qapi/visitor.h +1
-1* * FIXME: For input visitors, *@list can be assigned here even if * later visits will fail; this can lead to memory leaks if clients * aren't careful. */ -GenericList *visit_next_list (Visitor *v,GenericList **list,Error **errp); +void visit_start_list(Visitor *v, const char *name, GenericList **list,
include/qapi/visitor.h void visit_end_implicit_struct(Visitor *v); · line 143
Quoted 10 lines
include/qapi/visitor.h +10
-0+ Error **errp); +/** +* Iterate over a GenericList during a list visit. +* Before calling this function, the caller should use the appropriate +* visit_type_FOO() for the current list element at @element->value, and +* check for errors. @element must not be NULL; on the first iteration, +* it should be the value in *list after visit_start_list(); on other +* calls it should be the previous return value. This function +* returns NULL once there are no further list elements. +*/
I feel if we get visit_start_list()'s comment right, then this one can concentrate on what this function does, and leave intended usage of the start/next/end team to visit_start_list()'s comment.
Quoted 20 lines
include/qapi/visitor.h +1
-0+GenericList *visit_next_list (Visitor *v,GenericList *element,Error **errp);/**
* Complete the list started earlier.
* Must be called after any successful use ofvisit_start_list(),qapi/opts-visitor.c +1
-2@@ -21,9 +21,8 @@enum ListMode {LM_NONE ,/* not traversing a list of repeated options */ -LM_STARTED ,/* opts_start_list() succeeded */ -LM_IN_PROGRESS ,/* opts_next_list() has been called. +LM_IN_PROGRESS ,/* opts_next_list() ready to be called. * * Generating the next list link will consume the most * recently parsed QemuOpt instance of the repeated
qapi/opts-visitor.c lookup_distinct(const OptsVisitor *ov, const char *name, Error **errp) · line 214
Quoted 5 lines
qapi/opts-visitor.c +1
-1@@ -212,35 +211,32 @@ lookup_distinct(const OptsVisitor *ov, const char *name, Error **errp)static void -opts_start_list (Visitor *v,const char *name,Error **errp) +opts_start_list (Visitor *v,const char *name,GenericList **list,Error **errp)
I'd break this line before Error.
qapi/opts-visitor.c lookup_distinct(const OptsVisitor *ov, const char *name, Error **errp) · line 221
Quoted 7 lines
qapi/opts-visitor.c +2
-0{OptsVisitor *ov =to_ov (v);/* we can't traverse a list in a list */ assert (ov->list_mode ==LM_NONE ); +/* we don't support visits without GenericList, yet */ +assert (list);
Aha, this is why you wrote "If supported by a visitor". The visitors better document what they support then.
Quoted 52 lines
qapi/opts-visitor.c +8
-14ov->repeated_opts =lookup_distinct (ov, name, errp); -if (ov->repeated_opts !=NULL ) { - ov->list_mode =LM_STARTED ; +if (ov->repeated_opts) { + ov->list_mode =LM_IN_PROGRESS ; + *list =g_new0 (GenericList,1 ); + }else { + *list =NULL ; } }static GenericList * -opts_next_list (Visitor *v,GenericList **list,Error **errp) +opts_next_list (Visitor *v,GenericList *list,Error **errp) {OptsVisitor *ov =to_ov (v); -GenericList **link;switch (ov->list_mode) { -case LM_STARTED : - ov->list_mode =LM_IN_PROGRESS ; - link = list; -break ; -case LM_SIGNED_INTERVAL :case LM_UNSIGNED_INTERVAL : - link = &(*list)->next; -if (ov->list_mode ==LM_SIGNED_INTERVAL ) {if (ov->range_next.s < ov->range_limit.s) { ++ov->range_next.s;@@ -261,7 +257,6 @@ opts_next_list(Visitor *v, GenericList **list, Error **errp)g_hash_table_remove (ov->unprocessed_opts, opt->name);return NULL ; } - link = &(*list)->next;break ; }@@ -269,8 +264,8 @@ opts_next_list(Visitor *v, GenericList **list, Error **errp)abort (); } - *link =g_malloc0 (sizeof **link); -return *link; + list->next =g_new0 (GenericList,1 ); +return list->next; }
qapi/opts-visitor.c opts_end_list(Visitor *v) · line 280
Quoted 9 lines
qapi/opts-visitor.c +1
-2@@ -279,8 +274,7 @@ opts_end_list(Visitor *v) {OptsVisitor *ov =to_ov (v); -assert (ov->list_mode ==LM_STARTED || - ov->list_mode ==LM_IN_PROGRESS || +assert (ov->list_mode ==LM_IN_PROGRESS || ov->list_mode ==LM_SIGNED_INTERVAL || ov->list_mode ==LM_UNSIGNED_INTERVAL ); ov->repeated_opts =NULL ;
Only slight simplification for this visitor: we lose LM_STARTED.
Quoted 24 lines
qapi/qapi-dealloc-visitor.c +0
-5@@ -20,7 +20,6 @@typedef struct StackEntry {void *value; -bool is_list_head;QTAILQ_ENTRY (StackEntry) node; }StackEntry ;@@ -41,10 +40,6 @@ static void qapi_dealloc_push(QapiDeallocVisitor *qov, void *value) e->value = value; -/* see if we're just pushing a list head tracker */ -if (value ==NULL ) { - e->is_list_head = true; - }QTAILQ_INSERT_HEAD (&qov->stack, e, node); }
qapi/qapi-dealloc-visitor.c static void qapi_dealloc_end_implicit_struct(Visitor *v) · line 94
Quoted 9 lines
qapi/qapi-dealloc-visitor.c +2
-1@@ -92,31 +87,19 @@ static void qapi_dealloc_end_implicit_struct(Visitor *v) } } -static void qapi_dealloc_start_list (Visitor *v,const char *name,Error **errp) +static void qapi_dealloc_start_list (Visitor *v,const char *name, +GenericList **list,Error **errp) {QapiDeallocVisitor *qov =to_qov (v);qapi_dealloc_push (qov,NULL );
Do we still need to push/pop for a list?
If yes, can we push list instead of NULL? Pointers always become more complicated when they can be null...
Quoted 16 lines
qapi/qapi-dealloc-visitor.c +1
-11} -static GenericList *qapi_dealloc_next_list (Visitor *v,GenericList **listp, +static GenericList *qapi_dealloc_next_list (Visitor *v,GenericList *list,Error **errp) { -GenericList *list = *listp; -QapiDeallocVisitor *qov =to_qov (v); -StackEntry *e =QTAILQ_FIRST (&qov->stack); - -if (e && e->is_list_head) { - e->is_list_head = false; -return list; - } - -if (list) {
qapi/qapi-dealloc-visitor.c static void qapi_dealloc_end_implicit_struct(Visitor *v) · line 103
Quoted 10 lines
qapi/qapi-dealloc-visitor.c +3
-6- list = list->next; -g_free (*listp); -return list; - } - -return NULL ; +GenericList *next = list->next; +g_free (list); +return next; }
Okay, this is actually a more worthwhile simplification.
Quoted 44 lines
qapi/qapi-dealloc-visitor.c +0
-0static void qapi_dealloc_end_list (Visitor *v)qapi/qapi-visit-core.c +4
-3@@ -67,12 +67,13 @@ void visit_end_implicit_struct(Visitor *v) } } -void visit_start_list (Visitor *v,const char *name,Error **errp) +void visit_start_list (Visitor *v,const char *name,GenericList **list, +Error **errp) { - v->start_list (v, name, errp); + v->start_list (v, name, list, errp); } -GenericList *visit_next_list (Visitor *v,GenericList **list,Error **errp) +GenericList *visit_next_list (Visitor *v,GenericList *list,Error **errp) {assert (list);return v->next_list (v, list, errp);qapi/qmp-input-visitor.c +7
-3@@ -44,16 +44,20 @@ static QObject *qmp_input_get_object(QmpInputVisitor *qiv,const char *name, bool consume) { - QObject *qobj = qiv->stack[qiv->nb_stack - 1].obj; + StackObject *so = &qiv->stack[qiv->nb_stack - 1]; +QObject *qobj = so->obj;if (qobj) {if (name &&qobject_type (qobj) ==QTYPE_QDICT ) { -if (qiv->stack[qiv->nb_stack -1 ].h && consume) { -g_hash_table_remove (qiv->stack[qiv->nb_stack -1 ].h, name); +if (so->h && consume) { +g_hash_table_remove (so->h, name); + } + qobj =qdict_get (qobject_to_qdict (qobj), name); + }else if (so->entry) {
qapi/qmp-input-visitor.c static QObject *qmp_input_get_object(QmpInputVisitor *qiv, · line 63
Quoted 10 lines
qapi/qmp-input-visitor.c +3
-3+ qobj =qlist_entry_obj (so->entry); +if (consume) { + so->entry =qlist_next (so->entry); } -return qdict_get (qobject_to_qdict (qobj), name); - }else if (qiv->stack[qiv->nb_stack -1 ].entry) { -return qlist_entry_obj (qiv->stack[qiv->nb_stack -1 ].entry); } }
Much easier to read if split into two steps:
1. Capture the pointer to the top of the stack in a variable
@@ -44,16 +44,17 @@ static QObject *qmp_input_get_object(QmpInputVisitor *qiv,
const char *name,
bool consume)
{
- QObject *qobj = qiv->stack[qiv->nb_stack - 1].obj; + StackObject *so = &qiv->stack[qiv->nb_stack - 1]; + QObject *qobj = so->obj;
if (qobj) {
if (name && qobject_type(qobj) == QTYPE_QDICT) {
- if (qiv->stack[qiv->nb_stack - 1].h && consume) {
- g_hash_table_remove(qiv->stack[qiv->nb_stack - 1].h, name);
+ if (so->h && consume) {
+ g_hash_table_remove(so->h, name);
}
return qdict_get(qobject_to_qdict(qobj), name);
- } else if (qiv->stack[qiv->nb_stack - 1].entry) {
- return qlist_entry_obj(qiv->stack[qiv->nb_stack - 1].entry);
+ } else if (so->entry) {
+ return qlist_entry_obj(so->entry);
}
}2. Make the actual change
@@ -52,9 +52,12 @@ static QObject *qmp_input_get_object(QmpInputVisitor *qiv,
if (so->h && consume) {
g_hash_table_remove(so->h, name);
}
- return qdict_get(qobject_to_qdict(qobj), name);
+ qobj = qdict_get(qobject_to_qdict(qobj), name);
} else if (so->entry) {
- return qlist_entry_obj(so->entry);
+ qobj = qlist_entry_obj(so->entry);
+ if (consume) {
+ so->entry = qlist_next(so->entry);
+ }
}
}
return qobj;I'd call the new variable tos (top of stack) instead of so. Needs a matching rename in qmp_input_next_list().
Note that @consume is true unless we're called from qmp_input_get_next_type(). What is it supposed to do? Can it be true in the place where you add a use?
Since we're cleaning up the function anyway in step 1, I'd be tempted to reduce its nesting:
if (!qobj) {
return NULL;
} else if (name && qobject_type(qobj) == QTYPE_QDICT) {
if (tos->h && consume) {
g_hash_table_remove(tos->h, name);
}
return qdict_get(qobject_to_qdict(qobj), name);
} else if (tos->entry) {
return qlist_entry_obj(tos->entry);
} else {
return qobj;
}Immediately begs the question what the four cases mean. Unobvious enough to justify comments, I think.
What's the stack's contents? You cleaned that up and documented it in qmp-output-visitor.c. Same treatment here?
qapi/qmp-input-visitor.c static void qdict_add_key(const char *key, QObject *obj, void *opaque) · line 77
Quoted 10 lines
qapi/qmp-input-visitor.c +2
-1@@ -66,7 +70,8 @@ static void qdict_add_key(const char *key, QObject *obj, void *opaque)g_hash_table_insert (h, (gpointer ) key,NULL ); } -static void qmp_input_push (QmpInputVisitor *qiv,QObject *obj,Error **errp) +static void qmp_input_push (QmpInputVisitor *qiv,QObject *obj, +const QListEntry *entry,Error **errp) {GHashTable *h;
if (qiv->nb_stack >= QIV_STACK_SIZE) {
error_setg(errp, "An internal buffer overran");
return;
}Aside: this is stupid, realloc() exists. It's less stupid than the qmp-output-visitor.c's tail queue, though.
Quoted 10 lines
qapi/qmp-input-visitor.c +1
-1@@ -76,7 +81,7 @@ static void qmp_input_push(QmpInputVisitor *qiv, QObject *obj, Error **errp) } qiv->stack[qiv->nb_stack].obj = obj; - qiv->stack[qiv->nb_stack].entry =NULL ; + qiv->stack[qiv->nb_stack].entry = entry; qiv->stack[qiv->nb_stack].h =NULL ;if (qiv->strict &&qobject_type (obj) ==QTYPE_QDICT ) {
qapi/qmp-input-visitor.c static void qmp_input_start_struct(Visitor *v, const char *name, void **obj, · line 149
Quoted 8 lines
qapi/qmp-input-visitor.c +1
-1@@ -138,7 +143,7 @@ static void qmp_input_start_struct(Visitor *v, const char *name, void **obj,return ; } -qmp_input_push (qiv, qobj, &err); +qmp_input_push (qiv, qobj,NULL , &err);if (err) {error_propagate (errp, err);return ;
The stack entry for a struct being visited has obj = its source QDict, entry = NULL.
Quoted 15 lines
qapi/qmp-input-visitor.c +3
-1@@ -158,10 +163,12 @@ static void qmp_input_start_implicit_struct(Visitor *v, void **obj, } } -static void qmp_input_start_list (Visitor *v,const char *name,Error **errp) +static void qmp_input_start_list (Visitor *v,const char *name, +GenericList **list,Error **errp) {QmpInputVisitor *qiv =to_qiv (v);QObject *qobj =qmp_input_get_object (qiv, name, true); +const QListEntry *entry;if (!qobj ||qobject_type (qobj) !=QTYPE_QLIST ) { error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",
qapi/qmp-input-visitor.c static void qmp_input_start_list(Visitor *v, const char *name, Error **errp) · line 180
Quoted 6 lines
qapi/qmp-input-visitor.c +2
-1@@ -169,37 +176,28 @@ static void qmp_input_start_list(Visitor *v, const char *name, Error **errp)return ; } -qmp_input_push (qiv, qobj, errp); + entry =qlist_first (qobject_to_qlist (qobj)); +qmp_input_push (qiv, qobj, entry, errp);
The stack entry for a list being visited has obj = its source QList, entry = NULL.
Quoted 45 lines
qapi/qmp-input-visitor.c +11
-21+if (list) { +if (entry) { + *list =g_new0 (GenericList,1 ); + }else { + *list =NULL ; + } + } } -static GenericList *qmp_input_next_list (Visitor *v,GenericList **list, +static GenericList *qmp_input_next_list (Visitor *v,GenericList *list,Error **errp) {QmpInputVisitor *qiv =to_qiv (v); -GenericList *entry;StackObject *so = &qiv->stack[qiv->nb_stack -1 ]; -bool first; -if (so->entry ==NULL ) { - so->entry =qlist_first (qobject_to_qlist (so->obj)); - first = true; - }else { - so->entry =qlist_next (so->entry); - first = false; - } - -if (so->entry ==NULL ) { +if (!so->entry) {return NULL ; } - - entry =g_malloc0 (sizeof (*entry)); -if (first) { - *list = entry; - }else { - (*list)->next = entry; - } - -return entry; + list->next =g_new0 (GenericList,1 ); +return list->next; }
qapi/qmp-input-visitor.c QmpInputVisitor *qmp_input_visitor_new(QObject *obj) · line 376
Quoted 5 lines
qapi/qmp-input-visitor.c +1
-1@@ -375,7 +373,7 @@ QmpInputVisitor *qmp_input_visitor_new(QObject *obj) v->visitor.optional = qmp_input_optional; v->visitor.get_next_type = qmp_input_get_next_type; -qmp_input_push (v, obj,NULL ); +qmp_input_push (v, obj,NULL ,NULL );
The stack entry for the root value being visited has obj = its source QObject, entry = NULL.
Quoted 48 lines
qapi/qmp-input-visitor.c +0
-0qobject_incref (obj);return v;qapi/qmp-output-visitor.c +3
-11@@ -21,7 +21,6 @@typedef struct QStackEntry {QObject *value; -bool is_list_head;QTAILQ_ENTRY (QStackEntry) node; }QStackEntry ;@@ -51,9 +50,6 @@ static void qmp_output_push_obj(QmpOutputVisitor *qov, QObject *value)assert (qov->root);assert (value); e->value = value; -if (qobject_type (e->value) ==QTYPE_QLIST ) { - e->is_list_head = true; - }QTAILQ_INSERT_HEAD (&qov->stack, e, node); }@@ -122,7 +118,8 @@ static void qmp_output_end_struct(Visitor *v)qmp_output_pop (qov,QTYPE_QDICT ); } -static void qmp_output_start_list (Visitor *v,const char *name,Error **errp) +static void qmp_output_start_list (Visitor *v,const char *name, +GenericList **listp,Error **errp) {QmpOutputVisitor *qov =to_qov (v);QList *list =qlist_new ();@@ -131,20 +128,10 @@ static void qmp_output_start_list(Visitor *v, const char *name, Error **errp)qmp_output_push (qov, list); } -static GenericList *qmp_output_next_list (Visitor *v,GenericList **listp, +static GenericList *qmp_output_next_list (Visitor *v,GenericList *list,Error **errp) { -GenericList *list = *listp; -QmpOutputVisitor *qov =to_qov (v); -QStackEntry *e =QTAILQ_FIRST (&qov->stack); - -assert (e);
qapi/qmp-output-visitor.c static void qmp_output_start_list(Visitor *v, const char *name, Error **errp) · line 137
Quoted 10 lines
qapi/qmp-output-visitor.c +1
-6-if (e->is_list_head) { - e->is_list_head = false; -return list; - } - -return list ? list->next :NULL ; +return list->next; }static void qmp_output_end_list (Visitor *v)
A simple one, for a change.
Quoted 22 lines
qapi/string-input-visitor.c +2
-3@@ -23,8 +23,6 @@ struct StringInputVisitor {Visitor visitor; -bool head; -GList *ranges;GList *cur_range;int64_t cur;@@ -123,11 +121,19 @@ error: }static void -start_list (Visitor *v,const char *name,Error **errp) +start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {StringInputVisitor *siv =to_siv (v); +Error *err =NULL ;
qapi/string-input-visitor.c error: · line 136
Quoted 10 lines
qapi/string-input-visitor.c +8
-1-parse_str (siv, errp); +/* We don't support visits without a GenericList, yet */ +assert (list); + +parse_str (siv, &err); +if (err) { +error_propagate (errp, err); +return ; + }
Should you set *@list = NULL on error?
Does this handle parse_str() error correctly before your patch?
qapi/string-input-visitor.c start_list(Visitor *v, const char *name, Error **errp) · line 148
Quoted 12 lines
qapi/string-input-visitor.c +3
-0siv->cur_range =g_list_first (siv->ranges);if (siv->cur_range) {@@ -135,14 +141,16 @@ start_list(Visitor *v, const char *name, Error **errp)if (r) { siv->cur = r->begin; } + *list =g_new0 (GenericList,1 ); + }else { + *list =NULL ; } }
If it does, then this must be the reason you have to bail out on error.
Quoted 63 lines
qapi/string-input-visitor.c +3
-14static GenericList * -next_list (Visitor *v,GenericList **list,Error **errp) +next_list (Visitor *v,GenericList *list,Error **errp) {StringInputVisitor *siv =to_siv (v); -GenericList **link;Range *r;if (!siv->ranges || !siv->cur_range) {@@ -166,22 +174,13 @@ next_list(Visitor *v, GenericList **list, Error **errp) siv->cur = r->begin; } -if (siv->head) { - link = list; - siv->head = false; - }else { - link = &(*list)->next; - } - - *link =g_malloc0 (sizeof **link); -return *link; + list->next =g_new0 (GenericList,1 ); +return list->next; }static void end_list (Visitor *v) { -StringInputVisitor *siv =to_siv (v); - siv->head = true; } static void parse_type_int64(Visitor *v, const char *name, int64_t *obj,@@ -361,6 +360,5 @@ StringInputVisitor *string_input_visitor_new(const char *str) v->visitor.optional = parse_optional; v->string = str; - v->head = true;return v; }qapi/string-output-visitor.c +1
-2@@ -57,7 +57,6 @@ struct StringOutputVisitorVisitor visitor;bool human;GString *string; -bool head;ListMode list_mode;union {int64_t s;@@ -265,40 +264,29 @@ static void print_type_number(Visitor *v, const char *name, double *obj, }static void -start_list (Visitor *v,const char *name,Error **errp) +start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {StringOutputVisitor *sov =to_sov (v);
qapi/string-output-visitor.c static void print_type_number(Visitor *v, const char *name, double *obj, · line 278
Quoted 10 lines
qapi/string-output-visitor.c +6
-2/* we can't traverse a list in a list */ assert (sov->list_mode ==LM_NONE ); - sov->list_mode =LM_STARTED ; - sov->head = true; +/* We don't support visits without a GenericList, yet */ +assert (list); +/* List handling is only needed if there are at least two elements */ +if (*list && (*list)->next) { + sov->list_mode =LM_STARTED ; + }
Contradicts the comment next to LM_STARTED: /* start_list() succeeded */
Why do you need to stay in state LM_NONE for shorter lists now?
Quoted 22 lines
qapi/string-output-visitor.c +2
-14}static GenericList * -next_list (Visitor *v,GenericList **list,Error **errp) +next_list (Visitor *v,GenericList *list,Error **errp) {StringOutputVisitor *sov =to_sov (v); -GenericList *ret =NULL ; -if (*list) { -if (sov->head) { - ret = *list; - }else { - ret = (*list)->next; - } +GenericList *ret = list->next; -if (sov->head) { -if (ret && ret->next ==NULL ) { - sov->list_mode =LM_NONE ; - } - sov->head = false; - }else {
qapi/string-output-visitor.c static void print_type_number(Visitor *v, const char *name, double *obj, · line 291
Quoted 10 lines
qapi/string-output-visitor.c +2
-5-if (ret && ret->next ==NULL ) { - sov->list_mode =LM_END ; - } - } +if (ret && !ret->next) { + sov->list_mode =LM_END ; } -return ret; }
What does state LM_END mean? It has no comment...
qapi/string-output-visitor.c end_list(Visitor *v) · line 305
Quoted 10 lines
qapi/string-output-visitor.c +0
-2@@ -312,8 +300,6 @@ end_list(Visitor *v) sov->list_mode ==LM_NONE || sov->list_mode == LM_IN_PROGRESS); sov->list_mode =LM_NONE ; - sov->head = true; - }char *string_output_get_string (StringOutputVisitor *sov)
Unless I'm blind, no next_list() implementation sets an error. Drop parameter errp and simplify?
scripts/qapi-visit.py def gen_visit_list(name, element_type): · line 128
Quoted 10 lines
scripts/qapi-visit.py +1
-1@@ -125,20 +125,23 @@ def gen_visit_list(name, element_type): void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) { Error *err = NULL; - GenericList *i, **prev; + %(c_name)s *elt;
This isn't an element, it's a list node. I'd call it tail.
Sure changing its type from GenericList to the specific one saves casts?
Quoted 13 lines
scripts/qapi-visit.py +2
-7- visit_start_list(v, name, &err); + visit_start_list(v, name, (GenericList **)obj, &err); if (err) { goto out; } - - for (prev = (GenericList **)obj; - !err && (i = visit_next_list(v, prev, &err)) != NULL; - prev = &i) { - %(c_name)s *native_i = (%(c_name)s *)i; - visit_type_%(c_elt_type)s(v, NULL, &native_i->value, &err); + elt = *obj;
scripts/qapi-visit.py def gen_visit_list(name, element_type): · line 144
Quoted 10 lines
scripts/qapi-visit.py +9
-0+ while (elt) { + visit_type_%(c_elt_type)s(v, NULL, &elt->value, &err); + if (err) { + break; + } + elt = (%(c_name)s *)visit_next_list(v, (GenericList *)elt, &err); + if (err) { + break; + } }
With a simplified next_list(), this could be a nice for-loop:
for (tail = *obj; tail; tail = visit_next_list(v, tail, &err)) ...
Quoted 4 lines
scripts/qapi-visit.py +0
-1- visit_end_list(v); out: error_propagate(errp, err);
PATCH v9 35/37 qapi: Change visit_type_FOO() to no longer return partial objects
In reply to Eric BlakeReturning a partial object on error is an invitation for a careless caller to leak memory. As no one outside the testsuite was actually relying on these semantics, it is cleaner to just document and guarantee that ALL pointer-based visit_type_FOO() functions always leave a safe value in *obj during an input visitor (either the new object on success, or NULL if an error is encountered).
Since input visitors have blind assignment semantics, we have to track the result of whether an assignment is made all the way down to each visitor callback implementation, to avoid making decisions based on potentially uninitialized storage.
Note that we still leave *obj unchanged after a scalar-based visit_type_FOO(); I did not feel like auditing all uses of visit_type_Enum() to see if the callers would tolerate a specific sentinel value (not to mention having to decide whether it would be better to use 0 or ENUM__MAX as that sentinel).
---
v9: fix bug in use of errp
v8: rebase to earlier changes
v7: rebase to earlier changes, enhance commit message, also fix visit_type_str() and visit_type_any()
v6: rebase on top of earlier doc and formatting improvements, mention that *obj can be uninitialized on entry to an input visitor, rework semantics to keep valgrind happy on uninitialized input, break some long lines
--- include/qapi/visitor-impl.h | 6 ++--- include/qapi/visitor.h | 53 ++++++++++++++++++++++++++++-------------- qapi/opts-visitor.c | 11 ++++++--- qapi/qapi-dealloc-visitor.c | 9 ++++--- qapi/qapi-visit-core.c | 45 ++++++++++++++++++++++++++++------- qapi/qmp-input-visitor.c | 18 +++++++++----- qapi/qmp-output-visitor.c | 6 +++-- qapi/string-input-visitor.c | 6 +++-- qapi/string-output-visitor.c | 3 ++- scripts/qapi-visit.py | 40 +++++++++++++++++++++++-------- tests/test-qmp-commands.c | 13 +++++------ tests/test-qmp-input-strict.c | 19 +++++++-------- tests/test-qmp-input-visitor.c | 10 ++------ 13 files changed, 157 insertions(+), 82 deletions(-)
include/qapi/visitor-impl.h +3 -3
@@ -26,7 +26,7 @@ struct Visitor {/* Must be provided to visit structs (the string visitors do not * currently visit structs). */ -void (*start_struct)(Visitor *v,const char *name,void **obj, +bool (*start_struct)(Visitor *v,const char *name,void **obj,size_t size,Error **errp);/* May be NULL; most useful for input visitors. */ void (*check_struct)(Visitor *v,Error **errp);
@@ -34,13 +34,13 @@ struct Visitorvoid (*end_struct)(Visitor *v);/* May be NULL; most useful for input visitors. */ -void (*start_implicit_struct)(Visitor *v,void **obj,size_t size, +bool (*start_implicit_struct)(Visitor *v,void **obj,size_t size,Error **errp);/* May be NULL */ void (*end_implicit_struct)(Visitor *v);/* Must be set */ -void (*start_list)(Visitor *v,const char *name,GenericList **list, +bool (*start_list)(Visitor *v,const char *name,GenericList **list,Error **errp);/* Must be set */ GenericList *(*next_list)(Visitor *v, GenericList *element, Error **errp);
include/qapi/visitor.h +36 -17
83 lines not on this page · raw message
qapi/opts-visitor.c +8 -3
@@ -122,18 +122,20 @@ opts_visitor_insert(GHashTable *unprocessed_opts, const QemuOpt *opt) } -static void +static bool opts_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp) {OptsVisitor *ov =to_ov (v);const QemuOpt *opt; +bool result = false;if (obj) { *obj =g_malloc0 (size >0 ? size :1 ); + result = true; }if (ov->depth++ >0 ) { -return ; +return result; } ov->unprocessed_opts = g_hash_table_new_full(&g_str_hash, &g_str_equal,
@@ -152,6 +154,7 @@ opts_start_struct(Visitor *v, const char *name, void **obj, ov->fake_id_opt->str =g_strdup (ov->opts_root->id);opts_visitor_insert (ov->unprocessed_opts, ov->fake_id_opt); } +return result; }
@@ -210,7 +213,7 @@ lookup_distinct(const OptsVisitor *ov, const char *name, Error **errp) } -static void +static bool opts_start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {OptsVisitor *ov =to_ov (v);
@@ -223,8 +226,10 @@ opts_start_list(Visitor *v, const char *name, GenericList **list, Error **errp)if (ov->repeated_opts) { ov->list_mode =LM_IN_PROGRESS ; *list =g_new0 (GenericList,1 ); +return true; }else { *list =NULL ; +return false; } }
qapi/qapi-dealloc-visitor.c +6 -3
@@ -53,11 +53,12 @@ static void *qapi_dealloc_pop(QapiDeallocVisitor *qov)return value; } -static void qapi_dealloc_start_struct (Visitor *v,const char *name,void **obj, +static bool qapi_dealloc_start_struct (Visitor *v,const char *name,void **obj,size_t unused,Error **errp) {QapiDeallocVisitor *qov =to_qov (v);qapi_dealloc_push (qov, obj); +return false; }static void qapi_dealloc_end_struct (Visitor *v)
@@ -69,13 +70,14 @@ static void qapi_dealloc_end_struct(Visitor *v) } } -static void qapi_dealloc_start_implicit_struct (Visitor *v, +static bool qapi_dealloc_start_implicit_struct (Visitor *v,void **obj,size_t size,Error **errp) {QapiDeallocVisitor *qov =to_qov (v);qapi_dealloc_push (qov, obj); +return false; }static void qapi_dealloc_end_implicit_struct (Visitor *v)
@@ -87,11 +89,12 @@ static void qapi_dealloc_end_implicit_struct(Visitor *v) } } -static void qapi_dealloc_start_list (Visitor *v,const char *name, +static bool qapi_dealloc_start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {QapiDeallocVisitor *qov =to_qov (v);qapi_dealloc_push (qov,NULL ); +return false; } static GenericList *qapi_dealloc_next_list(Visitor *v, GenericList *list,
qapi/qapi-visit-core.c +36 -9
107 lines not on this page · raw message
qapi/qmp-input-visitor.c +12 -6
@@ -130,7 +130,7 @@ static void qmp_input_pop(Visitor *v) qiv->nb_stack--; } -static void qmp_input_start_struct (Visitor *v,const char *name,void **obj, +static bool qmp_input_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp) {QmpInputVisitor *qiv =to_qiv (v);
@@ -140,30 +140,34 @@ static void qmp_input_start_struct(Visitor *v, const char *name, void **obj,if (!qobj ||qobject_type (qobj) !=QTYPE_QDICT ) {error_setg (errp,QERR_INVALID_PARAMETER_TYPE , name ? name :"null" ,"QDict" ); -return ; +return false; }qmp_input_push (qiv, qobj,NULL , &err);if (err) {error_propagate (errp, err); -return ; +return false; }if (obj) { *obj =g_malloc0 (size); +return true; } +return false; } -static void qmp_input_start_implicit_struct (Visitor *v,void **obj, +static bool qmp_input_start_implicit_struct (Visitor *v,void **obj,size_t size,Error **errp) {if (obj) { *obj =g_malloc0 (size); +return true; } +return false; } -static void qmp_input_start_list (Visitor *v,const char *name, +static bool qmp_input_start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {QmpInputVisitor *qiv =to_qiv (v);
@@ -173,7 +177,7 @@ static void qmp_input_start_list(Visitor *v, const char *name,if (!qobj ||qobject_type (qobj) !=QTYPE_QLIST ) {error_setg (errp,QERR_INVALID_PARAMETER_TYPE , name ? name :"null" ,"list" ); -return ; +return false; } entry =qlist_first (qobject_to_qlist (qobj));
@@ -181,10 +185,12 @@ static void qmp_input_start_list(Visitor *v, const char *name,if (list) {if (entry) { *list =g_new0 (GenericList,1 ); +return true; }else { *list =NULL ; } } +return false; } static GenericList *qmp_input_next_list(Visitor *v, GenericList *list,
qapi/qmp-output-visitor.c +4 -2
@@ -102,7 +102,7 @@ static void qmp_output_add_obj(QmpOutputVisitor *qov, const char *name, } } -static void qmp_output_start_struct (Visitor *v,const char *name,void **obj, +static bool qmp_output_start_struct (Visitor *v,const char *name,void **obj,size_t unused,Error **errp) {QmpOutputVisitor *qov =to_qov (v);
@@ -110,6 +110,7 @@ static void qmp_output_start_struct(Visitor *v, const char *name, void **obj,qmp_output_add (qov, name, dict);qmp_output_push (qov, dict); +return false; }static void qmp_output_end_struct (Visitor *v)
@@ -118,7 +119,7 @@ static void qmp_output_end_struct(Visitor *v)qmp_output_pop (qov,QTYPE_QDICT ); } -static void qmp_output_start_list (Visitor *v,const char *name, +static bool qmp_output_start_list (Visitor *v,const char *name,GenericList **listp,Error **errp) {QmpOutputVisitor *qov =to_qov (v);
@@ -126,6 +127,7 @@ static void qmp_output_start_list(Visitor *v, const char *name,qmp_output_add (qov, name, list);qmp_output_push (qov, list); +return false; } static GenericList *qmp_output_next_list(Visitor *v, GenericList *list,
qapi/string-input-visitor.c +4 -2
@@ -120,7 +120,7 @@ error: siv->ranges =NULL ; } -static void +static bool start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {StringInputVisitor *siv =to_siv (v);
@@ -132,7 +132,7 @@ start_list(Visitor *v, const char *name, GenericList **list, Error **errp)parse_str (siv, &err);if (err) {error_propagate (errp, err); -return ; +return false; } siv->cur_range =g_list_first (siv->ranges);
@@ -142,8 +142,10 @@ start_list(Visitor *v, const char *name, GenericList **list, Error **errp) siv->cur = r->begin; } *list =g_new0 (GenericList,1 ); +return true; }else { *list =NULL ; +return false; } }
qapi/string-output-visitor.c +2 -1
@@ -263,7 +263,7 @@ static void print_type_number(Visitor *v, const char *name, double *obj,string_output_set (sov,g_strdup_printf ("%f" , *obj)); } -static void +static bool start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {StringOutputVisitor *sov =to_sov (v);
@@ -276,6 +276,7 @@ start_list(Visitor *v, const char *name, GenericList **list, Error **errp)if (*list && (*list)->next) { sov->list_mode =LM_STARTED ; } +return false; } static GenericList *
scripts/qapi-visit.py +30 -10
@@ -58,8 +58,10 @@ def gen_visit_implicit_struct(typ): static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error **errp) { Error *err = NULL; + bool allocated; - visit_start_implicit_struct(v, (void **)obj, sizeof(%(c_type)s), &err); + allocated = visit_start_implicit_struct(v, (void **)obj, + sizeof(%(c_type)s), &err); if (err) { goto out; }
@@ -69,6 +71,10 @@ static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * visit_type_%(c_type)s_fields(v, obj, &err); out_obj: visit_end_implicit_struct(v); + if (allocated && err) { + g_free(*obj); + *obj = NULL; + } out: error_propagate(errp, err); }
@@ -116,18 +122,15 @@ out: def gen_visit_list(name, element_type): - # FIXME: if *obj is NULL on entry, and the first visit_next_list() - # assigns to *obj, while a later one fails, we should clean up *obj - # rather than leaving it non-NULL. As currently written, the caller must - # call qapi_free_FOOList() to avoid a memory leak of the partial FOOList. return mcgen(''' void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) { Error *err = NULL; %(c_name)s *elt; + bool allocated; - visit_start_list(v, name, (GenericList **)obj, &err); + allocated = visit_start_list(v, name, (GenericList **)obj, &err); if (err) { goto out; }
@@ -144,6 +147,10 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error } visit_end_list(v); out: + if (allocated && err) { + qapi_free_%(c_name)s(*obj); + *obj = NULL; + } error_propagate(errp, err); } ''',
@@ -174,8 +181,10 @@ def gen_visit_alternate(name, variants): void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) { Error *err = NULL; + bool allocated; - visit_start_implicit_struct(v, (void**) obj, sizeof(%(c_name)s), &err); + allocated = visit_start_implicit_struct(v, (void **)obj, + sizeof(%(c_name)s), &err); if (err) { goto out; }
@@ -204,11 +213,15 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error } out_obj: visit_end_implicit_struct(v); + if (allocated && err) { + qapi_free_%(c_name)s(*obj); + *obj = NULL; + } out: error_propagate(errp, err); } ''', - name=name) + name=name, c_name=c_name(name)) return ret
@@ -236,8 +249,10 @@ def gen_visit_object(name, base, members, variants): void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) { Error *err = NULL; + bool allocated; - visit_start_struct(v, name, (void **)obj, sizeof(%(c_name)s), &err); + allocated = visit_start_struct(v, name, (void **)obj, sizeof(%(c_name)s), + &err); if (err) { goto out; }
@@ -301,10 +316,15 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error visit_check_struct(v, &err); out_obj: visit_end_struct(v); + if (allocated && err) { + qapi_free_%(c_name)s(*obj); + *obj = NULL; + } out: error_propagate(errp, err); } -''') +''', + c_name=c_name(name)) return ret
tests/test-qmp-commands.c +6 -7
@@ -227,14 +227,13 @@ static void test_dealloc_partial(void)QDECREF (ud2_dict); } -/* verify partial success */ -assert (ud2 !=NULL ); -assert (ud2->string0 !=NULL ); -assert (strcmp (ud2->string0, text) ==0 ); -assert (ud2->dict1 ==NULL ); - -/* confirm & release construction error */ +/* verify that visit_type_XXX() cleans up properly on error */ error_free_or_abort (&err); +assert (!ud2); + +/* Manually create a partial object, leaving ud2->dict1 at NULL */ + ud2 =g_new0 (UserDefTwo,1 ); + ud2->string0 =g_strdup (text);/* tear down partial object */ qapi_free_UserDefTwo (ud2);
tests/test-qmp-input-strict.c +8 -11
@@ -181,10 +181,7 @@ static void test_validate_fail_struct(TestInputVisitorData *data,visit_type_TestStruct (v,NULL , &p, &err);error_free_or_abort (&err); -if (p) { -g_free (p->string); - } -g_free (p); +g_assert (!p); } static void test_validate_fail_struct_nested(TestInputVisitorData *data,
@@ -198,7 +195,7 @@ static void test_validate_fail_struct_nested(TestInputVisitorData *data,visit_type_UserDefTwo (v,NULL , &udp, &err);error_free_or_abort (&err); -qapi_free_UserDefTwo (udp); +g_assert (!udp); } static void test_validate_fail_list(TestInputVisitorData *data,
@@ -212,7 +209,7 @@ static void test_validate_fail_list(TestInputVisitorData *data,visit_type_UserDefOneList (v,NULL , &head, &err);error_free_or_abort (&err); -qapi_free_UserDefOneList (head); +g_assert (!head); } static void test_validate_fail_union_native_list(TestInputVisitorData *data,
@@ -227,7 +224,7 @@ static void test_validate_fail_union_native_list(TestInputVisitorData *data,visit_type_UserDefNativeListUnion (v,NULL , &tmp, &err);error_free_or_abort (&err); -qapi_free_UserDefNativeListUnion (tmp); +g_assert (!tmp); } static void test_validate_fail_union_flat(TestInputVisitorData *data,
@@ -241,7 +238,7 @@ static void test_validate_fail_union_flat(TestInputVisitorData *data,visit_type_UserDefFlatUnion (v,NULL , &tmp, &err);error_free_or_abort (&err); -qapi_free_UserDefFlatUnion (tmp); +g_assert (!tmp); } static void test_validate_fail_union_flat_no_discrim(TestInputVisitorData *data,
@@ -256,13 +253,13 @@ static void test_validate_fail_union_flat_no_discrim(TestInputVisitorData *data,visit_type_UserDefFlatUnion2 (v,NULL , &tmp, &err);error_free_or_abort (&err); -qapi_free_UserDefFlatUnion2 (tmp); +g_assert (!tmp); }static void test_validate_fail_alternate (TestInputVisitorData *data,const void *unused) { -UserDefAlternate *tmp =NULL ; +UserDefAlternate *tmp;Visitor *v;Error *err =NULL ;
@@ -270,7 +267,7 @@ static void test_validate_fail_alternate(TestInputVisitorData *data,visit_type_UserDefAlternate (v,NULL , &tmp, &err);error_free_or_abort (&err); -qapi_free_UserDefAlternate (tmp); +g_assert (!tmp); } static void do_test_validate_qmp_introspect(TestInputVisitorData *data,
tests/test-qmp-input-visitor.c +2 -8
@@ -733,18 +733,12 @@ static void test_visitor_in_errors(TestInputVisitorData *data,visit_type_TestStruct (v,NULL , &p, &err);error_free_or_abort (&err); -/* FIXME - a failed parse should not leave a partially-allocated p -* for us to clean up; this could cause callers to leak memory. */ -g_assert (p->string ==NULL ); - -g_free (p->string); -g_free (p); +g_assert (!p); v =visitor_input_test_init (data,"[ '1', '2', false, '3' ]" );visit_type_strList (v,NULL , &q, &err);error_free_or_abort (&err); -assert (q); -qapi_free_strList (q); +assert (!q); } static void test_visitor_in_wrong_type(TestInputVisitorData *data,
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 35/37] qapi: Change visit_type_FOO() to no longer return partial objects
Quoted 11 lines · Eric Blake
Returning a partial object on error is an invitation for a careless caller to leak memory. As no one outside the testsuite was actually relying on these semantics, it is cleaner to just document and guarantee that ALL pointer-based
visit_type_FOO()functions always leave a safe value in *obj during an input visitor (either the new object on success, or NULL if an error is encountered).Since input visitors have blind assignment semantics, we have to track the result of whether an assignment is made all the way down to each visitor callback implementation, to avoid making decisions based on potentially uninitialized storage.
I'm not sure I get this paragraph. What's "blind assignment semantics"?
Quoted 5 lines
Note that we still leave *obj unchanged after a scalar-based
visit_type_FOO(); I did not feel like auditing all uses ofvisit_type_Enum()to see if the callers would tolerate a specific sentinel value (not to mention having to decide whether it would be better to use 0 orENUM__MAXas that sentinel).
The assigning input visitor functions (core and generated) all assign either a pointer to a newly allocated object, or a non-pointer scalar value.
Possible behaviors on error:
(0) What we have now: assign something that must be cleaned up with the dealloc visitor if it's a pointer, but is otherwise useless
CON: callers have to clean up
CON: exposes careless callers to useless values
(1) Don't assign anything
PRO: consistent
CON: exposes careless callers to uninitialized values
(2) Assign zero bits
PRO: consistent
CON: exposes careless callers to bogus zero values
(3) Assign null pointer, else don't assign anything
CON: inconsistent
CON: mix of (1)'s and (2)'s CON(4) Other ideas?
Note that *obj is almost always null on entry, because we allocate objects zero-initialized. Only root visits can expose their caller to uninitialized values.
Quoted 64 lines
Signed-off-by Eric Blake <[email protected]>---
v9: fix bug in use of errp
v8: rebase to earlier changes
v7: rebase to earlier changes, enhance commit message, also fixvisit_type_str()andvisit_type_any()
v6: rebase on top of earlier doc and formatting improvements, mention that *obj can be uninitialized on entry to an input visitor, rework semantics to keep valgrind happy on uninitialized input, break some long lines--- include/qapi/visitor-impl.h | 6 ++--- include/qapi/visitor.h | 53 ++++++++++++++++++++++++++++-------------- qapi/opts-visitor.c | 11 ++++++--- qapi/qapi-dealloc-visitor.c | 9 ++++--- qapi/qapi-visit-core.c | 45 ++++++++++++++++++++++++++++------- qapi/qmp-input-visitor.c | 18 +++++++++----- qapi/qmp-output-visitor.c | 6 +++-- qapi/string-input-visitor.c | 6 +++-- qapi/string-output-visitor.c | 3 ++- scripts/qapi-visit.py | 40 +++++++++++++++++++++++-------- tests/test-qmp-commands.c | 13 +++++------ tests/test-qmp-input-strict.c | 19 +++++++-------- tests/test-qmp-input-visitor.c | 10 ++------ 13 files changed, 157 insertions(+), 82 deletions(-)include/qapi/visitor-impl.h +3
-3@@ -26,7 +26,7 @@ struct Visitor {/* Must be provided to visit structs (the string visitors do not * currently visit structs). */ -void (*start_struct)(Visitor *v,const char *name,void **obj, +bool (*start_struct)(Visitor *v,const char *name,void **obj,size_t size,Error **errp);/* May be NULL; most useful for input visitors. */ void (*check_struct)(Visitor *v,Error **errp);@@ -34,13 +34,13 @@ struct Visitorvoid (*end_struct)(Visitor *v);/* May be NULL; most useful for input visitors. */ -void (*start_implicit_struct)(Visitor *v,void **obj,size_t size, +bool (*start_implicit_struct)(Visitor *v,void **obj,size_t size,Error **errp);/* May be NULL */ void (*end_implicit_struct)(Visitor *v);/* Must be set */ -void (*start_list)(Visitor *v,const char *name,GenericList **list, +bool (*start_list)(Visitor *v,const char *name,GenericList **list,Error **errp);/* Must be set */ GenericList *(*next_list)(Visitor *v, GenericList *element, Error **errp);include/qapi/visitor.h +0
-0@@ -31,6 +31,27 @@* visitor-impl.h. */
include/qapi/visitor.h line 43
Quoted 10 lines
include/qapi/visitor.h +10
-0+/* All qapi types have a corresponding function with a signature +* roughly compatible with this: +* +* void visit_type_FOO(Visitor *v, void *obj, const char *name, Error **errp); +* +* where *@obj is itself a pointer or a scalar. The visit functions for +* built-in types are declared here, while the functions for qapi-defined +* struct, union, enum, and list types are generated (see qapi-visit.h). +* Input visitors may receive an uninitialized *@obj, and guarantee a +* safe value is assigned (a new object on success, or NULL on failure).
This specifies the safe value: NULL. Makes no sense for non-pointer scalars.
May input visitors really receive uninitialized *@obj? As far as I can see, we routinely store a newly allocated object to *@obj on success, and store nothing on failure. To be able to pass this to the dealloc visitor, *@obj must have been null initially, mustn't it?
include/qapi/visitor.h line 44
Quoted 1 line
include/qapi/visitor.h +1
-0+* Output visitors expect *@obj to be properly initialized on entry.
What about the dealloc visitor?
include/qapi/visitor.h line 52
Quoted 8 lines
include/qapi/visitor.h +8
-0+* +* Additionally, all qapi structs have a generated function compatible +* with this: +* +* void qapi_free_FOO(void *obj); +* +* which behaves like free(), even if @obj is NULL or was only partially +* allocated before encountering an error.
Will partially allocated QAPI objects remain visible outside input visitors?
Quoted 10 lines
include/qapi/visitor.h +2
-1+*/ +/* This struct is layout-compatible with all other *List structs * created by the qapi generator. */ typedef struct GenericList@@ -62,11 +83,12 @@ typedef struct GenericList* Set *@errp on failure; for example, if the input stream does not * have a member @name or if the member is not an object. * -* FIXME: For input visitors, *@obj can be assigned here even if later
include/qapi/visitor.h typedef struct GenericList · line 92
Quoted 10 lines
include/qapi/visitor.h +5
-3-* visits will fail; this can lead to memory leaks if clients aren't -* careful. +* Returns true if *@obj was allocated; if that happens, and an error +* occurs any time before the matching visit_end_struct(), then the +* caller (usually a visit_type_FOO() function) knows to undo the +* allocation before returning control further. */ -void visit_start_struct (Visitor *v,const char *name,void **obj, +bool visit_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp);
Need to see how this is used before I can judge whether I like it :)
Quoted 72 lines
include/qapi/visitor.h +10
-13/** * Prepare for completing a struct visit. @@ -85,19 +107,15 @@ void visit_end_struct(Visitor *v);/** * Prepare to visit an implicit struct. -* Similar to visit_start_struct(), except that an implicit struct -* represents a subset of keys that are present at the same nesting level -* of a common object but as a separate qapi C struct, rather than a new -* object at a deeper nesting level. +* Similar to visit_start_struct(), including return semantics, except +* that an implicit struct represents a subset of keys that are present +* at the same nesting level of a common object but as a separate qapi +* C struct, rather than a new object at a deeper nesting level. * * @obj must not be NULL, since this function is only called when * visiting with qapi structs. -* -* FIXME: For input visitors, *@obj can be assigned here even if later -* visits will fail; this can lead to memory leaks if clients aren't -* careful. */ -void visit_start_implicit_struct (Visitor *v,void **obj,size_t size, +bool visit_start_implicit_struct (Visitor *v,void **obj,size_t size,Error **errp);/** * Complete an implicit struct visit started earlier. @@ -126,11 +144,12 @@ void visit_end_implicit_struct(Visitor *v);* in this case, visit_next_list() will not be needed, but * visit_end_list() is still mandatory. * -* FIXME: For input visitors, *@list can be assigned here even if -* later visits will fail; this can lead to memory leaks if clients -* aren't careful. +* Returns true if *@list was allocated; if that happens, and an error +* occurs any time before the matching visit_end_list(), then the +* caller (usually a visit_type_FOO() function) knows to undo the +* allocation before returning control further. */ -void visit_start_list (Visitor *v,const char *name,GenericList **list, +bool visit_start_list (Visitor *v,const char *name,GenericList **list,Error **errp);/** * Iterate over a GenericList during a list visit. qapi/opts-visitor.c +4
-2@@ -122,18 +122,20 @@ opts_visitor_insert(GHashTable *unprocessed_opts, const QemuOpt *opt) } -static void +static bool opts_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp) {OptsVisitor *ov =to_ov (v);const QemuOpt *opt; +bool result = false;if (obj) { *obj =g_malloc0 (size >0 ? size :1 ); + result = true; }if (ov->depth++ >0 ) { -return ; +return result; } ov->unprocessed_opts = g_hash_table_new_full(&g_str_hash, &g_str_equal,
qapi/opts-visitor.c opts_start_struct(Visitor *v, const char *name, void **obj, · line 158
Quoted 5 lines
qapi/opts-visitor.c +1
-0@@ -152,6 +154,7 @@ opts_start_struct(Visitor *v, const char *name, void **obj, ov->fake_id_opt->str =g_strdup (ov->opts_root->id);opts_visitor_insert (ov->unprocessed_opts, ov->fake_id_opt); } +return result; }
Stores the newly allocated object in *@obj on success, doesn't store anything on failure.
To make cleanup possible, *@obj must be null initially. Then the return value is true iff *@obj is non-null on return.
Quoted 12 lines
qapi/opts-visitor.c +1
-1@@ -210,7 +213,7 @@ lookup_distinct(const OptsVisitor *ov, const char *name, Error **errp) } -static void +static bool opts_start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {OptsVisitor *ov =to_ov (v);
qapi/opts-visitor.c opts_start_list(Visitor *v, const char *name, GenericList **list, Error **errp) · line 234
Quoted 9 lines
qapi/opts-visitor.c +2
-0@@ -223,8 +226,10 @@ opts_start_list(Visitor *v, const char *name, GenericList **list, Error **errp)if (ov->repeated_opts) { ov->list_mode =LM_IN_PROGRESS ; *list =g_new0 (GenericList,1 ); +return true; }else { *list =NULL ; +return false; } }
This one stores null on failure, unlike opts_start_struct().
Again, the return value is true iff *@list is non-null on return.
Quoted 8 lines
qapi/qapi-dealloc-visitor.c +0
-0@@ -53,11 +53,12 @@ static void *qapi_dealloc_pop(QapiDeallocVisitor *qov)return value; }
qapi/qapi-dealloc-visitor.c static void *qapi_dealloc_pop(QapiDeallocVisitor *qov) · line 63
Quoted 10 lines
qapi/qapi-dealloc-visitor.c +2
-1-static void qapi_dealloc_start_struct (Visitor *v,const char *name,void **obj, +static bool qapi_dealloc_start_struct (Visitor *v,const char *name,void **obj,size_t unused,Error **errp) {QapiDeallocVisitor *qov =to_qov (v);qapi_dealloc_push (qov, obj); +return false; }
Not an input visitor, always returns false.
Quoted 6 lines
qapi/qapi-dealloc-visitor.c +0
-1static void qapi_dealloc_end_struct (Visitor *v)@@ -69,13 +70,14 @@ static void qapi_dealloc_end_struct(Visitor *v) } } -static void qapi_dealloc_start_implicit_struct(Visitor *v,
qapi/qapi-dealloc-visitor.c static void qapi_dealloc_end_struct(Visitor *v) · line 82
Quoted 10 lines
qapi/qapi-dealloc-visitor.c +2
-0+static bool qapi_dealloc_start_implicit_struct (Visitor *v,void **obj,size_t size,Error **errp) {QapiDeallocVisitor *qov =to_qov (v);qapi_dealloc_push (qov, obj); +return false; }
Likewise.
Quoted 4 lines
qapi/qapi-dealloc-visitor.c +0
-0static void qapi_dealloc_end_implicit_struct (Visitor *v)@@ -87,11 +89,12 @@ static void qapi_dealloc_end_implicit_struct(Visitor *v) } }
qapi/qapi-dealloc-visitor.c static void qapi_dealloc_end_implicit_struct(Visitor *v) · line 99
Quoted 10 lines
qapi/qapi-dealloc-visitor.c +2
-1-static void qapi_dealloc_start_list (Visitor *v,const char *name, +static bool qapi_dealloc_start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {QapiDeallocVisitor *qov =to_qov (v);qapi_dealloc_push (qov,NULL ); +return false; }
Likewise.
Quoted 23 lines
qapi/qapi-dealloc-visitor.c +0
-0static GenericList *qapi_dealloc_next_list(Visitor *v, GenericList *list,qapi/qapi-visit-core.c +3
-2@@ -2,7 +2,7 @@* Core Definitions for QAPI Visitor Classes * * Copyright IBM, Corp. 2011 -* Copyright (C) 2015 Red Hat, Inc. +* Copyright (C) 2015-2016 Red Hat, Inc. * * Authors: * Anthony Liguori <[email protected]> @@ -26,14 +26,20 @@ static bool visit_is_output(Visitor *v)return v->type_enum == output_type_enum; } -void visit_start_struct (Visitor *v,const char *name,void **obj, +bool visit_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp) { +bool result;
qapi/qapi-visit-core.c static bool visit_is_output(Visitor *v) · line 41
Quoted 10 lines
qapi/qapi-visit-core.c +5
-1+assert (obj ? size : !size);if (obj &&visit_is_output (v)) {assert (*obj); } - v->start_struct (v, name, obj, size, errp); + result = v->start_struct (v, name, obj, size, errp); +if (result) { +assert (obj && *obj); + }
Roundabout way to write assert(!result || (obj && *obj));
Heh, you even assert one half of what I'm trying to prove.
Can we make it assert(result == (visit_is_input(v) && obj && *obj) ?
Similarly for the other functions.
Quoted 55 lines
qapi/qapi-visit-core.c +16
-4+return result; }void visit_check_struct (Visitor *v,Error **errp)@@ -48,16 +54,22 @@ void visit_end_struct(Visitor *v) v->end_struct (v); } -void visit_start_implicit_struct (Visitor *v,void **obj,size_t size, +bool visit_start_implicit_struct (Visitor *v,void **obj,size_t size,Error **errp) { +bool result = false; +assert (obj && size);if (visit_is_output (v)) {assert (*obj); }if (v->start_implicit_struct) { - v->start_implicit_struct (v, obj, size, errp); + result = v->start_implicit_struct (v, obj, size, errp); } +if (result) { +assert (*obj); + } +return result; }void visit_end_implicit_struct (Visitor *v)@@ -67,10 +79,14 @@ void visit_end_implicit_struct(Visitor *v) } } -void visit_start_list (Visitor *v,const char *name,GenericList **list, +bool visit_start_list (Visitor *v,const char *name,GenericList **list,Error **errp) { - v->start_list (v, name, list, errp); +bool result = v->start_list (v, name, list, errp); +if (result) { +assert (list && *list); + } +return result; }GenericList *visit_next_list (Visitor *v,GenericList *list,Error **errp)@@ -229,6 +245,7 @@ void visit_type_bool(Visitor *v, const char *name, bool *obj, Error **errp)void visit_type_str (Visitor *v,const char *name,char **obj,Error **errp) { +Error *err =NULL ;assert (obj);/* TODO: Fix callers to not pass NULL when they mean "", so that we * can enable:
qapi/qapi-visit-core.c void visit_type_str(Visitor *v, const char *name, char **obj, Error **errp) · line 258
Quoted 7 lines
qapi/qapi-visit-core.c +3
-1@@ -236,7 +253,11 @@ void visit_type_str(Visitor *v, const char *name, char **obj, Error **errp)assert(*obj); } */ - v->type_str (v, name, obj, errp); + v->type_str (v, name, obj, &err); +if (!visit_is_output (v) && err) { + *obj =NULL ;
Shouldn't storing null on error be left to v->type_str(), like we do for structs and lists? Not least because it begs the question whether this leaks a string stored by it.
!visit_is_output(v) covers input visitors and the dealloc visitor.
Quoted 9 lines
qapi/qapi-visit-core.c +2
-0+ } +error_propagate (errp, err); } void visit_type_number(Visitor *v, const char *name, double *obj,@@ -248,11 +269,17 @@ void visit_type_number(Visitor *v, const char *name, double *obj,void visit_type_any (Visitor *v,const char *name,QObject **obj,Error **errp) {
qapi/qapi-visit-core.c void visit_type_number(Visitor *v, const char *name, double *obj, · line 280
Quoted 10 lines
qapi/qapi-visit-core.c +5
-1+Error *err =NULL ; +assert (obj);if (visit_is_output (v)) {assert (*obj); } - v->type_any (v, name, obj, errp); + v->type_any (v, name, obj, &err); +if (!visit_is_output (v) && err) { + *obj =NULL ;
Likewise.
Quoted 28 lines
qapi/qapi-visit-core.c +2
-0+ } +error_propagate (errp, err); }void visit_type_null (Visitor *v,const char *name,Error **errp)qapi/qmp-input-visitor.c +2
-2@@ -130,7 +130,7 @@ static void qmp_input_pop(Visitor *v) qiv->nb_stack--; } -static void qmp_input_start_struct (Visitor *v,const char *name,void **obj, +static bool qmp_input_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp) {QmpInputVisitor *qiv =to_qiv (v);@@ -140,30 +140,34 @@ static void qmp_input_start_struct(Visitor *v, const char *name, void **obj,if (!qobj ||qobject_type (qobj) !=QTYPE_QDICT ) {error_setg (errp,QERR_INVALID_PARAMETER_TYPE , name ? name :"null" ,"QDict" ); -return ; +return false; }qmp_input_push (qiv, qobj,NULL , &err);if (err) {
qapi/qmp-input-visitor.c static void qmp_input_start_struct(Visitor *v, const char *name, void **obj, · line 156
Quoted 10 lines
qapi/qmp-input-visitor.c +3
-1error_propagate (errp, err); -return ; +return false; }if (obj) { *obj =g_malloc0 (size); +return true; } +return false;
Stores the newly allocated object in *@obj on success, doesn't store anything on failure.
To make cleanup possible, *@obj must be null initially. Then the return value is true iff *@obj is non-null on return.
Just like opts-visitor.c.
qapi/qmp-input-visitor.c static void qmp_input_start_struct(Visitor *v, const char *name, void **obj, · line 168
Quoted 13 lines
qapi/qmp-input-visitor.c +3
-1} -static void qmp_input_start_implicit_struct (Visitor *v,void **obj, +static bool qmp_input_start_implicit_struct (Visitor *v,void **obj,size_t size,Error **errp) {if (obj) { *obj =g_malloc0 (size); +return true; } +return false; }
Likewise.
Quoted 16 lines
qapi/qmp-input-visitor.c +2
-2-static void qmp_input_start_list (Visitor *v,const char *name, +static bool qmp_input_start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {QmpInputVisitor *qiv =to_qiv (v);@@ -173,7 +177,7 @@ static void qmp_input_start_list(Visitor *v, const char *name,if (!qobj ||qobject_type (qobj) !=QTYPE_QLIST ) {error_setg (errp,QERR_INVALID_PARAMETER_TYPE , name ? name :"null" ,"list" ); -return ; +return false; } entry =qlist_first (qobject_to_qlist (qobj));
qapi/qmp-input-visitor.c static void qmp_input_start_list(Visitor *v, const char *name, · line 194
Quoted 10 lines
qapi/qmp-input-visitor.c +2
-0@@ -181,10 +185,12 @@ static void qmp_input_start_list(Visitor *v, const char *name,if (list) {if (entry) { *list =g_new0 (GenericList,1 ); +return true; }else { *list =NULL ; } } +return false; }
This one stores null on failure, unlike start_struct().
Again, the return value is true iff *@list is non-null on return.
Just like opts-visitor.c.
Quoted 16 lines
qapi/qmp-input-visitor.c +0
-0static GenericList *qmp_input_next_list(Visitor *v, GenericList *list,qapi/qmp-output-visitor.c +1
-1@@ -102,7 +102,7 @@ static void qmp_output_add_obj(QmpOutputVisitor *qov, const char *name, } } -static void qmp_output_start_struct (Visitor *v,const char *name,void **obj, +static bool qmp_output_start_struct (Visitor *v,const char *name,void **obj,size_t unused,Error **errp) {QmpOutputVisitor *qov =to_qov (v);
qapi/qmp-output-visitor.c static void qmp_output_start_struct(Visitor *v, const char *name, void **obj, · line 114
Quoted 5 lines
qapi/qmp-output-visitor.c +1
-0@@ -110,6 +110,7 @@ static void qmp_output_start_struct(Visitor *v, const char *name, void **obj,qmp_output_add (qov, name, dict);qmp_output_push (qov, dict); +return false; }
Not an input visitor, always returns false.
Quoted 12 lines
qapi/qmp-output-visitor.c +1
-1static void qmp_output_end_struct (Visitor *v)@@ -118,7 +119,7 @@ static void qmp_output_end_struct(Visitor *v)qmp_output_pop (qov,QTYPE_QDICT ); } -static void qmp_output_start_list (Visitor *v,const char *name, +static bool qmp_output_start_list (Visitor *v,const char *name,GenericList **listp,Error **errp) {QmpOutputVisitor *qov =to_qov (v);
qapi/qmp-output-visitor.c static void qmp_output_start_list(Visitor *v, const char *name, · line 131
Quoted 5 lines
qapi/qmp-output-visitor.c +1
-0@@ -126,6 +127,7 @@ static void qmp_output_start_list(Visitor *v, const char *name,qmp_output_add (qov, name, list);qmp_output_push (qov, list); +return false; }
Likewise.
Quoted 25 lines
qapi/qmp-output-visitor.c +0
-0static GenericList *qmp_output_next_list(Visitor *v, GenericList *list,qapi/string-input-visitor.c +2
-2@@ -120,7 +120,7 @@ error: siv->ranges =NULL ; } -static void +static bool start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {StringInputVisitor *siv =to_siv (v);@@ -132,7 +132,7 @@ start_list(Visitor *v, const char *name, GenericList **list, Error **errp)parse_str (siv, &err);if (err) {error_propagate (errp, err); -return ; +return false; } siv->cur_range =g_list_first (siv->ranges);
qapi/string-input-visitor.c start_list(Visitor *v, const char *name, GenericList **list, Error **errp) · line 150
Quoted 9 lines
qapi/string-input-visitor.c +2
-0@@ -142,8 +142,10 @@ start_list(Visitor *v, const char *name, GenericList **list, Error **errp) siv->cur = r->begin; } *list =g_new0 (GenericList,1 ); +return true; }else { *list =NULL ; +return false; } }
This one stores null on failure, like the start_list() we've seen before, and unlike the start_struct().
Again, the return value is true iff *@list is non-null on return.
Quoted 15 lines
qapi/string-output-visitor.c +1
-1@@ -263,7 +263,7 @@ static void print_type_number(Visitor *v, const char *name, double *obj,string_output_set (sov,g_strdup_printf ("%f" , *obj)); } -static void +static bool start_list (Visitor *v,const char *name,GenericList **list,Error **errp) {StringOutputVisitor *sov =to_sov (v);
qapi/string-output-visitor.c start_list(Visitor *v, const char *name, GenericList **list, Error **errp) · line 280
Quoted 5 lines
qapi/string-output-visitor.c +1
-0@@ -276,6 +276,7 @@ start_list(Visitor *v, const char *name, GenericList **list, Error **errp)if (*list && (*list)->next) { sov->list_mode =LM_STARTED ; } +return false; }
Not an input visitor, always returns false.
Quoted 109 lines
qapi/string-output-visitor.c +0
-0static GenericList *scripts/qapi-visit.py +27
-9@@ -58,8 +58,10 @@ def gen_visit_implicit_struct(typ): static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error **errp) { Error *err = NULL; + bool allocated; - visit_start_implicit_struct(v, (void **)obj, sizeof(%(c_type)s), &err); + allocated = visit_start_implicit_struct(v, (void **)obj, + sizeof(%(c_type)s), &err); if (err) { goto out; }@@ -69,6 +71,10 @@ static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error * visit_type_%(c_type)s_fields(v, obj, &err); out_obj: visit_end_implicit_struct(v); + if (allocated && err) { + g_free(*obj); + *obj = NULL; + } out: error_propagate(errp, err); }@@ -116,18 +122,15 @@ out: def gen_visit_list(name, element_type): - # FIXME: if *obj is NULL on entry, and the first visit_next_list() - # assigns to *obj, while a later one fails, we should clean up *obj - # rather than leaving it non-NULL. As currently written, the caller must - # call qapi_free_FOOList() to avoid a memory leak of the partial FOOList. return mcgen(''' void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) { Error *err = NULL; %(c_name)s *elt; + bool allocated; - visit_start_list(v, name, (GenericList **)obj, &err); + allocated = visit_start_list(v, name, (GenericList **)obj, &err); if (err) { goto out; }@@ -144,6 +147,10 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error } visit_end_list(v); out: + if (allocated && err) { + qapi_free_%(c_name)s(*obj); + *obj = NULL; + } error_propagate(errp, err); } ''',@@ -174,8 +181,10 @@ def gen_visit_alternate(name, variants): void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) { Error *err = NULL; + bool allocated; - visit_start_implicit_struct(v, (void**) obj, sizeof(%(c_name)s), &err); + allocated = visit_start_implicit_struct(v, (void **)obj, + sizeof(%(c_name)s), &err); if (err) { goto out; }@@ -204,11 +213,15 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error } out_obj: visit_end_implicit_struct(v); + if (allocated && err) { + qapi_free_%(c_name)s(*obj); + *obj = NULL; + } out: error_propagate(errp, err); } ''', - name=name) + name=name, c_name=c_name(name)) return ret@@ -236,8 +249,10 @@ def gen_visit_object(name, base, members, variants): void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error **errp) { Error *err = NULL; + bool allocated; - visit_start_struct(v, name, (void **)obj, sizeof(%(c_name)s), &err); + allocated = visit_start_struct(v, name, (void **)obj, sizeof(%(c_name)s), + &err); if (err) { goto out; }@@ -301,10 +316,15 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error visit_check_struct(v, &err); out_obj: visit_end_struct(v); + if (allocated && err) { + qapi_free_%(c_name)s(*obj); + *obj = NULL;
scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 330
Quoted 10 lines
scripts/qapi-visit.py +3
-1+ } out: error_propagate(errp, err); } -''') +''', + c_name=c_name(name)) return ret
Hmm.
This grows qapi-visit.c by 14% for me.
Can we do the deallocation in the visitor core somehow? We'd have to pass "how to deallocate" information: the appropriate qapi_free_FOO() function. We already pass in "how to allocate" information: size.
Quoted 80 lines
tests/test-qmp-commands.c +6
-7@@ -227,14 +227,13 @@ static void test_dealloc_partial(void)QDECREF (ud2_dict); } -/* verify partial success */ -assert (ud2 !=NULL ); -assert (ud2->string0 !=NULL ); -assert (strcmp (ud2->string0, text) ==0 ); -assert (ud2->dict1 ==NULL ); - -/* confirm & release construction error */ +/* verify that visit_type_XXX() cleans up properly on error */ error_free_or_abort (&err); +assert (!ud2); + +/* Manually create a partial object, leaving ud2->dict1 at NULL */ + ud2 =g_new0 (UserDefTwo,1 ); + ud2->string0 =g_strdup (text);/* tear down partial object */ qapi_free_UserDefTwo (ud2);tests/test-qmp-input-strict.c +5
-8@@ -181,10 +181,7 @@ static void test_validate_fail_struct(TestInputVisitorData *data,visit_type_TestStruct (v,NULL , &p, &err);error_free_or_abort (&err); -if (p) { -g_free (p->string); - } -g_free (p); +g_assert (!p); } static void test_validate_fail_struct_nested(TestInputVisitorData *data,@@ -198,7 +195,7 @@ static void test_validate_fail_struct_nested(TestInputVisitorData *data,visit_type_UserDefTwo (v,NULL , &udp, &err);error_free_or_abort (&err); -qapi_free_UserDefTwo (udp); +g_assert (!udp); } static void test_validate_fail_list(TestInputVisitorData *data,@@ -212,7 +209,7 @@ static void test_validate_fail_list(TestInputVisitorData *data,visit_type_UserDefOneList (v,NULL , &head, &err);error_free_or_abort (&err); -qapi_free_UserDefOneList (head); +g_assert (!head); } static void test_validate_fail_union_native_list(TestInputVisitorData *data,@@ -227,7 +224,7 @@ static void test_validate_fail_union_native_list(TestInputVisitorData *data,visit_type_UserDefNativeListUnion (v,NULL , &tmp, &err);error_free_or_abort (&err); -qapi_free_UserDefNativeListUnion (tmp); +g_assert (!tmp); } static void test_validate_fail_union_flat(TestInputVisitorData *data,@@ -241,7 +238,7 @@ static void test_validate_fail_union_flat(TestInputVisitorData *data,visit_type_UserDefFlatUnion (v,NULL , &tmp, &err);error_free_or_abort (&err); -qapi_free_UserDefFlatUnion (tmp); +g_assert (!tmp); } static void test_validate_fail_union_flat_no_discrim(TestInputVisitorData *data,@@ -256,13 +253,13 @@ static void test_validate_fail_union_flat_no_discrim(TestInputVisitorData *data,visit_type_UserDefFlatUnion2 (v,NULL , &tmp, &err);
tests/test-qmp-input-strict.c static void test_validate_fail_union_flat_no_discrim(TestInputVisitorData *data, · line 262
Quoted 10 lines
tests/test-qmp-input-strict.c +2
-2error_free_or_abort (&err); -qapi_free_UserDefFlatUnion2 (tmp); +g_assert (!tmp); }static void test_validate_fail_alternate (TestInputVisitorData *data,const void *unused) { -UserDefAlternate *tmp =NULL ; +UserDefAlternate *tmp;
Are you sure this is sound?
Quoted 27 lines
tests/test-qmp-input-strict.c +1
-1Visitor *v;Error *err =NULL ;@@ -270,7 +267,7 @@ static void test_validate_fail_alternate(TestInputVisitorData *data,visit_type_UserDefAlternate (v,NULL , &tmp, &err);error_free_or_abort (&err); -qapi_free_UserDefAlternate (tmp); +g_assert (!tmp); } static void do_test_validate_qmp_introspect(TestInputVisitorData *data,tests/test-qmp-input-visitor.c +1
-6@@ -733,18 +733,12 @@ static void test_visitor_in_errors(TestInputVisitorData *data,visit_type_TestStruct (v,NULL , &p, &err);error_free_or_abort (&err); -/* FIXME - a failed parse should not leave a partially-allocated p -* for us to clean up; this could cause callers to leak memory. */ -g_assert (p->string ==NULL ); - -g_free (p->string); -g_free (p); +g_assert (!p);
tests/test-qmp-input-visitor.c static void test_visitor_in_errors(TestInputVisitorData *data, · line 744
Quoted 10 lines
tests/test-qmp-input-visitor.c +1
-2v =visitor_input_test_init (data,"[ '1', '2', false, '3' ]" );visit_type_strList (v,NULL , &q, &err);error_free_or_abort (&err); -assert (q); -qapi_free_strList (q); +assert (!q); } static void test_visitor_in_wrong_type(TestInputVisitorData *data,
Now I've seen the complete patch, two more remarks:
* I think all the allocating methods should behave the same. Right now, some store null on failure, and some don't. For the latter to work, the value must be null initially (or else the dealloc visitor runs amok).
* Do we really need the new return value? It looks like it's always equal to visit_is_input(v) && obj && *obj.
Re: [Qemu-devel] [PATCH v9 35/37] qapi: Change visit_type_FOO() to no longer return partial objects
Quoted 9 lines · Markus Armbruster
Quoted 7 lines · Eric Blake
Returning a partial object on error is an invitation for a careless caller to leak memory. As no one outside the testsuite was actually relying on these semantics, it is cleaner to just document and guarantee that ALL pointer-based
visit_type_FOO()functions always leave a safe value in *obj during an input visitor (either the new object on success, or NULL if an error is encountered).
Quoted 6 lines
Quoted 4 lines
Since input visitors have blind assignment semantics, we have to track the result of whether an assignment is made all the way down to each visitor callback implementation, to avoid making decisions based on potentially uninitialized storage.
I'm not sure I get this paragraph. What's "blind assignment semantics"?
The caller does:
{
Foo *bar; /* uninit */
visit_type_Foo(&bar);
if (no error) {
/* use bar */
}
}Which means the visitor core can't do 'if (*obj)', because obj may be uninitialized on entry; if it dereferences obj at all, it must be via '*obj = ...' which I'm terming a blind assignment.
But I can try and come up with better wording.
Quoted 16 lines
Quoted 6 lines
Note that we still leave *obj unchanged after a scalar-based
visit_type_FOO(); I did not feel like auditing all uses ofvisit_type_Enum()to see if the callers would tolerate a specific sentinel value (not to mention having to decide whether it would be better to use 0 orENUM__MAXas that sentinel).The assigning input visitor functions (core and generated) all assign either a pointer to a newly allocated object, or a non-pointer scalar value.
Possible behaviors on error:
(0) What we have now: assign something that must be cleaned up with the dealloc visitor if it's a pointer, but is otherwise useless
Quoted 7 lines
CON: callers have to clean up
CON: exposes careless callers to useless values(1) Don't assign anything
PRO: consistent
CON: exposes careless callers to uninitialized values
Half-PRO: Caller can pre-initialize a default, and rely on that value on error. In fact, I think we have callers doing that when visiting an enum, and I didn't feel up to auditing them all when first writing the patch.
But a small audit right now shows:
qom/object.c:object_property_get_enum() starts with uninitialized 'int ret;', hardcodes 'return 0;' on some failures, but otherwise passes it to visit_type_enum() then blindly returns that value even if errp is set. Yuck. Callers HAVE to check errp rather than relying on the return value to flag errors; although it looks like the lone caller is in numa.c and passes &error_abort.
Maybe I should just bite the bullet, and audit ALL uses of visitor for their behavior of what to expect in *obj on error.
Quoted 5 lines
(2) Assign zero bits
PRO: consistent
CON: exposes careless callers to bogus zero values
Half-CON: Caller cannot pre-initialize a default
Quoted 5 lines
(3) Assign null pointer, else don't assign anything
CON: inconsistent CON: mix of (1)'s and (2)'s CON
Which I think is what I did in this patch.
Quoted 2 lines
(4) Other ideas?
Store the caller's initial value (often all zero, but not necessarily), and restore THAT value on error (preserves a pre-initialized default, but leaves uninitialized garbage in place to bite careless callers)
Quoted 19 lines
Note that *obj is almost always null on entry, because we allocate objects zero-initialized. Only root visits can expose their caller to uninitialized values.
Quoted 13 lines
Signed-off-by Eric Blake <[email protected]>+/* All qapi types have a corresponding function with a signature
+ * roughly compatible with this:
+ *
+ * voidvisit_type_FOO(Visitor *v, void *obj, const char *name, Error **errp);
+ *
+ * where *@obj is itself a pointer or a scalar. The visit functions for
+ * built-in types are declared here, while the functions for qapi-defined
+ * struct, union, enum, and list types are generated (seeqapi-visit.h).
+ * Input visitors may receive an uninitialized *@obj, and guarantee a
+ * safe value is assigned (a new object on success, or NULL on failure).
Quoted 7 lines
This specifies the safe value: NULL. Makes no sense for non-pointer scalars.
May input visitors really receive uninitialized *@obj? As far as I can see, we routinely store a newly allocated object to *@obj on success, and store nothing on failure. To be able to pass this to the dealloc visitor, *@obj must have been null initially, mustn't it?
Correct. Pre-patch: either the caller pre-initialized obj to NULL (and can then blindly pass it to the dealloc visitor regardless of whether visit_start_struct() succeeded), or it did not (in which case the dealloc visitor must not be called if *obj remains uninitialized because visit_start_struct() failed, but MUST be called if visit_start_struct() succeeded to clean up the partial object).
Post-patch: calling visit_start_struct() always assigns to *obj, and the dealloc visitor can be safely called.
Quoted 4 lines
Quoted 2 lines
+ * Output visitors expect *@obj to be properly initialized on entry.
What about the dealloc visitor?
Can be passed NULL, a partial object, or a complete object. But spelling that out would indeed be useful.
Quoted 10 lines
Quoted 9 lines
+ *
+ * Additionally, all qapi structs have a generated function compatible
+ * with this:
+ *
+ * voidqapi_free_FOO(void *obj);
+ *
+ * which behaves likefree(), even if @obj is NULL or was only partially
+ * allocated before encountering an error.
Quoted 2 lines
Will partially allocated QAPI objects remain visible outside input visitors?
A user can still hand-initialize a QAPI struct into partial state, although you are correct that this patch is what is changing things to no longer leak a partial object outside of the visit_type_FOO() calls.
Quoted 21 lines
include/qapi/visitor.h typedef struct GenericList · line 92
Quoted 8 lines
+ * Returns true if *@obj was allocated; if that happens, and an error
+ * occurs any time before the matchingvisit_end_struct(), then the
+ * caller (usually avisit_type_FOO()function) knows to undo the
+ * allocation before returning control further.
*/include/qapi/visitor.h +1
-1-void visit_start_struct (Visitor *v,const char *name,void **obj, +bool visit_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp);Need to see how this is used before I can judge whether I like it :)
qapi/opts-visitor.c opts_start_struct(Visitor *v, const char *name, void **obj, · line 158
Quoted 6 lines
qapi/opts-visitor.c +1
-0@@ -152,6 +154,7 @@ opts_start_struct(Visitor *v, const char *name, void **obj, ov->fake_id_opt->str =g_strdup (ov->opts_root->id);opts_visitor_insert (ov->unprocessed_opts, ov->fake_id_opt); } +return result; }Stores the newly allocated object in *@obj on success, doesn't store anything on failure.
Quoted 2 lines
To make cleanup possible, *@obj must be null initially. Then the return value is true iff *@obj is non-null on return.
If we want, I can change these to all store *obj = NULL on failure. Thinking about it more: for any given visit_type_FOO(), if visit_start_struct() succeeds but something else later fails, *obj will be NULL; so it also makes sense that if visit_start_struct() fails than *obj should be NULL.
Quoted 18 lines
Quoted 5 lines
qapi/qapi-visit-core.c +1
-1-void visit_start_struct (Visitor *v,const char *name,void **obj, +bool visit_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp){
qapi/qapi-visit-core.c +1
-0+bool result;qapi/qapi-visit-core.c static bool visit_is_output(Visitor *v) · line 41
Quoted 10 lines
qapi/qapi-visit-core.c +5
-1+assert (obj ? size : !size);if (obj &&visit_is_output (v)) {assert (*obj); } - v->start_struct (v, name, obj, size, errp); + result = v->start_struct (v, name, obj, size, errp); +if (result) { +assert (obj && *obj); + }Roundabout way to write
assert(!result || (obj && *obj));
Quoted 3 lines
Heh, you even assert one half of what I'm trying to prove.
Can we make it assert(result == (
visit_is_input(v)&& obj && *obj) ?
Missing a ); guessing that you meant:
assert(result == (visit_is_input(v) && obj && *obj));
Yes, I think we can, but we'd need a visit_is_input() helper.
Quoted 4 lines
Quoted 4 lines
qapi/qapi-visit-core.c +0
-0@@ -236,7 +253,11 @@ void visit_type_str(Visitor *v, const char *name, char **obj, Error **errp)assert(*obj); } */
Quoted 8 lines
qapi/qapi-visit-core.c void visit_type_str(Visitor *v, const char *name, char **obj, Error **errp) · line 258
Quoted 4 lines
qapi/qapi-visit-core.c +3
-1- v->type_str (v, name, obj, errp); + v->type_str (v, name, obj, &err); +if (!visit_is_output (v) && err) { + *obj =NULL ;Shouldn't storing null on error be left to
v->type_str(), like we do for structs and lists? Not least because it begs the question whether this leaks a string stored by it.
May be worthwhile to mandate that tighter semantics on each visitor.
Quoted 22 lines
Quoted 9 lines
scripts/qapi-visit.py +4
-0+++ b/scripts/qapi-visit.py@@ -301,10 +316,15 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error visit_check_struct(v, &err); out_obj: visit_end_struct(v); + if (allocated && err) { + qapi_free_%(c_name)s(*obj); + *obj = NULL;scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 330
Quoted 10 lines
scripts/qapi-visit.py +3
-1+ } out: error_propagate(errp, err); } -''') +''', + c_name=c_name(name)) return retHmm.
Quoted 5 lines
This grows
qapi-visit.cby 14% for me.Can we do the deallocation in the visitor core somehow? We'd have to pass "how to deallocate" information: the appropriate
qapi_free_FOO()function. We already pass in "how to allocate" information: size.
I thought about that; do we really want to be type-punning functions like that? But it does sound smaller; I can play with the idea.
Quoted 7 lines
Now I've seen the complete patch, two more remarks:
* I think all the allocating methods should behave the same. Right now, some store null on failure, and some don't. For the latter to work, the value must be null initially (or else the dealloc visitor runs amok).
Agree; I'm leaning towards ALL allocating methods must store into *obj (either NULL on failure, or object on success).
Quoted 3 lines
* Do we really need the new return value? It looks like it's always equal to
visit_is_input(v)&& obj && *obj.
Except we don't (yet) have a visit_is_input() function, let alone one visible from within the generated qapi-visit.c code. Maybe doing that first would help.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v9 35/37] qapi: Change visit_type_FOO() to no longer return partial objects
Quoted 27 lines · Eric Blake
Quoted 9 lines · Markus Armbruster
Quoted 7 lines · Eric Blake
Returning a partial object on error is an invitation for a careless caller to leak memory. As no one outside the testsuite was actually relying on these semantics, it is cleaner to just document and guarantee that ALL pointer-based
visit_type_FOO()functions always leave a safe value in *obj during an input visitor (either the new object on success, or NULL if an error is encountered).Quoted 6 lines
Quoted 4 lines
Since input visitors have blind assignment semantics, we have to track the result of whether an assignment is made all the way down to each visitor callback implementation, to avoid making decisions based on potentially uninitialized storage.
I'm not sure I get this paragraph. What's "blind assignment semantics"?
The caller does:
{ Foo *bar; /* uninit */ visit_type_Foo(&bar); if (no error) { /* use bar */ } }
Quoted 5 lines
Which means the visitor core can't do 'if (*obj)', because obj may be uninitialized on entry; if it dereferences obj at all, it must be via '*obj = ...' which I'm terming a blind assignment.
But I can try and come up with better wording.
I'd suggest one, but I think we should first make up our minds on error behavior.
Quoted 12 lines
Quoted 12 lines
Quoted 5 lines
Note that we still leave *obj unchanged after a scalar-based
visit_type_FOO(); I did not feel like auditing all uses ofvisit_type_Enum()to see if the callers would tolerate a specific sentinel value (not to mention having to decide whether it would be better to use 0 orENUM__MAXas that sentinel).The assigning input visitor functions (core and generated) all assign either a pointer to a newly allocated object, or a non-pointer scalar value.
Possible behaviors on error:
Quoted 7 lines
Quoted 7 lines
(0) What we have now: assign something that must be cleaned up with the dealloc visitor if it's a pointer, but is otherwise useless
CON: callers have to clean up
CON: exposes careless callers to useless values(1) Don't assign anything
Need to be very careful to store only when success is assured.
Consider visiting a QAPI type that is actually two levels of containers, say a list of a struct of scalars. The visit is a walk of this tree then:
list
___/ ... \___
/ \
struct1 structN
/ ... \ / ... \
scal11 scal1M scalN1 scalNMNow let's consider the state when the visit reaches scalN1:
* The visits of scal11..scal1M and struct 1 have all succeeded already, and stored their value into their container. Same for the visits of structI (I < N) omitted in the diagram, and their scalars.
* The visit of list and struct N are in progress: the object has been partially constructed, but not yet stored.
* The remaining visits haven't begun, and their members in objects already allocated are still zero.
Now the visit of scalN1 fails. The visit of structN fails in turn, freeing its (not yet stored, partially constructed) object. Finally, the visit of list fails, freeing its object.
That the failed visits of scalN1 and structN didn't store is actually unimportant.
Of course, this isn't how things work now. Visits of containers store the newly allocated object before visiting members, in visit_start_*(), and the member visits use that to find the object.
Quoted 20 lines
Quoted 2 lines
PRO: consistent
CON: exposes careless callers to uninitialized valuesHalf-PRO: Caller can pre-initialize a default, and rely on that value on error. In fact, I think we have callers doing that when visiting an enum, and I didn't feel up to auditing them all when first writing the patch.
But a small audit right now shows:
qom/object.c:object_property_get_enum() starts with uninitialized 'int ret;', hardcodes 'return 0;' on some failures, but otherwise passes it to
visit_type_enum()then blindly returns that value even if errp is set. Yuck. Callers HAVE to check errp rather than relying on the return value to flag errors; although it looks like the lone caller is innuma.cand passes&error_abort.Maybe I should just bite the bullet, and audit ALL uses of visitor for their behavior of what to expect in *obj on error.
Quoted 1 line
Quoted 6 lines
Quoted 4 lines
(2) Assign zero bits
PRO: consistent
CON: exposes careless callers to bogus zero valuesHalf-CON: Caller cannot pre-initialize a default
With (1) don't assign, the caller can pick an error value by assigning it before the visit, and it must not access the value on error unless it does.
With (2) assign zero, the caller can't pick an error value, but may safely access the value even on error.
Tradeoff. I figure either can work for us.
Quoted 6 lines
Quoted 4 lines
(3) Assign null pointer, else don't assign anything
CON: inconsistent CON: mix of (1)'s and (2)'s CONWhich I think is what I did in this patch.
I don't like the inconsistency. It complicates the interface.
Quoted 5 lines
Quoted 1 line
(4) Other ideas?
Store the caller's initial value (often all zero, but not necessarily), and restore THAT value on error (preserves a pre-initialized default, but leaves uninitialized garbage in place to bite careless callers)
Behaves like (1). Under the hood, it replaces "store only when success is assured" by "undo the store on failure". I'd guess this would be more complicated.
Quoted 21 lines
Quoted 21 lines
Note that *obj is almost always null on entry, because we allocate objects zero-initialized. Only root visits can expose their caller to uninitialized values.
Quoted 13 lines
Signed-off-by Eric Blake <[email protected]>+/* All qapi types have a corresponding function with a signature
+ * roughly compatible with this:
+ *
+ * voidvisit_type_FOO(Visitor *v, void *obj, const char *name, Error **errp);
+ *
+ * where *@obj is itself a pointer or a scalar. The visit functions for
+ * built-in types are declared here, while the functions for qapi-defined
+ * struct, union, enum, and list types are generated (seeqapi-visit.h).
+ * Input visitors may receive an uninitialized *@obj, and guarantee a
+ * safe value is assigned (a new object on success, or NULL on failure).This specifies the safe value: NULL. Makes no sense for non-pointer scalars.
Quoted 8 lines
Quoted 4 lines
May input visitors really receive uninitialized *@obj? As far as I can see, we routinely store a newly allocated object to *@obj on success, and store nothing on failure. To be able to pass this to the dealloc visitor, *@obj must have been null initially, mustn't it?
Correct. Pre-patch: either the caller pre-initialized obj to NULL (and can then blindly pass it to the dealloc visitor regardless of whether
visit_start_struct()succeeded),
Yes.
Three cases:
(a) visit_start_struct() succeeds: it stored to *obj, and caller must clean it up.
(b) visit_start_struct() fails without storing to *obj: *obj is still null, and caller may clean it up (it's a nop). Whatever visit_start_struct() allocated, it has to clean up itself.
(c) visit_start_struct() fails with storing to *obj: caller must clean it up.
Cleanup is relatively easy for the caller: just do it always.
But what if caller forgets to initialize to null? That's next:
Quoted 4 lines
or it did not (in which case the
dealloc visitor must not be called if *obj remains uninitialized becausevisit_start_struct()failed, but MUST be called ifvisit_start_struct()succeeded to clean up the partial object).
Case (b) changes:
(b) visit_start_struct() fails without storing to *obj: caller must not use *obj. Whatever visit_start_struct() allocated, it has to clean up itself.
I can't see how the caller could get cleanup right without initializing to null.
Quoted 2 lines
Post-patch: calling
visit_start_struct()always assigns to *obj, and the dealloc visitor can be safely called.
Actually, it always assigns *pointers*. That's enough to permit unconditional cleanup, of course.
Quoted 17 lines
Quoted 3 lines
Quoted 1 line
+ * Output visitors expect *@obj to be properly initialized on entry.
What about the dealloc visitor?
Can be passed NULL, a partial object, or a complete object. But spelling that out would indeed be useful.
Quoted 10 lines
Quoted 9 lines
+ *
+ * Additionally, all qapi structs have a generated function compatible
+ * with this:
+ *
+ * voidqapi_free_FOO(void *obj);
+ *
+ * which behaves likefree(), even if @obj is NULL or was only partially
+ * allocated before encountering an error.
Quoted 6 lines
Quoted 2 lines
Will partially allocated QAPI objects remain visible outside input visitors?
A user can still hand-initialize a QAPI struct into partial state, although you are correct that this patch is what is changing things to no longer leak a partial object outside of the
visit_type_FOO()calls.
Okay.
Quoted 21 lines
Quoted 21 lines
include/qapi/visitor.h typedef struct GenericList · line 92
Quoted 8 lines
+ * Returns true if *@obj was allocated; if that happens, and an error
+ * occurs any time before the matchingvisit_end_struct(), then the
+ * caller (usually avisit_type_FOO()function) knows to undo the
+ * allocation before returning control further.
*/include/qapi/visitor.h +1
-1-void visit_start_struct (Visitor *v,const char *name,void **obj, +bool visit_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp);Need to see how this is used before I can judge whether I like it :)
qapi/opts-visitor.c opts_start_struct(Visitor *v, const char *name, void **obj, · line 158
Quoted 6 lines
qapi/opts-visitor.c +1
-0@@ -152,6 +154,7 @@ opts_start_struct(Visitor *v, const char *name, void **obj, ov->fake_id_opt->str =g_strdup (ov->opts_root->id);opts_visitor_insert (ov->unprocessed_opts, ov->fake_id_opt); } +return result; }Stores the newly allocated object in *@obj on success, doesn't store anything on failure.
Quoted 8 lines
Quoted 2 lines
To make cleanup possible, *@obj must be null initially. Then the return value is true iff *@obj is non-null on return.
If we want, I can change these to all store *obj = NULL on failure. Thinking about it more: for any given
visit_type_FOO(), ifvisit_start_struct()succeeds but something else later fails, *obj will be NULL; so it also makes sense that ifvisit_start_struct()fails than *obj should be NULL.
I think behavior (1) don't assign and (2) assign zero both work, we just have to pick one and run with it.
If we pick behavior (1) don't assign, then we should assert something like !obj || !*obj on entry. With such assertions in place, I think (1) should be roughly as safe as (2).
Quoted 18 lines
Quoted 18 lines
Quoted 5 lines
qapi/qapi-visit-core.c +1
-1-void visit_start_struct (Visitor *v,const char *name,void **obj, +bool visit_start_struct (Visitor *v,const char *name,void **obj,size_t size,Error **errp){
qapi/qapi-visit-core.c +1
-0+bool result;qapi/qapi-visit-core.c static bool visit_is_output(Visitor *v) · line 41
Quoted 10 lines
qapi/qapi-visit-core.c +5
-1+assert (obj ? size : !size);if (obj &&visit_is_output (v)) {assert (*obj); } - v->start_struct (v, name, obj, size, errp); + result = v->start_struct (v, name, obj, size, errp); +if (result) { +assert (obj && *obj); + }Roundabout way to write
assert(!result || (obj && *obj));
Quoted 7 lines
Quoted 3 lines
Heh, you even assert one half of what I'm trying to prove.
Can we make it assert(result == (
visit_is_input(v)&& obj && *obj) ?Missing a ); guessing that you meant:
assert(result == (visit_is_input(v) && obj && *obj));
Yes.
Quoted 1 line
Yes, I think we can, but we'd need a
visit_is_input()helper.
Right now, I'm not proposing to change the assertion, I'm only trying to find out whether we actually need the return value.
Quoted 13 lines
Quoted 4 lines
Quoted 4 lines
qapi/qapi-visit-core.c +0
-0@@ -236,7 +253,11 @@ void visit_type_str(Visitor *v, const char *name, char **obj, Error **errp)assert(*obj); } */ Quoted 8 lines
qapi/qapi-visit-core.c void visit_type_str(Visitor *v, const char *name, char **obj, Error **errp) · line 258
Quoted 4 lines
qapi/qapi-visit-core.c +3
-1- v->type_str (v, name, obj, errp); + v->type_str (v, name, obj, &err); +if (!visit_is_output (v) && err) { + *obj =NULL ;Shouldn't storing null on error be left to
v->type_str(), like we do for structs and lists? Not least because it begs the question whether this leaks a string stored by it.
Quoted 1 line
May be worthwhile to mandate that tighter semantics on each visitor.
Yes, please. If we adopt consistent behaviors (1) or (2), a general rule will cover them all.
Quoted 22 lines
Quoted 22 lines
Quoted 9 lines
scripts/qapi-visit.py +4
-0+++ b/scripts/qapi-visit.py@@ -301,10 +316,15 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error visit_check_struct(v, &err); out_obj: visit_end_struct(v); + if (allocated && err) { + qapi_free_%(c_name)s(*obj); + *obj = NULL;scripts/qapi-visit.py void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error · line 330
Quoted 10 lines
scripts/qapi-visit.py +3
-1+ } out: error_propagate(errp, err); } -''') +''', + c_name=c_name(name)) return retHmm.
Quoted 8 lines
Quoted 5 lines
This grows
qapi-visit.cby 14% for me.Can we do the deallocation in the visitor core somehow? We'd have to pass "how to deallocate" information: the appropriate
qapi_free_FOO()function. We already pass in "how to allocate" information: size.I thought about that; do we really want to be type-punning functions like that? But it does sound smaller; I can play with the idea.
Type-punning functions is usually a bad idea. Calling the result has undefined behavior unless the two function types are compatible. The function types at hand differ only in the parameter type, but void * would not be compatible with some struct QAPIType *.
As long as the two pointer types have the same representation, the compiler would have to work to actually screw this up.
A perfectly clean solution would need a wrapper function, negating some of the code savings.
Quoted 9 lines
Quoted 6 lines
Now I've seen the complete patch, two more remarks:
* I think all the allocating methods should behave the same. Right now, some store null on failure, and some don't. For the latter to work, the value must be null initially (or else the dealloc visitor runs amok).
Agree; I'm leaning towards ALL allocating methods must store into *obj (either NULL on failure, or object on success).
If this was a function return value, correct behavior would be obvious:
return object on success, return null on failure. Equivalent to (2). But this is a side effect. There, I rather like "do nothing on failure". That's (1).
But "rather like" doesn't justify implementation complexity. If (2) turns out to be simpler, go for it.
Quoted 6 lines
Quoted 2 lines
* Do we really need the new return value? It looks like it's always equal to
visit_is_input(v)&& obj && *obj.Except we don't (yet) have a
visit_is_input()function, let alone one visible from within the generatedqapi-visit.ccode. Maybe doing that first would help.
If we move the destruction into the core, this problem goes away:
void visit_type_T(Visitor *v, const char *name, T **obj, Error **errp)
{
Error *err = NULL;
visit_start_struct(v, name, (void **)obj, sizeof(T), &err);
if (err) {
goto out;
}
if (!*obj) {
goto out_obj;
}
visit_type_T_fields(v, obj, &err);
if (err) {
goto out_obj;
}
visit_check_struct(v, &err);
out_obj:
visit_end_struct(v, qapi_free_T); // type punning omitted here
out:
error_propagate(errp, err);
}v->end_struct() frees if v is an input visitor and an error occured. The former condition is trivial, the latter requires tracking errors. Storing &err in the stack object could do. Alternatively, pass err through visit_end_struct() to v->end_struct().
Yet another way to skin this cat: instead of freeing, end_struct() returns whether to free. Looks like this:
out_obj:
if (visit_end_struct(v)) {
qapi_free_T(*obj);
}or maybe returns whether something was allocated:
out_obj:
if (visit_end_struct(v) && err) {
qapi_free_T(*obj);
}These are perhaps the simplest solutions so far.
Re: [Qemu-devel] [PATCH v9 35/37] qapi: Change visit_type_FOO() to no longer return partial objects
Quoted 10 lines · Markus Armbruster
With (1) don't assign, the caller can pick an error value by assigning it before the visit, and it must not access the value on error unless it does.
With (2) assign zero, the caller can't pick an error value, but may safely access the value even on error.
Tradeoff. I figure either can work for us.
Quoted 8 lines
Quoted 6 lines
Quoted 4 lines
(3) Assign null pointer, else don't assign anything
CON: inconsistent CON: mix of (1)'s and (2)'s CONWhich I think is what I did in this patch.
I don't like the inconsistency. It complicates the interface.
I'll go ahead and audit to see whether more scalar visits were relying on (1) and would have to be rewritten to use style (2); vs. whether more pointer visits were passing in uninitialized obj and would have to be rewritten to use style (1).
Quoted 6 lines
I think behavior (1) don't assign and (2) assign zero both work, we just have to pick one and run with it.
If we pick behavior (1) don't assign, then we should assert something like !obj || !*obj on entry. With such assertions in place, I think (1) should be roughly as safe as (2).
I think your assessment is right, and it's now just a matter of seeing which way to get to a consistent state is less effort (I may still end up doing both ways as competing patches, for comparison purposes).
Quoted 6 lines
or maybe returns whether something was allocated:
out_obj: if (visit_end_struct(v) && err) { qapi_free_T(*obj); }
I'm liking that. Dealloc and output visitors always return false, and input visitors may need to track something on their stack for whether they allocated or returned error earlier on, but it results in less generated output. Basically, it's lowering the 'bool allocated' that I added in this attempt out of the generated code and into the visitors.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
PATCH v9 36/37 RFC: qapi: Adjust layout of FooList types
In reply to Eric BlakeBy sticking the next pointer first, we don't need a union with 64-bit padding for smaller types. On 32-bit platforms, this can reduce the size of uint8List from 16 bytes (or 12, depending on whether 64-bit ints can tolerate 4-byte alignment) down to 8. It has no effect on 64-bit platforms (where alignment still dictates a 16-byte struct); but fewer anonymous unions is still a win in my book.
However, this requires visit_start_list() and visit_next_list() to gain a size parameter, to know what size element to allocate.
I debated about going one step further, to allow for fewer casts, by doing:
typedef GenericList GenericList;
struct GenericList {
GenericList *next;
};
struct FooList {
GenericList base;
Foo value;
};so that you convert to 'GenericList *' by '&foolist->base', and back by 'container_of(generic, GenericList, base)' (as opposed to the existing '(GenericList *)foolist' and '(FooList *)generic'). But doing that would require hoisting the declaration of GenericList prior to inclusion of qapi-types.h, rather than its current spot in visitor.h; it also makes iteration a bit more verbose through 'foolist->base.next' instead of 'foolist->next'.
---
v9: no change
v8: rebase to earlier changes
v7: new patch; probably too invasive to be worth it, especially if we can't prove that our current size for uint8List is a bottleneck
--- hw/ppc/spapr_drc.c | 2 +- include/qapi/visitor-impl.h | 5 +++-- include/qapi/visitor.h | 39 +++++++++++++++++++-------------------- qapi/opts-visitor.c | 9 +++++---- qapi/qapi-dealloc-visitor.c | 5 +++-- qapi/qapi-visit-core.c | 14 +++++++++----- qapi/qmp-input-visitor.c | 8 ++++---- qapi/qmp-output-visitor.c | 5 +++-- qapi/string-input-visitor.c | 9 +++++---- qapi/string-output-visitor.c | 5 +++-- scripts/qapi-types.py | 5 +---- scripts/qapi-visit.py | 4 ++-- 12 files changed, 58 insertions(+), 52 deletions(-)
hw/ppc/spapr_drc.c +1 -1
@@ -299,7 +299,7 @@ static void prop_get_fdt(Object *obj, Visitor *v, const char *name,int i; prop =fdt_get_property_by_offset (fdt, fdt_offset, &prop_len); name =fdt_string (fdt,fdt32_to_cpu (prop->nameoff)); -visit_start_list (v, name,NULL , &err); +visit_start_list (v, name,NULL ,0 , &err);if (err) {error_propagate (errp, err);return ;
include/qapi/visitor-impl.h +3 -2
@@ -41,9 +41,10 @@ struct Visitor/* Must be set */ bool (*start_list)(Visitor *v,const char *name,GenericList **list, -Error **errp); +size_t size,Error **errp);/* Must be set */ - GenericList *(*next_list)(Visitor *v, GenericList *element, Error **errp); +GenericList *(*next_list)(Visitor *v,GenericList *element,size_t size, +Error **errp);/* Must be set */ void (*end_list)(Visitor *v);
include/qapi/visitor.h +19 -20
@@ -56,11 +56,8 @@* created by the qapi generator. */ typedef struct GenericList { -union { -void *value; -uint64_t padding; - };struct GenericList *next; +char padding[]; }GenericList ;/**
@@ -130,19 +127,19 @@ void visit_end_implicit_struct(Visitor *v);/** * Prepare to visit a list tied to an object key @name. * @name will be NULL if this is visited as part of another list. -* Input visitors malloc a qapi List struct into *@list, or set it to -* NULL if there are no elements in the list; and output visitors -* expect *@list to point to the start of the list, if any. On -* return, if *@list is non-NULL, the caller should enter a loop +* Input visitors malloc a qapi List struct into *@list of size @size, +* or set it to NULL if there are no elements in the list; and output +* visitors expect *@list to point to the start of the list, if any. +* On return, if *@list is non-NULL, the caller should enter a loop * visiting the current element, then using visit_next_list() to * advance to the next element, until that returns NULL; then * visit_end_list() must be used to complete the visit. * -* If supported by a visitor, @list can be NULL to indicate that there -* is no qapi List struct, and that the upcoming visit calls are -* parsing input to or creating output from some other representation; -* in this case, visit_next_list() will not be needed, but -* visit_end_list() is still mandatory. +* If supported by a visitor, @list can be NULL (and @size 0) to +* indicate that there is no qapi List struct, and that the upcoming +* visit calls are parsing input to or creating output from some other +* representation; in this case, visit_next_list() will not be needed, +* but visit_end_list() is still mandatory. * * Returns true if *@list was allocated; if that happens, and an error * occurs any time before the matching visit_end_list(), then the
@@ -150,17 +147,19 @@ void visit_end_implicit_struct(Visitor *v);* allocation before returning control further. */ bool visit_start_list (Visitor *v,const char *name,GenericList **list, -Error **errp); +size_t size,Error **errp);/** * Iterate over a GenericList during a list visit. * Before calling this function, the caller should use the appropriate -* visit_type_FOO() for the current list element at @element->value, and -* check for errors. @element must not be NULL; on the first iteration, -* it should be the value in *list after visit_start_list(); on other -* calls it should be the previous return value. This function -* returns NULL once there are no further list elements. +* visit_type_FOO() for the current list element at @element->value, +* and check for errors. @element must not be NULL; on the first +* iteration, it should be the value in *list after +* visit_start_list(); on other calls it should be the previous return +* value. @size should be the same as for visit_start_list(). This +* function returns NULL once there are no further list elements. */ -GenericList *visit_next_list (Visitor *v,GenericList *element,Error **errp); +GenericList *visit_next_list (Visitor *v,GenericList *element,size_t size, +Error **errp);/** * Complete the list started earlier. * Must be called after any successful use of visit_start_list(),
qapi/opts-visitor.c +5 -4
@@ -214,7 +214,8 @@ lookup_distinct(const OptsVisitor *ov, const char *name, Error **errp)static bool -opts_start_list (Visitor *v,const char *name,GenericList **list,Error **errp) +opts_start_list (Visitor *v,const char *name,GenericList **list,size_t size, +Error **errp) {OptsVisitor *ov =to_ov (v);
@@ -225,7 +226,7 @@ opts_start_list(Visitor *v, const char *name, GenericList **list, Error **errp) ov->repeated_opts =lookup_distinct (ov, name, errp);if (ov->repeated_opts) { ov->list_mode =LM_IN_PROGRESS ; - *list =g_new0 (GenericList,1 ); + *list =g_malloc0 (size);return true; }else { *list =NULL ;
@@ -235,7 +236,7 @@ opts_start_list(Visitor *v, const char *name, GenericList **list, Error **errp)static GenericList * -opts_next_list (Visitor *v,GenericList *list,Error **errp) +opts_next_list (Visitor *v,GenericList *list,size_t size,Error **errp) {OptsVisitor *ov =to_ov (v);
@@ -269,7 +270,7 @@ opts_next_list(Visitor *v, GenericList *list, Error **errp)abort (); } - list->next =g_new0 (GenericList,1 ); + list->next =g_malloc0 (size);return list->next; }
qapi/qapi-dealloc-visitor.c +3 -2
@@ -90,7 +90,8 @@ static void qapi_dealloc_end_implicit_struct(Visitor *v) }static bool qapi_dealloc_start_list (Visitor *v,const char *name, -GenericList **list,Error **errp) +GenericList **list,size_t size, +Error **errp) {QapiDeallocVisitor *qov =to_qov (v);qapi_dealloc_push (qov,NULL );
@@ -98,7 +99,7 @@ static bool qapi_dealloc_start_list(Visitor *v, const char *name, }static GenericList *qapi_dealloc_next_list (Visitor *v,GenericList *list, -Error **errp) +size_t size,Error **errp) {GenericList *next = list->next;g_free (list);
qapi/qapi-visit-core.c +9 -5
@@ -80,19 +80,23 @@ void visit_end_implicit_struct(Visitor *v) }bool visit_start_list (Visitor *v,const char *name,GenericList **list, -Error **errp) +size_t size,Error **errp) { -bool result = v->start_list (v, name, list, errp); +bool result; + +assert (list ? size : !size); + result = v->start_list (v, name, list, size, errp);if (result) {assert (list && *list); }return result; } -GenericList *visit_next_list (Visitor *v,GenericList *list,Error **errp) +GenericList *visit_next_list (Visitor *v,GenericList *list,size_t size, +Error **errp) { -assert (list); -return v->next_list (v, list, errp); +assert (list && size); +return v->next_list (v, list, size, errp); }void visit_end_list (Visitor *v)
qapi/qmp-input-visitor.c +4 -4
@@ -168,7 +168,7 @@ static bool qmp_input_start_implicit_struct(Visitor *v, void **obj, }static bool qmp_input_start_list (Visitor *v,const char *name, -GenericList **list,Error **errp) +GenericList **list,size_t size,Error **errp) {QmpInputVisitor *qiv =to_qiv (v);QObject *qobj =qmp_input_get_object (qiv, name, true);
@@ -184,7 +184,7 @@ static bool qmp_input_start_list(Visitor *v, const char *name,qmp_input_push (qiv, qobj, entry, errp);if (list) {if (entry) { - *list =g_new0 (GenericList,1 ); + *list =g_malloc0 (size);return true; }else { *list =NULL ;
@@ -194,7 +194,7 @@ static bool qmp_input_start_list(Visitor *v, const char *name, }static GenericList *qmp_input_next_list (Visitor *v,GenericList *list, -Error **errp) +size_t size,Error **errp) {QmpInputVisitor *qiv =to_qiv (v);StackObject *so = &qiv->stack[qiv->nb_stack -1 ];
@@ -202,7 +202,7 @@ static GenericList *qmp_input_next_list(Visitor *v, GenericList *list,if (!so->entry) {return NULL ; } - list->next =g_new0 (GenericList,1 ); + list->next =g_malloc0 (size);return list->next; }
qapi/qmp-output-visitor.c +3 -2
@@ -120,7 +120,8 @@ static void qmp_output_end_struct(Visitor *v) }static bool qmp_output_start_list (Visitor *v,const char *name, -GenericList **listp,Error **errp) +GenericList **listp,size_t size, +Error **errp) {QmpOutputVisitor *qov =to_qov (v);QList *list =qlist_new ();
@@ -131,7 +132,7 @@ static bool qmp_output_start_list(Visitor *v, const char *name, }static GenericList *qmp_output_next_list (Visitor *v,GenericList *list, -Error **errp) +size_t size,Error **errp) {return list->next; }
qapi/string-input-visitor.c +5 -4
@@ -121,7 +121,8 @@ error: }static bool -start_list (Visitor *v,const char *name,GenericList **list,Error **errp) +start_list (Visitor *v,const char *name,GenericList **list,size_t size, +Error **errp) {StringInputVisitor *siv =to_siv (v);Error *err =NULL ;
@@ -141,7 +142,7 @@ start_list(Visitor *v, const char *name, GenericList **list, Error **errp)if (r) { siv->cur = r->begin; } - *list =g_new0 (GenericList,1 ); + *list =g_malloc0 (size);return true; }else { *list =NULL ;
@@ -150,7 +151,7 @@ start_list(Visitor *v, const char *name, GenericList **list, Error **errp) }static GenericList * -next_list (Visitor *v,GenericList *list,Error **errp) +next_list (Visitor *v,GenericList *list,size_t size,Error **errp) {StringInputVisitor *siv =to_siv (v);Range *r;
@@ -176,7 +177,7 @@ next_list(Visitor *v, GenericList *list, Error **errp) siv->cur = r->begin; } - list->next =g_new0 (GenericList,1 ); + list->next =g_malloc0 (size);return list->next; }
qapi/string-output-visitor.c +3 -2
@@ -264,7 +264,8 @@ static void print_type_number(Visitor *v, const char *name, double *obj, }static bool -start_list (Visitor *v,const char *name,GenericList **list,Error **errp) +start_list (Visitor *v,const char *name,GenericList **list,size_t size, +Error **errp) {StringOutputVisitor *sov =to_sov (v);
@@ -280,7 +281,7 @@ start_list(Visitor *v, const char *name, GenericList **list, Error **errp) }static GenericList * -next_list (Visitor *v,GenericList *list,Error **errp) +next_list (Visitor *v,GenericList *list,size_t size,Error **errp) {StringOutputVisitor *sov =to_sov (v);GenericList *ret = list->next;
scripts/qapi-types.py +1 -4
@@ -26,11 +26,8 @@ def gen_array(name, element_type): return mcgen(''' struct %(c_name)s { - union { - %(c_type)s value; - uint64_t padding; - }; %(c_name)s *next; + %(c_type)s value; }; ''', c_name=c_name(name), c_type=element_type.c_type())
scripts/qapi-visit.py +2 -2
@@ -130,7 +130,7 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error %(c_name)s *elt; bool allocated; - allocated = visit_start_list(v, name, (GenericList **)obj, &err); + allocated = visit_start_list(v, name, (GenericList **)obj, sizeof(%(c_name)s), &err); if (err) { goto out; }
@@ -140,7 +140,7 @@ void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s **obj, Error if (err) { break; } - elt = (%(c_name)s *)visit_next_list(v, (GenericList *)elt, &err); + elt = (%(c_name)s *)visit_next_list(v, (GenericList *)elt, sizeof(%(c_name)s), &err); if (err) { break; }
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 36/37] RFC: qapi: Adjust layout of FooList types
Quoted 86 lines · Eric Blake
By sticking the next pointer first, we don't need a union with 64-bit padding for smaller types. On 32-bit platforms, this can reduce the size of uint8List from 16 bytes (or 12, depending on whether 64-bit ints can tolerate 4-byte alignment) down to 8. It has no effect on 64-bit platforms (where alignment still dictates a 16-byte struct); but fewer anonymous unions is still a win in my book.
However, this requires
visit_start_list()andvisit_next_list()to gain a size parameter, to know what size element to allocate.I debated about going one step further, to allow for fewer casts, by doing:
typedef GenericList GenericList; struct GenericList { GenericList *next; }; struct FooList { GenericList base; Foo value; };so that you convert to 'GenericList *' by '
&foolist->base', and back by 'container_of(generic, GenericList, base)' (as opposed to the existing '(GenericList *)foolist' and '(FooList *)generic'). But doing that would require hoisting the declaration of GenericList prior to inclusion ofqapi-types.h, rather than its current spot invisitor.h; it also makes iteration a bit more verbose through 'foolist->base.next' instead of 'foolist->next'.Signed-off-by Eric Blake <[email protected]>---
v9: no change
v8: rebase to earlier changes
v7: new patch; probably too invasive to be worth it, especially if we can't prove that our current size for uint8List is a bottleneck--- hw/ppc/spapr_drc.c | 2 +- include/qapi/visitor-impl.h | 5 +++-- include/qapi/visitor.h | 39 +++++++++++++++++++-------------------- qapi/opts-visitor.c | 9 +++++---- qapi/qapi-dealloc-visitor.c | 5 +++-- qapi/qapi-visit-core.c | 14 +++++++++----- qapi/qmp-input-visitor.c | 8 ++++---- qapi/qmp-output-visitor.c | 5 +++-- qapi/string-input-visitor.c | 9 +++++---- qapi/string-output-visitor.c | 5 +++-- scripts/qapi-types.py | 5 +---- scripts/qapi-visit.py | 4 ++-- 12 files changed, 58 insertions(+), 52 deletions(-)hw/ppc/spapr_drc.c +1
-1@@ -299,7 +299,7 @@ static void prop_get_fdt(Object *obj, Visitor *v, const char *name,int i; prop =fdt_get_property_by_offset (fdt, fdt_offset, &prop_len); name =fdt_string (fdt,fdt32_to_cpu (prop->nameoff)); -visit_start_list (v, name,NULL , &err); +visit_start_list (v, name,NULL ,0 , &err);if (err) {error_propagate (errp, err);return ;include/qapi/visitor-impl.h +3
-2@@ -41,9 +41,10 @@ struct Visitor/* Must be set */ bool (*start_list)(Visitor *v,const char *name,GenericList **list, -Error **errp); +size_t size,Error **errp);/* Must be set */ - GenericList *(*next_list)(Visitor *v, GenericList *element, Error **errp); +GenericList *(*next_list)(Visitor *v,GenericList *element,size_t size, +Error **errp);/* Must be set */ void (*end_list)(Visitor *v);include/qapi/visitor.h +0
-0
include/qapi/visitor.h line 61
Quoted 10 lines
include/qapi/visitor.h +1
-4@@ -56,11 +56,8 @@* created by the qapi generator. */ typedef struct GenericList { -union { -void *value; -uint64_t padding; - };struct GenericList *next; +char padding[]; }GenericList ;
Less trickery, I like it.
Member padding appears to be unused.
Quoted 127 lines
include/qapi/visitor.h +18
-16/** @@ -130,19 +127,19 @@ void visit_end_implicit_struct(Visitor *v);/** * Prepare to visit a list tied to an object key @name. * @name will be NULL if this is visited as part of another list. -* Input visitors malloc a qapi List struct into *@list, or set it to -* NULL if there are no elements in the list; and output visitors -* expect *@list to point to the start of the list, if any. On -* return, if *@list is non-NULL, the caller should enter a loop +* Input visitors malloc a qapi List struct into *@list of size @size, +* or set it to NULL if there are no elements in the list; and output +* visitors expect *@list to point to the start of the list, if any. +* On return, if *@list is non-NULL, the caller should enter a loop * visiting the current element, then using visit_next_list() to * advance to the next element, until that returns NULL; then * visit_end_list() must be used to complete the visit. * -* If supported by a visitor, @list can be NULL to indicate that there -* is no qapi List struct, and that the upcoming visit calls are -* parsing input to or creating output from some other representation; -* in this case, visit_next_list() will not be needed, but -* visit_end_list() is still mandatory. +* If supported by a visitor, @list can be NULL (and @size 0) to +* indicate that there is no qapi List struct, and that the upcoming +* visit calls are parsing input to or creating output from some other +* representation; in this case, visit_next_list() will not be needed, +* but visit_end_list() is still mandatory. * * Returns true if *@list was allocated; if that happens, and an error * occurs any time before the matching visit_end_list(), then the @@ -150,17 +147,19 @@ void visit_end_implicit_struct(Visitor *v);* allocation before returning control further. */ bool visit_start_list (Visitor *v,const char *name,GenericList **list, -Error **errp); +size_t size,Error **errp);/** * Iterate over a GenericList during a list visit. * Before calling this function, the caller should use the appropriate -* visit_type_FOO() for the current list element at @element->value, and -* check for errors. @element must not be NULL; on the first iteration, -* it should be the value in *list after visit_start_list(); on other -* calls it should be the previous return value. This function -* returns NULL once there are no further list elements. +* visit_type_FOO() for the current list element at @element->value, +* and check for errors. @element must not be NULL; on the first +* iteration, it should be the value in *list after +* visit_start_list(); on other calls it should be the previous return +* value. @size should be the same as for visit_start_list(). This +* function returns NULL once there are no further list elements. */ -GenericList *visit_next_list (Visitor *v,GenericList *element,Error **errp); +GenericList *visit_next_list (Visitor *v,GenericList *element,size_t size, +Error **errp);/** * Complete the list started earlier. * Must be called after any successful use of visit_start_list(), qapi/opts-visitor.c +5
-4@@ -214,7 +214,8 @@ lookup_distinct(const OptsVisitor *ov, const char *name, Error **errp)static bool -opts_start_list (Visitor *v,const char *name,GenericList **list,Error **errp) +opts_start_list (Visitor *v,const char *name,GenericList **list,size_t size, +Error **errp) {OptsVisitor *ov =to_ov (v);@@ -225,7 +226,7 @@ opts_start_list(Visitor *v, const char *name, GenericList **list, Error **errp) ov->repeated_opts =lookup_distinct (ov, name, errp);if (ov->repeated_opts) { ov->list_mode =LM_IN_PROGRESS ; - *list =g_new0 (GenericList,1 ); + *list =g_malloc0 (size);return true; }else { *list =NULL ;@@ -235,7 +236,7 @@ opts_start_list(Visitor *v, const char *name, GenericList **list, Error **errp)static GenericList * -opts_next_list (Visitor *v,GenericList *list,Error **errp) +opts_next_list (Visitor *v,GenericList *list,size_t size,Error **errp) {OptsVisitor *ov =to_ov (v);@@ -269,7 +270,7 @@ opts_next_list(Visitor *v, GenericList *list, Error **errp)abort (); } - list->next =g_new0 (GenericList,1 ); + list->next =g_malloc0 (size);return list->next; }qapi/qapi-dealloc-visitor.c +3
-2@@ -90,7 +90,8 @@ static void qapi_dealloc_end_implicit_struct(Visitor *v) }static bool qapi_dealloc_start_list (Visitor *v,const char *name, -GenericList **list,Error **errp) +GenericList **list,size_t size, +Error **errp) {QapiDeallocVisitor *qov =to_qov (v);qapi_dealloc_push (qov,NULL );@@ -98,7 +99,7 @@ static bool qapi_dealloc_start_list(Visitor *v, const char *name, }static GenericList *qapi_dealloc_next_list (Visitor *v,GenericList *list, -Error **errp) +size_t size,Error **errp) {GenericList *next = list->next;g_free (list);qapi/qapi-visit-core.c +0
-0
qapi/qapi-visit-core.c void visit_end_implicit_struct(Visitor *v) · line 87
Quoted 10 lines
qapi/qapi-visit-core.c +4
-2@@ -80,19 +80,23 @@ void visit_end_implicit_struct(Visitor *v) }bool visit_start_list (Visitor *v,const char *name,GenericList **list, -Error **errp) +size_t size,Error **errp) { -bool result = v->start_list (v, name, list, errp); +bool result; + +assert (list ? size : !size);
Tighter than size != 0 would be size >= GenericList. Same elsewhere.
Quoted 8 lines
qapi/qapi-visit-core.c +1
-1+ result = v->start_list (v, name, list, size, errp);if (result) {assert (list && *list); }return result; } -GenericList *visit_next_list (Visitor *v,GenericList *list,Error **errp)
qapi/qapi-visit-core.c void visit_end_implicit_struct(Visitor *v) · line 102
Quoted 10 lines
qapi/qapi-visit-core.c +4
-2+GenericList *visit_next_list (Visitor *v,GenericList *list,size_t size, +Error **errp) { -assert (list); -return v->next_list (v, list, errp); +assert (list && size); +return v->next_list (v, list, size, errp); }void visit_end_list (Visitor *v)
[...]
Rest looks good. Didn't look as closely as for the previous patches (getting tired), but so far I like the idea.
Re: [Qemu-devel] [PATCH v9 36/37] RFC: qapi: Adjust layout of FooList types
Quoted 22 lines · Markus Armbruster
Quoted 20 lines · Eric Blake
By sticking the next pointer first, we don't need a union with 64-bit padding for smaller types. On 32-bit platforms, this can reduce the size of uint8List from 16 bytes (or 12, depending on whether 64-bit ints can tolerate 4-byte alignment) down to 8. It has no effect on 64-bit platforms (where alignment still dictates a 16-byte struct); but fewer anonymous unions is still a win in my book.
However, this requires
visit_start_list()andvisit_next_list()to gain a size parameter, to know what size element to allocate.I debated about going one step further, to allow for fewer casts, by doing:
typedef GenericList GenericList; struct GenericList { GenericList *next; }; struct FooList { GenericList base; Foo value;
Quoted 8 lines
Quoted 8 lines
};so that you convert to 'GenericList *' by '
&foolist->base', and back by 'container_of(generic, GenericList, base)' (as opposed to the existing '(GenericList *)foolist' and '(FooList *)generic'). But doing that would require hoisting the declaration of GenericList prior to inclusion ofqapi-types.h, rather than its current spot invisitor.h; it also makes iteration a bit more verbose through 'foolist->base.next' instead of 'foolist->next'.
Should I attempt this?
Quoted 10 lines
include/qapi/visitor.h line 61
Quoted 9 lines
typedef struct GenericList
{include/qapi/visitor.h +1
-4-union { -void *value; -uint64_t padding; - };struct GenericList *next; +char padding[]; } GenericList;
Quoted 3 lines
Less trickery, I like it.
Member padding appears to be unused.
or just leave it at this?
Quoted 10 lines
qapi/qapi-visit-core.c void visit_end_implicit_struct(Visitor *v) · line 87
Quoted 8 lines
bool visit_start_list(Visitor *v, const char *name, GenericList **list,
qapi/qapi-visit-core.c +4
-2- Error **errp) + size_t size, Error **errp) { -bool result = v->start_list (v, name, list, errp); + bool result; + +assert (list ? size : !size);Tighter than size != 0 would be size >= GenericList. Same elsewhere.
Makes sense.
Quoted 3 lines
Rest looks good. Didn't look as closely as for the previous patches (getting tired), but so far I like the idea.
Okay, I'll keep it and drop the RFC.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v9 36/37] RFC: qapi: Adjust layout of FooList types
Quoted 32 lines · Eric Blake
Quoted 22 lines · Markus Armbruster
Quoted 20 lines · Eric Blake
By sticking the next pointer first, we don't need a union with 64-bit padding for smaller types. On 32-bit platforms, this can reduce the size of uint8List from 16 bytes (or 12, depending on whether 64-bit ints can tolerate 4-byte alignment) down to 8. It has no effect on 64-bit platforms (where alignment still dictates a 16-byte struct); but fewer anonymous unions is still a win in my book.
However, this requires
visit_start_list()andvisit_next_list()to gain a size parameter, to know what size element to allocate.I debated about going one step further, to allow for fewer casts, by doing:
typedef GenericList GenericList; struct GenericList { GenericList *next; }; struct FooList { GenericList base; Foo value;Quoted 8 lines
Quoted 8 lines
};so that you convert to 'GenericList *' by '
&foolist->base', and back by 'container_of(generic, GenericList, base)' (as opposed to the existing '(GenericList *)foolist' and '(FooList *)generic'). But doing that would require hoisting the declaration of GenericList prior to inclusion ofqapi-types.h, rather than its current spot invisitor.h; it also makes iteration a bit more verbose through 'foolist->base.next' instead of 'foolist->next'.
Quoted 1 line
Should I attempt this?
A quick grep for '(GenericList' finds two in qapi-code-gen.txt, and two in qapi-visit-py. I doubt avoiding them is worth much of your time or mine :)
Quoted 10 lines
Quoted 10 lines
Quoted 9 lines
typedef struct GenericList
{include/qapi/visitor.h +1
-4-union { -void *value; -uint64_t padding; - };struct GenericList *next; +char padding[]; } GenericList;
Quoted 5 lines
Quoted 3 lines
Less trickery, I like it.
Member padding appears to be unused.
or just leave it at this?
I'd say good enough.
Quoted 11 lines
Quoted 10 lines
qapi/qapi-visit-core.c void visit_end_implicit_struct(Visitor *v) · line 87
Quoted 8 lines
bool visit_start_list(Visitor *v, const char *name, GenericList **list,
qapi/qapi-visit-core.c +4
-2- Error **errp) + size_t size, Error **errp) { -bool result = v->start_list (v, name, list, errp); + bool result; + +assert (list ? size : !size);Tighter than size != 0 would be size >= GenericList. Same elsewhere.
Quoted 7 lines
Makes sense.
Quoted 3 lines
Rest looks good. Didn't look as closely as for the previous patches (getting tired), but so far I like the idea.
Okay, I'll keep it and drop the RFC.
Thanks!
PATCH v9 37/37 qapi: Update docs to match recent generator changes
In reply to Eric BlakeSeveral commits have been changing the generator, but not updating the docs to match:
- The implicit tag member is named "type", not "kind". Screwed up in commit 39a1815.
- Commit 9f08c8ec made list types lazy, and thereby dropped UserDefOneList if nothing explicitly uses the list type.
- The parameter order has switched 'name' to occur earlier.
- The generated code now checks for partial allocations.
- etc.
Rework the examples to show slightly more output (we don't want to show too much; that's what the testsuite is for), and regenerate the output to match all recent changes.
---
v9: new patch
--- docs/qapi-code-gen.txt | 130 +++++++++++++++++++++++++++++-------------------- 1 file changed, 78 insertions(+), 52 deletions(-)
docs/qapi-code-gen.txt +78 -52
@@ -1,7 +1,7 @@ = How to use the QAPI code generator = Copyright IBM Corp. 2011 -Copyright (C) 2012-2015 Red Hat, Inc. +Copyright (C) 2012-2016 Red Hat, Inc. This work is licensed under the terms of the GNU GPL, version 2 or later. See the COPYING file in the top-level directory.
@@ -655,7 +655,7 @@ Union types { "name": "BlockdevOptions", "meta-type": "object", "members": [ - { "name": "kind", "type": "BlockdevOptionsKind" } ], + { "name": "type", "type": "BlockdevOptionsKind" } ], "tag": "type", "variants": [ { "case": "file", "type": ":obj-FileOptions-wrapper" },
@@ -721,29 +721,34 @@ the names of built-in types. Clients should examine member == Code generation == -Schemas are fed into four scripts to generate all the code/files that, +Schemas are fed into five scripts to generate all the code/files that, paired with the core QAPI libraries, comprise everything required to take JSON commands read in by a Client JSON Protocol server, unmarshal the arguments into the underlying C types, call into the corresponding -C function, and map the response back to a Client JSON Protocol -response to be returned to the user. +C function, map the response back to a Client JSON Protocol response +to be returned to the user, and introspect the commands. -As an example, we'll use the following schema, which describes a single -complex user-defined type (which will produce a C struct, along with a list -node structure that can be used to chain together a list of such types in -case we want to accept/return a list of this type with a command), and a -command which takes that type as a parameter and returns the same type: +As an example, we'll use the following schema, which describes a +single complex user-defined type, along with command which takes a +list of that type as a parameter. The user is responsible for writing +the implementation of qmp_my_command(); everything else is produced by +the generator. $ cat example-schema.json { 'struct': 'UserDefOne', - 'data': { 'integer': 'int', 'string': 'str' } } + 'data': { 'integer': 'int', '*string': 'str' } } { 'command': 'my-command', - 'data': {'arg1': 'UserDefOne'}, + 'data': { 'arg1': ['UserDefOne'] }, 'returns': 'UserDefOne' } { 'event': 'MY_EVENT' } +For a more thorough look at generated code, the testsuite includes +tests/qapi-schema/qapi-schema-tests.json that covers more examples of +what the generator will accept, and compiles the resulting C code as +part of 'make check-unit'. + === scripts/qapi-types.py === Used to generate the C types defined by a schema. The following files are
@@ -776,7 +781,7 @@ Example: qdv = qapi_dealloc_visitor_new(); v = qapi_dealloc_get_visitor(qdv); - visit_type_UserDefOne(v, &obj, NULL, NULL); + visit_type_UserDefOne(v, NULL, &obj, NULL); qapi_dealloc_visitor_cleanup(qdv); }
@@ -791,7 +796,7 @@ Example: qdv = qapi_dealloc_visitor_new(); v = qapi_dealloc_get_visitor(qdv); - visit_type_UserDefOneList(v, &obj, NULL, NULL); + visit_type_UserDefOneList(v, NULL, &obj, NULL); qapi_dealloc_visitor_cleanup(qdv); } $ cat qapi-generated/example-qapi-types.h
@@ -808,17 +813,15 @@ Example: struct UserDefOne { int64_t integer; + bool has_string; char *string; }; void qapi_free_UserDefOne(UserDefOne *obj); struct UserDefOneList { - union { - UserDefOne *value; - uint64_t padding; - }; UserDefOneList *next; + UserDefOne *value; }; void qapi_free_UserDefOneList(UserDefOneList *obj);
@@ -854,54 +857,76 @@ Example: { Error *err = NULL; - visit_type_int(v, &(*obj)->integer, "integer", &err); + visit_type_int(v, "integer", &(*obj)->integer, &err); if (err) { goto out; } - visit_type_str(v, &(*obj)->string, "string", &err); - if (err) { - goto out; + if (visit_optional(v, "string", &(*obj)->has_string)) { + visit_type_str(v, "string", &(*obj)->string, &err); + if (err) { + goto out; + } } out: error_propagate(errp, err); } - void visit_type_UserDefOne(Visitor *v, UserDefOne **obj, const char *name, Error **errp) + void visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp) { Error *err = NULL; + bool allocated; - visit_start_struct(v, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), &err); - if (!err) { - if (*obj) { - visit_type_UserDefOne_fields(v, obj, errp); - } - visit_end_struct(v, &err); + allocated = visit_start_struct(v, name, (void **)obj, sizeof(UserDefOne), + &err); + if (err) { + goto out; + } + if (!*obj) { + goto out_obj; + } + visit_type_UserDefOne_fields(v, obj, &err); + if (err) { + goto out_obj; } + visit_check_struct(v, &err); + out_obj: + visit_end_struct(v); + if (allocated && err) { + qapi_free_UserDefOne(*obj); + *obj = NULL; + } + out: error_propagate(errp, err); } - void visit_type_UserDefOneList(Visitor *v, UserDefOneList **obj, const char *name, Error **errp) + void visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp) { Error *err = NULL; - GenericList *i, **prev; + UserDefOneList *eld; + bool allocated; - visit_start_list(v, name, &err); + allocated = visit_start_list(v, name, (GenericList **)obj, sizeof(UserDefOneList), &err); if (err) { goto out; } - - for (prev = (GenericList **)obj; - !err && (i = visit_next_list(v, prev, &err)) != NULL; - prev = &i) { - UserDefOneList *native_i = (UserDefOneList *)i; - visit_type_UserDefOne(v, &native_i->value, NULL, &err); + elt = *obj; + while (elt) { + visit_type_UserDefOne(v, NULL, &elt->value, &err); + if (err) { + break; + } + elt = (UserDefOneList *)visit_next_list(v, (GenericList *)elt, sizeof(UserDefOneList), &err); + if (err) { + break; + } } - - error_propagate(errp, err); - err = NULL; - visit_end_list(v, &err); + visit_end_list(v); out: + if (allocated && err) { + qapi_free_UserDefOneList(*obj); + *obj = NULL; + } error_propagate(errp, err); } $ cat qapi-generated/example-qapi-visit.h
@@ -912,8 +937,8 @@ Example: [Visitors for built-in types omitted...] - void visit_type_UserDefOne(Visitor *v, UserDefOne **obj, const char *name, Error **errp); - void visit_type_UserDefOneList(Visitor *v, UserDefOneList **obj, const char *name, Error **errp); + void visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp); + void visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp); #endif
@@ -949,7 +974,7 @@ Example: Visitor *v; v = qmp_output_get_visitor(qov); - visit_type_UserDefOne(v, &ret_in, "unused", &err); + visit_type_UserDefOne(v, "unused", &ret_in, &err); if (err) { goto out; }
@@ -960,7 +985,7 @@ Example: qmp_output_visitor_cleanup(qov); qdv = qapi_dealloc_visitor_new(); v = qapi_dealloc_get_visitor(qdv); - visit_type_UserDefOne(v, &ret_in, "unused", NULL); + visit_type_UserDefOne(v, "unused", &ret_in, NULL); qapi_dealloc_visitor_cleanup(qdv); }
@@ -971,10 +996,10 @@ Example: QmpInputVisitor *qiv = qmp_input_visitor_new_strict(QOBJECT(args)); QapiDeallocVisitor *qdv; Visitor *v; - UserDefOne *arg1 = NULL; + UserDefOneList *arg1 = NULL; v = qmp_input_get_visitor(qiv); - visit_type_UserDefOne(v, &arg1, "arg1", &err); + visit_type_UserDefOne(v, "arg1", &arg1, &err); if (err) { goto out; }
@@ -991,7 +1016,7 @@ Example: qmp_input_visitor_cleanup(qiv); qdv = qapi_dealloc_visitor_new(); v = qapi_dealloc_get_visitor(qdv); - visit_type_UserDefOne(v, &arg1, "arg1", NULL); + visit_type_UserDefOne(v, "arg1", &arg1, NULL); qapi_dealloc_visitor_cleanup(qdv); }
@@ -1011,7 +1036,7 @@ Example: #include "qapi/qmp/qdict.h" #include "qapi/error.h" - UserDefOne *qmp_my_command(UserDefOne *arg1, Error **errp); + UserDefOne *qmp_my_command(UserDefOneList *arg1, Error **errp); #endif
@@ -1095,8 +1120,9 @@ Example: "{\"arg-type\": \"0\", \"meta-type\": \"event\", \"name\": \"MY_EVENT\"}, " "{\"arg-type\": \"1\", \"meta-type\": \"command\", \"name\": \"my-command\", \"ret-type\": \"2\"}, " "{\"members\": [], \"meta-type\": \"object\", \"name\": \"0\"}, " - "{\"members\": [{\"name\": \"arg1\", \"type\": \"2\"}], \"meta-type\": \"object\", \"name\": \"1\"}, " - "{\"members\": [{\"name\": \"integer\", \"type\": \"int\"}, {\"name\": \"string\", \"type\": \"str\"}], \"meta-type\": \"object\", \"name\": \"2\"}, " + "{\"members\": [{\"name\": \"arg1\", \"type\": \"[2]\"}], \"meta-type\": \"object\", \"name\": \"1\"}, " + "{\"members\": [{\"name\": \"integer\", \"type\": \"int\"}, {\"default\": null, \"name\": \"string\", \"type\": \"str\"}], \"meta-type\": \"object\", \"name\": \"2\"}, " + "{\"element-type\": \"2\", \"meta-type\": \"array\", \"name\": \"[2]\"}, " "{\"json-type\": \"int\", \"meta-type\": \"builtin\", \"name\": \"int\"}, " "{\"json-type\": \"string\", \"meta-type\": \"builtin\", \"name\": \"str\"}]"; $ cat qapi-generated/example-qmp-introspect.h
Signature · 1 line
2.5.0
Re: [Qemu-devel] [PATCH v9 37/37] qapi: Update docs to match recent generator changes
Quoted 58 lines · Eric Blake
Several commits have been changing the generator, but not updating the docs to match:
- The implicit tag member is named "type", not "kind". Screwed up in commit 39a1815.
- Commit9f08c8ecmade list types lazy, and thereby dropped UserDefOneList if nothing explicitly uses the list type.
- The parameter order has switched 'name' to occur earlier.
- The generated code now checks for partial allocations.
- etc.Rework the examples to show slightly more output (we don't want to show too much; that's what the testsuite is for), and regenerate the output to match all recent changes.
Reported-by Marc-André Lureau <[email protected]>Signed-off-by Eric Blake <[email protected]>Signed-off-by Markus Armbruster <[email protected]>---
v9: new patch--- docs/qapi-code-gen.txt | 130 +++++++++++++++++++++++++++++-------------------- 1 file changed, 78 insertions(+), 52 deletions(-)docs/qapi-code-gen.txt +4
-5@@ -1,7 +1,7 @@ = How to use the QAPI code generator = Copyright IBM Corp. 2011 -Copyright (C) 2012-2015 Red Hat, Inc. +Copyright (C) 2012-2016 Red Hat, Inc. This work is licensed under the terms of the GNU GPL, version 2 or later. See the COPYING file in the top-level directory.@@ -655,7 +655,7 @@ Union types { "name": "BlockdevOptions", "meta-type": "object", "members": [ - { "name": "kind", "type": "BlockdevOptionsKind" } ], + { "name": "type", "type": "BlockdevOptionsKind" } ], "tag": "type", "variants": [ { "case": "file", "type": ":obj-FileOptions-wrapper" },@@ -721,29 +721,34 @@ the names of built-in types. Clients should examine member == Code generation == -Schemas are fed into four scripts to generate all the code/files that, +Schemas are fed into five scripts to generate all the code/files that, paired with the core QAPI libraries, comprise everything required to take JSON commands read in by a Client JSON Protocol server, unmarshal the arguments into the underlying C types, call into the corresponding -C function, and map the response back to a Client JSON Protocol -response to be returned to the user. +C function, map the response back to a Client JSON Protocol response
docs/qapi-code-gen.txt the names of built-in types. Clients should examine member · line 733
Quoted 10 lines
docs/qapi-code-gen.txt +4
-5+to be returned to the user, and introspect the commands. -As an example, we'll use the following schema, which describes a single -complex user-defined type (which will produce a C struct, along with a list -node structure that can be used to chain together a list of such types in -case we want to accept/return a list of this type with a command), and a -command which takes that type as a parameter and returns the same type: +As an example, we'll use the following schema, which describes a +single complex user-defined type, along with command which takes a +list of that type as a parameter.
Lost: and returns the same type
Quoted 11 lines
docs/qapi-code-gen.txt +3
-2The user is responsible for writing +the implementation of qmp_my_command(); everything else is produced by +the generator. $ cat example-schema.json { 'struct': 'UserDefOne', - 'data': { 'integer': 'int', 'string': 'str' } } + 'data': { 'integer': 'int', '*string': 'str' } } { 'command': 'my-command', - 'data': {'arg1': 'UserDefOne'},
docs/qapi-code-gen.txt the names of built-in types. Clients should examine member · line 751
Quoted 10 lines
docs/qapi-code-gen.txt +6
-0+ 'data': { 'arg1': ['UserDefOne'] }, 'returns': 'UserDefOne' } { 'event': 'MY_EVENT' } +For a more thorough look at generated code, the testsuite includes +tests/qapi-schema/qapi-schema-tests.json that covers more examples of +what the generator will accept, and compiles the resulting C code as +part of 'make check-unit'. +
Good idea.
Remaining changes are all to example output. I'll check them when we're closer to merging this series.
Quoted 4 lines · Eric Blake
Based on qemu.git master. Pending prerequisites:
+ Not a strong dependency, but for qapi-tests to consistently pass, I needed a race fixed:
https://lists.gnu.org/archive/html/qemu-devel/2015-12/msg01827.html
Commit a174da3.
Series needs a rebase now. I figure there are enough actionable review insights to warrant a full respin.
However, the series' length makes review taxing. Could you try to split off an easier part for hopefully quick merging?
Non-easy topics, from memory:
* Retrofitting a contract to visitors.
* Shall we require visit_end_FOO() even after error? I have to admit review dampened my enthusiasm for this idea.
* PATCH 30+
[...]