xref: /freebsd/crypto/openssl/test/memleaktest.c (revision d37eb51047221dc3322b34db1038ff3aa533883f)
1 /*
2  * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 <string.h>
11 #include <openssl/bio.h>
12 #include <openssl/crypto.h>
13 
14 #include "testutil.h"
15 
16 /* __has_feature is a clang-ism, while __SANITIZE_ADDRESS__ is a gcc-ism */
17 #if defined(__has_feature)
18 # if __has_feature(address_sanitizer)
19 #  define __SANITIZE_ADDRESS__ 1
20 # endif
21 #endif
22 /* If __SANITIZE_ADDRESS__ isn't defined, define it to be false */
23 /* Leak detection is not yet supported with MSVC on Windows, so */
24 /* set __SANITIZE_ADDRESS__ to false in this case as well.      */
25 #if !defined(__SANITIZE_ADDRESS__) || defined(_MSC_VER)
26 # undef __SANITIZE_ADDRESS__
27 # define __SANITIZE_ADDRESS__ 0
28 #endif
29 
30 /*
31  * We use a proper main function here instead of the custom main from the
32  * test framework to avoid CRYPTO_mem_leaks stuff.
33  */
34 
35 int main(int argc, char *argv[])
36 {
37 #if __SANITIZE_ADDRESS__
38     int exitcode = EXIT_SUCCESS;
39 #else
40     /*
41      * When we don't sanitize, we set the exit code to what we would expect
42      * to get when we are sanitizing.  This makes it easy for wrapper scripts
43      * to detect that we get the result we expect.
44      */
45     int exitcode = EXIT_FAILURE;
46 #endif
47     char *lost;
48 
49     lost = OPENSSL_malloc(3);
50     if (!TEST_ptr(lost))
51         return EXIT_FAILURE;
52 
53     strcpy(lost, "ab");
54 
55     if (argv[1] && strcmp(argv[1], "freeit") == 0) {
56         OPENSSL_free(lost);
57         exitcode = EXIT_SUCCESS;
58     }
59 
60     lost = NULL;
61     return exitcode;
62 }
63