aboutsummaryrefslogtreecommitdiffstats
path: root/src/heap.c
blob: 92978b7251933db3bad6d227637917bf0b68330c (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
#include <heap.h>
#include <task.h>

#define HEAP_ALIGN 16

typedef struct {
	uint32_t size;
	void *next;
} __attribute__ ((packed)) alloc_t;

static alloc_t *free_blocks;
static void *heap_end;
static uint32_t heap_used;

void heap_init(void *buf)
{
	heap_end = buf;
	free_blocks = 0;
	heap_used = 0;
}

void *malloc(uint32_t size)
{
	//task_hold(1);
	size = (size + sizeof(alloc_t) + HEAP_ALIGN) & ~(HEAP_ALIGN - 1);

	alloc_t *node = free_blocks;
	alloc_t *prev = 0;
	while (node != 0) {
		if (node->size >= size) {
			if (prev != 0)
				prev->next = node->next;
			else
				free_blocks = node->next;
			node->next = 0;
			heap_used += node->size;
			return (void *)((uint8_t *)node + sizeof(alloc_t));
		}

		prev = node;
		node = node->next;
	}

	node = (alloc_t *)heap_end;
	node->size = size;
	node->next = 0;

	heap_end = (void *)((uint8_t *)heap_end + size);
	heap_used += size;

	//task_hold(0);
	return (void *)((uint8_t *)node + sizeof(alloc_t)); 
}

void *calloc(uint32_t count, uint32_t size)
{
	uint8_t *buf = malloc(count * size);
	for (uint32_t i = 0; i < count * size; i++)
		buf[i] = 0;
	return buf;
}

void free(void *buf)
{
	if (buf == 0)
		return;

	alloc_t *alloc = (alloc_t *)((uint8_t *)buf - sizeof(alloc_t));
	heap_used -= alloc->size;
	alloc->next = free_blocks;
	free_blocks = alloc;
}