aboutsummaryrefslogtreecommitdiffstats
path: root/libtest/libtest_check_no_leaks.c
blob: 15f7e589216d95573988166d2f3b74a4b2a9a183 (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
/* 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, "\tat ", 0u, mem->backtrace);
#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)
{
	/* TODO check file descriptor leaks */
	return check_no_memory_leaks();
}


#else


int
main(void)
{
	void *p;

	SET_UP_ALARM();

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

	return 0;
}


#endif