openssl/test/bio_memleak_test.c
Corey Minyard 492f70645c Fix a memory leak in the mem bio
If you use a BIO and set up your own buffer that is not freed, the
memory bio will leak the BIO_BUF_MEM object it allocates.

The trouble is that the BIO_BUF_MEM is allocated and kept around,
but it is not freed if BIO_NOCLOSE is set.

The freeing of BIO_BUF_MEM was fairly confusing, simplify things
so mem_buf_free only frees the memory buffer and free the BIO_BUF_MEM
in mem_free(), where it should be done.

Alse add a test for a leak in the memory bio
Setting a memory buffer caused a leak.

Signed-off-by: Corey Minyard <minyard@acm.org>

Reviewed-by: Bernd Edlinger <bernd.edlinger@hotmail.de>
Reviewed-by: Paul Dale <paul.dale@oracle.com>
(Merged from https://github.com/openssl/openssl/pull/8051)

(cherry picked from commit c6048af23c)
2019-01-21 17:50:04 +10:00

54 lines
1.2 KiB
C

/*
* Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <string.h>
#include <openssl/buffer.h>
#include <openssl/bio.h>
#include "testutil.h"
static int test_bio_memleak(void)
{
int ok = 0;
BIO *bio;
BUF_MEM bufmem;
const char *str = "BIO test\n";
char buf[100];
bio = BIO_new(BIO_s_mem());
if (bio == NULL)
goto finish;
bufmem.length = strlen(str) + 1;
bufmem.data = (char *) str;
bufmem.max = bufmem.length;
BIO_set_mem_buf(bio, &bufmem, BIO_NOCLOSE);
BIO_set_flags(bio, BIO_FLAGS_MEM_RDONLY);
if (BIO_read(bio, buf, sizeof(buf)) <= 0)
goto finish;
ok = strcmp(buf, str) == 0;
finish:
BIO_free(bio);
return ok;
}
int global_init(void)
{
CRYPTO_set_mem_debug(1);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
return 1;
}
int setup_tests(void)
{
ADD_TEST(test_bio_memleak);
return 1;
}