aboutsummaryrefslogtreecommitdiffstats
path: root/memcheck.c
blob: b119fad6fc5dbd7ed33a639129d8c4a8c13bb524 (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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
/* See LICENSE file for copyright and license details. */
#include "memcheck.h"

#include <sys/syscall.h>
#include <sys/mman.h>
#include <errno.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <elfutils/libdwfl.h>


enum alloctype {
	ALLOCTYPE_REALLOC,
	ALLOCTYPE_MMAP
};

#ifdef PRINT_BACKTRACES
struct backtrace {
	size_t alloc_size;
	size_t n;
	uintptr_t rips[];
};
#endif

struct allocinfo {
	void *real;
	void *ptr;
	size_t real_size;
	enum alloctype type;
	int flags;
	int dont_track;
#ifdef PRINT_BACKTRACES
	struct backtrace *backtrace;
#endif
};


static struct allocinfo *allocs = NULL;
static size_t nallocs = 0;
static size_t allocs_size = 0;
static size_t alloc_fail_exclusion = 0;
static size_t memleak_exclusion = 1;
static size_t alloc_fail_in = 0;
static int alloc_fail_all = 0;
static int have_custom_malloc = 0;


static void *
memcheck_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off)
{
#ifdef SYS_mmap2
	unsigned long pgoff = (unsigned long)(off / 4096);
	long int r = syscall(SYS_mmap2, addr, len, (unsigned long)prot, (unsigned long)flags, fd, pgoff);
#else
	long int r = syscall(SYS_mmap, addr, len, (unsigned long)prot, (unsigned long)flags, fd, off);
#endif
	return (void *)r;
}


static void *
memcheck_mremap(void *old, size_t old_size, size_t new_size, int flags, void *new_address)
{
	long int r = syscall(SYS_mremap, old, old_size, new_size, flags, new_address);
	return (void *)r;
}


static int
memcheck_munmap(void *ptr, size_t n)
{
	return (int)syscall(SYS_munmap, ptr, n);
}


static void *
memcheck_mmap_ram(size_t n)
{
	return memcheck_mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
}


#ifdef PRINT_BACKTRACES
static struct backtrace *
memcheck_create_backtrace(void)
{
	struct backtrace *ret = NULL, *new;
	unw_word_t rip;
	unw_cursor_t cursor;
	unw_context_t context;
	size_t n = 0, size = 0;
	int saved_errno = errno;

	memleak_exclusion += 1;

	if (unw_getcontext(&context))
		goto fail;
	if (unw_init_local(&cursor, &context))
		goto fail;

	n = 8;
	size = offsetof(struct backtrace, rips) + n * sizeof(*ret->rips);
	ret = memcheck_mmap_ram(size);
	if (!ret)
		goto fail;
	ret->alloc_size = size;

	ret->n = 0;
	while (unw_step(&cursor) > 0) {
		if (unw_get_reg(&cursor, UNW_REG_IP, &rip))
			goto fail;
		if (ret->n == n) {
			n += 8;
			size = offsetof(struct backtrace, rips) + n * sizeof(*ret->rips);
			new = memcheck_mmap_ram(size);
			if (!new)
				goto fail;
			new->alloc_size = size;
			new->n = ret->n;
			memcpy(new->rips, ret->rips, n * sizeof(*ret->rips));
			memcheck_munmap(ret, ret->alloc_size);
			ret = new;
		}
		ret->rips[ret->n++] = (uintptr_t)rip;
	}

	errno = saved_errno;
	memleak_exclusion -= 1;
	return ret;

fail:
	if (ret)
		memcheck_munmap(ret, ret->alloc_size);
	errno = saved_errno;
	memleak_exclusion -= 1;
	return NULL;
}
#endif


