[hackers] [scc] [libc] Add implementation of sbrk() || Roberto E. Vargas Caballero

From: <git_AT_suckless.org>
Date: Wed, 8 Mar 2017 15:08:17 +0100 (CET)

commit d3d71beefae3f4c76b3f69284e1f54998dc5553a
Author: Roberto E. Vargas Caballero <k0ga_AT_shike2.com>
AuthorDate: Wed Mar 8 15:02:51 2017 +0100
Commit: Roberto E. Vargas Caballero <k0ga_AT_shike2.com>
CommitDate: Wed Mar 8 15:08:07 2017 +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.

diff --git a/libc/src/malloc.c b/libc/src/malloc.c
index e9f9f91..3c012af 100644
--- a/libc/src/malloc.c
+++ b/libc/src/malloc.c
_AT_@ -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
_AT_@ -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)
 {
_AT_@ -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;
Received on Wed Mar 08 2017 - 15:08:17 CET

This archive was generated by hypermail 2.3.0 : Wed Mar 08 2017 - 15:12:19 CET