-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest.c
80 lines (65 loc) · 2.37 KB
/
test.c
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
#include <time.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
#include "buddy.h"
#define NUM_PAGES 2
#define PAGE_SIZE (1 << 12)
#define MAX_ALLOCS (1 << 14)
struct alloc_info {
uintptr_t ptr;
uintptr_t len;
};
static bool contains_ptr(struct alloc_info *array, int count, void *ptr)
{
uintptr_t x = (uintptr_t) ptr;
for (int i = 0; i < count; i++) {
uintptr_t head = array[i].ptr;
uintptr_t tail = array[i].len + head;
if (x >= head && x < tail)
return true;
}
return false;
}
int main(void)
{
_Alignas(PAGE_SIZE) char mem[NUM_PAGES * PAGE_SIZE];
struct buddy *alloc = buddy_startup(mem, sizeof(mem));
struct alloc_info current_allocs[MAX_ALLOCS];
int num_current_allocs = 0;
int failed = 0;
for (;;) {
if (failed == 10 || num_current_allocs == MAX_ALLOCS) {
failed = 0;
while (1 + rand() % 10 < 6 && num_current_allocs > 0) {
int i = rand() % num_current_allocs;
struct alloc_info deallocating = current_allocs[i];
current_allocs[i] = current_allocs[--num_current_allocs];
fprintf(stderr, "buddy_free(%d, %d)\n", (int) deallocating.len, (int) ((uintptr_t) deallocating.ptr - (uintptr_t) buddy_get_base(alloc)));
buddy_free(alloc, deallocating.len, (void*) deallocating.ptr);
}
}
size_t len = 1 + (rand() % PAGE_SIZE);
assert(len > 0 && len <= PAGE_SIZE);
void *ptr = buddy_malloc(alloc, len);
if (ptr == NULL) {
failed++;
//fprintf(stderr, "buddy_malloc(%lu) = NULL\n", len);
} else {
//buddy_dump(&alloc, stderr);
fprintf(stderr, "buddy_malloc(%d) = %d\n", (int) len, (int) ((uintptr_t) ptr - (uintptr_t) buddy_get_base(alloc)));
}
if (ptr != NULL) {
assert(contains_ptr(current_allocs, num_current_allocs, ptr) == false);
current_allocs[num_current_allocs++] = (struct alloc_info) {.ptr=(uintptr_t)ptr, .len=len};
/*
fprintf(stderr, "Allocations:\n");
for (int i = 0; i < num_current_allocs; i++) {
fprintf(stderr, " len: %-4lu | ptr: %lu\n", current_allocs[i].len, (uintptr_t) current_allocs[i].ptr - (uintptr_t) alloc.base);
}
*/
}
}
return 0;
}