aboutsummaryrefslogtreecommitdiffstats
path: root/libtest/libtest_check_no_leaks.c
blob: faaf724e92cc9405adad0181369c92c00f9d895b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* See LICENSE file for copyright and license details. */
#include "common.h"
extern int libtest_suppress_leak_output;
#ifndef TEST


int libtest_suppress_leak_output = 0;


static int
check_no_memory_leaks(void)
{
	struct meminfo *mem;
	int no_leaks = 1;

	SPINLOCK(libtest_allocs_list_spinlock);

	if (!libtest_allocs_list_inited)
		goto out;

	libtest_kill_malloc_tracking++;
	libtest_malloc_internal_usage++;
	for (mem = libtest_allocs_head.next; mem->next; mem = mem->next) {
		if (mem->accept_leakage)
			continue;
		no_leaks = 0;
		if (libtest_suppress_leak_output)
			continue;
		fprintf(stderr, "Memory leak: %p (alloc-size=%zu)\n",
		        mem->usable_area, mem->requested_alloc_size);
#ifdef WITH_BACKTRACE
		if (mem->backtrace)
			libtest_print_backtrace(stderr, NULL, "\tat ", 0u, mem->backtrace, NULL);
#endif
		fflush(stderr);
	}
	libtest_malloc_internal_usage--;
	libtest_kill_malloc_tracking--;

out:
	SPINUNLOCK(libtest_allocs_list_spinlock);
	return no_leaks;
}


int
libtest_check_no_leaks(void)
{
	int r = 1;
	r &= libtest_fd_tracking(-1);
	r &= check_no_memory_leaks();
	return r;
}


#else


#define p libtest_ptr___
extern unsigned char *volatile p;
unsigned char *volatile p;


int
main(void)
{
#ifdef WITH_BACKTRACE
	int fd1, fd2;
#endif

	SET_UP_ALARM();

#ifdef WITH_BACKTRACE
	fd1 = dup(STDERR_FILENO);
	assert(fd1 >= 0 || errno == EBADF);
	assert(fd1 != STDERR_FILENO);
	if (fd1 >= 0) {
		close(STDERR_FILENO);
		fd2 = open("/dev/null", O_WRONLY);
		assert(fd2 >= 0);
		if (fd2 != STDERR_FILENO) {
			assert(dup2(fd2, STDERR_FILENO) == STDERR_FILENO);
			close(fd2);
		}
	}
	libtest_print_backtrace(stderr, "", "", 0u, NULL, NULL);
	if (fd1 >= 0) {
		assert(dup2(fd1, STDERR_FILENO) == STDERR_FILENO);
		close(fd1);
	}
#endif

	libtest_start_tracking();
	assert(!libtest_kill_malloc_tracking);
	p = malloc(1u);
	assert(p);
	libtest_suppress_leak_output = 1;
	*p = 0;
	atomic_thread_fence(memory_order_seq_cst);
	EXPECT(!libtest_check_no_leaks());
	atomic_thread_fence(memory_order_seq_cst);
	libtest_suppress_leak_output = 0;
	free(p);
	libtest_stop_tracking();
	atomic_thread_fence(memory_order_seq_cst);
	EXPECT(libtest_check_no_leaks());

	return 0;
}


#endif