scc

simple C compiler
git clone git://git.2f30.org/scc
Log | Files | Refs | README | LICENSE

commit d3d71beefae3f4c76b3f69284e1f54998dc5553a
parent 36d9492c408ec4d07629be1798fec2ea4cc17b0e
Author: Roberto E. Vargas Caballero <k0ga@shike2.com>
Date:   Wed,  8 Mar 2017 15:02:51 +0100

[libc] Add implementation of sbrk()

This interface can be built over _brk() because the linker knows
which is the last address used by the program. In UNIX systems
this value is represented by the global value end[], and we are
going to follow this convention.

Diffstat:
libc/src/malloc.c | 28++++++++++++++++++++++++----
1 file changed, 24 insertions(+), 4 deletions(-)

diff --git a/libc/src/malloc.c b/libc/src/malloc.c @@ -1,15 +1,19 @@ /* See LICENSE file for copyright and license details. */ +#include <stdint.h> #include <stdlib.h> #include <string.h> -#include <stdint.h> #include "malloc.h" +#include "syscall.h" -extern void *_sbrk(intptr_t increment); +#define MAXADDR ((char *)-1) +#define ERRADDR ((char *)-1) +extern char end[]; static Header base = { .h.next = &base }; static Header *freep = &base; +static char *heap = end; /* * Run over the free list looking for the nearest previous @@ -66,6 +70,22 @@ free(void *mem) freep = prev; } +static void * +sbrk(uintptr_t inc) +{ + char *new, *old = heap; + + if (old >= MAXADDR - inc) + return ERRADDR; + + new = old + inc; + if (_brk(new) < 0) + return ERRADDR; + heap = new; + + return old; +} + static Header * morecore(size_t nunits) { @@ -75,8 +95,8 @@ morecore(size_t nunits) if (nunits < NALLOC) nunits = NALLOC; - rawmem = _sbrk(nunits * sizeof(Header)); - if (rawmem == (void *)-1) + rawmem = sbrk(nunits * sizeof(Header)); + if (rawmem == ERRADDR) return NULL; hp = (Header*)rawmem;