stdlib.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. #include <stdlib.h>
  2. #include <sys/mman.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #include <alloca.h>
  7. #include <assert.h>
  8. #include <errno.h>
  9. #include <ctype.h>
  10. #include <AK/Assertions.h>
  11. #include <AK/Types.h>
  12. #include <Kernel/Syscall.h>
  13. #include <AK/StdLibExtras.h>
  14. #include <AK/HashMap.h>
  15. #include <AK/AKString.h>
  16. extern "C" {
  17. #define MALLOC_SCRUB_BYTE 0x85
  18. #define FREE_SCRUB_BYTE 0x82
  19. struct MallocHeader {
  20. uint16_t first_chunk_index;
  21. uint16_t chunk_count;
  22. size_t size;
  23. uint32_t compute_xorcheck() const
  24. {
  25. return 0x19820413 ^ ((first_chunk_index << 16) | chunk_count) ^ size;
  26. }
  27. };
  28. struct MallocFooter {
  29. uint32_t xorcheck;
  30. };
  31. #define CHUNK_SIZE 32
  32. #define POOL_SIZE 4 * 1048576
  33. static const size_t malloc_budget = POOL_SIZE;
  34. static byte s_malloc_map[POOL_SIZE / CHUNK_SIZE / 8];
  35. static byte* s_malloc_pool;
  36. static uint32_t s_malloc_sum_alloc = 0;
  37. static uint32_t s_malloc_sum_free = POOL_SIZE;
  38. void* malloc(size_t size)
  39. {
  40. if (size == 0)
  41. return nullptr;
  42. // We need space for the MallocHeader structure at the head of the block.
  43. size_t real_size = size + sizeof(MallocHeader) + sizeof(MallocFooter);
  44. if (s_malloc_sum_free < real_size) {
  45. fprintf(stderr, "malloc(): Out of memory\ns_malloc_sum_free=%u, real_size=%u\n", s_malloc_sum_free, real_size);
  46. assert(false);
  47. }
  48. size_t chunks_needed = real_size / CHUNK_SIZE;
  49. if (real_size % CHUNK_SIZE)
  50. chunks_needed++;
  51. size_t chunks_here = 0;
  52. size_t first_chunk = 0;
  53. for (unsigned i = 0; i < (POOL_SIZE / CHUNK_SIZE / 8); ++i) {
  54. if (s_malloc_map[i] == 0xff) {
  55. // Skip over completely full bucket.
  56. chunks_here = 0;
  57. continue;
  58. }
  59. // FIXME: This scan can be optimized further with TZCNT.
  60. for (unsigned j = 0; j < 8; ++j) {
  61. if ((s_malloc_map[i] & (1<<j))) {
  62. // This is in use, so restart chunks_here counter.
  63. chunks_here = 0;
  64. continue;
  65. }
  66. if (chunks_here == 0) {
  67. // Mark where potential allocation starts.
  68. first_chunk = i * 8 + j;
  69. }
  70. ++chunks_here;
  71. if (chunks_here == chunks_needed) {
  72. auto* header = (MallocHeader*)(s_malloc_pool + (first_chunk * CHUNK_SIZE));
  73. byte* ptr = ((byte*)header) + sizeof(MallocHeader);
  74. header->chunk_count = chunks_needed;
  75. header->first_chunk_index = first_chunk;
  76. header->size = size;
  77. auto* footer = (MallocFooter*)((byte*)header + (header->chunk_count * CHUNK_SIZE) - sizeof(MallocFooter));
  78. footer->xorcheck = header->compute_xorcheck();
  79. for (size_t k = first_chunk; k < (first_chunk + chunks_needed); ++k)
  80. s_malloc_map[k / 8] |= 1 << (k % 8);
  81. s_malloc_sum_alloc += header->chunk_count * CHUNK_SIZE;
  82. s_malloc_sum_free -= header->chunk_count * CHUNK_SIZE;
  83. memset(ptr, MALLOC_SCRUB_BYTE, (header->chunk_count * CHUNK_SIZE) - (sizeof(MallocHeader) + sizeof(MallocFooter)));
  84. return ptr;
  85. }
  86. }
  87. }
  88. fprintf(stderr, "malloc(): Out of memory (no consecutive chunks found for size %u)\n", size);
  89. volatile char* crashme = (char*)0xc007d00d;
  90. *crashme = 0;
  91. return nullptr;
  92. }
  93. static void validate_mallocation(void* ptr, const char* func)
  94. {
  95. auto* header = (MallocHeader*)((((byte*)ptr) - sizeof(MallocHeader)));
  96. if (header->size == 0) {
  97. fprintf(stderr, "%s called on bad pointer %p, size=0\n", func, ptr);
  98. assert(false);
  99. }
  100. auto* footer = (MallocFooter*)((byte*)header + (header->chunk_count * CHUNK_SIZE) - sizeof(MallocFooter));
  101. uint32_t expected_xorcheck = header->compute_xorcheck();
  102. if (footer->xorcheck != expected_xorcheck) {
  103. fprintf(stderr, "%s called on bad pointer %p, xorcheck=%w (expected %w)\n", func, ptr, footer->xorcheck, expected_xorcheck);
  104. assert(false);
  105. }
  106. }
  107. void free(void* ptr)
  108. {
  109. if (!ptr)
  110. return;
  111. validate_mallocation(ptr, "free()");
  112. auto* header = (MallocHeader*)((((byte*)ptr) - sizeof(MallocHeader)));
  113. for (unsigned i = header->first_chunk_index; i < (header->first_chunk_index + header->chunk_count); ++i)
  114. s_malloc_map[i / 8] &= ~(1 << (i % 8));
  115. s_malloc_sum_alloc -= header->chunk_count * CHUNK_SIZE;
  116. s_malloc_sum_free += header->chunk_count * CHUNK_SIZE;
  117. memset(header, FREE_SCRUB_BYTE, header->chunk_count * CHUNK_SIZE);
  118. }
  119. void __malloc_init()
  120. {
  121. s_malloc_pool = (byte*)mmap(nullptr, malloc_budget, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
  122. int rc = set_mmap_name(s_malloc_pool, malloc_budget, "malloc pool");
  123. if (rc < 0)
  124. perror("set_mmap_name failed");
  125. }
  126. void* calloc(size_t count, size_t size)
  127. {
  128. size_t new_size = count * size;
  129. auto* ptr = malloc(new_size);
  130. memset(ptr, 0, new_size);
  131. return ptr;
  132. }
  133. void* realloc(void *ptr, size_t size)
  134. {
  135. if (!ptr)
  136. return malloc(size);
  137. validate_mallocation(ptr, "realloc()");
  138. auto* header = (MallocHeader*)((((byte*)ptr) - sizeof(MallocHeader)));
  139. size_t old_size = header->size;
  140. if (size == old_size)
  141. return ptr;
  142. auto* new_ptr = malloc(size);
  143. memcpy(new_ptr, ptr, min(old_size, size));
  144. free(ptr);
  145. return new_ptr;
  146. }
  147. void exit(int status)
  148. {
  149. _exit(status);
  150. assert(false);
  151. }
  152. void abort()
  153. {
  154. // FIXME: Implement proper abort().
  155. exit(253);
  156. }
  157. char* getenv(const char* name)
  158. {
  159. for (size_t i = 0; environ[i]; ++i) {
  160. const char* decl = environ[i];
  161. char* eq = strchr(decl, '=');
  162. if (!eq)
  163. continue;
  164. size_t varLength = eq - decl;
  165. char* var = (char*)alloca(varLength + 1);
  166. memcpy(var, decl, varLength);
  167. var[varLength] = '\0';
  168. if (!strcmp(var, name)) {
  169. char* value = eq + 1;
  170. return value;
  171. }
  172. }
  173. return nullptr;
  174. }
  175. int putenv(char* new_var)
  176. {
  177. HashMap<String, String> environment;
  178. auto handle_environment_entry = [&environment] (const char* decl) {
  179. char* eq = strchr(decl, '=');
  180. if (!eq)
  181. return;
  182. size_t var_length = eq - decl;
  183. char* var = (char*)alloca(var_length + 1);
  184. memcpy(var, decl, var_length);
  185. var[var_length] = '\0';
  186. const char* value = eq + 1;
  187. environment.set(var, value);
  188. };
  189. for (size_t i = 0; environ[i]; ++i)
  190. handle_environment_entry(environ[i]);
  191. handle_environment_entry(new_var);
  192. //extern bool __environ_is_malloced;
  193. //if (__environ_is_malloced)
  194. // free(environ);
  195. //__environ_is_malloced = true;
  196. int environment_size = sizeof(char*); // For the null sentinel.
  197. for (auto& it : environment)
  198. environment_size += (int)sizeof(char*) + it.key.length() + 1 + it.value.length() + 1;
  199. char* buffer = (char*)malloc(environment_size);
  200. environ = (char**)buffer;
  201. char* bufptr = buffer + sizeof(char*) * (environment.size() + 1);
  202. int i = 0;
  203. for (auto& it : environment) {
  204. environ[i] = bufptr;
  205. memcpy(bufptr, it.key.characters(), it.key.length());
  206. bufptr += it.key.length();
  207. *(bufptr++) = '=';
  208. memcpy(bufptr, it.value.characters(), it.value.length());
  209. bufptr += it.value.length();
  210. *(bufptr++) = '\0';
  211. ++i;
  212. }
  213. environ[environment.size()] = nullptr;
  214. return 0;
  215. }
  216. double strtod(const char* str, char** endptr)
  217. {
  218. (void)str;
  219. (void)endptr;
  220. dbgprintf("LibC: strtod: '%s'\n", str);
  221. assert(false);
  222. }
  223. double atof(const char* str)
  224. {
  225. dbgprintf("LibC: atof: '%s'\n", str);
  226. assert(false);
  227. }
  228. int atoi(const char* str)
  229. {
  230. size_t len = strlen(str);
  231. int value = 0;
  232. bool isNegative = false;
  233. for (size_t i = 0; i < len; ++i) {
  234. if (i == 0 && str[0] == '-') {
  235. isNegative = true;
  236. continue;
  237. }
  238. if (str[i] < '0' || str[i] > '9')
  239. return value;
  240. value = value * 10;
  241. value += str[i] - '0';
  242. }
  243. return isNegative ? -value : value;
  244. }
  245. long atol(const char* str)
  246. {
  247. static_assert(sizeof(int) == sizeof(long));
  248. return atoi(str);
  249. }
  250. long long atoll(const char* str)
  251. {
  252. dbgprintf("FIXME(Libc): atoll('%s') passing through to atol()\n", str);
  253. return atol(str);
  254. }
  255. static char ptsname_buf[32];
  256. char* ptsname(int fd)
  257. {
  258. if (ptsname_r(fd, ptsname_buf, sizeof(ptsname_buf)) < 0)
  259. return nullptr;
  260. return ptsname_buf;
  261. }
  262. int ptsname_r(int fd, char* buffer, size_t size)
  263. {
  264. int rc = syscall(SC_ptsname_r, fd, buffer, size);
  265. __RETURN_WITH_ERRNO(rc, rc, -1);
  266. }
  267. static unsigned long s_next_rand = 1;
  268. int rand()
  269. {
  270. s_next_rand = s_next_rand * 1103515245 + 12345;
  271. return((unsigned)(s_next_rand/((RAND_MAX + 1) * 2)) % (RAND_MAX + 1));
  272. }
  273. void srand(unsigned seed)
  274. {
  275. s_next_rand = seed;
  276. }
  277. int abs(int i)
  278. {
  279. return i < 0 ? -i : i;
  280. }
  281. long int random()
  282. {
  283. return rand();
  284. }
  285. void srandom(unsigned seed)
  286. {
  287. srand(seed);
  288. }
  289. int system(const char* command)
  290. {
  291. return execl("/bin/sh", "sh", "-c", command, nullptr);
  292. }
  293. char* mktemp(char* pattern)
  294. {
  295. int length = strlen(pattern);
  296. // FIXME: Check for an invalid template pattern and return EINVAL.
  297. if (length < 6) {
  298. pattern[0] = '\0';
  299. errno = EINVAL;
  300. return pattern;
  301. }
  302. int start = length - 6;
  303. static constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  304. for (int attempt = 0; attempt < 100; ++attempt) {
  305. for (int i = 0; i < 6; ++i)
  306. pattern[start + i] = random_characters[(rand() % sizeof(random_characters))];
  307. struct stat st;
  308. int rc = lstat(pattern, &st);
  309. if (rc < 0 && errno == ENOENT)
  310. return pattern;
  311. }
  312. pattern[0] = '\0';
  313. errno = EEXIST;
  314. return pattern;
  315. }
  316. void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))
  317. {
  318. dbgprintf("FIXME(LibC): bsearch(%p, %p, %u, %u, %p)\n", key, base, nmemb, size, compar);
  319. ASSERT_NOT_REACHED();
  320. }
  321. div_t div(int numerator, int denominator)
  322. {
  323. div_t result;
  324. result.quot = numerator / denominator;
  325. result.rem = numerator % denominator;
  326. return result;
  327. }
  328. ldiv_t ldiv(long numerator, long denominator)
  329. {
  330. ldiv_t result;
  331. result.quot = numerator / denominator;
  332. result.rem = numerator % denominator;
  333. return result;
  334. }
  335. size_t mbstowcs(wchar_t*, const char*, size_t)
  336. {
  337. assert(false);
  338. }
  339. int atexit(void (*function)())
  340. {
  341. (void)function;
  342. assert(false);
  343. }
  344. long strtol(const char* str, char** endptr, int base)
  345. {
  346. const char* s = str;
  347. unsigned long acc;
  348. int c;
  349. unsigned long cutoff;
  350. int neg = 0;
  351. int any;
  352. int cutlim;
  353. do {
  354. c = *s++;
  355. } while (isspace(c));
  356. if (c == '-') {
  357. neg = 1;
  358. c = *s++;
  359. } else if (c == '+')
  360. c = *s++;
  361. if ((base == 0 || base == 16) &&
  362. c == '0' && (*s == 'x' || *s == 'X')) {
  363. c = s[1];
  364. s += 2;
  365. base = 16;
  366. }
  367. if (base == 0)
  368. base = c == '0' ? 8 : 10;
  369. cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
  370. cutlim = cutoff % (unsigned long)base;
  371. cutoff /= (unsigned long)base;
  372. for (acc = 0, any = 0;; c = *s++) {
  373. if (isdigit(c))
  374. c -= '0';
  375. else if (isalpha(c))
  376. c -= isupper(c) ? 'A' - 10 : 'a' - 10;
  377. else
  378. break;
  379. if (c >= base)
  380. break;
  381. if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
  382. any = -1;
  383. else {
  384. any = 1;
  385. acc *= base;
  386. acc += c;
  387. }
  388. }
  389. if (any < 0) {
  390. acc = neg ? LONG_MIN : LONG_MAX;
  391. errno = ERANGE;
  392. } else if (neg)
  393. acc = -acc;
  394. if (endptr)
  395. *endptr = (char*)(any ? s - 1 : str);
  396. return acc;
  397. }
  398. unsigned long strtoul(const char*, char** endptr, int base)
  399. {
  400. (void)endptr;
  401. (void)base;
  402. assert(false);
  403. }
  404. }