[PATCH 10/33] virDomainDefSetMetadata: Rework memory handling

Peter Krempa pkrempa at redhat.com
Wed Feb 24 16:16:45 UTC 2021


Switch to use g_autoptr for 'doc' and 'new' local variables.
Additionally report proper error when 'xmlAddChild' fails because OOM is
not the only error it can report.

Signed-off-by: Peter Krempa <pkrempa at redhat.com>
---
 src/conf/domain_conf.c | 34 ++++++++++++++++------------------
 1 file changed, 16 insertions(+), 18 deletions(-)

diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index 6f4487fcfc..46620d38ed 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -30423,15 +30423,14 @@ virDomainDefSetMetadata(virDomainDefPtr def,
                         const char *key,
                         const char *uri)
 {
-    xmlDocPtr doc = NULL;
+    g_autoptr(xmlDoc) doc = NULL;
     xmlNodePtr old;
-    xmlNodePtr new = NULL;
-    int ret = -1;
+    g_autoptr(xmlNode) new = NULL;

     if (type >= VIR_DOMAIN_METADATA_LAST) {
         virReportError(VIR_ERR_INVALID_ARG,
                        _("unknown metadata type '%d'"), type);
-        goto cleanup;
+        return -1;
     }

     switch ((virDomainMetadataType) type) {
@@ -30451,23 +30450,24 @@ virDomainDefSetMetadata(virDomainDefPtr def,

     case VIR_DOMAIN_METADATA_ELEMENT:
         if (metadata) {
+
             /* parse and modify the xml from the user */
             if (!(doc = virXMLParseString(metadata, _("(metadata_xml)"))))
-                goto cleanup;
+                return -1;

             if (virXMLInjectNamespace(doc->children, uri, key) < 0)
-                goto cleanup;
+                return -1;

             /* create the root node if needed */
             if (!def->metadata &&
                 !(def->metadata = xmlNewNode(NULL, (unsigned char *)"metadata"))) {
                 virReportOOMError();
-                goto cleanup;
+                return -1;
             }

             if (!(new = xmlCopyNode(doc->children, 1))) {
                 virReportOOMError();
-                goto cleanup;
+                return -1;
             }
         }

@@ -30477,11 +30477,13 @@ virDomainDefSetMetadata(virDomainDefPtr def,
             xmlFreeNode(old);
         }

-        if (new &&
-            !(xmlAddChild(def->metadata, new))) {
-            xmlFreeNode(new);
-            virReportOOMError();
-            goto cleanup;
+        if (new) {
+            if (!(xmlAddChild(def->metadata, new))) {
+                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
+                               _("failed to add metadata to XML document"));
+                return -1;
+            }
+            new = NULL;
         }
         break;

@@ -30490,11 +30492,7 @@ virDomainDefSetMetadata(virDomainDefPtr def,
         break;
     }

-    ret = 0;
-
- cleanup:
-    xmlFreeDoc(doc);
-    return ret;
+    return 0;
 }


-- 
2.29.2




More information about the libvir-list mailing list