stdlib.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include <stdlib.h>
  2. #include <mman.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #include <alloca.h>
  7. #include <Kernel/Syscall.h>
  8. #include <AK/Assertions.h>
  9. extern "C" {
  10. // FIXME: This is a temporary malloc() implementation. It never frees anything,
  11. // and you can't allocate more than 128 kB total.
  12. static const size_t mallocBudget = 131072;
  13. static byte* nextptr = nullptr;
  14. static byte* endptr = nullptr;
  15. void __malloc_init()
  16. {
  17. nextptr = (byte*)mmap(nullptr, mallocBudget, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
  18. endptr = nextptr + mallocBudget;
  19. int rc = set_mmap_name(nextptr, mallocBudget, "malloc");
  20. if (rc < 0)
  21. perror("set_mmap_name failed");
  22. }
  23. void* malloc(size_t size)
  24. {
  25. if ((nextptr + size) > endptr) {
  26. volatile char* crashme = (char*)0xc007d00d;
  27. *crashme = 0;
  28. }
  29. byte* ret = nextptr;
  30. nextptr += size;
  31. nextptr += 16;
  32. nextptr = (byte*)((dword)nextptr & 0xfffffff0);
  33. return ret;
  34. }
  35. void free(void* ptr)
  36. {
  37. if (!ptr)
  38. return;
  39. #if 0
  40. munmap(ptr, 4096);
  41. #endif
  42. }
  43. void* calloc(size_t nmemb, size_t)
  44. {
  45. ASSERT_NOT_REACHED();
  46. return nullptr;
  47. }
  48. void* realloc(void *ptr, size_t)
  49. {
  50. ASSERT_NOT_REACHED();
  51. return nullptr;
  52. }
  53. void exit(int status)
  54. {
  55. Syscall::invoke(Syscall::SC_exit, (dword)status);
  56. }
  57. void abort()
  58. {
  59. // FIXME: Implement proper abort().
  60. exit(253);
  61. }
  62. char* getenv(const char* name)
  63. {
  64. for (size_t i = 0; environ[i]; ++i) {
  65. const char* decl = environ[i];
  66. char* eq = strchr(decl, '=');
  67. if (!eq)
  68. continue;
  69. size_t varLength = eq - decl;
  70. char* var = (char*)alloca(varLength + 1);
  71. memcpy(var, decl, varLength);
  72. var[varLength] = '\0';
  73. if (!strcmp(var, name)) {
  74. char* value = eq + 1;
  75. return value;
  76. }
  77. }
  78. return nullptr;
  79. }
  80. int atoi(const char* str)
  81. {
  82. ssize_t len = strlen(str);
  83. int value = 0;
  84. bool isNegative = false;
  85. for (size_t i = 0; i < len; ++i) {
  86. if (i == 0 && str[0] == '-') {
  87. isNegative = true;
  88. continue;
  89. }
  90. if (str[i] < '0' || str[i] > '9')
  91. return 0;
  92. value = value * 10;
  93. value += str[i] - '0';
  94. }
  95. return isNegative ? -value : value;
  96. }
  97. }