blob: 09f3c178e4c59e07f220287dce937c1642c88fe7 (
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
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
|
#include <stdlib.h>
#include <string.h>
typedef unsigned int uint;
enum
{
MAGIC = 0xbada110c,
MAX2SIZE = 32,
CUTOFF = 12,
};
typedef struct Bucket Bucket;
struct Bucket
{
int size;
int magic;
Bucket *next;
int pad;
char data[1];
};
typedef struct Arena Arena;
struct Arena
{
Bucket *btab[MAX2SIZE];
};
static Arena arena;
#define datoff ((int)((Bucket*)0)->data)
#define nil ((void*)0)
extern void *sbrk(unsigned long);
void*
malloc(size_t size)
{
uint next;
int pow, n;
Bucket *bp, *nbp;
for(pow = 1; pow < MAX2SIZE; pow++) {
if(size <= (1<<pow))
goto good;
}
return nil;
good:
/* Allocate off this list */
bp = arena.btab[pow];
if(bp) {
arena.btab[pow] = bp->next;
if(bp->magic != 0)
abort();
bp->magic = MAGIC;
return bp->data;
}
size = sizeof(Bucket)+(1<<pow);
size += 7;
size &= ~7;
if(pow < CUTOFF) {
n = (CUTOFF-pow)+2;
bp = sbrk(size*n);
if((int)bp < 0)
return nil;
next = (uint)bp+size;
nbp = (Bucket*)next;
arena.btab[pow] = nbp;
for(n -= 2; n; n--) {
next = (uint)nbp+size;
nbp->next = (Bucket*)next;
nbp->size = pow;
nbp = nbp->next;
}
nbp->size = pow;
}
else {
bp = sbrk(size);
if((int)bp < 0)
return nil;
}
bp->size = pow;
bp->magic = MAGIC;
return bp->data;
}
void
free(void *ptr)
{
Bucket *bp, **l;
if(ptr == nil)
return;
/* Find the start of the structure */
bp = (Bucket*)((uint)ptr - datoff);
if(bp->magic != MAGIC)
abort();
bp->magic = 0;
l = &arena.btab[bp->size];
bp->next = *l;
*l = bp;
}
void*
realloc(void *ptr, size_t n)
{
void *new;
uint osize;
Bucket *bp;
if(ptr == nil)
return malloc(n);
/* Find the start of the structure */
bp = (Bucket*)((uint)ptr - datoff);
if(bp->magic != MAGIC)
abort();
/* enough space in this bucket */
osize = 1<<bp->size;
if(osize >= n)
return ptr;
new = malloc(n);
if(new == nil)
return nil;
memmove(new, ptr, osize);
free(ptr);
return new;
}
|