From babb4e6d31d43fc84f065ab01a6c831405fd7583 Mon Sep 17 00:00:00 2001 From: Michal Privoznik Date: Thu, 18 Apr 2019 13:59:15 +0200 Subject: [PATCH] virbuffer: Don't leak memory in virBufferAddBuffer If an error occurs in a virBuffer* API the idea is to free the content immediately and set @error member used in error reporting later. Well, this is not what how virBufferAddBuffer works. Signed-off-by: Michal Privoznik Reviewed-by: Erik Skultety Reviewed-by: Andrea Bolognani --- src/util/virbuffer.c | 2 +- tests/virbuftest.c | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/util/virbuffer.c b/src/util/virbuffer.c index 54703a28d8..b2ae7963a1 100644 --- a/src/util/virbuffer.c +++ b/src/util/virbuffer.c @@ -197,7 +197,7 @@ virBufferAddBuffer(virBufferPtr buf, virBufferPtr toadd) if (buf->error || toadd->error) { if (!buf->error) - buf->error = toadd->error; + virBufferSetError(buf, toadd->error); goto done; } diff --git a/tests/virbuftest.c b/tests/virbuftest.c index 778754d7c1..caad6f3ecb 100644 --- a/tests/virbuftest.c +++ b/tests/virbuftest.c @@ -303,6 +303,32 @@ static int testBufAddBuffer(const void *data ATTRIBUTE_UNUSED) return ret; } +static int +testBufAddBuffer2(const void *opaque ATTRIBUTE_UNUSED) +{ + VIR_AUTOCLEAN(virBuffer) buf1 = VIR_BUFFER_INITIALIZER; + VIR_AUTOCLEAN(virBuffer) buf2 = VIR_BUFFER_INITIALIZER; + + /* Intent of this test is to demonstrate a memleak that happen with + * virBufferAddBuffer */ + + virBufferAddLit(&buf1, "Hello world!\n"); + virBufferAddLit(&buf2, "Hello world!\n"); + + /* Intentional usage error */ + virBufferAdjustIndent(&buf2, -2); + + virBufferAddBuffer(&buf1, &buf2); + + if (virBufferCurrentContent(&buf1) || + !virBufferCurrentContent(&buf2)) { + VIR_TEST_DEBUG("Unexpected buffer content"); + return -1; + } + + return 0; +} + struct testBufAddStrData { const char *data; const char *expect; @@ -460,6 +486,7 @@ mymain(void) DO_TEST("Auto-indentation", testBufAutoIndent, 0); DO_TEST("Trim", testBufTrim, 0); DO_TEST("AddBuffer", testBufAddBuffer, 0); + DO_TEST("AddBuffer2", testBufAddBuffer2, 0); DO_TEST("set indent", testBufSetIndent, 0); DO_TEST("autoclean", testBufferAutoclean, 0); -- GitLab