#ifdef PRINT_BACKTRACES
static void
memcheck_print_backtrace(struct backtrace *backtrace, const char *indent)
{
	int saved_errno = errno, lineno;
	char *debuginfo_path = NULL;
	Dwarf_Addr ip;
	Dwfl_Callbacks callbacks;
	Dwfl *dwfl = NULL;
	Dwfl_Line *line = NULL;
	Dwfl_Module *module = NULL;
	const char *filename = NULL;
	const char *funcname = NULL;
	size_t i;

	if (!backtrace)
		return;

	memleak_exclusion += 1;

	memset(&callbacks, 0, sizeof(callbacks));

	callbacks.find_elf       = dwfl_linux_proc_find_elf;
	callbacks.find_debuginfo = dwfl_standard_find_debuginfo;
	callbacks.debuginfo_path = &debuginfo_path;

	if (dwfl) {
		if (dwfl_linux_proc_report(dwfl, getpid()) ||
		    dwfl_report_end(dwfl, NULL, NULL)) {
			perror("");
			dwfl_end(dwfl);
			dwfl = NULL;
		}
	}

	for (i = 0; i < backtrace->n; i++) {
		ip = (Dwarf_Addr)backtrace->rips[i];

		if (dwfl) {
			module   = dwfl_addrmodule(dwfl, ip);
			funcname = module ? dwfl_module_addrname(module, ip) : NULL;
			line     = dwfl_getsrc(dwfl, ip);
			if (line)
				filename = dwfl_lineinfo(line, &(Dwarf_Addr){0}, &lineno, NULL, NULL, NULL);
		}

		dprintf(STDERR_FILENO, "%s%s 0x%016"PRIxPTR": %s",
		        indent, !i ? "at" : "by",
			(uintptr_t)ip,
		        funcname ? funcname : "???");
		if (line)
			dprintf(STDERR_FILENO, " (%s:%i)\n", filename, lineno);
		else
			dprintf(STDERR_FILENO, "\n");
	}

	if (dwfl)
		dwfl_end(dwfl);

	errno = saved_errno;
	memleak_exclusion -= 1;
}
#endif


#if defined(__GNUC__)
__attribute__((__format__(__gnu_printf__, 1, 2)))
#endif
static void
memcheck_errorf(const char *fmt, ...)
{
	va_list ap;
	memleak_exclusion = 1;
	va_start(ap, fmt);
	vdprintf(STDERR_FILENO, fmt, ap);
	dprintf(STDERR_FILENO, ", aborting...\n");
	va_end(ap);
#ifdef PRINT_BACKTRACES
	memcheck_print_backtrace(memcheck_create_backtrace(), "\t");
#endif
	abort();
}


#if defined(__GNUC__)
__attribute__((__pure__))
#endif
static struct allocinfo *
memcheck_getalloc(void *ptr)
{
	size_t i;
	for (i = 0; i < nallocs; i++)
		if (allocs[i].ptr == ptr)
			return &allocs[i];
	return NULL;
}


static int
memcheck_fake_fail(void)
{
	have_custom_malloc = 1;

	if (!alloc_fail_exclusion) {
	        if (alloc_fail_all || (alloc_fail_in && !--alloc_fail_in)) {
		        alloc_fail_all = 1;
	                errno = ENOMEM;
                        return 1;
		}
	}

	return 0;
}


static void
memcheck_putalloc(struct allocinfo *info)
{
	if (nallocs == allocs_size) {
		size_t old_allocs_size = allocs_size;
		void *new;
		if (allocs_size > SIZE_MAX / sizeof(*allocs) - 64)
			memcheck_errorf("size of memory bookkeeping will exceed SIZE_MAX");
		allocs_size += 64;
		new = memcheck_mmap_ram(allocs_size * sizeof(*allocs));
		if (!new)
			memcheck_errorf("failed to allocate enought memory for bookkeeping");
		if (allocs) {
			memcpy(new, allocs, nallocs * sizeof(*allocs));
			memcheck_munmap(allocs, old_allocs_size * sizeof(*allocs));
		}
		allocs = new;
	}
	allocs[nallocs++] = *info;
}


static int
memcheck_free(void *ptr, size_t size, enum alloctype type)
{
	int ret;
	struct allocinfo *alloc;
	alloc = memcheck_getalloc(ptr);
	if (!alloc)
		memcheck_errorf("attempting to deallocate unknown pointer %p", ptr);
	if (alloc->type != type)
		memcheck_errorf("attempting to deallocating with incompatible function");
	if (type == ALLOCTYPE_MMAP && size != alloc->real_size)
		memcheck_errorf("attempting to munmap(2) pointer %p with wrong size", ptr);
	ret = memcheck_munmap(alloc->real, alloc->real_size);
#ifdef PRINT_BACKTRACES
	if (alloc->backtrace)
		memcheck_munmap(alloc->backtrace, alloc->backtrace->alloc_size);
#endif
	*alloc = allocs[--nallocs];
	if (!nallocs) {
		memcheck_munmap(allocs, allocs_size * sizeof(*allocs));
		allocs = NULL;
		nallocs = 0;
		allocs_size = 0;
	}
	return ret;
}


