forked from GJDuck/e9patch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlimit.c
More file actions
104 lines (89 loc) · 1.9 KB
/
limit.c
File metadata and controls
104 lines (89 loc) · 1.9 KB
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
/*
* LIMIT instrumentation.
*/
/*
* Associates a counter with each instruction address. Once LIMIT is
* reached, then abort() execution.
*/
#include "stdlib.c"
// Reuse the e9patch RB-tree implementation:
#define RB_AUGMENT(_) /* NOP */
#include "../src/e9patch/e9rbtree.h"
struct NODE;
typedef struct NODE NODE;
struct TREE
{
NODE *root;
};
typedef struct TREE TREE;
struct NODE
{
const void *addr;
RB_ENTRY(NODE) entry;
int color;
size_t count;
};
static int compare(const NODE *n, const NODE *m)
{
if (n->addr < m->addr)
return -1;
if (n->addr > m->addr)
return 1;
return 0;
}
RB_GENERATE_STATIC(TREE, NODE, entry, compare);
#define find(t, n) TREE_RB_FIND((t), (n))
#define insert(t, n) TREE_RB_INSERT((t), (n))
static TREE t = {NULL};
static mutex_t mutex = MUTEX_INITIALIZER;
static size_t limit = 0;
/*
* Entry point.
*
* call entry(addr)@limit
*/
void entry(const void *addr)
{
if (mutex_lock(&mutex) < 0)
{
switch (errno)
{
case EOWNERDEAD:
fputs("thread died with lock\n", stderr);
abort();
default:
return;
}
}
NODE key;
key.addr = addr;
NODE *n = find(&t, &key);
if (n == NULL)
{
n = (NODE *)malloc_unlocked(sizeof(NODE));
if (n == NULL)
{
fprintf(stderr, "failed to allocated %zu bytes\n",
sizeof(NODE));
abort();
}
n->addr = addr;
n->count = 0;
insert(&t, n);
}
n->count++;
if (n->count > limit)
{
fprintf(stderr, "limit=%zu reached @ addr=%p\n", limit, addr);
abort();
}
mutex_unlock(&mutex);
}
void init(int argc, char **argv, char **envp)
{
environ = envp;
limit = 100000;
const char *val = getenv("LIMIT");
if (val != NULL)
limit = atoll(val);
}