Add qapi-to-JSON visitor
v6 cover Add qapi-to-JSON visitor
[5 months later...]
Going from qapi to QObject to JSON is wasteful compared to going straight from qapi to JSON. What's more, having QObject in the middle means that dict keys are shuffled according to hash ordering, while going straight from qapi means we match the .json QAPI file declaration order. Factoring out JSON visits to a common central file will make it easier to make any further tweaks, such as patching floating point output to be unambiguous.
Based on Markus' qapi-next branch, but should apply to current qemu.git master.
Diff from v4, which was at:
https://lists.gnu.org/archive/html/qemu-devel/2016-05/msg03220.html
(v4 was both JSON and clone visitors; v5 split out just the clone visitor, leaving just the JSON visitor and hence calling this v6):
- assert up front that we are no longer willing to receive or pass non-finite numbers through QMP
- drop experiment related to string-izing nonfinite numbers
- rebase to recent changes
- address other minor review comments from Markus
Available as a tag at:
git fetch git://repo.or.cz/qemu/ericb.git qapi-jsonv6
001/15:[down] 'qapi: Visitor documentation tweak'
002/15:[down] 'qapi: Assert finite use of 'number'' 003/15:[0013] [FC] 'qapi: Factor out JSON string escaping' 004/15:[0022] [FC] 'qapi: Factor out JSON number formatting' 005/15:[----] [--] 'qapi: Add qstring_append_printf()' 006/15:[----] [--] 'qapi: Use qstring_append_chr() where appropriate' 007/15:[----] [--] 'qstring: Add qstring_consume_str()' 008/15:[0022] [FC] 'qstring: Add qstring_wrap_str()' 009/15:[----] [-C] 'qobject: Consolidate qobject_to_json() calls' 010/15:[----] [--] 'tests: Test qobject_to_json() pretty formatting' 011/15:[0013] [FC] 'qapi: Add JSON output visitor' 012/15:[0012] [FC] 'qapi: Support pretty printing in JSON output visitor' 013/15:[0041] [FC] 'qobject: Implement qobject_to_json() atop JSON visitor' 014/15:[----] [--] 'qapi: Add 'any' support to JSON output' 015/15:[0002] [FC] 'qemu-img: Use new JSON output formatter'
Eric Blake (15):
qapi: Visitor documentation tweak
qapi: Assert finite use of 'number'
qapi: Factor out JSON string escaping
qapi: Factor out JSON number formatting
qapi: Add qstring_append_printf()
qapi: Use qstring_append_chr() where appropriate
qstring: Add qstring_consume_str()
qstring: Add qstring_wrap_str()
qobject: Consolidate qobject_to_json() calls
tests: Test qobject_to_json() pretty formatting
qapi: Add JSON output visitor
qapi: Support pretty printing in JSON output visitor
qobject: Implement qobject_to_json() atop JSON visitor
qapi: Add 'any' support to JSON output
qemu-img: Use new JSON output formatter
include/qapi/visitor.h | 33 +-- include/qapi/json-output-visitor.h | 29 +++ include/qapi/qmp/qjson.h | 16 +- include/qapi/qmp/qstring.h | 9 +- block.c | 5 +- block/accounting.c | 6 +- block/archipelago.c | 6 +- blockdev.c | 3 +- migration/migration.c | 4 + migration/qjson.c | 12 +- monitor.c | 10 +- qapi/json-output-visitor.c | 211 ++++++++++++++++ qemu-img.c | 46 ++-- qga/main.c | 5 +- qobject/json-parser.c | 25 +- qobject/qjson.c | 301 ++++++++++------------- qobject/qstring.c | 69 +++++- qom/object.c | 3 +- tests/check-qjson.c | 93 ++++++-- tests/check-qstring.c | 46 +++- tests/libqtest.c | 2 +- tests/test-json-output-visitor.c | 477 +++++++++++++++++++++++++++++++++++++ tests/test-qmp-output-visitor.c | 5 + tests/test-visitor-serialization.c | 2 +- qapi/Makefile.objs | 2 +- tests/.gitignore | 1 + tests/Makefile.include | 5 +- tests/qemu-iotests/043.out | 22 +- 28 files changed, 1137 insertions(+), 311 deletions(-) create mode 100644 include/qapi/json-output-visitor.h create mode 100644 qapi/json-output-visitor.c create mode 100644 tests/test-json-output-visitor.c
Signature · 1 line
2.7.4
PATCH v6 1/15 qapi: Visitor documentation tweak
Make it clear that the name parameter to visit_start_struct() has the same semantics as for visit_start_int().
---
v6: split into separate patch
--- include/qapi/visitor.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)
include/qapi/visitor.h +6 -5
@@ -60,11 +60,12 @@* visitors are declared here; the remaining visitors are generated in * qapi-visit.h. * -* The @name parameter of visit_type_FOO() describes the relation -* between this QAPI value and its parent container. When visiting -* the root of a tree, @name is ignored; when visiting a member of an -* object, @name is the key associated with the value; and when -* visiting a member of a list, @name is NULL. +* The @name parameter of visit_type_FOO() and visit_start_OBJECT() +* describes the relation between this QAPI value and its parent +* container. When visiting the root of a tree, @name is ignored; +* when visiting a member of an object, @name is the key associated +* with the value; and when visiting a member of a list, @name is +* NULL. * * FIXME: Clients must pass NULL for @name when visiting a member of a * list, but this leads to poor error messages; it might be nicer to
Signature · 1 line
2.7.4
PATCH v6 2/15 qapi: Assert finite use of 'number'
In reply to Eric BlakeAdd assertions to all QMP commands that use a QAPI number (namely migrate_set_downtime on input; query-migrate and query-blockstats on output), to make it obvious where we would have to revisit the code if we were to extend QMP to support Infinity or NaN.
Furthermore, make it part of our contract that we don't plan to convert QObject to JSON unless all numbers are finite.
---
v6: new patch
--- block/accounting.c | 6 +++++- migration/migration.c | 4 ++++ qobject/qjson.c | 8 ++++---- 3 files changed, 13 insertions(+), 5 deletions(-)
block/accounting.c +5 -1
@@ -24,6 +24,7 @@*/ #include "qemu/osdep.h" +#include <math.h> #include "block/accounting.h" #include "block/block_int.h" #include "qemu/timer.h"
@@ -164,10 +165,13 @@ double block_acct_queue_depth(BlockAcctTimedStats *stats, enum BlockAcctType type) {uint64_t sum, elapsed; +double result;assert (type <BLOCK_MAX_IOTYPE ); sum =timed_average_sum (&stats->latency[type], &elapsed); -return (double ) sum / elapsed; + result = (double ) sum / elapsed; +assert (isfinite (result)); +return result; }
migration/migration.c +4 -0
@@ -14,6 +14,7 @@*/ #include "qemu/osdep.h" +#include <math.h> #include "qemu/cutils.h" #include "qemu/error-report.h" #include "qemu/main-loop.h"
@@ -1192,6 +1193,7 @@ void qmp_migrate_set_speed(int64_t value, Error **errp)void qmp_migrate_set_downtime (double value,Error **errp) { +assert (isfinite (value));/* JSON (thus QMP) doesn't permit inf or NaN */ value *=1000 ;/* Convert to milliseconds */ value =MAX (0 ,MIN (INT64_MAX , value));
@@ -1811,6 +1813,7 @@ static void *migration_thread(void *opaque) s->mbps = (((double ) transferred_bytes *8.0 ) / ((double ) time_spent /1000.0 )) /1000.0 /1000.0 ; +assert (isfinite (s->mbps));trace_migrate_transferred (transferred_bytes, time_spent, bandwidth, max_size);
@@ -1846,6 +1849,7 @@ static void *migration_thread(void *opaque)if (s->total_time) { s->mbps = (((double ) transferred_bytes *8.0 ) / ((double ) s->total_time)) /1000 ; +assert (isfinite (s->mbps)); }runstate_set (RUN_STATE_POSTMIGRATE ); }else {
qobject/qjson.c +4 -4
@@ -12,6 +12,7 @@*/ #include "qemu/osdep.h" +#include <math.h> #include "qapi/qmp/json-lexer.h" #include "qapi/qmp/json-parser.h" #include "qapi/qmp/json-streamer.h"
@@ -231,20 +232,19 @@ static void to_json(const QObject *obj, QString *str, int pretty, int indent)break ; }case QTYPE_QFLOAT : { -QFloat *val =qobject_to_qfloat (obj); +double val =qfloat_get_double (qobject_to_qfloat (obj));char buffer[1024 ];int len; +assert (isfinite (val));/* FIXME: snprintf() is locale dependent; but JSON requires * numbers to be formatted as if in the C locale. Dependence * on C locale is a pervasive issue in QEMU. */ -/* FIXME: This risks printing Inf or NaN, which are not valid -* JSON values. */ /* FIXME: the default precision of 6 for %f often causes * rounding errors; we should be using DBL_DECIMAL_DIG (17), * and only rounding to a shorter number if the result would * still produce the same floating point value. */ - len =snprintf (buffer,sizeof (buffer),"%f" ,qfloat_get_double (val)); + len =snprintf (buffer,sizeof (buffer),"%f" , val);while (len >0 && buffer[len -1 ] =='0' ) { len--; }
Signature · 1 line
2.7.4
PATCH v6 3/15 qapi: Factor out JSON string escaping
In reply to Eric BlakePull out a new qstring_append_json_string() helper, so that all JSON output producers can use the same output escaping rules.
While it appears that vmstate's use of the simpler qjson.c formatter is not currently encountering any string that needs escapes to be valid JSON, it is better to be safe than sorry, and this substitution is not adding any potential asserts during migration.
Adding a return value will let callers that care diagnose the situation where an attempt was made to output invalid JSON (we use substitute characters, and in fact guarantee that our output is ASCII via escapes even if the input was UTF-8). None of the current callers care, but a future patch wants to make it possible to conditionally turn this situation into an error.
---
v6: comment tweaks
[no v5 due to series split]
v4: keep helper in qobject-json.[ch], tweak variable name and for loop iterator, add return value, drop R-b
v3: rebase to include cleanups in master
v2: no change
--- include/qapi/qmp/qjson.h | 2 + migration/qjson.c | 10 ++-- qobject/qjson.c | 126 ++++++++++++++++++++++++++--------------------- 3 files changed, 76 insertions(+), 62 deletions(-)
include/qapi/qmp/qjson.h +2 -0
@@ -24,4 +24,6 @@ QObject *qobject_from_jsonv(const char *string, va_list *ap) GCC_FMT_ATTR(1, 0);QString *qobject_to_json (const QObject *obj);QString *qobject_to_json_pretty (const QObject *obj); +int qstring_append_json_string (QString *qstring,const char *str); +#endif /* QJSON_H */
migration/qjson.c +4 -6
@@ -26,6 +26,7 @@#include "qemu/osdep.h" #include "qapi/qmp/qstring.h" #include "migration/qjson.h" +#include "qapi/qmp/qjson.h" struct QJSON {QString *str;
@@ -42,9 +43,8 @@ static void json_emit_element(QJSON *json, const char *name) }if (name) { -qstring_append (json->str,"\"" ); -qstring_append (json->str, name); -qstring_append (json->str,"\" : " ); +qstring_append_json_string (json->str, name); +qstring_append (json->str," : " ); } }
@@ -83,9 +83,7 @@ void json_prop_int(QJSON *json, const char *name, int64_t val)void json_prop_str (QJSON *json,const char *name,const char *str) {json_emit_element (json, name); -qstring_append_chr (json->str,'"' ); -qstring_append (json->str, str); -qstring_append_chr (json->str,'"' ); +qstring_append_json_string (json->str, str); }const char *qjson_get_str (QJSON *json)
qobject/qjson.c +70 -56
147 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH v6 4/15 qapi: Factor out JSON number formatting
In reply to Eric BlakePull out a new qstring_append_json_number() helper, so that all JSON output producers can use a consistent style for printing floating point without duplicating code (since we are doing more data massaging than a simple printf format can handle). (For now, there is only one client, but later patches will use it.)
Unlike qstring_append_json_string() which has a return value to allow callers to detect when output was munged to produce valid JSON, this code either succeeds or triggers an assertion failure.
---
v6: drop return value, now that we assert finite floats on any QObject converted to JSON
[no v5 due to series split]
v4: keep helper in qobject-json.[ch], don't use Error **errp for inf/NaN handling, drop R-b
v3: rebase to latest; even though the patch differs quite a bit from v2, the changes are due to prior comment changes that are just moving between files, so R-b kept
v2: minor wording tweaks
--- include/qapi/qmp/qjson.h | 1 + qobject/qjson.c | 57 +++++++++++++++++++++++++++++------------------- 2 files changed, 36 insertions(+), 22 deletions(-)
include/qapi/qmp/qjson.h +1 -0
@@ -25,5 +25,6 @@ QString *qobject_to_json(const QObject *obj);QString *qobject_to_json_pretty (const QObject *obj);int qstring_append_json_string (QString *qstring,const char *str); +void qstring_append_json_number (QString *qstring,double number);#endif /* QJSON_H */
qobject/qjson.c +35 -22
67 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH v6 5/15 qapi: Add qstring_append_printf()
In reply to Eric BlakeBack in commit 764c1ca (Nov 2009), we added qstring_append_int(). However, it did not see any use until commit 190c882 (Jan 2015). Furthermore, it has a rather limited use case - to print anything else, callers still have to format into a temporary buffer, unless we want to introduce an explosion of new qstring_append_* methods for each useful type to print.
A much better approach is to add a wrapper that merges printf behavior onto qstring_append, via the new qstring_append_printf() (and its vararg counterpart), with a name based on glib's g_string_append_printf(). In fact, with our wrapper in place, we no longer need qstring_append_int().
Other immediate uses for the new function include simplifying two existing clients of qstring_append() on a just-formatted buffer, and the fact that we can take advantage of printf width manipulations for more efficient indentation.
---
v6: no change
[no v5 due to series split]
v4: retitle, s/_format/_printf/, drop R-b, move up in series
v3: rebase to master
v2: also simplify qstring_append_json_string(), add assertion that format is well-formed
--- include/qapi/qmp/qstring.h | 7 +++++-- migration/qjson.c | 2 +- qobject/qjson.c | 38 ++++++++++---------------------------- qobject/qstring.c | 26 +++++++++++++++++++++----- 4 files changed, 37 insertions(+), 36 deletions(-)
include/qapi/qmp/qstring.h +5 -2
@@ -1,7 +1,7 @@/* * QString Module * -* Copyright (C) 2009 Red Hat Inc. +* Copyright (C) 2009-2016 Red Hat Inc. * * Authors: * Luiz Capitulino <[email protected]>
@@ -27,9 +27,12 @@ QString *qstring_from_str(const char *str);QString *qstring_from_substr (const char *str,int start,int end);size_t qstring_get_length (const QString *qstring);const char *qstring_get_str (const QString *qstring); -void qstring_append_int (QString *qstring,int64_t value);void qstring_append (QString *qstring,const char *str);void qstring_append_chr (QString *qstring,int c); +void qstring_append_printf(QString *qstring, const char *fmt, ...) + GCC_FMT_ATTR(2, 3); +void qstring_append_vprintf(QString *qstring, const char *fmt, va_list ap) + GCC_FMT_ATTR(2, 0);QString *qobject_to_qstring (const QObject *obj);void qstring_destroy_obj (QObject *obj);
migration/qjson.c +1 -1
@@ -77,7 +77,7 @@ void json_end_array(QJSON *json)void json_prop_int (QJSON *json,const char *name,int64_t val) {json_emit_element (json, name); -qstring_append_int (json->str, val); +qstring_append_printf (json->str,"%" PRId64, val); }void json_prop_str (QJSON *json,const char *name,const char *str)
qobject/qjson.c +10 -28
@@ -82,16 +82,13 @@ static void to_json(const QObject *obj, QString *str, int pretty, int indent);static void to_json_dict_iter (const char *key,QObject *obj,void *opaque) {ToJsonIterState *s = opaque; -int j;if (s->count) {qstring_append (s->str, s->pretty ?"," :", " ); }if (s->pretty) { -qstring_append (s->str,"\n" ); -for (j =0 ; j < s->indent ; j++) -qstring_append (s->str," " ); +qstring_append_printf (s->str,"\n%*s" ,4 * s->indent,"" ); }qstring_append_json_string (s->str, key);
@@ -104,16 +101,13 @@ static void to_json_dict_iter(const char *key, QObject *obj, void *opaque)static void to_json_list_iter (QObject *obj,void *opaque) {ToJsonIterState *s = opaque; -int j;if (s->count) {qstring_append (s->str, s->pretty ?"," :", " ); }if (s->pretty) { -qstring_append (s->str,"\n" ); -for (j =0 ; j < s->indent ; j++) -qstring_append (s->str," " ); +qstring_append_printf (s->str,"\n%*s" ,4 * s->indent,"" ); }to_json (obj, s->str, s->pretty, s->indent);
@@ -128,10 +122,7 @@ static void to_json(const QObject *obj, QString *str, int pretty, int indent)break ;case QTYPE_QINT : {QInt *val =qobject_to_qint (obj); -char buffer[1024 ]; - -snprintf (buffer,sizeof (buffer),"%" PRId64,qint_get_int (val)); -qstring_append (str, buffer); +qstring_append_printf (str,"%" PRId64,qint_get_int (val));break ; }case QTYPE_QSTRING : {
@@ -152,10 +143,7 @@ static void to_json(const QObject *obj, QString *str, int pretty, int indent)qstring_append (str,"{" );qdict_iter (val, to_json_dict_iter, &s);if (pretty) { -int j; -qstring_append (str,"\n" ); -for (j =0 ; j < indent ; j++) -qstring_append (str," " ); +qstring_append_printf (str,"\n%*s" ,4 * indent,"" ); }qstring_append (str,"}" );break ;
@@ -171,10 +159,7 @@ static void to_json(const QObject *obj, QString *str, int pretty, int indent)qstring_append (str,"[" );qlist_iter (val, (void *)to_json_list_iter, &s);if (pretty) { -int j; -qstring_append (str,"\n" ); -for (j =0 ; j < indent ; j++) -qstring_append (str," " ); +qstring_append_printf (str,"\n%*s" ,4 * indent,"" ); }qstring_append (str,"]" );break ;
@@ -230,7 +215,6 @@ int qstring_append_json_string(QString *qstring, const char *str) {const char *ptr;int cp; -char buf[16 ];char *end;int result =0 ;
@@ -267,16 +251,14 @@ int qstring_append_json_string(QString *qstring, const char *str) }if (cp >0xFFFF ) {/* beyond BMP; need a surrogate pair */ -snprintf (buf,sizeof (buf),"\\u%04X\\u%04X" , -0xD800 + ((cp -0x10000 ) >>10 ), -0xDC00 + ((cp -0x10000 ) &0x3FF )); +qstring_append_printf (qstring,"\\u%04X\\u%04X" , +0xD800 + ((cp -0x10000 ) >>10 ), +0xDc00 + ((cp -0x10000 ) &0x3FF )); }else if (cp <0x20 || cp >=0x7F ) { -snprintf (buf,sizeof (buf),"\\u%04X" , cp); +qstring_append_printf (qstring,"\\u%04X" , cp); }else { - buf[0 ] = cp; - buf[1 ] =0 ; +qstring_append_chr (qstring, cp); } -qstring_append (qstring, buf); } };
qobject/qstring.c +21 -5
@@ -1,7 +1,7 @@/* * QString Module * -* Copyright (C) 2009 Red Hat Inc. +* Copyright (C) 2009-2016 Red Hat Inc. * * Authors: * Luiz Capitulino <[email protected]>
@@ -88,12 +88,28 @@ void qstring_append(QString *qstring, const char *str) qstring->string[qstring->length] =0 ; } -void qstring_append_int (QString *qstring,int64_t value) +void qstring_append_printf (QString *qstring,const char *fmt, ...) { -char num[32 ]; +va_list ap; -snprintf (num,sizeof (num),"%" PRId64, value); -qstring_append (qstring, num); +va_start (ap, fmt); +qstring_append_vprintf (qstring, fmt, ap); +va_end (ap); +} + +void qstring_append_vprintf (QString *qstring,const char *fmt,va_list ap) +{ +va_list ap2; +int len; + +va_copy (ap2, ap); + len =vsnprintf (NULL ,0 , fmt, ap2); +assert (len >=0 ); +va_end (ap2); + +capacity_increase (qstring, len); +vsnprintf (qstring->string + qstring->length, len +1 , fmt, ap); + qstring->length += len; }/**
Signature · 1 line
2.7.4
PATCH v6 6/15 qapi: Use qstring_append_chr() where appropriate
In reply to Eric Blakeqstring_append_chr() is more efficient than qstring_append() when dealing with a one-byte string (including the case of a temporary 2-byte buffer just for creating a dynamic one-byte string).
---
v6: no change
[no v5 due to series split]
v4: also convert qstring_append() of one-byte strings
v3: no change
v2: no change
--- qobject/json-parser.c | 25 ++++++++++--------------- qobject/qjson.c | 12 ++++++------ 2 files changed, 16 insertions(+), 21 deletions(-)
qobject/json-parser.c +10 -15
@@ -143,39 +143,39 @@ static QString *qstring_from_escaped_str(JSONParserContext *ctxt,switch (*ptr) {case '"' : -qstring_append (str,"\"" ); +qstring_append_chr (str,'"' ); ptr++;break ;case '\'' : -qstring_append (str,"'" ); +qstring_append_chr (str,'\'' ); ptr++;break ;case '\\' : -qstring_append (str,"\\" ); +qstring_append_chr (str,'\\' ); ptr++;break ;case '/' : -qstring_append (str,"/" ); +qstring_append_chr (str,'/' ); ptr++;break ;case 'b' : -qstring_append (str,"\b" ); +qstring_append_chr (str,'\b' ); ptr++;break ;case 'f' : -qstring_append (str,"\f" ); +qstring_append_chr (str,'\f' ); ptr++;break ;case 'n' : -qstring_append (str,"\n" ); +qstring_append_chr (str,'\n' ); ptr++;break ;case 'r' : -qstring_append (str,"\r" ); +qstring_append_chr (str,'\r' ); ptr++;break ;case 't' : -qstring_append (str,"\t" ); +qstring_append_chr (str,'\t' ); ptr++;break ;case 'u' : {
@@ -204,12 +204,7 @@ static QString *qstring_from_escaped_str(JSONParserContext *ctxt, goto out; } }else { -char dummy[2 ]; - - dummy[0 ] = *ptr++; - dummy[1 ] =0 ; - -qstring_append (str, dummy); +qstring_append_chr (str, *ptr++); } }
qobject/qjson.c +6 -6
@@ -140,12 +140,12 @@ static void to_json(const QObject *obj, QString *str, int pretty, int indent) s.str = str; s.indent = indent +1 ; s.pretty = pretty; -qstring_append (str,"{" ); +qstring_append_chr (str,'{' );qdict_iter (val, to_json_dict_iter, &s);if (pretty) {qstring_append_printf (str,"\n%*s" ,4 * indent,"" ); } -qstring_append (str,"}" ); +qstring_append_chr (str,'}' );break ; }case QTYPE_QLIST : {
@@ -156,12 +156,12 @@ static void to_json(const QObject *obj, QString *str, int pretty, int indent) s.str = str; s.indent = indent +1 ; s.pretty = pretty; -qstring_append (str,"[" ); +qstring_append_chr (str,'[' );qlist_iter (val, (void *)to_json_list_iter, &s);if (pretty) {qstring_append_printf (str,"\n%*s" ,4 * indent,"" ); } -qstring_append (str,"]" ); +qstring_append_chr (str,']' );break ; }case QTYPE_QFLOAT : {
@@ -218,7 +218,7 @@ int qstring_append_json_string(QString *qstring, const char *str)char *end;int result =0 ; -qstring_append (qstring,"\"" ); +qstring_append_chr (qstring,'"' );for (ptr = str; *ptr; ptr = end) { cp =mod_utf8_codepoint (ptr,6 , &end);
@@ -262,7 +262,7 @@ int qstring_append_json_string(QString *qstring, const char *str) } }; -qstring_append (qstring,"\"" ); +qstring_append_chr (qstring,'"' );return result; }
Signature · 1 line
2.7.4
PATCH v6 7/15 qstring: Add qstring_consume_str()
In reply to Eric BlakeSimilar to g_string_free(), there are cases where we want to destroy our reference to a QString while grabbing its contents, where we want to avoid use-after-free but also avoid a needless strdup(). But unlike g_string_free(), we are at least sensible enough to add this feature via a different function name, instead of trying to overload two completely separate concepts into a single function. Do this by introducing the new qstring_consume_str(), then use it where it makes sense.
In the case of monitor.c, note that QString _always_ has a non-NULL embedded string with at least one byte allocated for a terminating NUL, so special-casing on length 0 was wasted code.
---
v6: no change
[no v5 due to series split]
v4: new patch, suggested by Markus
--- include/qapi/qmp/qstring.h | 1 + monitor.c | 6 +----- qobject/qstring.c | 23 +++++++++++++++++++++++ qom/object.c | 3 +-- tests/check-qstring.c | 31 +++++++++++++++++++++++++++---- 5 files changed, 53 insertions(+), 11 deletions(-)
include/qapi/qmp/qstring.h +1 -0
@@ -27,6 +27,7 @@ QString *qstring_from_str(const char *str);QString *qstring_from_substr (const char *str,int start,int end);size_t qstring_get_length (const QString *qstring);const char *qstring_get_str (const QString *qstring); +char *qstring_consume_str (QString *qstring);void qstring_append (QString *qstring,const char *str);void qstring_append_chr (QString *qstring,int c);void qstring_append_printf (QString *qstring,const char *fmt, ...)
monitor.c +1 -5
@@ -624,11 +624,7 @@ char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index, cur_mon = old_mon;qemu_mutex_lock (&hmp.out_lock); -if (qstring_get_length (hmp.outbuf) >0 ) { - output =g_strdup (qstring_get_str (hmp.outbuf)); - }else { - output =g_strdup ("" ); - } + output =qstring_consume_str (hmp.outbuf);qemu_mutex_unlock (&hmp.out_lock); out:
qobject/qstring.c +23 -0
@@ -145,6 +145,29 @@ const char *qstring_get_str(const QString *qstring) }/** +* qstring_consume_str(): Destructively convert a QString to string +* +* The reference count of @qstring is decremented by one, and the +* caller is responsible for calling g_free() on the result. In the +* common case where @qstring was not shared, this is faster than +* using strdup() on the result of qstring_get_str(); otherwise, the +* result is a copy and remaining users of @qstring are unaffected. +*/ +char *qstring_consume_str (QString *qstring) +{ +char *result; + +if (qstring->base.refcnt ==1 ) { + result = qstring->string; + qstring->string =NULL ; + }else { + result =g_strdup (qstring->string); + } +qobject_decref (&qstring->base); +return result; +} + +/** * qstring_destroy_obj(): Free all memory allocated by a QString * object */
qom/object.c +1 -2
@@ -1112,10 +1112,9 @@ char *object_property_get_str(Object *obj, const char *name,error_setg (errp,QERR_INVALID_PARAMETER_TYPE , name,"string" ); retval =NULL ; }else { - retval =g_strdup (qstring_get_str (qstring)); + retval =qstring_consume_str (qstring); } -QDECREF (qstring);return retval; }
tests/check-qstring.c +27 -4
@@ -1,7 +1,7 @@/* * QString unit-tests. * -* Copyright (C) 2009 Red Hat Inc. +* Copyright (C) 2009-2016 Red Hat Inc. * * Authors: * Luiz Capitulino <[email protected]>
@@ -31,9 +31,7 @@ static void qstring_from_str_test(void)g_assert (strcmp (str, qstring->string) ==0 );g_assert (qobject_type (QOBJECT (qstring)) ==QTYPE_QSTRING ); -// destroy doesn't exit yet -g_free (qstring->string); -g_free (qstring); +QDECREF (qstring); }static void qstring_destroy_test (void )
@@ -55,6 +53,30 @@ static void qstring_get_str_test(void)QDECREF (qstring); } +static void qstring_consume_str_test (void ) +{ +QString *qstring; +char *ret_str; +const char *str ="QEMU/KVM" ; +char *ptr; + + qstring =qstring_from_str (str); +QINCREF (qstring); + g_assert_cmpint(qstring->base.refcnt, ==, 2); + ptr = qstring->string; + + ret_str =qstring_consume_str (qstring); + g_assert_cmpint(qstring->base.refcnt, ==, 1); +g_assert (ret_str != ptr); + g_assert_cmpstr(ret_str, ==, str); +g_free (ret_str); + + ret_str =qstring_consume_str (qstring); +g_assert (ret_str == ptr); + g_assert_cmpstr(ret_str, ==, str); +g_free (ret_str); +} +static void qstring_append_chr_test (void ) {int i;
@@ -102,6 +124,7 @@ int main(int argc, char **argv)g_test_add_func ("/public/append_chr" , qstring_append_chr_test);g_test_add_func ("/public/from_substr" , qstring_from_substr_test);g_test_add_func ("/public/to_qstring" , qobject_to_qstring_test); +g_test_add_func ("/public/consume_str" , qstring_consume_str_test);return g_test_run (); }
Signature · 1 line
2.7.4
PATCH v6 8/15 qstring: Add qstring_wrap_str()
In reply to Eric BlakeSeveral spots in the code malloc a string, then wrap it in a QString, which has to duplicate the input. Adding a new constructor with transfer semantics makes this pattern more efficient, comparable to the just-added transfer semantics to go from QString back to raw string. Use the new qstring_wrap_str() where it makes sense.
The new test still passes under valgrind.
---
v6: don't auto-convert NULL into ""
[no v5 due to series split]
v4: new patch
--- include/qapi/qmp/qstring.h | 1 + block.c | 3 ++- block/archipelago.c | 6 ++---- blockdev.c | 3 +-- qobject/qstring.c | 20 ++++++++++++++++++++ tests/check-qstring.c | 15 +++++++++++++++ 6 files changed, 41 insertions(+), 7 deletions(-)
include/qapi/qmp/qstring.h +1 -0
@@ -25,6 +25,7 @@ typedef struct QString {QString *qstring_new (void );QString *qstring_from_str (const char *str);QString *qstring_from_substr (const char *str,int start,int end); +QString *qstring_wrap_str (char *str);size_t qstring_get_length (const QString *qstring);const char *qstring_get_str (const QString *qstring);char *qstring_consume_str (QString *qstring);
block.c +2 -1
@@ -1640,7 +1640,8 @@ static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,qdict_put (snapshot_options,"file.driver" ,qstring_from_str ("file" ));qdict_put (snapshot_options,"file.filename" , -qstring_from_str (tmp_filename)); +qstring_wrap_str (tmp_filename)); + tmp_filename =NULL ;qdict_put (snapshot_options,"driver" ,qstring_from_str ("qcow2" ));
block/archipelago.c +2 -4
@@ -426,13 +426,11 @@ static void archipelago_parse_filename(const char *filename, QDict *options,parse_filename_opts (filename, errp, &volume, &segment_name, &mport, &vport);if (volume) { -qdict_put (options,ARCHIPELAGO_OPT_VOLUME ,qstring_from_str (volume)); -g_free (volume); +qdict_put (options,ARCHIPELAGO_OPT_VOLUME ,qstring_wrap_str (volume)); }if (segment_name) {qdict_put (options,ARCHIPELAGO_OPT_SEGMENT , -qstring_from_str (segment_name)); -g_free (segment_name); +qstring_wrap_str (segment_name)); }if (mport != NoPort) {qdict_put (options,ARCHIPELAGO_OPT_MPORT ,qint_from_int (mport));
blockdev.c +1 -2
@@ -1026,8 +1026,7 @@ DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type) new_id =g_strdup_printf ("%s%s%i" , if_name[type], mediastr, unit_id); } -qdict_put (bs_opts,"id" ,qstring_from_str (new_id)); -g_free (new_id); +qdict_put (bs_opts,"id" ,qstring_wrap_str (new_id)); }/* Add virtio block device */
qobject/qstring.c +20 -0
@@ -66,6 +66,26 @@ QString *qstring_from_str(const char *str)return qstring_from_substr (str,0 ,strlen (str) -1 ); } +/** +* qstring_wrap_str(): Create a new QString around a malloc'd C string +* +* Returns a strong reference, and caller must not use @str any more. +* @str must not be NULL. +*/ +QString *qstring_wrap_str (char *str) +{ +QString *qstring; + + qstring =g_malloc (sizeof (*qstring)); +qobject_init (QOBJECT (qstring),QTYPE_QSTRING ); + +assert (str); + qstring->string = str; + qstring->capacity = qstring->length =strlen (str); + +return qstring; +} +static void capacity_increase (QString *qstring,size_t len) {if (qstring->capacity < (qstring->length + len)) {
tests/check-qstring.c +15 -0
@@ -34,6 +34,20 @@ static void qstring_from_str_test(void)QDECREF (qstring); } +static void qstring_wrap_str_test (void ) +{ +QString *qstring; +char *str =g_strdup ("QEMU" ); + + qstring =qstring_wrap_str (str); +g_assert (qstring !=NULL ); +g_assert (qstring->base.refcnt ==1 ); +g_assert (strcmp ("QEMU" , qstring->string) ==0 ); +g_assert (qobject_type (QOBJECT (qstring)) ==QTYPE_QSTRING ); + +QDECREF (qstring); +} +static void qstring_destroy_test (void ) {QString *qstring =qstring_from_str ("destroy test" );
@@ -119,6 +133,7 @@ int main(int argc, char **argv)g_test_init (&argc, &argv,NULL );g_test_add_func ("/public/from_str" , qstring_from_str_test); +g_test_add_func ("/public/wrap_str" , qstring_wrap_str_test);g_test_add_func ("/public/destroy" , qstring_destroy_test);g_test_add_func ("/public/get_str" , qstring_get_str_test);g_test_add_func ("/public/append_chr" , qstring_append_chr_test);
Signature · 1 line
2.7.4
Re: [Qemu-devel] [PATCH v6 08/15] qstring: Add qstring_wrap_str()
Hi
Quoted 43 lines · Eric Blake
Several spots in the code malloc a string, then wrap it in a QString, which has to duplicate the input. Adding a new constructor with transfer semantics makes this pattern more efficient, comparable to the just-added transfer semantics to go from QString back to raw string. Use the new
qstring_wrap_str()where it makes sense.The new test still passes under valgrind.
Signed-off-by Eric Blake <[email protected]>---
v6: don't auto-convert NULL into ""
[no v5 due to series split]
v4: new patch--- include/qapi/qmp/qstring.h | 1 + block.c | 3 ++- block/archipelago.c | 6 ++---- blockdev.c | 3 +-- qobject/qstring.c | 20 ++++++++++++++++++++ tests/check-qstring.c | 15 +++++++++++++++ 6 files changed, 41 insertions(+), 7 deletions(-)include/qapi/qmp/qstring.h +1
-0@@ -25,6 +25,7 @@ typedef struct QString {QString *qstring_new (void );QString *qstring_from_str (const char *str);QString *qstring_from_substr (const char *str,int start,int end); +QString *qstring_wrap_str (char *str);size_t qstring_get_length (const QString *qstring);const char *qstring_get_str (const QString *qstring);char *qstring_consume_str (QString *qstring);block.c +0
-0
block.c static BlockDriverState · line 1647
Quoted 9 lines
block.c +2
-1@@ -1640,7 +1640,8 @@ static BlockDriverState *bdrv_append_temp_snapshot (BlockDriverState *bs,qdict_put (snapshot_options,"file.driver" , qstring_from_str("file"));qdict_put (snapshot_options,"file.filename" , -qstring_from_str (tmp_filename)); +qstring_wrap_str (tmp_filename)); + tmp_filename =NULL ;qdict_put (snapshot_options,"driver" ,qstring_from_str ("qcow2" ));
You could also remove g_free(tmp_filename) from the normal return path (this may please static analyzers).
block/archipelago.c +0 -0
Quoted 106 lines
index 37b8aca..ac047e4 100644
block/archipelago.c +2
-4@@ -426,13 +426,11 @@ static void archipelago_parse_filename(const char *filename, QDict *options,parse_filename_opts (filename, errp, &volume, &segment_name, &mport, &vport);if (volume) { -qdict_put (options,ARCHIPELAGO_OPT_VOLUME , qstring_from_str(volume)); -g_free (volume); +qdict_put (options,ARCHIPELAGO_OPT_VOLUME ,qstring_wrap_str (volume)); }if (segment_name) {qdict_put (options,ARCHIPELAGO_OPT_SEGMENT , -qstring_from_str (segment_name)); -g_free (segment_name); +qstring_wrap_str (segment_name)); }if (mport != NoPort) {qdict_put (options,ARCHIPELAGO_OPT_MPORT ,qint_from_int (mport));blockdev.c +1
-2@@ -1026,8 +1026,7 @@ DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type) new_id =g_strdup_printf ("%s%s%i" , if_name[type], mediastr, unit_id); } -qdict_put (bs_opts,"id" ,qstring_from_str (new_id)); -g_free (new_id); +qdict_put (bs_opts,"id" ,qstring_wrap_str (new_id)); }/* Add virtio block device */qobject/qstring.c +20
-0@@ -66,6 +66,26 @@ QString *qstring_from_str(const char *str)return qstring_from_substr (str,0 ,strlen (str) -1 ); } +/** +* qstring_wrap_str(): Create a new QString around a malloc'd C string +* +* Returns a strong reference, and caller must not use @str any more. +* @str must not be NULL. +*/ +QString *qstring_wrap_str (char *str) +{ +QString *qstring; + + qstring =g_malloc (sizeof (*qstring)); +qobject_init (QOBJECT (qstring),QTYPE_QSTRING ); + +assert (str); + qstring->string = str; + qstring->capacity = qstring->length =strlen (str); + +return qstring; +} +static void capacity_increase (QString *qstring,size_t len) {if (qstring->capacity < (qstring->length + len)) {tests/check-qstring.c +15
-1@@ -34,6 +34,20 @@ static void qstring_from_str_test(void)QDECREF (qstring); } +static void qstring_wrap_str_test (void ) +{ +QString *qstring; +char *str =g_strdup ("QEMU" ); + + qstring =qstring_wrap_str (str); +g_assert (qstring !=NULL ); +g_assert (qstring->base.refcnt ==1 ); +g_assert (strcmp ("QEMU" , qstring->string) ==0 ); +g_assert (qobject_type (QOBJECT (qstring)) ==QTYPE_QSTRING ); + +QDECREF (qstring); +} +static void qstring_destroy_test (void ) {QString *qstring =qstring_from_str ("destroy test" );@@ -119,6 +133,7 @@ int main(int argc, char **argv)g_test_init (&argc, &argv,NULL );g_test_add_func ("/public/from_str" , qstring_from_str_test); +g_test_add_func ("/public/wrap_str" , qstring_wrap_str_test);g_test_add_func ("/public/destroy" , qstring_destroy_test);g_test_add_func ("/public/get_str" , qstring_get_str_test);g_test_add_func ("/public/append_chr" , qstring_append_chr_test); --2.7.4
Quoted 1 line
--
Marc-André Lureau
Re: [Qemu-devel] [PATCH v6 08/15] qstring: Add qstring_wrap_str()
Quoted 7 lines · Marc-André Lureau
Quoted 7 lines
+++
b/block.c(quoted diff) +0
-1@@ -1640,7 +1640,8 @@ static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs, qdict_put(snapshot_options, "file.driver", qstring_from_str("file")); qdict_put(snapshot_options, "file.filename", - qstring_from_str(tmp_filename));
Quoted 8 lines
Review static BlockDriverState · line 1647
Quoted 6 lines
(quoted diff) +2
-0+ qstring_wrap_str(tmp_filename)); + tmp_filename = NULL; qdict_put(snapshot_options, "driver", qstring_from_str("qcow2"));You could also remove
g_free(tmp_filename)from the normal return path (this may please static analyzers).
No. g_free(NULL) is safe, but we can also reach the 'out' label with tmp_filename still malloc'd prior to the place where we transfer it here, so the g_free() in the cleanup label is still required. The assignment to NULL here prevents a double free. The patch is correct as-is.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v6 08/15] qstring: Add qstring_wrap_str()
Quoted 18 lines · Eric Blake
Quoted 7 lines · Marc-André Lureau
Quoted 7 lines
+++
b/block.c(quoted diff) +0
-1@@ -1640,7 +1640,8 @@ static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs, qdict_put(snapshot_options, "file.driver", qstring_from_str("file")); qdict_put(snapshot_options, "file.filename", - qstring_from_str(tmp_filename));Quoted 8 lines
Review static BlockDriverState · line 1647
Quoted 6 lines
(quoted diff) +2
-0+ qstring_wrap_str(tmp_filename)); + tmp_filename = NULL; qdict_put(snapshot_options, "driver", qstring_from_str("qcow2"));You could also remove
g_free(tmp_filename)from the normal return path (this may please static analyzers).
Quoted 4 lines
No.
g_free(NULL)is safe, but we can also reach the 'out' label withtmp_filenamestill malloc'd prior to the place where we transfer it here, so theg_free()in the cleanup label is still required. The assignment to NULL here prevents a double free. The patch is correct as-is.
Spoke too soon. I see what you're saying - the normal return path now has a dead g_free(NULL). It won't cause any grief to the static analyzers, but it is a useless no-op function call, so I can indeed trim it (the one before the label, not the one after).
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v6 08/15] qstring: Add qstring_wrap_str()
Hi
Quoted 23 lines · Eric Blake
Quoted 18 lines · Eric Blake
Quoted 7 lines · Marc-André Lureau
Quoted 7 lines
+++
b/block.c(quoted diff) +0
-1@@ -1640,7 +1640,8 @@ static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs, qdict_put(snapshot_options, "file.driver", qstring_from_str("file")); qdict_put(snapshot_options, "file.filename", - qstring_from_str(tmp_filename));Quoted 8 lines
Review static BlockDriverState · line 1647
Quoted 6 lines
(quoted diff) +2
-0+ qstring_wrap_str(tmp_filename)); + tmp_filename = NULL; qdict_put(snapshot_options, "driver", qstring_from_str("qcow2"));You could also remove
g_free(tmp_filename)from the normal return path (this may please static analyzers).Quoted 4 lines
No.
g_free(NULL)is safe, but we can also reach the 'out' label withtmp_filenamestill malloc'd prior to the place where we transfer it here, so theg_free()in the cleanup label is still required. The assignment to NULL here prevents a double free. The patch is correct
Quoted 7 lines
as-is.
Spoke too soon. I see what you're saying - the normal return path now has a dead
g_free(NULL). It won't cause any grief to the static analyzers, but it is a useless no-op function call, so I can indeed trim it (the one before the label, not the one after).
static analyzers could catch the fact that you always call g_free(NULL) in this code path, please remove it.
Quoted 5 lines
--
Eric Blake eblake redhat com +1-919-301-3266 <+1%20919-301-3266>
Libvirt virtualization library http://libvirt.org--
Marc-André Lureau
PATCH v6 1/1 fixup! qstring: Add qstring_wrap_str()
In reply to Eric Blake---
squash this in to address Marc-Andre's finding on a harmless extra g_free.
--- block.c | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-)
block.c +3 -6
@@ -1605,7 +1605,7 @@ static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,char *tmp_filename =g_malloc0 (PATH_MAX +1 );int64_t total_size;QemuOpts *opts =NULL ; -BlockDriverState *bs_snapshot; +BlockDriverState *bs_snapshot =NULL ;int ret;/* if snapshot, we create a temporary backing file and open it
@@ -1658,13 +1658,10 @@ static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,bdrv_ref (bs_snapshot);bdrv_append (bs_snapshot, bs); +out: +QDECREF (snapshot_options);g_free (tmp_filename);return bs_snapshot; - -out: -QDECREF (snapshot_options); -g_free (tmp_filename); -return NULL ; }/*
Signature · 1 line
2.7.4
PATCH v6 9/15 qobject: Consolidate qobject_to_json() calls
In reply to Eric BlakeIt's simpler to have a single conversion function that takes a bool parameter, rather than two functions where the choice of function determines an internal bool. Similar to commit fc471c18.
While at it, the conversion currently cannot fail (maybe it SHOULD be possible to choose to fail, when encountering invalid UTF-8 encoding or an Infinity or NaN valued double, but that's a story for another day), so clean up callers to avoid a needless assert. And use bool rather than int for 'pretty'.
---
v6: rebase
[no v5 due to series split]
v4: new patch
--- include/qapi/qmp/qjson.h | 4 ++-- block.c | 2 +- monitor.c | 4 +--- qemu-img.c | 9 +++------ qga/main.c | 5 +---- qobject/qjson.c | 19 +++++-------------- tests/check-qjson.c | 27 +++++++++++---------------- tests/libqtest.c | 2 +- tests/test-visitor-serialization.c | 2 +- 9 files changed, 26 insertions(+), 48 deletions(-)
include/qapi/qmp/qjson.h +2 -2
@@ -21,8 +21,8 @@ QObject *qobject_from_json(const char *string);QObject *qobject_from_jsonf (const char *string, ...)GCC_FMT_ATTR (1 ,2 );QObject *qobject_from_jsonv (const char *string,va_list *ap)GCC_FMT_ATTR (1 ,0 ); -QString *qobject_to_json (const QObject *obj); -QString *qobject_to_json_pretty (const QObject *obj); +/* Convert the object to QString; does not fail. */ +QString *qobject_to_json (const QObject *obj,bool pretty);int qstring_append_json_string (QString *qstring,const char *str);void qstring_append_json_number (QString *qstring,double number);
block.c +1 -1
@@ -4021,7 +4021,7 @@ void bdrv_refresh_filename(BlockDriverState *bs)if (bs->exact_filename[0 ]) {pstrcpy (bs->filename,sizeof (bs->filename), bs->exact_filename); }else if (bs->full_open_options) { -QString *json =qobject_to_json (QOBJECT (bs->full_open_options)); +QString *json =qobject_to_json (QOBJECT (bs->full_open_options), false);snprintf (bs->filename,sizeof (bs->filename),"json:%s" ,qstring_get_str (json));QDECREF (json);
monitor.c +1 -3
@@ -388,9 +388,7 @@ static void monitor_json_emitter(Monitor *mon, const QObject *data) {QString *json; - json = mon->flags &MONITOR_USE_PRETTY ?qobject_to_json_pretty (data) : -qobject_to_json (data); -assert (json !=NULL ); + json =qobject_to_json (data, mon->flags &MONITOR_USE_PRETTY );qstring_append_chr (json,'\n' );monitor_puts (mon,qstring_get_str (json));
qemu-img.c +3 -6
@@ -504,8 +504,7 @@ static void dump_json_image_check(ImageCheck *check, bool quiet)visit_type_ImageCheck (v,NULL , &check, &error_abort);visit_complete (v, &obj); - str =qobject_to_json_pretty (obj); -assert (str !=NULL ); + str =qobject_to_json (obj, true);qprintf (quiet,"%s\n" ,qstring_get_str (str));qobject_decref (obj);visit_free (v);
@@ -2197,8 +2196,7 @@ static void dump_json_image_info_list(ImageInfoList *list)visit_type_ImageInfoList (v,NULL , &list, &error_abort);visit_complete (v, &obj); - str =qobject_to_json_pretty (obj); -assert (str !=NULL ); + str =qobject_to_json (obj, true);printf ("%s\n" ,qstring_get_str (str));qobject_decref (obj);visit_free (v);
@@ -2213,8 +2211,7 @@ static void dump_json_image_info(ImageInfo *info)visit_type_ImageInfo (v,NULL , &info, &error_abort);visit_complete (v, &obj); - str =qobject_to_json_pretty (obj); -assert (str !=NULL ); + str =qobject_to_json (obj, true);printf ("%s\n" ,qstring_get_str (str));qobject_decref (obj);visit_free (v);
qga/main.c +1 -4
@@ -522,10 +522,7 @@ static int send_response(GAState *s, QObject *payload)g_assert (payload && s->channel); - payload_qstr =qobject_to_json (payload); -if (!payload_qstr) { -return -EINVAL ; - } + payload_qstr =qobject_to_json (payload, false);if (s->delimit_response) { s->delimit_response = false;
qobject/qjson.c +5 -14
@@ -72,12 +72,12 @@ QObject *qobject_from_jsonf(const char *string, ...)typedef struct ToJsonIterState {int indent; -int pretty; +bool pretty;int count;QString *str; }ToJsonIterState ; -static void to_json (const QObject *obj,QString *str,int pretty,int indent); +static void to_json (const QObject *obj,QString *str,bool pretty,int indent);static void to_json_dict_iter (const char *key,QObject *obj,void *opaque) {
@@ -114,7 +114,7 @@ static void to_json_list_iter(QObject *obj, void *opaque) s->count++; } -static void to_json (const QObject *obj,QString *str,int pretty,int indent) +static void to_json (const QObject *obj,QString *str,bool pretty,int indent) {switch (qobject_type (obj)) {case QTYPE_QNULL :
@@ -185,20 +185,11 @@ static void to_json(const QObject *obj, QString *str, int pretty, int indent) } } -QString *qobject_to_json (const QObject *obj) +QString *qobject_to_json (const QObject *obj,bool pretty) {QString *str =qstring_new (); -to_json (obj, str,0 ,0 ); - -return str; -} - -QString *qobject_to_json_pretty (const QObject *obj) -{ -QString *str =qstring_new (); - -to_json (obj, str,1 ,0 ); +to_json (obj, str, pretty,0 );return str; }
tests/check-qjson.c +11 -16
@@ -62,7 +62,7 @@ static void escaped_string(void) g_assert_cmpstr(qstring_get_str(str), ==, test_cases[i].decoded);if (test_cases[i].skip ==0 ) { - str =qobject_to_json (obj); + str =qobject_to_json (obj, false); g_assert_cmpstr(qstring_get_str(str), ==, test_cases[i].encoded);qobject_decref (obj); }
@@ -96,7 +96,7 @@ static void simple_string(void) str =qobject_to_qstring (obj);g_assert (strcmp (qstring_get_str (str), test_cases[i].decoded) ==0 ); - str =qobject_to_json (obj); + str =qobject_to_json (obj, false);g_assert (strcmp (qstring_get_str (str), test_cases[i].encoded) ==0 );qobject_decref (obj);
@@ -830,13 +830,8 @@ static void utf8_string(void)qobject_decref (obj); obj =QOBJECT (qstring_from_str (utf8_in)); - str =qobject_to_json (obj); -if (json_out) { -g_assert (str); - g_assert_cmpstr(qstring_get_str(str), ==, json_out); - }else { -g_assert (!str); - } + str =qobject_to_json (obj, false); + g_assert_cmpstr(qstring_get_str(str), ==, json_out);QDECREF (str);qobject_decref (obj);
@@ -911,7 +906,7 @@ static void simple_number(void)if (test_cases[i].skip ==0 ) {QString *str; - str =qobject_to_json (obj); + str =qobject_to_json (obj, false);g_assert (strcmp (qstring_get_str (str), test_cases[i].encoded) ==0 );QDECREF (str); }
@@ -949,7 +944,7 @@ static void float_number(void)if (test_cases[i].skip ==0 ) {QString *str; - str =qobject_to_json (obj); + str =qobject_to_json (obj, false);g_assert (strcmp (qstring_get_str (str), test_cases[i].encoded) ==0 );QDECREF (str); }
@@ -1009,7 +1004,7 @@ static void keyword_literal(void) qbool =qobject_to_qbool (obj);g_assert (qbool_get_bool (qbool) == true); - str =qobject_to_json (obj); + str =qobject_to_json (obj, false);g_assert (strcmp (qstring_get_str (str),"true" ) ==0 );QDECREF (str);
@@ -1022,7 +1017,7 @@ static void keyword_literal(void) qbool =qobject_to_qbool (obj);g_assert (qbool_get_bool (qbool) == false); - str =qobject_to_json (obj); + str =qobject_to_json (obj, false);g_assert (strcmp (qstring_get_str (str),"false" ) ==0 );QDECREF (str);
@@ -1189,7 +1184,7 @@ static void simple_dict(void)g_assert (compare_litqobj_to_qobj (&test_cases[i].decoded, obj) ==1 ); - str =qobject_to_json (obj); + str =qobject_to_json (obj, false);qobject_decref (obj); obj =qobject_from_json (qstring_get_str (str));
@@ -1304,7 +1299,7 @@ static void simple_list(void)g_assert (compare_litqobj_to_qobj (&test_cases[i].decoded, obj) ==1 ); - str =qobject_to_json (obj); + str =qobject_to_json (obj, false);qobject_decref (obj); obj =qobject_from_json (qstring_get_str (str));
@@ -1372,7 +1367,7 @@ static void simple_whitespace(void)g_assert (compare_litqobj_to_qobj (&test_cases[i].decoded, obj) ==1 ); - str =qobject_to_json (obj); + str =qobject_to_json (obj, false);qobject_decref (obj); obj =qobject_from_json (qstring_get_str (str));
tests/libqtest.c +1 -1
@@ -420,7 +420,7 @@ void qmp_fd_sendv(int fd, const char *fmt, va_list ap)/* No need to send anything for an empty QObject. */ if (qobj) {int log =getenv ("QTEST_LOG" ) !=NULL ; -QString *qstr =qobject_to_json (qobj); +QString *qstr =qobject_to_json (qobj, false);const char *str =qstring_get_str (qstr);size_t size =qstring_get_length (qstr);
tests/test-visitor-serialization.c +1 -1
@@ -1036,7 +1036,7 @@ static void qmp_deserialize(void **native_out, void *datap,visit_complete (d->qov, &d->obj); obj_orig = d->obj; - output_json =qobject_to_json (obj_orig); + output_json =qobject_to_json (obj_orig, false); obj =qobject_from_json (qstring_get_str (output_json));QDECREF (output_json);
Signature · 1 line
2.7.4
PATCH v6 10/15 tests: Test qobject_to_json() pretty formatting
In reply to Eric BlakeIt's risky to refactor qobject_to_json() without at least testing that pretty output remains unchanged :)
Note that the new simple_pretty() test is a bit sensitive to our current notion of prettiness, as well as to the hash ordering in QDict (most of the tests in check-qobject-json intentionally do not compare the original string to the round-trip string, because we liberally accept more input forms than the canonical form that we output).
---
v6: no change
[no v5 due to series split]
v4: new patch, split from v3 12/18
--- tests/check-qjson.c | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-)
tests/check-qjson.c +65 -1
@@ -1,6 +1,6 @@/* * Copyright IBM, Corp. 2009 -* Copyright (c) 2013, 2015 Red Hat Inc. +* Copyright (c) 2013-2016 Red Hat Inc. * * Authors: * Anthony Liguori <[email protected]>
@@ -1381,6 +1381,69 @@ static void simple_whitespace(void) } } +static void simple_pretty (void ) +{ +int i; +struct { +const char *encoded; +LiteralQObject decoded; + } test_cases[] = { + { + .encoded = +"[\n" +" 43,\n" +" 42\n" +"]" , + .decoded =QLIT_QLIST (((LiteralQObject []){ +QLIT_QINT (43 ), +QLIT_QINT (42 ), + { } + })), + }, + { + .encoded = +"[\n" +" 43,\n" +" {\n" +" \"a\": 32,\n" +" \"h\": \"b\"\n" +" },\n" +" [\n" +" ],\n" +" 42\n" +"]" , + .decoded =QLIT_QLIST (((LiteralQObject []){ +QLIT_QINT (43 ), +QLIT_QDICT (((LiteralQDictEntry []){ + {"a" ,QLIT_QINT (32 ) }, + {"h" ,QLIT_QSTR ("b" ) }, + { } })), +QLIT_QLIST (((LiteralQObject []){ + { } })), +QLIT_QINT (42 ), + { } + })), + }, + { } + }; + +for (i =0 ; test_cases[i].encoded; i++) { +QObject *obj; +QString *str; + + obj =qobject_from_json (test_cases[i].encoded); +g_assert (obj !=NULL ); +g_assert (qobject_type (obj) ==QTYPE_QLIST ); + +g_assert (compare_litqobj_to_qobj (&test_cases[i].decoded, obj) ==1 ); + + str =qobject_to_json (obj, true); +qobject_decref (obj); + g_assert_cmpstr(qstring_get_str(str), ==, test_cases[i].encoded); +QDECREF (str); + } +} +static void simple_varargs (void ) {QObject *embedded_obj;
@@ -1518,6 +1581,7 @@ int main(int argc, char **argv)g_test_add_func ("/lists/simple_list" , simple_list);g_test_add_func ("/whitespace/simple_whitespace" , simple_whitespace); +g_test_add_func ("/whitespace/simple_pretty" , simple_pretty);g_test_add_func ("/varargs/simple_varargs" , simple_varargs);
Signature · 1 line
2.7.4
PATCH v6 11/15 qapi: Add JSON output visitor
In reply to Eric BlakeWe have several places that want to go from qapi to JSON; right now, they have to create an intermediate QObject to do the work. That also has the drawback that the JSON formatting of a QDict will rearrange keys (according to a deterministic, but unpredictable, hash), when humans have an easier time if dicts are produced in the same order as the qapi type.
For these reasons, it is time to add a new JSON output visitor. This patch just adds the basic visitor and tests that it works; later patches will add pretty-printing, support for visit_type_any(), and conversion of clients to use the visitor.
Design choices: Unlike the QMP output visitor, the JSON visitor refuses to visit a required string with a NULL value, via abort(). Reusing QString to grow the contents means that we easily share code with qjson.c; although it might be nice to enhance things to take an optional output callback function so that the output can truly be streamed instead of collected in memory. visit_complete() can be called at most once, so that we can take advantage of transfer semantics into the caller's pointer saved in jov->result.
---
v6: tweak commit message, adjust includes
[no v5 due to series split]
v4: retitle, split off inf/NaN handling, rebase to visit_complete and visit_free changes, defer type_any, address other findings from Markus
v3: retitle, rebase to master, minor cleanups
v2: rebase to qapi subset E v8; add test of error outputting infinity; use unsigned depth
--- include/qapi/visitor.h | 22 +-- include/qapi/json-output-visitor.h | 28 +++ qapi/json-output-visitor.c | 193 +++++++++++++++++++ tests/test-json-output-visitor.c | 383 +++++++++++++++++++++++++++++++++++++ tests/test-qmp-output-visitor.c | 5 + qapi/Makefile.objs | 2 +- tests/.gitignore | 1 + tests/Makefile.include | 5 +- 8 files changed, 626 insertions(+), 13 deletions(-) create mode 100644 include/qapi/json-output-visitor.h create mode 100644 qapi/json-output-visitor.c create mode 100644 tests/test-json-output-visitor.c
include/qapi/visitor.h +11 -11
@@ -27,17 +27,17 @@* * There are four kinds of visitor classes: input visitors (QMP, * string, and QemuOpts) parse an external representation and build -* the corresponding QAPI graph, output visitors (QMP and string) take -* a completed QAPI graph and generate an external representation, the -* dealloc visitor can take a QAPI graph (possibly partially -* constructed) and recursively free its resources, and the clone -* visitor performs a deep clone of one QAPI object to another. While -* the dealloc and QMP input/output visitors are general, the string, -* QemuOpts, and clone visitors have some implementation limitations; -* see the documentation for each visitor for more details on what it -* supports. Also, see visitor-impl.h for the callback contracts -* implemented by each visitor, and docs/qapi-code-gen.txt for more -* about the QAPI code generator. +* the corresponding QAPI graph, output visitors (QMP, string, and +* JSON) take a completed QAPI graph and generate an external +* representation, the dealloc visitor can take a QAPI graph (possibly +* partially constructed) and recursively free its resources, and the +* clone visitor performs a deep clone of one QAPI object to another. +* While the dealloc, JSON output, and QMP input/output visitors are +* general, the string, QemuOpts, and clone visitors have some +* implementation limitations; see the documentation for each visitor +* for more details on what it supports. Also, see visitor-impl.h for +* the callback contracts implemented by each visitor, and +* docs/qapi-code-gen.txt for more about the QAPI code generator. * * All of the visitors are created via: *
include/qapi/json-output-visitor.h new file +28 -0
@@ -0,0 +1,28 @@ +/* +* JSON Output Visitor +* +* Copyright (C) 2015-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. +* +*/ + +#ifndef JSON_OUTPUT_VISITOR_H +#define JSON_OUTPUT_VISITOR_H + +#include "qapi/visitor.h" + +typedef struct JsonOutputVisitor JsonOutputVisitor ; + +/* +* Create a new JSON output visitor. +* +* If everything else succeeds, pass @result to visit_complete() to +* collect the result of the visit. +* +* For now, this cannot be used to visit the 'any' type. +*/ +Visitor *json_output_visitor_new (char **result); + +#endif
qapi/json-output-visitor.c new file +193 -0
193 lines not on this page · raw message
tests/test-json-output-visitor.c new file +383 -0
383 lines not on this page · raw message
tests/test-qmp-output-visitor.c +5 -0
@@ -10,6 +10,11 @@* See the COPYING file in the top-level directory. */ +/* +* Similar in design to test-json-output-visitor; if you add tests +* here, consider adding tests there as well. +*/ +#include "qemu/osdep.h" #include "qemu-common.h"
qapi/Makefile.objs +1 -1
@@ -1,6 +1,6 @@ util-obj-y = qapi-visit-core.o qapi-dealloc-visitor.o qmp-input-visitor.o util-obj-y += qmp-output-visitor.o qmp-registry.o qmp-dispatch.o util-obj-y += string-input-visitor.o string-output-visitor.o -util-obj-y += opts-visitor.o qapi-clone-visitor.o +util-obj-y += opts-visitor.o qapi-clone-visitor.o json-output-visitor.o util-obj-y += qmp-event.o util-obj-y += qapi-util.o
tests/.gitignore +1 -0
@@ -42,6 +42,7 @@ test-io-channel-file.txt test-io-channel-socket test-io-channel-tls test-io-task +test-json-output-visitor test-logging test-mul64 test-opts-visitor
tests/Makefile.include +4 -1
@@ -24,6 +24,8 @@ check-unit-y += tests/test-qmp-output-visitor$(EXESUF) gcov-files-test-qmp-output-visitor-y = qapi/qmp-output-visitor.c check-unit-y += tests/test-clone-visitor$(EXESUF) gcov-files-test-clone-visitor-y = qapi/qapi-clone-visitor.c +check-unit-y += tests/test-json-output-visitor$(EXESUF) +gcov-files-test-json-output-visitor-y = qapi/json-output-visitor.c check-unit-y += tests/test-qmp-input-visitor$(EXESUF) gcov-files-test-qmp-input-visitor-y = qapi/qmp-input-visitor.c check-unit-y += tests/test-qmp-input-strict$(EXESUF)
@@ -447,7 +449,7 @@ test-obj-y = tests/check-qint.o tests/check-qstring.o tests/check-qdict.o \ tests/check-qjson.o \ tests/test-coroutine.o tests/test-string-output-visitor.o \ tests/test-string-input-visitor.o tests/test-qmp-output-visitor.o \ - tests/test-clone-visitor.o \ + tests/test-clone-visitor.o tests/test-json-output-visitor.o \ tests/test-qmp-input-visitor.o tests/test-qmp-input-strict.o \ tests/test-qmp-commands.o tests/test-visitor-serialization.o \ tests/test-x86-cpuid.o tests/test-mul64.o tests/test-int128.o \
@@ -551,6 +553,7 @@ tests/test-string-input-visitor$(EXESUF): tests/test-string-input-visitor.o $(te tests/test-qmp-event$(EXESUF): tests/test-qmp-event.o $(test-qapi-obj-y) tests/test-qmp-output-visitor$(EXESUF): tests/test-qmp-output-visitor.o $(test-qapi-obj-y) tests/test-clone-visitor$(EXESUF): tests/test-clone-visitor.o $(test-qapi-obj-y) +tests/test-json-output-visitor$(EXESUF): tests/test-json-output-visitor.o $(test-qapi-obj-y) tests/test-qmp-input-visitor$(EXESUF): tests/test-qmp-input-visitor.o $(test-qapi-obj-y) tests/test-qmp-input-strict$(EXESUF): tests/test-qmp-input-strict.o $(test-qapi-obj-y) tests/test-qmp-commands$(EXESUF): tests/test-qmp-commands.o tests/test-qmp-marshal.o $(test-qapi-obj-y)
Signature · 1 line
2.7.4
PATCH v6 12/15 qapi: Support pretty printing in JSON output visitor
In reply to Eric BlakeAdd pretty printing, where the format intentionally matches that of qobject_to_json() (a later patch will then rework qobject-json.c to work on top of the JSON visitor). The trickiest part is probably that the testsuite now has to honor parameterization on whether pretty printing is enabled.
---
v6: tweak commit message, use of 'bool pretty' in testsuite [no v5 due to series split]
v4: rebase to earlier changes, defer type_any() to later
v3: rebase to earlier changes
v2: rebase to earlier changes
--- include/qapi/json-output-visitor.h | 5 +- qapi/json-output-visitor.c | 15 ++++- tests/test-json-output-visitor.c | 124 +++++++++++++++++++++++++------------ 3 files changed, 101 insertions(+), 43 deletions(-)
include/qapi/json-output-visitor.h +4 -1
@@ -21,8 +21,11 @@ typedef struct JsonOutputVisitor JsonOutputVisitor;* If everything else succeeds, pass @result to visit_complete() to * collect the result of the visit. * +* If @pretty, make the output legible with newlines and indentation; +* otherwise the output uses a single line. +* * For now, this cannot be used to visit the 'any' type. */ -Visitor *json_output_visitor_new (char **result); +Visitor *json_output_visitor_new (bool pretty,char **result);#endif
qapi/json-output-visitor.c +13 -2
@@ -17,6 +17,7 @@struct JsonOutputVisitor {Visitor visitor;QString *str; +bool pretty;bool comma;unsigned int depth;char **result;
@@ -30,10 +31,13 @@ static JsonOutputVisitor *to_jov(Visitor *v)static void json_output_name (JsonOutputVisitor *jov,const char *name) {if (jov->comma) { -qstring_append (jov->str,", " ); +qstring_append (jov->str, jov->pretty ?"," :", " ); }else { jov->comma = true; } +if (jov->pretty && jov->depth) { +qstring_append_printf (jov->str,"\n%*s" ,4 * jov->depth,"" ); + }if (name && jov->depth) {qstring_append_json_string (jov->str, name);qstring_append (jov->str,": " );
@@ -57,6 +61,9 @@ static void json_output_end_struct(Visitor *v, void **obj)assert (jov->depth); jov->depth--; +if (jov->pretty) { +qstring_append_printf (jov->str,"\n%*s" ,4 * jov->depth,"" ); + }qstring_append (jov->str,"}" ); jov->comma = true; }
@@ -85,6 +92,9 @@ static void json_output_end_list(Visitor *v, void **obj)assert (jov->depth); jov->depth--; +if (jov->pretty) { +qstring_append_printf (jov->str,"\n%*s" ,4 * jov->depth,"" ); + }qstring_append (jov->str,"]" ); jov->comma = true; }
@@ -165,11 +175,12 @@ static void json_output_free(Visitor *v)g_free (jov); } -Visitor *json_output_visitor_new (char **result) +Visitor *json_output_visitor_new (bool pretty,char **result) {JsonOutputVisitor *v; v =g_malloc0 (sizeof (*v)); + v->pretty = pretty; v->result = result; *result =NULL ; v->str =qstring_new ();
tests/test-json-output-visitor.c +84 -40
176 lines not on this page · raw message
Signature · 1 line
2.7.4
Re: [Qemu-devel] [PATCH v6 12/15] qapi: Support pretty printing in JSON output visitor
Quoted 112 lines · Eric Blake
Add pretty printing, where the format intentionally matches that of
qobject_to_json()(a later patch will then reworkqobject-json.cto work on top of the JSON visitor). The trickiest part is probably that the testsuite now has to honor parameterization on whether pretty printing is enabled.Signed-off-by Eric Blake <[email protected]>---
v6: tweak commit message, use of 'bool pretty' in testsuite [no v5 due to series split]
v4: rebase to earlier changes, defertype_any()to later
v3: rebase to earlier changes
v2: rebase to earlier changes--- include/qapi/json-output-visitor.h | 5 +- qapi/json-output-visitor.c | 15 ++++- tests/test-json-output-visitor.c | 124 +++++++++++++++++++++++++------------ 3 files changed, 101 insertions(+), 43 deletions(-)include/qapi/json-output-visitor.h +4
-1@@ -21,8 +21,11 @@ typedef struct JsonOutputVisitor JsonOutputVisitor;* If everything else succeeds, pass @result to visit_complete() to * collect the result of the visit. * +* If @pretty, make the output legible with newlines and indentation; +* otherwise the output uses a single line. +* * For now, this cannot be used to visit the 'any' type. */ -Visitor *json_output_visitor_new (char **result); +Visitor *json_output_visitor_new (bool pretty,char **result);#endif qapi/json-output-visitor.c +8
-1@@ -17,6 +17,7 @@struct JsonOutputVisitor {Visitor visitor;QString *str; +bool pretty;bool comma;unsigned int depth;char **result;@@ -30,10 +31,13 @@ static JsonOutputVisitor *to_jov(Visitor *v)static void json_output_name (JsonOutputVisitor *jov,const char *name) {if (jov->comma) { -qstring_append (jov->str,", " ); +qstring_append (jov->str, jov->pretty ?"," :", " ); }else { jov->comma = true; } +if (jov->pretty && jov->depth) { +qstring_append_printf (jov->str,"\n%*s" ,4 * jov->depth,"" ); + }if (name && jov->depth) {qstring_append_json_string (jov->str, name);qstring_append (jov->str,": " );@@ -57,6 +61,9 @@ static void json_output_end_struct(Visitor *v, void **obj)assert (jov->depth); jov->depth--; +if (jov->pretty) { +qstring_append_printf (jov->str,"\n%*s" ,4 * jov->depth,"" ); + }qstring_append (jov->str,"}" ); jov->comma = true;}
qapi/json-output-visitor.c +5
-1@@ -85,6 +92,9 @@ static void json_output_end_list(Visitor *v, void **obj)assert (jov->depth); jov->depth--; +if (jov->pretty) { +qstring_append_printf (jov->str,"\n%*s" ,4 * jov->depth,"" ); + }qstring_append (jov->str,"]" ); jov->comma = true; }@@ -165,11 +175,12 @@ static void json_output_free(Visitor *v)g_free (jov); } -Visitor *json_output_visitor_new (char **result) +Visitor *json_output_visitor_new (bool pretty,char **result) {JsonOutputVisitor *v; v =g_malloc0 (sizeof (*v)); + v->pretty = pretty; v->result = result; *result =NULL ; v->str =qstring_new ();tests/test-json-output-visitor.c +1
-0@@ -24,13 +24,17 @@ typedef struct TestOutputVisitorData { Visitor *ov; + bool pretty; char *str;
tests/test-json-output-visitor.c line 36
Quoted 10 lines
tests/test-json-output-visitor.c +3
-2} TestOutputVisitorData;static void visitor_output_setup (TestOutputVisitorData *data, -const void *unused) +const void *arg) { - data->ov =json_output_visitor_new (&data->str); +bool pretty = *(bool *)arg; +
Have you considered GPOINTER_TO_INT/GINT_TO_POINTER instead of pointers to the stack frame?
either way, it's fine.
Quoted 182 lines
tests/test-json-output-visitor.c +5
-1+ data->pretty = pretty; + data->ov =json_output_visitor_new (pretty, &data->str);g_assert (data->ov); }@@ -52,8 +56,10 @@ static const char *visitor_get(TestOutputVisitorData *data)static void visitor_reset (TestOutputVisitorData *data) { +bool pretty = data->pretty; +visitor_output_teardown (data,NULL ); -visitor_output_setup (data,NULL ); +visitor_output_setup (data, &pretty); }static void test_visitor_out_int(TestOutputVisitorData *data,
tests/test-json-output-visitor.c +2
-1@@ -161,8 +167,9 @@ static void test_visitor_out_struct(TestOutputVisitorData *data, }static void test_visitor_out_struct_nested (TestOutputVisitorData *data, -const void *unused) +const void *arg) { +bool pretty = *(bool *)arg;int64_t value =42 ;UserDefTwo *ud2;const char *string = "user def string";tests/test-json-output-visitor.c +10
-21@@ -192,27 +199,51 @@ static voidtest_visitor_out_struct_nested (TestOutputVisitorData *data, visit_type_UserDefTwo(data->ov, "unused", &ud2, &error_abort); out =visitor_get (data); - g_assert_cmpstr(out, ==, -"{" -"\"string0\": \"forty two\", " -"\"dict1\": {" -"\"string1\": \"forty three\", " -"\"dict2\": {" -"\"userdef\": {" -"\"integer\": 42, " -"\"string\": \"user def string\"" -"}, " -"\"string\": \"forty four\"" -"}, " -"\"dict3\": {" -"\"userdef\": {" -"\"integer\": 42, " -"\"string\": \"user def string\"" -"}, " -"\"string\": \"forty five\"" -"}" -"}" -"}" ); + if (pretty) { + g_assert_cmpstr(out, ==, + "{\n" + " \"string0\": \"forty two\",\n" + " \"dict1\": {\n" + " \"string1\": \"forty three\",\n" + " \"dict2\": {\n" + " \"userdef\": {\n" + " \"integer\": 42,\n" + " \"string\": \"user defstring\"\n"
tests/test-json-output-visitor.c +7
-0+" },\n" +" \"string\": \"forty four\"\n" +" },\n" +" \"dict3\": {\n" +" \"userdef\": {\n" +" \"integer\": 42,\n" + " \"string\": \"user defstring\"\n"
tests/test-json-output-visitor.c +56
-16+" },\n" +" \"string\": \"forty five\"\n" +" }\n" +" }\n" + "}"); + }else { + g_assert_cmpstr(out, ==, +"{" +"\"string0\": \"forty two\", " +"\"dict1\": {" +"\"string1\": \"forty three\", " +"\"dict2\": {" +"\"userdef\": {" +"\"integer\": 42, " +"\"string\": \"user def string\"" +"}, " +"\"string\": \"forty four\"" +"}, " +"\"dict3\": {" +"\"userdef\": {" +"\"integer\": 42, " +"\"string\": \"user def string\"" +"}, " +"\"string\": \"forty five\"" +"}" +"}" +"}" ); + }qapi_free_UserDefTwo (ud2); }@@ -346,36 +377,49 @@ static voidtest_visitor_out_null (TestOutputVisitorData *data, g_assert_cmpstr(out, ==, "null"); } -static void output_visitor_test_add (const char *testpath, +static void output_visitor_test_add (const char *testpath,bool *data,void (*test_func)(TestOutputVisitorData *,const void *)) { -g_test_add (testpath, TestOutputVisitorData,NULL , visitor_output_setup, +g_test_add (testpath, TestOutputVisitorData, data, visitor_output_setup, test_func, visitor_output_teardown); }int main (int argc,char **argv) { +bool plain = false; +bool pretty = true; +g_test_init (&argc, &argv,NULL ); -output_visitor_test_add ("/visitor/json/int" , test_visitor_out_int); -output_visitor_test_add ("/visitor/json/bool" , test_visitor_out_bool); -output_visitor_test_add ("/visitor/json/number" , test_visitor_out_number); -output_visitor_test_add ("/visitor/json/string" , test_visitor_out_string); -output_visitor_test_add ("/visitor/json/enum" , test_visitor_out_enum); -output_visitor_test_add ("/visitor/json/enum-errors" , +output_visitor_test_add ("/visitor/json/int" , &plain, + test_visitor_out_int); +output_visitor_test_add ("/visitor/json/bool" , &plain, + test_visitor_out_bool); +output_visitor_test_add ("/visitor/json/number" , &plain, + test_visitor_out_number); +output_visitor_test_add ("/visitor/json/string" , &plain, + test_visitor_out_string); +output_visitor_test_add ("/visitor/json/enum" , &plain, + test_visitor_out_enum); +output_visitor_test_add ("/visitor/json/enum-errors" , &plain, test_visitor_out_enum_errors); -output_visitor_test_add ("/visitor/json/struct" , test_visitor_out_struct); -output_visitor_test_add ("/visitor/json/struct-nested" , +output_visitor_test_add ("/visitor/json/struct" , &plain, + test_visitor_out_struct); +output_visitor_test_add ("/visitor/json/struct-nested" , &plain, test_visitor_out_struct_nested); -output_visitor_test_add ("/visitor/json/struct-errors" , +output_visitor_test_add ("/visitor/json-pretty/struct-nested" , &pretty, + test_visitor_out_struct_nested); +output_visitor_test_add ("/visitor/json/struct-errors" , &plain, test_visitor_out_struct_errors); -output_visitor_test_add ("/visitor/json/list" , test_visitor_out_list); -output_visitor_test_add ("/visitor/json/union-flat" , +output_visitor_test_add ("/visitor/json/list" , &plain, + test_visitor_out_list); +output_visitor_test_add ("/visitor/json/union-flat" , &plain, test_visitor_out_union_flat); -output_visitor_test_add ("/visitor/json/alternate" , +output_visitor_test_add ("/visitor/json/alternate" , &plain, test_visitor_out_alternate); -output_visitor_test_add ("/visitor/json/null" , test_visitor_out_null); +output_visitor_test_add ("/visitor/json/null" , &plain, + test_visitor_out_null);g_test_run (); --2.7.4
Quoted 1 line
--
Marc-André Lureau
Re: [Qemu-devel] [PATCH v6 12/15] qapi: Support pretty printing in JSON output visitor
Quoted 19 lines · Marc-André Lureau
Quoted 10 lines · Eric Blake
Add pretty printing, where the format intentionally matches that of
qobject_to_json()(a later patch will then reworkqobject-json.cto work on top of the JSON visitor). The trickiest part is probably that the testsuite now has to honor parameterization on whether pretty printing is enabled.static void visitor_output_setup(TestOutputVisitorData *data,
tests/test-json-output-visitor.c line 35
Quoted 6 lines
tests/test-json-output-visitor.c +3
-2- const void *unused) + const void *arg) { - data->ov =json_output_visitor_new (&data->str); +bool pretty = *(bool *)arg; +
Quoted 2 lines
Have you considered GPOINTER_TO_INT/GINT_TO_POINTER instead of pointers to the stack frame?
Casting integer values to void* and back requires a lot of typing to pacify all compilers (either explicit casts, or casts hidden inside the lengthy macro names from glib); and fails to work for 64-bit values when void* is only 32 bits. Dereferencing a stack pointer is a lot less thought and less typing, and works regardless of the integer size.
Quoted 3 lines
either way, it's fine.
Good, I won't bother changing it.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
PATCH v6 13/15 qobject: Implement qobject_to_json() atop JSON visitor
In reply to Eric BlakeRather than open-code two different JSON visitors, it's nicer to make qobject_to_json() reuse the JSON output visitor. The JSON output visitor allowed us to separate formatting from walking the tree, where the tree walk is normally done by the QAPI-generated code for a "real" visit. Now we can add another tree walk of QObject, while reusing the formatting of the JSON visitor, in a "virtual" visit.
Note that this virtual QObject tree walk can also be paired with other visitors. The string output visitor isn't useful (it would fail if structs are involved), but the (misnamed) QMP output visitor could be used to perform a QObject deep clone. However, I did not find any obvious QObject clones in the current code base that needed to use this trick.
---
v6: rebase, improve commit message, simplify iterators [no v5 due to series split]
v4: new patch, inspired by discussion on v3 12/18
--- include/qapi/qmp/qjson.h | 9 ++++ qobject/qjson.c | 113 +++++++++++++---------------------------------- 2 files changed, 40 insertions(+), 82 deletions(-)
include/qapi/qmp/qjson.h +9 -0
@@ -24,6 +24,15 @@ QObject *qobject_from_jsonv(const char *string, va_list *ap) GCC_FMT_ATTR(1, 0);/* Convert the object to QString; does not fail. */ QString *qobject_to_json (const QObject *obj,bool pretty); +/* +* Visit the object with an output visitor @v. +* +* @name represents the relationship of this object to any parent +* (ignored for a top-level visit, must be set if part of a +* dictionary, should be NULL if part of a list). +*/ +void qobject_visit_output (Visitor *v,const char *name,const QObject *obj); +int qstring_append_json_string (QString *qstring,const char *str);void qstring_append_json_number (QString *qstring,double number);
qobject/qjson.c +31 -82
163 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH v6 14/15 qapi: Add 'any' support to JSON output
In reply to Eric BlakeNow that we can visit any QObject, it's easy to add support for visit_type_any() in the JSON output visitor.
---
v6: no change
[no v5 due to series split]
v4: new patch, split out of v3 7/18, but made simpler by not requiring v3 12/18
--- include/qapi/json-output-visitor.h | 2 -- qapi/json-output-visitor.c | 7 ++++++ tests/test-json-output-visitor.c | 50 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-)
include/qapi/json-output-visitor.h +0 -2
@@ -23,8 +23,6 @@ typedef struct JsonOutputVisitor JsonOutputVisitor;* * If @pretty, make the output legible with newlines and indentation; * otherwise the output uses a single line. -* -* For now, this cannot be used to visit the 'any' type. */ Visitor *json_output_visitor_new (bool pretty,char **result);
qapi/json-output-visitor.c +7 -0
@@ -147,6 +147,12 @@ static void json_output_type_number(Visitor *v, const char *name, double *obj,qstring_append_json_number (jov->str, *obj); } +static void json_output_type_any (Visitor *v,const char *name,QObject **obj, +Error **errp) +{ +qobject_visit_output (v, name, *obj); +} +static void json_output_type_null (Visitor *v,const char *name,Error **errp) {JsonOutputVisitor *jov =to_jov (v);
@@ -196,6 +202,7 @@ Visitor *json_output_visitor_new(bool pretty, char **result) v->visitor.type_bool = json_output_type_bool; v->visitor.type_str = json_output_type_str; v->visitor.type_number = json_output_type_number; + v->visitor.type_any = json_output_type_any; v->visitor.type_null = json_output_type_null; v->visitor.complete = json_output_complete; v->visitor.free = json_output_free;
tests/test-json-output-visitor.c +50 -0
62 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH v6 15/15 qemu-img: Use new JSON output formatter
In reply to Eric BlakeNow that we can pretty-print straight to JSON from a visitor, we can eliminate the temporary conversion into QObject inside qemu-img.
The changes to qemu-iotests 043 expected output demonstrates the fact that output is now done in qapi declaration order, rather than QDict hash order.
---
v6: rebase
[no v5 due to series split]
v4: rebase to earlier changes
v3: rebase to master
v2: Drop RFC, adjust expected output of 043; rebase to 'name' motion
Overlaps with Fam's qemu-img edits, although he has expressed interest in getting this one in first.
https://lists.gnu.org/archive/html/qemu-devel/2015-12/msg01756.html
https://lists.gnu.org/archive/html/qemu-devel/2015-12/msg01806.html
--- qemu-img.c | 43 +++++++++++++++++-------------------------- tests/qemu-iotests/043.out | 22 +++++++++++----------- 2 files changed, 28 insertions(+), 37 deletions(-)
qemu-img.c +17 -26
@@ -25,9 +25,9 @@#include "qemu-version.h" #include "qapi/error.h" #include "qapi-visit.h" -#include "qapi/qmp-output-visitor.h" +#include "qapi/json-output-visitor.h" #include "qapi/qmp/qerror.h" -#include "qapi/qmp/qjson.h" +#include "qapi/qmp/types.h" #include "qemu/cutils.h" #include "qemu/config-file.h" #include "qemu/option.h"
@@ -498,17 +498,14 @@ fail:static void dump_json_image_check (ImageCheck *check,bool quiet) { -QString *str; -QObject *obj; -Visitor *v =qmp_output_visitor_new (&obj); +char *str; +Visitor *v =json_output_visitor_new (true, &str);visit_type_ImageCheck (v,NULL , &check, &error_abort); -visit_complete (v, &obj); - str =qobject_to_json (obj, true); -qprintf (quiet,"%s\n" ,qstring_get_str (str)); -qobject_decref (obj); +visit_complete (v, &str); +qprintf (quiet,"%s\n" , str); +g_free (str);visit_free (v); -QDECREF (str); }static void dump_human_image_check (ImageCheck *check,bool quiet)
@@ -2190,32 +2187,26 @@ static void dump_snapshots(BlockDriverState *bs)static void dump_json_image_info_list (ImageInfoList *list) { -QString *str; -QObject *obj; -Visitor *v =qmp_output_visitor_new (&obj); +char *str; +Visitor *v =json_output_visitor_new (true, &str);visit_type_ImageInfoList (v,NULL , &list, &error_abort); -visit_complete (v, &obj); - str =qobject_to_json (obj, true); -printf ("%s\n" ,qstring_get_str (str)); -qobject_decref (obj); +visit_complete (v, &str); +printf ("%s\n" , str);visit_free (v); -QDECREF (str); +g_free (str); }static void dump_json_image_info (ImageInfo *info) { -QString *str; -QObject *obj; -Visitor *v =qmp_output_visitor_new (&obj); +char *str; +Visitor *v =json_output_visitor_new (true, &str);visit_type_ImageInfo (v,NULL , &info, &error_abort); -visit_complete (v, &obj); - str =qobject_to_json (obj, true); -printf ("%s\n" ,qstring_get_str (str)); -qobject_decref (obj); +visit_complete (v, &str); +printf ("%s\n" , str);visit_free (v); -QDECREF (str); +g_free (str); }static void dump_human_image_info_list (ImageInfoList *list)
tests/qemu-iotests/043.out +11 -11
@@ -40,29 +40,29 @@ cluster_size: 65536 == finite chain of length 3 (json) == [ { - "virtual-size": 134217728, "filename": "TEST_DIR/t.IMGFMT", - "cluster-size": 65536, "format": "IMGFMT", - "full-backing-filename": "TEST_DIR/t.IMGFMT.2.base", + "dirty-flag": false, + "virtual-size": 134217728, + "cluster-size": 65536, "backing-filename": "TEST_DIR/t.IMGFMT.2.base", - "dirty-flag": false + "full-backing-filename": "TEST_DIR/t.IMGFMT.2.base", }, { - "virtual-size": 134217728, "filename": "TEST_DIR/t.IMGFMT.2.base", - "cluster-size": 65536, "format": "IMGFMT", - "full-backing-filename": "TEST_DIR/t.IMGFMT.1.base", + "dirty-flag": false, + "virtual-size": 134217728, + "cluster-size": 65536, "backing-filename": "TEST_DIR/t.IMGFMT.1.base", - "dirty-flag": false + "full-backing-filename": "TEST_DIR/t.IMGFMT.1.base", }, { - "virtual-size": 134217728, "filename": "TEST_DIR/t.IMGFMT.1.base", - "cluster-size": 65536, "format": "IMGFMT", - "dirty-flag": false + "dirty-flag": false, + "virtual-size": 134217728, + "cluster-size": 65536, } ] *** done
Signature · 1 line
2.7.4
Hi
Quoted 44 lines · Eric Blake
[5 months later...]
Going from qapi to QObject to JSON is wasteful compared to going straight from qapi to JSON. What's more, having QObject in the middle means that dict keys are shuffled according to hash ordering, while going straight from qapi means we match the .json QAPI file declaration order. Factoring out JSON visits to a common central file will make it easier to make any further tweaks, such as patching floating point output to be unambiguous.Based on Markus' qapi-next branch, but should apply to current qemu.git master.
Diff from v4, which was at:
https://lists.gnu.org/archive/html/qemu-devel/2016-05/msg03220.html
(v4 was both JSON and clone visitors; v5 split out just the clone visitor, leaving just the JSON visitor and hence calling this v6):- assert up front that we are no longer willing to receive or pass non-finite numbers through QMP
- drop experiment related to string-izing nonfinite numbers
- rebase to recent changes
- address other minor review comments from MarkusAvailable as a tag at:
git fetchgit://repo.or.cz/qemu/ericb.gitqapi-jsonv6001/15:[down] 'qapi: Visitor documentation tweak'
002/15:[down] 'qapi: Assert finite use of 'number'' 003/15:[0013] [FC] 'qapi: Factor out JSON string escaping' 004/15:[0022] [FC] 'qapi: Factor out JSON number formatting' 005/15:[----] [--] 'qapi: Addqstring_append_printf()' 006/15:[----] [--] 'qapi: Useqstring_append_chr()where appropriate' 007/15:[----] [--] 'qstring: Addqstring_consume_str()' 008/15:[0022] [FC] 'qstring: Addqstring_wrap_str()' 009/15:[----] [-C] 'qobject: Consolidateqobject_to_json()calls' 010/15:[----] [--] 'tests: Testqobject_to_json()pretty formatting' 011/15:[0013] [FC] 'qapi: Add JSON output visitor' 012/15:[0012] [FC] 'qapi: Support pretty printing in JSON output visitor' 013/15:[0041] [FC] 'qobject: Implementqobject_to_json()atop JSON visitor' 014/15:[----] [--] 'qapi: Add 'any' support to JSON output' 015/15:[0002] [FC] 'qemu-img: Use new JSON output formatter'
Quoted 17 lines
Eric Blake (15):
qapi: Visitor documentation tweak
qapi: Assert finite use of 'number'
qapi: Factor out JSON string escaping
qapi: Factor out JSON number formatting
qapi: Addqstring_append_printf()
qapi: Useqstring_append_chr()where appropriate
qstring: Addqstring_consume_str()
qstring: Addqstring_wrap_str()
qobject: Consolidateqobject_to_json()calls
tests: Testqobject_to_json()pretty formatting
qapi: Add JSON output visitor
qapi: Support pretty printing in JSON output visitor
qobject: Implementqobject_to_json()atop JSON visitor
qapi: Add 'any' support to JSON output
qemu-img: Use new JSON output formatter
Except the minor comments I left in patch 8 and 12, the whole series is good to me:
Quoted 35 lines
include/qapi/visitor.h | 33 +-- include/qapi/json-output-visitor.h | 29 +++ include/qapi/qmp/qjson.h | 16 +- include/qapi/qmp/qstring.h | 9 +- block.c | 5 +- block/accounting.c | 6 +- block/archipelago.c | 6 +- blockdev.c | 3 +- migration/migration.c | 4 + migration/qjson.c | 12 +- monitor.c | 10 +- qapi/json-output-visitor.c | 211 ++++++++++++++++ qemu-img.c | 46 ++-- qga/main.c | 5 +- qobject/json-parser.c | 25 +- qobject/qjson.c | 301 ++++++++++------------- qobject/qstring.c | 69 +++++- qom/object.c | 3 +- tests/check-qjson.c | 93 ++++++-- tests/check-qstring.c | 46 +++- tests/libqtest.c | 2 +- tests/test-json-output-visitor.c | 477 +++++++++++++++++++++++++++++++++++++ tests/test-qmp-output-visitor.c | 5 + tests/test-visitor-serialization.c | 2 +- qapi/Makefile.objs | 2 +- tests/.gitignore | 1 + tests/Makefile.include | 5 +- tests/qemu-iotests/043.out | 22 +- 28 files changed, 1137 insertions(+), 311 deletions(-) create mode 100644 include/qapi/json-output-visitor.h create mode 100644 qapi/json-output-visitor.c create mode 100644 tests/test-json-output-visitor.c
Quoted 5 lines
--
2.7.4--
Marc-André Lureau