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 <mprivozn@redhat.com>
Reviewed-by: Erik Skultety <eskultet@redhat.com>
Reviewed-by: Andrea Bolognani <abologna@redhat.com>
This commit is contained in:
Michal Privoznik 2019-04-18 13:59:15 +02:00
parent 63a960c725
commit babb4e6d31
2 changed files with 28 additions and 1 deletions

View File

@ -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;
}

View File

@ -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);