]> xenbits.xensource.com Git - libvirt.git/commitdiff
virjson: always raise vir error on append failures
authorEric Blake <eblake@redhat.com>
Fri, 25 Jan 2019 03:28:23 +0000 (21:28 -0600)
committerEric Blake <eblake@redhat.com>
Fri, 25 Jan 2019 15:21:24 +0000 (09:21 -0600)
A function that returns -1 for multiple possible failures, but only
raises a libvirt error for some of those failures, can be hard to
use correctly. Yet both of our JSON object/array appenders fall in
that pattern.  True, the silent errors represent coding bugs that
none of the callers should ever trigger, while the noisy errors
represent memory failures that can happen anywhere, so we happened
to never end up failing without an error. But it is better to
either use the _QUIET memory allocation variants, and make callers
decide to report failure; or make all failure paths noisy. This
patch takes the latter approach.

Signed-off-by: Eric Blake <eblake@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
src/util/virjson.c

index 78f868a16271d40f78912a4d5fd0756900424a64..a028a0813a6471daa401a11ab6c2399814bc0feb 100644 (file)
@@ -620,11 +620,16 @@ virJSONValueObjectAppend(virJSONValuePtr object,
 {
     char *newkey;
 
-    if (object->type != VIR_JSON_TYPE_OBJECT)
+    if (object->type != VIR_JSON_TYPE_OBJECT) {
+        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
+                       _("expecting JSON object"));
         return -1;
+    }
 
-    if (virJSONValueObjectHasKey(object, key))
+    if (virJSONValueObjectHasKey(object, key)) {
+        virReportError(VIR_ERR_INTERNAL_ERROR, _("duplicate key '%s'"), key);
         return -1;
+    }
 
     if (VIR_STRDUP(newkey, key) < 0)
         return -1;
@@ -774,8 +779,10 @@ int
 virJSONValueArrayAppend(virJSONValuePtr array,
                         virJSONValuePtr value)
 {
-    if (array->type != VIR_JSON_TYPE_ARRAY)
+    if (array->type != VIR_JSON_TYPE_ARRAY) {
+        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("expecting JSON array"));
         return -1;
+    }
 
     if (VIR_REALLOC_N(array->data.array.values,
                       array->data.array.nvalues + 1) < 0)