Debian Codegraph @

tests/tools.c

raw
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #include <math.h>
4 #include <dlfcn.h>
5 #include "tools.h"
6
7 static int n_fails = 0;
8 static int fail_after = 0;
9
10 void*
11 malloc(size_t s)
12 {
13 if (fail_after > 0) {
14 ++n_fails;
15 if (n_fails >= fail_after) return NULL;
16 }
17 void *(*real_malloc)(size_t) = dlsym(RTLD_NEXT, "malloc");
18 return real_malloc(s);
19 }
20
21
22 void*
23 realloc(void * ptr, size_t s)
24 {
25 if (fail_after > 0) {
26 ++n_fails;
27 if (n_fails >= fail_after)
28 return NULL;
29 }
30 void *(*real_realloc)(void *, size_t) = dlsym(RTLD_NEXT, "realloc");
31 return real_realloc(ptr, s);
32 }
33
34 void*
35 strdup(const char *s)
36 {
37 if (fail_after > 0) {
38 ++n_fails;
39 if (n_fails >= fail_after) {
40 return NULL;
41 }
42 }
43 void *(*real_strdup)(const char*) = dlsym(RTLD_NEXT, "strdup");
44 return real_strdup(s);
45 }
46
47 void
48 set_fail_after(int limit) {
49 if (limit < 0) limit = 0;
50 fail_after = limit;
51 n_fails = 0;
52 }
53
54 int float_eq(double a, double b, double tolerance)
55 {
56 if (fabs(a-b) < tolerance) return 1;
57 printf("floats not equal: a = %f, b = %f, diff = %f, tolerance = %f\n",
58 a, b, fabs(a-b), tolerance);
59 fflush(stdout);
60 return 0;
61 }