shithub: scc

Download patch

ref: 45871c6d68969b6052e4cd983084f7b5c44b4be0
parent: 51ee6bb33d83575c9da8e4bbaad11cd55b16400e
author: Roberto E. Vargas Caballero <k0ga@shike2.com>
date: Wed Mar 8 10:02:51 EST 2017

[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.

--- 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 @@
 	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 @@
 	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;