Re: [libvirt PATCH 4/4] tools: be more paranoid about possibly NULL description

2020-07-22 Thread Laine Stump

On 7/22/20 1:21 PM, Daniel P. Berrangé wrote:

GCC 10 complains about "desc" possibly being a NULL dereference. Even
though it is a false positive, we can easily avoid it.

Signed-off-by: Daniel P. Berrangé 



Reviewed-by: Laine Stump 



So those were the only complaints of gcc 10? We got off easy :-)



---
  tools/vsh.c | 2 +-
  1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tools/vsh.c b/tools/vsh.c
index 527c135424..b65e99cbd2 100644
--- a/tools/vsh.c
+++ b/tools/vsh.c
@@ -689,7 +689,7 @@ vshCmddefHelp(vshControl *ctl, const vshCmdDef *def)
  fputc('\n', stdout);
  
  desc = vshCmddefGetInfo(def, "desc");

-if (*desc) {
+if (desc && *desc) {
  /* Print the description only if it's not empty.  */
  fputs(_("\n  DESCRIPTION\n"), stdout);
  fprintf(stdout, "%s\n", _(desc));





Re: [libvirt PATCH 3/4] tests: don't mock the time() function on mingw

2020-07-22 Thread Laine Stump

On 7/22/20 1:21 PM, Daniel P. Berrangé wrote:

The mingw header define time() as a static inline function and this
causes a duplicate definition build failure. Since we're not using the
LD_PRELOAD at all on Mingw, we ideally wouldn't compile any of the
mock libraries. Rather than change the build system now though, this
just stubs out the offending function.

Signed-off-by: Daniel P. Berrangé 



Reviewed-by: Laine Stump 



---
  tests/virnetdaemonmock.c | 2 ++
  1 file changed, 2 insertions(+)

diff --git a/tests/virnetdaemonmock.c b/tests/virnetdaemonmock.c
index 3b92fff8c9..c523da0791 100644
--- a/tests/virnetdaemonmock.c
+++ b/tests/virnetdaemonmock.c
@@ -23,6 +23,7 @@
  
  #define VIR_FROM_THIS VIR_FROM_NONE
  
+#ifndef WIN32

  time_t time(time_t *t)
  {
  const time_t ret = 1234567890;
@@ -30,3 +31,4 @@ time_t time(time_t *t)
  *t = ret;
  return ret;
  }
+#endif





Re: [libvirt PATCH 1/4] util: refactor code to workaround gcc 10.1.0 bug

2020-07-22 Thread Laine Stump

On 7/22/20 1:21 PM, Daniel P. Berrangé wrote:

gcc 10.1.0 on Debian sid has a bug where the bounds checking gets
confused beteen two branches:

In file included from /usr/include/string.h:495,
  from ../../src/internal.h:28,
  from ../../src/util/virsocket.h:21,
  from ../../src/util/virsocketaddr.h:21,
  from ../../src/util/virnetdevip.h:21,
  from ../../src/util/virnetdevip.c:21:
In function 'memcpy',
 inlined from 'virNetDevGetifaddrsAddress' at 
../../src/util/virnetdevip.c:914:13,
 inlined from 'virNetDevIPAddrGet' at ../../src/util/virnetdevip.c:962:16:
/usr/include/arm-linux-gnueabihf/bits/string_fortified.h:34:10: error: 
'__builtin_memcpy' offset [16, 27] from the object at 'addr' is out of the 
bounds of referenced subobject 'inet4' with type 'struct sockaddr_in' at offset 
0 [-Werror=array-bounds]
34 |   return __builtin___memcpy_chk (__dest, __src, __len, __bos0 
(__dest));
   |  ^~
In file included from ../../src/util/virnetdevip.h:21,
  from ../../src/util/virnetdevip.c:21:
../../src/util/virnetdevip.c: In function 'virNetDevIPAddrGet':
../../src/util/virsocketaddr.h:29:28: note: subobject 'inet4' declared here
29 | struct sockaddr_in inet4;
   |^
cc1: all warnings being treated as errors

Note the source location is pointing to the "inet6" / AF_INET6 branch of
the "if", but is complaining about bounds of the "inet4" field. Changing
the code into a switch() is sufficient to avoid triggering the bug and
is arguably better code too.

Signed-off-by: Daniel P. Berrangé 


(Huh, I thought I sent an ack for this when you posted it the first time 
this morning, but I guess it failed to send, so it was still sitting in 
an obscured window on my screen...)



I don't have a system running gcc 10 yet, but this code looks to provide 
identical functionality, and still works with gcc 9.3.1



Reviewed-by: Laine Stump 



---
  src/util/virnetdevip.c | 17 -
  1 file changed, 8 insertions(+), 9 deletions(-)

diff --git a/src/util/virnetdevip.c b/src/util/virnetdevip.c
index ba9e567e5a..8b85c7beca 100644
--- a/src/util/virnetdevip.c
+++ b/src/util/virnetdevip.c
@@ -897,26 +897,25 @@ virNetDevGetifaddrsAddress(const char *ifname,
  }
  
  for (ifa = ifap; ifa; ifa = ifa->ifa_next) {

-int family;
-
  if (STRNEQ_NULLABLE(ifa->ifa_name, ifname))
  continue;
  
  if (!ifa->ifa_addr)

  continue;
-family = ifa->ifa_addr->sa_family;
-
-if (family != AF_INET6 && family != AF_INET)
-continue;
  
-if (family == AF_INET6) {

+switch (ifa->ifa_addr->sa_family) {
+case AF_INET6:
  addr->len = sizeof(addr->data.inet6);
  memcpy(>data.inet6, ifa->ifa_addr, addr->len);
-} else {
+break;
+case AF_INET:
  addr->len = sizeof(addr->data.inet4);
  memcpy(>data.inet4, ifa->ifa_addr, addr->len);
+break;
+default:
+continue;
  }
-addr->data.stor.ss_family = family;
+addr->data.stor.ss_family = ifa->ifa_addr->sa_family;
  ret = 0;
  goto cleanup;
  }





Re: [libvirt PATCH 2/4] m4: enable -fstack-protector-strong on mingw

2020-07-22 Thread Laine Stump

On 7/22/20 1:21 PM, Daniel P. Berrangé wrote:

Historically we avoided -fstack-protector* since it resulted in a broken
build on Mingw. In GCC 10 in Fedora though, we have the opposite problem,
getting a broken build if we don't enable one of the -fstack-protector*
options. This also works in GCC 9, so we don't need to worry about the
old brokeness which evidentally got fixed at some time without noticing.



...and I guess there's no "super old" mingw releases that we need to 
worry about, since it's always the mingw on the current release of 
Fedora that's used (did I get that right?)



Reviewed-by: Laine Stump 




Signed-off-by: Daniel P. Berrangé 
---
  m4/virt-compile-warnings.m4 | 4 +---
  1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/m4/virt-compile-warnings.m4 b/m4/virt-compile-warnings.m4
index d3538d59f8..d171d09991 100644
--- a/m4/virt-compile-warnings.m4
+++ b/m4/virt-compile-warnings.m4
@@ -169,13 +169,11 @@ AC_DEFUN([LIBVIRT_COMPILE_WARNINGS],[
  gl_WARN_ADD([-Wframe-larger-than=262144], [RELAXED_FRAME_LIMIT_CFLAGS])
  
  # Extra special flags

-dnl -fstack-protector stuff passes gl_WARN_ADD with gcc
-dnl on Mingw32, but fails when actually used
  case $host in
 aarch64-*-*)
 dnl "error: -fstack-protector not supported for this target [-Werror]"
 ;;
-   *-*-linux*)
+   *-*-linux* | *-*-mingw*)
 dnl Prefer -fstack-protector-strong if it's available.
 dnl There doesn't seem to be great overhead in adding
 dnl -fstack-protector-all instead of -fstack-protector.





Re: [libvirt PATCH v2 06/15] network: eliminate unnecessary labels

2020-07-21 Thread Laine Stump

On 7/21/20 8:04 AM, John Ferlan wrote:



On 7/7/20 5:08 PM, Laine Stump wrote:

All these cleanup/error labels were reduced to having just "return
ret" by a previous patch, so get rid of them and return directly.

Signed-off-by: Laine Stump 
---
  src/network/bridge_driver.c   | 264 --
  src/network/bridge_driver_linux.c |  15 +-
  2 files changed, 113 insertions(+), 166 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 31bd0dd92c..79b2ca3330 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c


[...]

Coverity noted there's a leak with this part of the change for @field...

  
@@ -2207,7 +2164,6 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)

  {
  virNetworkDefPtr def = virNetworkObjGetDef(obj);
  g_autofree char *field = NULL;
-int ret = -1;
  bool enableIPv6 = !!virNetworkDefGetIPByIndex(def, AF_INET6, 0);
  
  /* set disable_ipv6 if there are no ipv6 addresses defined for the

@@ -2221,15 +2177,14 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
  if (!enableIPv6)
  VIR_DEBUG("ipv6 appears to already be disabled on %s",
def->bridge);
-ret = 0;
-goto cleanup;
+return 0;
  }


Below here doesn't match w/ current source, but I assume you know that.
Looks like a mis-merge with the review from the previous patch.


Sigh.

I *thought* I had removed all the changes to this function when I 
rebased the series the last time (since Jan already had a better patch 
for it), but I guess I didn't look carefully enough at the diffs before 
I pushed :-(


Fortunately, Jan has pushed his patch, which completely replaces the 
function.





  
  if (virFileWriteStr(field, enableIPv6 ? "0" : "1", 0) < 0) {

  virReportSystemError(errno,
   _("cannot write to %s to enable/disable IPv6 "
 "on bridge %s"), field, def->bridge);
-goto cleanup;
+return -1;
  }
  
  /* The rest of the ipv6 sysctl tunables should always be set the

@@ -2246,7 +2201,7 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
  if (virFileWriteStr(field, "0", 0) < 0) {
  virReportSystemError(errno,
   _("cannot disable %s"), field);
-goto cleanup;
+return -1;
  }
  
  /* All interfaces used as a gateway (which is what this is, by

@@ -2258,12 +2213,10 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
  if (virFileWriteStr(field, "0", 0) < 0) {
  virReportSystemError(errno,
   _("cannot disable %s"), field);
-goto cleanup;
+return -1;
  }
  
-ret = 0;

- cleanup:
-return ret;
+return 0;
  }


[...]





Re: [libvirt PATCH v2 08/15] nwfilter: remove unnecessary code from ebtablesGetSubChainInsts()

2020-07-20 Thread Laine Stump

On 7/20/20 5:04 PM, Ján Tomko wrote:

On a Saturday in 2020, Laine Stump wrote:

On 7/15/20 11:30 AM, Ján Tomko wrote:

On a Tuesday in 2020, Laine Stump wrote:


Signed-off-by: Laine Stump 



My S-o-b stands. I still think this is the right thing to do.



S-o-b merely means that you are the author and/or have the author's
permission to use the code. I don't think you can revoke a S-o-b,
even if you don't think the code is right. 



Yeah, I know that a misuse of S-o-b, I just like the idea of putting 
something at the end of the commit message that's equivalent to a 
politician at the end of their election ad: "I'm Zaphod Beeblebrox, and 
I approve this message". :-)




[PATCH 3/5] util: log an error if virXMLNodeContentString will return NULL

2020-07-20 Thread Laine Stump
Many of our calls to xmlNodeGetContent() (which are now all via
virXMLNodeContentString() are failing to check for a NULL return. We
need to remedy that, but in order to make the remedy simpler, let's
log an error in virXMLNodeContentString(), so that the callers don't
all individually need to (since it would be the same error message for
all of them anyway).

Signed-off-by: Laine Stump 
---
 src/util/virxml.c | 18 +-
 1 file changed, 17 insertions(+), 1 deletion(-)

diff --git a/src/util/virxml.c b/src/util/virxml.c
index 27d22598ee..5315d4ff6f 100644
--- a/src/util/virxml.c
+++ b/src/util/virxml.c
@@ -538,7 +538,23 @@ virXMLPropStringLimit(xmlNodePtr node,
 char *
 virXMLNodeContentString(xmlNodePtr node)
 {
-return (char *)xmlNodeGetContent(node);
+char *ret = (char *)xmlNodeGetContent(node);
+
+if (node->type !=  XML_ELEMENT_NODE) {
+virReportError(VIR_ERR_INTERNAL_ERROR,
+   _("node '%s' has unexpected type %d"),
+   node->name, node->type);
+return NULL;
+}
+
+if (!ret) {
+virReportError(VIR_ERR_INTERNAL_ERROR,
+   _("node '%s' has unexpected NULL content. This could be 
caused by malformed input, or a memory allocation failure"),
+   node->name);
+return NULL;
+}
+
+return ret;
 }
 
 
-- 
2.25.4



[PATCH 1/5] conf: refactor virDomainBlkioDeviceParseXML to reduce calls to xmlNodeGetContent

2020-07-20 Thread Laine Stump
virDomainBlkioDeviceParseXML() calls xmlNodeGetContent() multiple
times in a loop, but can easily be refactored to call it once for all
element nodes, and then use the result of that one call in each of the
(mutually exclusive) blocks that previously each had their own call to
xmlNodeGetContent.

This is being done in order to reduce the number of changes needed in
an upcoming patch that will eliminate the lack of checking for NULL on
return from xmlNodeGetContent().

As part of the simplification, the while() loop has been changed into
a for() so that we can use "continue" without bypassing the "node =
node->next".

Signed-off-by: Laine Stump 

Change from V1: turned into for() loop and log error rather than
ignoring NULL. Jano had suggested we might be able to set dev->path
directly instead of using a temporary var, but doing that would
require keeping the error: label and its cleanup of dev->path, rather
than just relying on g_autofree.

Signed-off-by: Laine Stump 
---
 src/conf/domain_conf.c | 128 ++---
 1 file changed, 70 insertions(+), 58 deletions(-)

diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index 7ecd2818b9..ade8c13914 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -1635,73 +1635,85 @@ virDomainBlkioDeviceParseXML(xmlNodePtr root,
  virBlkioDevicePtr dev)
 {
 xmlNodePtr node;
-g_autofree char *c = NULL;
-
-node = root->children;
-while (node) {
-if (node->type == XML_ELEMENT_NODE) {
-if (virXMLNodeNameEqual(node, "path") && !dev->path) {
-dev->path = (char *)xmlNodeGetContent(node);
-} else if (virXMLNodeNameEqual(node, "weight")) {
-c = (char *)xmlNodeGetContent(node);
-if (virStrToLong_ui(c, NULL, 10, >weight) < 0) {
-virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
-   _("could not parse weight %s"),
-   c);
-goto error;
-}
-VIR_FREE(c);
-} else if (virXMLNodeNameEqual(node, "read_bytes_sec")) {
-c = (char *)xmlNodeGetContent(node);
-if (virStrToLong_ull(c, NULL, 10, >rbps) < 0) {
-virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
-   _("could not parse read bytes sec %s"),
-   c);
-goto error;
-}
-VIR_FREE(c);
-} else if (virXMLNodeNameEqual(node, "write_bytes_sec")) {
-c = (char *)xmlNodeGetContent(node);
-if (virStrToLong_ull(c, NULL, 10, >wbps) < 0) {
-virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
-   _("could not parse write bytes sec %s"),
-   c);
-goto error;
-}
-VIR_FREE(c);
-} else if (virXMLNodeNameEqual(node, "read_iops_sec")) {
-c = (char *)xmlNodeGetContent(node);
-if (virStrToLong_ui(c, NULL, 10, >riops) < 0) {
-virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
-   _("could not parse read iops sec %s"),
-   c);
-goto error;
-}
-VIR_FREE(c);
-} else if (virXMLNodeNameEqual(node, "write_iops_sec")) {
-c = (char *)xmlNodeGetContent(node);
-if (virStrToLong_ui(c, NULL, 10, >wiops) < 0) {
-virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
-   _("could not parse write iops sec %s"),
-   c);
-goto error;
-}
-VIR_FREE(c);
+g_autofree char *path = NULL;
+
+for (node = root->children; node != NULL; node = node->next) {
+g_autofree char *c = NULL;
+
+if (node->type != XML_ELEMENT_NODE)
+continue;
+
+c = (char *)xmlNodeGetContent(node);
+
+if (virXMLNodeNameEqual(node, "path")) {
+/* To avoid the need for explicit cleanup on failure,
+ * don't set dev->path until we're assured of
+ * success. Until then, store it in an autofree pointer.
+ */
+if (!path)
+path = g_steal_pointer();
+continue;
+}
+
+if (virXMLNodeNameEqual(node, "weight")) {
+if (virStrToLong_ui(c, NULL, 10, >weight) < 0) {
+virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
+   _("could n

[FYI PATCH 5/5] util: open code virXMLNodeContentString to access the node object directly

2020-07-20 Thread Laine Stump
(I am *NOT* advocating that we apply this patch. Just providing it for
informational purposes, since we had previously discussed this
possibility on the list)

Since it's impossible to determine whether xmlNodeContent has returned
a NULL due to OOM, or due to badly formed / evil XML, this patch open
codes virXMLNodeContentString to get the content string directly from
the node.

This turns out to not be so easy as it seemed at first glance when it
was suggested - the "content" member of the element node itself does
not contain the content string for the node. The content string that
we want can be found (at least for our uses of libxml) by looking for
a child node of the element node - if that child node is of type
XML_TEXT_NODE, then the content member of *that* node is the string
we're looking for. If there is no child node, then the element has no
content, so we return "". Likewise, if the child node is type
XML_TEXT_NODE but has no content, we also return "". In all other
cases, we log an error and return because this is some case that
hasn't been encountered in our test cases, so either someone is
sending bad XML, or our assumptions about the layout of the XML node
object list are incorrect.

Note that while calling virXMLNodeContentString() would return NULL
from an OOM situation, this new code will exit the process on OOM
(since it is calling glib for memory allocation).

Signed-off-by: Laine Stump 
---
 src/util/virxml.c | 43 ++-
 1 file changed, 38 insertions(+), 5 deletions(-)

diff --git a/src/util/virxml.c b/src/util/virxml.c
index 5315d4ff6f..b2298d74c8 100644
--- a/src/util/virxml.c
+++ b/src/util/virxml.c
@@ -538,7 +538,17 @@ virXMLPropStringLimit(xmlNodePtr node,
 char *
 virXMLNodeContentString(xmlNodePtr node)
 {
-char *ret = (char *)xmlNodeGetContent(node);
+/* We specifically avoid using virXMLNodeContentString() here, because
+ * when NULL is returned, it is difficult/impossible to
+ * distinguish between 1) OOM, 2) NULL content, 3) some other error.
+ */
+
+/* for elements used the way libvirt uses them, the xmlNode object
+ * for an element will have a type of XML_ELEMENT_NODE, and if the
+ * node has any content, it will be in the content field of a
+ * child node of that object which is itself of type
+ * XML_TEXT_NODE.
+ */
 
 if (node->type !=  XML_ELEMENT_NODE) {
 virReportError(VIR_ERR_INTERNAL_ERROR,
@@ -547,15 +557,38 @@ virXMLNodeContentString(xmlNodePtr node)
 return NULL;
 }
 
-if (!ret) {
+/* no children --> empty element node */
+if (!node->children)
+return g_strdup("");
+
+/* if the child isn't text, or there is more than a single node
+ * hanging off "children", our assumptions have been wrong
+ */
+if (node->children->type != XML_TEXT_NODE) {
+virReportError(VIR_ERR_INTERNAL_ERROR,
+   _("child of element node '%s' has unexpected name '%s', 
type %d"),
+   node->name, node->children->name, node->children->type);
+return NULL;
+}
+if (node->children->next) {
 virReportError(VIR_ERR_INTERNAL_ERROR,
-   _("node '%s' has unexpected NULL content. This could be 
caused by malformed input, or a memory allocation failure"),
+   _("child of element node '%s' is type XML_TEXT_NODE, 
but is a list"),
+   node->name);
+return NULL;
+}
+if (node->children->children) {
+virReportError(VIR_ERR_INTERNAL_ERROR,
+   _("child of element node '%s' is type XML_TEXT_NODE, 
but has children"),
node->name);
 return NULL;
 }
 
-return ret;
-}
+/* if content is NULL, return "" instead */
+if (!node->children->content)
+return g_strdup("");
+
+return g_strdup((char *)node->children->content);
+ }
 
 
 /**
-- 
2.25.4



[PATCH 2/5] util: replace all calls to xmlNodeGetContent with virXMLNodeContentString

2020-07-20 Thread Laine Stump
No functional change

Signed-off-by: Laine Stump 
---
 src/conf/domain_conf.c  | 20 ++--
 src/conf/network_conf.c |  2 +-
 src/conf/node_device_conf.c |  4 ++--
 3 files changed, 13 insertions(+), 13 deletions(-)

diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index ade8c13914..cb69c97a8e 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -1643,7 +1643,7 @@ virDomainBlkioDeviceParseXML(xmlNodePtr root,
 if (node->type != XML_ELEMENT_NODE)
 continue;
 
-c = (char *)xmlNodeGetContent(node);
+c = virXMLNodeContentString(node);
 
 if (virXMLNodeNameEqual(node, "path")) {
 /* To avoid the need for explicit cleanup on failure,
@@ -9373,10 +9373,10 @@ virDomainLeaseDefParseXML(xmlNodePtr node)
 while (cur != NULL) {
 if (cur->type == XML_ELEMENT_NODE) {
 if (!key && virXMLNodeNameEqual(cur, "key")) {
-key = (char *)xmlNodeGetContent(cur);
+key = virXMLNodeContentString(cur);
 } else if (!lockspace &&
virXMLNodeNameEqual(cur, "lockspace")) {
-lockspace = (char *)xmlNodeGetContent(cur);
+lockspace = virXMLNodeContentString(cur);
 } else if (!path &&
virXMLNodeNameEqual(cur, "target")) {
 path = virXMLPropString(cur, "path");
@@ -10595,16 +10595,16 @@ virDomainDiskDefParseXML(virDomainXMLOptionPtr xmlopt,
 
 } else if (!serial &&
virXMLNodeNameEqual(cur, "serial")) {
-serial = (char *)xmlNodeGetContent(cur);
+serial = virXMLNodeContentString(cur);
 } else if (!wwn &&
virXMLNodeNameEqual(cur, "wwn")) {
-wwn = (char *)xmlNodeGetContent(cur);
+wwn = virXMLNodeContentString(cur);
 
 if (!virValidateWWN(wwn))
 goto error;
 } else if (!vendor &&
virXMLNodeNameEqual(cur, "vendor")) {
-vendor = (char *)xmlNodeGetContent(cur);
+vendor = virXMLNodeContentString(cur);
 
 if (strlen(vendor) > VENDOR_LEN) {
 virReportError(VIR_ERR_XML_ERROR, "%s",
@@ -10619,7 +10619,7 @@ virDomainDiskDefParseXML(virDomainXMLOptionPtr xmlopt,
 }
 } else if (!product &&
virXMLNodeNameEqual(cur, "product")) {
-product = (char *)xmlNodeGetContent(cur);
+product = virXMLNodeContentString(cur);
 
 if (strlen(product) > PRODUCT_LEN) {
 virReportError(VIR_ERR_XML_ERROR, "%s",
@@ -13513,7 +13513,7 @@ virDomainSmartcardDefParseXML(virDomainXMLOptionPtr 
xmlopt,
  "exactly three certificates"));
 goto error;
 }
-def->data.cert.file[i] = (char *)xmlNodeGetContent(cur);
+def->data.cert.file[i] = virXMLNodeContentString(cur);
 if (!def->data.cert.file[i]) {
 virReportOOMError();
 goto error;
@@ -13522,7 +13522,7 @@ virDomainSmartcardDefParseXML(virDomainXMLOptionPtr 
xmlopt,
 } else if (cur->type == XML_ELEMENT_NODE &&
virXMLNodeNameEqual(cur, "database") &&
!def->data.cert.database) {
-def->data.cert.database = (char *)xmlNodeGetContent(cur);
+def->data.cert.database = virXMLNodeContentString(cur);
 if (!def->data.cert.database) {
 virReportOOMError();
 goto error;
@@ -19875,7 +19875,7 @@ virDomainLoaderDefParseXML(xmlNodePtr node,
 if (!fwAutoSelect) {
 readonly_str = virXMLPropString(node, "readonly");
 type_str = virXMLPropString(node, "type");
-loader->path = (char *) xmlNodeGetContent(node);
+loader->path = virXMLNodeContentString(node);
 if (STREQ_NULLABLE(loader->path, ""))
 VIR_FREE(loader->path);
 }
diff --git a/src/conf/network_conf.c b/src/conf/network_conf.c
index 0fd68a7d66..0a32f57188 100644
--- a/src/conf/network_conf.c
+++ b/src/conf/network_conf.c
@@ -720,7 +720,7 @@ virNetworkDNSHostDefParseXML(const char *networkName,
 if (cur->type == XML_ELEMENT_NODE &&
 virXMLNodeNameEqual(cur, "hostname")) {
   if (cur->children != NULL) {
-  g_autofree char *name = (char *) xmlNodeGetContent(cur);
+  g_autofree char *name = virXMLNodeContentString(cur);
 
   if (!name) {
   virReportError(VIR_ERR_XM

[PATCH 0/5] be consistent about error checking xmlNodeGetContent() return

2020-07-20 Thread Laine Stump
Awhile back I noticed that calls to xmlNodeGetContent() from libvirt
code were inconsistent in their handling of the returned
pointer. Sometimes we would assume the return was always non-NULL
(dereferencing with wild abandon without concern for the
consequences), sometimes we would interpret NULL as "", and sometimes
as OOM. I sent mail about this to the list last week, wondering (and
doubting) if we could assume that a NULL return would always mean OOM:

https://www.redhat.com/archives/libvir-list/2020-July/msg00333.html

After looking at the libxml code, danpb's determination was that a
NULL return from xmlNodeGetContent *might* mean OOM, but it might also
mean some odd XML that we weren't expecting, so we can't just always
exit on a NULL return. He also agreed with (and expanded on) my
suspicion that there really is no reliable way to tell the reason for
a NULL return from xmlNodeGetContent, and suggested that possibly we
could just examing the xmlNode directly to learn the content instead
of calling xmlNodeGetContent().

This series is a followup to that discussion. The first 4 patches
clean up the code with the result that:

1) a libvirt wrapper function is always called instead of calling
xmlNodeGetContent() directly.

2) that wrapper function logs an error when it gets back NULL from
xmlNodeGetContent().

3) All the callers check for a NULL return, and do a "silent error
return" themselves when there is a NULL.

In the final patch, I try out Dan's idea of looking at the xmlNode
object directly to get the content. It turns out it's not as
straightforward as you would think from just looking at the layout of
the object - a full explanation is in patch 5. I'm mainly sending that
patch as an "FYI" (one step back from an "RFC"), since really all it
changes is that libvirt will exit on OOM, and log (different, but not
any more informative) error messages when the problem isn't
OOM. Unless someone has a strong opinion otherwise, I think just the
first 4 patches should be applied, and users can just "deal" with the
ambiguity in case of error.


Laine Stump (5):
  conf: refactor virDomainBlkioDeviceParseXML to reduce calls to
xmlNodeGetContent
  util: replace all calls to xmlNodeGetContent with
virXMLNodeContentString
  util: log an error if virXMLNodeContentString will return NULL
  treat all NULL returns from virXMLNodeContentString() as an error
  util: open code virXMLNodeContentString to access the node object
directly

 src/conf/domain_conf.c  | 194 
 src/conf/network_conf.c |   7 +-
 src/conf/node_device_conf.c |   6 +-
 src/util/virxml.c   |  53 +-
 4 files changed, 169 insertions(+), 91 deletions(-)

-- 
2.25.4



[PATCH 4/5] treat all NULL returns from virXMLNodeContentString() as an error

2020-07-20 Thread Laine Stump
and stop erroneously equating NULL with "". The latter means that the
element has empty content, while the former means there was an error
during parsing (either internal with the parser, or the content of the
XML was bad).

Signed-off-by: Laine Stump 
---
 src/conf/domain_conf.c  | 68 ++---
 src/conf/network_conf.c |  5 ++-
 src/conf/node_device_conf.c |  6 ++--
 3 files changed, 48 insertions(+), 31 deletions(-)

diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index cb69c97a8e..c377fd74aa 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -1643,7 +1643,8 @@ virDomainBlkioDeviceParseXML(xmlNodePtr root,
 if (node->type != XML_ELEMENT_NODE)
 continue;
 
-c = virXMLNodeContentString(node);
+if (!(c = virXMLNodeContentString(node)))
+return -1;
 
 if (virXMLNodeNameEqual(node, "path")) {
 /* To avoid the need for explicit cleanup on failure,
@@ -9373,10 +9374,12 @@ virDomainLeaseDefParseXML(xmlNodePtr node)
 while (cur != NULL) {
 if (cur->type == XML_ELEMENT_NODE) {
 if (!key && virXMLNodeNameEqual(cur, "key")) {
-key = virXMLNodeContentString(cur);
+if (!(key = virXMLNodeContentString(cur)))
+goto error;
 } else if (!lockspace &&
virXMLNodeNameEqual(cur, "lockspace")) {
-lockspace = virXMLNodeContentString(cur);
+if (!(lockspace = virXMLNodeContentString(cur)))
+goto error;
 } else if (!path &&
virXMLNodeNameEqual(cur, "target")) {
 path = virXMLPropString(cur, "path");
@@ -10595,16 +10598,19 @@ virDomainDiskDefParseXML(virDomainXMLOptionPtr xmlopt,
 
 } else if (!serial &&
virXMLNodeNameEqual(cur, "serial")) {
-serial = virXMLNodeContentString(cur);
+if (!(serial = virXMLNodeContentString(cur)))
+goto error;
 } else if (!wwn &&
virXMLNodeNameEqual(cur, "wwn")) {
-wwn = virXMLNodeContentString(cur);
+if (!(wwn = virXMLNodeContentString(cur)))
+goto error;
 
 if (!virValidateWWN(wwn))
 goto error;
 } else if (!vendor &&
virXMLNodeNameEqual(cur, "vendor")) {
-vendor = virXMLNodeContentString(cur);
+if (!(vendor = virXMLNodeContentString(cur)))
+goto error;
 
 if (strlen(vendor) > VENDOR_LEN) {
 virReportError(VIR_ERR_XML_ERROR, "%s",
@@ -10619,7 +10625,8 @@ virDomainDiskDefParseXML(virDomainXMLOptionPtr xmlopt,
 }
 } else if (!product &&
virXMLNodeNameEqual(cur, "product")) {
-product = virXMLNodeContentString(cur);
+if (!(product = virXMLNodeContentString(cur)))
+goto error;
 
 if (strlen(product) > PRODUCT_LEN) {
 virReportError(VIR_ERR_XML_ERROR, "%s",
@@ -13513,20 +13520,16 @@ virDomainSmartcardDefParseXML(virDomainXMLOptionPtr 
xmlopt,
  "exactly three certificates"));
 goto error;
 }
-def->data.cert.file[i] = virXMLNodeContentString(cur);
-if (!def->data.cert.file[i]) {
-virReportOOMError();
+if (!(def->data.cert.file[i] = virXMLNodeContentString(cur)))
 goto error;
-}
+
 i++;
 } else if (cur->type == XML_ELEMENT_NODE &&
virXMLNodeNameEqual(cur, "database") &&
!def->data.cert.database) {
-def->data.cert.database = virXMLNodeContentString(cur);
-if (!def->data.cert.database) {
-virReportOOMError();
+if (!(def->data.cert.database = virXMLNodeContentString(cur)))
 goto error;
-}
+
 if (*def->data.cert.database != '/') {
 virReportError(VIR_ERR_XML_ERROR,
_("expecting absolute path: %s"),
@@ -15638,8 +15641,10 @@ virSysinfoOEMStringsParseXML(xmlNodePtr node,
 goto cleanup;
 
 def->nvalues = nstrings;
-for (i = 0; i < nstrings; i++)
-def->values[i] = virXMLNodeContentString(strings[i]);
+for (i = 0; i < nstrings; i++) {
+if (!(def->values[i] = virXMLNodeContentString(strings[i])))
+goto cleanup;
+}
 
 *oem = g_steal_pointer();
 ret = 0;
@@ -1576

Re: [libvirt PATCH v2 08/15] nwfilter: remove unnecessary code from ebtablesGetSubChainInsts()

2020-07-17 Thread Laine Stump

On 7/15/20 11:30 AM, Ján Tomko wrote:

On a Tuesday in 2020, Laine Stump wrote:

On failure, this function would clear out and free the list of
subchains it had been called with. This is unnecessary, because the
*only* caller of this function will also clear out and free the list
of subchains if it gets a failure from ebtablesGetSubChainInsts().

(It also makes more logical sense for the function that is creating
the entire list to be the one freeing the entire list, rather than
having a function whose purpose is only to create *one item* on the
list freeing the entire list).


This is the function creating the list,



I disagree with that characterization. The list is created, with 0 
elements, when the caller (ebiptablesApplyNewRules()) defines it. Then 
each time ebtablesGetSubChainInsts() is called, it doesn't create the 
list anew, it just adds to whatever is already on the existing list - as 
a matter of fact it is called multiple times and each time it adds more 
items to the list without re=initializing it.



This is very much like what happens with a virBuffer - some function 
creates a virBuffer by defining it and initializing it to empty, then 
each time a virBuffer function is called, it adds more text to the 
buffer. But if there is an error in a virBuffer function, it doesn't 
clear out the buffer before returning, it just returns an error leaving 
the buffer in whatever state it was in when the error occurred; it is 
then up to the caller, who is the owner of the virBuffer, to clear it out.




I think it makes sense
to not leave anything allocated in case of failure.



Aside from making the code simpler and cleaner, I think it doesn't make 
sense for one invocation of the function to clear out anything that was 
put into the list by *a different* invocation of the function. If you're 
going to be a purist about it, then a failed ebtablesGetSubChainInsts() 
should remove from the list *only those items that were added during the 
current call* and nothing else.



But that's just pedantic nitpicking (Hey, *you* started the nitpicking 
though :-P)



(Also, there is only one caller of ebtablesGetSubChainInsts(), and 
whenever ebtablesGetSubChainInsts() fails, the *very next thing* that 
caller does is to clear out the entire list. So in fact, "nothing is 
left allocated in case of failure".)





Jano



Signed-off-by: Laine Stump 



My S-o-b stands. I still think this is the right thing to do.




---
src/nwfilter/nwfilter_ebiptables_driver.c | 6 --
1 file changed, 6 deletions(-)





[PATCH] network: refactor networkSetIPv6Sysctls() for proper g_autofree usage

2020-07-17 Thread Laine Stump
This function used the same char* three times for different purposes,
freeing it after each use. Since we don't want to ever manually free
an autofree'd pointer, modify it to use three separate char*, and make
them all g_autofree.

Signed-off-by: Laine Stump 
---
This was suggested by Jan in

  https://www.redhat.com/archives/libvir-list/2020-July/msg00805.html

pushing this patch along with the patch 5 referenced there will permit
pushing patch 06/15 of that series unmodified.

 src/network/bridge_driver.c | 32 
 1 file changed, 16 insertions(+), 16 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index dd8f34e543..6d341dba7c 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -2248,7 +2248,9 @@ static int
 networkSetIPv6Sysctls(virNetworkObjPtr obj)
 {
 virNetworkDefPtr def = virNetworkObjGetDef(obj);
-char *field = NULL;
+g_autofree char *disable_ipv6 = NULL;
+g_autofree char *accept_ra = NULL;
+g_autofree char *autoconf = NULL;
 int ret = -1;
 bool enableIPv6 = !!virNetworkDefGetIPByIndex(def, AF_INET6, 0);
 
@@ -2256,10 +2258,10 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
  * network. But also unset it if there *are* ipv6 addresses, as we
  * can't be sure of its default value.
  */
-field = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/disable_ipv6",
-def->bridge);
+disable_ipv6 = g_strdup_printf(SYSCTL_PATH 
"/net/ipv6/conf/%s/disable_ipv6",
+   def->bridge);
 
-if (access(field, W_OK) < 0 && errno == ENOENT) {
+if (access(disable_ipv6, W_OK) < 0 && errno == ENOENT) {
 if (!enableIPv6)
 VIR_DEBUG("ipv6 appears to already be disabled on %s",
   def->bridge);
@@ -2267,13 +2269,12 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
 goto cleanup;
 }
 
-if (virFileWriteStr(field, enableIPv6 ? "0" : "1", 0) < 0) {
+if (virFileWriteStr(disable_ipv6, enableIPv6 ? "0" : "1", 0) < 0) {
 virReportSystemError(errno,
  _("cannot write to %s to enable/disable IPv6 "
-   "on bridge %s"), field, def->bridge);
+   "on bridge %s"), disable_ipv6, def->bridge);
 goto cleanup;
 }
-VIR_FREE(field);
 
 /* The rest of the ipv6 sysctl tunables should always be set the
  * same, whether or not we're using ipv6 on this bridge.
@@ -2282,30 +2283,29 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
 /* Prevent guests from hijacking the host network by sending out
  * their own router advertisements.
  */
-field = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/accept_ra",
-def->bridge);
+accept_ra = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/accept_ra",
+def->bridge);
 
-if (virFileWriteStr(field, "0", 0) < 0) {
+if (virFileWriteStr(accept_ra, "0", 0) < 0) {
 virReportSystemError(errno,
- _("cannot disable %s"), field);
+ _("cannot disable %s"), accept_ra);
 goto cleanup;
 }
-VIR_FREE(field);
 
 /* All interfaces used as a gateway (which is what this is, by
  * definition), must always have autoconf=0.
  */
-field = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/autoconf", 
def->bridge);
+autoconf = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/autoconf",
+   def->bridge);
 
-if (virFileWriteStr(field, "0", 0) < 0) {
+if (virFileWriteStr(autoconf, "0", 0) < 0) {
 virReportSystemError(errno,
- _("cannot disable %s"), field);
+ _("cannot disable %s"), autoconf);
 goto cleanup;
 }
 
 ret = 0;
  cleanup:
-VIR_FREE(field);
 return ret;
 }
 
-- 
2.25.4



Re: [libvirt PATCH v2 05/15] network: use g_auto wherever appropriate

2020-07-15 Thread Laine Stump

On 7/15/20 11:10 AM, Ján Tomko wrote:

On a Tuesday in 2020, Laine Stump wrote:

This includes standard g_autofree() as well as other objects that have
a cleanup function defined to use via g_autoptr (virCommand,
virJSONValue)

Signed-off-by: Laine Stump 
---
src/network/bridge_driver.c   | 206 ++
src/network/bridge_driver_linux.c |   7 +-
src/network/leaseshelper.c    |  16 +--
3 files changed, 76 insertions(+), 153 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index ab359acdb5..31bd0dd92c 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c


[...]


@@ -1095,7 +1081,6 @@ networkDnsmasqConfContents(virNetworkObjPtr obj,
    bool wantDNS = dns->enable != VIR_TRISTATE_BOOL_NO;
    virNetworkIPDefPtr tmpipdef, ipdef, ipv4def, ipv6def;
    bool ipv6SLAAC;
-    char *saddr = NULL, *eaddr = NULL;

    *configstr = NULL;



[...]


@@ -1414,6 +1396,8 @@ networkDnsmasqConfContents(virNetworkObjPtr obj,
    int thisRange;
    virNetworkDHCPRangeDef range = ipdef->ranges[r];
    g_autofree char *leasetime = NULL;
+    g_autofree char *saddr = NULL;
+    g_autofree char *eaddr = NULL;


300 lines below the original location. Long function is long. :)



At least there were no unrelated changes in be... oh, wait. Nevermind.


A long time ago (1988) in a galaxy far far away (Lake City, Minnesota) I 
worked with a guy who told me that any function that wouldn't fit on a 
single screen was too long and needed to be broken up (this was in the 
80x25 ASCII terminal days). He would probably rip out his moustache and 
scream if he saw some of the functions in libvirt.







    if (!(saddr = virSocketAddrFormat()) ||
    !(eaddr = virSocketAddrFormat()))


[...]


@@ -2248,7 +2206,7 @@ static int
networkSetIPv6Sysctls(virNetworkObjPtr obj)
{
    virNetworkDefPtr def = virNetworkObjGetDef(obj);
-    char *field = NULL;
+    g_autofree char *field = NULL;


Last time I tried manually freeing an autofree'd variable, I was told
not to do that O:-)



Yeah, there's a few places where we re-use a pointer for "temporary" 
strings. In a different patch I sent a few weeks ago, I fixed it by just 
declaring multiple separate autofree variables, one for each usage, and 
I think that is the least future-bug-prone method of dealing with it.



(I hadn't seen anyone scolding about not manually freeing and autofree'd 
variable, but since doing so made me uneasy anyway, I'm happy to jump on 
the bandwagon :-)





The clean way here seems to be refactoring the function. I can put that
somewhere into the depths of my TODO list.



If you really want to, you can. Otherwise I can send a patch for that to 
be pushed along with this series, just so that I won't have the icky 
feeling of leaving a job not quite done.






    int ret = -1;
    bool enableIPv6 = !!virNetworkDefGetIPByIndex(def, AF_INET6, 0);

@@ -2273,7 +2231,6 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
   "on bridge %s"), field, def->bridge);
    goto cleanup;
    }
-    VIR_FREE(field);

    /* The rest of the ipv6 sysctl tunables should always be set the
 * same, whether or not we're using ipv6 on this bridge.
@@ -2282,6 +2239,7 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
    /* Prevent guests from hijacking the host network by sending out
 * their own router advertisements.
 */
+    VIR_FREE(field);
    field = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/accept_ra",
    def->bridge);

@@ -2290,11 +2248,11 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
 _("cannot disable %s"), field);
    goto cleanup;
    }
-    VIR_FREE(field);

    /* All interfaces used as a gateway (which is what this is, by
 * definition), must always have autoconf=0.
 */
+    VIR_FREE(field);
    field = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/autoconf", 
def->bridge);


    if (virFileWriteStr(field, "0", 0) < 0) {
@@ -2305,7 +2263,6 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)

    ret = 0;
 cleanup:
-    VIR_FREE(field);
    return ret;
}



[...]

@@ -3276,8 +3221,6 @@ 
networkFindUnusedBridgeName(virNetworkObjListPtr nets,

   MAX_BRIDGE_ID);
    ret = 0;


So this function returned 0 even on failure.
Introduced by a28d3e485f01d16320af15780bc935f54782a45d


 cleanup:
-    if (ret < 0)
-    VIR_FREE(newname);
    return ret;
}



Without the networkSetIPv6Sysctls changes:
Reviewed-by: Ján Tomko 

Jano





Re: [libvirt PATCH v2 00/15] convert network and nwfilter directories to glib memory allocation.

2020-07-14 Thread Laine Stump

ping

On 7/7/20 5:08 PM, Laine Stump wrote:

V1 was here:

https://www.redhat.com/archives/libvir-list/2020-June/msg01156.html

Some patches were ACKed and pushed. I re-ordered/re-organized most of
the rest, and removed some others to deal with separately (the
xmlNodeContent stuff)

What's left here is a few preliminary patches, then the standard set,
once for network and again for nwfilter:

1) convert from VIR_(RE)ALLOC(_N) to g_new0()/g_renew()
2) use g_auto*() where appropriate, removing unneeded free's
3) get rid of now-extraneous labels
4) (controversial) replace any remaining VIR_FREE() with g_free() (and
possibly g_clear_pointer() when needed

NB: these patches require my virBuffer "convert to g_auto" series
as a prerequisite:

   https://www.redhat.com/archives/libvir-list/2020-July/msg00185.html



^^ This has been pushed, so there are no longer any extra prerequisites.




Changes from V1:

   * move conversion of virFirewall and virBuffer automatics to another
 series (see above)
   
   * re-order to replace VIR_ALLOC first (without adding any g_auto*)

 instead of doing it after g_auto conversion of automatics, then do
 all g_auto additions at o

   * separate label elimination into separate patches per jtomko's
 suggestion.


Laine Stump (15):
   replace g_new() with g_new0() for consistency
   util: define g_autoptr cleanups for a couple dnsmasq objects
   define g_autoptr cleanup function for virNetworkDHCPLease
   network: replace VIR_ALLOC/REALLOC with g_new0/g_renew
   network: use g_auto wherever appropriate
   network: eliminate unnecessary labels
   network: use g_free() in place of remaining VIR_FREE()
   nwfilter: remove unnecessary code from ebtablesGetSubChainInsts()
   nwfilter: clear nrules when resetting virNWFilterInst
   nwfilter: define a typedef for struct ebtablesSubChainInst
   nwfilter: transform logic in virNWFilterRuleInstSort to eliminate
 label
   nwfilter: use standard label names when reasonable
   nwfilter: replace VIR_ALLOC with g_new0
   nwfilter: convert local pointers to use g_auto*
   nwfilter: convert remaining VIR_FREE() to g_free()

  src/datatypes.h   |   2 +
  src/network/bridge_driver.c   | 536 --
  src/network/bridge_driver_linux.c |  22 +-
  src/network/leaseshelper.c|  16 +-
  src/nwfilter/nwfilter_dhcpsnoop.c | 150 +++---
  src/nwfilter/nwfilter_driver.c|  13 +-
  src/nwfilter/nwfilter_ebiptables_driver.c | 119 ++---
  src/nwfilter/nwfilter_gentech_driver.c|  57 ++-
  src/nwfilter/nwfilter_learnipaddr.c   |  43 +-
  src/qemu/qemu_backup.c|   2 +-
  src/util/virdnsmasq.h |   4 +
  src/util/virutil.c|   2 +-
  tests/qemuhotplugmock.c   |   2 +-
  13 files changed, 379 insertions(+), 589 deletions(-)





[PATCH] docs: point out that locals should be defined at the top of a block of code

2020-07-09 Thread Laine Stump
Although we have nothing in make syntax-check to enforce this, and
apparently there are places where it isn't the case (according to
Dan), we should discourage the practice of defining new variables in
the middle of a block of code.

https://www.redhat.com/archives/libvir-list/2020-July/msg00433.html
Signed-off-by: Laine Stump 
---
 docs/coding-style.rst | 38 ++
 1 file changed, 38 insertions(+)

diff --git a/docs/coding-style.rst b/docs/coding-style.rst
index 03b89c86e5..b9b4a16987 100644
--- a/docs/coding-style.rst
+++ b/docs/coding-style.rst
@@ -541,6 +541,44 @@ diligent about this, when you see a non-const pointer, 
you're
 guaranteed that it is used to modify the storage it points to, or
 it is aliased to another pointer that is.
 
+Defining Local Variables
+
+
+Always define local variables at the top of the block in which they
+are used (before any pure code). Although modern C compilers allow
+defining a local variable in the middle of a block of code, this
+practice can lead to bugs, and must be avoided in all libvirt
+code. (As indicated in these examples, it is okay to initialize
+variables where they are defined, even if the initialization involves
+calling another function.)
+
+::
+
+  GOOD:
+int
+Bob(char *loblaw)
+{
+int x;
+int y = lawBlog(loblaw);
+char *z = NULL;
+
+x = y + 20;
+...
+}
+
+  BAD:
+int
+Bob(char *loblaw)
+{
+int x;
+int y = lawBlog(loblaw);
+
+x = y + 20;
+
+char *z = NULL; <===
+...
+}
+
 Attribute annotations
 -
 
-- 
2.25.4



Re: [libvirt PATCH] All pointers to virXMLPropString() use g_autofree.

2020-07-08 Thread Laine Stump

On 7/8/20 4:19 PM, Nicolas Brignone wrote:

  All pointers to virXMLPropString() use g_autofree.



I changed the summary line like this, to be more precise:


conf: use g_autofree for all pointers to virXMLPropString() in device_conf.c



All modified functions are similar, in all cases "cleanup" label is removed,
along with all the "goto" calls.



I've been advised in the recent past to put the g_autofree additions and 
corresponding removals of free functions into one patch, then do the 
removal of the extra labels (in favor of directly returning) in a 
separate patch to make it easier to hand-verify / review. Here's a 
couple recent examples:



https://www.redhat.com/archives/libvir-list/2020-July/msg00317.html


In your case the changes are few enough that I'm okay with it a single 
patch, except...





Signed-off-by: Nicolas Brignone 
---
  src/conf/device_conf.c | 183 +
  1 file changed, 56 insertions(+), 127 deletions(-)

diff --git a/src/conf/device_conf.c b/src/conf/device_conf.c
index 7d48a3f..9fa6141 100644
--- a/src/conf/device_conf.c
+++ b/src/conf/device_conf.c
@@ -208,45 +208,43 @@ int
  virPCIDeviceAddressParseXML(xmlNodePtr node,
  virPCIDeviceAddressPtr addr)
  {
-char *domain, *slot, *bus, *function, *multi;
  xmlNodePtr cur;
  xmlNodePtr zpci = NULL;
-int ret = -1;
  
  memset(addr, 0, sizeof(*addr));
  
-domain   = virXMLPropString(node, "domain");

-bus  = virXMLPropString(node, "bus");
-slot = virXMLPropString(node, "slot");
-function = virXMLPropString(node, "function");
-multi= virXMLPropString(node, "multifunction");
+g_autofree char *domain   = virXMLPropString(node, "domain");
+g_autofree char *bus  = virXMLPropString(node, "bus");
+g_autofree char *slot = virXMLPropString(node, "slot");
+g_autofree char *function = virXMLPropString(node, "function");
+g_autofree char *multi= virXMLPropString(node, "multifunction");



... you've modified it so that local variables are being declared 
*below* a line of executable code rather than at the top of the block. 
Although I don't see anything in the coding style document 
(https://libvirt.org/coding-style.html) about it, and it may just be 
leftover from a time when we supported a compiler that required all 
declarations to be at top of scope, I think pretty much all of libvirts 
code declares all local variables at the top of the scope.


That's simple enough for me to just fixup before pushing, so


Reviewed-by: Laine Stump 


Congratulations on your first libvirt patch! :-)

  
  if (domain &&

  virStrToLong_uip(domain, NULL, 0, >domain) < 0) {
  virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
 _("Cannot parse  'domain' attribute"));
-goto cleanup;
+return -1;
  }
  
  if (bus &&

  virStrToLong_uip(bus, NULL, 0, >bus) < 0) {
  virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
 _("Cannot parse  'bus' attribute"));
-goto cleanup;
+return -1;
  }
  
  if (slot &&

  virStrToLong_uip(slot, NULL, 0, >slot) < 0) {
  virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
 _("Cannot parse  'slot' attribute"));
-goto cleanup;
+return -1;
  }
  
  if (function &&

  virStrToLong_uip(function, NULL, 0, >function) < 0) {
  virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
 _("Cannot parse  'function' attribute"));
-goto cleanup;
+return -1;
  }
  
  if (multi &&

@@ -254,11 +252,11 @@ virPCIDeviceAddressParseXML(xmlNodePtr node,
  virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
 _("Unknown value '%s' for  'multifunction' 
attribute"),
 multi);
-goto cleanup;
+return -1;
  
  }

  if (!virPCIDeviceAddressIsEmpty(addr) && 
!virPCIDeviceAddressIsValid(addr, true))
-goto cleanup;
+return -1;
  
  cur = node->children;

  while (cur) {
@@ -270,17 +268,9 @@ virPCIDeviceAddressParseXML(xmlNodePtr node,
  }
  
  if (zpci && virZPCIDeviceAddressParseXML(zpci, addr) < 0)

-goto cleanup;
+return -1;
  
-ret = 0;

-
- cleanup:
-VIR_FREE(domain);
-VIR_FREE(bus);
-VIR_FREE(slot);
-VIR_FREE(function);
-VIR_FREE(multi);
-return ret;
+return 0;
  }
  
  void

@@ -309,187 +299,149 @@ int
  virDomainDeviceCCWAddressParseXML(xmlNodePtr node,
virDomainDeviceCCWAddressPtr addr)
  {
-int   ret = 

Re: How to best handle NULL return from xmlNodeGetContent()

2020-07-08 Thread Laine Stump

On 7/8/20 4:35 AM, Daniel P. Berrangé wrote:

On Tue, Jul 07, 2020 at 06:48:57PM -0400, Laine Stump wrote:

libvirt has several uses of xmlNodeGetContent() (from libxml2) added at
different times over the years. Some of those uses report an Out of Memory
error when xmlNodeGetContent() returns NULL, and some of them ignore a NULL
return (treating it as if it were ""), and some just assume that the return
will never be NULL, but always at least a pointer to "".

I ran across this when I noticed a usage of the latter type - it wasn't
checking for NULL at all. A lack of check seemed troubling, so I looked at
other uses within libvirt and found the hodge-podge described above, so no
help there in determining the right thing to do. I then looked at the
libxml2 documentation for xmlNodeGetContent(), which says:

   Returns: a new #xmlChar * or NULL if no content is available.

To an uninformed outsider, this sounds like the function could return NULL
simply if the node was empty (e.g. ""). But when we look at the return
from xmlNodeGetContent() for this example, it says that the content is "",
not NULL.

In the meantime, since libxml doesn't abort on OOM errors (as libvirt does),
it could also be possible that it's returning NULL due to OOM. So using
anecdotal evidence acquired so far, one *could* surmise that any time
libvirt gets a NULL return from xmlNodeGetContent(), it is indeed an OOM
error.

Looking at the source for xmlNodeGetContent() that is definitely not
the case.


The purist in me thinks that isn't right, though - I took a quick look at
the libxml code and saw cases where  it returns NULL that don't seem related
to OOM, but rather to the type of node or something. But being an outsider
and not wanting to learn any more than necessary about the internals of
libxml, I'm not sure if any of those cases even apply to libvirt's simple
use of xmlNodeGetContent().

I think we have to expect that the node type will not match what we
want it to be, when faced with malicious XML user input.


So, in the end I just want to modify libvirt's dozen or so calls to
xmlNodeGetContent() to consistently do the right thing, but first I want to
learn the true answers to these questions:

1) Keeping in mind that we've already successfully parsed the XML, will
calls to xmlNodeGetContent() in the simple cases as when libvirt calls it
only return NULL for OOM, but not for any other reason?

No, there's other reasons it will return NULL that could hit us.



Okay, I kind of figured that was the case, and asked the question as a 
strawman.




2) If not, is the proper way to distinguish OOM in this case to call
xmlGetLasterror(), and check if the domain is XML_FROM_MEMORY?

There are a bunch of cases in xmlNodeGetContent() which return NULL
without ever bothering to update the last error indicator.



Sigh. Okay.



  Also
xmlGetLastError is not using a thread local, so it is completely
unsafe to use it in any modern app that has threads :-(



Well, the documentation says this:


  "Get the last global error registered. This is

   per thread if compiled with thread support."


and I certainly *hope* that libxml2 is being compiled everywhere with 
support for multiple threads (if it's not, then we could very well have 
bigger problems than just improper error handling). But that's a moot 
point if it's not being set anyway :-/






3) Aside from returning NULL in the case of errors, would it ever be
possible for correct XML to return NULL as valid "node content", or is it
always an error of some kind?

It does look like it only happens in error, but many of the users
look like that can be triggered from user chosen input, so we must
not abort.



Right. The only case where I would think of aborting is OOM. In any 
other case we have to log some sort of message to let the user know how 
to avoid the same problem next time.




Since libvirt now aborts on OOM, an OOM error could be handled in one place
by a wrapper function around xmlNodeGetContent() (we already have such a
function, currently a one-liner passthrough, and not called by everyone).
But if there is any chance that any other libxml error could be encountered,
then I suppose we really should be reporting those without aborting, and
then still checking for NULL on return from the wrapper function (presumably
by just logging the contents of "message" from the xmlErrorPtr returned from
xmlGetLastError().

xmlNodeGetContent() looks unusably broken to me in terms of error handling.

I notice however that the xmlNodePtr struct contents is actually fully
public in the API:

http://www.xmlsoft.org/html/libxml-tree.html#xmlNode

Given this, we can avoid xmlNodeGetContent entirely and just access the
node->content field directly, after first validating node->type.



Ah, right. I recall seeing at least one place in libvirt where we 
already do that. When I saw it I thought that 

How to best handle NULL return from xmlNodeGetContent()

2020-07-07 Thread Laine Stump
libvirt has several uses of xmlNodeGetContent() (from libxml2) added at 
different times over the years. Some of those uses report an Out of 
Memory error when xmlNodeGetContent() returns NULL, and some of them 
ignore a NULL return (treating it as if it were ""), and some just 
assume that the return will never be NULL, but always at least a pointer 
to "".


I ran across this when I noticed a usage of the latter type - it wasn't 
checking for NULL at all. A lack of check seemed troubling, so I looked 
at other uses within libvirt and found the hodge-podge described above, 
so no help there in determining the right thing to do. I then looked at 
the libxml2 documentation for xmlNodeGetContent(), which says:


  Returns: a new #xmlChar * or NULL if no content is available.

To an uninformed outsider, this sounds like the function could return 
NULL simply if the node was empty (e.g. ""). But when we look at 
the return from xmlNodeGetContent() for this example, it says that the 
content is "", not NULL.


In the meantime, since libxml doesn't abort on OOM errors (as libvirt 
does), it could also be possible that it's returning NULL due to OOM. So 
using anecdotal evidence acquired so far, one *could* surmise that any 
time libvirt gets a NULL return from xmlNodeGetContent(), it is indeed 
an OOM error.


The purist in me thinks that isn't right, though - I took a quick look 
at the libxml code and saw cases where  it returns NULL that don't seem 
related to OOM, but rather to the type of node or something. But being 
an outsider and not wanting to learn any more than necessary about the 
internals of libxml, I'm not sure if any of those cases even apply to 
libvirt's simple use of xmlNodeGetContent().


So, in the end I just want to modify libvirt's dozen or so calls to 
xmlNodeGetContent() to consistently do the right thing, but first I want 
to learn the true answers to these questions:


1) Keeping in mind that we've already successfully parsed the XML, will 
calls to xmlNodeGetContent() in the simple cases as when libvirt calls 
it only return NULL for OOM, but not for any other reason?


2) If not, is the proper way to distinguish OOM in this case to call 
xmlGetLasterror(), and check if the domain is XML_FROM_MEMORY?


3) Aside from returning NULL in the case of errors, would it ever be 
possible for correct XML to return NULL as valid "node content", or is 
it always an error of some kind?


Since libvirt now aborts on OOM, an OOM error could be handled in one 
place by a wrapper function around xmlNodeGetContent() (we already have 
such a function, currently a one-liner passthrough, and not called by 
everyone). But if there is any chance that any other libxml error could 
be encountered, then I suppose we really should be reporting those 
without aborting, and then still checking for NULL on return from the 
wrapper function (presumably by just logging the contents of "message" 
from the xmlErrorPtr returned from xmlGetLastError().




[libvirt PATCH v2 07/15] network: use g_free() in place of remaining VIR_FREE()

2020-07-07 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c | 45 +++--
 1 file changed, 23 insertions(+), 22 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 79b2ca3330..7d81d4dd78 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -158,7 +158,7 @@ networkDnsmasqDefNamespaceFree(void *nsdata)
 
 virStringListFreeCount(def->options, def->noptions);
 
-VIR_FREE(def);
+g_free(def);
 }
 G_DEFINE_AUTOPTR_CLEANUP_FUNC(networkDnsmasqXmlNsDef, 
networkDnsmasqDefNamespaceFree);
 
@@ -707,7 +707,7 @@ networkStateInitialize(bool privileged,
 
 network_driver->lockFD = -1;
 if (virMutexInit(_driver->lock) < 0) {
-VIR_FREE(network_driver);
+g_clear_pointer(_driver, g_free);
 goto error;
 }
 
@@ -875,18 +875,18 @@ networkStateCleanup(void)
 virPidFileRelease(network_driver->stateDir, "driver",
   network_driver->lockFD);
 
-VIR_FREE(network_driver->networkConfigDir);
-VIR_FREE(network_driver->networkAutostartDir);
-VIR_FREE(network_driver->stateDir);
-VIR_FREE(network_driver->pidDir);
-VIR_FREE(network_driver->dnsmasqStateDir);
-VIR_FREE(network_driver->radvdStateDir);
+g_free(network_driver->networkConfigDir);
+g_free(network_driver->networkAutostartDir);
+g_free(network_driver->stateDir);
+g_free(network_driver->pidDir);
+g_free(network_driver->dnsmasqStateDir);
+g_free(network_driver->radvdStateDir);
 
 virObjectUnref(network_driver->dnsmasqCaps);
 
 virMutexDestroy(_driver->lock);
 
-VIR_FREE(network_driver);
+g_clear_pointer(_driver, g_free);
 
 return 0;
 }
@@ -2194,7 +2194,7 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
 /* Prevent guests from hijacking the host network by sending out
  * their own router advertisements.
  */
-VIR_FREE(field);
+g_free(field);
 field = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/accept_ra",
 def->bridge);
 
@@ -2207,7 +2207,7 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
 /* All interfaces used as a gateway (which is what this is, by
  * definition), must always have autoconf=0.
  */
-VIR_FREE(field);
+g_free(field);
 field = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/autoconf", 
def->bridge);
 
 if (virFileWriteStr(field, "0", 0) < 0) {
@@ -2714,19 +2714,19 @@ networkCreateInterfacePool(virNetworkDefPtr netdef)
 for (i = 0; i < netdef->forward.nifs; i++) {
 if (netdef->forward.ifs[i].type
 == VIR_NETWORK_FORWARD_HOSTDEV_DEVICE_NETDEV)
-VIR_FREE(netdef->forward.ifs[i].device.dev);
+g_free(netdef->forward.ifs[i].device.dev);
 }
 netdef->forward.nifs = 0;
 }
 if (netdef->forward.nifs == 0)
-VIR_FREE(netdef->forward.ifs);
+g_clear_pointer(>forward.ifs, g_free);
 
 for (i = 0; i < numVirtFns; i++) {
-VIR_FREE(vfNames[i]);
-VIR_FREE(virtFns[i]);
+g_free(vfNames[i]);
+g_free(virtFns[i]);
 }
-VIR_FREE(vfNames);
-VIR_FREE(virtFns);
+g_free(vfNames);
+g_free(virtFns);
 return ret;
 }
 
@@ -3162,7 +3162,7 @@ networkFindUnusedBridgeName(virNetworkObjListPtr nets,
  */
 if (!(virNetworkObjBridgeInUse(nets, newname, def->name) ||
   virNetDevExists(newname) == 1)) {
-VIR_FREE(def->bridge); /*could contain template */
+g_free(def->bridge); /*could contain template */
 def->bridge = g_steal_pointer();
 return 0;
 }
@@ -4272,7 +4272,7 @@ networkGetDHCPLeases(virNetworkPtr net,
 if (leases_ret) {
 for (i = 0; i < nleases; i++)
 virNetworkDHCPLeaseFree(leases_ret[i]);
-VIR_FREE(leases_ret);
+g_free(leases_ret);
 }
 goto cleanup;
 }
@@ -4396,7 +4396,7 @@ networkAllocatePort(virNetworkObjPtr obj,
 return -1;
 }
 if (portprofile) {
-VIR_FREE(port->virtPortProfile);
+g_free(port->virtPortProfile);
 port->virtPortProfile = portprofile;
 }
 
@@ -5513,9 +5513,10 @@ networkPortSetParameters(virNetworkPortPtr port,
  * So if no average or floor is given, we free inbound/outbound
  * here which causes inbound/outbound to not be set. */
 if (!bandwidth->in->average && !bandwidth->in->floor)
-VIR_FREE(bandwidth->in);
+g_clear_pointer(>in, g_free);
+
 if (!bandwidth->out->average)
-VIR_FREE(bandwidth->out);
+g_clear_pointer(>out, g_free);
 
 if (networkUpdatePortBandwidth(obj,
>mac,
-- 
2.25.4



[libvirt PATCH v2 15/15] nwfilter: convert remaining VIR_FREE() to g_free()

2020-07-07 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_dhcpsnoop.c | 16 
 src/nwfilter/nwfilter_driver.c| 10 +-
 src/nwfilter/nwfilter_ebiptables_driver.c |  2 +-
 src/nwfilter/nwfilter_gentech_driver.c|  6 +++---
 src/nwfilter/nwfilter_learnipaddr.c   |  8 
 5 files changed, 21 insertions(+), 21 deletions(-)

diff --git a/src/nwfilter/nwfilter_dhcpsnoop.c 
b/src/nwfilter/nwfilter_dhcpsnoop.c
index 64671af135..aafa6de322 100644
--- a/src/nwfilter/nwfilter_dhcpsnoop.c
+++ b/src/nwfilter/nwfilter_dhcpsnoop.c
@@ -314,7 +314,7 @@ virNWFilterSnoopCancel(char **threadKey)
 virNWFilterSnoopActiveLock();
 
 ignore_value(virHashRemoveEntry(virNWFilterSnoopState.active, *threadKey));
-VIR_FREE(*threadKey);
+g_free(*threadKey);
 
 virNWFilterSnoopActiveUnlock();
 }
@@ -600,7 +600,7 @@ virNWFilterSnoopReqFree(virNWFilterSnoopReqPtr req)
 virCondDestroy(>threadStatusCond);
 virFreeError(req->threadError);
 
-VIR_FREE(req);
+g_free(req);
 }
 
 /*
@@ -731,7 +731,7 @@ virNWFilterSnoopReqLeaseAdd(virNWFilterSnoopReqPtr req,
 
 if (req->threadkey && virNWFilterSnoopIPLeaseInstallRule(pl, true) < 0) {
 virNWFilterSnoopReqUnlock(req);
-VIR_FREE(pl);
+g_free(pl);
 return -1;
 }
 
@@ -850,7 +850,7 @@ virNWFilterSnoopReqLeaseDel(virNWFilterSnoopReqPtr req,
 }
 
  skip_instantiate:
-VIR_FREE(ipl);
+g_free(ipl);
 
 ignore_value(!!g_atomic_int_dec_and_test());
 
@@ -1149,7 +1149,7 @@ virNWFilterSnoopDHCPDecodeJobSubmit(virThreadPoolPtr pool,
 if (ret == 0)
 g_atomic_int_add(qCtr, 1);
 else
-VIR_FREE(job);
+g_free(job);
 
 return ret;
 }
@@ -1502,7 +1502,7 @@ virNWFilterDHCPSnoopThread(void *req0)
 ignore_value(virHashRemoveEntry(virNWFilterSnoopState.ifnameToKey,
 req->binding->portdevname));
 
-VIR_FREE(req->binding->portdevname);
+g_clear_pointer(>binding->portdevname, g_free);
 
 virNWFilterSnoopReqUnlock(req);
 virNWFilterSnoopUnlock();
@@ -1970,7 +1970,7 @@ virNWFilterSnoopRemAllReqIter(const void *payload,
  */
 virNWFilterIPAddrMapDelIPAddr(req->binding->portdevname, NULL);
 
-VIR_FREE(req->binding->portdevname);
+g_clear_pointer(>binding->portdevname, g_free);
 }
 
 virNWFilterSnoopReqUnlock(req);
@@ -2079,7 +2079,7 @@ virNWFilterDHCPSnoopEnd(const char *ifname)
 /* keep valid lease req; drop interface association */
 virNWFilterSnoopCancel(>threadkey);
 
-VIR_FREE(req->binding->portdevname);
+g_clear_pointer(>binding->portdevname, g_free);
 
 virNWFilterSnoopReqUnlock(req);
 
diff --git a/src/nwfilter/nwfilter_driver.c b/src/nwfilter/nwfilter_driver.c
index 39d0a2128e..7853ad59fa 100644
--- a/src/nwfilter/nwfilter_driver.c
+++ b/src/nwfilter/nwfilter_driver.c
@@ -303,7 +303,7 @@ nwfilterStateInitialize(bool privileged,
 
  err_free_driverstate:
 virNWFilterObjListFree(driver->nwfilters);
-VIR_FREE(driver);
+g_free(driver);
 
 return VIR_DRV_STATE_INIT_ERROR;
 }
@@ -367,9 +367,9 @@ nwfilterStateCleanup(void)
 if (driver->lockFD != -1)
 virPidFileRelease(driver->stateDir, "driver", driver->lockFD);
 
-VIR_FREE(driver->stateDir);
-VIR_FREE(driver->configDir);
-VIR_FREE(driver->bindingDir);
+g_free(driver->stateDir);
+g_free(driver->configDir);
+g_free(driver->bindingDir);
 nwfilterDriverUnlock();
 }
 
@@ -379,7 +379,7 @@ nwfilterStateCleanup(void)
 virNWFilterObjListFree(driver->nwfilters);
 
 virMutexDestroy(>lock);
-VIR_FREE(driver);
+g_free(driver);
 
 return 0;
 }
diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index 9c9d63f14b..6aefbe226b 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -3517,7 +3517,7 @@ ebiptablesApplyNewRules(const char *ifname,
 
  cleanup:
 for (i = 0; i < nsubchains; i++)
-VIR_FREE(subchains[i]);
+g_free(subchains[i]);
 
 return ret;
 }
diff --git a/src/nwfilter/nwfilter_gentech_driver.c 
b/src/nwfilter/nwfilter_gentech_driver.c
index 071f15caea..c93f2ed18f 100644
--- a/src/nwfilter/nwfilter_gentech_driver.c
+++ b/src/nwfilter/nwfilter_gentech_driver.c
@@ -122,7 +122,7 @@ virNWFilterRuleInstFree(virNWFilterRuleInstPtr inst)
 return;
 
 virHashFree(inst->vars);
-VIR_FREE(inst);
+g_free(inst);
 }
 
 
@@ -234,12 +234,12 @@ virNWFilterInstReset(virNWFilterInstPtr inst)
 
 for (i = 0; i < inst->nfilters; i++)
 virNWFilterObjUnlock(inst->filters[i]);
-VIR_FREE(inst->filters);
+g_free(inst->filters);
 inst->nfilters = 0;
 
 for (i = 0; i < inst->nr

[libvirt PATCH v2 01/15] replace g_new() with g_new0() for consistency

2020-07-07 Thread Laine Stump
g_new() is used in only 3 places. Switching them to g_new0() will do
no harm, reduces confusion, and helps me sleep better at night knowing
that all allocated memory is initialized to 0 :-) (Yes, I *know* that
in all three cases the associated memory is immediately assigned some
other value. Today.)

Signed-off-by: Laine Stump 
---
 src/qemu/qemu_backup.c  | 2 +-
 src/util/virutil.c  | 2 +-
 tests/qemuhotplugmock.c | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/qemu/qemu_backup.c b/src/qemu/qemu_backup.c
index 8dc9d2504d..dae9300567 100644
--- a/src/qemu/qemu_backup.c
+++ b/src/qemu/qemu_backup.c
@@ -64,7 +64,7 @@ qemuBackupPrepare(virDomainBackupDefPtr def)
 
 if (def->type == VIR_DOMAIN_BACKUP_TYPE_PULL) {
 if (!def->server) {
-def->server = g_new(virStorageNetHostDef, 1);
+def->server = g_new0(virStorageNetHostDef, 1);
 
 def->server->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
 def->server->name = g_strdup("localhost");
diff --git a/src/util/virutil.c b/src/util/virutil.c
index 04f882fda7..ff664ea778 100644
--- a/src/util/virutil.c
+++ b/src/util/virutil.c
@@ -962,7 +962,7 @@ virGetGroupList(uid_t uid, gid_t gid, gid_t **list)
 if (uid != (uid_t)-1 &&
 virGetUserEnt(uid, , , NULL, NULL, true) >= 0) {
 int nallocgrps = 10;
-gid_t *grps = g_new(gid_t, nallocgrps);
+gid_t *grps = g_new0(gid_t, nallocgrps);
 
 while (1) {
 int nprevallocgrps = nallocgrps;
diff --git a/tests/qemuhotplugmock.c b/tests/qemuhotplugmock.c
index d2324913cf..29fac8a598 100644
--- a/tests/qemuhotplugmock.c
+++ b/tests/qemuhotplugmock.c
@@ -57,7 +57,7 @@ virDevMapperGetTargets(const char *path,
 *devPaths = NULL;
 
 if (STREQ(path, "/dev/mapper/virt")) {
-*devPaths = g_new(char *, 4);
+*devPaths = g_new0(char *, 4);
 (*devPaths)[0] = g_strdup("/dev/block/8:0");  /* /dev/sda */
 (*devPaths)[1] = g_strdup("/dev/block/8:16"); /* /dev/sdb */
 (*devPaths)[2] = g_strdup("/dev/block/8:32"); /* /dev/sdc */
-- 
2.25.4



[libvirt PATCH v2 05/15] network: use g_auto wherever appropriate

2020-07-07 Thread Laine Stump
This includes standard g_autofree() as well as other objects that have
a cleanup function defined to use via g_autoptr (virCommand,
virJSONValue)

Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c   | 206 ++
 src/network/bridge_driver_linux.c |   7 +-
 src/network/leaseshelper.c|  16 +--
 3 files changed, 76 insertions(+), 153 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index ab359acdb5..31bd0dd92c 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -160,6 +160,7 @@ networkDnsmasqDefNamespaceFree(void *nsdata)
 
 VIR_FREE(def);
 }
+G_DEFINE_AUTOPTR_CLEANUP_FUNC(networkDnsmasqXmlNsDef, 
networkDnsmasqDefNamespaceFree);
 
 
 static int
@@ -195,7 +196,7 @@ static int
 networkDnsmasqDefNamespaceParse(xmlXPathContextPtr ctxt,
 void **data)
 {
-networkDnsmasqXmlNsDefPtr nsdata = g_new0(networkDnsmasqXmlNsDef, 1);
+g_autoptr(networkDnsmasqXmlNsDef) nsdata = g_new0(networkDnsmasqXmlNsDef, 
1);
 int ret = -1;
 
 if (networkDnsmasqDefNamespaceParseOptions(nsdata, ctxt))
@@ -207,7 +208,6 @@ networkDnsmasqDefNamespaceParse(xmlXPathContextPtr ctxt,
 ret = 0;
 
  cleanup:
-networkDnsmasqDefNamespaceFree(nsdata);
 return ret;
 }
 
@@ -329,7 +329,7 @@ networkRunHook(virNetworkObjPtr obj,
 {
 virNetworkDefPtr def;
 g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
-char *xml = NULL;
+g_autofree char *xml = NULL;
 int hookret;
 int ret = -1;
 
@@ -366,7 +366,6 @@ networkRunHook(virNetworkObjPtr obj,
 
 ret = 0;
  cleanup:
-VIR_FREE(xml);
 return ret;
 }
 
@@ -431,14 +430,14 @@ static int
 networkRemoveInactive(virNetworkDriverStatePtr driver,
   virNetworkObjPtr obj)
 {
-char *leasefile = NULL;
-char *customleasefile = NULL;
-char *radvdconfigfile = NULL;
-char *configfile = NULL;
-char *radvdpidbase = NULL;
-char *statusfile = NULL;
-char *macMapFile = NULL;
-dnsmasqContext *dctx = NULL;
+g_autofree char *leasefile = NULL;
+g_autofree char *customleasefile = NULL;
+g_autofree char *radvdconfigfile = NULL;
+g_autofree char *configfile = NULL;
+g_autofree char *radvdpidbase = NULL;
+g_autofree char *statusfile = NULL;
+g_autofree char *macMapFile = NULL;
+g_autoptr(dnsmasqContext) dctx = NULL;
 virNetworkDefPtr def = virNetworkObjGetPersistentDef(obj);
 
 int ret = -1;
@@ -492,14 +491,6 @@ networkRemoveInactive(virNetworkDriverStatePtr driver,
 ret = 0;
 
  cleanup:
-VIR_FREE(leasefile);
-VIR_FREE(configfile);
-VIR_FREE(customleasefile);
-VIR_FREE(radvdconfigfile);
-VIR_FREE(radvdpidbase);
-VIR_FREE(statusfile);
-VIR_FREE(macMapFile);
-dnsmasqContextFree(dctx);
 return ret;
 }
 
@@ -550,9 +541,9 @@ networkUpdateState(virNetworkObjPtr obj,
 {
 virNetworkDefPtr def;
 virNetworkDriverStatePtr driver = opaque;
-dnsmasqCapsPtr dnsmasq_caps = networkGetDnsmasqCaps(driver);
+g_autoptr(dnsmasqCaps) dnsmasq_caps = networkGetDnsmasqCaps(driver);
 virMacMapPtr macmap;
-char *macMapFile = NULL;
+g_autofree char *macMapFile = NULL;
 int ret = -1;
 
 virObjectLock(obj);
@@ -614,7 +605,7 @@ networkUpdateState(virNetworkObjPtr obj,
 if (virNetworkObjIsActive(obj) && def->ips && (def->nips > 0)) {
 pid_t radvdPid;
 pid_t dnsmasqPid;
-char *radvdpidbase;
+g_autofree char *radvdpidbase = NULL;
 
 ignore_value(virPidFileReadIfAlive(driver->pidDir,
def->name,
@@ -630,14 +621,11 @@ networkUpdateState(virNetworkObjPtr obj,
radvdpidbase,
, RADVD));
 virNetworkObjSetRadvdPid(obj, radvdPid);
-VIR_FREE(radvdpidbase);
 }
 
 ret = 0;
  cleanup:
 virObjectUnlock(obj);
-virObjectUnref(dnsmasq_caps);
-VIR_FREE(macMapFile);
 return ret;
 }
 
@@ -716,8 +704,8 @@ networkStateInitialize(bool privileged,
void *opaque G_GNUC_UNUSED)
 {
 int ret = VIR_DRV_STATE_INIT_ERROR;
-char *configdir = NULL;
-char *rundir = NULL;
+g_autofree char *configdir = NULL;
+g_autofree char *rundir = NULL;
 bool autostart = true;
 #ifdef WITH_FIREWALLD
 DBusConnection *sysbus = NULL;
@@ -845,8 +833,6 @@ networkStateInitialize(bool privileged,
 
 ret = VIR_DRV_STATE_INIT_COMPLETE;
  cleanup:
-VIR_FREE(configdir);
-VIR_FREE(rundir);
 return ret;
 
  error:
@@ -1047,10 +1033,11 @@ networkDnsmasqConfLocalPTRs(virBufferPtr buf,
 {
 virNetworkIPDefPtr ip;
 size_t i;
-char *ptr = NULL;
 int rc;
 
 for (i = 0; i < def->nips; i++) {
+g_autofree char *ptr = NULL;
+
 ip = def->ips + i;
 
 if (ip->localPTR != VIR_TRISTATE_BOOL_YES)
@@ -1071,7 +1058,6 

[libvirt PATCH v2 12/15] nwfilter: use standard label names when reasonable

2020-07-07 Thread Laine Stump
Rather than having labels named exit, done, exit_snooprequnlock,
skip_rename, etc, use the standard "cleanup" label. And instead of
err_exit, malformed, tear_down_tmpebchains, use "error".

Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_dhcpsnoop.c | 36 +++
 src/nwfilter/nwfilter_ebiptables_driver.c | 12 
 src/nwfilter/nwfilter_gentech_driver.c| 32 ++--
 src/nwfilter/nwfilter_learnipaddr.c   | 24 +++
 4 files changed, 52 insertions(+), 52 deletions(-)

diff --git a/src/nwfilter/nwfilter_dhcpsnoop.c 
b/src/nwfilter/nwfilter_dhcpsnoop.c
index f530341872..6de41ff209 100644
--- a/src/nwfilter/nwfilter_dhcpsnoop.c
+++ b/src/nwfilter/nwfilter_dhcpsnoop.c
@@ -456,11 +456,11 @@ 
virNWFilterSnoopIPLeaseInstallRule(virNWFilterSnoopIPLeasePtr ipl,
 virNWFilterSnoopReqLock(req);
 
 if (virNWFilterIPAddrMapAddIPAddr(req->binding->portdevname, ipaddr) < 0)
-goto exit_snooprequnlock;
+goto cleanup;
 
 if (!instantiate) {
 rc = 0;
-goto exit_snooprequnlock;
+goto cleanup;
 }
 
 /* instantiate the filters */
@@ -471,7 +471,7 @@ 
virNWFilterSnoopIPLeaseInstallRule(virNWFilterSnoopIPLeasePtr ipl,
   req->ifindex);
 }
 
- exit_snooprequnlock:
+ cleanup:
 virNWFilterSnoopReqUnlock(req);
 
 VIR_FREE(ipaddr);
@@ -732,7 +732,7 @@ virNWFilterSnoopReqLeaseAdd(virNWFilterSnoopReqPtr req,
 
 virNWFilterSnoopReqUnlock(req);
 
-goto exit;
+goto cleanup;
 }
 
 virNWFilterSnoopReqUnlock(req);
@@ -757,7 +757,7 @@ virNWFilterSnoopReqLeaseAdd(virNWFilterSnoopReqPtr req,
 
 g_atomic_int_add(, 1);
 
- exit:
+ cleanup:
 if (update_leasefile)
 virNWFilterSnoopLeaseFileSave(pl);
 
@@ -902,7 +902,7 @@ virNWFilterSnoopDHCPGetOpt(virNWFilterSnoopDHCPHdrPtr pd, 
int len,
 switch (pd->d_opts[oind]) {
 case DHCPO_LEASE:
 if (olen - oind < 6)
-goto malformed;
+goto error;
 if (*pleasetime)
 return -1;  /* duplicate lease time */
 memcpy(, (char *)pd->d_opts + oind + 2, sizeof(nwint));
@@ -910,7 +910,7 @@ virNWFilterSnoopDHCPGetOpt(virNWFilterSnoopDHCPHdrPtr pd, 
int len,
 break;
 case DHCPO_MTYPE:
 if (olen - oind < 3)
-goto malformed;
+goto error;
 if (*pmtype)
 return -1;  /* duplicate message type */
 *pmtype = pd->d_opts[oind + 2];
@@ -922,12 +922,12 @@ virNWFilterSnoopDHCPGetOpt(virNWFilterSnoopDHCPHdrPtr pd, 
int len,
 return 0;
 default:
 if (olen - oind < 2)
-goto malformed;
+goto error;
 }
 oind += pd->d_opts[oind + 1] + 2;
 }
 return 0;
- malformed:
+ error:
 VIR_WARN("got lost in the options!");
 return -1;
 }
@@ -1386,7 +1386,7 @@ virNWFilterDHCPSnoopThread(void *req0)
 virNWFilterSnoopReqUnlock(req);
 
 if (req->threadStatus != THREAD_STATUS_OK)
-goto exit;
+goto cleanup;
 
 while (!error) {
 if (virNWFilterSnoopAdjustPoll(pcapConf,
@@ -1414,7 +1414,7 @@ virNWFilterDHCPSnoopThread(void *req0)
  */
 if (!virNWFilterSnoopIsActive(threadkey) ||
 req->jobCompletionStatus != 0)
-goto exit;
+goto cleanup;
 
 for (i = 0; n > 0 && i < G_N_ELEMENTS(fds); i++) {
 if (!fds[i].revents)
@@ -1531,7 +1531,7 @@ virNWFilterDHCPSnoopThread(void *req0)
 virNWFilterSnoopReqUnlock(req);
 virNWFilterSnoopUnlock();
 
- exit:
+ cleanup:
 virThreadPoolFree(worker);
 
 virNWFilterSnoopReqPut(req);
@@ -1774,14 +1774,14 @@ 
virNWFilterSnoopLeaseFileSave(virNWFilterSnoopIPLeasePtr ipl)
 virNWFilterSnoopLeaseFileOpen();
 if (virNWFilterSnoopLeaseFileWrite(virNWFilterSnoopState.leaseFD,
req->ifkey, ipl) < 0)
-goto err_exit;
+goto error;
 
 /* keep dead leases at < ~95% of file size */
 if (g_atomic_int_add(, 1) >=
 g_atomic_int_get() * 20)
 virNWFilterSnoopLeaseFileLoad();   /* load & refresh lease file */
 
- err_exit:
+ error:
 virNWFilterSnoopUnlock();
 }
 
@@ -1876,7 +1876,7 @@ virNWFilterSnoopLeaseFileRefresh(void)
 if (VIR_CLOSE(tfd) < 0) {
 virReportSystemError(errno, _("unable to close %s"), TMPLEASEFILE);
 /* assuming the old lease file is still better, skip the renaming */
-goto skip_rename;
+goto cleanup;
 }
 
 if (rename(TMPLEASEFILE, LEASEFILE) < 0) {
@@ -1886,7 +1886,7 @@ virNWFilterSnoopLeaseFileRefresh(void)
 }
 g_atomic_int_set(, 0);
 
- skip_rename:
+ cleanup:
 virNWFilterSnoopLeaseFileOpen();
 }
 
@@ -2051,14 +2051,14 @@ virN

[libvirt PATCH v2 13/15] nwfilter: replace VIR_ALLOC with g_new0

2020-07-07 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_dhcpsnoop.c | 9 +++--
 src/nwfilter/nwfilter_driver.c| 3 +--
 src/nwfilter/nwfilter_ebiptables_driver.c | 3 +--
 src/nwfilter/nwfilter_gentech_driver.c| 3 +--
 src/nwfilter/nwfilter_learnipaddr.c   | 6 ++
 5 files changed, 8 insertions(+), 16 deletions(-)

diff --git a/src/nwfilter/nwfilter_dhcpsnoop.c 
b/src/nwfilter/nwfilter_dhcpsnoop.c
index 6de41ff209..4bc1607694 100644
--- a/src/nwfilter/nwfilter_dhcpsnoop.c
+++ b/src/nwfilter/nwfilter_dhcpsnoop.c
@@ -562,8 +562,7 @@ virNWFilterSnoopReqNew(const char *ifkey)
 return NULL;
 }
 
-if (VIR_ALLOC(req) < 0)
-return NULL;
+req = g_new0(virNWFilterSnoopReq, 1);
 
 req->threadStatus = THREAD_STATUS_NONE;
 
@@ -737,8 +736,7 @@ virNWFilterSnoopReqLeaseAdd(virNWFilterSnoopReqPtr req,
 
 virNWFilterSnoopReqUnlock(req);
 
-if (VIR_ALLOC(pl) < 0)
-return -1;
+pl = g_new0(virNWFilterSnoopIPLease, 1);
 *pl = *plnew;
 
 /* protect req->threadkey */
@@ -1160,8 +1158,7 @@ virNWFilterSnoopDHCPDecodeJobSubmit(virThreadPoolPtr pool,
 if (len <= MIN_VALID_DHCP_PKT_SIZE || len > sizeof(job->packet))
 return 0;
 
-if (VIR_ALLOC(job) < 0)
-return -1;
+job = g_new0(virNWFilterDHCPDecodeJob, 1);
 
 memcpy(job->packet, pep, len);
 job->caplen = len;
diff --git a/src/nwfilter/nwfilter_driver.c b/src/nwfilter/nwfilter_driver.c
index 1c407727db..39d0a2128e 100644
--- a/src/nwfilter/nwfilter_driver.c
+++ b/src/nwfilter/nwfilter_driver.c
@@ -193,8 +193,7 @@ nwfilterStateInitialize(bool privileged,
 !(sysbus = virDBusGetSystemBus()))
 return VIR_DRV_STATE_INIT_ERROR;
 
-if (VIR_ALLOC(driver) < 0)
-return VIR_DRV_STATE_INIT_ERROR;
+driver = g_new0(virNWFilterDriverState, 1);
 
 driver->lockFD = -1;
 if (virMutexInit(>lock) < 0)
diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index 8ac3a7271e..177e7e62b9 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -3312,8 +3312,7 @@ ebtablesGetSubChainInsts(virHashTablePtr chains,
 if ((int)idx < 0)
 continue;
 
-if (VIR_ALLOC(inst) < 0)
-goto cleanup;
+inst = g_new0(ebtablesSubChainInst, 1);
 inst->priority = *(const virNWFilterChainPriority 
*)filter_names[i].value;
 inst->incoming = incoming;
 inst->protoidx = idx;
diff --git a/src/nwfilter/nwfilter_gentech_driver.c 
b/src/nwfilter/nwfilter_gentech_driver.c
index 400d064724..acd5614987 100644
--- a/src/nwfilter/nwfilter_gentech_driver.c
+++ b/src/nwfilter/nwfilter_gentech_driver.c
@@ -262,8 +262,7 @@ virNWFilterRuleDefToRuleInst(virNWFilterDefPtr def,
 virNWFilterRuleInstPtr ruleinst;
 int ret = -1;
 
-if (VIR_ALLOC(ruleinst) < 0)
-goto cleanup;
+ruleinst = g_new0(virNWFilterRuleInst, 1);
 
 ruleinst->chainSuffix = def->chainsuffix;
 ruleinst->chainPriority = def->chainPriority;
diff --git a/src/nwfilter/nwfilter_learnipaddr.c 
b/src/nwfilter/nwfilter_learnipaddr.c
index 95e21050b4..63fac37132 100644
--- a/src/nwfilter/nwfilter_learnipaddr.c
+++ b/src/nwfilter/nwfilter_learnipaddr.c
@@ -151,8 +151,7 @@ virNWFilterLockIface(const char *ifname)
 
 ifaceLock = virHashLookup(ifaceLockMap, ifname);
 if (!ifaceLock) {
-if (VIR_ALLOC(ifaceLock) < 0)
-goto error;
+ifaceLock = g_new0(virNWFilterIfaceLock, 1);
 
 if (virMutexInitRecursive(>lock) < 0) {
 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
@@ -718,8 +717,7 @@ virNWFilterLearnIPAddress(virNWFilterTechDriverPtr 
techdriver,
 return -1;
 }
 
-if (VIR_ALLOC(req) < 0)
-return -1;
+req = g_new0(virNWFilterIPAddrLearnReq, 1);
 
 if (!(req->binding = virNWFilterBindingDefCopy(binding)))
 goto err_free_req;
-- 
2.25.4



[libvirt PATCH v2 00/15] convert network and nwfilter directories to glib memory allocation.

2020-07-07 Thread Laine Stump
V1 was here:

https://www.redhat.com/archives/libvir-list/2020-June/msg01156.html

Some patches were ACKed and pushed. I re-ordered/re-organized most of
the rest, and removed some others to deal with separately (the
xmlNodeContent stuff)

What's left here is a few preliminary patches, then the standard set,
once for network and again for nwfilter:

1) convert from VIR_(RE)ALLOC(_N) to g_new0()/g_renew()
2) use g_auto*() where appropriate, removing unneeded free's
3) get rid of now-extraneous labels
4) (controversial) replace any remaining VIR_FREE() with g_free() (and
   possibly g_clear_pointer() when needed

NB: these patches require my virBuffer "convert to g_auto" series
as a prerequisite:

  https://www.redhat.com/archives/libvir-list/2020-July/msg00185.html

Changes from V1:

  * move conversion of virFirewall and virBuffer automatics to another
series (see above)
  
  * re-order to replace VIR_ALLOC first (without adding any g_auto*)
instead of doing it after g_auto conversion of automatics, then do
all g_auto additions at o

  * separate label elimination into separate patches per jtomko's
suggestion.


Laine Stump (15):
  replace g_new() with g_new0() for consistency
  util: define g_autoptr cleanups for a couple dnsmasq objects
  define g_autoptr cleanup function for virNetworkDHCPLease
  network: replace VIR_ALLOC/REALLOC with g_new0/g_renew
  network: use g_auto wherever appropriate
  network: eliminate unnecessary labels
  network: use g_free() in place of remaining VIR_FREE()
  nwfilter: remove unnecessary code from ebtablesGetSubChainInsts()
  nwfilter: clear nrules when resetting virNWFilterInst
  nwfilter: define a typedef for struct ebtablesSubChainInst
  nwfilter: transform logic in virNWFilterRuleInstSort to eliminate
label
  nwfilter: use standard label names when reasonable
  nwfilter: replace VIR_ALLOC with g_new0
  nwfilter: convert local pointers to use g_auto*
  nwfilter: convert remaining VIR_FREE() to g_free()

 src/datatypes.h   |   2 +
 src/network/bridge_driver.c   | 536 --
 src/network/bridge_driver_linux.c |  22 +-
 src/network/leaseshelper.c|  16 +-
 src/nwfilter/nwfilter_dhcpsnoop.c | 150 +++---
 src/nwfilter/nwfilter_driver.c|  13 +-
 src/nwfilter/nwfilter_ebiptables_driver.c | 119 ++---
 src/nwfilter/nwfilter_gentech_driver.c|  57 ++-
 src/nwfilter/nwfilter_learnipaddr.c   |  43 +-
 src/qemu/qemu_backup.c|   2 +-
 src/util/virdnsmasq.h |   4 +
 src/util/virutil.c|   2 +-
 tests/qemuhotplugmock.c   |   2 +-
 13 files changed, 379 insertions(+), 589 deletions(-)

-- 
2.25.4



[libvirt PATCH v2 14/15] nwfilter: convert local pointers to use g_auto*

2020-07-07 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_dhcpsnoop.c | 91 +++
 src/nwfilter/nwfilter_ebiptables_driver.c | 75 +++
 src/nwfilter/nwfilter_gentech_driver.c| 15 ++--
 src/nwfilter/nwfilter_learnipaddr.c   |  7 +-
 4 files changed, 61 insertions(+), 127 deletions(-)

diff --git a/src/nwfilter/nwfilter_dhcpsnoop.c 
b/src/nwfilter/nwfilter_dhcpsnoop.c
index 4bc1607694..64671af135 100644
--- a/src/nwfilter/nwfilter_dhcpsnoop.c
+++ b/src/nwfilter/nwfilter_dhcpsnoop.c
@@ -292,18 +292,17 @@ static const unsigned char dhcp_magic[4] = { 99, 130, 83, 
99 };
 static char *
 virNWFilterSnoopActivate(virNWFilterSnoopReqPtr req)
 {
-char *key;
-
-key = g_strdup_printf("%p-%d", req, req->ifindex);
+g_autofree char *key = g_strdup_printf("%p-%d", req, req->ifindex);
+char *ret = NULL;
 
 virNWFilterSnoopActiveLock();
 
-if (virHashAddEntry(virNWFilterSnoopState.active, key, (void *)0x1) < 0)
-VIR_FREE(key);
+if (virHashAddEntry(virNWFilterSnoopState.active, key, (void *)0x1) == 0)
+ret = g_steal_pointer();
 
 virNWFilterSnoopActiveUnlock();
 
-return key;
+return ret;
 }
 
 static void
@@ -442,11 +441,10 @@ static int
 virNWFilterSnoopIPLeaseInstallRule(virNWFilterSnoopIPLeasePtr ipl,
bool instantiate)
 {
-char *ipaddr;
+g_autofree char *ipaddr = virSocketAddrFormat(>ipAddress);
 int rc = -1;
 virNWFilterSnoopReqPtr req;
 
-ipaddr = virSocketAddrFormat(>ipAddress);
 if (!ipaddr)
 return -1;
 
@@ -473,9 +471,6 @@ 
virNWFilterSnoopIPLeaseInstallRule(virNWFilterSnoopIPLeasePtr ipl,
 
  cleanup:
 virNWFilterSnoopReqUnlock(req);
-
-VIR_FREE(ipaddr);
-
 return rc;
 }
 
@@ -551,7 +546,7 @@ virNWFilterSnoopReqGet(virNWFilterSnoopReqPtr req)
 static virNWFilterSnoopReqPtr
 virNWFilterSnoopReqNew(const char *ifkey)
 {
-virNWFilterSnoopReqPtr req;
+g_autofree virNWFilterSnoopReqPtr req = g_new0(virNWFilterSnoopReq, 1);
 
 if (ifkey == NULL || strlen(ifkey) != VIR_IFKEY_LEN - 1) {
 virReportError(VIR_ERR_INTERNAL_ERROR,
@@ -562,28 +557,20 @@ virNWFilterSnoopReqNew(const char *ifkey)
 return NULL;
 }
 
-req = g_new0(virNWFilterSnoopReq, 1);
-
 req->threadStatus = THREAD_STATUS_NONE;
 
-if (virStrcpyStatic(req->ifkey, ifkey) < 0||
-virMutexInitRecursive(>lock) < 0)
-goto err_free_req;
+if (virStrcpyStatic(req->ifkey, ifkey) < 0 ||
+virMutexInitRecursive(>lock) < 0) {
+return NULL;
+}
 
-if (virCondInit(>threadStatusCond) < 0)
-goto err_destroy_mutex;
+if (virCondInit(>threadStatusCond) < 0) {
+virMutexDestroy(>lock);
+return NULL;
+}
 
 virNWFilterSnoopReqGet(req);
-
-return req;
-
- err_destroy_mutex:
-virMutexDestroy(>lock);
-
- err_free_req:
-VIR_FREE(req);
-
-return NULL;
+return g_steal_pointer();
 }
 
 /*
@@ -815,7 +802,7 @@ virNWFilterSnoopReqLeaseDel(virNWFilterSnoopReqPtr req,
 {
 int ret = 0;
 virNWFilterSnoopIPLeasePtr ipl;
-char *ipstr = NULL;
+g_autofree char *ipstr = NULL;
 
 /* protect req->start, req->ifname and the lease */
 virNWFilterSnoopReqLock(req);
@@ -868,8 +855,6 @@ virNWFilterSnoopReqLeaseDel(virNWFilterSnoopReqPtr req,
 ignore_value(!!g_atomic_int_dec_and_test());
 
  lease_not_found:
-VIR_FREE(ipstr);
-
 virNWFilterSnoopReqUnlock(req);
 
 return ret;
@@ -1045,7 +1030,7 @@ virNWFilterSnoopDHCPOpen(const char *ifname, virMacAddr 
*mac,
 pcap_t *handle = NULL;
 struct bpf_program fp;
 char pcap_errbuf[PCAP_ERRBUF_SIZE];
-char *ext_filter = NULL;
+g_autofree char *ext_filter = NULL;
 char macaddr[VIR_MAC_STRING_BUFLEN];
 
 virMacAddrFormat(mac, macaddr);
@@ -1075,7 +1060,7 @@ virNWFilterSnoopDHCPOpen(const char *ifname, virMacAddr 
*mac,
 if (handle == NULL) {
 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("pcap_create failed"));
-goto cleanup_nohandle;
+return NULL;
 }
 
 if (pcap_set_snaplen(handle, PCAP_PBUFSIZE) < 0 ||
@@ -1107,17 +1092,12 @@ virNWFilterSnoopDHCPOpen(const char *ifname, virMacAddr 
*mac,
 }
 
 pcap_freecode();
-VIR_FREE(ext_filter);
-
 return handle;
 
  cleanup_freecode:
 pcap_freecode();
  cleanup:
 pcap_close(handle);
- cleanup_nohandle:
-VIR_FREE(ext_filter);
-
 return NULL;
 }
 
@@ -1128,7 +1108,7 @@ virNWFilterSnoopDHCPOpen(const char *ifname, virMacAddr 
*mac,
 static void virNWFilterDHCPDecodeWorker(void *jobdata, void *opaque)
 {
 virNWFilterSnoopReqPtr req = opaque;
-virNWFilterDHCPDecodeJobPtr job = jobdata;
+g_autofree virNWFilterDHCPDecodeJobPtr job = jobdata;
 virNWFilterSnoopEthHdrPtr packet = (virNWFilterSnoopEthHdrPtr)job->packet;
 
 if (virNWFilte

[libvirt PATCH v2 10/15] nwfilter: define a typedef for struct ebtablesSubChainInst

2020-07-07 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_ebiptables_driver.c | 14 --
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index 426212e0dc..cc0f3f93d9 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -3269,7 +3269,9 @@ ebtablesRuleInstCommand(virFirewallPtr fw,
 return ret;
 }
 
-struct ebtablesSubChainInst {
+typedef struct _ebtablesSubChainInst ebtablesSubChainInst;
+typedef ebtablesSubChainInst *ebtablesSubChainInstPtr;
+struct _ebtablesSubChainInst {
 virNWFilterChainPriority priority;
 bool incoming;
 enum l3_proto_idx protoidx;
@@ -3280,8 +3282,8 @@ struct ebtablesSubChainInst {
 static int
 ebtablesSubChainInstSort(const void *a, const void *b)
 {
-const struct ebtablesSubChainInst **insta = (const struct 
ebtablesSubChainInst **)a;
-const struct ebtablesSubChainInst **instb = (const struct 
ebtablesSubChainInst **)b;
+const ebtablesSubChainInst **insta = (const ebtablesSubChainInst **)a;
+const ebtablesSubChainInst **instb = (const ebtablesSubChainInst **)b;
 
 /* priorities are limited to range [-1000, 1000] */
 return (*insta)->priority - (*instb)->priority;
@@ -3291,7 +3293,7 @@ ebtablesSubChainInstSort(const void *a, const void *b)
 static int
 ebtablesGetSubChainInsts(virHashTablePtr chains,
  bool incoming,
- struct ebtablesSubChainInst ***insts,
+ ebtablesSubChainInstPtr **insts,
  size_t *ninsts)
 {
 virHashKeyValuePairPtr filter_names;
@@ -3304,7 +3306,7 @@ ebtablesGetSubChainInsts(virHashTablePtr chains,
 return -1;
 
 for (i = 0; filter_names[i].key; i++) {
-struct ebtablesSubChainInst *inst;
+ebtablesSubChainInstPtr inst;
 enum l3_proto_idx idx = ebtablesGetProtoIdxByFiltername(
   filter_names[i].key);
 
@@ -3344,7 +3346,7 @@ ebiptablesApplyNewRules(const char *ifname,
 bool haveEbtables = false;
 bool haveIptables = false;
 bool haveIp6tables = false;
-struct ebtablesSubChainInst **subchains = NULL;
+ebtablesSubChainInstPtr *subchains = NULL;
 size_t nsubchains = 0;
 int ret = -1;
 
-- 
2.25.4



[libvirt PATCH v2 09/15] nwfilter: clear nrules when resetting virNWFilterInst

2020-07-07 Thread Laine Stump
It's possible/probable the callers to virNWFilterInstReset() make it
unnecessary to set the object's nrules to 0 after freeing all its
rules, but that same function is setting nfilters to 0, so let's do
the same for the sake of consistency.

Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_gentech_driver.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/nwfilter/nwfilter_gentech_driver.c 
b/src/nwfilter/nwfilter_gentech_driver.c
index b7633eb10a..aff42cbfb0 100644
--- a/src/nwfilter/nwfilter_gentech_driver.c
+++ b/src/nwfilter/nwfilter_gentech_driver.c
@@ -240,6 +240,7 @@ virNWFilterInstReset(virNWFilterInstPtr inst)
 for (i = 0; i < inst->nrules; i++)
 virNWFilterRuleInstFree(inst->rules[i]);
 VIR_FREE(inst->rules);
+inst->nrules = 0;
 }
 
 
-- 
2.25.4



[libvirt PATCH v2 11/15] nwfilter: transform logic in virNWFilterRuleInstSort to eliminate label

2020-07-07 Thread Laine Stump
This rewrite of a nested conditional produces the same results, but
eliminate a goto and corresponding label.

Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_ebiptables_driver.c | 11 +--
 1 file changed, 5 insertions(+), 6 deletions(-)

diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index cc0f3f93d9..94eaac927a 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -3113,13 +3113,12 @@ virNWFilterRuleInstSort(const void *a, const void *b)
 /* ensure root chain commands appear before all others since
we will need them to create the child chains */
 if (root_a) {
-if (root_b)
-goto normal;
-return -1; /* a before b */
-}
-if (root_b)
+if (!root_b)
+return -1; /* a before b */
+} else if (root_b) {
 return 1; /* b before a */
- normal:
+}
+
 /* priorities are limited to range [-1000, 1000] */
 return insta->priority - instb->priority;
 }
-- 
2.25.4



[libvirt PATCH v2 08/15] nwfilter: remove unnecessary code from ebtablesGetSubChainInsts()

2020-07-07 Thread Laine Stump
On failure, this function would clear out and free the list of
subchains it had been called with. This is unnecessary, because the
*only* caller of this function will also clear out and free the list
of subchains if it gets a failure from ebtablesGetSubChainInsts().

(It also makes more logical sense for the function that is creating
the entire list to be the one freeing the entire list, rather than
having a function whose purpose is only to create *one item* on the
list freeing the entire list).

Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_ebiptables_driver.c | 6 --
 1 file changed, 6 deletions(-)

diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index 78a52408b2..426212e0dc 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -3328,12 +3328,6 @@ ebtablesGetSubChainInsts(virHashTablePtr chains,
 
  cleanup:
 VIR_FREE(filter_names);
-if (ret < 0) {
-for (i = 0; i < *ninsts; i++)
-VIR_FREE(*insts[i]);
-VIR_FREE(*insts);
-*ninsts = 0;
-}
 return ret;
 
 }
-- 
2.25.4



[libvirt PATCH v2 04/15] network: replace VIR_ALLOC/REALLOC with g_new0/g_renew

2020-07-07 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c | 29 ++---
 1 file changed, 10 insertions(+), 19 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 713763130b..ab359acdb5 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -177,8 +177,7 @@ 
networkDnsmasqDefNamespaceParseOptions(networkDnsmasqXmlNsDefPtr nsdef,
 if (nnodes == 0)
 return 0;
 
-if (VIR_ALLOC_N(nsdef->options, nnodes) < 0)
-return -1;
+nsdef->options = g_new0(char *, nnodes);
 
 for (i = 0; i < nnodes; i++) {
 if (!(nsdef->options[nsdef->noptions++] = virXMLPropString(nodes[i], 
"value"))) {
@@ -196,12 +195,9 @@ static int
 networkDnsmasqDefNamespaceParse(xmlXPathContextPtr ctxt,
 void **data)
 {
-networkDnsmasqXmlNsDefPtr nsdata = NULL;
+networkDnsmasqXmlNsDefPtr nsdata = g_new0(networkDnsmasqXmlNsDef, 1);
 int ret = -1;
 
-if (VIR_ALLOC(nsdata) < 0)
-return -1;
-
 if (networkDnsmasqDefNamespaceParseOptions(nsdata, ctxt))
 goto cleanup;
 
@@ -733,8 +729,7 @@ networkStateInitialize(bool privileged,
 return -1;
 }
 
-if (VIR_ALLOC(network_driver) < 0)
-goto error;
+network_driver = g_new0(virNetworkDriverState, 1);
 
 network_driver->lockFD = -1;
 if (virMutexInit(_driver->lock) < 0) {
@@ -2753,8 +2748,7 @@ networkCreateInterfacePool(virNetworkDefPtr netdef)
 goto cleanup;
 }
 
-if (VIR_ALLOC_N(netdef->forward.ifs, numVirtFns) < 0)
-goto cleanup;
+netdef->forward.ifs = g_new0(virNetworkForwardIfDef, numVirtFns);
 
 for (i = 0; i < numVirtFns; i++) {
 virPCIDeviceAddressPtr thisVirtFn = virtFns[i];
@@ -4323,8 +4317,7 @@ networkGetDHCPLeases(virNetworkPtr net,
 continue;
 
 if (need_results) {
-if (VIR_ALLOC(lease) < 0)
-goto error;
+lease = g_new0(virNetworkDHCPLease, 1);
 
 lease->expirytime = expirytime_tmp;
 
@@ -4378,9 +4371,8 @@ networkGetDHCPLeases(virNetworkPtr net,
 
 if (leases_ret) {
 /* NULL terminated array */
-ignore_value(VIR_REALLOC_N(leases_ret, nleases + 1));
-*leases = leases_ret;
-leases_ret = NULL;
+leases_ret = g_renew(virNetworkDHCPLeasePtr, leases_ret,  nleases + 1);
+*leases = g_steal_pointer(_ret);
 }
 
 rv = nleases;
@@ -5612,10 +5604,9 @@ networkPortSetParameters(virNetworkPortPtr port,
 if (!(dir = virNetworkObjGetPortStatusDir(obj, driver->stateDir)))
 goto cleanup;
 
-if ((VIR_ALLOC(bandwidth) < 0) ||
-(VIR_ALLOC(bandwidth->in) < 0) ||
-(VIR_ALLOC(bandwidth->out) < 0))
-goto cleanup;
+bandwidth = g_new0(virNetDevBandwidth, 1);
+bandwidth->in = g_new0(virNetDevBandwidthRate, 1);
+bandwidth->out = g_new0(virNetDevBandwidthRate, 1);
 
 for (i = 0; i < nparams; i++) {
 virTypedParameterPtr param = [i];
-- 
2.25.4



[libvirt PATCH v2 03/15] define g_autoptr cleanup function for virNetworkDHCPLease

2020-07-07 Thread Laine Stump
virNetworkDHCPLease and virNetworkDHCPLeaseFree() are declared in the
public API file libvirt-network.h, and we can't pollute that with glib
macro invocations, so put this in src/datatypes.h next to the other
virNetwork items.

Signed-off-by: Laine Stump 
---
 src/datatypes.h | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/src/datatypes.h b/src/datatypes.h
index d58429ad6c..ade3779e43 100644
--- a/src/datatypes.h
+++ b/src/datatypes.h
@@ -635,6 +635,8 @@ struct _virNetworkPort {
 
 G_DEFINE_AUTOPTR_CLEANUP_FUNC(virNetworkPort, virObjectUnref);
 
+/* virNetworkDHCPLease is defined in the public API - libvirt-network.h */
+G_DEFINE_AUTOPTR_CLEANUP_FUNC(virNetworkDHCPLease, virNetworkDHCPLeaseFree);
 
 /**
 * _virInterface:
-- 
2.25.4



[libvirt PATCH v2 02/15] util: define g_autoptr cleanups for a couple dnsmasq objects

2020-07-07 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/util/virdnsmasq.h | 4 
 1 file changed, 4 insertions(+)

diff --git a/src/util/virdnsmasq.h b/src/util/virdnsmasq.h
index 4c14bc6ca7..e3814c2eb1 100644
--- a/src/util/virdnsmasq.h
+++ b/src/util/virdnsmasq.h
@@ -78,10 +78,14 @@ typedef enum {
 typedef struct _dnsmasqCaps dnsmasqCaps;
 typedef dnsmasqCaps *dnsmasqCapsPtr;
 
+G_DEFINE_AUTOPTR_CLEANUP_FUNC(dnsmasqCaps, virObjectUnref);
+
 
 dnsmasqContext * dnsmasqContextNew(const char *network_name,
const char *config_dir);
 void dnsmasqContextFree(dnsmasqContext *ctx);
+G_DEFINE_AUTOPTR_CLEANUP_FUNC(dnsmasqContext, dnsmasqContextFree);
+
 int  dnsmasqAddDhcpHost(dnsmasqContext *ctx,
 const char *mac,
 virSocketAddr *ip,
-- 
2.25.4



[libvirt PATCH v2 06/15] network: eliminate unnecessary labels

2020-07-07 Thread Laine Stump
All these cleanup/error labels were reduced to having just "return
ret" by a previous patch, so get rid of them and return directly.

Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c   | 264 --
 src/network/bridge_driver_linux.c |  15 +-
 2 files changed, 113 insertions(+), 166 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 31bd0dd92c..79b2ca3330 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -197,18 +197,14 @@ networkDnsmasqDefNamespaceParse(xmlXPathContextPtr ctxt,
 void **data)
 {
 g_autoptr(networkDnsmasqXmlNsDef) nsdata = g_new0(networkDnsmasqXmlNsDef, 
1);
-int ret = -1;
 
 if (networkDnsmasqDefNamespaceParseOptions(nsdata, ctxt))
-goto cleanup;
+return -1;
 
 if (nsdata->noptions > 0)
 *data = g_steal_pointer();
 
-ret = 0;
-
- cleanup:
-return ret;
+return 0;
 }
 
 
@@ -331,22 +327,20 @@ networkRunHook(virNetworkObjPtr obj,
 g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 g_autofree char *xml = NULL;
 int hookret;
-int ret = -1;
 
 if (virHookPresent(VIR_HOOK_DRIVER_NETWORK)) {
 if (!obj) {
 VIR_DEBUG("Not running hook as @obj is NULL");
-ret = 0;
-goto cleanup;
+return 0;
 }
 def = virNetworkObjGetDef(obj);
 
 virBufferAddLit(, "\n");
 virBufferAdjustIndent(, 2);
 if (virNetworkDefFormatBuf(, def, network_driver->xmlopt, 0) < 0)
-goto cleanup;
+return -1;
 if (port && virNetworkPortDefFormatBuf(, port) < 0)
-goto cleanup;
+return -1;
 
 virBufferAdjustIndent(, -2);
 virBufferAddLit(, "");
@@ -359,14 +353,12 @@ networkRunHook(virNetworkObjPtr obj,
  * If the script raised an error, pass it to the callee.
  */
 if (hookret < 0)
-goto cleanup;
+return -1;
 
 networkNetworkObjTaint(obj, VIR_NETWORK_TAINT_HOOK);
 }
 
-ret = 0;
- cleanup:
-return ret;
+return 0;
 }
 
 
@@ -440,34 +432,32 @@ networkRemoveInactive(virNetworkDriverStatePtr driver,
 g_autoptr(dnsmasqContext) dctx = NULL;
 virNetworkDefPtr def = virNetworkObjGetPersistentDef(obj);
 
-int ret = -1;
-
 /* remove the (possibly) existing dnsmasq and radvd files */
 if (!(dctx = dnsmasqContextNew(def->name,
driver->dnsmasqStateDir))) {
-goto cleanup;
+return -1;
 }
 
 if (!(leasefile = networkDnsmasqLeaseFileNameDefault(driver, def->name)))
-goto cleanup;
+return -1;
 
 if (!(customleasefile = networkDnsmasqLeaseFileNameCustom(driver, 
def->bridge)))
-goto cleanup;
+return -1;
 
 if (!(radvdconfigfile = networkRadvdConfigFileName(driver, def->name)))
-goto cleanup;
+return -1;
 
 if (!(radvdpidbase = networkRadvdPidfileBasename(def->name)))
-goto cleanup;
+return -1;
 
 if (!(configfile = networkDnsmasqConfigFileName(driver, def->name)))
-goto cleanup;
+return -1;
 
 if (!(statusfile = virNetworkConfigFile(driver->stateDir, def->name)))
-goto cleanup;
+return -1;
 
 if (!(macMapFile = virMacMapFileName(driver->dnsmasqStateDir, 
def->bridge)))
-goto cleanup;
+return -1;
 
 /* dnsmasq */
 dnsmasqDelete(dctx);
@@ -488,10 +478,7 @@ networkRemoveInactive(virNetworkDriverStatePtr driver,
 /* remove the network definition */
 virNetworkObjRemoveInactive(driver->networks, obj);
 
-ret = 0;
-
- cleanup:
-return ret;
+return 0;
 }
 
 
@@ -703,7 +690,6 @@ networkStateInitialize(bool privileged,
virStateInhibitCallback callback G_GNUC_UNUSED,
void *opaque G_GNUC_UNUSED)
 {
-int ret = VIR_DRV_STATE_INIT_ERROR;
 g_autofree char *configdir = NULL;
 g_autofree char *rundir = NULL;
 bool autostart = true;
@@ -831,13 +817,12 @@ networkStateInitialize(bool privileged,
 }
 #endif
 
-ret = VIR_DRV_STATE_INIT_COMPLETE;
- cleanup:
-return ret;
+return VIR_DRV_STATE_INIT_COMPLETE;
+
 
  error:
 networkStateCleanup();
-goto cleanup;
+return VIR_DRV_STATE_INIT_ERROR;
 }
 
 
@@ -1074,7 +1059,7 @@ networkDnsmasqConfContents(virNetworkObjPtr obj,
 {
 virNetworkDefPtr def = virNetworkObjGetDef(obj);
 g_auto(virBuffer) configbuf = VIR_BUFFER_INITIALIZER;
-int r, ret = -1;
+int r;
 int nbleases = 0;
 size_t i;
 virNetworkDNSDefPtr dns = >dns;
@@ -1138,7 +1123,7 @@ networkDnsmasqConfContents(virNetworkObjPtr obj,
 g_autofree char *addr = virSocketAddrFormat(>addr);
 
 if (!addr)
-goto cleanup;
+

Re: Release of libvirt-6.5.0

2020-07-07 Thread Laine Stump

On 7/3/20 3:56 AM, Daniel Veillard wrote:

It will also be my last release of libvirt after close to 15 years,


.

(I missed this sentence when I saw the mail the first time, and just now 
it randomly popped up when scrolling through messages.)



Thanks for your helpful and positive attitude, and in general being a 
good example for everyone to follow for all these years. It's a bit sad 
that you're not involved with the project as you once were, but 
comforting to know that you're still around and reachable.




[PATCH 14/32] network: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c | 9 +++--
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 0f5212ce04..9f37d8f558 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -332,7 +332,7 @@ networkRunHook(virNetworkObjPtr obj,
int sub_op)
 {
 virNetworkDefPtr def;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char *xml = NULL;
 int hookret;
 int ret = -1;
@@ -370,7 +370,6 @@ networkRunHook(virNetworkObjPtr obj,
 
 ret = 0;
  cleanup:
-virBufferFreeAndReset();
 VIR_FREE(xml);
 return ret;
 }
@@ -1093,7 +1092,7 @@ networkDnsmasqConfContents(virNetworkObjPtr obj,
dnsmasqCapsPtr caps G_GNUC_UNUSED)
 {
 virNetworkDefPtr def = virNetworkObjGetDef(obj);
-virBuffer configbuf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) configbuf = VIR_BUFFER_INITIALIZER;
 int r, ret = -1;
 int nbleases = 0;
 size_t i;
@@ -1577,7 +1576,6 @@ networkDnsmasqConfContents(virNetworkObjPtr obj,
  cleanup:
 VIR_FREE(saddr);
 VIR_FREE(eaddr);
-virBufferFreeAndReset();
 return ret;
 }
 
@@ -1843,7 +1841,7 @@ networkRadvdConfContents(virNetworkObjPtr obj,
  char **configstr)
 {
 virNetworkDefPtr def = virNetworkObjGetDef(obj);
-virBuffer configbuf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) configbuf = VIR_BUFFER_INITIALIZER;
 int ret = -1;
 size_t i;
 virNetworkIPDefPtr ipdef;
@@ -1907,7 +1905,6 @@ networkRadvdConfContents(virNetworkObjPtr obj,
 
 ret = 0;
  cleanup:
-virBufferFreeAndReset();
 return ret;
 }
 
-- 
2.25.4



[PATCH 21/32] conf: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/conf/capabilities.c|  5 +--
 src/conf/checkpoint_conf.c |  8 ++--
 src/conf/cpu_conf.c| 18 +++-
 src/conf/domain_conf.c | 88 +++---
 src/conf/network_conf.c|  5 +--
 src/conf/nwfilter_conf.c   |  5 +--
 src/conf/secret_conf.c |  5 +--
 src/conf/snapshot_conf.c   | 11 ++---
 src/conf/storage_conf.c| 17 ++--
 src/conf/virnetworkobj.c   |  7 +--
 src/conf/virsavecookie.c   |  5 +--
 11 files changed, 67 insertions(+), 107 deletions(-)

diff --git a/src/conf/capabilities.c b/src/conf/capabilities.c
index 6a48af1fca..610e6e8242 100644
--- a/src/conf/capabilities.c
+++ b/src/conf/capabilities.c
@@ -1340,7 +1340,7 @@ virCapabilitiesFormatXML(virCapsPtr caps)
 virBufferAdjustIndent(, 2);
 
 if (virCapabilitiesFormatHostXML(>host, ) < 0)
-goto error;
+return NULL;
 
 virCapabilitiesFormatGuestXML(caps->guests, caps->nguests, );
 
@@ -1350,9 +1350,6 @@ virCapabilitiesFormatXML(virCapsPtr caps)
 virBufferAddLit(, "\n");
 
 return virBufferContentAndReset();
-
- error:
-return NULL;
 }
 
 /* get the maximum ID of cpus in the host */
diff --git a/src/conf/checkpoint_conf.c b/src/conf/checkpoint_conf.c
index 41f67bd895..861004801e 100644
--- a/src/conf/checkpoint_conf.c
+++ b/src/conf/checkpoint_conf.c
@@ -476,7 +476,7 @@ virDomainCheckpointDefFormatInternal(virBufferPtr buf,
 for (i = 0; i < def->ndisks; i++) {
 if (virDomainCheckpointDiskDefFormat(buf, >disks[i],
  flags) < 0)
-goto error;
+return -1;
 }
 virBufferAdjustIndent(buf, -2);
 virBufferAddLit(buf, "\n");
@@ -485,17 +485,15 @@ virDomainCheckpointDefFormatInternal(virBufferPtr buf,
 if (!(flags & VIR_DOMAIN_CHECKPOINT_FORMAT_NO_DOMAIN) &&
 virDomainDefFormatInternal(def->parent.dom, xmlopt,
buf, domainflags) < 0)
-goto error;
+return -1;
 
 virBufferAdjustIndent(buf, -2);
 virBufferAddLit(buf, "\n");
 
 return 0;
-
- error:
-return -1;
 }
 
+
 char *
 virDomainCheckpointDefFormat(virDomainCheckpointDefPtr def,
  virDomainXMLOptionPtr xmlopt,
diff --git a/src/conf/cpu_conf.c b/src/conf/cpu_conf.c
index dd3db00bc8..7be108fa63 100644
--- a/src/conf/cpu_conf.c
+++ b/src/conf/cpu_conf.c
@@ -671,12 +671,9 @@ virCPUDefFormat(virCPUDefPtr def,
 g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 if (virCPUDefFormatBufFull(, def, numa) < 0)
-goto cleanup;
+return NULL;
 
 return virBufferContentAndReset();
-
- cleanup:
-return NULL;
 }
 
 
@@ -685,7 +682,6 @@ virCPUDefFormatBufFull(virBufferPtr buf,
virCPUDefPtr def,
virDomainNumaPtr numa)
 {
-int ret = -1;
 g_auto(virBuffer) attributeBuf = VIR_BUFFER_INITIALIZER;
 g_auto(virBuffer) childrenBuf = VIR_BUFFER_INIT_CHILD(buf);
 
@@ -701,7 +697,7 @@ virCPUDefFormatBufFull(virBufferPtr buf,
 if (!(tmp = virCPUModeTypeToString(def->mode))) {
 virReportError(VIR_ERR_INTERNAL_ERROR,
_("Unexpected CPU mode %d"), def->mode);
-goto cleanup;
+return -1;
 }
 virBufferAsprintf(, " mode='%s'", tmp);
 
@@ -710,7 +706,7 @@ virCPUDefFormatBufFull(virBufferPtr buf,
 virReportError(VIR_ERR_INTERNAL_ERROR,
_("Unexpected CPU match policy %d"),
def->match);
-goto cleanup;
+return -1;
 }
 virBufferAsprintf(, " match='%s'", tmp);
 }
@@ -731,10 +727,10 @@ virCPUDefFormatBufFull(virBufferPtr buf,
 virBufferAsprintf(, "%s\n",
   virArchToString(def->arch));
 if (virCPUDefFormatBuf(, def) < 0)
-goto cleanup;
+return -1;
 
 if (virDomainNumaDefCPUFormatXML(, numa) < 0)
-goto cleanup;
+return -1;
 
 /* Put it all together */
 if (virBufferUse() || virBufferUse()) {
@@ -752,9 +748,7 @@ virCPUDefFormatBufFull(virBufferPtr buf,
 }
 }
 
-ret = 0;
- cleanup:
-return ret;
+return 0;
 }
 
 int
diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index e5070ed871..706d050f4d 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -29543,7 +29543,7 @@ virDomainDefFormatInternalSetRootName(virDomainDefPtr 
def,
 if (!(type = virDomainVirtTypeToString(def->virtType))) {
 virReportError(VIR_ERR_INTERNAL_ERROR,
_("unexpected domain type %d"), def->virtType);
-goto error;
+return -1;
 }
 
 if (def->id == -

[PATCH 31/32] use g_autoptr() for all usages of virFirewallNew/Free

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/network/bridge_driver_linux.c | 11 ++---
 src/nwfilter/nwfilter_ebiptables_driver.c | 31 --
 src/util/virebtables.c|  8 +---
 src/util/viriptables.c|  6 +--
 tests/virfirewalltest.c   | 50 +--
 5 files changed, 25 insertions(+), 81 deletions(-)

diff --git a/src/network/bridge_driver_linux.c 
b/src/network/bridge_driver_linux.c
index 30f6aa8fe1..f72f94f38d 100644
--- a/src/network/bridge_driver_linux.c
+++ b/src/network/bridge_driver_linux.c
@@ -838,7 +838,7 @@ int networkAddFirewallRules(virNetworkDefPtr def)
 {
 size_t i;
 virNetworkIPDefPtr ipdef;
-virFirewallPtr fw = NULL;
+g_autoptr(virFirewall) fw = virFirewallNew();
 int ret = -1;
 
 if (virOnce(, networkSetupPrivateChains) < 0)
@@ -925,8 +925,6 @@ int networkAddFirewallRules(virNetworkDefPtr def)
 }
 }
 
-fw = virFirewallNew();
-
 virFirewallStartTransaction(fw, 0);
 
 networkAddGeneralFirewallRules(fw, def);
@@ -956,7 +954,6 @@ int networkAddFirewallRules(virNetworkDefPtr def)
 
 ret = 0;
  cleanup:
-virFirewallFree(fw);
 return ret;
 }
 
@@ -965,9 +962,7 @@ void networkRemoveFirewallRules(virNetworkDefPtr def)
 {
 size_t i;
 virNetworkIPDefPtr ipdef;
-virFirewallPtr fw = NULL;
-
-fw = virFirewallNew();
+g_autoptr(virFirewall) fw = virFirewallNew();
 
 virFirewallStartTransaction(fw, VIR_FIREWALL_TRANSACTION_IGNORE_ERRORS);
 networkRemoveChecksumFirewallRules(fw, def);
@@ -985,5 +980,5 @@ void networkRemoveFirewallRules(virNetworkDefPtr def)
 virFirewallApply(fw);
 
  cleanup:
-virFirewallFree(fw);
+return;
 }
diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index 6cdb3ca45e..2976521e6d 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -2858,7 +2858,7 @@ static int
 ebtablesApplyBasicRules(const char *ifname,
 const virMacAddr *macaddr)
 {
-virFirewallPtr fw = virFirewallNew();
+g_autoptr(virFirewall) fw = virFirewallNew();
 char chain[MAX_CHAINNAME_LENGTH];
 char chainPrefix = CHAINPREFIX_HOST_IN_TEMP;
 char macaddr_str[VIR_MAC_STRING_BUFLEN];
@@ -2895,13 +2895,11 @@ ebtablesApplyBasicRules(const char *ifname,
 if (virFirewallApply(fw) < 0)
 goto tear_down_tmpebchains;
 
-virFirewallFree(fw);
 return 0;
 
  tear_down_tmpebchains:
 ebtablesCleanAll(ifname);
  error:
-virFirewallFree(fw);
 return -1;
 }
 
@@ -2934,7 +2932,7 @@ ebtablesApplyDHCPOnlyRules(const char *ifname,
 char macaddr_str[VIR_MAC_STRING_BUFLEN];
 unsigned int idx = 0;
 unsigned int num_dhcpsrvrs;
-virFirewallPtr fw = virFirewallNew();
+g_autoptr(virFirewall) fw = virFirewallNew();
 
 virMacAddrFormat(macaddr, macaddr_str);
 
@@ -3014,14 +3012,11 @@ ebtablesApplyDHCPOnlyRules(const char *ifname,
 if (virFirewallApply(fw) < 0)
 goto tear_down_tmpebchains;
 
-virFirewallFree(fw);
-
 return 0;
 
  tear_down_tmpebchains:
 ebtablesCleanAll(ifname);
  error:
-virFirewallFree(fw);
 return -1;
 }
 
@@ -3040,7 +3035,7 @@ ebtablesApplyDropAllRules(const char *ifname)
 {
 char chain_in [MAX_CHAINNAME_LENGTH],
  chain_out[MAX_CHAINNAME_LENGTH];
-virFirewallPtr fw = virFirewallNew();
+g_autoptr(virFirewall) fw = virFirewallNew();
 
 if (ebiptablesAllTeardown(ifname) < 0)
 goto error;
@@ -3069,13 +3064,11 @@ ebtablesApplyDropAllRules(const char *ifname)
 if (virFirewallApply(fw) < 0)
 goto tear_down_tmpebchains;
 
-virFirewallFree(fw);
 return 0;
 
  tear_down_tmpebchains:
 ebtablesCleanAll(ifname);
  error:
-virFirewallFree(fw);
 return -1;
 }
 
@@ -3090,7 +3083,7 @@ ebtablesRemoveBasicRules(const char *ifname)
 static int
 ebtablesCleanAll(const char *ifname)
 {
-virFirewallPtr fw = virFirewallNew();
+g_autoptr(virFirewall) fw = virFirewallNew();
 int ret = -1;
 
 virFirewallStartTransaction(fw, VIR_FIREWALL_TRANSACTION_IGNORE_ERRORS);
@@ -3108,7 +3101,6 @@ ebtablesCleanAll(const char *ifname)
 ebtablesRemoveTmpRootChainFW(fw, false, ifname);
 
 ret = virFirewallApply(fw);
-virFirewallFree(fw);
 return ret;
 }
 
@@ -3357,7 +3349,7 @@ ebiptablesApplyNewRules(const char *ifname,
 size_t nrules)
 {
 size_t i, j;
-virFirewallPtr fw = virFirewallNew();
+g_autoptr(virFirewall) fw = virFirewallNew();
 virHashTablePtr chains_in_set  = virHashCreate(10, NULL);
 virHashTablePtr chains_out_set = virHashCreate(10, NULL);
 bool haveEbtables = false;
@@ -3558,7 +3550,6 @@ ebiptablesApplyNewRules(const char *ifname,
 for (i = 0; i < nsubchains; i++)
 VIR_FREE(subchains[i]);
 VIR_FREE(subchains);
-virFirewallFree(fw);
 virHashFree(chains_in_set);
 virHashF

[PATCH 28/32] esx: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/esx/esx_vi.c | 9 +++--
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/src/esx/esx_vi.c b/src/esx/esx_vi.c
index d48a24e9d3..71aa3876b3 100644
--- a/src/esx/esx_vi.c
+++ b/src/esx/esx_vi.c
@@ -369,7 +369,7 @@ int
 esxVI_CURL_Download(esxVI_CURL *curl, const char *url, char **content,
 unsigned long long offset, unsigned long long *length)
 {
-char *range = NULL;
+g_autofree char *range = NULL;
 g_auto(virBuffer) buffer = VIR_BUFFER_INITIALIZER;
 int responseCode = 0;
 
@@ -405,12 +405,12 @@ esxVI_CURL_Download(esxVI_CURL *curl, const char *url, 
char **content,
 virMutexUnlock(>lock);
 
 if (responseCode < 0) {
-goto cleanup;
+return -1;
 } else if (responseCode != 200 && responseCode != 206) {
 virReportError(VIR_ERR_INTERNAL_ERROR,
_("HTTP response code %d for download from '%s'"),
responseCode, url);
-goto cleanup;
+return -1;
 }
 
 if (length)
@@ -418,9 +418,6 @@ esxVI_CURL_Download(esxVI_CURL *curl, const char *url, char 
**content,
 
 *content = virBufferContentAndReset();
 
- cleanup:
-VIR_FREE(range);
-
 if (!(*content))
 return -1;
 
-- 
2.25.4



[PATCH 12/32] rpc: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/rpc/virnetclient.c| 4 ++--
 src/rpc/virnetlibsshsession.c | 7 ++-
 src/rpc/virnetsocket.c| 2 +-
 src/rpc/virnetsshsession.c| 2 +-
 4 files changed, 6 insertions(+), 9 deletions(-)

diff --git a/src/rpc/virnetclient.c b/src/rpc/virnetclient.c
index 1c5bef86a1..441f1502a6 100644
--- a/src/rpc/virnetclient.c
+++ b/src/rpc/virnetclient.c
@@ -428,7 +428,7 @@ virNetClientPtr virNetClientNewLibSSH2(const char *host,
 {
 virNetSocketPtr sock = NULL;
 
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 g_autofree char *nc = NULL;
 g_autofree char *command = NULL;
 
@@ -518,7 +518,7 @@ virNetClientPtr virNetClientNewLibssh(const char *host,
 {
 virNetSocketPtr sock = NULL;
 
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 g_autofree char *nc = NULL;
 g_autofree char *command = NULL;
 
diff --git a/src/rpc/virnetlibsshsession.c b/src/rpc/virnetlibsshsession.c
index 0a566eaa54..c9b31e9462 100644
--- a/src/rpc/virnetlibsshsession.c
+++ b/src/rpc/virnetlibsshsession.c
@@ -664,7 +664,7 @@ 
virNetLibsshAuthenticateKeyboardInteractive(virNetLibsshSessionPtr sess,
 while (ret == SSH_AUTH_INFO) {
 const char *name, *instruction;
 int nprompts, iprompt;
-virBuffer buff = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buff = VIR_BUFFER_INITIALIZER;
 
 name = ssh_userauth_kbdint_getname(sess->session);
 instruction = ssh_userauth_kbdint_getinstruction(sess->session);
@@ -706,7 +706,7 @@ 
virNetLibsshAuthenticateKeyboardInteractive(virNetLibsshSessionPtr sess,
  * buffer if specified
  */
 if (virBufferUse() > 0) {
-virBuffer prompt_buff = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) prompt_buff = VIR_BUFFER_INITIALIZER;
 
 virBufferAddBuffer(_buff, );
 virBufferAdd(_buff, promptStr, promptStrLen);
@@ -750,12 +750,9 @@ 
virNetLibsshAuthenticateKeyboardInteractive(virNetLibsshSessionPtr sess,
 
  prompt_error:
 VIR_FREE(prompt);
-virBufferFreeAndReset();
 return SSH_AUTH_ERROR;
 }
 
-virBufferFreeAndReset();
-
 ret = ssh_userauth_kbdint(sess->session, NULL, NULL);
 ++try;
 if (ret == SSH_AUTH_DENIED && (priv->tries < 0 || try < priv->tries))
diff --git a/src/rpc/virnetsocket.c b/src/rpc/virnetsocket.c
index 3ea863f625..d1f4c531aa 100644
--- a/src/rpc/virnetsocket.c
+++ b/src/rpc/virnetsocket.c
@@ -849,7 +849,7 @@ int virNetSocketNewConnectSSH(const char *nodename,
 {
 char *quoted;
 virCommandPtr cmd;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 *retsock = NULL;
 
diff --git a/src/rpc/virnetsshsession.c b/src/rpc/virnetsshsession.c
index b4dea15452..490e9d5c5d 100644
--- a/src/rpc/virnetsshsession.c
+++ b/src/rpc/virnetsshsession.c
@@ -287,7 +287,7 @@ virNetSSHCheckHostKey(virNetSSHSessionPtr sess)
 int keyType;
 size_t keyLength;
 char *errmsg;
-virBuffer buff = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buff = VIR_BUFFER_INITIALIZER;
 virConnectCredential askKey;
 struct libssh2_knownhost *knownHostEntry = NULL;
 size_t i;
-- 
2.25.4



[PATCH 10/32] util: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/util/virbitmap.c  |  4 ++--
 src/util/vircommand.c |  3 +--
 src/util/virconf.c|  5 ++---
 src/util/virdnsmasq.c |  6 ++
 src/util/virfile.c|  2 +-
 src/util/virfilecache.c   |  2 +-
 src/util/virfirewall.c|  2 +-
 src/util/virlog.c |  5 ++---
 src/util/virnetdevip.c|  3 +--
 src/util/virpidfile.c |  2 +-
 src/util/virqemu.c|  3 +--
 src/util/virresctrl.c | 10 +++---
 src/util/virsocketaddr.c  |  3 +--
 src/util/virstoragefile.c |  2 +-
 src/util/virstring.c  |  4 ++--
 src/util/virsysinfo.c |  4 ++--
 src/util/virsystemd.c |  4 ++--
 src/util/viruri.c |  2 +-
 src/util/virxml.c |  3 +--
 19 files changed, 28 insertions(+), 41 deletions(-)

diff --git a/src/util/virbitmap.c b/src/util/virbitmap.c
index d38a2dd7e9..60fd8491dd 100644
--- a/src/util/virbitmap.c
+++ b/src/util/virbitmap.c
@@ -345,7 +345,7 @@ virBitmapToString(virBitmapPtr bitmap,
   bool prefix,
   bool trim)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t sz;
 size_t len;
 size_t diff;
@@ -404,7 +404,7 @@ virBitmapToString(virBitmapPtr bitmap,
 char *
 virBitmapFormat(virBitmapPtr bitmap)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 bool first = true;
 int start, cur, prev;
 
diff --git a/src/util/vircommand.c b/src/util/vircommand.c
index aae0ddb730..e21116b232 100644
--- a/src/util/vircommand.c
+++ b/src/util/vircommand.c
@@ -2080,7 +2080,7 @@ char *
 virCommandToString(virCommandPtr cmd, bool linebreaks)
 {
 size_t i;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 bool prevopt = false;
 
 /* Cannot assume virCommandRun will be called; so report the error
@@ -2101,7 +2101,6 @@ virCommandToString(virCommandPtr cmd, bool linebreaks)
 char *eq = strchr(cmd->env[i], '=');
 
 if (!eq) {
-virBufferFreeAndReset();
 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("invalid use of command API"));
 return NULL;
diff --git a/src/util/virconf.c b/src/util/virconf.c
index f79024f07a..77ca3f9b79 100644
--- a/src/util/virconf.c
+++ b/src/util/virconf.c
@@ -1419,7 +1419,7 @@ int virConfWalk(virConfPtr conf,
 int
 virConfWriteFile(const char *filename, virConfPtr conf)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virConfEntryPtr cur;
 int ret;
 int fd;
@@ -1437,7 +1437,6 @@ virConfWriteFile(const char *filename, virConfPtr conf)
 
 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
 if (fd < 0) {
-virBufferFreeAndReset();
 virConfError(NULL, VIR_ERR_WRITE_FAILED, _("failed to open file"));
 return -1;
 }
@@ -1471,7 +1470,7 @@ virConfWriteFile(const char *filename, virConfPtr conf)
 int
 virConfWriteMem(char *memory, int *len, virConfPtr conf)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virConfEntryPtr cur;
 char *content;
 unsigned int use;
diff --git a/src/util/virdnsmasq.c b/src/util/virdnsmasq.c
index 818219fbeb..b22d4622d5 100644
--- a/src/util/virdnsmasq.c
+++ b/src/util/virdnsmasq.c
@@ -139,7 +139,7 @@ addnhostsNew(const char *name,
  const char *config_dir)
 {
 dnsmasqAddnHostsfile *addnhostsfile;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 if (VIR_ALLOC(addnhostsfile) < 0)
 return NULL;
@@ -157,7 +157,6 @@ addnhostsNew(const char *name,
 return addnhostsfile;
 
  error:
-virBufferFreeAndReset();
 addnhostsFree(addnhostsfile);
 return NULL;
 }
@@ -342,7 +341,7 @@ hostsfileNew(const char *name,
  const char *config_dir)
 {
 dnsmasqHostsfile *hostsfile;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 if (VIR_ALLOC(hostsfile) < 0)
 return NULL;
@@ -359,7 +358,6 @@ hostsfileNew(const char *name,
 return hostsfile;
 
  error:
-virBufferFreeAndReset();
 hostsfileFree(hostsfile);
 return NULL;
 }
diff --git a/src/util/virfile.c b/src/util/virfile.c
index c034df5931..213acdbcaa 100644
--- a/src/util/virfile.c
+++ b/src/util/virfile.c
@@ -1303,7 +1303,7 @@ int
 virBuildPathInternal(char **path, ...)
 {
 char *path_component = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 va_list ap;
 int ret = 0;
 
diff --git a/src/util/virfilecache.c b/src/util/virfilecache.c
index 2162917b11..195587e6bd 100644
--- a/src/util/virfilecache.c
+++ b/src/util/virfilecache.c
@@ -101,7 +101,7 @@ virFileCacheGetFileName(virFileCachePtr cache,

[PATCH 23/32] util: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/util/virqemu.c   |  8 ++--
 src/util/virsocketaddr.c | 22 +++---
 src/util/virxml.c|  8 ++--
 3 files changed, 11 insertions(+), 27 deletions(-)

diff --git a/src/util/virqemu.c b/src/util/virqemu.c
index 52f3a2ca12..486b8e03db 100644
--- a/src/util/virqemu.c
+++ b/src/util/virqemu.c
@@ -361,16 +361,12 @@ char *
 virQEMUBuildDriveCommandlineFromJSON(virJSONValuePtr srcdef)
 {
 g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
-char *ret = NULL;
 
 if (virQEMUBuildCommandLineJSON(srcdef, , NULL, false,
 virQEMUBuildCommandLineJSONArrayNumbered) 
< 0)
-goto cleanup;
-
-ret = virBufferContentAndReset();
+return NULL;
 
- cleanup:
-return ret;
+return virBufferContentAndReset();
 }
 
 
diff --git a/src/util/virsocketaddr.c b/src/util/virsocketaddr.c
index 0fda8e101b..e0eb76ded3 100644
--- a/src/util/virsocketaddr.c
+++ b/src/util/virsocketaddr.c
@@ -1265,16 +1265,15 @@ virSocketAddrPTRDomain(const virSocketAddr *addr,
 {
 g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t i;
-int ret = -1;
 
 if (VIR_SOCKET_ADDR_IS_FAMILY(addr, AF_INET)) {
 virSocketAddrIPv4 ip;
 
 if (prefix == 0 || prefix >= 32 || prefix % 8 != 0)
-goto unsupported;
+return -2;
 
 if (virSocketAddrGetIPv4Addr(addr, ) < 0)
-goto cleanup;
+return -1;
 
 for (i = prefix / 8; i > 0; i--)
 virBufferAsprintf(, "%u.", ip[i - 1]);
@@ -1284,30 +1283,23 @@ virSocketAddrPTRDomain(const virSocketAddr *addr,
 virSocketAddrIPv6Nibbles ip;
 
 if (prefix == 0 || prefix >= 128 || prefix % 4 != 0)
-goto unsupported;
+return -2;
 
 if (virSocketAddrGetIPv6Nibbles(addr, ) < 0)
-goto cleanup;
+return -1;
 
 for (i = prefix / 4; i > 0; i--)
 virBufferAsprintf(, "%x.", ip[i - 1]);
 
 virBufferAddLit(, VIR_SOCKET_ADDR_IPV6_ARPA);
 } else {
-goto unsupported;
+return -2;
 }
 
 if (!(*ptr = virBufferContentAndReset()))
-goto cleanup;
-
-ret = 0;
-
- cleanup:
-return ret;
+return -1;
 
- unsupported:
-ret = -2;
-goto cleanup;
+return 0;
 }
 
 void
diff --git a/src/util/virxml.c b/src/util/virxml.c
index 56e6f67597..5558b3829f 100644
--- a/src/util/virxml.c
+++ b/src/util/virxml.c
@@ -1271,19 +1271,15 @@ int
 virXMLValidatorValidate(virXMLValidatorPtr validator,
 xmlDocPtr doc)
 {
-int ret = -1;
-
 if (xmlRelaxNGValidateDoc(validator->rngValid, doc) != 0) {
 virReportError(VIR_ERR_XML_INVALID_SCHEMA,
_("Unable to validate doc against %s\n%s"),
validator->schemafile,
virBufferCurrentContent(>buf));
-goto cleanup;
+return -1;
 }
 
-ret = 0;
- cleanup:
-return ret;
+return 0;
 }
 
 
-- 
2.25.4



[PATCH 19/32] libxml: eliminate extra copy of string

2020-07-05 Thread Laine Stump
libxlMakeNic was calling g_strdup(virBufferCurrentContent()) to
make a copy of the buffer contents, and then later freeing the buffer
without ever using it again. Instead of this extra strdup, just
transfer ownership of the virBuffer's string with
virBufferContentAndReset(), and be done with it.

Signed-off-by: Laine Stump 
---
 src/libxl/libxl_conf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/libxl/libxl_conf.c b/src/libxl/libxl_conf.c
index 124e08d598..fe8ad4a3cb 100644
--- a/src/libxl/libxl_conf.c
+++ b/src/libxl/libxl_conf.c
@@ -1335,7 +1335,7 @@ libxlMakeNic(virDomainDefPtr def,
 }
 }
 }
-x_nic->bridge = g_strdup(virBufferCurrentContent());
+x_nic->bridge = virBufferContentAndReset();
 G_GNUC_FALLTHROUGH;
 case VIR_DOMAIN_NET_TYPE_ETHERNET:
 x_nic->script = g_strdup(script);
-- 
2.25.4



[PATCH 20/32] bhyve: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/bhyve/bhyve_command.c | 25 ++---
 1 file changed, 10 insertions(+), 15 deletions(-)

diff --git a/src/bhyve/bhyve_command.c b/src/bhyve/bhyve_command.c
index 9649c2d2a2..22d0b24ec4 100644
--- a/src/bhyve/bhyve_command.c
+++ b/src/bhyve/bhyve_command.c
@@ -169,7 +169,6 @@ bhyveBuildAHCIControllerArgStr(const virDomainDef *def,
 g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 const char *disk_source;
 size_t i;
-int ret = -1;
 
 for (i = 0; i < def->ndisks; i++) {
 g_auto(virBuffer) device = VIR_BUFFER_INITIALIZER;
@@ -187,11 +186,11 @@ bhyveBuildAHCIControllerArgStr(const virDomainDef *def,
 (virDomainDiskGetType(disk) != VIR_STORAGE_TYPE_VOLUME)) {
 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
_("unsupported disk type"));
-goto error;
+return -1;
 }
 
 if (virDomainDiskTranslateSourcePool(disk) < 0)
-goto error;
+return -1;
 
 disk_source = virDomainDiskGetSource(disk);
 
@@ -200,7 +199,7 @@ bhyveBuildAHCIControllerArgStr(const virDomainDef *def,
 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
_("cdrom device without source path "
  "not supported"));
-goto error;
+return -1;
 }
 
 switch (disk->device) {
@@ -219,7 +218,7 @@ bhyveBuildAHCIControllerArgStr(const virDomainDef *def,
 default:
 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
_("unsupported disk device"));
-goto error;
+return -1;
 }
 virBufferAddBuffer(, );
 }
@@ -229,9 +228,7 @@ bhyveBuildAHCIControllerArgStr(const virDomainDef *def,
controller->info.addr.pci.slot,
virBufferCurrentContent());
 
-ret = 0;
- error:
-return ret;
+return 0;
 }
 
 static int
@@ -406,7 +403,7 @@ bhyveBuildGraphicsArgStr(const virDomainDef *def,
 if (!(glisten = virDomainGraphicsGetListen(graphics, 0))) {
 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("Missing listen element"));
-goto error;
+return -1;
 }
 
 virBufferAsprintf(, "%d:%d,fbuf", video->info.addr.pci.slot, 
video->info.addr.pci.function);
@@ -421,13 +418,13 @@ bhyveBuildGraphicsArgStr(const virDomainDef *def,
  graphics->data.vnc.port > 65535)) {
 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
_("vnc port must be in range [5900,65535]"));
-goto error;
+return -1;
 }
 
 if (graphics->data.vnc.auth.passwd) {
 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
_("vnc password auth not supported"));
-goto error;
+return -1;
 } else {
  /* Bhyve doesn't support VNC Auth yet, so print a warning about
   * unauthenticated VNC sessions */
@@ -461,11 +458,11 @@ bhyveBuildGraphicsArgStr(const virDomainDef *def,
 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NONE:
 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
_("Unsupported listen type"));
-goto error;
+return -1;
 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_LAST:
 default:
 virReportEnumRangeError(virDomainGraphicsListenType, glisten->type);
-goto error;
+return -1;
 }
 
 if (video->driver)
@@ -476,8 +473,6 @@ bhyveBuildGraphicsArgStr(const virDomainDef *def,
 virCommandAddArgBuffer(cmd, );
 return 0;
 
- error:
-return -1;
 }
 
 virCommandPtr
-- 
2.25.4



[PATCH 09/32] conf: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/conf/capabilities.c  |  8 +++-
 src/conf/checkpoint_conf.c   |  2 +-
 src/conf/cpu_conf.c  |  9 +++--
 src/conf/domain_addr.c   |  2 +-
 src/conf/domain_capabilities.c   |  2 +-
 src/conf/domain_conf.c   | 12 ++--
 src/conf/interface_conf.c|  7 +++
 src/conf/network_conf.c  |  3 +--
 src/conf/node_device_conf.c  |  2 +-
 src/conf/nwfilter_conf.c |  7 +++
 src/conf/secret_conf.c   |  3 +--
 src/conf/snapshot_conf.c |  2 +-
 src/conf/storage_capabilities.c  |  6 ++
 src/conf/storage_conf.c  | 11 ---
 src/conf/virnetworkobj.c |  3 +--
 src/conf/virnetworkportdef.c |  6 ++
 src/conf/virnwfilterbindingdef.c |  6 ++
 src/conf/virnwfilterbindingobj.c |  6 ++
 src/conf/virsavecookie.c |  3 +--
 19 files changed, 39 insertions(+), 61 deletions(-)

diff --git a/src/conf/capabilities.c b/src/conf/capabilities.c
index 99b69aebb5..6a48af1fca 100644
--- a/src/conf/capabilities.c
+++ b/src/conf/capabilities.c
@@ -705,7 +705,7 @@ virCapabilitiesDomainDataLookupInternal(virCapsPtr caps,
 
 /* XXX check default_emulator, see how it uses this */
 if (!foundguest) {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 if (ostype)
 virBufferAsprintf(, "ostype=%s ",
   virDomainOSTypeToString(ostype));
@@ -725,7 +725,6 @@ virCapabilitiesDomainDataLookupInternal(virCapsPtr caps,
 virReportError(VIR_ERR_INVALID_ARG,
_("could not find capabilities for %s"),
virBufferCurrentContent());
-virBufferFreeAndReset();
 return ret;
 }
 
@@ -901,7 +900,7 @@ virCapabilitiesFormatResctrlMonitor(virBufferPtr buf,
 virResctrlInfoMonPtr monitor)
 {
 size_t i = 0;
-virBuffer childrenBuf = VIR_BUFFER_INIT_CHILD(buf);
+g_auto(virBuffer) childrenBuf = VIR_BUFFER_INIT_CHILD(buf);
 
 /* monitor not supported, no capability */
 if (!monitor)
@@ -1335,7 +1334,7 @@ virCapabilitiesFormatStoragePoolXML(virCapsStoragePoolPtr 
*pools,
 char *
 virCapabilitiesFormatXML(virCapsPtr caps)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 virBufferAddLit(, "\n\n");
 virBufferAdjustIndent(, 2);
@@ -1353,7 +1352,6 @@ virCapabilitiesFormatXML(virCapsPtr caps)
 return virBufferContentAndReset();
 
  error:
-virBufferFreeAndReset();
 return NULL;
 }
 
diff --git a/src/conf/checkpoint_conf.c b/src/conf/checkpoint_conf.c
index d557fada49..e0dce9c2ed 100644
--- a/src/conf/checkpoint_conf.c
+++ b/src/conf/checkpoint_conf.c
@@ -502,7 +502,7 @@ virDomainCheckpointDefFormat(virDomainCheckpointDefPtr def,
  virDomainXMLOptionPtr xmlopt,
  unsigned int flags)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 virCheckFlags(VIR_DOMAIN_CHECKPOINT_FORMAT_SECURE |
   VIR_DOMAIN_CHECKPOINT_FORMAT_NO_DOMAIN |
diff --git a/src/conf/cpu_conf.c b/src/conf/cpu_conf.c
index e1b0a5653f..dd3db00bc8 100644
--- a/src/conf/cpu_conf.c
+++ b/src/conf/cpu_conf.c
@@ -668,7 +668,7 @@ char *
 virCPUDefFormat(virCPUDefPtr def,
 virDomainNumaPtr numa)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 if (virCPUDefFormatBufFull(, def, numa) < 0)
 goto cleanup;
@@ -676,7 +676,6 @@ virCPUDefFormat(virCPUDefPtr def,
 return virBufferContentAndReset();
 
  cleanup:
-virBufferFreeAndReset();
 return NULL;
 }
 
@@ -687,8 +686,8 @@ virCPUDefFormatBufFull(virBufferPtr buf,
virDomainNumaPtr numa)
 {
 int ret = -1;
-virBuffer attributeBuf = VIR_BUFFER_INITIALIZER;
-virBuffer childrenBuf = VIR_BUFFER_INIT_CHILD(buf);
+g_auto(virBuffer) attributeBuf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) childrenBuf = VIR_BUFFER_INIT_CHILD(buf);
 
 if (!def)
 return 0;
@@ -755,8 +754,6 @@ virCPUDefFormatBufFull(virBufferPtr buf,
 
 ret = 0;
  cleanup:
-virBufferFreeAndReset();
-virBufferFreeAndReset();
 return ret;
 }
 
diff --git a/src/conf/domain_addr.c b/src/conf/domain_addr.c
index 2f9ff899d7..1068cbf1d2 100644
--- a/src/conf/domain_addr.c
+++ b/src/conf/domain_addr.c
@@ -1941,7 +1941,7 @@ virDomainUSBAddressPortFormatBuf(virBufferPtr buf,
 static char * ATTRIBUTE_NONNULL(1)
 virDomainUSBAddressPortFormat(unsigned int *port)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virDomainUSBAddressPortFormatBuf(, port);
 return virBufferContentAndReset();
 }
diff --git a/src/conf/domain_capabilities.c b/src/conf/domain_capabilities.c
in

[PATCH 30/32] storage: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/storage/storage_util.c | 5 +
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/src/storage/storage_util.c b/src/storage/storage_util.c
index 36b5b21a5b..9f46ea764b 100644
--- a/src/storage/storage_util.c
+++ b/src/storage/storage_util.c
@@ -749,7 +749,7 @@ 
storageBackendCreateQemuImgOpts(virStorageEncryptionInfoDefPtr encinfo,
_("lazy_refcounts not supported with compat"
  " level %s"),
info->compat);
-goto error;
+return -1;
 }
 virBufferAddLit(, "lazy_refcounts,");
 }
@@ -759,9 +759,6 @@ 
storageBackendCreateQemuImgOpts(virStorageEncryptionInfoDefPtr encinfo,
 
 *opts = virBufferContentAndReset();
 return 0;
-
- error:
-return -1;
 }
 
 
-- 
2.25.4



[PATCH 18/32] remove redundant calls to virBufferFreeAndReset()

2020-07-05 Thread Laine Stump
There are several calls to virBufferFreeAndReset() when functions
encounter an error, but the caller never uses the virBuffer once an
error has been encountered (all callers detect error by looking at the
function return value, not the contents of the virBuffer being
operated on), and now that all virBuffers are auto-freed there is no
reason for the lower level functions like these to spend time freeing
a buffer that is guaranteed to be freed momentarily anyway.

Signed-off-by: Laine Stump 
---
 src/conf/checkpoint_conf.c | 1 -
 src/conf/domain_conf.c | 1 -
 src/conf/snapshot_conf.c   | 1 -
 src/libxl/xen_xl.c | 1 -
 src/util/virsysinfo.c  | 1 -
 src/util/virxml.c  | 1 -
 6 files changed, 6 deletions(-)

diff --git a/src/conf/checkpoint_conf.c b/src/conf/checkpoint_conf.c
index e0dce9c2ed..41f67bd895 100644
--- a/src/conf/checkpoint_conf.c
+++ b/src/conf/checkpoint_conf.c
@@ -493,7 +493,6 @@ virDomainCheckpointDefFormatInternal(virBufferPtr buf,
 return 0;
 
  error:
-virBufferFreeAndReset(buf);
 return -1;
 }
 
diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index 33bf0a1727..e5070ed871 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -30038,7 +30038,6 @@ virDomainDefFormatInternalSetRootName(virDomainDefPtr 
def,
 return 0;
 
  error:
-virBufferFreeAndReset(buf);
 return -1;
 }
 
diff --git a/src/conf/snapshot_conf.c b/src/conf/snapshot_conf.c
index 9767592bfc..b7ed3b42df 100644
--- a/src/conf/snapshot_conf.c
+++ b/src/conf/snapshot_conf.c
@@ -916,7 +916,6 @@ virDomainSnapshotDefFormatInternal(virBufferPtr buf,
 return 0;
 
  error:
-virBufferFreeAndReset(buf);
 return -1;
 }
 
diff --git a/src/libxl/xen_xl.c b/src/libxl/xen_xl.c
index ec5e4791a3..4baf5e336e 100644
--- a/src/libxl/xen_xl.c
+++ b/src/libxl/xen_xl.c
@@ -1432,7 +1432,6 @@ xenFormatXLVnode(virConfValuePtr list,
 ret = 0;
 
  cleanup:
-virBufferFreeAndReset(buf);
 return ret;
 }
 
diff --git a/src/util/virsysinfo.c b/src/util/virsysinfo.c
index dbca99c1ef..e69fc51a1e 100644
--- a/src/util/virsysinfo.c
+++ b/src/util/virsysinfo.c
@@ -1581,7 +1581,6 @@ virSysinfoFormat(virBufferPtr buf, virSysinfoDefPtr def)
 virReportError(VIR_ERR_INTERNAL_ERROR,
_("unexpected sysinfo type model %d"),
def->type);
-virBufferFreeAndReset(buf);
 return -1;
 }
 
diff --git a/src/util/virxml.c b/src/util/virxml.c
index e9ea9fe1a4..56e6f67597 100644
--- a/src/util/virxml.c
+++ b/src/util/virxml.c
@@ -1283,7 +1283,6 @@ virXMLValidatorValidate(virXMLValidatorPtr validator,
 
 ret = 0;
  cleanup:
-virBufferFreeAndReset(>buf);
 return ret;
 }
 
-- 
2.25.4



[PATCH 25/32] tools: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 tools/virsh-pool.c | 13 ++---
 1 file changed, 6 insertions(+), 7 deletions(-)

diff --git a/tools/virsh-pool.c b/tools/virsh-pool.c
index 885e000ed2..622b1396d0 100644
--- a/tools/virsh-pool.c
+++ b/tools/virsh-pool.c
@@ -330,9 +330,10 @@ virshBuildPoolXML(vshControl *ctl,
 VSH_EXCLUSIVE_OPTIONS("secret-usage", "secret-uuid");
 
 if (vshCommandOptStringReq(ctl, cmd, "name", ) < 0)
-goto cleanup;
+return false;
+
 if (vshCommandOptStringReq(ctl, cmd, "type", ) < 0)
-goto cleanup;
+return false;
 
 if (vshCommandOptStringReq(ctl, cmd, "source-host", ) < 0 ||
 vshCommandOptStringReq(ctl, cmd, "source-path", ) < 0 ||
@@ -351,8 +352,9 @@ virshBuildPoolXML(vshControl *ctl,
 vshCommandOptStringReq(ctl, cmd, "adapter-parent-wwnn", 
) < 0 ||
 vshCommandOptStringReq(ctl, cmd, "adapter-parent-wwpn", 
) < 0 ||
 vshCommandOptStringReq(ctl, cmd, "adapter-parent-fabric-wwn", 
) < 0 ||
-vshCommandOptStringReq(ctl, cmd, "source-protocol-ver", ) < 0)
-goto cleanup;
+vshCommandOptStringReq(ctl, cmd, "source-protocol-ver", ) < 
0) {
+return false;
+}
 
 virBufferAsprintf(, "\n", type);
 virBufferAdjustIndent(, 2);
@@ -419,9 +421,6 @@ virshBuildPoolXML(vshControl *ctl,
 *xml = virBufferContentAndReset();
 *retname = name;
 return true;
-
- cleanup:
-return false;
 }
 
 /*
-- 
2.25.4



[PATCH 16/32] qemu: remove unnecessary virBufferFreeAndReset() after virCommandAddArgBuffer()

2020-07-05 Thread Laine Stump
The latter function is guaranteed to always clear out the virBuffer
anyway, so this is redundant and could add to extra cargo-cult code if
used as an example.

Signed-off-by: Laine Stump 
---
 src/qemu/qemu_command.c | 1 -
 1 file changed, 1 deletion(-)

diff --git a/src/qemu/qemu_command.c b/src/qemu/qemu_command.c
index 789c5b8f56..73c6997a49 100644
--- a/src/qemu/qemu_command.c
+++ b/src/qemu/qemu_command.c
@@ -8913,7 +8913,6 @@ qemuBuldDomainLoaderPflashCommandLine(virCommandPtr cmd,
 virCommandAddArgBuffer(cmd, );
 
 if (loader->nvram) {
-virBufferFreeAndReset();
 virBufferAddLit(, "file=");
 virQEMUBuildBufferEscapeComma(, loader->nvram);
 virBufferAsprintf(, ",if=pflash,format=raw,unit=%d", unit);
-- 
2.25.4



[PATCH 29/32] nwfilter: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_ebiptables_driver.c | 89 +++
 1 file changed, 43 insertions(+), 46 deletions(-)

diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index dad631f03b..6cdb3ca45e 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -1797,7 +1797,6 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
 const char *target;
 bool hasMask = false;
 virFirewallRulePtr fwrule;
-int ret = -1;
 g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 if (STREQ(chainSuffix,
@@ -1813,7 +1812,7 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
 if (printDataType(vars, \
   field, sizeof(field), \
   >p.STRUCT.ITEM) < 0) \
-goto cleanup; \
+return -1; \
 virFirewallRuleAddArg(fw, fwrule, CLI); \
 if (ENTRY_WANT_NEG_SIGN(>p.STRUCT.ITEM)) \
 virFirewallRuleAddArg(fw, fwrule, "!"); \
@@ -1825,7 +1824,7 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
 if (printDataType(vars, \
   field, sizeof(field), \
   >p.STRUCT.ITEM) < 0) \
-goto cleanup; \
+return -1; \
 virFirewallRuleAddArg(fw, fwrule, CLI); \
 if (ENTRY_WANT_NEG_SIGN(>p.STRUCT.ITEM)) \
 virFirewallRuleAddArg(fw, fwrule, "!"); \
@@ -1833,7 +1832,7 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
 if (printDataType(vars, \
   fieldalt, sizeof(fieldalt), \
   >p.STRUCT.ITEM_HI) < 0) \
-goto cleanup; \
+return -1; \
 virFirewallRuleAddArgFormat(fw, fwrule, \
 "%s%s%s", field, SEP, fieldalt); \
 } else  { \
@@ -1855,13 +1854,13 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
  vars,
  >p.ethHdrFilter.ethHdr,
  reverse) < 0)
-goto cleanup;
+return -1;
 
 if (HAS_ENTRY_ITEM(>p.ethHdrFilter.dataProtocolID)) {
 if (printDataTypeAsHex(vars,
number, sizeof(number),
>p.ethHdrFilter.dataProtocolID) < 0)
-goto cleanup;
+return -1;
 virFirewallRuleAddArg(fw, fwrule, "-p");
 if (ENTRY_WANT_NEG_SIGN(>p.ethHdrFilter.dataProtocolID))
 virFirewallRuleAddArg(fw, fwrule, "!");
@@ -1877,7 +1876,7 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
  vars,
  >p.vlanHdrFilter.ethHdr,
  reverse) < 0)
-goto cleanup;
+return -1;
 
 virFirewallRuleAddArgList(fw, fwrule,
   "-p", "0x8100", NULL);
@@ -1906,7 +1905,7 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
  vars,
  >p.stpHdrFilter.ethHdr,
  reverse) < 0)
-goto cleanup;
+return -1;
 
 virFirewallRuleAddArgList(fw, fwrule,
   "-d",  NWFILTER_MAC_BGA, NULL);
@@ -1942,7 +1941,7 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
  vars,
  >p.arpHdrFilter.ethHdr,
  reverse) < 0)
-goto cleanup;
+return -1;
 
 virFirewallRuleAddArg(fw, fwrule, "-p");
 virFirewallRuleAddArgFormat(fw, fwrule, "0x%x",
@@ -1954,7 +1953,7 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
 if (printDataType(vars,
   number, sizeof(number),
   >p.arpHdrFilter.dataHWType) < 0)
-goto cleanup;
+return -1;
 virFirewallRuleAddArg(fw, fwrule, "--arp-htype");
 if (ENTRY_WANT_NEG_SIGN(>p.arpHdrFilter.dataHWType))
 virFirewallRuleAddArg(fw, fwrule, "!");
@@ -1965,7 +1964,7 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
 if (printDataType(vars,
   number, sizeof(number),
   >p.arpHdrFilter.dataOpcode) < 0)
-goto cleanup;
+return -1;
 virFirewallRuleAddArg(fw, fwrule, "--arp-opcode");
 if (ENTRY_WANT_NEG_SIGN(>p.arpHdrFilter.dataOpcode))

[PATCH 11/32] cpu: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/cpu/cpu_map.c | 2 +-
 src/cpu/cpu_x86.c | 6 +++---
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/cpu/cpu_map.c b/src/cpu/cpu_map.c
index 4465ebfa7b..d14488f8aa 100644
--- a/src/cpu/cpu_map.c
+++ b/src/cpu/cpu_map.c
@@ -171,7 +171,7 @@ int cpuMapLoad(const char *arch,
 {
 xmlDocPtr xml = NULL;
 xmlXPathContextPtr ctxt = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char *xpath = NULL;
 int ret = -1;
 char *mapfile;
diff --git a/src/cpu/cpu_x86.c b/src/cpu/cpu_x86.c
index bf26cf4e76..1e5cd93abb 100644
--- a/src/cpu/cpu_x86.c
+++ b/src/cpu/cpu_x86.c
@@ -972,7 +972,7 @@ x86FeatureNames(virCPUx86MapPtr map,
 const char *separator,
 virCPUx86Data *data)
 {
-virBuffer ret = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) ret = VIR_BUFFER_INITIALIZER;
 bool first = true;
 size_t i;
 
@@ -1208,7 +1208,7 @@ virCPUx86SignaturesMatch(virCPUx86SignaturesPtr sigs,
 static char *
 virCPUx86SignaturesFormat(virCPUx86SignaturesPtr sigs)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t i;
 
 if (!sigs)
@@ -1707,7 +1707,7 @@ virCPUx86DataFormat(const virCPUData *data)
 {
 virCPUx86DataIterator iter;
 virCPUx86DataItemPtr item;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 virCPUx86DataIteratorInit(, >data.x86);
 
-- 
2.25.4



[PATCH 24/32] tests: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 tests/virbuftest.c | 35 ++-
 1 file changed, 14 insertions(+), 21 deletions(-)

diff --git a/tests/virbuftest.c b/tests/virbuftest.c
index 39ae7c2b9d..df341be50c 100644
--- a/tests/virbuftest.c
+++ b/tests/virbuftest.c
@@ -100,7 +100,6 @@ static int testBufTrim(const void *data G_GNUC_UNUSED)
 virBufferPtr buf = NULL;
 g_autofree char *result = NULL;
 const char *expected = "a,b";
-int ret = -1;
 
 virBufferTrim(buf, "");
 buf = 
@@ -120,13 +119,10 @@ static int testBufTrim(const void *data G_GNUC_UNUSED)
 result = virBufferContentAndReset(buf);
 if (!result || STRNEQ(result, expected)) {
 virTestDifference(stderr, expected, result);
-goto cleanup;
+return -1;
 }
 
-ret = 0;
-
- cleanup:
-return ret;
+return 0;
 }
 
 static int
@@ -158,7 +154,6 @@ static int testBufAddBuffer(const void *data G_GNUC_UNUSED)
 g_auto(virBuffer) buf1 = VIR_BUFFER_INITIALIZER;
 g_auto(virBuffer) buf2 = VIR_BUFFER_INITIALIZER;
 g_auto(virBuffer) buf3 = VIR_BUFFER_INITIALIZER;
-int ret = -1;
 g_autofree char *result = NULL;
 const char *expected = \
 "  A long time ago, in a galaxy far,\n" \
@@ -178,17 +173,17 @@ static int testBufAddBuffer(const void *data 
G_GNUC_UNUSED)
 
 if (virBufferUse()) {
 VIR_TEST_DEBUG("buf1 already in use");
-goto cleanup;
+return -1;
 }
 
 if (virBufferUse()) {
 VIR_TEST_DEBUG("buf2 already in use");
-goto cleanup;
+return -1;
 }
 
 if (virBufferUse()) {
 VIR_TEST_DEBUG("buf3 already in use");
-goto cleanup;
+return -1;
 }
 
 virBufferAdjustIndent(, 2);
@@ -213,52 +208,50 @@ static int testBufAddBuffer(const void *data 
G_GNUC_UNUSED)
 
 if (!virBufferUse()) {
 VIR_TEST_DEBUG("Error adding to buf1");
-goto cleanup;
+return -1;
 }
 
 if (!virBufferUse()) {
 VIR_TEST_DEBUG("Error adding to buf2");
-goto cleanup;
+return -1;
 }
 
 if (!virBufferUse()) {
 VIR_TEST_DEBUG("Error adding to buf3");
-goto cleanup;
+return -1;
 }
 
 virBufferAddBuffer(, );
 
 if (!virBufferUse()) {
 VIR_TEST_DEBUG("buf2 cleared mistakenly");
-goto cleanup;
+return -1;
 }
 
 if (virBufferUse()) {
 VIR_TEST_DEBUG("buf3 is not clear even though it should be");
-goto cleanup;
+return -1;
 }
 
 virBufferAddBuffer(, );
 
 if (!virBufferUse()) {
 VIR_TEST_DEBUG("buf1 cleared mistakenly");
-goto cleanup;
+return -1;
 }
 
 if (virBufferUse()) {
 VIR_TEST_DEBUG("buf2 is not clear even though it should be");
-goto cleanup;
+return -1;
 }
 
 result = virBufferContentAndReset();
 if (STRNEQ_NULLABLE(result, expected)) {
 virTestDifference(stderr, expected, result);
-goto cleanup;
+return -1;
 }
 
-ret = 0;
- cleanup:
-return ret;
+return 0;
 }
 
 static int
-- 
2.25.4



[PATCH 04/32] libxl: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/libxl/libxl_conf.c  |  6 ++
 src/libxl/libxl_driver.c|  2 +-
 src/libxl/libxl_migration.c |  2 +-
 src/libxl/xen_common.c  | 12 +---
 src/libxl/xen_xl.c  | 19 +++
 src/libxl/xen_xm.c  |  3 +--
 6 files changed, 17 insertions(+), 27 deletions(-)

diff --git a/src/libxl/libxl_conf.c b/src/libxl/libxl_conf.c
index a0059fc2a7..124e08d598 100644
--- a/src/libxl/libxl_conf.c
+++ b/src/libxl/libxl_conf.c
@@ -911,7 +911,7 @@ libxlMakeNetworkDiskSrcStr(virStorageSourcePtr src,
const char *secret)
 {
 char *ret = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t i;
 
 switch ((virStorageNetProtocol) src->protocol) {
@@ -978,7 +978,6 @@ libxlMakeNetworkDiskSrcStr(virStorageSourcePtr src,
 }
 
  cleanup:
-virBufferFreeAndReset();
 return ret;
 }
 
@@ -1241,7 +1240,7 @@ libxlMakeNic(virDomainDefPtr def,
 const virNetDevBandwidth *actual_bw;
 const virNetDevVPortProfile *port_profile;
 const virNetDevVlan *virt_vlan;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t i;
 const char *script = NULL;
 int ret = -1;
@@ -1434,7 +1433,6 @@ libxlMakeNic(virDomainDefPtr def,
 ret = 0;
 
  cleanup:
-virBufferFreeAndReset();
 virObjectUnref(network);
 virObjectUnref(conn);
 
diff --git a/src/libxl/libxl_driver.c b/src/libxl/libxl_driver.c
index a80bc3fe3a..9b9713df2c 100644
--- a/src/libxl/libxl_driver.c
+++ b/src/libxl/libxl_driver.c
@@ -942,7 +942,7 @@ static char *
 libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
 {
 libxlDriverPrivatePtr driver = conn->privateData;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 virCheckFlags(0, NULL);
 
diff --git a/src/libxl/libxl_migration.c b/src/libxl/libxl_migration.c
index 9d253346eb..87cd5337ba 100644
--- a/src/libxl/libxl_migration.c
+++ b/src/libxl/libxl_migration.c
@@ -117,7 +117,7 @@ libxlMigrationBakeCookie(libxlMigrationCookiePtr mig,
  char **cookieout,
  int *cookieoutlen)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char uuidstr[VIR_UUID_STRING_BUFLEN];
 
 if (!cookieout || !cookieoutlen)
diff --git a/src/libxl/xen_common.c b/src/libxl/xen_common.c
index 5c37e431eb..6b16752c8a 100644
--- a/src/libxl/xen_common.c
+++ b/src/libxl/xen_common.c
@@ -1633,7 +1633,7 @@ xenFormatSxprChr(virDomainChrDefPtr def,
 static int
 xenFormatSerial(virConfValuePtr list, virDomainChrDefPtr serial)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virConfValuePtr val, tmp;
 int ret;
 
@@ -1661,7 +1661,6 @@ xenFormatSerial(virConfValuePtr list, virDomainChrDefPtr 
serial)
 return 0;
 
  cleanup:
-virBufferFreeAndReset();
 return -1;
 }
 
@@ -1694,7 +1693,7 @@ xenFormatNet(virConnectPtr conn,
  int hvm,
  const char *vif_typename)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virConfValuePtr val, tmp;
 char macaddr[VIR_MAC_STRING_BUFLEN];
 
@@ -1826,7 +1825,6 @@ xenFormatNet(virConnectPtr conn,
 return 0;
 
  cleanup:
-virBufferFreeAndReset();
 return -1;
 }
 
@@ -2034,7 +2032,7 @@ xenFormatCharDev(virConfPtr conf, virDomainDefPtr def,
 
 if (def->os.type == VIR_DOMAIN_OSTYPE_HVM) {
 if (def->nparallels) {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char *str;
 int ret;
 
@@ -2052,7 +2050,7 @@ xenFormatCharDev(virConfPtr conf, virDomainDefPtr def,
 
 if (def->nserials) {
 if ((def->nserials == 1) && (def->serials[0]->target.port == 0)) {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char *str;
 int ret;
 
@@ -2329,7 +2327,7 @@ xenFormatVfb(virConfPtr conf, virDomainDefPtr def)
 } else {
 virConfValuePtr vfb, disp;
 char *vfbstr = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 if (def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL) {
 virBufferAddLit(, "type=sdl");
diff --git a/src/libxl/xen_xl.c b/src/libxl/xen_xl.c
index d40c2e1d8e..ec5e4791a3 100644
--- a/src/libxl/xen_xl.c
+++ b/src/libxl/xen_xl.c
@@ -1445,7 +1445,7 @@ xenFormatXLVnuma(virConfValuePtr list,
 int ret = -1;
 size_t i;
 
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virCon

[PATCH 07/32] tests: use g_auto for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 tests/commandtest.c  |  3 +--
 tests/cputest.c  |  2 +-
 tests/networkxml2firewalltest.c  |  3 +--
 tests/nodedevmdevctltest.c   |  6 ++
 tests/nwfilterebiptablestest.c   | 21 +++--
 tests/nwfilterxml2firewalltest.c |  3 +--
 tests/qemublocktest.c|  2 +-
 tests/qemucommandutiltest.c  |  2 +-
 tests/qemumigparamstest.c|  6 ++
 tests/qemumonitorjsontest.c  |  9 -
 tests/qemumonitortestutils.c |  2 +-
 tests/testutils.c|  2 +-
 tests/vboxsnapshotxmltest.c  |  3 +--
 tests/virbuftest.c   | 23 ++-
 tests/vircgrouptest.c|  3 +--
 tests/virfirewalltest.c  | 30 ++
 tests/virhostcputest.c   |  3 +--
 tests/virkmodtest.c  |  4 ++--
 tests/virnetdevbandwidthtest.c   |  3 +--
 19 files changed, 49 insertions(+), 81 deletions(-)

diff --git a/tests/commandtest.c b/tests/commandtest.c
index d5092b7dd0..f0e60ee5fe 100644
--- a/tests/commandtest.c
+++ b/tests/commandtest.c
@@ -390,7 +390,7 @@ static int test9(const void *unused G_GNUC_UNUSED)
 {
 virCommandPtr cmd = virCommandNew(abs_builddir "/commandhelper");
 const char* const args[] = { "arg1", "arg2", NULL };
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 virCommandAddArg(cmd, "-version");
 virCommandAddArgPair(cmd, "-log", "bar.log");
@@ -402,7 +402,6 @@ static int test9(const void *unused G_GNUC_UNUSED)
 
 if (virBufferUse()) {
 printf("Buffer not transferred\n");
-virBufferFreeAndReset();
 virCommandFree(cmd);
 return -1;
 }
diff --git a/tests/cputest.c b/tests/cputest.c
index 0cf6870574..83d63bf495 100644
--- a/tests/cputest.c
+++ b/tests/cputest.c
@@ -237,7 +237,7 @@ cpuTestGuestCPU(const void *arg)
 virCPUDefPtr host = NULL;
 virCPUDefPtr cpu = NULL;
 virCPUCompareResult cmpResult;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char *result = NULL;
 
 if (!(host = cpuTestLoadXML(data->arch, data->host)) ||
diff --git a/tests/networkxml2firewalltest.c b/tests/networkxml2firewalltest.c
index 69fadd55c4..29e7d8bc38 100644
--- a/tests/networkxml2firewalltest.c
+++ b/tests/networkxml2firewalltest.c
@@ -62,7 +62,7 @@ static int testCompareXMLToArgvFiles(const char *xml,
  const char *baseargs)
 {
 char *actualargv = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virNetworkDefPtr def = NULL;
 int ret = -1;
 char *actual;
@@ -92,7 +92,6 @@ static int testCompareXMLToArgvFiles(const char *xml,
 ret = 0;
 
  cleanup:
-virBufferFreeAndReset();
 VIR_FREE(actualargv);
 virNetworkDefFree(def);
 return ret;
diff --git a/tests/nodedevmdevctltest.c b/tests/nodedevmdevctltest.c
index f5bcf5227d..9780553a3a 100644
--- a/tests/nodedevmdevctltest.c
+++ b/tests/nodedevmdevctltest.c
@@ -54,7 +54,7 @@ testMdevctlStart(const char *virt_type,
 {
 g_autoptr(virNodeDeviceDef) def = NULL;
 virNodeDeviceObjPtr obj = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 const char *actualCmdline = NULL;
 int ret = -1;
 g_autofree char *uuid = NULL;
@@ -87,7 +87,6 @@ testMdevctlStart(const char *virt_type,
 ret = 0;
 
  cleanup:
-virBufferFreeAndReset();
 virCommandSetDryRun(NULL, NULL, NULL);
 virNodeDeviceObjEndAPI();
 return ret;
@@ -114,7 +113,7 @@ static int
 testMdevctlStop(const void *data)
 {
 const char *uuid = data;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 const char *actualCmdline = NULL;
 int ret = -1;
 g_autoptr(virCommand) cmd = NULL;
@@ -140,7 +139,6 @@ testMdevctlStop(const void *data)
 ret = 0;
 
  cleanup:
-virBufferFreeAndReset();
 virCommandSetDryRun(NULL, NULL, NULL);
 return ret;
 }
diff --git a/tests/nwfilterebiptablestest.c b/tests/nwfilterebiptablestest.c
index 3e6c335d4e..4d8791023c 100644
--- a/tests/nwfilterebiptablestest.c
+++ b/tests/nwfilterebiptablestest.c
@@ -68,7 +68,7 @@
 static int
 testNWFilterEBIPTablesAllTeardown(const void *opaque G_GNUC_UNUSED)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 const char *expected =
 VIR_NWFILTER_NEW_RULES_TEARDOWN
 "iptables -D libvirt-out -m physdev --physdev-is-bridged --physdev-out 
vnet0 -g FO-vnet0\n"
@@ -120,7 +120,6 @@ testNWFilterEBIPTablesAllTeardown(const void *opaque 
G_GNUC_UNUSED)
 ret = 0;
  cleanup:
 virCommandSetDryRun(NULL, NULL, NULL);
-virBufferFreeAndReset();
 VIR_FREE(actual);
 return ret;
 }
@

[PATCH 17/32] conf: consistently check for error when calling virSysinfoFormat()

2020-07-05 Thread Laine Stump
Every other caller of this function checks for an error return and
ends their formatting early if there is an error. This function
happily continues on its way.

Signed-off-by: Laine Stump 
---
 src/conf/domain_conf.c | 6 --
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index c02d1c8bd2..33bf0a1727 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -29649,8 +29649,10 @@ virDomainDefFormatInternalSetRootName(virDomainDefPtr 
def,
 if (def->resource)
 virDomainResourceDefFormat(buf, def->resource);
 
-for (i = 0; i < def->nsysinfo; i++)
-virSysinfoFormat(buf, def->sysinfo[i]);
+for (i = 0; i < def->nsysinfo; i++) {
+if (virSysinfoFormat(buf, def->sysinfo[i]) < 0)
+goto error;
+}
 
 if (def->os.bootloader) {
 virBufferEscapeString(buf, "%s\n",
-- 
2.25.4



[PATCH 32/32] eliminate unnecessary labels and ret variables

2020-07-05 Thread Laine Stump
after making all virFirewall objects use g_autoptr().

Signed-off-by: Laine Stump 
---
 src/network/bridge_driver_linux.c | 27 +++
 src/nwfilter/nwfilter_ebiptables_driver.c | 32 +++
 src/util/virebtables.c| 16 ++--
 src/util/viriptables.c|  8 ++
 4 files changed, 22 insertions(+), 61 deletions(-)

diff --git a/src/network/bridge_driver_linux.c 
b/src/network/bridge_driver_linux.c
index f72f94f38d..5fc77785dc 100644
--- a/src/network/bridge_driver_linux.c
+++ b/src/network/bridge_driver_linux.c
@@ -839,7 +839,6 @@ int networkAddFirewallRules(virNetworkDefPtr def)
 size_t i;
 virNetworkIPDefPtr ipdef;
 g_autoptr(virFirewall) fw = virFirewallNew();
-int ret = -1;
 
 if (virOnce(, networkSetupPrivateChains) < 0)
 return -1;
@@ -869,11 +868,11 @@ int networkAddFirewallRules(virNetworkDefPtr def)
_("zone %s requested for network %s "
  "but firewalld is not active"),
def->bridgeZone, def->name);
-goto cleanup;
+return -1;
 }
 
 if (virFirewallDInterfaceSetZone(def->bridge, def->bridgeZone) < 0)
-goto cleanup;
+return -1;
 
 } else {
 
@@ -893,13 +892,13 @@ int networkAddFirewallRules(virNetworkDefPtr def)
  */
 if (virFirewallDZoneExists("libvirt")) {
 if (virFirewallDInterfaceSetZone(def->bridge, "libvirt") < 0)
-goto cleanup;
+return -1;
 } else {
 unsigned long version;
 int vresult = virFirewallDGetVersion();
 
 if (vresult < 0)
-goto cleanup;
+return -1;
 
 /* Support for nftables backend was added in firewalld
  * 0.6.0. Support for rule priorities (required by the
@@ -919,7 +918,7 @@ int networkAddFirewallRules(virNetworkDefPtr def)
  "version supporting rule priorities "
  "(0.7.0+) and/or rebuilding "
  "libvirt with --with-firewalld-zone"));
-goto cleanup;
+return -1;
 }
 }
 }
@@ -933,7 +932,7 @@ int networkAddFirewallRules(virNetworkDefPtr def)
  (ipdef = virNetworkDefGetIPByIndex(def, AF_UNSPEC, i));
  i++) {
 if (networkAddIPSpecificFirewallRules(fw, def, ipdef) < 0)
-goto cleanup;
+return -1;
 }
 
 virFirewallStartRollback(fw, 0);
@@ -942,19 +941,14 @@ int networkAddFirewallRules(virNetworkDefPtr def)
  (ipdef = virNetworkDefGetIPByIndex(def, AF_UNSPEC, i));
  i++) {
 if (networkRemoveIPSpecificFirewallRules(fw, def, ipdef) < 0)
-goto cleanup;
+return -1;
 }
 networkRemoveGeneralFirewallRules(fw, def);
 
 virFirewallStartTransaction(fw, VIR_FIREWALL_TRANSACTION_IGNORE_ERRORS);
 networkAddChecksumFirewallRules(fw, def);
 
-if (virFirewallApply(fw) < 0)
-goto cleanup;
-
-ret = 0;
- cleanup:
-return ret;
+return virFirewallApply(fw);
 }
 
 /* Remove all rules for all ip addresses (and general rules) on a network */
@@ -973,12 +967,9 @@ void networkRemoveFirewallRules(virNetworkDefPtr def)
  (ipdef = virNetworkDefGetIPByIndex(def, AF_UNSPEC, i));
  i++) {
 if (networkRemoveIPSpecificFirewallRules(fw, def, ipdef) < 0)
-goto cleanup;
+return;
 }
 networkRemoveGeneralFirewallRules(fw, def);
 
 virFirewallApply(fw);
-
- cleanup:
-return;
 }
diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index 2976521e6d..78a52408b2 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -2866,7 +2866,7 @@ ebtablesApplyBasicRules(const char *ifname,
 virMacAddrFormat(macaddr, macaddr_str);
 
 if (ebiptablesAllTeardown(ifname) < 0)
-goto error;
+return -1;
 
 virFirewallStartTransaction(fw, 0);
 
@@ -2899,7 +2899,6 @@ ebtablesApplyBasicRules(const char *ifname,
 
  tear_down_tmpebchains:
 ebtablesCleanAll(ifname);
- error:
 return -1;
 }
 
@@ -2937,7 +2936,7 @@ ebtablesApplyDHCPOnlyRules(const char *ifname,
 virMacAddrFormat(macaddr, macaddr_str);
 
 if (ebiptablesAllTeardown(ifname) < 0)
-goto error;
+return -1;
 
 virFirewallStartTransaction(fw, 0);
 
@@ -3016,7 +3015,6 @@ ebtablesApplyDHCPOnlyRules(const char *ifname,
 
  tear_down_tmpebchains:
 ebtablesCleanAll(ifname);
- error:
 return -1;
 }
 
@@ -3038,7 +3036,7 @@ ebtablesApplyDropAllRules(const char *ifname)
 

[PATCH 13/32] nwfilter: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_ebiptables_driver.c | 8 +++-
 src/nwfilter/nwfilter_gentech_driver.c| 6 ++
 src/nwfilter/nwfilter_learnipaddr.c   | 2 +-
 3 files changed, 6 insertions(+), 10 deletions(-)

diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index 6fc8044c8d..dad631f03b 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -190,7 +190,7 @@ _printDataType(virNWFilterVarCombIterPtr vars,
 bool done;
 char *data;
 uint8_t ctr;
-virBuffer vb = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) vb = VIR_BUFFER_INITIALIZER;
 char *flags;
 
 if (printVar(vars, buf, bufsize, item, ) < 0)
@@ -1528,7 +1528,7 @@ _iptablesCreateRuleInstance(virFirewallPtr fw,
 static int
 printStateMatchFlags(int32_t flags, char **bufptr)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virNWFilterPrintStateMatchFlags(,
 "",
 flags,
@@ -1798,7 +1798,7 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
 bool hasMask = false;
 virFirewallRulePtr fwrule;
 int ret = -1;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 if (STREQ(chainSuffix,
   virNWFilterChainSuffixTypeToString(
@@ -2423,8 +2423,6 @@ ebtablesCreateRuleInstance(virFirewallPtr fw,
 
 ret = 0;
  cleanup:
-virBufferFreeAndReset();
-
 return ret;
 }
 
diff --git a/src/nwfilter/nwfilter_gentech_driver.c 
b/src/nwfilter/nwfilter_gentech_driver.c
index 6789a4a3fa..b7633eb10a 100644
--- a/src/nwfilter/nwfilter_gentech_driver.c
+++ b/src/nwfilter/nwfilter_gentech_driver.c
@@ -426,15 +426,13 @@ virNWFilterDetermineMissingVarsRec(virNWFilterDefPtr 
filter,
 if (!virNWFilterVarAccessIsAvailable(rule->varAccess[j],
  vars)) {
 char *varAccess;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 virNWFilterVarAccessPrint(rule->varAccess[j], );
 
 val = virNWFilterVarValueCreateSimpleCopyValue("1");
-if (!val) {
-virBufferFreeAndReset();
+if (!val)
 return -1;
-}
 
 varAccess = virBufferContentAndReset();
 rc = virHashUpdateEntry(missing_vars, varAccess, val);
diff --git a/src/nwfilter/nwfilter_learnipaddr.c 
b/src/nwfilter/nwfilter_learnipaddr.c
index 4ce8d5ba03..14c66cff35 100644
--- a/src/nwfilter/nwfilter_learnipaddr.c
+++ b/src/nwfilter/nwfilter_learnipaddr.c
@@ -397,7 +397,7 @@ learnIPAddressThread(void *arg)
req->binding->portdevname);
 int dhcp_opts_len;
 char macaddr[VIR_MAC_STRING_BUFLEN];
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char *filter = NULL;
 uint16_t etherType;
 bool showError = true;
-- 
2.25.4



[PATCH 03/32] hyperv: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/hyperv/hyperv_driver.c | 34 --
 src/hyperv/hyperv_wmi.c| 11 +--
 2 files changed, 21 insertions(+), 24 deletions(-)

diff --git a/src/hyperv/hyperv_driver.c b/src/hyperv/hyperv_driver.c
index 4677a25ff8..20d372b274 100644
--- a/src/hyperv/hyperv_driver.c
+++ b/src/hyperv/hyperv_driver.c
@@ -60,7 +60,7 @@ static int
 hypervInitConnection(virConnectPtr conn, hypervPrivate *priv,
  char *username, char *password)
 {
-virBuffer query = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) query = VIR_BUFFER_INITIALIZER;
 hypervWqlQuery wqlQuery = HYPERV_WQL_QUERY_INITIALIZER;
 hypervObject *computerSystem = NULL;
 int ret = -1;
@@ -204,7 +204,7 @@ hypervConnectGetHostname(virConnectPtr conn)
 {
 char *hostname = NULL;
 hypervPrivate *priv = conn->privateData;
-virBuffer query = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) query = VIR_BUFFER_INITIALIZER;
 Win32_ComputerSystem *computerSystem = NULL;
 
 virBufferAddLit(, WIN32_COMPUTERSYSTEM_WQL_SELECT);
@@ -234,7 +234,7 @@ hypervNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
 {
 int result = -1;
 hypervPrivate *priv = conn->privateData;
-virBuffer query = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) query = VIR_BUFFER_INITIALIZER;
 Win32_ComputerSystem *computerSystem = NULL;
 Win32_Processor *processorList = NULL;
 Win32_Processor *processor = NULL;
@@ -329,7 +329,7 @@ hypervConnectListDomains(virConnectPtr conn, int *ids, int 
maxids)
 {
 bool success = false;
 hypervPrivate *priv = conn->privateData;
-virBuffer query = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) query = VIR_BUFFER_INITIALIZER;
 Msvm_ComputerSystem *computerSystemList = NULL;
 Msvm_ComputerSystem *computerSystem = NULL;
 int count = 0;
@@ -371,7 +371,7 @@ hypervConnectNumOfDomains(virConnectPtr conn)
 {
 bool success = false;
 hypervPrivate *priv = conn->privateData;
-virBuffer query = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) query = VIR_BUFFER_INITIALIZER;
 Msvm_ComputerSystem *computerSystemList = NULL;
 Msvm_ComputerSystem *computerSystem = NULL;
 int count = 0;
@@ -407,7 +407,7 @@ hypervDomainLookupByID(virConnectPtr conn, int id)
 {
 virDomainPtr domain = NULL;
 hypervPrivate *priv = conn->privateData;
-virBuffer query = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) query = VIR_BUFFER_INITIALIZER;
 Msvm_ComputerSystem *computerSystem = NULL;
 
 virBufferAddLit(, MSVM_COMPUTERSYSTEM_WQL_SELECT);
@@ -439,7 +439,7 @@ hypervDomainLookupByUUID(virConnectPtr conn, const unsigned 
char *uuid)
 virDomainPtr domain = NULL;
 hypervPrivate *priv = conn->privateData;
 char uuid_string[VIR_UUID_STRING_BUFLEN];
-virBuffer query = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) query = VIR_BUFFER_INITIALIZER;
 Msvm_ComputerSystem *computerSystem = NULL;
 
 virUUIDFormat(uuid, uuid_string);
@@ -473,7 +473,7 @@ hypervDomainLookupByName(virConnectPtr conn, const char 
*name)
 {
 virDomainPtr domain = NULL;
 hypervPrivate *priv = conn->privateData;
-virBuffer query = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) query = VIR_BUFFER_INITIALIZER;
 Msvm_ComputerSystem *computerSystem = NULL;
 
 virBufferAddLit(, MSVM_COMPUTERSYSTEM_WQL_SELECT);
@@ -612,7 +612,7 @@ hypervDomainGetInfo(virDomainPtr domain, virDomainInfoPtr 
info)
 int result = -1;
 hypervPrivate *priv = domain->conn->privateData;
 char uuid_string[VIR_UUID_STRING_BUFLEN];
-virBuffer query = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) query = VIR_BUFFER_INITIALIZER;
 Msvm_ComputerSystem *computerSystem = NULL;
 Msvm_VirtualSystemSettingData *virtualSystemSettingData = NULL;
 Msvm_ProcessorSettingData *processorSettingData = NULL;
@@ -746,7 +746,7 @@ hypervDomainGetXMLDesc(virDomainPtr domain, unsigned int 
flags)
 hypervPrivate *priv = domain->conn->privateData;
 virDomainDefPtr def = NULL;
 char uuid_string[VIR_UUID_STRING_BUFLEN];
-virBuffer query = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) query = VIR_BUFFER_INITIALIZER;
 Msvm_ComputerSystem *computerSystem = NULL;
 Msvm_VirtualSystemSettingData *virtualSystemSettingData = NULL;
 Msvm_ProcessorSettingData *processorSettingData = NULL;
@@ -851,7 +851,7 @@ hypervDomainGetXMLDesc(virDomainPtr domain, unsigned int 
flags)
 } else if (priv->wmiVersion == HYPERV_WMI_VERSION_V2 &&
virtualSystemSettingData->data.v2->Notes.data != NULL) {
 char **notes = (char **)virtualSystemSettingData->data.v2->Notes.data;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t i = 0;
 
 /* in practice Notes has 1 element */
@@ -906,7 +906,7 @@ hypervConnectListDefinedDomains(virConnectPtr conn, ch

[PATCH 26/32] network: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c | 16 ++--
 1 file changed, 6 insertions(+), 10 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 9f37d8f558..713763130b 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -1842,7 +1842,6 @@ networkRadvdConfContents(virNetworkObjPtr obj,
 {
 virNetworkDefPtr def = virNetworkObjGetDef(obj);
 g_auto(virBuffer) configbuf = VIR_BUFFER_INITIALIZER;
-int ret = -1;
 size_t i;
 virNetworkIPDefPtr ipdef;
 bool v6present = false, dhcp6 = false;
@@ -1859,10 +1858,8 @@ networkRadvdConfContents(virNetworkObjPtr obj,
 }
 
 /* If there are no IPv6 addresses, then we are done */
-if (!v6present) {
-ret = 0;
-goto cleanup;
-}
+if (!v6present)
+return 0;
 
 /* create radvd config file appropriate for this network;
  * IgnoreIfMissing allows radvd to start even when the bridge is down
@@ -1887,10 +1884,11 @@ networkRadvdConfContents(virNetworkObjPtr obj,
 virReportError(VIR_ERR_INTERNAL_ERROR,
_("bridge '%s' has an invalid prefix"),
def->bridge);
-goto cleanup;
+return -1;
 }
 if (!(netaddr = virSocketAddrFormat(>address)))
-goto cleanup;
+return -1;
+
 virBufferAsprintf(,
   "  prefix %s/%d\n"
   "  {\n%s  };\n",
@@ -1903,9 +1901,7 @@ networkRadvdConfContents(virNetworkObjPtr obj,
 
 *configstr = virBufferContentAndReset();
 
-ret = 0;
- cleanup:
-return ret;
+return 0;
 }
 
 
-- 
2.25.4



[PATCH 22/32] libxl: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/libxl/libxl_conf.c | 11 ---
 src/libxl/xen_common.c | 16 +---
 src/libxl/xen_xl.c | 25 -
 src/libxl/xen_xm.c |  7 ++-
 4 files changed, 19 insertions(+), 40 deletions(-)

diff --git a/src/libxl/libxl_conf.c b/src/libxl/libxl_conf.c
index fe8ad4a3cb..02cc5e6f1b 100644
--- a/src/libxl/libxl_conf.c
+++ b/src/libxl/libxl_conf.c
@@ -910,7 +910,6 @@ libxlMakeNetworkDiskSrcStr(virStorageSourcePtr src,
const char *username,
const char *secret)
 {
-char *ret = NULL;
 g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t i;
 
@@ -931,14 +930,14 @@ libxlMakeNetworkDiskSrcStr(virStorageSourcePtr src,
 virReportError(VIR_ERR_NO_SUPPORT,
_("Unsupported network block protocol '%s'"),
virStorageNetProtocolTypeToString(src->protocol));
-goto cleanup;
+return NULL;
 
 case VIR_STORAGE_NET_PROTOCOL_RBD:
 if (strchr(src->path, ':')) {
 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
_("':' not allowed in RBD source volume name '%s'"),
src->path);
-goto cleanup;
+return NULL;
 }
 
 virBufferStrcat(, "rbd:", src->volume, "/", src->path, NULL);
@@ -973,12 +972,10 @@ libxlMakeNetworkDiskSrcStr(virStorageSourcePtr src,
 if (src->configFile)
 virBufferEscape(, '\\', ":", ":conf=%s", src->configFile);
 
-ret = virBufferContentAndReset();
-break;
+return virBufferContentAndReset();
 }
 
- cleanup:
-return ret;
+return NULL;
 }
 
 static int
diff --git a/src/libxl/xen_common.c b/src/libxl/xen_common.c
index 6b16752c8a..475c64f944 100644
--- a/src/libxl/xen_common.c
+++ b/src/libxl/xen_common.c
@@ -1640,13 +1640,13 @@ xenFormatSerial(virConfValuePtr list, 
virDomainChrDefPtr serial)
 if (serial) {
 ret = xenFormatSxprChr(serial, );
 if (ret < 0)
-goto cleanup;
+return -1;
 } else {
 virBufferAddLit(, "none");
 }
 
 if (VIR_ALLOC(val) < 0)
-goto cleanup;
+return -1;
 
 val->type = VIR_CONF_STRING;
 val->str = virBufferContentAndReset();
@@ -1659,9 +1659,6 @@ xenFormatSerial(virConfValuePtr list, virDomainChrDefPtr 
serial)
 list->list = val;
 
 return 0;
-
- cleanup:
-return -1;
 }
 
 char *
@@ -1781,12 +1778,12 @@ xenFormatNet(virConnectPtr conn,
 case VIR_DOMAIN_NET_TYPE_USER:
 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, _("Unsupported net type 
'%s'"),
virDomainNetTypeToString(net->type));
-goto cleanup;
+return -1;
 
 case VIR_DOMAIN_NET_TYPE_LAST:
 default:
 virReportEnumRangeError(virDomainNetType, net->type);
-goto cleanup;
+return -1;
 }
 
 if (virDomainNetGetModelString(net)) {
@@ -1810,7 +1807,7 @@ xenFormatNet(virConnectPtr conn,
 virBufferAsprintf(, ",rate=%lluKB/s", 
net->bandwidth->out->average);
 
 if (VIR_ALLOC(val) < 0)
-goto cleanup;
+return -1;
 
 val->type = VIR_CONF_STRING;
 val->str = virBufferContentAndReset();
@@ -1823,9 +1820,6 @@ xenFormatNet(virConnectPtr conn,
 list->list = val;
 
 return 0;
-
- cleanup:
-return -1;
 }
 
 
diff --git a/src/libxl/xen_xl.c b/src/libxl/xen_xl.c
index 4baf5e336e..b81c5d23ce 100644
--- a/src/libxl/xen_xl.c
+++ b/src/libxl/xen_xl.c
@@ -1412,11 +1412,10 @@ static int
 xenFormatXLVnode(virConfValuePtr list,
  virBufferPtr buf)
 {
-int ret = -1;
 virConfValuePtr numaPnode, tmp;
 
 if (VIR_ALLOC(numaPnode) < 0)
-goto cleanup;
+return -1;
 
 /* Place VNODE directive */
 numaPnode->type = VIR_CONF_STRING;
@@ -1429,10 +1428,8 @@ xenFormatXLVnode(virConfValuePtr list,
 tmp->next = numaPnode;
 else
 list->list = numaPnode;
-ret = 0;
 
- cleanup:
-return ret;
+return 0;
 }
 
 static int
@@ -1561,7 +1558,6 @@ xenFormatXLXenbusLimits(virConfPtr conf, virDomainDefPtr 
def)
 static char *
 xenFormatXLDiskSrcNet(virStorageSourcePtr src)
 {
-char *ret = NULL;
 g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t i;
 
@@ -1582,14 +1578,14 @@ xenFormatXLDiskSrcNet(virStorageSourcePtr src)
 virReportError(VIR_ERR_NO_SUPPORT,
_("Unsupported network block protocol '%s'"),
virStorageNetProtocolTypeToString(src->protocol));
-goto cleanup;
+return NULL;
 
 case VIR_STORAGE_NET_PROTOCOL_RBD:
 if (strchr(src->path, ':')) {
 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
_(

[PATCH 08/32] tools: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 tools/virsh-checkpoint.c |  3 +-
 tools/virsh-domain-monitor.c |  3 +-
 tools/virsh-domain.c | 58 +---
 tools/virsh-pool.c   |  6 ++--
 tools/virsh-secret.c |  2 +-
 tools/virsh-snapshot.c   |  3 +-
 tools/virsh-volume.c |  3 +-
 tools/vsh-table.c|  2 +-
 tools/vsh.c  | 15 --
 9 files changed, 42 insertions(+), 53 deletions(-)

diff --git a/tools/virsh-checkpoint.c b/tools/virsh-checkpoint.c
index 853fe05fc4..821212f86b 100644
--- a/tools/virsh-checkpoint.c
+++ b/tools/virsh-checkpoint.c
@@ -235,7 +235,7 @@ cmdCheckpointCreateAs(vshControl *ctl,
 char *buffer = NULL;
 const char *name = NULL;
 const char *desc = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 unsigned int flags = 0;
 const vshCmdOpt *opt = NULL;
 
@@ -278,7 +278,6 @@ cmdCheckpointCreateAs(vshControl *ctl,
 ret = virshCheckpointCreate(ctl, dom, buffer, flags, NULL);
 
  cleanup:
-virBufferFreeAndReset();
 VIR_FREE(buffer);
 virshDomainFree(dom);
 
diff --git a/tools/virsh-domain-monitor.c b/tools/virsh-domain-monitor.c
index 9b8c69fa9d..d8333a2f44 100644
--- a/tools/virsh-domain-monitor.c
+++ b/tools/virsh-domain-monitor.c
@@ -2413,7 +2413,7 @@ cmdDomIfAddr(vshControl *ctl, const vshCmd *cmd)
 }
 
 for (j = 0; j < iface->naddrs; j++) {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 switch (iface->addrs[j].type) {
 case VIR_IP_ADDR_TYPE_IPV4:
@@ -2442,7 +2442,6 @@ cmdDomIfAddr(vshControl *ctl, const vshCmd *cmd)
 vshPrint(ctl, " %-10s %-17s%s\n",
  "-", "-", ip_addr_str);
 
-virBufferFreeAndReset();
 VIR_FREE(ip_addr_str);
 }
 }
diff --git a/tools/virsh-domain.c b/tools/virsh-domain.c
index 085b88b097..f0f3456b77 100644
--- a/tools/virsh-domain.c
+++ b/tools/virsh-domain.c
@@ -575,7 +575,7 @@ cmdAttachDisk(vshControl *ctl, const vshCmd *cmd)
 int ret;
 unsigned int flags = VIR_DOMAIN_AFFECT_CURRENT;
 const char *stype = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char *xml = NULL;
 struct stat st;
 bool current = vshCommandOptBool(cmd, "current");
@@ -778,7 +778,6 @@ cmdAttachDisk(vshControl *ctl, const vshCmd *cmd)
  cleanup:
 VIR_FREE(xml);
 virshDomainFree(dom);
-virBufferFreeAndReset();
 return functionReturn;
 }
 
@@ -905,7 +904,7 @@ cmdAttachInterface(vshControl *ctl, const vshCmd *cmd)
 virDomainNetType typ;
 int ret;
 bool functionReturn = false;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char *xml = NULL;
 unsigned int flags = VIR_DOMAIN_AFFECT_CURRENT;
 bool current = vshCommandOptBool(cmd, "current");
@@ -1091,7 +1090,6 @@ cmdAttachInterface(vshControl *ctl, const vshCmd *cmd)
  cleanup:
 VIR_FREE(xml);
 virshDomainFree(dom);
-virBufferFreeAndReset();
 return functionReturn;
 }
 
@@ -2412,7 +2410,7 @@ cmdBlockcopy(vshControl *ctl, const vshCmd *cmd)
 }
 
 if (!xmlstr) {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virBufferAsprintf(, "\n",
   blockdev ? "block" : "file");
 virBufferAdjustIndent(, 2);
@@ -8504,7 +8502,7 @@ cmdDesc(vshControl *ctl, const vshCmd *cmd)
 char *tmp = NULL;
 char *tmpstr;
 const vshCmdOpt *opt = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 bool ret = false;
 unsigned int flags = VIR_DOMAIN_AFFECT_CURRENT;
 
@@ -9642,7 +9640,7 @@ cmdQemuMonitorCommand(vshControl *ctl, const vshCmd *cmd)
 g_autoptr(virJSONValue) resultjson = NULL;
 unsigned int flags = 0;
 const vshCmdOpt *opt = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 bool pretty = vshCommandOptBool(cmd, "pretty");
 bool returnval = vshCommandOptBool(cmd, "return-value");
 virJSONValuePtr formatjson;
@@ -9956,7 +9954,7 @@ cmdQemuAgentCommand(vshControl *ctl, const vshCmd *cmd)
 int judge = 0;
 unsigned int flags = 0;
 const vshCmdOpt *opt = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virJSONValuePtr pretty = NULL;
 
 dom = virshCommandOptDomain(ctl, cmd, NULL);
@@ -11506,7 +11504,7 @@ cmdDomDisplay(vshControl *ctl, const vshCmd *cmd)
 xmlDocPtr xml = NULL;
 xmlXPathContextPtr ctxt = NULL;
 virDomainPtr dom;
-virBuffer buf = VIR_BUFFER_INI

[PATCH 15/32] use g_auto() for all remaining non-g_auto() virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/hypervisor/domain_driver.c | 7 +++
 src/locking/lock_driver_sanlock.c  | 2 +-
 src/node_device/node_device_udev.c | 2 +-
 src/openvz/openvz_driver.c | 5 ++---
 src/security/virt-aa-helper.c  | 4 ++--
 src/storage/storage_backend_rbd.c  | 7 ++-
 src/storage/storage_util.c | 9 -
 src/vmx/vmx.c  | 5 +
 src/vz/vz_driver.c | 4 ++--
 9 files changed, 18 insertions(+), 27 deletions(-)

diff --git a/src/hypervisor/domain_driver.c b/src/hypervisor/domain_driver.c
index 31821fc712..f5f0f6e2e9 100644
--- a/src/hypervisor/domain_driver.c
+++ b/src/hypervisor/domain_driver.c
@@ -86,7 +86,7 @@ virDomainDriverGenerateMachineName(const char *drivername,
const char *name,
bool privileged)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 if (root) {
 g_autofree char *hash = NULL;
@@ -100,10 +100,9 @@ virDomainDriverGenerateMachineName(const char *drivername,
 if (!privileged) {
 
 g_autofree char *username = NULL;
-if (!(username = virGetUserName(geteuid( {
-virBufferFreeAndReset();
+if (!(username = virGetUserName(geteuid(
 return NULL;
-}
+
 virBufferAsprintf(, "%s-", username);
 }
 }
diff --git a/src/locking/lock_driver_sanlock.c 
b/src/locking/lock_driver_sanlock.c
index 4ebe98e86d..23711a75cb 100644
--- a/src/locking/lock_driver_sanlock.c
+++ b/src/locking/lock_driver_sanlock.c
@@ -825,7 +825,7 @@ virLockManagerSanlockRegisterKillscript(int sock,
 const char *uuidstr,
 virDomainLockFailureAction action)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char *path;
 char *args = NULL;
 int ret = -1;
diff --git a/src/node_device/node_device_udev.c 
b/src/node_device/node_device_udev.c
index cec99cb898..e389b56302 100644
--- a/src/node_device/node_device_udev.c
+++ b/src/node_device/node_device_udev.c
@@ -294,7 +294,7 @@ udevGenerateDeviceName(struct udev_device *device,
const char *s)
 {
 size_t i;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 virBufferAsprintf(, "%s_%s",
   udev_device_get_subsystem(device),
diff --git a/src/openvz/openvz_driver.c b/src/openvz/openvz_driver.c
index 79a100c343..71e270ea09 100644
--- a/src/openvz/openvz_driver.c
+++ b/src/openvz/openvz_driver.c
@@ -704,7 +704,7 @@ openvzDomainSetNetwork(virConnectPtr conn, const char 
*vpsid,
 if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
 (net->type == VIR_DOMAIN_NET_TYPE_ETHERNET &&
  net->guestIP.nips == 0)) {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer)buf = VIR_BUFFER_INITIALIZER;
 int veid = openvzGetVEID(vpsid);
 
 /* if net is ethernet and the user has specified guest interface name,
@@ -782,7 +782,7 @@ openvzDomainSetNetworkConfig(virConnectPtr conn,
  virDomainDefPtr def)
 {
 size_t i;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 char *param;
 int first = 1;
 struct openvz_driver *driver =  conn->privateData;
@@ -819,7 +819,6 @@ openvzDomainSetNetworkConfig(virConnectPtr conn,
 return 0;
 
  exit:
-virBufferFreeAndReset();
 return -1;
 }
 
diff --git a/src/security/virt-aa-helper.c b/src/security/virt-aa-helper.c
index 08eb162b8c..dadb9d1614 100644
--- a/src/security/virt-aa-helper.c
+++ b/src/security/virt-aa-helper.c
@@ -907,7 +907,7 @@ storage_source_add_files(virStorageSourcePtr src,
 static int
 get_files(vahControl * ctl)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 int rc = -1;
 size_t i;
 char *uuid;
@@ -1448,7 +1448,6 @@ int
 main(int argc, char **argv)
 {
 vahControl _ctl, *ctl = &_ctl;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
 int rc = -1;
 char *profile = NULL;
 char *include_file = NULL;
@@ -1496,6 +1495,7 @@ main(int argc, char **argv)
 }
 } else if (ctl->cmd == 'c' || ctl->cmd == 'r') {
 char *included_files = NULL;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 if (ctl->cmd == 'c' && virFileExists(profile))
 vah_error(ctl, 1, _("profile exists"));
diff --git a/src/storage/storage_backend_rbd.c 
b/src/storage/storage_backend_rbd.c
index f0b7653736..08dc5a19dc 100644
--- a/src/storage/storage_backend_rbd.c
+++ b/src/storage/storage_backend_rbd.c
@@ -190,7 +190,7 @@ 
virStorageBackendRBDOpenRADOSConn(virStorageBackendRBDStatePtr ptr,

[PATCH 27/32] lxc: eliminate unnecessary labels

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/lxc/lxc_controller.c | 9 +++--
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/src/lxc/lxc_controller.c b/src/lxc/lxc_controller.c
index 01cdeb29db..ae6b737b60 100644
--- a/src/lxc/lxc_controller.c
+++ b/src/lxc/lxc_controller.c
@@ -1380,13 +1380,12 @@ virLXCControllerSetupUsernsMap(virDomainIdMapEntryPtr 
map,
 {
 g_auto(virBuffer) map_value = VIR_BUFFER_INITIALIZER;
 size_t i;
-int ret = -1;
 
 /* The kernel supports up to 340 lines in /proc//{g,u}id_map */
 if (num > 340) {
 virReportError(VIR_ERR_INVALID_ARG, "%s",
_("Too many id mappings defined."));
-goto cleanup;
+return -1;
 }
 
 for (i = 0; i < num; i++)
@@ -1397,12 +1396,10 @@ virLXCControllerSetupUsernsMap(virDomainIdMapEntryPtr 
map,
 
 if (virFileWriteStr(path, virBufferCurrentContent(_value), 0) < 0) {
 virReportSystemError(errno, _("unable write to %s"), path);
-goto cleanup;
+return -1;
 }
 
-ret = 0;
- cleanup:
-return ret;
+return 0;
 }
 
 /**
-- 
2.25.4



[PATCH 06/32] qemu: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/qemu/qemu_agent.c| 2 +-
 src/qemu/qemu_block.c| 2 +-
 src/qemu/qemu_capabilities.c | 2 +-
 src/qemu/qemu_command.c  | 4 ++--
 src/qemu/qemu_dbus.c | 2 +-
 src/qemu/qemu_domain.c   | 4 ++--
 src/qemu/qemu_driver.c   | 5 ++---
 src/qemu/qemu_migration.c| 2 +-
 src/qemu/qemu_migration_cookie.c | 6 ++
 src/qemu/qemu_monitor.c  | 2 +-
 10 files changed, 14 insertions(+), 17 deletions(-)

diff --git a/src/qemu/qemu_agent.c b/src/qemu/qemu_agent.c
index 6fa48c06e3..37b5451e33 100644
--- a/src/qemu/qemu_agent.c
+++ b/src/qemu/qemu_agent.c
@@ -155,7 +155,7 @@ static char *
 qemuAgentEscapeNonPrintable(const char *text)
 {
 size_t i;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 for (i = 0; text[i] != '\0'; i++) {
 if (text[i] == '\\')
 virBufferAddLit(, "");
diff --git a/src/qemu/qemu_block.c b/src/qemu/qemu_block.c
index b00694c96f..a727366373 100644
--- a/src/qemu/qemu_block.c
+++ b/src/qemu/qemu_block.c
@@ -3271,7 +3271,7 @@ qemuBlockStorageSourceNeedsStorageSliceLayer(const 
virStorageSource *src)
 char *
 qemuBlockStorageSourceGetCookieString(virStorageSourcePtr src)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t i;
 
 for (i = 0; i < src->ncookies; i++) {
diff --git a/src/qemu/qemu_capabilities.c b/src/qemu/qemu_capabilities.c
index efc42aac17..0cf9165ecc 100644
--- a/src/qemu/qemu_capabilities.c
+++ b/src/qemu/qemu_capabilities.c
@@ -4602,7 +4602,7 @@ virQEMUCapsFormatSEVInfo(virQEMUCapsPtr qemuCaps, 
virBufferPtr buf)
 char *
 virQEMUCapsFormatCache(virQEMUCapsPtr qemuCaps)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t i;
 
 virBufferAddLit(, "\n");
diff --git a/src/qemu/qemu_command.c b/src/qemu/qemu_command.c
index 6e7fd59561..789c5b8f56 100644
--- a/src/qemu/qemu_command.c
+++ b/src/qemu/qemu_command.c
@@ -5477,7 +5477,7 @@ qemuBuildRNGCommandLine(virLogManagerPtr logManager,
 
 for (i = 0; i < def->nrngs; i++) {
 g_autoptr(virJSONValue) props = NULL;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virDomainRNGDefPtr rng = def->rngs[i];
 g_autofree char *chardev = NULL;
 g_autofree char *devstr = NULL;
@@ -6155,7 +6155,7 @@ qemuBuildBootCommandLine(virCommandPtr cmd,
 if (def->os.dtb)
 virCommandAddArgList(cmd, "-dtb", def->os.dtb, NULL);
 if (def->os.slic_table) {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virCommandAddArg(cmd, "-acpitable");
 virBufferAddLit(, "sig=SLIC,file=");
 virQEMUBuildBufferEscapeComma(, def->os.slic_table);
diff --git a/src/qemu/qemu_dbus.c b/src/qemu/qemu_dbus.c
index 53f6c45986..51f6c94e3e 100644
--- a/src/qemu/qemu_dbus.c
+++ b/src/qemu/qemu_dbus.c
@@ -100,7 +100,7 @@ qemuDBusGetAddress(virQEMUDriverPtr driver,
 static int
 qemuDBusWriteConfig(const char *filename, const char *path)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 g_autofree char *config = NULL;
 
 virBufferAddLit(, "deviceType != VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL ||
@@ -6001,7 +6001,7 @@ qemuDomainDefFormatXMLInternal(virQEMUDriverPtr driver,
virCPUDefPtr origCPU,
unsigned int flags)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 if (qemuDomainDefFormatBufInternal(driver, qemuCaps, def, origCPU, flags, 
) < 0)
 return NULL;
diff --git a/src/qemu/qemu_driver.c b/src/qemu/qemu_driver.c
index a5b38b3d24..247baa9b8d 100644
--- a/src/qemu/qemu_driver.c
+++ b/src/qemu/qemu_driver.c
@@ -1272,7 +1272,7 @@ static char *
 qemuConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
 {
 virQEMUDriverPtr driver = conn->privateData;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 virCheckFlags(0, NULL);
 
@@ -14398,7 +14398,7 @@ 
qemuDomainSnapshotCreateInactiveExternal(virQEMUDriverPtr driver,
 virBitmapPtr created = NULL;
 g_autoptr(virQEMUDriverConfig) cfg = virQEMUDriverGetConfig(driver);
 int ret = -1;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 virDomainSnapshotDefPtr snapdef = virDomainSnapshotObjGetDef(snap);
 
 if (!(qemuImgPath = qemuFindQemuImgBinary(driver)))
@@ -14485,7 +14485,6 @@ 
qemuDomainSnapshotCreateInactiveExternal(virQEMUDriverPtr driver,
 ret = 0;
 
  cleanup:
-virBufferFreeAndReset();
 virCommandFree(cmd);
 
 /* unlink images if c

[PATCH 00/32] always use g_auto() for virBuffer and virFirewall objects

2020-07-05 Thread Laine Stump
Like most other things I do, this started as a distraction from
something else. I noticed that a function that took a virBufferPtr as
an argument was clearing that buffer on error, but most (but *not
all*) of its callers (which were the creators/owners of said
virBuffer) were already clearing the buffer object on error
anyway. Here's the original patch resulting from my seeing this in one
place:

  https://www.redhat.com/archives/libvir-list/2020-June/msg01163.html

In the example I saw, eliminating the extra clearing of the virBuffer
in the subordinate function would simplify the error-cleanup code for
that function, but it turned out the calling function *wasn't*
clearing the virBuffer when an error occurred.

Looking further, I saw this same pattern occurred in other places in
the code - a function would create a new buffer (with "virBuffer buf =
VIR_BUFFER_INITIALIZER;"), and clear/free that buffer when it was
finished *unless there was an error*, in which case some functions
would properly clear the buffer, and some would just return, I guess
assuming the caller that generated the error had cleared the buffer.

This not only makes the error cleanup logic in subordinate functions
messier, it seems philosophically wrong to me, it also sounds like a
memory leak just waiting to happen.

So I decided that the way it should more properly work is this:

1) all virBuffers should be declared with g_auto(virBuffer), so that
they are automatically cleared (with virBufferFreeAndReset()) when
that toplevel function declaring/initializing the buffer returns to
its caller.

2) subordinate functions called with the virBuffer object as an arg
should just leave the buffer in whatever state it was when the error
occurred. Since those functions don't use the virBuffer after the
error happens, and the caller doesn't look at anything in the
virBuffer to determine an error has occurred, this is completely safe.

(obvious exceptions to (2) are of course those functions whose main
intent is in fact to consume the virBuffer,
e.g. virBufferContentAndReset(), and virCommandAddArgBuffer())


Patches 01 - 15 handle part (1) - *all* declarations of virBuffer as
an automatic are changed to g_auto(virBuffer), and any
virBufferFreeAndReset() calls in those same functions are removed.

(I have it split into so many patches because virBuffer is used all
over the place, and I figured it would make it easier to backport just
one part of the entire set if needed when backported some unrelated
bugfix that only touched one of the many directories represented
here. I would happily squash together any group of patches anyone
wants, however).

Patches 16 and 17 fix a couple "one-off" anomolies in the code related
to virBuffers.

Patch 18 then takes care of point (2) above, by removing any
extraneous virBufferFreeAndReset() calls in subordinate functions that
are no longer necessary due to the guarantee that the toplevel will
cleanup after error.

Patches 19-30 just eliminate any labels (and associated "ret"
variables and "goto's) that have been rendered pointless by removal of
virBufferFreeAndReset().

Finally Patches 31 and 32 convert all usages of virFirewall to use
g_autoptr(). They are included in this same set because virFirewall
objects are often declared right next to virBuffer objects, so doing
those patches in a different order would have caused merge conflicts..

NB: In many of the cases where "virBuffer" was changed to
"g_auto(virBuffer)", it doesn't actually eliminate any code from the
function, due to the function *always* calling
virBufferContentAndReset() anyway. I considered not changing those
cases, but in the ended decided it was better to add g_auto() even in
those cases for two reasons:

1) consistency makes verification easier, and means someone a year
from now won't come up with the same idea and waste time verifying all
those cases of virBuffer don't need g_auto().

2) if those functions ever change to have an alternate return that
doesn't explicitly call virBufferContentAndReset(), they will still be
safe.

3) the extra overhead is very minimal; a small price to pay for (1)
and (2)


NB2: these patches aren't just academic code churning; they have fixed
some actual (well, theoretically actual) memory leaks, I just haven't
taken the time to try and track all of them down or document them,
because they only occur in error cases which will likely never
happen. One example from my notes:

  virStoragePoolSaveState calls
virStoragePoolDefFormatBuf which calls
  virStoragePoolSourceFormat, which errors, returns
virStoragePoolDefFormatBuf, returns
  virStoragePoolSaveState returns without freeing virBuffer

Laine Stump (32):
  bhyve: use g_auto() for all virBuffers
  esx: use g_auto() for all virBuffers
  hyperv: use g_auto() for all virBuffers
  libxl: use g_auto() for all virBuffers
  lxc: use g_auto() for all virBuffers
  qemu: use g_auto() for all virBuff

[PATCH 05/32] lxc: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/lxc/lxc_container.c  | 4 +---
 src/lxc/lxc_controller.c | 3 +--
 src/lxc/lxc_driver.c | 2 +-
 src/lxc/lxc_fuse.c   | 3 +--
 4 files changed, 4 insertions(+), 8 deletions(-)

diff --git a/src/lxc/lxc_container.c b/src/lxc/lxc_container.c
index c22b7b0709..24a3b6d626 100644
--- a/src/lxc/lxc_container.c
+++ b/src/lxc/lxc_container.c
@@ -174,7 +174,7 @@ static virCommandPtr 
lxcContainerBuildInitCmd(virDomainDefPtr vmDef,
 {
 char uuidstr[VIR_UUID_STRING_BUFLEN];
 virCommandPtr cmd;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 size_t i;
 
 /* 'container_ptys' must exclude the PTY associated with
@@ -185,7 +185,6 @@ static virCommandPtr 
lxcContainerBuildInitCmd(virDomainDefPtr vmDef,
 virReportError(VIR_ERR_INTERNAL_ERROR,
_("Expected a /dev path for '%s'"),
ttyPaths[i]);
-virBufferFreeAndReset();
 return NULL;
 }
 virBufferAdd(, ttyPaths[i] + 5, -1);
@@ -219,7 +218,6 @@ static virCommandPtr 
lxcContainerBuildInitCmd(virDomainDefPtr vmDef,
   vmDef->os.initenv[i]->value);
 }
 
-virBufferFreeAndReset();
 return cmd;
 }
 
diff --git a/src/lxc/lxc_controller.c b/src/lxc/lxc_controller.c
index 89f9773b2c..01cdeb29db 100644
--- a/src/lxc/lxc_controller.c
+++ b/src/lxc/lxc_controller.c
@@ -1378,7 +1378,7 @@ virLXCControllerSetupUsernsMap(virDomainIdMapEntryPtr map,
int num,
char *path)
 {
-virBuffer map_value = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) map_value = VIR_BUFFER_INITIALIZER;
 size_t i;
 int ret = -1;
 
@@ -1402,7 +1402,6 @@ virLXCControllerSetupUsernsMap(virDomainIdMapEntryPtr map,
 
 ret = 0;
  cleanup:
-virBufferFreeAndReset(_value);
 return ret;
 }
 
diff --git a/src/lxc/lxc_driver.c b/src/lxc/lxc_driver.c
index 46a182be45..1cdd6ee455 100644
--- a/src/lxc/lxc_driver.c
+++ b/src/lxc/lxc_driver.c
@@ -4618,7 +4618,7 @@ static char *
 lxcConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
 {
 virLXCDriverPtr driver = conn->privateData;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 virCheckFlags(0, NULL);
 
diff --git a/src/lxc/lxc_fuse.c b/src/lxc/lxc_fuse.c
index 146629f67e..6e23361617 100644
--- a/src/lxc/lxc_fuse.c
+++ b/src/lxc/lxc_fuse.c
@@ -124,7 +124,7 @@ static int lxcProcReadMeminfo(char *hostpath, 
virDomainDefPtr def,
 g_autofree char *line = NULL;
 size_t n;
 struct virLXCMeminfo meminfo;
-virBuffer buffer = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buffer = VIR_BUFFER_INITIALIZER;
 virBufferPtr new_meminfo = 
 
 if (virLXCCgroupGetMeminfo() < 0) {
@@ -223,7 +223,6 @@ static int lxcProcReadMeminfo(char *hostpath, 
virDomainDefPtr def,
 memcpy(buf, virBufferCurrentContent(new_meminfo), res);
 
  cleanup:
-virBufferFreeAndReset(new_meminfo);
 VIR_FORCE_FCLOSE(fd);
 return res;
 }
-- 
2.25.4



[PATCH 01/32] bhyve: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
In most cases this eliminates one or more calls to
virBufferClearAndReset(), but even when it doesn't it's better because:

1) it makes the code more consistent, making it more likely that new 
contributors who are "learning by example" will to the right thing.

2) it protects against future modifications that might have otherwise
needed to add a virBufferClearAndReset()

3) Currently some functions don't call virBufferClearAndReset() only
because they're relying on some subordinate function to call it for
them (e.g. bhyveConnectGetSysinfo() in this patch relies on
virSysinfoFormat() to clear out the buffer when there is an error). I
think this is sloppy behavior, and that the toplevel function that
defines and initializes the buffer should be the function clearing it
at the end.

Signed-off-by: Laine Stump 
---
 src/bhyve/bhyve_command.c | 15 ++-
 src/bhyve/bhyve_driver.c  |  4 ++--
 2 files changed, 8 insertions(+), 11 deletions(-)

diff --git a/src/bhyve/bhyve_command.c b/src/bhyve/bhyve_command.c
index 5b1d80083a..9649c2d2a2 100644
--- a/src/bhyve/bhyve_command.c
+++ b/src/bhyve/bhyve_command.c
@@ -166,14 +166,15 @@ bhyveBuildAHCIControllerArgStr(const virDomainDef *def,
bhyveConnPtr driver,
virCommandPtr cmd)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
-virBuffer device = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 const char *disk_source;
 size_t i;
 int ret = -1;
 
 for (i = 0; i < def->ndisks; i++) {
+g_auto(virBuffer) device = VIR_BUFFER_INITIALIZER;
 virDomainDiskDefPtr disk = def->disks[i];
+
 if (disk->bus != VIR_DOMAIN_DISK_BUS_SATA)
 continue;
 
@@ -221,7 +222,6 @@ bhyveBuildAHCIControllerArgStr(const virDomainDef *def,
 goto error;
 }
 virBufferAddBuffer(, );
-virBufferFreeAndReset();
 }
 
 virCommandAddArg(cmd, "-s");
@@ -231,7 +231,6 @@ bhyveBuildAHCIControllerArgStr(const virDomainDef *def,
 
 ret = 0;
  error:
-virBufferFreeAndReset();
 return ret;
 }
 
@@ -378,7 +377,7 @@ bhyveBuildGraphicsArgStr(const virDomainDef *def,
  virCommandPtr cmd,
  bool dryRun)
 {
-virBuffer opt = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) opt = VIR_BUFFER_INITIALIZER;
 virDomainGraphicsListenDefPtr glisten = NULL;
 bool escapeAddr;
 unsigned short port;
@@ -478,7 +477,6 @@ bhyveBuildGraphicsArgStr(const virDomainDef *def,
 return 0;
 
  error:
-virBufferFreeAndReset();
 return -1;
 }
 
@@ -765,7 +763,6 @@ virBhyveProcessBuildGrubbhyveCmd(virDomainDefPtr def,
  char **devicesmap_out)
 {
 virDomainDiskDefPtr hdd, cd, userdef, diskdef;
-virBuffer devicemap;
 virCommandPtr cmd;
 unsigned int best_idx = UINT_MAX;
 size_t i;
@@ -773,8 +770,6 @@ virBhyveProcessBuildGrubbhyveCmd(virDomainDefPtr def,
 if (def->os.bootloaderArgs != NULL)
 return virBhyveProcessBuildCustomLoaderCmd(def);
 
-devicemap = (virBuffer)VIR_BUFFER_INITIALIZER;
-
 /* Search disk list for CD or HDD device. We'll respect  if
  * present and otherwise pick the first CD or failing that HDD we come
  * across. */
@@ -809,6 +804,8 @@ virBhyveProcessBuildGrubbhyveCmd(virDomainDefPtr def,
 VIR_DEBUG("grub-bhyve with default arguments");
 
 if (devicesmap_out != NULL) {
+g_auto(virBuffer) devicemap = VIR_BUFFER_INITIALIZER;
+
 /* Grub device.map (just for boot) */
 if (userdef != NULL) {
 virBhyveFormatGrubDevice(, userdef);
diff --git a/src/bhyve/bhyve_driver.c b/src/bhyve/bhyve_driver.c
index b6204c7fb9..daa20bad40 100644
--- a/src/bhyve/bhyve_driver.c
+++ b/src/bhyve/bhyve_driver.c
@@ -244,7 +244,7 @@ static char *
 bhyveConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
 {
 bhyveConnPtr privconn = conn->privateData;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 
 virCheckFlags(0, NULL);
 
@@ -678,7 +678,7 @@ bhyveConnectDomainXMLToNative(virConnectPtr conn,
   const char *xmlData,
   unsigned int flags)
 {
-virBuffer buf = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
 bhyveConnPtr privconn = conn->privateData;
 virDomainDefPtr def = NULL;
 virCommandPtr cmd = NULL, loadcmd = NULL;
-- 
2.25.4



[PATCH 02/32] esx: use g_auto() for all virBuffers

2020-07-05 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/esx/esx_driver.c | 19 +--
 src/esx/esx_util.c   |  4 ++--
 src/esx/esx_vi.c | 19 +--
 src/esx/esx_vi_methods.c |  6 +-
 4 files changed, 13 insertions(+), 35 deletions(-)

diff --git a/src/esx/esx_driver.c b/src/esx/esx_driver.c
index 0ede65279a..3fb7a3b62c 100644
--- a/src/esx/esx_driver.c
+++ b/src/esx/esx_driver.c
@@ -275,7 +275,7 @@ esxFormatVMXFileName(const char *fileName, void *opaque)
 esxVI_ObjectContent *datastore = NULL;
 esxVI_DatastoreHostMount *hostMount = NULL;
 char separator = '/';
-virBuffer buffer = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buffer = VIR_BUFFER_INITIALIZER;
 char *tmp;
 size_t length;
 
@@ -336,10 +336,8 @@ esxFormatVMXFileName(const char *fileName, void *opaque)
 success = true;
 
  cleanup:
-if (! success) {
-virBufferFreeAndReset();
+if (! success)
 VIR_FREE(result);
-}
 
 VIR_FREE(datastoreName);
 VIR_FREE(directoryAndFileName);
@@ -2359,7 +2357,7 @@ esxDomainScreenshot(virDomainPtr domain, virStreamPtr 
stream,
 esxVI_String *propertyNameList = NULL;
 esxVI_ObjectContent *virtualMachine = NULL;
 esxVI_VirtualMachinePowerState powerState;
-virBuffer buffer = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buffer = VIR_BUFFER_INITIALIZER;
 char *url = NULL;
 
 virCheckFlags(0, NULL);
@@ -2413,7 +2411,6 @@ esxDomainScreenshot(virDomainPtr domain, virStreamPtr 
stream,
 }
 
  cleanup:
-virBufferFreeAndReset();
 
 esxVI_String_Free();
 esxVI_ObjectContent_Free();
@@ -2579,7 +2576,7 @@ esxDomainGetXMLDesc(virDomainPtr domain, unsigned int 
flags)
 char *datastoreName = NULL;
 char *directoryName = NULL;
 char *directoryAndFileName = NULL;
-virBuffer buffer = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buffer = VIR_BUFFER_INITIALIZER;
 char *url = NULL;
 char *vmx = NULL;
 virVMXContext ctx;
@@ -2653,9 +2650,6 @@ esxDomainGetXMLDesc(virDomainPtr domain, unsigned int 
flags)
 }
 
  cleanup:
-if (!url)
-virBufferFreeAndReset();
-
 esxVI_String_Free();
 esxVI_ObjectContent_Free();
 VIR_FREE(moref);
@@ -2936,7 +2930,7 @@ esxDomainDefineXMLFlags(virConnectPtr conn, const char 
*xml, unsigned int flags)
 char *datastoreName = NULL;
 char *directoryName = NULL;
 char *escapedName = NULL;
-virBuffer buffer = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buffer = VIR_BUFFER_INITIALIZER;
 char *url = NULL;
 char *datastoreRelatedPath = NULL;
 esxVI_String *propertyNameList = NULL;
@@ -3124,9 +3118,6 @@ esxDomainDefineXMLFlags(virConnectPtr conn, const char 
*xml, unsigned int flags)
 /* FIXME: Add proper rollback in case of an error */
 
  cleanup:
-if (!url)
-virBufferFreeAndReset();
-
 virDomainDefFree(def);
 VIR_FREE(vmx);
 VIR_FREE(datastoreName);
diff --git a/src/esx/esx_util.c b/src/esx/esx_util.c
index 89d136248f..11f43acc19 100644
--- a/src/esx/esx_util.c
+++ b/src/esx/esx_util.c
@@ -357,7 +357,7 @@ esxUtil_EscapeBase64(const char *string)
 static const char *base64 =
   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
 
-virBuffer buffer = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buffer = VIR_BUFFER_INITIALIZER;
 const char *tmp1 = string;
 size_t length;
 unsigned char c1, c2, c3;
@@ -456,7 +456,7 @@ esxUtil_EscapeDatastoreItem(const char *string)
 char *
 esxUtil_EscapeForXml(const char *string)
 {
-virBuffer buffer = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buffer = VIR_BUFFER_INITIALIZER;
 
 virBufferEscapeString(, "%s", string);
 
diff --git a/src/esx/esx_vi.c b/src/esx/esx_vi.c
index 16690edfbe..d48a24e9d3 100644
--- a/src/esx/esx_vi.c
+++ b/src/esx/esx_vi.c
@@ -370,7 +370,7 @@ esxVI_CURL_Download(esxVI_CURL *curl, const char *url, char 
**content,
 unsigned long long offset, unsigned long long *length)
 {
 char *range = NULL;
-virBuffer buffer = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buffer = VIR_BUFFER_INITIALIZER;
 int responseCode = 0;
 
 ESX_VI_CHECK_ARG_LIST(content);
@@ -421,10 +421,8 @@ esxVI_CURL_Download(esxVI_CURL *curl, const char *url, 
char **content,
  cleanup:
 VIR_FREE(range);
 
-if (!(*content)) {
-virBufferFreeAndReset();
+if (!(*content))
 return -1;
-}
 
 return 0;
 }
@@ -1025,7 +1023,7 @@ esxVI_Context_LookupManagedObjectsByPath(esxVI_Context 
*ctx, const char *path)
 char *saveptr = NULL;
 char *previousItem = NULL;
 char *item = NULL;
-virBuffer buffer = VIR_BUFFER_INITIALIZER;
+g_auto(virBuffer) buffer = VIR_BUFFER_INITIALIZER;
 esxVI_ManagedObjectReference *root = NULL;
 esxVI_Folder *folder = NULL;
 
@@ -1184,9 +1182,6 @@ esxVI_Context_LookupManagedObjectsByPath(esxVI_Context 
*ctx, const char *path)
 result = 0;
 
  cleanup:

Re: [PATCH 04/25] util: validate return from xmlNodeGetContent before use

2020-06-26 Thread Laine Stump

On 6/25/20 6:55 PM, Ján Tomko wrote:

On a Wednesday in 2020, Laine Stump wrote:

There were a few uses of xmlNodeGetContent() that didn't check for
NULL before using the result.

A NULL return from xmlNodeGetContent() *could* (probably does) mean
that there was an Out of Memory condition, but it is unclear from the
documentation if that is always the case, or if it could just indicate
a missing value in the document, so we don't report an OOM error, but
just don't try to use it for, e.g., conversion to an integer.


Is it possible to have an element with "no value"?



I never found anywhere that said "No". But I also never found anywhere 
that says "yes", so I opted for "do no harm" (or something like that).




Even  gives me an empty string instead of NULL.



Okay, *that* says "No". So I'll change the patch to always report an OOM 
error.





Jano



Signed-off-by: Laine Stump 
---
src/conf/domain_conf.c | 28 ++--
1 file changed, 14 insertions(+), 14 deletions(-)





Re: [PATCH 03/25] conf: refactor virDomainBlkioDeviceParseXML to remove possible NULL dereference

2020-06-26 Thread Laine Stump

On 6/26/20 6:54 PM, Laine Stump wrote:

On 6/25/20 6:44 PM, Ján Tomko wrote:


and give a possibility of assigning the path directly
to 'path', without the extra steal_pointer.



I don't follow there - if you assign directly from xmlNodeGetContent() 
into path, then you'll need to duplicate the virReportOOMError().



Sigh. Nevermind. It had already been several days since I wrote the 
code, so I'd completely forgotten it and hadn't looked back at the 
bottom yet (where I would have seen the "extra steal pointer" you mention).



Now I get it.




Re: [PATCH 03/25] conf: refactor virDomainBlkioDeviceParseXML to remove possible NULL dereference

2020-06-26 Thread Laine Stump

On 6/25/20 6:44 PM, Ján Tomko wrote:

On a Wednesday in 2020, Laine Stump wrote:

virDomainBlkioDeviceParseXML() has multiple cases of sending the
return from xmlNodeGetContent() directly to virStrToLong_xx() without
checking for NULL. Although it is *very* rare for xmlNodeGetContent()
to return NULL (possibly it only happens in an OOM condition? The
documentation is unclear), it could happen, and the refactor in this
patch manages to eliminate several lines of repeated code while adding
in a (single) check for NULL.

Signed-off-by: Laine Stump 
---
src/conf/domain_conf.c | 39 +++
1 file changed, 15 insertions(+), 24 deletions(-)

diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index 1916b51d38..8cde1cd0e8 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -1628,73 +1628,64 @@ virDomainBlkioDeviceParseXML(xmlNodePtr root,
 virBlkioDevicePtr dev)
{
    xmlNodePtr node;
-    g_autofree char *c = NULL;
+    g_autofree char *path = NULL;

    node = root->children;
    while (node) {
-    if (node->type == XML_ELEMENT_NODE) {
-    if (virXMLNodeNameEqual(node, "path") && !dev->path) {
-    dev->path = (char *)xmlNodeGetContent(node);
+    g_autofree char *c = NULL;
+
+    if (node->type == XML_ELEMENT_NODE &&
+    (c = (char *)xmlNodeGetContent(node))) {


Missing ErrorReport if xmlNodeGetContent fails.



Well, I was uncertain whether or not it was *always* an error. The API 
docs don't specifically say, a google search revealed people asking the 
question, but nobody answering it definitively (I think there may have 
been some snarky condescending reply on stackexchange (par for the 
course), but no actual information), and I stopped trying to figure it 
out by looking at the libxml2 source after just a couple layers - ain't 
nobody got time for that!



But you apparently tried it out and determined that it will return "" 
rather than NULL as long as node->type == XML_ELEMENT_NODE, so I'll 
trust that and treat all NULL returns as OOM (including in a later patch).






Converting this open-coded for loop to an actual for loop would
grant us 'continue' privileges, which would make the checks
nicer 



If you're averse to "else if" I guess.



and give a possibility of assigning the path directly
to 'path', without the extra steal_pointer.



I don't follow there - if you assign directly from xmlNodeGetContent() 
into path, then you'll need to duplicate the virReportOOMError().



Anyway, I'll turn it into a for() loop make the NULL return from 
xmlNodeGetContent() an error (rather than ignoring it) and resubmit, 
since it's too many changes to trust me on it.





Alternatively, the minimum diff where I'd consider this patch to be
a strict improvement is:

} else if (node->type == XML_ELEMENT_NODE && !c) {
    virReportOOMError();
    return -1;
}

With that: Reviewed-by: Ján Tomko 

Jano





Re: [PATCH 11/25] network: use g_free() in place of remaining VIR_FREE()

2020-06-26 Thread Laine Stump

On 6/25/20 11:12 AM, Daniel P. Berrangé wrote:

On Thu, Jun 25, 2020 at 11:01:48AM -0400, Laine Stump wrote:

On 6/25/20 3:55 AM, Peter Krempa wrote:

On Wed, Jun 24, 2020 at 23:34:00 -0400, Laine Stump wrote:

Signed-off-by: Laine Stump 
---
   src/network/bridge_driver.c | 59 +
   1 file changed, 33 insertions(+), 26 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 668aa9ca88..a1b2f5b6c7 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c

[...]


@@ -706,7 +706,8 @@ networkStateInitialize(bool privileged,
   network_driver->lockFD = -1;
   if (virMutexInit(_driver->lock) < 0) {
-VIR_FREE(network_driver);
+g_free(network_driver);
+network_driver = NULL;
   goto error;

In general I'm agains senseless replacement of VIR_FREE for g_free.
There is IMO no value to do so. VIR_FREE is now implemented via
g_clear_pointer(, g_free) so g_free is actually used.

Mass replacements are also substrate for adding bugs and need to be
approached carefully, so doing this en-mass might lead to others
attempting the same with possibly less care.




In general, mass replacements should be done only to

g_clear_pointer(, g_free)

and I'm not sure it's worth it.



There's no getting around it - that looks ugly. And who wants to replace
5506 occurences of one simple-looking thing with something else that's
functionally equivalent but more painful to look at?


I would vote for just documenting that, for safety and consistency reasons,
VIR_FREE() should always be used instead of g_free(), and eliminating all
direct use of g_free() (along with the aforementioned syntax check). (BTW, I
had assumed there had been more changes to g_free(), but when I looked at my
current tree just now, there were only 228 occurences, including the changes
in this patch)


The point in getting rid of VIR_FREE is so that we reduce the libvirt
specific wrappers in favour of standard APIs.


Is this just to make the code more accessible/understandable to new 
contributors? Or is there some other reason that I missed due to being 
incapable of reading all the messages on all the lists? (I guess there's 
also the issue of reducing support burden by reproducing identical code 
to something that someone else is already maintaining in a different 
library. But in this case we're just talking about a few lines that 
enforces good behavior.)




A large portion of the VIR_FREE's will be eliminated by g_autoptr.

Another large set of them are used in the virFooStructFree() methods.
Those can all be converted to g_free safely, as all the methods do
is free stuff.

Most VIR_FREEs that occur at the exit of functions can also be
safely converted to g_free, if g_autoptr  isnt applicable. Sometimes
needs a little care if you have multiple goto jumps between labels.


It still requires thought + diligence = time. And what if new code is 
added to the end of a function, thus making those things that had been 
"at the end" now in the middle. The more thought and decision making is 
needed to get something right, the more likely it is that someone will 
get it wrong.



The big danger cases are the VIR_FREE()s that occur in the middle
of methods, especially in loop bodies. Those the ones that must
use the g_clear_pointer, and that's not very many of those, so the
ugly syntax isn't an issue.


1) Maybe I'll feel differently after more of the code has been converted 
to use g_auto* and eliminated more of the existing explicit frees, but 
with currently > 5000 uses of VIR_FREE still in the code, I fear that 
"not many of those" may be more than we're expecting, and especially 
with many of them left, it would give me more warm fuzzies to be able to 
say


 "We can verifiably state that no pointers will be used
  after free , because their values have been NULLed,
  and any access will either be a NOP, or cause an
  immediate segfault"

rather than

 "We believe that the contributors to libvirt have been
  diligent in their manual auditing of all cases of
  free'ing memory to assure that none of the freed
  pointers are ever used at any later point,
  because well, just *because*".

(on the other hand, admittedly any pointer to something with its own 
vir*Free() function already requires diligence on the part of the 
programmer, since vir*Free() doesn't NULL the pointer. In that case, 
what's a little extra burden?)



2) Speaking from my experience with the occurrences I converted here, 
the worst offenders were the places where someone re-used a local 
pointer multiple times in a function (sometimes naming the multiply-used 
variable something generic like "tmp", other times naming it 
specifically (e.g. "flags", then using it once for a matching purpose 
(e.g. a string containing the flags arg for an ebtables command option), 
and again for something

Re: [libvirt PATCH v3 0/2] Refuse PCI Address for ramfb device definition

2020-06-25 Thread Laine Stump

On 6/25/20 4:18 PM, Jonathon Jongsma wrote:

Changes in this version:
  - Add the test case input file
  - modify the test itself to properly fail when an input file is missing.

Jonathon Jongsma (2):
   qemu: ramfb video device doesn't support PCI address
   tests: ensure failure if input file doesn't exist

  src/qemu/qemu_validate.c  |  8 +
  ...video-ramfb-display-device-pci-address.xml | 30 +++
  tests/qemuxml2argvtest.c  |  7 +
  3 files changed, 45 insertions(+)
  create mode 100644 
tests/qemuxml2argvdata/video-ramfb-display-device-pci-address.xml



For both:

Reviewed-by: Laine Stump 

and pushed (...nd I just realized I forgot to add the Reviewed-by: 
tag before pushing :-/. Ah well, it shows me as the committer, so you 
won't have to *totally* take the fall if something blows up :-))




Re: [PATCH 16/25] squash into 'network: convert local pointers to g_auto*'

2020-06-25 Thread Laine Stump

On 6/25/20 7:34 PM, Ján Tomko wrote:

On a Wednesday in 2020, Laine Stump wrote:

OOPS!!

I meant to squash this into patch 10 before posting. If you want to 
just review it separately I can squash it in before push. Or if you 
want to be pedantic I can squash it in and resend :-)




To me, these seem like changes unrelated to patch 10 and deserve their
own commit.



Well, they're all related to the cleanup that naturally follows from 
making a pointer g_autofree - 1) you need to initialize it when you 
define it (and so you might as well initialize it with the first real 
value it's going to get, as long as that value would end up *always* 
being assigned anyway, and 2) code reduction related to removing 
now-empty cleanup: label. But I see you just responded to patch 10 
saying you thought the patch was too long and should be split, so I 
suppose I could make this the 2nd of the 2 that you suggest.





Jano


On 6/24/20 11:34 PM, Laine Stump wrote:

Signed-off-by: Laine Stump 
---
 src/network/bridge_driver_linux.c | 9 ++---
 1 file changed, 2 insertions(+), 7 deletions(-)

diff --git a/src/network/bridge_driver_linux.c 
b/src/network/bridge_driver_linux.c

index 0d0ac730f2..7f765bcf99 100644
--- a/src/network/bridge_driver_linux.c
+++ b/src/network/bridge_driver_linux.c
@@ -834,7 +834,7 @@ int networkAddFirewallRules(virNetworkDefPtr def)
 {
 size_t i;
 virNetworkIPDefPtr ipdef;
-    g_autoptr(virFirewall) fw = NULL;
+    g_autoptr(virFirewall) fw = virFirewallNew();
 if (virOnce(, networkSetupPrivateChains) < 0)
 return -1;
@@ -920,8 +920,6 @@ int networkAddFirewallRules(virNetworkDefPtr def)
 }
 }
-    fw = virFirewallNew();
-
 virFirewallStartTransaction(fw, 0);
 networkAddGeneralFirewallRules(fw, def);
@@ -946,10 +944,7 @@ int networkAddFirewallRules(virNetworkDefPtr def)
 virFirewallStartTransaction(fw, 
VIR_FIREWALL_TRANSACTION_IGNORE_ERRORS);

 networkAddChecksumFirewallRules(fw, def);
-    if (virFirewallApply(fw) < 0)
-    return -1;
-
-    return 0;
+    return virFirewallApply(fw);
 }
 /* Remove all rules for all ip addresses (and general rules) on a 
network */







Re: [PATCH 07/25] util: eliminate error label in virDomainDefFormatInternalSetRootName()

2020-06-25 Thread Laine Stump

On 6/25/20 7:08 PM, Ján Tomko wrote:

On a Wednesday in 2020, Laine Stump wrote:

The only reason for the error label in this function is to call
virBufferFreeAndReset(). It's actually more common for a failed format
function to just leave the virBuffer alone and let the caller free it
when there is a failure, and in fact the only caller of this function
that *wasn't* already calling virBufferFreeAndReset() on failure was
virDomainDefFormat() (via virDomainDefFormatInternal()).



qemuDomainDefFormatXMLInternal does not call it either.



Dang! I thought I had followed every call chain with cscope, but maybe I 
just searched in this one file? Anyway, it's especially embarrassing 
because not only did I miss qemuDomainFormatXMLInternal(), I also missed 
virDomainSnapshotDefFormat (which called 
virDomainSnapshotDefFormatInternal(), which calls 
virDomainDefFormatInternal()) :-(



I think as a followup patch, I should convert every occurrence of 
"virBuffer blah = VIR_BUFFER_INITIALIZER" to "g_auto(virBuffer) blah = 
VIR_BUFFER_INITIALIZER" - in a quick search just now I already found a 
couple more (totally unrelated to virDomainDefFormat) that aren't 
properly cleared out on error.



Thanks for taking the time to actually fact check my claims.


#FakeCommitLogs





That is easily solved by modifying virDomainDefFormat() to declare its
virBuffer buf with g_auto(), so that virBufferFreeAndReset() is
automatically called.

Signed-off-by: Laine Stump 
---
src/conf/domain_conf.c | 88 --
1 file changed, 42 insertions(+), 46 deletions(-)


With that fixed:
Reviewed-by: Ján Tomko 

Jano





Re: [PATCH 09/25] util: add g_autoptr cleanup function for virFirewall objects

2020-06-25 Thread Laine Stump

On 6/25/20 7:17 PM, Ján Tomko wrote:

The cleanup function was already added by:
commit 2ad0284627ea3d6c123e0a266b9c7bb00aea4576
CommitDate: 2018-07-27 17:21:04 +0200

    util: firewall: define cleanup function using VIR_DEFINE_AUTOPTR_FUNC

On a Wednesday in 2020, Laine Stump wrote:

Put in a separate patch so that two future patches can be re-ordered /
selectively backported independent of each other.

Signed-off-by: Laine Stump 
---
src/util/virfirewall.h | 1 +
1 file changed, 1 insertion(+)

diff --git a/src/util/virfirewall.h b/src/util/virfirewall.h
index 6148f46827..ff690b36f0 100644
--- a/src/util/virfirewall.h
+++ b/src/util/virfirewall.h
@@ -40,6 +40,7 @@ virFirewallPtr virFirewallNew(void);

void virFirewallFree(virFirewallPtr firewall);

+


This is just a whitespace change that contradicts the prevailing style
in this file.



Right. Another patch that I intended to remove before I posted, but 
forgot because it was late and I wanted to end the day with a clean slate.



Derp.




Re: [libvirt PATCH v2] qemu: ramfb video device doesn't support PCI address

2020-06-25 Thread Laine Stump

On 6/25/20 12:30 PM, Jonathon Jongsma wrote:

On Thu, 2020-06-25 at 12:20 -0400, Laine Stump wrote:

On 6/25/20 10:34 AM, Jonathon Jongsma wrote:

Although a ramfb video device is not a PCI device, we don't
currently
report an error for ramfb device definitions containing a PCI
address.
However, a guest configured with such a device will fail to start:

  # virsh start test1
  error: Failed to start domain test1
  error: internal error: qemu unexpectedly closed the monitor:
2020-06-16T05:23:02.759221Z qemu-kvm: -device
ramfb,id=video0,bus=pcie.0,addr=0x1: Device 'ramfb' can't go on
PCIE bus

A better approach is to reject any device definitions that contain
PCI
addresses.  While this is a change in behavior, any existing
configurations were non-functional.

https://bugzilla.redhat.com/show_bug.cgi?id=1847259

Signed-off-by: Jonathon Jongsma 
---
changes in v2:
   - move validation to qemu-specific validation function as
suggested by Laine

   src/qemu/qemu_validate.c | 8 
   tests/qemuxml2argvtest.c | 1 +
   2 files changed, 9 insertions(+)

diff --git a/src/qemu/qemu_validate.c b/src/qemu/qemu_validate.c
index 5082a29dc7..b13c03759e 100644
--- a/src/qemu/qemu_validate.c
+++ b/src/qemu/qemu_validate.c
@@ -1925,6 +1925,14 @@ qemuValidateDomainDeviceDefVideo(const
virDomainVideoDef *video,
   if (qemuValidateDomainVirtioOptions(video->virtio, qemuCaps)
< 0)
   return -1;
   
+if (video->type == VIR_DOMAIN_VIDEO_TYPE_RAMFB &&

+video->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
+virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
+   _("'address' is not supported for 'ramfb'
video devices"));
+return -1;
+}
+
+
   return 0;
   }
   
diff --git a/tests/qemuxml2argvtest.c b/tests/qemuxml2argvtest.c

index 1195f9c982..f2522fa530 100644
--- a/tests/qemuxml2argvtest.c
+++ b/tests/qemuxml2argvtest.c
@@ -2276,6 +2276,7 @@ mymain(void)
   QEMU_CAPS_VIRTIO_GPU_MAX_OUTPUTS);
   DO_TEST_CAPS_LATEST("video-bochs-display-device");
   DO_TEST_CAPS_LATEST("video-ramfb-display-device");
+DO_TEST_CAPS_LATEST_PARSE_ERROR("video-ramfb-display-device-
pci-address");

Did you forget to git-add the test case data?

OK, well that points out an interesting property of the
DO_TEST_CAPS_LATEST_PARSE_ERROR() macro. It passed the 'make check'
because it failed to parse the xml file as expected. But the reason it
failed was obviously not the reason I expected it to fail... I want it
to fail due to the specifying a PCI address for the ramfb device. But
it actually fails because the xml file didn't exist... :/



That gave me the best laugh I'd had all day!! :-)


I just realized you don't have push privileges on gitlab. If you re-send 
with test case data, I'll push it.



(I guess we should also fix the test harness to "fail to fail" if the 
test case data is missing, but that's a separate issue)




Re: [libvirt PATCH v2] qemu: ramfb video device doesn't support PCI address

2020-06-25 Thread Laine Stump

On 6/25/20 10:34 AM, Jonathon Jongsma wrote:

Although a ramfb video device is not a PCI device, we don't currently
report an error for ramfb device definitions containing a PCI address.
However, a guest configured with such a device will fail to start:

 # virsh start test1
 error: Failed to start domain test1
 error: internal error: qemu unexpectedly closed the monitor: 
2020-06-16T05:23:02.759221Z qemu-kvm: -device 
ramfb,id=video0,bus=pcie.0,addr=0x1: Device 'ramfb' can't go on PCIE bus

A better approach is to reject any device definitions that contain PCI
addresses.  While this is a change in behavior, any existing
configurations were non-functional.

https://bugzilla.redhat.com/show_bug.cgi?id=1847259

Signed-off-by: Jonathon Jongsma 
---
changes in v2:
  - move validation to qemu-specific validation function as suggested by Laine

  src/qemu/qemu_validate.c | 8 
  tests/qemuxml2argvtest.c | 1 +
  2 files changed, 9 insertions(+)

diff --git a/src/qemu/qemu_validate.c b/src/qemu/qemu_validate.c
index 5082a29dc7..b13c03759e 100644
--- a/src/qemu/qemu_validate.c
+++ b/src/qemu/qemu_validate.c
@@ -1925,6 +1925,14 @@ qemuValidateDomainDeviceDefVideo(const virDomainVideoDef 
*video,
  if (qemuValidateDomainVirtioOptions(video->virtio, qemuCaps) < 0)
  return -1;
  
+if (video->type == VIR_DOMAIN_VIDEO_TYPE_RAMFB &&

+video->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
+virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
+   _("'address' is not supported for 'ramfb' video 
devices"));
+return -1;
+}
+
+
  return 0;
  }
  
diff --git a/tests/qemuxml2argvtest.c b/tests/qemuxml2argvtest.c

index 1195f9c982..f2522fa530 100644
--- a/tests/qemuxml2argvtest.c
+++ b/tests/qemuxml2argvtest.c
@@ -2276,6 +2276,7 @@ mymain(void)
  QEMU_CAPS_VIRTIO_GPU_MAX_OUTPUTS);
  DO_TEST_CAPS_LATEST("video-bochs-display-device");
  DO_TEST_CAPS_LATEST("video-ramfb-display-device");
+DO_TEST_CAPS_LATEST_PARSE_ERROR("video-ramfb-display-device-pci-address");



Did you forget to git-add the test case data?



  DO_TEST("video-none-device",
  QEMU_CAPS_VNC);
  DO_TEST_PARSE_ERROR("video-invalid-multiple-devices", NONE);



With the test case data added

Reviewed-by: Laine Stump 



Re: [PATCH 11/25] network: use g_free() in place of remaining VIR_FREE()

2020-06-25 Thread Laine Stump

On 6/25/20 3:55 AM, Peter Krempa wrote:

On Wed, Jun 24, 2020 at 23:34:00 -0400, Laine Stump wrote:

Signed-off-by: Laine Stump 
---
  src/network/bridge_driver.c | 59 +
  1 file changed, 33 insertions(+), 26 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 668aa9ca88..a1b2f5b6c7 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c

[...]


@@ -706,7 +706,8 @@ networkStateInitialize(bool privileged,
  
  network_driver->lockFD = -1;

  if (virMutexInit(_driver->lock) < 0) {
-VIR_FREE(network_driver);
+g_free(network_driver);
+network_driver = NULL;
  goto error;

In general I'm agains senseless replacement of VIR_FREE for g_free.
There is IMO no value to do so. VIR_FREE is now implemented via
g_clear_pointer(, g_free) so g_free is actually used.

Mass replacements are also substrate for adding bugs and need to be
approached carefully, so doing this en-mass might lead to others
attempting the same with possibly less care.



Actually I agree with you :-)


When we started into all this glib stuff, I thought that it was kind of 
unproductive to churn the code around in cases where it was just 
renaming one thing to something else - aside from (as you point out) 
being a siren call for regressions, this also makes backports to old 
branches more annoying, obscures *actual* functional history, and 
besides, what happens the *next* time we want to change how we do 
[whatever thing we're changing]? Do we do yet another global replacement 
for the "new new hotness"? But this was one of those things that didn't 
seem worth getting in the way of (and in balance it was definitely a net 
win), so I mostly ignored it (including not going out of my way to 
convert any code over just for the sake of converting).



In the meantime, lots and lots of patches have come in converting this 
stuff piecemeal over the codebase, and it's all becoming more and more 
g_*-centric. I still didn't really bother with it much.



Then I saw a memory leak in a patch a couple weeks ago that wouldn't 
have occurred if the existing function had used g_autofree (and thus 
reminded the author to use g_autofree for their additions to this 
existing function). This led me to make a patch to convert that file to 
use g_autofree and g_autoptr wherever possible, which in turn got me to 
look at xmlBuffer allocation/free and notice a couple bugs, which led to 
noticing something else inconsistent with current style, which led to 
noticing some other existing bug, and from there to something else ad 
infinitum.



So this one recognition of a single memory leak organically led to a 
bunch of drive-by patches, but the drive-by patches left everything in 
an in-between limbo state - half of things were the "old way" and half 
were the "new way". Somewhere in the middle of all this, I looked back 
at a recent set of patches from danpb for reference, and saw that along 
with making locals g_auto*, and changing VIR_ALLOC to g_new0, he had 
also replaced VIR_FREE with g_free, so I figured I should probably do 
that too while I was already churning things. The semantic change (no 
longer setting the pointer to the freed memory to NULL) was bothered me, 
but since it was already being used, I assumed there must have been 
discussion about it among all the glib conversion mails I skipped over, 
and decided to make my patches consistent with "current convention", and 
just carefully examine each usage to assure that either the pointer 
wasn't referenced after free, or that it was explicitly set to NULL.



I do recognize your concern that "some other people" (thanks for 
explicitly, though incorrectly, excluding me! :-)) may not be as 
diligent when doing a similar replacement though, and even after doing 
it myself I have concern that I may have missed something.



And now you point out the new implementation to VIR_FREE() (*yet 
another* change missed by me, as with so many other things that whiz by 
on the mailing list) that uses g_clear_pointer (which, having not read 
through the glib reference manual nor worked on other projects using 
glib, I didn't know about until today)! This validates my original 
apprehension (in the before before time) about replacing VIR_* with g_* 
macros - when we use our own macros it may be slightly more difficult 
for first-time readers of the code who *might* have already been 
familiar with glib (or maybe not), but it allows us to easily change the 
underlying implementation in the future without yet again churning 
through all the code.



This convinces me that VIR_FREE shouldn't be replaced with g_free in 
*any* circumstance. As a matter of fact, I would even go so far as to 
say that use of g_free() should be .. er "prohibited" with a syntax 
check (or would that be limiting free speech?).



(BTW, in 

Re: [PATCH] qemuDomainDeviceNetDefPostParse: Switch order of conditions

2020-06-25 Thread Laine Stump

On 6/25/20 3:48 AM, Michal Privoznik wrote:

A few commits back (in v6.4.0-131-gbdb8f2e418) the post parse
function for domain interface was changed so that it doesn't fill
in model for hostdev types of interfaces (including network type
interfaces which would end up hostdevs).

While the idea is sound, the execution can be a bit better:
virDomainNetResolveActualType() which is used to determine
runtime type of given interface is heavy gun - it connects to
network driver, fetches network XML, parses it. This all is
followed by check whether the interface doesn't already have
model set (from domain XML).

If we switch the order of these two checks then the short circuit
evaluation will ensure the expensive check is done only if really
needed.



Oops! I should have caught that when I reviewed the earlier commit.


Reviewed-by: Laine Stump 




Re: [PATCH 16/25] squash into 'network: convert local pointers to g_auto*'

2020-06-24 Thread Laine Stump

OOPS!!

I meant to squash this into patch 10 before posting. If you want to just 
review it separately I can squash it in before push. Or if you want to 
be pedantic I can squash it in and resend :-)


On 6/24/20 11:34 PM, Laine Stump wrote:

Signed-off-by: Laine Stump 
---
  src/network/bridge_driver_linux.c | 9 ++---
  1 file changed, 2 insertions(+), 7 deletions(-)

diff --git a/src/network/bridge_driver_linux.c 
b/src/network/bridge_driver_linux.c
index 0d0ac730f2..7f765bcf99 100644
--- a/src/network/bridge_driver_linux.c
+++ b/src/network/bridge_driver_linux.c
@@ -834,7 +834,7 @@ int networkAddFirewallRules(virNetworkDefPtr def)
  {
  size_t i;
  virNetworkIPDefPtr ipdef;
-g_autoptr(virFirewall) fw = NULL;
+g_autoptr(virFirewall) fw = virFirewallNew();
  
  if (virOnce(, networkSetupPrivateChains) < 0)

  return -1;
@@ -920,8 +920,6 @@ int networkAddFirewallRules(virNetworkDefPtr def)
  }
  }
  
-fw = virFirewallNew();

-
  virFirewallStartTransaction(fw, 0);
  
  networkAddGeneralFirewallRules(fw, def);

@@ -946,10 +944,7 @@ int networkAddFirewallRules(virNetworkDefPtr def)
  virFirewallStartTransaction(fw, VIR_FIREWALL_TRANSACTION_IGNORE_ERRORS);
  networkAddChecksumFirewallRules(fw, def);
  
-if (virFirewallApply(fw) < 0)

-return -1;
-
-return 0;
+return virFirewallApply(fw);
  }
  
  /* Remove all rules for all ip addresses (and general rules) on a network */





[PATCH 14/25] network: replace VIR_ALLOC/REALLOC with g_new0/g_renew

2020-06-24 Thread Laine Stump
most of these are long-lived or attached to some other object, but a
couple are automatics, and can take advantage of g_autoptr.

Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c | 44 +++--
 1 file changed, 13 insertions(+), 31 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 275502b778..1dee2fac6e 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -160,6 +160,7 @@ networkDnsmasqDefNamespaceFree(void *nsdata)
 
 g_free(def);
 }
+G_DEFINE_AUTOPTR_CLEANUP_FUNC(networkDnsmasqXmlNsDefPtr, 
networkDnsmasqDefNamespaceFree);
 
 
 static int
@@ -177,8 +178,7 @@ 
networkDnsmasqDefNamespaceParseOptions(networkDnsmasqXmlNsDefPtr nsdef,
 if (nnodes == 0)
 return 0;
 
-if (VIR_ALLOC_N(nsdef->options, nnodes) < 0)
-return -1;
+nsdef->options = g_new0(char *, nnodes);
 
 for (i = 0; i < nnodes; i++) {
 if (!(nsdef->options[nsdef->noptions++] = virXMLPropString(nodes[i], 
"value"))) {
@@ -196,23 +196,15 @@ static int
 networkDnsmasqDefNamespaceParse(xmlXPathContextPtr ctxt,
 void **data)
 {
-networkDnsmasqXmlNsDefPtr nsdata = NULL;
-int ret = -1;
-
-if (VIR_ALLOC(nsdata) < 0)
-return -1;
+networkDnsmasqXmlNsDefPtr nsdata = g_new0(networkDnsmasqXmlNsDef, 1);
 
 if (networkDnsmasqDefNamespaceParseOptions(nsdata, ctxt))
-goto cleanup;
+return -1;
 
 if (nsdata->noptions > 0)
 *data = g_steal_pointer();
 
-ret = 0;
-
- cleanup:
-networkDnsmasqDefNamespaceFree(nsdata);
-return ret;
+return 0;
 }
 
 
@@ -711,8 +703,7 @@ networkStateInitialize(bool privileged,
 return -1;
 }
 
-if (VIR_ALLOC(network_driver) < 0)
-goto error;
+network_driver = g_new0(virNetworkDriverState, 1);
 
 network_driver->lockFD = -1;
 if (virMutexInit(_driver->lock) < 0) {
@@ -2658,8 +2649,7 @@ networkCreateInterfacePool(virNetworkDefPtr netdef)
 goto cleanup;
 }
 
-if (VIR_ALLOC_N(netdef->forward.ifs, numVirtFns) < 0)
-goto cleanup;
+netdef->forward.ifs = g_new0(virNetworkForwardIfDef, numVirtFns);
 
 for (i = 0; i < numVirtFns; i++) {
 virPCIDeviceAddressPtr thisVirtFn = virtFns[i];
@@ -4129,7 +4119,6 @@ networkGetDHCPLeases(virNetworkPtr net,
 virJSONValuePtr lease_tmp = NULL;
 g_autoptr(virJSONValue) leases_array = NULL;
 virNetworkIPDefPtr ipdef_tmp = NULL;
-virNetworkDHCPLeasePtr lease = NULL;
 virNetworkDHCPLeasePtr *leases_ret = NULL;
 virNetworkObjPtr obj;
 virNetworkDefPtr def;
@@ -4218,8 +4207,7 @@ networkGetDHCPLeases(virNetworkPtr net,
 continue;
 
 if (need_results) {
-if (VIR_ALLOC(lease) < 0)
-goto error;
+g_autoptr(virNetworkDHCPLease) lease = g_new0(virNetworkDHCPLease, 
1);
 
 lease->expirytime = expirytime_tmp;
 
@@ -4267,22 +4255,17 @@ networkGetDHCPLeases(virNetworkPtr net,
 } else {
 nleases++;
 }
-
-g_free(lease);
-lease = NULL;
 }
 
 if (leases_ret) {
 /* NULL terminated array */
-ignore_value(VIR_REALLOC_N(leases_ret, nleases + 1));
-*leases = leases_ret;
-leases_ret = NULL;
+leases_ret = g_renew(virNetworkDHCPLeasePtr, leases_ret,  nleases + 1);
+*leases = g_steal_pointer(_ret);
 }
 
 rv = nleases;
 
  cleanup:
-g_free(lease);
 virNetworkObjEndAPI();
 
 return rv;
@@ -5504,10 +5487,9 @@ networkPortSetParameters(virNetworkPortPtr port,
 if (!(dir = virNetworkObjGetPortStatusDir(obj, driver->stateDir)))
 goto cleanup;
 
-if ((VIR_ALLOC(bandwidth) < 0) ||
-(VIR_ALLOC(bandwidth->in) < 0) ||
-(VIR_ALLOC(bandwidth->out) < 0))
-goto cleanup;
+bandwidth = g_new0(virNetDevBandwidth, 1);
+bandwidth->in = g_new0(virNetDevBandwidthRate, 1);
+bandwidth->out = g_new0(virNetDevBandwidthRate, 1);
 
 for (i = 0; i < nparams; i++) {
 virTypedParameterPtr param = [i];
-- 
2.25.4



[PATCH 18/25] nwfilter: define a typedef for struct ebtablesSubChainInst

2020-06-24 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_ebiptables_driver.c | 14 --
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index 8b77578117..cc814235aa 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -3274,7 +3274,9 @@ ebtablesRuleInstCommand(virFirewallPtr fw,
 return ret;
 }
 
-struct ebtablesSubChainInst {
+typedef struct _ebtablesSubChainInst ebtablesSubChainInst;
+typedef ebtablesSubChainInst *ebtablesSubChainInstPtr;
+struct _ebtablesSubChainInst {
 virNWFilterChainPriority priority;
 bool incoming;
 enum l3_proto_idx protoidx;
@@ -3285,8 +3287,8 @@ struct ebtablesSubChainInst {
 static int
 ebtablesSubChainInstSort(const void *a, const void *b)
 {
-const struct ebtablesSubChainInst **insta = (const struct 
ebtablesSubChainInst **)a;
-const struct ebtablesSubChainInst **instb = (const struct 
ebtablesSubChainInst **)b;
+const ebtablesSubChainInst **insta = (const ebtablesSubChainInst **)a;
+const ebtablesSubChainInst **instb = (const ebtablesSubChainInst **)b;
 
 /* priorities are limited to range [-1000, 1000] */
 return (*insta)->priority - (*instb)->priority;
@@ -3296,7 +3298,7 @@ ebtablesSubChainInstSort(const void *a, const void *b)
 static int
 ebtablesGetSubChainInsts(virHashTablePtr chains,
  bool incoming,
- struct ebtablesSubChainInst ***insts,
+ ebtablesSubChainInstPtr **insts,
  size_t *ninsts)
 {
 virHashKeyValuePairPtr filter_names;
@@ -3309,7 +3311,7 @@ ebtablesGetSubChainInsts(virHashTablePtr chains,
 return -1;
 
 for (i = 0; filter_names[i].key; i++) {
-struct ebtablesSubChainInst *inst;
+ebtablesSubChainInstPtr inst;
 enum l3_proto_idx idx = ebtablesGetProtoIdxByFiltername(
   filter_names[i].key);
 
@@ -3355,7 +3357,7 @@ ebiptablesApplyNewRules(const char *ifname,
 bool haveEbtables = false;
 bool haveIptables = false;
 bool haveIp6tables = false;
-struct ebtablesSubChainInst **subchains = NULL;
+ebtablesSubChainInstPtr *subchains = NULL;
 size_t nsubchains = 0;
 int ret = -1;
 
-- 
2.25.4



[PATCH 24/25] nwfilter: use standard label names when reasonable

2020-06-24 Thread Laine Stump
Rather than having labels named exit, done, exit_snooprequnlock,
skip_rename, etc, use the standard "cleanup" label. And instead of
err_exit, malformed, tear_down_tmpebchains, use "error".

Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_dhcpsnoop.c | 36 +++
 src/nwfilter/nwfilter_ebiptables_driver.c | 12 
 src/nwfilter/nwfilter_gentech_driver.c| 32 ++--
 src/nwfilter/nwfilter_learnipaddr.c   | 22 +++---
 4 files changed, 51 insertions(+), 51 deletions(-)

diff --git a/src/nwfilter/nwfilter_dhcpsnoop.c 
b/src/nwfilter/nwfilter_dhcpsnoop.c
index e41062feca..efb3257e92 100644
--- a/src/nwfilter/nwfilter_dhcpsnoop.c
+++ b/src/nwfilter/nwfilter_dhcpsnoop.c
@@ -454,11 +454,11 @@ 
virNWFilterSnoopIPLeaseInstallRule(virNWFilterSnoopIPLeasePtr ipl,
 virNWFilterSnoopReqLock(req);
 
 if (virNWFilterIPAddrMapAddIPAddr(req->binding->portdevname, ipaddr) < 0)
-goto exit_snooprequnlock;
+goto cleanup;
 
 if (!instantiate) {
 rc = 0;
-goto exit_snooprequnlock;
+goto cleanup;
 }
 
 /* instantiate the filters */
@@ -469,7 +469,7 @@ 
virNWFilterSnoopIPLeaseInstallRule(virNWFilterSnoopIPLeasePtr ipl,
   req->ifindex);
 }
 
- exit_snooprequnlock:
+ cleanup:
 virNWFilterSnoopReqUnlock(req);
 return rc;
 }
@@ -718,7 +718,7 @@ virNWFilterSnoopReqLeaseAdd(virNWFilterSnoopReqPtr req,
 
 virNWFilterSnoopReqUnlock(req);
 
-goto exit;
+goto cleanup;
 }
 
 virNWFilterSnoopReqUnlock(req);
@@ -742,7 +742,7 @@ virNWFilterSnoopReqLeaseAdd(virNWFilterSnoopReqPtr req,
 
 g_atomic_int_add(, 1);
 
- exit:
+ cleanup:
 if (update_leasefile)
 virNWFilterSnoopLeaseFileSave(pl);
 
@@ -885,7 +885,7 @@ virNWFilterSnoopDHCPGetOpt(virNWFilterSnoopDHCPHdrPtr pd, 
int len,
 switch (pd->d_opts[oind]) {
 case DHCPO_LEASE:
 if (olen - oind < 6)
-goto malformed;
+goto error;
 if (*pleasetime)
 return -1;  /* duplicate lease time */
 memcpy(, (char *)pd->d_opts + oind + 2, sizeof(nwint));
@@ -893,7 +893,7 @@ virNWFilterSnoopDHCPGetOpt(virNWFilterSnoopDHCPHdrPtr pd, 
int len,
 break;
 case DHCPO_MTYPE:
 if (olen - oind < 3)
-goto malformed;
+goto error;
 if (*pmtype)
 return -1;  /* duplicate message type */
 *pmtype = pd->d_opts[oind + 2];
@@ -905,12 +905,12 @@ virNWFilterSnoopDHCPGetOpt(virNWFilterSnoopDHCPHdrPtr pd, 
int len,
 return 0;
 default:
 if (olen - oind < 2)
-goto malformed;
+goto error;
 }
 oind += pd->d_opts[oind + 1] + 2;
 }
 return 0;
- malformed:
+ error:
 VIR_WARN("got lost in the options!");
 return -1;
 }
@@ -1362,7 +1362,7 @@ virNWFilterDHCPSnoopThread(void *req0)
 virNWFilterSnoopReqUnlock(req);
 
 if (req->threadStatus != THREAD_STATUS_OK)
-goto exit;
+goto cleanup;
 
 while (!error) {
 if (virNWFilterSnoopAdjustPoll(pcapConf,
@@ -1390,7 +1390,7 @@ virNWFilterDHCPSnoopThread(void *req0)
  */
 if (!virNWFilterSnoopIsActive(threadkey) ||
 req->jobCompletionStatus != 0)
-goto exit;
+goto cleanup;
 
 for (i = 0; n > 0 && i < G_N_ELEMENTS(fds); i++) {
 if (!fds[i].revents)
@@ -1507,7 +1507,7 @@ virNWFilterDHCPSnoopThread(void *req0)
 virNWFilterSnoopReqUnlock(req);
 virNWFilterSnoopUnlock();
 
- exit:
+ cleanup:
 virThreadPoolFree(worker);
 
 virNWFilterSnoopReqPut(req);
@@ -1736,14 +1736,14 @@ 
virNWFilterSnoopLeaseFileSave(virNWFilterSnoopIPLeasePtr ipl)
 virNWFilterSnoopLeaseFileOpen();
 if (virNWFilterSnoopLeaseFileWrite(virNWFilterSnoopState.leaseFD,
req->ifkey, ipl) < 0)
-goto err_exit;
+goto error;
 
 /* keep dead leases at < ~95% of file size */
 if (g_atomic_int_add(, 1) >=
 g_atomic_int_get() * 20)
 virNWFilterSnoopLeaseFileLoad();   /* load & refresh lease file */
 
- err_exit:
+ error:
 virNWFilterSnoopUnlock();
 }
 
@@ -1838,7 +1838,7 @@ virNWFilterSnoopLeaseFileRefresh(void)
 if (VIR_CLOSE(tfd) < 0) {
 virReportSystemError(errno, _("unable to close %s"), TMPLEASEFILE);
 /* assuming the old lease file is still better, skip the renaming */
-goto skip_rename;
+goto cleanup;
 }
 
 if (rename(TMPLEASEFILE, LEASEFILE) < 0) {
@@ -1848,7 +1848,7 @@ virNWFilterSnoopLeaseFileRefresh(void)
 }
 g_atomic_int_set(, 0);
 
- skip_rename:
+ cleanup:
 virNWFilterSnoopLeaseFileOpen();
 }
 
@@ -2013,14 +2013,14 @@ virN

[PATCH 08/25] network: fix memory leak in networkBuildDhcpDaemonCommandLine()

2020-06-24 Thread Laine Stump
hostsfilestr was not being freed. This will be turned into g_autofree
in an upcoming patch converting a lot more of the same file to using
g_auto*, but I wanted to make a separate patch for this first so the
other patch is simpler to review.

Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 47d5d95678..aff1b7b1bc 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -1628,6 +1628,7 @@ 
networkBuildDhcpDaemonCommandLine(virNetworkDriverStatePtr driver,
 virObjectUnref(dnsmasq_caps);
 VIR_FREE(configfile);
 VIR_FREE(configstr);
+VIR_FREE(hostsfilestr);
 VIR_FREE(leaseshelper_path);
 return ret;
 }
-- 
2.25.4



[PATCH 11/25] network: use g_free() in place of remaining VIR_FREE()

2020-06-24 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c | 59 +
 1 file changed, 33 insertions(+), 26 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index 668aa9ca88..a1b2f5b6c7 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -148,7 +148,7 @@ networkDnsmasqDefNamespaceFree(void *nsdata)
 
 virStringListFreeCount(def->options, def->noptions);
 
-VIR_FREE(def);
+g_free(def);
 }
 
 
@@ -706,7 +706,8 @@ networkStateInitialize(bool privileged,
 
 network_driver->lockFD = -1;
 if (virMutexInit(_driver->lock) < 0) {
-VIR_FREE(network_driver);
+g_free(network_driver);
+network_driver = NULL;
 goto error;
 }
 
@@ -874,18 +875,19 @@ networkStateCleanup(void)
 virPidFileRelease(network_driver->stateDir, "driver",
   network_driver->lockFD);
 
-VIR_FREE(network_driver->networkConfigDir);
-VIR_FREE(network_driver->networkAutostartDir);
-VIR_FREE(network_driver->stateDir);
-VIR_FREE(network_driver->pidDir);
-VIR_FREE(network_driver->dnsmasqStateDir);
-VIR_FREE(network_driver->radvdStateDir);
+g_free(network_driver->networkConfigDir);
+g_free(network_driver->networkAutostartDir);
+g_free(network_driver->stateDir);
+g_free(network_driver->pidDir);
+g_free(network_driver->dnsmasqStateDir);
+g_free(network_driver->radvdStateDir);
 
 virObjectUnref(network_driver->dnsmasqCaps);
 
 virMutexDestroy(_driver->lock);
 
-VIR_FREE(network_driver);
+g_free(network_driver);
+network_driver = NULL;
 
 return 0;
 }
@@ -2192,7 +2194,7 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
 /* Prevent guests from hijacking the host network by sending out
  * their own router advertisements.
  */
-VIR_FREE(field);
+g_free(field);
 field = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/accept_ra",
 def->bridge);
 
@@ -2205,7 +2207,7 @@ networkSetIPv6Sysctls(virNetworkObjPtr obj)
 /* All interfaces used as a gateway (which is what this is, by
  * definition), must always have autoconf=0.
  */
-VIR_FREE(field);
+g_free(field);
 field = g_strdup_printf(SYSCTL_PATH "/net/ipv6/conf/%s/autoconf", 
def->bridge);
 
 if (virFileWriteStr(field, "0", 0) < 0) {
@@ -2713,19 +2715,19 @@ networkCreateInterfacePool(virNetworkDefPtr netdef)
 for (i = 0; i < netdef->forward.nifs; i++) {
 if (netdef->forward.ifs[i].type
 == VIR_NETWORK_FORWARD_HOSTDEV_DEVICE_NETDEV)
-VIR_FREE(netdef->forward.ifs[i].device.dev);
+g_free(netdef->forward.ifs[i].device.dev);
 }
 netdef->forward.nifs = 0;
 }
 if (netdef->forward.nifs == 0)
-VIR_FREE(netdef->forward.ifs);
+g_free(netdef->forward.ifs);
 
 for (i = 0; i < numVirtFns; i++) {
-VIR_FREE(vfNames[i]);
-VIR_FREE(virtFns[i]);
+g_free(vfNames[i]);
+g_free(virtFns[i]);
 }
-VIR_FREE(vfNames);
-VIR_FREE(virtFns);
+g_free(vfNames);
+g_free(virtFns);
 return ret;
 }
 
@@ -3161,7 +3163,7 @@ networkFindUnusedBridgeName(virNetworkObjListPtr nets,
  */
 if (!(virNetworkObjBridgeInUse(nets, newname, def->name) ||
   virNetDevExists(newname) == 1)) {
-VIR_FREE(def->bridge); /*could contain template */
+g_free(def->bridge); /*could contain template */
 def->bridge = g_steal_pointer();
 return 0;
 }
@@ -4256,7 +4258,8 @@ networkGetDHCPLeases(virNetworkPtr net,
 nleases++;
 }
 
-VIR_FREE(lease);
+g_free(lease);
+lease = NULL;
 }
 
 if (leases_ret) {
@@ -4269,7 +4272,7 @@ networkGetDHCPLeases(virNetworkPtr net,
 rv = nleases;
 
  cleanup:
-VIR_FREE(lease);
+g_free(lease);
 virNetworkObjEndAPI();
 
 return rv;
@@ -4278,7 +4281,7 @@ networkGetDHCPLeases(virNetworkPtr net,
 if (leases_ret) {
 for (i = 0; i < nleases; i++)
 virNetworkDHCPLeaseFree(leases_ret[i]);
-VIR_FREE(leases_ret);
+g_free(leases_ret);
 }
 goto cleanup;
 }
@@ -4402,7 +4405,7 @@ networkAllocatePort(virNetworkObjPtr obj,
 return -1;
 }
 if (portprofile) {
-VIR_FREE(port->virtPortProfile);
+g_free(port->virtPortProfile);
 port->virtPortProfile = portprofile;
 }
 
@@ -5519,10 +5522,14 @@ networkPortSetParameters(virNetworkPortPtr port,
 /* average or floor are mandatory, peak and burst are optional.
  * So if no average or floor is given, we free inbound/outbound
  * here which causes inbound/outbound to not be set. */
-if (!bandwidth->in-&g

[PATCH 21/25] nwfilter: convert local pointers to use g_auto*

2020-06-24 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_dhcpsnoop.c |  91 
 src/nwfilter/nwfilter_ebiptables_driver.c | 170 +-
 src/nwfilter/nwfilter_gentech_driver.c|  19 +--
 src/nwfilter/nwfilter_learnipaddr.c   |   9 +-
 4 files changed, 108 insertions(+), 181 deletions(-)

diff --git a/src/nwfilter/nwfilter_dhcpsnoop.c 
b/src/nwfilter/nwfilter_dhcpsnoop.c
index f54e1a88e0..32cd6492ad 100644
--- a/src/nwfilter/nwfilter_dhcpsnoop.c
+++ b/src/nwfilter/nwfilter_dhcpsnoop.c
@@ -292,18 +292,17 @@ static const unsigned char dhcp_magic[4] = { 99, 130, 83, 
99 };
 static char *
 virNWFilterSnoopActivate(virNWFilterSnoopReqPtr req)
 {
-char *key;
-
-key = g_strdup_printf("%p-%d", req, req->ifindex);
+g_autofree char *key = g_strdup_printf("%p-%d", req, req->ifindex);
+char *ret = NULL;
 
 virNWFilterSnoopActiveLock();
 
-if (virHashAddEntry(virNWFilterSnoopState.active, key, (void *)0x1) < 0)
-VIR_FREE(key);
+if (virHashAddEntry(virNWFilterSnoopState.active, key, (void *)0x1) == 0)
+ret = g_steal_pointer();
 
 virNWFilterSnoopActiveUnlock();
 
-return key;
+return ret;
 }
 
 static void
@@ -442,11 +441,10 @@ static int
 virNWFilterSnoopIPLeaseInstallRule(virNWFilterSnoopIPLeasePtr ipl,
bool instantiate)
 {
-char *ipaddr;
+g_autofree char *ipaddr = virSocketAddrFormat(>ipAddress);
 int rc = -1;
 virNWFilterSnoopReqPtr req;
 
-ipaddr = virSocketAddrFormat(>ipAddress);
 if (!ipaddr)
 return -1;
 
@@ -473,9 +471,6 @@ 
virNWFilterSnoopIPLeaseInstallRule(virNWFilterSnoopIPLeasePtr ipl,
 
  exit_snooprequnlock:
 virNWFilterSnoopReqUnlock(req);
-
-VIR_FREE(ipaddr);
-
 return rc;
 }
 
@@ -551,7 +546,7 @@ virNWFilterSnoopReqGet(virNWFilterSnoopReqPtr req)
 static virNWFilterSnoopReqPtr
 virNWFilterSnoopReqNew(const char *ifkey)
 {
-virNWFilterSnoopReqPtr req;
+g_autofree virNWFilterSnoopReqPtr req = g_new0(virNWFilterSnoopReq, 1);
 
 if (ifkey == NULL || strlen(ifkey) != VIR_IFKEY_LEN - 1) {
 virReportError(VIR_ERR_INTERNAL_ERROR,
@@ -562,28 +557,20 @@ virNWFilterSnoopReqNew(const char *ifkey)
 return NULL;
 }
 
-req = g_new0(virNWFilterSnoopReq, 1);
-
 req->threadStatus = THREAD_STATUS_NONE;
 
-if (virStrcpyStatic(req->ifkey, ifkey) < 0||
-virMutexInitRecursive(>lock) < 0)
-goto err_free_req;
+if (virStrcpyStatic(req->ifkey, ifkey) < 0 ||
+virMutexInitRecursive(>lock) < 0) {
+return NULL;
+}
 
-if (virCondInit(>threadStatusCond) < 0)
-goto err_destroy_mutex;
+if (virCondInit(>threadStatusCond) < 0) {
+virMutexDestroy(>lock);
+return NULL;
+}
 
 virNWFilterSnoopReqGet(req);
-
-return req;
-
- err_destroy_mutex:
-virMutexDestroy(>lock);
-
- err_free_req:
-VIR_FREE(req);
-
-return NULL;
+return g_steal_pointer();
 }
 
 /*
@@ -815,7 +802,7 @@ virNWFilterSnoopReqLeaseDel(virNWFilterSnoopReqPtr req,
 {
 int ret = 0;
 virNWFilterSnoopIPLeasePtr ipl;
-char *ipstr = NULL;
+g_autofree char *ipstr = NULL;
 
 /* protect req->start, req->ifname and the lease */
 virNWFilterSnoopReqLock(req);
@@ -868,8 +855,6 @@ virNWFilterSnoopReqLeaseDel(virNWFilterSnoopReqPtr req,
 ignore_value(!!g_atomic_int_dec_and_test());
 
  lease_not_found:
-VIR_FREE(ipstr);
-
 virNWFilterSnoopReqUnlock(req);
 
 return ret;
@@ -1045,7 +1030,7 @@ virNWFilterSnoopDHCPOpen(const char *ifname, virMacAddr 
*mac,
 pcap_t *handle = NULL;
 struct bpf_program fp;
 char pcap_errbuf[PCAP_ERRBUF_SIZE];
-char *ext_filter = NULL;
+g_autofree char *ext_filter = NULL;
 char macaddr[VIR_MAC_STRING_BUFLEN];
 
 virMacAddrFormat(mac, macaddr);
@@ -1075,7 +1060,7 @@ virNWFilterSnoopDHCPOpen(const char *ifname, virMacAddr 
*mac,
 if (handle == NULL) {
 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("pcap_create failed"));
-goto cleanup_nohandle;
+return NULL;
 }
 
 if (pcap_set_snaplen(handle, PCAP_PBUFSIZE) < 0 ||
@@ -1107,17 +1092,12 @@ virNWFilterSnoopDHCPOpen(const char *ifname, virMacAddr 
*mac,
 }
 
 pcap_freecode();
-VIR_FREE(ext_filter);
-
 return handle;
 
  cleanup_freecode:
 pcap_freecode();
  cleanup:
 pcap_close(handle);
- cleanup_nohandle:
-VIR_FREE(ext_filter);
-
 return NULL;
 }
 
@@ -1128,7 +1108,7 @@ virNWFilterSnoopDHCPOpen(const char *ifname, virMacAddr 
*mac,
 static void virNWFilterDHCPDecodeWorker(void *jobdata, void *opaque)
 {
 virNWFilterSnoopReqPtr req = opaque;
-virNWFilterDHCPDecodeJobPtr job = jobdata;
+g_autofree virNWFilterDHCPDecodeJobPtr job = jobdata;
 virNWFilterSnoopEthHdrPtr packet = (virNWFilterSnoopEthHdrPtr)job->packet;
 
 if (vir

[PATCH 20/25] nwfilter: remove unnecessary code from ebtablesGetSubChainInsts()

2020-06-24 Thread Laine Stump
On failure, this function would clear out and free the list of
subchains it had been called with. This is unnecessary, because the
*only* caller of this function will also clear out and free the list
of subchains if it gets a failure from ebtablesGetSubChainInsts().

(It also makes more logical sense for the function that is creating
the entire list to be the one freeing the entire list, rather than
having a function whose purpose is only to create *one item* on the
list freeing the entire list).

Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_ebiptables_driver.c | 6 --
 1 file changed, 6 deletions(-)

diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index 89c131e17f..8fdc8e8897 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -3334,12 +3334,6 @@ ebtablesGetSubChainInsts(virHashTablePtr chains,
 
  cleanup:
 VIR_FREE(filter_names);
-if (ret < 0) {
-for (i = 0; i < *ninsts; i++)
-VIR_FREE(*insts[i]);
-VIR_FREE(*insts);
-*ninsts = 0;
-}
 return ret;
 
 }
-- 
2.25.4



[PATCH 10/25] network: convert local pointers to g_auto*

2020-06-24 Thread Laine Stump
This includes those that use plain VIR_FREE() as well as those that
have a cleanup function defined for use via g_auto/g_autoptr
(virCommand, virFirewall, virBuffer, virJSONValue etc).

Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c   | 477 +++---
 src/network/bridge_driver_linux.c |  55 ++--
 src/network/leaseshelper.c|  16 +-
 src/util/virdnsmasq.h |   4 +
 4 files changed, 209 insertions(+), 343 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index aff1b7b1bc..668aa9ca88 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -322,25 +322,23 @@ networkRunHook(virNetworkObjPtr obj,
int sub_op)
 {
 virNetworkDefPtr def;
-virBuffer buf = VIR_BUFFER_INITIALIZER;
-char *xml = NULL;
+g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
+g_autofree char *xml = NULL;
 int hookret;
-int ret = -1;
 
 if (virHookPresent(VIR_HOOK_DRIVER_NETWORK)) {
 if (!obj) {
 VIR_DEBUG("Not running hook as @obj is NULL");
-ret = 0;
-goto cleanup;
+return 0;
 }
 def = virNetworkObjGetDef(obj);
 
 virBufferAddLit(, "\n");
 virBufferAdjustIndent(, 2);
 if (virNetworkDefFormatBuf(, def, network_driver->xmlopt, 0) < 0)
-goto cleanup;
+return -1;
 if (port && virNetworkPortDefFormatBuf(, port) < 0)
-goto cleanup;
+return -1;
 
 virBufferAdjustIndent(, -2);
 virBufferAddLit(, "");
@@ -353,16 +351,12 @@ networkRunHook(virNetworkObjPtr obj,
  * If the script raised an error, pass it to the callee.
  */
 if (hookret < 0)
-goto cleanup;
+return -1;
 
 networkNetworkObjTaint(obj, VIR_NETWORK_TAINT_HOOK);
 }
 
-ret = 0;
- cleanup:
-virBufferFreeAndReset();
-VIR_FREE(xml);
-return ret;
+return 0;
 }
 
 
@@ -426,44 +420,42 @@ static int
 networkRemoveInactive(virNetworkDriverStatePtr driver,
   virNetworkObjPtr obj)
 {
-char *leasefile = NULL;
-char *customleasefile = NULL;
-char *radvdconfigfile = NULL;
-char *configfile = NULL;
-char *radvdpidbase = NULL;
-char *statusfile = NULL;
-char *macMapFile = NULL;
-dnsmasqContext *dctx = NULL;
+g_autofree char *leasefile = NULL;
+g_autofree char *customleasefile = NULL;
+g_autofree char *radvdconfigfile = NULL;
+g_autofree char *configfile = NULL;
+g_autofree char *radvdpidbase = NULL;
+g_autofree char *statusfile = NULL;
+g_autofree char *macMapFile = NULL;
+g_autoptr(dnsmasqContext) dctx = NULL;
 virNetworkDefPtr def = virNetworkObjGetPersistentDef(obj);
 
-int ret = -1;
-
 /* remove the (possibly) existing dnsmasq and radvd files */
 if (!(dctx = dnsmasqContextNew(def->name,
driver->dnsmasqStateDir))) {
-goto cleanup;
+return -1;
 }
 
 if (!(leasefile = networkDnsmasqLeaseFileNameDefault(driver, def->name)))
-goto cleanup;
+return -1;
 
 if (!(customleasefile = networkDnsmasqLeaseFileNameCustom(driver, 
def->bridge)))
-goto cleanup;
+return -1;
 
 if (!(radvdconfigfile = networkRadvdConfigFileName(driver, def->name)))
-goto cleanup;
+return -1;
 
 if (!(radvdpidbase = networkRadvdPidfileBasename(def->name)))
-goto cleanup;
+return -1;
 
 if (!(configfile = networkDnsmasqConfigFileName(driver, def->name)))
-goto cleanup;
+return -1;
 
 if (!(statusfile = virNetworkConfigFile(driver->stateDir, def->name)))
-goto cleanup;
+return -1;
 
 if (!(macMapFile = virMacMapFileName(driver->dnsmasqStateDir, 
def->bridge)))
-goto cleanup;
+return -1;
 
 /* dnsmasq */
 dnsmasqDelete(dctx);
@@ -484,18 +476,7 @@ networkRemoveInactive(virNetworkDriverStatePtr driver,
 /* remove the network definition */
 virNetworkObjRemoveInactive(driver->networks, obj);
 
-ret = 0;
-
- cleanup:
-VIR_FREE(leasefile);
-VIR_FREE(configfile);
-VIR_FREE(customleasefile);
-VIR_FREE(radvdconfigfile);
-VIR_FREE(radvdpidbase);
-VIR_FREE(statusfile);
-VIR_FREE(macMapFile);
-dnsmasqContextFree(dctx);
-return ret;
+return 0;
 }
 
 
@@ -545,9 +526,9 @@ networkUpdateState(virNetworkObjPtr obj,
 {
 virNetworkDefPtr def;
 virNetworkDriverStatePtr driver = opaque;
-dnsmasqCapsPtr dnsmasq_caps = networkGetDnsmasqCaps(driver);
+g_autoptr(dnsmasqCaps) dnsmasq_caps = networkGetDnsmasqCaps(driver);
 virMacMapPtr macmap;
-char *macMapFile = NULL;
+g_autofree char *macMapFile = NULL;
 int ret = -1;
 
 virObjectLock(obj);
@@ -609,7 +590,7 @@ networkUpdateState(v

[PATCH 12/25] network: make networkDnsmasqXmlNsDef private to bridge_driver.c

2020-06-24 Thread Laine Stump
This struct isn't used anywhere else.

Signed-off-by: Laine Stump 
---
 src/network/bridge_driver.c | 10 ++
 src/network/bridge_driver.h |  9 -
 2 files changed, 10 insertions(+), 9 deletions(-)

diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c
index a1b2f5b6c7..275502b778 100644
--- a/src/network/bridge_driver.c
+++ b/src/network/bridge_driver.c
@@ -139,6 +139,16 @@ networkDnsmasqCapsRefresh(virNetworkDriverStatePtr driver)
 }
 
 
+extern virXMLNamespace networkDnsmasqXMLNamespace;
+
+typedef struct _networkDnsmasqXmlNsDef networkDnsmasqXmlNsDef;
+typedef networkDnsmasqXmlNsDef *networkDnsmasqXmlNsDefPtr;
+struct _networkDnsmasqXmlNsDef {
+size_t noptions;
+char **options;
+};
+
+
 static void
 networkDnsmasqDefNamespaceFree(void *nsdata)
 {
diff --git a/src/network/bridge_driver.h b/src/network/bridge_driver.h
index fb0ccad4b1..2613fc629d 100644
--- a/src/network/bridge_driver.h
+++ b/src/network/bridge_driver.h
@@ -27,15 +27,6 @@
 #include "virdnsmasq.h"
 #include "virnetworkobj.h"
 
-extern virXMLNamespace networkDnsmasqXMLNamespace;
-
-typedef struct _networkDnsmasqXmlNsDef networkDnsmasqXmlNsDef;
-typedef networkDnsmasqXmlNsDef *networkDnsmasqXmlNsDefPtr;
-struct _networkDnsmasqXmlNsDef {
-size_t noptions;
-char **options;
-};
-
 virNetworkXMLOptionPtr
 networkDnsmasqCreateXMLConf(void);
 
-- 
2.25.4



[PATCH 16/25] squash into 'network: convert local pointers to g_auto*'

2020-06-24 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/network/bridge_driver_linux.c | 9 ++---
 1 file changed, 2 insertions(+), 7 deletions(-)

diff --git a/src/network/bridge_driver_linux.c 
b/src/network/bridge_driver_linux.c
index 0d0ac730f2..7f765bcf99 100644
--- a/src/network/bridge_driver_linux.c
+++ b/src/network/bridge_driver_linux.c
@@ -834,7 +834,7 @@ int networkAddFirewallRules(virNetworkDefPtr def)
 {
 size_t i;
 virNetworkIPDefPtr ipdef;
-g_autoptr(virFirewall) fw = NULL;
+g_autoptr(virFirewall) fw = virFirewallNew();
 
 if (virOnce(, networkSetupPrivateChains) < 0)
 return -1;
@@ -920,8 +920,6 @@ int networkAddFirewallRules(virNetworkDefPtr def)
 }
 }
 
-fw = virFirewallNew();
-
 virFirewallStartTransaction(fw, 0);
 
 networkAddGeneralFirewallRules(fw, def);
@@ -946,10 +944,7 @@ int networkAddFirewallRules(virNetworkDefPtr def)
 virFirewallStartTransaction(fw, VIR_FIREWALL_TRANSACTION_IGNORE_ERRORS);
 networkAddChecksumFirewallRules(fw, def);
 
-if (virFirewallApply(fw) < 0)
-return -1;
-
-return 0;
+return virFirewallApply(fw);
 }
 
 /* Remove all rules for all ip addresses (and general rules) on a network */
-- 
2.25.4



[PATCH 04/25] util: validate return from xmlNodeGetContent before use

2020-06-24 Thread Laine Stump
There were a few uses of xmlNodeGetContent() that didn't check for
NULL before using the result.

A NULL return from xmlNodeGetContent() *could* (probably does) mean
that there was an Out of Memory condition, but it is unclear from the
documentation if that is always the case, or if it could just indicate
a missing value in the document, so we don't report an OOM error, but
just don't try to use it for, e.g., conversion to an integer.

Signed-off-by: Laine Stump 
---
 src/conf/domain_conf.c | 28 ++--
 1 file changed, 14 insertions(+), 14 deletions(-)

diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index 8cde1cd0e8..4d27c9caa8 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -10556,22 +10556,22 @@ virDomainDiskDefParseXML(virDomainXMLOptionPtr xmlopt,
virXMLNodeNameEqual(cur, "wwn")) {
 wwn = (char *)xmlNodeGetContent(cur);
 
-if (!virValidateWWN(wwn))
+if (wwn && !virValidateWWN(wwn))
 goto error;
 } else if (!vendor &&
virXMLNodeNameEqual(cur, "vendor")) {
-vendor = (char *)xmlNodeGetContent(cur);
-
-if (strlen(vendor) > VENDOR_LEN) {
-virReportError(VIR_ERR_XML_ERROR, "%s",
-   _("disk vendor is more than 8 characters"));
-goto error;
-}
+if ((vendor = (char *)xmlNodeGetContent(cur))) {
+if (strlen(vendor) > VENDOR_LEN) {
+virReportError(VIR_ERR_XML_ERROR, "%s",
+   _("disk vendor is more than 8 characters"));
+goto error;
+}
 
-if (!virStringIsPrintable(vendor)) {
-virReportError(VIR_ERR_XML_ERROR, "%s",
-   _("disk vendor is not printable string"));
-goto error;
+if (!virStringIsPrintable(vendor)) {
+virReportError(VIR_ERR_XML_ERROR, "%s",
+   _("disk vendor is not printable string"));
+goto error;
+}
 }
 } else if (!product &&
virXMLNodeNameEqual(cur, "product")) {
@@ -20374,8 +20374,8 @@ virDomainDefParseBootOptions(virDomainDefPtr def,
 
 if (STREQ_NULLABLE(tmp, "slic")) {
 VIR_FREE(tmp);
-tmp = virXMLNodeContentString(nodes[0]);
-def->os.slic_table = virFileSanitizePath(tmp);
+if ((tmp = virXMLNodeContentString(nodes[0])))
+def->os.slic_table = virFileSanitizePath(tmp);
 } else {
 virReportError(VIR_ERR_XML_ERROR,
_("Unknown acpi table type: %s"),
-- 
2.25.4



[PATCH 22/25] nwfilter: convert remaining VIR_FREE() to g_free()

2020-06-24 Thread Laine Stump
Signed-off-by: Laine Stump 
---
 src/nwfilter/nwfilter_dhcpsnoop.c | 16 
 src/nwfilter/nwfilter_driver.c| 10 +-
 src/nwfilter/nwfilter_ebiptables_driver.c |  2 +-
 src/nwfilter/nwfilter_gentech_driver.c|  6 +++---
 src/nwfilter/nwfilter_learnipaddr.c   |  8 
 5 files changed, 21 insertions(+), 21 deletions(-)

diff --git a/src/nwfilter/nwfilter_dhcpsnoop.c 
b/src/nwfilter/nwfilter_dhcpsnoop.c
index 32cd6492ad..e41062feca 100644
--- a/src/nwfilter/nwfilter_dhcpsnoop.c
+++ b/src/nwfilter/nwfilter_dhcpsnoop.c
@@ -314,7 +314,7 @@ virNWFilterSnoopCancel(char **threadKey)
 virNWFilterSnoopActiveLock();
 
 ignore_value(virHashRemoveEntry(virNWFilterSnoopState.active, *threadKey));
-VIR_FREE(*threadKey);
+g_free(*threadKey);
 
 virNWFilterSnoopActiveUnlock();
 }
@@ -600,7 +600,7 @@ virNWFilterSnoopReqFree(virNWFilterSnoopReqPtr req)
 virCondDestroy(>threadStatusCond);
 virFreeError(req->threadError);
 
-VIR_FREE(req);
+g_free(req);
 }
 
 /*
@@ -731,7 +731,7 @@ virNWFilterSnoopReqLeaseAdd(virNWFilterSnoopReqPtr req,
 
 if (req->threadkey && virNWFilterSnoopIPLeaseInstallRule(pl, true) < 0) {
 virNWFilterSnoopReqUnlock(req);
-VIR_FREE(pl);
+g_free(pl);
 return -1;
 }
 
@@ -850,7 +850,7 @@ virNWFilterSnoopReqLeaseDel(virNWFilterSnoopReqPtr req,
 }
 
  skip_instantiate:
-VIR_FREE(ipl);
+g_free(ipl);
 
 ignore_value(!!g_atomic_int_dec_and_test());
 
@@ -1149,7 +1149,7 @@ virNWFilterSnoopDHCPDecodeJobSubmit(virThreadPoolPtr pool,
 if (ret == 0)
 g_atomic_int_add(qCtr, 1);
 else
-VIR_FREE(job);
+g_free(job);
 
 return ret;
 }
@@ -1502,7 +1502,7 @@ virNWFilterDHCPSnoopThread(void *req0)
 ignore_value(virHashRemoveEntry(virNWFilterSnoopState.ifnameToKey,
 req->binding->portdevname));
 
-VIR_FREE(req->binding->portdevname);
+g_free(req->binding->portdevname);
 
 virNWFilterSnoopReqUnlock(req);
 virNWFilterSnoopUnlock();
@@ -1970,7 +1970,7 @@ virNWFilterSnoopRemAllReqIter(const void *payload,
  */
 virNWFilterIPAddrMapDelIPAddr(req->binding->portdevname, NULL);
 
-VIR_FREE(req->binding->portdevname);
+g_free(req->binding->portdevname);
 }
 
 virNWFilterSnoopReqUnlock(req);
@@ -2079,7 +2079,7 @@ virNWFilterDHCPSnoopEnd(const char *ifname)
 /* keep valid lease req; drop interface association */
 virNWFilterSnoopCancel(>threadkey);
 
-VIR_FREE(req->binding->portdevname);
+g_free(req->binding->portdevname);
 
 virNWFilterSnoopReqUnlock(req);
 
diff --git a/src/nwfilter/nwfilter_driver.c b/src/nwfilter/nwfilter_driver.c
index 39d0a2128e..7853ad59fa 100644
--- a/src/nwfilter/nwfilter_driver.c
+++ b/src/nwfilter/nwfilter_driver.c
@@ -303,7 +303,7 @@ nwfilterStateInitialize(bool privileged,
 
  err_free_driverstate:
 virNWFilterObjListFree(driver->nwfilters);
-VIR_FREE(driver);
+g_free(driver);
 
 return VIR_DRV_STATE_INIT_ERROR;
 }
@@ -367,9 +367,9 @@ nwfilterStateCleanup(void)
 if (driver->lockFD != -1)
 virPidFileRelease(driver->stateDir, "driver", driver->lockFD);
 
-VIR_FREE(driver->stateDir);
-VIR_FREE(driver->configDir);
-VIR_FREE(driver->bindingDir);
+g_free(driver->stateDir);
+g_free(driver->configDir);
+g_free(driver->bindingDir);
 nwfilterDriverUnlock();
 }
 
@@ -379,7 +379,7 @@ nwfilterStateCleanup(void)
 virNWFilterObjListFree(driver->nwfilters);
 
 virMutexDestroy(>lock);
-VIR_FREE(driver);
+g_free(driver);
 
 return 0;
 }
diff --git a/src/nwfilter/nwfilter_ebiptables_driver.c 
b/src/nwfilter/nwfilter_ebiptables_driver.c
index b382b9405d..6e05e638aa 100644
--- a/src/nwfilter/nwfilter_ebiptables_driver.c
+++ b/src/nwfilter/nwfilter_ebiptables_driver.c
@@ -3518,7 +3518,7 @@ ebiptablesApplyNewRules(const char *ifname,
 
  cleanup:
 for (i = 0; i < nsubchains; i++)
-VIR_FREE(subchains[i]);
+g_free(subchains[i]);
 
 return ret;
 }
diff --git a/src/nwfilter/nwfilter_gentech_driver.c 
b/src/nwfilter/nwfilter_gentech_driver.c
index f586c7e938..183e2f0a91 100644
--- a/src/nwfilter/nwfilter_gentech_driver.c
+++ b/src/nwfilter/nwfilter_gentech_driver.c
@@ -122,7 +122,7 @@ virNWFilterRuleInstFree(virNWFilterRuleInstPtr inst)
 return;
 
 virHashFree(inst->vars);
-VIR_FREE(inst);
+g_free(inst);
 }
 
 
@@ -234,12 +234,12 @@ virNWFilterInstReset(virNWFilterInstPtr inst)
 
 for (i = 0; i < inst->nfilters; i++)
 virNWFilterObjUnlock(inst->filters[i]);
-VIR_FREE(inst->filters);
+g_free(inst->filters);
 inst->nfilters = 0;
 
 for (i = 0; i < inst->nrules; i++)
 virNWFilterRuleInst

[PATCH 00/25] Several g_auto* conversion and related small bugfixes

2020-06-24 Thread Laine Stump
This started out with me noticing a memory leak in a patch that led to
the realization that domain_conf.c hadn't been converted to use
g_autofree yet, and each step of the way uncovered some other
annoyance that I wanted to get rid of. Most of the changes are related
to converting code to use g_auto*, g_new0, and g_free, but there is
also a some of elimination of labels, fixing actual or theoretical
memory leaks, modifications for style, etc. None of it should have any
functional effect (except the fixing one or two memory leaks).


Laine Stump (25):
  conf, vmx: check for OOM after calling xmlBufferCreate()
  use g_autoptr for all xmlBuffers
  conf: refactor virDomainBlkioDeviceParseXML to remove possible NULL
dereference
  util: validate return from xmlNodeGetContent before use
  util: remove OOM error log from virGetHostnameImpl()
  conf: eliminate useless error label in virDomainFeaturesDefParse()
  util: eliminate error label in virDomainDefFormatInternalSetRootName()
  network: fix memory leak in networkBuildDhcpDaemonCommandLine()
  util: add g_autoptr cleanup function for virFirewall objects
  network: convert local pointers to g_auto*
  network: use g_free() in place of remaining VIR_FREE()
  network: make networkDnsmasqXmlNsDef private to bridge_driver.c
  define g_autoptr cleanup function for virNetworkDHCPLease
  network: replace VIR_ALLOC/REALLOC with g_new0/g_renew
  network: use proper arg type when calling virNetDevSetOnline()
  squash into 'network: convert local pointers to g_auto*'
  use g_autoptr() for all usages of virFirewallNew/Free
  nwfilter: define a typedef for struct ebtablesSubChainInst
  nwfilter replace VIR_ALLOC with g_new0
  nwfilter: remove unnecessary code from ebtablesGetSubChainInsts()
  nwfilter: convert local pointers to use g_auto*
  nwfilter: convert remaining VIR_FREE() to g_free()
  nwfilter: transform logic in virNWFilterRuleInstSort to eliminate
label
  nwfilter: use standard label names when reasonable
  replace g_new() with g_new0() for consistency

 src/conf/domain_conf.c| 254 +-
 src/conf/network_conf.c   |  10 +-
 src/datatypes.h   |   2 +
 src/network/bridge_driver.c   | 585 +-
 src/network/bridge_driver.h   |   9 -
 src/network/bridge_driver_linux.c |  58 +--
 src/network/leaseshelper.c|  16 +-
 src/nwfilter/nwfilter_dhcpsnoop.c | 150 +++---
 src/nwfilter/nwfilter_driver.c|  13 +-
 src/nwfilter/nwfilter_ebiptables_driver.c | 277 --
 src/nwfilter/nwfilter_gentech_driver.c|  60 +--
 src/nwfilter/nwfilter_learnipaddr.c   |  45 +-
 src/qemu/qemu_backup.c|   2 +-
 src/util/virdnsmasq.h |   4 +
 src/util/virebtables.c|  24 +-
 src/util/virfirewall.h|   1 +
 src/util/viriptables.c|  14 +-
 src/util/virutil.c|  12 +-
 src/util/virxml.c |  12 +-
 src/vmx/vmx.c |  17 +-
 tests/qemuhotplugmock.c   |   2 +-
 tests/virfirewalltest.c   |  50 +-
 22 files changed, 640 insertions(+), 977 deletions(-)

-- 
2.25.4



[PATCH 13/25] define g_autoptr cleanup function for virNetworkDHCPLease

2020-06-24 Thread Laine Stump
virNetworkDHCPLease and virNetworkDHCPLeaseFree() are declared in the
public API file libvirt-network.h, and we can't pollute that with glib
macro invocations, so put this in src/datatypes.h next to the other
virNetwork items.

Signed-off-by: Laine Stump 
---
 src/datatypes.h | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/src/datatypes.h b/src/datatypes.h
index d58429ad6c..ade3779e43 100644
--- a/src/datatypes.h
+++ b/src/datatypes.h
@@ -635,6 +635,8 @@ struct _virNetworkPort {
 
 G_DEFINE_AUTOPTR_CLEANUP_FUNC(virNetworkPort, virObjectUnref);
 
+/* virNetworkDHCPLease is defined in the public API - libvirt-network.h */
+G_DEFINE_AUTOPTR_CLEANUP_FUNC(virNetworkDHCPLease, virNetworkDHCPLeaseFree);
 
 /**
 * _virInterface:
-- 
2.25.4



[PATCH 02/25] use g_autoptr for all xmlBuffers

2020-06-24 Thread Laine Stump
AUTOPTR_CLEANUP_FUNC is set to xmlBufferFree() in util/virxml.h (This
is actually new - added accidentally (but fortunately harmlessly!) in
commit 257aba2dafe. I had added it along with the hunks in this patch,
then decided to remove it and submit separately, but missed taking out
the hunk in virxml.h)

Signed-off-by: Laine Stump 
---
 src/conf/domain_conf.c  |  4 +---
 src/conf/network_conf.c |  4 +---
 src/util/virxml.c   | 12 +++-
 src/vmx/vmx.c   | 10 +++---
 4 files changed, 8 insertions(+), 22 deletions(-)

diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index 9d057f8c78..1916b51d38 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -29579,7 +29579,7 @@ virDomainDefFormatInternalSetRootName(virDomainDefPtr 
def,
   def->description);
 
 if (def->metadata) {
-xmlBufferPtr xmlbuf;
+g_autoptr(xmlBuffer) xmlbuf = NULL;
 int oldIndentTreeOutput = xmlIndentTreeOutput;
 
 /* Indentation on output requires that we previously set
@@ -29596,12 +29596,10 @@ virDomainDefFormatInternalSetRootName(virDomainDefPtr 
def,
 
 if (xmlNodeDump(xmlbuf, def->metadata->doc, def->metadata,
 virBufferGetIndent(buf) / 2, 1) < 0) {
-xmlBufferFree(xmlbuf);
 xmlIndentTreeOutput = oldIndentTreeOutput;
 goto error;
 }
 virBufferAsprintf(buf, "%s\n", (char *) xmlBufferContent(xmlbuf));
-xmlBufferFree(xmlbuf);
 xmlIndentTreeOutput = oldIndentTreeOutput;
 }
 
diff --git a/src/conf/network_conf.c b/src/conf/network_conf.c
index 5b578f894c..4ebad1483c 100644
--- a/src/conf/network_conf.c
+++ b/src/conf/network_conf.c
@@ -2508,7 +2508,7 @@ virNetworkDefFormatBuf(virBufferPtr buf,
 virBufferAsprintf(buf, "%s\n", uuidstr);
 
 if (def->metadata) {
-xmlBufferPtr xmlbuf;
+g_autoptr(xmlBuffer) xmlbuf = NULL;
 int oldIndentTreeOutput = xmlIndentTreeOutput;
 
 /* Indentation on output requires that we previously set
@@ -2525,12 +2525,10 @@ virNetworkDefFormatBuf(virBufferPtr buf,
 
 if (xmlNodeDump(xmlbuf, def->metadata->doc, def->metadata,
 virBufferGetIndent(buf) / 2, 1) < 0) {
-xmlBufferFree(xmlbuf);
 xmlIndentTreeOutput = oldIndentTreeOutput;
 return -1;
 }
 virBufferAsprintf(buf, "%s\n", (char *) xmlBufferContent(xmlbuf));
-xmlBufferFree(xmlbuf);
 xmlIndentTreeOutput = oldIndentTreeOutput;
 }
 
diff --git a/src/util/virxml.c b/src/util/virxml.c
index 02b59ea2f8..848d549a8b 100644
--- a/src/util/virxml.c
+++ b/src/util/virxml.c
@@ -953,8 +953,7 @@ char *
 virXMLNodeToString(xmlDocPtr doc,
xmlNodePtr node)
 {
-xmlBufferPtr xmlbuf = NULL;
-char *ret = NULL;
+g_autoptr(xmlBuffer) xmlbuf = NULL;
 
 if (!(xmlbuf = xmlBufferCreate())) {
 virReportOOMError();
@@ -964,15 +963,10 @@ virXMLNodeToString(xmlDocPtr doc,
 if (xmlNodeDump(xmlbuf, doc, node, 0, 1) == 0) {
 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("failed to convert the XML node tree"));
-goto cleanup;
+return NULL;
 }
 
-ret = g_strdup((const char *)xmlBufferContent(xmlbuf));
-
- cleanup:
-xmlBufferFree(xmlbuf);
-
-return ret;
+return g_strdup((const char *)xmlBufferContent(xmlbuf));
 }
 
 
diff --git a/src/vmx/vmx.c b/src/vmx/vmx.c
index fa9766995c..67bbe27fde 100644
--- a/src/vmx/vmx.c
+++ b/src/vmx/vmx.c
@@ -697,8 +697,8 @@ virVMXConvertToUTF8(const char *encoding, const char 
*string)
 {
 char *result = NULL;
 xmlCharEncodingHandlerPtr handler;
-xmlBufferPtr input;
-xmlBufferPtr utf8;
+g_autoptr(xmlBuffer) input = NULL;
+g_autoptr(xmlBuffer) utf8 = NULL;
 
 handler = xmlFindCharEncodingHandler(encoding);
 
@@ -720,14 +720,10 @@ virVMXConvertToUTF8(const char *encoding, const char 
*string)
 goto cleanup;
 }
 
-result = (char *)utf8->content;
-utf8->content = NULL;
+result = (char *)g_steal_pointer(>content);
 
  cleanup:
 xmlCharEncCloseFunc(handler);
-xmlBufferFree(input);
-xmlBufferFree(utf8);
-
 return result;
 }
 
-- 
2.25.4



[PATCH 09/25] util: add g_autoptr cleanup function for virFirewall objects

2020-06-24 Thread Laine Stump
Put in a separate patch so that two future patches can be re-ordered /
selectively backported independent of each other.

Signed-off-by: Laine Stump 
---
 src/util/virfirewall.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/util/virfirewall.h b/src/util/virfirewall.h
index 6148f46827..ff690b36f0 100644
--- a/src/util/virfirewall.h
+++ b/src/util/virfirewall.h
@@ -40,6 +40,7 @@ virFirewallPtr virFirewallNew(void);
 
 void virFirewallFree(virFirewallPtr firewall);
 
+
 /**
  * virFirewallAddRule:
  * @firewall: firewall ruleset to add to
-- 
2.25.4



[PATCH 01/25] conf, vmx: check for OOM after calling xmlBufferCreate()

2020-06-24 Thread Laine Stump
Although libvirt itself uses g_malloc0() and friends, which exit when
there isn't enouogh memory, libxml2 uses standard malloc(), which just
returns NULL on OOM - this means we must check for NULL on return from
any libxml2 functions that allocate memory.

xmlBufferCreate(), for example, might return NULL, and we don't always
check for it. This patch adds checks where it isn't already done.

(NB: Although libxml2 has a provision for changing behavior on OOM (by
calling xmlMemSetup() to change what functions are used to
allocating/freeing memory), we can't use that, since parts of libvirt
code end up in libvirt.so, which is linked and called directly by
applications that may themselves use libxml2 (and may have already set
their own alternate malloc()), e.g. drivers like esx which live totally
in the library rather than a separate process.)

Signed-off-by: Laine Stump 
---
 src/conf/domain_conf.c  | 6 +-
 src/conf/network_conf.c | 6 +-
 src/vmx/vmx.c   | 7 +--
 3 files changed, 15 insertions(+), 4 deletions(-)

diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
index fc7fcfb0c6..9d057f8c78 100644
--- a/src/conf/domain_conf.c
+++ b/src/conf/domain_conf.c
@@ -29589,7 +29589,11 @@ virDomainDefFormatInternalSetRootName(virDomainDefPtr 
def,
  * Thankfully, libxml maps what looks like globals into
  * thread-local uses, so we are thread-safe.  */
 xmlIndentTreeOutput = 1;
-xmlbuf = xmlBufferCreate();
+if (!(xmlbuf = xmlBufferCreate())) {
+virReportOOMError();
+goto error;
+}
+
 if (xmlNodeDump(xmlbuf, def->metadata->doc, def->metadata,
 virBufferGetIndent(buf) / 2, 1) < 0) {
 xmlBufferFree(xmlbuf);
diff --git a/src/conf/network_conf.c b/src/conf/network_conf.c
index 87d43de1e3..5b578f894c 100644
--- a/src/conf/network_conf.c
+++ b/src/conf/network_conf.c
@@ -2518,7 +2518,11 @@ virNetworkDefFormatBuf(virBufferPtr buf,
  * Thankfully, libxml maps what looks like globals into
  * thread-local uses, so we are thread-safe.  */
 xmlIndentTreeOutput = 1;
-xmlbuf = xmlBufferCreate();
+if (!(xmlbuf = xmlBufferCreate())) {
+virReportOOMError();
+return -1;
+}
+
 if (xmlNodeDump(xmlbuf, def->metadata->doc, def->metadata,
 virBufferGetIndent(buf) / 2, 1) < 0) {
 xmlBufferFree(xmlbuf);
diff --git a/src/vmx/vmx.c b/src/vmx/vmx.c
index f2248cef53..fa9766995c 100644
--- a/src/vmx/vmx.c
+++ b/src/vmx/vmx.c
@@ -708,8 +708,11 @@ virVMXConvertToUTF8(const char *encoding, const char 
*string)
 return NULL;
 }
 
-input = xmlBufferCreateStatic((char *)string, strlen(string));
-utf8 = xmlBufferCreate();
+if (!(input = xmlBufferCreateStatic((char *)string, strlen(string))) ||
+!(utf8 = xmlBufferCreate())) {
+virReportOOMError();
+goto cleanup;
+}
 
 if (xmlCharEncInFunc(handler, utf8, input) < 0) {
 virReportError(VIR_ERR_INTERNAL_ERROR,
-- 
2.25.4



<    4   5   6   7   8   9   10   11   12   13   >