aboutsummaryrefslogtreecommitdiff
path: root/src/chaos.c
blob: 231c94ae2f05f15c2c369879848a204a24c1fd8f (plain)
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
/*
 * src/chaos.c
 * (c) 2021 Jonas Gunz <himself@jonasgunz.de>
 * License: MIT
 */

/**
 * Randomly inject errors in library functions to check resiliency
 */

#if defined(_CHAOS) && defined(_GNU_SOURCE)

#warning "CHAOS Mode enabled"

#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

void* malloc (size_t size) {
	int fd;
	uint16_t rand;

	void* (*realmalloc)(size_t size) =
		(void* (*)(size_t size)) dlsym(RTLD_NEXT, "malloc");

	fd = open("/dev/urandom", O_RDONLY);
	read(fd, &rand, 2);
	close(fd);

	if( rand < 1000 ) {
		errno = ENOMEM;
		return NULL;
	}

	return realmalloc(size);
}

#endif