summaryrefslogtreecommitdiff
path: root/klibc/klibc/sbrk.c
blob: f7401dcfe25fed99cdb7733d3f57ffd059553445 (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
/* sbrk.c - Change data segment size */

/* Written 2000 by Werner Almesberger */
/* Modified 2003-2004 for klibc by H. Peter Anvin */

#include <stddef.h>
#include <unistd.h>
#include <inttypes.h>
#include <errno.h>
#include "malloc.h"

char *__current_brk;		/* Common with brk.c */

/* p is an address,  a is alignment; must be a power of 2 */
static inline void *align_up(void *p, uintptr_t a)
{
  return (void *) (((uintptr_t)p + a-1) & ~(a-1));
}

void *sbrk(ptrdiff_t increment)
{
  char *start, *end, *new_brk;
  
  if (!__current_brk)
    __current_brk = __brk(NULL);

  start = align_up(__current_brk, SBRK_ALIGNMENT);
  end   = start + increment;

  new_brk = __brk(end);

  if (new_brk == (void *)-1)
    return (void *)-1;
  else if (new_brk < end) {
    errno = ENOMEM;
    return (void *) -1;
  }

  __current_brk = new_brk;
  return end;
}