From e5888a1ffdae813d7575f5fb02275c6bb07e5199 Mon Sep 17 00:00:00 2001 From: Taru Karttunen Date: Wed, 30 Mar 2011 15:46:40 +0300 Subject: Import sources from 2011-03-30 iso image --- sys/src/ape/lib/ap/plan9/malloc.c | 142 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100755 sys/src/ape/lib/ap/plan9/malloc.c (limited to 'sys/src/ape/lib/ap/plan9/malloc.c') diff --git a/sys/src/ape/lib/ap/plan9/malloc.c b/sys/src/ape/lib/ap/plan9/malloc.c new file mode 100755 index 000000000..09f3c178e --- /dev/null +++ b/sys/src/ape/lib/ap/plan9/malloc.c @@ -0,0 +1,142 @@ +#include +#include + +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<next; + + if(bp->magic != 0) + abort(); + + bp->magic = MAGIC; + return bp->data; + } + size = sizeof(Bucket)+(1<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<size; + if(osize >= n) + return ptr; + + new = malloc(n); + if(new == nil) + return nil; + + memmove(new, ptr, osize); + free(ptr); + + return new; +} -- cgit v1.2.3