heap.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /* mmap backing for the ring-3 allocator reused by the host browser.
  2. *
  3. * libc/malloc.c reserves a 64 MB arena (its HEAP_MAX_BYTES) and grows it in
  4. * place; reserve the whole range PROT_NONE up front so the grow is a
  5. * mprotect and the arena can never move. */
  6. #include <stddef.h>
  7. #include <sys/mman.h>
  8. #define HOST_ARENA_BYTES (64u * 1024u * 1024u)
  9. static unsigned char *base;
  10. void *__heap_map(unsigned int bytes)
  11. {
  12. if (base || bytes == 0 || bytes > HOST_ARENA_BYTES)
  13. return 0;
  14. base = (unsigned char *)mmap(0, HOST_ARENA_BYTES, PROT_NONE,
  15. MAP_PRIVATE | MAP_ANONYMOUS |
  16. MAP_NORESERVE, -1, 0);
  17. if (base == MAP_FAILED) {
  18. base = 0;
  19. return 0;
  20. }
  21. if (mprotect(base, bytes, PROT_READ | PROT_WRITE) != 0) {
  22. munmap(base, HOST_ARENA_BYTES);
  23. base = 0;
  24. return 0;
  25. }
  26. return base;
  27. }
  28. int __heap_grow(unsigned int total_bytes)
  29. {
  30. if (!base || total_bytes > HOST_ARENA_BYTES)
  31. return -1;
  32. return mprotect(base, total_bytes, PROT_READ | PROT_WRITE) == 0 ?
  33. 0 : -1;
  34. }
  35. void __heap_unmap(void)
  36. {
  37. if (base) {
  38. munmap(base, HOST_ARENA_BYTES);
  39. base = 0;
  40. }
  41. }