static void *
memcheck_realloc(void *old, size_t n, size_t m, size_t alignment, int initbyte)
{
	struct allocinfo info;
	uintptr_t addr;
	void *ret;

	if (memcheck_fake_fail())
		return NULL;

	if (!n || !m)
		memcheck_errorf("attempting to allocate with zero size which is implementation-defined behaviour");
	if (n > SIZE_MAX / m)
		memcheck_errorf("attempting allocate more than SIZE_MAX");

	if (!alignment)
		alignment = _Alignof(max_align_t);

	n *= m;
	if (n > SIZE_MAX - (alignment - 1U))
		memcheck_errorf("attempting allocate more than SIZE_MAX after alignment padding");

#ifdef PRINT_BACKTRACES
	info.backtrace = memleak_exclusion ? NULL : memcheck_create_backtrace();
#endif
	info.dont_track = memleak_exclusion > 0;
	info.flags = 0;
	info.type = ALLOCTYPE_REALLOC;
	info.real_size = n + (alignment - 1U);
	info.real = memcheck_mmap_ram(info.real_size);
	if (!info.real)
		memcheck_errorf("failed to allocate enough memory");
	memset(info.real, initbyte, info.real_size);

	addr = (uintptr_t)info.real;
	if (addr % alignment)
		addr += alignment - addr % alignment;
	ret = info.ptr = (void *)addr;

	memcheck_putalloc(&info);

	if (old) {
		struct allocinfo *oldinfo;
		oldinfo = memcheck_getalloc(old);
		if (!oldinfo)
			memcheck_errorf("attempting to reallocate unknown pointer %p", old);
		memcpy(info.real, oldinfo->real, info.real_size < oldinfo->real_size ? info.real_size : oldinfo->real_size);
		memcheck_free(old, 0, ALLOCTYPE_REALLOC);
	}

	return ret;
}



/* Implementation of checked functions */


#if defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wmissing-prototypes"
#endif


void *
mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off)
{
	struct allocinfo info;
	void *ret;

	if (off % 4096)
		memcheck_errorf("attempting to mmap(2) with offset %ju which is not a multiple of 4096", (uintmax_t)off);

#ifdef PRINT_BACKTRACES
	info.backtrace = memleak_exclusion ? NULL : memcheck_create_backtrace();
#endif
	info.dont_track = memleak_exclusion > 0;
	info.flags = flags;
	info.type = ALLOCTYPE_MMAP;
	info.real_size = len;
	info.real = memcheck_mmap(addr, len, prot, flags, fd, off);
	if (!info.real)
		memcheck_errorf("failed to mmap(2)");
	ret = info.ptr = info.real;

	memcheck_putalloc(&info);
	return ret;
}


int
munmap(void *ptr, size_t n)
{
	return memcheck_free(ptr, n, ALLOCTYPE_MMAP);
}


void *
mremap(void *old, size_t old_size, size_t new_size, int flags, ...)
{
	struct allocinfo *oldinfo;
	void *new_address = NULL;
	void *ret;

	if (memcheck_fake_fail())
		return NULL;

	oldinfo = memcheck_getalloc(old);
	if (!oldinfo)
		memcheck_errorf("attempting to mremap(2) unknown pointer %p", old);
	if (oldinfo->type != ALLOCTYPE_MMAP)
		memcheck_errorf("attempting to mremap(2) pointer %p that was not allocated with mmap(2) or mremap(2)", old);

	if (flags & MREMAP_FIXED) {
		va_list ap;
		va_start(ap, flags);
		new_address = va_arg(ap, void *);
		va_end(ap);
	}

	ret = memcheck_mremap(old, old_size, new_size, flags, new_address);
	if (!ret)
		return NULL;

	if (ret == old || !(flags & MREMAP_DONTUNMAP)) {
		oldinfo->ptr = oldinfo->real = ret;
		oldinfo->real_size = new_size;
	} else {
		struct allocinfo info;
		info = *oldinfo;
		info.ptr = info.real = ret;
		info.real_size = new_size;
		memcheck_putalloc(&info);
	}

	return ret;
}


void
free(void *ptr)
{
	if (!ptr)
		return;
	memcheck_free(ptr, 0, ALLOCTYPE_REALLOC);
}


