Update secmemtest and memeleaktest to use the test infrastructure.
[openssl.git] / test / secmemtest.c
1 /*
2  * Copyright 2015-2017 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
10 #include <openssl/crypto.h>
11
12 #include "test_main.h"
13 #include "testutil.h"
14
15 static int test_sec_mem(void)
16 {
17 #if defined(OPENSSL_SYS_LINUX) || defined(OPENSSL_SYS_UNIX)
18     int testresult = 0;
19     char *p = NULL, *q = NULL, *r = NULL, *s = NULL;
20
21     r = OPENSSL_secure_malloc(20);
22     /* r = non-secure 20 */
23     if (!TEST_ptr(r)
24         || !TEST_true(CRYPTO_secure_malloc_init(4096, 32))
25         || !TEST_false(CRYPTO_secure_allocated(r)))
26         goto end;
27     p = OPENSSL_secure_malloc(20);
28     if (!TEST_ptr(p)
29         /* r = non-secure 20, p = secure 20 */
30         || !TEST_true(CRYPTO_secure_allocated(p))
31         /* 20 secure -> 32-byte minimum allocaton unit */
32         || !TEST_size_t_eq(CRYPTO_secure_used(), 32))
33         goto end;
34     q = OPENSSL_malloc(20);
35     if (!TEST_ptr(q))
36         goto end;
37     /* r = non-secure 20, p = secure 20, q = non-secure 20 */
38     if (!TEST_false(CRYPTO_secure_allocated(q)))
39         goto end;
40     s = OPENSSL_secure_malloc(20);
41     if (!TEST_ptr(s)
42         /* r = non-secure 20, p = secure 20, q = non-secure 20, s = secure 20 */
43         || !TEST_true(CRYPTO_secure_allocated(s))
44         /* 2 * 20 secure -> 64 bytes allocated */
45         || !TEST_size_t_eq(CRYPTO_secure_used(), 64))
46         goto end;
47     OPENSSL_secure_free(p);
48     p = NULL;
49     /* 20 secure -> 32 bytes allocated */
50     if (!TEST_size_t_eq(CRYPTO_secure_used(), 32))
51         goto end;
52     OPENSSL_free(q);
53     q = NULL;
54     /* should not complete, as secure memory is still allocated */
55     if (!TEST_false(CRYPTO_secure_malloc_done())
56         || !TEST_true(CRYPTO_secure_malloc_initialized()))
57         goto end;
58     OPENSSL_secure_free(s);
59     s = NULL;
60     /* secure memory should now be 0, so done should complete */
61     if (!TEST_size_t_eq(CRYPTO_secure_used(), 0)
62         || !TEST_true(CRYPTO_secure_malloc_done())
63         || !TEST_false(CRYPTO_secure_malloc_initialized()))
64         goto end;
65     /* this can complete - it was not really secure */
66     testresult = 1;
67  end:
68     OPENSSL_secure_free(p);
69     OPENSSL_free(q);
70     OPENSSL_secure_free(r);
71     OPENSSL_secure_free(s);
72     return testresult;
73 #else
74     /* Should fail. */
75     return TEST_false(CRYPTO_secure_malloc_init(4096, 32));
76 #endif
77 }
78
79 void register_tests(void)
80 {
81     ADD_TEST(test_sec_mem);
82 }