lite_malloc.c 794 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <stdlib.h>
  2. #include <stdint.h>
  3. #include <limits.h>
  4. #include <errno.h>
  5. #include "libc.h"
  6. uintptr_t __brk(uintptr_t);
  7. #define ALIGN 16
  8. void *__simple_malloc(size_t n)
  9. {
  10. static uintptr_t cur, brk;
  11. uintptr_t base, new;
  12. static int lock[2];
  13. size_t align=1;
  14. if (!n) n++;
  15. if (n > SIZE_MAX/2) goto toobig;
  16. while (align<n && align<ALIGN)
  17. align += align;
  18. n = n + align - 1 & -align;
  19. LOCK(lock);
  20. if (!cur) cur = brk = __brk(0)+16;
  21. base = cur + align-1 & -align;
  22. if (n > SIZE_MAX - PAGE_SIZE - base) goto fail;
  23. if (base+n > brk) {
  24. new = base+n + PAGE_SIZE-1 & -PAGE_SIZE;
  25. if (__brk(new) != new) goto fail;
  26. brk = new;
  27. }
  28. cur = base+n;
  29. UNLOCK(lock);
  30. return (void *)base;
  31. fail:
  32. UNLOCK(lock);
  33. toobig:
  34. errno = ENOMEM;
  35. return 0;
  36. }
  37. weak_alias(__simple_malloc, malloc);