void *
malloc(size_t n)
{
	return memcheck_realloc(NULL, 1, n, 0, 'x');
}


void *
calloc(size_t n, size_t m)
{
	return memcheck_realloc(NULL, n, m, 0, 0);
}


void *
realloc(void *old, size_t n)
{
	return memcheck_realloc(old, 1, n, 0, 'x');
}


void *
reallocarray(void *old, size_t n, size_t m)
{
	return memcheck_realloc(old, n, m, 0, 'x');
}


void *
memdup(const void *s, size_t n)
{
	char *r = memcheck_realloc(NULL, 1, n, 0, 'x');
	if (r)
		memcpy(r, s, n);
	return r;
}


char *
strdup(const char *s)
{
	size_t n = strlen(s) + 1U;
	char *r = memcheck_realloc(NULL, 1, n, 0, 'x');
	if (r)
		memcpy(r, s, n);
	return r;
}


char *
strndup(const char *s, size_t max)
{
	size_t n = strnlen(s, max) + 1U;
	char *r = memcheck_realloc(NULL, 1, n, 0, 'x');
	if (n > max)
		n = max;
	if (r)
		memcpy(r, s, n);
	return r;
}


int
posix_memalign(void **ret_out, size_t align, size_t n)
{
	int saved_errno, r;
	saved_errno = errno, errno = 0;
	if (!align || (align & (align - 1U)) || align % sizeof(void *))
		memcheck_errorf("invalid alignment for posix_memalign: %zu", align);
	*ret_out = memcheck_realloc(NULL, 1, n, align, 'x');
	return r = errno, errno = saved_errno, r;
}


void *
memalign(size_t align, size_t n)
{
	if (!align)
		memcheck_errorf("invalid alignment for memalign: %zu", align);
	return memcheck_realloc(NULL, 1, n, align, 'x');
}


void *
aligned_alloc(size_t align, size_t n)
{
	if (!align || (align & (align - 1U)))
		memcheck_errorf("invalid alignment for aligned_alloc: %zu", align);
	return memcheck_realloc(NULL, 1, n, align, 'x');
}


void *
valloc(size_t n)
{
	return memcheck_realloc(NULL, 1, n, 4096U, 'x');
}


void *
pvalloc(size_t n)
{
	if (n % 4096U) {
		n |= 4096U - 1U;
		if (n == SIZE_MAX)
			memcheck_errorf("attempting to allocate beyond SIZE_MAX");
		n += 1U;
	}
	return memcheck_realloc(NULL, 1, n, 4096U, 'x');
}


#if defined(__GNUC__)
# pragma GCC diagnostic pop
#endif



/* Test functions */


int
memcheck_have_custom_malloc(void)
{
	static void *volatile test_have_custom_malloc_ptr = NULL;
        int saved_errno = errno;
        alloc_fail_exclusion++;
        memleak_exclusion++;
        test_have_custom_malloc_ptr = malloc(1);
        free(test_have_custom_malloc_ptr);
        memleak_exclusion--;
        alloc_fail_exclusion--;
	errno = saved_errno;
	return have_custom_malloc;
}

size_t
memcheck_alloc_fail_in(size_t n)
{
	size_t ret = alloc_fail_in;
	alloc_fail_in = n;
	alloc_fail_all = 0;
	return ret;
}


int
memcheck_check_memleaks(void)
{
	struct allocinfo *leak;
	size_t i, count = 0;
	memleak_exclusion = 1;
	for (i = 0; i < nallocs; i++) {
		leak = &allocs[i];
		if (leak->dont_track)
			continue;
		count += 1;
	}
	if (!count)
               	return 1;
	dprintf(STDERR_FILENO, "%zu %s!\n", count, count == 1 ? "memory leak" : "memory leaks");
#ifdef PRINT_BACKTRACES
	for (i = 0; i < nallocs; i++) {
		leak = &allocs[i];
		if (leak->dont_track)
			continue;
		memcheck_print_backtrace(leak->backtrace, "\t");
	}
#endif
	return 0;
}

void memcheck_alloc_fail_exclusion_begin(void) { alloc_fail_exclusion++; }
void memcheck_alloc_fail_exclusion_end(void) { alloc_fail_exclusion--; }
void memcheck_exclusion_begin(void) { memleak_exclusion++; }
void memcheck_exclusion_end(void) { memleak_exclusion--; }
void memcheck_begin(void) { memleak_exclusion = 0; }