c11455fc6074f0bb75d153afb61ab5b46aca44c3
[openssl.git] / test / bio_memleak_test.c
1 /*
2  * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 #include <stdio.h>
10 #include <string.h>
11 #include <openssl/buffer.h>
12 #include <openssl/bio.h>
13
14 #include "testutil.h"
15
16 static int test_bio_memleak(void)
17 {
18     int ok = 0;
19     BIO *bio;
20     BUF_MEM bufmem;
21     static const char str[] = "BIO test\n";
22     char buf[100];
23
24     bio = BIO_new(BIO_s_mem());
25     if (!TEST_ptr(bio))
26         goto finish;
27     bufmem.length = sizeof(str);
28     bufmem.data = (char *) str;
29     bufmem.max = bufmem.length;
30     BIO_set_mem_buf(bio, &bufmem, BIO_NOCLOSE);
31     BIO_set_flags(bio, BIO_FLAGS_MEM_RDONLY);
32     if (!TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(str)))
33         goto finish;
34     if (!TEST_mem_eq(buf, sizeof(str), str, sizeof(str)))
35         goto finish;
36     ok = 1;
37
38 finish:
39     BIO_free(bio);
40     return ok;
41 }
42
43 static int test_bio_get_mem(void)
44 {
45     int ok = 0;
46     BIO *bio = NULL;
47     BUF_MEM *bufmem = NULL;
48
49     bio = BIO_new(BIO_s_mem());
50     if (!TEST_ptr(bio))
51         goto finish;
52     if (!TEST_int_eq(BIO_puts(bio, "Hello World\n"), 12))
53         goto finish;
54     BIO_get_mem_ptr(bio, &bufmem);
55     if (!TEST_ptr(bufmem))
56         goto finish;
57     if (!TEST_int_gt(BIO_set_close(bio, BIO_NOCLOSE), 0))
58         goto finish;
59     BIO_free(bio);
60     bio = NULL;
61     if (!TEST_mem_eq(bufmem->data, bufmem->length, "Hello World\n", 12))
62         goto finish;
63     ok = 1;
64
65 finish:
66     BIO_free(bio);
67     BUF_MEM_free(bufmem);
68     return ok;
69 }
70
71 int global_init(void)
72 {
73     CRYPTO_set_mem_debug(1);
74     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
75     return 1;
76 }
77
78 int setup_tests(void)
79 {
80     ADD_TEST(test_bio_memleak);
81     ADD_TEST(test_bio_get_mem);
82     return 1;
83 }