-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmysys.c
executable file
·125 lines (104 loc) · 2.48 KB
/
mysys.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
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
/*
* @author P. Cooper
*
* mysys.c is a memory allocation routine to replace malloc, courtesy of P. Cooper.
* Malloc uses memory allocated in the CPU for the USB and Network buffers, these memory pointers
* can not be changed, so this code will not work if either of these features are used.
*
*/
#define USED 1
typedef struct {
unsigned size;
} UNIT;
typedef struct {
UNIT* free;
UNIT* heap;
} MSYS;
static MSYS msys;
static UNIT* compact( UNIT *p, unsigned nsize )
{
unsigned bsize, psize;
UNIT *best;
best = p;
bsize = 0;
while( psize = p->size, psize )
{
if( psize & USED )
{
if( bsize != 0 )
{
best->size = bsize;
if( bsize >= nsize )
{
return best;
}
}
bsize = 0;
best = p = (UNIT *)( (unsigned)p + (psize & ~USED) );
}
else
{
bsize += psize;
p = (UNIT *)( (unsigned)p + psize );
}
}
if( bsize != 0 )
{
best->size = bsize;
if( bsize >= nsize )
{
return best;
}
}
return 0;
}
void MSYS_Free( void *ptr )
{
if( ptr )
{
UNIT *p;
p = (UNIT *)( (unsigned)ptr - sizeof(UNIT) );
p->size &= ~USED;
}
}
void *MSYS_Alloc( unsigned size )
{
unsigned fsize;
UNIT *p;
if( size == 0 ) return 0;
size += 3 + sizeof(UNIT);
size >>= 2;
size <<= 2;
if( msys.free == 0 || size > msys.free->size )
{
msys.free = compact( msys.heap, size );
if( msys.free == 0 ) return 0;
}
p = msys.free;
fsize = msys.free->size;
if( fsize >= size + sizeof(UNIT) )
{
msys.free = (UNIT *)( (unsigned)p + size );
msys.free->size = fsize - size;
}
else
{
msys.free = 0;
size = fsize;
}
p->size = size | USED;
return (void *)( (unsigned)p + sizeof(UNIT) );
}
void MSYS_Init( void *heap, unsigned len )
{
len += 3;
len >>= 2;
len <<= 2;
msys.free = msys.heap = (UNIT *) heap;
msys.free->size = msys.heap->size = len - sizeof(UNIT);
*(unsigned *)((char *)heap + len - 4) = 0;
}
void MSYS_Compact( void )
{
msys.free = compact( msys.heap, 0x7FFFFFFF );
}