malloc.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Peter Elliott <pelliott@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/BuiltinWrappers.h>
  8. #include <AK/Debug.h>
  9. #include <AK/ScopedValueRollback.h>
  10. #include <AK/Vector.h>
  11. #include <assert.h>
  12. #include <errno.h>
  13. #include <mallocdefs.h>
  14. #include <pthread.h>
  15. #include <serenity.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <sys/internals.h>
  20. #include <sys/mman.h>
  21. #include <syscall.h>
  22. class PthreadMutexLocker {
  23. public:
  24. ALWAYS_INLINE explicit PthreadMutexLocker(pthread_mutex_t& mutex)
  25. : m_mutex(mutex)
  26. {
  27. lock();
  28. __heap_is_stable = false;
  29. }
  30. ALWAYS_INLINE ~PthreadMutexLocker()
  31. {
  32. __heap_is_stable = true;
  33. unlock();
  34. }
  35. ALWAYS_INLINE void lock() { pthread_mutex_lock(&m_mutex); }
  36. ALWAYS_INLINE void unlock() { pthread_mutex_unlock(&m_mutex); }
  37. private:
  38. pthread_mutex_t& m_mutex;
  39. };
  40. #define RECYCLE_BIG_ALLOCATIONS
  41. static pthread_mutex_t s_malloc_mutex = PTHREAD_MUTEX_INITIALIZER;
  42. bool __heap_is_stable = true;
  43. constexpr size_t number_of_hot_chunked_blocks_to_keep_around = 16;
  44. constexpr size_t number_of_cold_chunked_blocks_to_keep_around = 16;
  45. constexpr size_t number_of_big_blocks_to_keep_around_per_size_class = 8;
  46. static bool s_log_malloc = false;
  47. static bool s_scrub_malloc = true;
  48. static bool s_scrub_free = true;
  49. static bool s_profiling = false;
  50. static bool s_in_userspace_emulator = false;
  51. ALWAYS_INLINE static void ue_notify_malloc(void const* ptr, size_t size)
  52. {
  53. if (s_in_userspace_emulator)
  54. syscall(SC_emuctl, 1, size, (FlatPtr)ptr);
  55. }
  56. ALWAYS_INLINE static void ue_notify_free(void const* ptr)
  57. {
  58. if (s_in_userspace_emulator)
  59. syscall(SC_emuctl, 2, (FlatPtr)ptr, 0);
  60. }
  61. ALWAYS_INLINE static void ue_notify_realloc(void const* ptr, size_t size)
  62. {
  63. if (s_in_userspace_emulator)
  64. syscall(SC_emuctl, 3, size, (FlatPtr)ptr);
  65. }
  66. ALWAYS_INLINE static void ue_notify_chunk_size_changed(void const* block, size_t chunk_size)
  67. {
  68. if (s_in_userspace_emulator)
  69. syscall(SC_emuctl, 4, chunk_size, (FlatPtr)block);
  70. }
  71. struct MemoryAuditingSuppressor {
  72. ALWAYS_INLINE MemoryAuditingSuppressor()
  73. {
  74. if (s_in_userspace_emulator)
  75. syscall(SC_emuctl, 7);
  76. }
  77. ALWAYS_INLINE ~MemoryAuditingSuppressor()
  78. {
  79. if (s_in_userspace_emulator)
  80. syscall(SC_emuctl, 8);
  81. }
  82. };
  83. struct MallocStats {
  84. size_t number_of_malloc_calls;
  85. size_t number_of_big_allocator_hits;
  86. size_t number_of_big_allocator_purge_hits;
  87. size_t number_of_big_allocs;
  88. size_t number_of_hot_empty_block_hits;
  89. size_t number_of_cold_empty_block_hits;
  90. size_t number_of_cold_empty_block_purge_hits;
  91. size_t number_of_block_allocs;
  92. size_t number_of_blocks_full;
  93. size_t number_of_free_calls;
  94. size_t number_of_big_allocator_keeps;
  95. size_t number_of_big_allocator_frees;
  96. size_t number_of_freed_full_blocks;
  97. size_t number_of_hot_keeps;
  98. size_t number_of_cold_keeps;
  99. size_t number_of_frees;
  100. };
  101. static MallocStats g_malloc_stats = {};
  102. static size_t s_hot_empty_block_count { 0 };
  103. static ChunkedBlock* s_hot_empty_blocks[number_of_hot_chunked_blocks_to_keep_around] { nullptr };
  104. static size_t s_cold_empty_block_count { 0 };
  105. static ChunkedBlock* s_cold_empty_blocks[number_of_cold_chunked_blocks_to_keep_around] { nullptr };
  106. struct Allocator {
  107. size_t size { 0 };
  108. size_t block_count { 0 };
  109. ChunkedBlock::List usable_blocks;
  110. ChunkedBlock::List full_blocks;
  111. };
  112. struct BigAllocator {
  113. Vector<BigAllocationBlock*, number_of_big_blocks_to_keep_around_per_size_class> blocks;
  114. };
  115. // Allocators will be initialized in __malloc_init.
  116. // We can not rely on global constructors to initialize them,
  117. // because they must be initialized before other global constructors
  118. // are run. Similarly, we can not allow global destructors to destruct
  119. // them. We could have used AK::NeverDestoyed to prevent the latter,
  120. // but it would have not helped with the former.
  121. alignas(Allocator) static u8 g_allocators_storage[sizeof(Allocator) * num_size_classes];
  122. alignas(BigAllocator) static u8 g_big_allocators_storage[sizeof(BigAllocator)];
  123. static inline Allocator (&allocators())[num_size_classes]
  124. {
  125. return reinterpret_cast<Allocator(&)[num_size_classes]>(g_allocators_storage);
  126. }
  127. static inline BigAllocator (&big_allocators())[1]
  128. {
  129. return reinterpret_cast<BigAllocator(&)[1]>(g_big_allocators_storage);
  130. }
  131. // --- BEGIN MATH ---
  132. // This stuff is only used for checking if there exists an aligned block in a
  133. // chunk. It has no bearing on the rest of the allocator, especially for
  134. // regular malloc.
  135. static inline unsigned long modulo(long a, long b)
  136. {
  137. return (b + (a % b)) % b;
  138. }
  139. struct EuclideanResult {
  140. long x;
  141. long y;
  142. long gcd;
  143. };
  144. // Returns x, y, gcd.
  145. static inline EuclideanResult extended_euclid(long a, long b)
  146. {
  147. EuclideanResult old = { 1, 0, a };
  148. EuclideanResult current = { 0, 1, b };
  149. while (current.gcd != 0) {
  150. long quotient = old.gcd / current.gcd;
  151. EuclideanResult next = {
  152. old.x - quotient * current.x,
  153. old.y - quotient * current.y,
  154. old.gcd - quotient * current.gcd,
  155. };
  156. old = current;
  157. current = next;
  158. }
  159. return old;
  160. }
  161. static inline bool block_has_aligned_chunk(long align, long bytes_per_chunk, long chunk_capacity)
  162. {
  163. // Never do math on a normal malloc.
  164. if ((size_t)align <= sizeof(ChunkedBlock))
  165. return true;
  166. // Solve the linear congruence n*bytes_per_chunk = -sizeof(ChunkedBlock) (mod align).
  167. auto [x, y, gcd] = extended_euclid(bytes_per_chunk % align, align);
  168. long constant = modulo(-sizeof(ChunkedBlock), align);
  169. if (constant % gcd != 0)
  170. // No solution. Chunk size is probably a multiple of align.
  171. return false;
  172. long n = modulo(x * (constant / gcd), align);
  173. if (x < 0)
  174. n = (n + align / gcd) % align;
  175. // Don't ask me to prove this.
  176. VERIFY(n > 0);
  177. return n < chunk_capacity;
  178. }
  179. // --- END MATH ---
  180. static Allocator* allocator_for_size(size_t size, size_t& good_size, size_t align = 1)
  181. {
  182. for (size_t i = 0; size_classes[i]; ++i) {
  183. auto& allocator = allocators()[i];
  184. if (size <= size_classes[i] && block_has_aligned_chunk(align, allocator.size, (ChunkedBlock::block_size - sizeof(ChunkedBlock)) / allocator.size)) {
  185. good_size = size_classes[i];
  186. return &allocator;
  187. }
  188. }
  189. good_size = PAGE_ROUND_UP(size);
  190. return nullptr;
  191. }
  192. #ifdef RECYCLE_BIG_ALLOCATIONS
  193. static BigAllocator* big_allocator_for_size(size_t size)
  194. {
  195. if (size == 65536)
  196. return &big_allocators()[0];
  197. return nullptr;
  198. }
  199. #endif
  200. extern "C" {
  201. static ErrorOr<void*> os_alloc(size_t size, char const* name)
  202. {
  203. int flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_PURGEABLE;
  204. #if ARCH(X86_64)
  205. flags |= MAP_RANDOMIZED;
  206. #endif
  207. auto* ptr = serenity_mmap(nullptr, size, PROT_READ | PROT_WRITE, flags, 0, 0, ChunkedBlock::block_size, name);
  208. VERIFY(ptr != nullptr);
  209. if (ptr == MAP_FAILED) {
  210. return ENOMEM;
  211. }
  212. return ptr;
  213. }
  214. static void os_free(void* ptr, size_t size)
  215. {
  216. int rc = munmap(ptr, size);
  217. assert(rc == 0);
  218. }
  219. static void* try_allocate_chunk_aligned(size_t align, ChunkedBlock& block)
  220. {
  221. // These loops are guaranteed to run only once for a standard-aligned malloc.
  222. for (FreelistEntry** entry = &(block.m_freelist); *entry != nullptr; entry = &((*entry)->next)) {
  223. if ((reinterpret_cast<uintptr_t>(*entry) & (align - 1)) == 0) {
  224. --block.m_free_chunks;
  225. void* ptr = *entry;
  226. *entry = (*entry)->next; // Delete the entry.
  227. return ptr;
  228. }
  229. }
  230. for (; block.m_next_lazy_freelist_index < block.chunk_capacity(); block.m_next_lazy_freelist_index++) {
  231. void* ptr = block.m_slot + block.m_next_lazy_freelist_index * block.m_size;
  232. if ((reinterpret_cast<uintptr_t>(ptr) & (align - 1)) == 0) {
  233. --block.m_free_chunks;
  234. block.m_next_lazy_freelist_index++;
  235. return ptr;
  236. }
  237. auto* entry = (FreelistEntry*)ptr;
  238. entry->next = block.m_freelist;
  239. block.m_freelist = entry;
  240. }
  241. return nullptr;
  242. }
  243. enum class CallerWillInitializeMemory {
  244. No,
  245. Yes,
  246. };
  247. #ifndef NO_TLS
  248. __thread bool s_allocation_enabled = true;
  249. #endif
  250. static ErrorOr<void*> malloc_impl(size_t size, size_t align, CallerWillInitializeMemory caller_will_initialize_memory)
  251. {
  252. #ifndef NO_TLS
  253. VERIFY(s_allocation_enabled);
  254. #endif
  255. // Align must be a power of 2.
  256. if (popcount(align) != 1)
  257. return EINVAL;
  258. // FIXME: Support larger than 32KiB alignments (if you dare).
  259. if (sizeof(BigAllocationBlock) + align >= ChunkedBlock::block_size)
  260. return EINVAL;
  261. if (s_log_malloc)
  262. dbgln("LibC: malloc({})", size);
  263. if (!size) {
  264. // Legally we could just return a null pointer here, but this is more
  265. // compatible with existing software.
  266. size = 1;
  267. }
  268. g_malloc_stats.number_of_malloc_calls++;
  269. size_t good_size;
  270. auto* allocator = allocator_for_size(size, good_size, align);
  271. PthreadMutexLocker locker(s_malloc_mutex);
  272. if (!allocator) {
  273. size_t real_size = round_up_to_power_of_two(sizeof(BigAllocationBlock) + size + ((align > 16) ? align : 0), ChunkedBlock::block_size);
  274. if (real_size < size) {
  275. dbgln_if(MALLOC_DEBUG, "LibC: Detected overflow trying to do big allocation of size {} for {}", real_size, size);
  276. return ENOMEM;
  277. }
  278. #ifdef RECYCLE_BIG_ALLOCATIONS
  279. if (auto* allocator = big_allocator_for_size(real_size)) {
  280. if (!allocator->blocks.is_empty()) {
  281. g_malloc_stats.number_of_big_allocator_hits++;
  282. auto* block = allocator->blocks.take_last();
  283. int rc = madvise(block, real_size, MADV_SET_NONVOLATILE);
  284. bool this_block_was_purged = rc == 1;
  285. if (rc < 0) {
  286. perror("madvise");
  287. VERIFY_NOT_REACHED();
  288. }
  289. if (mprotect(block, real_size, PROT_READ | PROT_WRITE) < 0) {
  290. perror("mprotect");
  291. VERIFY_NOT_REACHED();
  292. }
  293. if (this_block_was_purged) {
  294. g_malloc_stats.number_of_big_allocator_purge_hits++;
  295. new (block) BigAllocationBlock(real_size);
  296. }
  297. void* ptr = reinterpret_cast<void*>(round_up_to_power_of_two(reinterpret_cast<uintptr_t>(&block->m_slot[0]), align));
  298. ue_notify_malloc(ptr, size);
  299. return ptr;
  300. }
  301. }
  302. #endif
  303. auto* block = (BigAllocationBlock*)TRY(os_alloc(real_size, "malloc: BigAllocationBlock"));
  304. g_malloc_stats.number_of_big_allocs++;
  305. new (block) BigAllocationBlock(real_size);
  306. void* ptr = reinterpret_cast<void*>(round_up_to_power_of_two(reinterpret_cast<uintptr_t>(&block->m_slot[0]), align));
  307. ue_notify_malloc(ptr, size);
  308. return ptr;
  309. }
  310. ChunkedBlock* block = nullptr;
  311. void* ptr = nullptr;
  312. for (auto& current : allocator->usable_blocks) {
  313. if (current.free_chunks()) {
  314. ptr = try_allocate_chunk_aligned(align, current);
  315. if (ptr) {
  316. block = &current;
  317. break;
  318. }
  319. }
  320. }
  321. if (!block && s_hot_empty_block_count) {
  322. g_malloc_stats.number_of_hot_empty_block_hits++;
  323. block = s_hot_empty_blocks[--s_hot_empty_block_count];
  324. if (block->m_size != good_size) {
  325. new (block) ChunkedBlock(good_size);
  326. ue_notify_chunk_size_changed(block, good_size);
  327. char buffer[64];
  328. snprintf(buffer, sizeof(buffer), "malloc: ChunkedBlock(%zu)", good_size);
  329. set_mmap_name(block, ChunkedBlock::block_size, buffer);
  330. }
  331. allocator->usable_blocks.append(*block);
  332. }
  333. if (!block && s_cold_empty_block_count) {
  334. g_malloc_stats.number_of_cold_empty_block_hits++;
  335. block = s_cold_empty_blocks[--s_cold_empty_block_count];
  336. int rc = madvise(block, ChunkedBlock::block_size, MADV_SET_NONVOLATILE);
  337. bool this_block_was_purged = rc == 1;
  338. if (rc < 0) {
  339. perror("madvise");
  340. VERIFY_NOT_REACHED();
  341. }
  342. rc = mprotect(block, ChunkedBlock::block_size, PROT_READ | PROT_WRITE);
  343. if (rc < 0) {
  344. perror("mprotect");
  345. VERIFY_NOT_REACHED();
  346. }
  347. if (this_block_was_purged || block->m_size != good_size) {
  348. if (this_block_was_purged)
  349. g_malloc_stats.number_of_cold_empty_block_purge_hits++;
  350. new (block) ChunkedBlock(good_size);
  351. ue_notify_chunk_size_changed(block, good_size);
  352. }
  353. allocator->usable_blocks.append(*block);
  354. }
  355. if (!block) {
  356. g_malloc_stats.number_of_block_allocs++;
  357. char buffer[64];
  358. snprintf(buffer, sizeof(buffer), "malloc: ChunkedBlock(%zu)", good_size);
  359. block = (ChunkedBlock*)TRY(os_alloc(ChunkedBlock::block_size, buffer));
  360. new (block) ChunkedBlock(good_size);
  361. allocator->usable_blocks.append(*block);
  362. ++allocator->block_count;
  363. }
  364. if (!ptr) {
  365. ptr = try_allocate_chunk_aligned(align, *block);
  366. }
  367. VERIFY(ptr);
  368. if (block->is_full()) {
  369. g_malloc_stats.number_of_blocks_full++;
  370. dbgln_if(MALLOC_DEBUG, "Block {:p} is now full in size class {}", block, good_size);
  371. allocator->usable_blocks.remove(*block);
  372. allocator->full_blocks.append(*block);
  373. }
  374. dbgln_if(MALLOC_DEBUG, "LibC: allocated {:p} (chunk in block {:p}, size {})", ptr, block, block->bytes_per_chunk());
  375. if (s_scrub_malloc && caller_will_initialize_memory == CallerWillInitializeMemory::No)
  376. memset(ptr, MALLOC_SCRUB_BYTE, block->m_size);
  377. ue_notify_malloc(ptr, size);
  378. return ptr;
  379. }
  380. static void free_impl(void* ptr)
  381. {
  382. #ifndef NO_TLS
  383. VERIFY(s_allocation_enabled);
  384. #endif
  385. ScopedValueRollback rollback(errno);
  386. if (!ptr)
  387. return;
  388. g_malloc_stats.number_of_free_calls++;
  389. void* block_base = (void*)((FlatPtr)ptr & ChunkedBlock::ChunkedBlock::block_mask);
  390. size_t magic = *(size_t*)block_base;
  391. PthreadMutexLocker locker(s_malloc_mutex);
  392. if (magic == MAGIC_BIGALLOC_HEADER) {
  393. auto* block = (BigAllocationBlock*)block_base;
  394. #ifdef RECYCLE_BIG_ALLOCATIONS
  395. if (auto* allocator = big_allocator_for_size(block->m_size)) {
  396. if (allocator->blocks.size() < number_of_big_blocks_to_keep_around_per_size_class) {
  397. g_malloc_stats.number_of_big_allocator_keeps++;
  398. allocator->blocks.append(block);
  399. size_t this_block_size = block->m_size;
  400. if (mprotect(block, this_block_size, PROT_NONE) < 0) {
  401. perror("mprotect");
  402. VERIFY_NOT_REACHED();
  403. }
  404. if (madvise(block, this_block_size, MADV_SET_VOLATILE) != 0) {
  405. perror("madvise");
  406. VERIFY_NOT_REACHED();
  407. }
  408. return;
  409. }
  410. }
  411. #endif
  412. g_malloc_stats.number_of_big_allocator_frees++;
  413. os_free(block, block->m_size);
  414. return;
  415. }
  416. assert(magic == MAGIC_PAGE_HEADER);
  417. auto* block = (ChunkedBlock*)block_base;
  418. dbgln_if(MALLOC_DEBUG, "LibC: freeing {:p} in allocator {:p} (size={}, used={})", ptr, block, block->bytes_per_chunk(), block->used_chunks());
  419. if (s_scrub_free)
  420. memset(ptr, FREE_SCRUB_BYTE, block->bytes_per_chunk());
  421. auto* entry = (FreelistEntry*)ptr;
  422. entry->next = block->m_freelist;
  423. block->m_freelist = entry;
  424. if (block->is_full()) {
  425. size_t good_size;
  426. auto* allocator = allocator_for_size(block->m_size, good_size);
  427. dbgln_if(MALLOC_DEBUG, "Block {:p} no longer full in size class {}", block, good_size);
  428. g_malloc_stats.number_of_freed_full_blocks++;
  429. allocator->full_blocks.remove(*block);
  430. allocator->usable_blocks.prepend(*block);
  431. }
  432. ++block->m_free_chunks;
  433. if (!block->used_chunks()) {
  434. size_t good_size;
  435. auto* allocator = allocator_for_size(block->m_size, good_size);
  436. if (s_hot_empty_block_count < number_of_hot_chunked_blocks_to_keep_around) {
  437. dbgln_if(MALLOC_DEBUG, "Keeping hot block {:p} around", block);
  438. g_malloc_stats.number_of_hot_keeps++;
  439. allocator->usable_blocks.remove(*block);
  440. s_hot_empty_blocks[s_hot_empty_block_count++] = block;
  441. return;
  442. }
  443. if (s_cold_empty_block_count < number_of_cold_chunked_blocks_to_keep_around) {
  444. dbgln_if(MALLOC_DEBUG, "Keeping cold block {:p} around", block);
  445. g_malloc_stats.number_of_cold_keeps++;
  446. allocator->usable_blocks.remove(*block);
  447. s_cold_empty_blocks[s_cold_empty_block_count++] = block;
  448. mprotect(block, ChunkedBlock::block_size, PROT_NONE);
  449. madvise(block, ChunkedBlock::block_size, MADV_SET_VOLATILE);
  450. return;
  451. }
  452. dbgln_if(MALLOC_DEBUG, "Releasing block {:p} for size class {}", block, good_size);
  453. g_malloc_stats.number_of_frees++;
  454. allocator->usable_blocks.remove(*block);
  455. --allocator->block_count;
  456. os_free(block, ChunkedBlock::block_size);
  457. }
  458. }
  459. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
  460. void* malloc(size_t size)
  461. {
  462. MemoryAuditingSuppressor suppressor;
  463. auto ptr_or_error = malloc_impl(size, 16, CallerWillInitializeMemory::No);
  464. if (ptr_or_error.is_error()) {
  465. errno = ptr_or_error.error().code();
  466. return nullptr;
  467. }
  468. if (s_profiling)
  469. perf_event(PERF_EVENT_MALLOC, size, reinterpret_cast<FlatPtr>(ptr_or_error.value()));
  470. return ptr_or_error.value();
  471. }
  472. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html
  473. void free(void* ptr)
  474. {
  475. MemoryAuditingSuppressor suppressor;
  476. if (s_profiling)
  477. perf_event(PERF_EVENT_FREE, reinterpret_cast<FlatPtr>(ptr), 0);
  478. ue_notify_free(ptr);
  479. free_impl(ptr);
  480. }
  481. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/calloc.html
  482. void* calloc(size_t count, size_t size)
  483. {
  484. MemoryAuditingSuppressor suppressor;
  485. if (Checked<size_t>::multiplication_would_overflow(count, size)) {
  486. errno = ENOMEM;
  487. return nullptr;
  488. }
  489. size_t new_size = count * size;
  490. auto ptr_or_error = malloc_impl(new_size, 16, CallerWillInitializeMemory::Yes);
  491. if (ptr_or_error.is_error()) {
  492. errno = ptr_or_error.error().code();
  493. return nullptr;
  494. }
  495. memset(ptr_or_error.value(), 0, new_size);
  496. return ptr_or_error.value();
  497. }
  498. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_memalign.html
  499. int posix_memalign(void** memptr, size_t alignment, size_t size)
  500. {
  501. MemoryAuditingSuppressor suppressor;
  502. auto ptr_or_error = malloc_impl(size, alignment, CallerWillInitializeMemory::No);
  503. if (ptr_or_error.is_error())
  504. return ptr_or_error.error().code();
  505. *memptr = ptr_or_error.value();
  506. return 0;
  507. }
  508. void* aligned_alloc(size_t alignment, size_t size)
  509. {
  510. MemoryAuditingSuppressor suppressor;
  511. auto ptr_or_error = malloc_impl(size, alignment, CallerWillInitializeMemory::No);
  512. if (ptr_or_error.is_error()) {
  513. errno = ptr_or_error.error().code();
  514. return nullptr;
  515. }
  516. return ptr_or_error.value();
  517. }
  518. size_t malloc_size(void const* ptr)
  519. {
  520. MemoryAuditingSuppressor suppressor;
  521. if (!ptr)
  522. return 0;
  523. void* page_base = (void*)((FlatPtr)ptr & ChunkedBlock::block_mask);
  524. auto* header = (CommonHeader const*)page_base;
  525. auto size = header->m_size;
  526. if (header->m_magic == MAGIC_BIGALLOC_HEADER)
  527. size -= sizeof(BigAllocationBlock);
  528. else
  529. VERIFY(header->m_magic == MAGIC_PAGE_HEADER);
  530. return size;
  531. }
  532. size_t malloc_good_size(size_t size)
  533. {
  534. size_t good_size;
  535. allocator_for_size(size, good_size);
  536. return good_size;
  537. }
  538. void* realloc(void* ptr, size_t size)
  539. {
  540. MemoryAuditingSuppressor suppressor;
  541. if (!ptr)
  542. return malloc(size);
  543. if (!size) {
  544. free(ptr);
  545. return nullptr;
  546. }
  547. auto existing_allocation_size = malloc_size(ptr);
  548. if (size <= existing_allocation_size) {
  549. ue_notify_realloc(ptr, size);
  550. return ptr;
  551. }
  552. auto* new_ptr = malloc(size);
  553. if (new_ptr) {
  554. memcpy(new_ptr, ptr, min(existing_allocation_size, size));
  555. free(ptr);
  556. }
  557. return new_ptr;
  558. }
  559. void __malloc_init()
  560. {
  561. s_in_userspace_emulator = (int)syscall(SC_emuctl, 0) != -ENOSYS;
  562. if (s_in_userspace_emulator) {
  563. // Don't bother scrubbing memory if we're running in UE since it
  564. // keeps track of heap memory anyway.
  565. s_scrub_malloc = false;
  566. s_scrub_free = false;
  567. }
  568. if (secure_getenv("LIBC_NOSCRUB_MALLOC"))
  569. s_scrub_malloc = false;
  570. if (secure_getenv("LIBC_NOSCRUB_FREE"))
  571. s_scrub_free = false;
  572. if (secure_getenv("LIBC_LOG_MALLOC"))
  573. s_log_malloc = true;
  574. if (secure_getenv("LIBC_PROFILE_MALLOC"))
  575. s_profiling = true;
  576. for (size_t i = 0; i < num_size_classes; ++i) {
  577. new (&allocators()[i]) Allocator();
  578. allocators()[i].size = size_classes[i];
  579. }
  580. new (&big_allocators()[0])(BigAllocator);
  581. }
  582. void serenity_dump_malloc_stats()
  583. {
  584. dbgln("# malloc() calls: {}", g_malloc_stats.number_of_malloc_calls);
  585. dbgln();
  586. dbgln("big alloc hits: {}", g_malloc_stats.number_of_big_allocator_hits);
  587. dbgln("big alloc hits that were purged: {}", g_malloc_stats.number_of_big_allocator_purge_hits);
  588. dbgln("big allocs: {}", g_malloc_stats.number_of_big_allocs);
  589. dbgln();
  590. dbgln("empty hot block hits: {}", g_malloc_stats.number_of_hot_empty_block_hits);
  591. dbgln("empty cold block hits: {}", g_malloc_stats.number_of_cold_empty_block_hits);
  592. dbgln("empty cold block hits that were purged: {}", g_malloc_stats.number_of_cold_empty_block_purge_hits);
  593. dbgln("block allocs: {}", g_malloc_stats.number_of_block_allocs);
  594. dbgln("filled blocks: {}", g_malloc_stats.number_of_blocks_full);
  595. dbgln();
  596. dbgln("# free() calls: {}", g_malloc_stats.number_of_free_calls);
  597. dbgln();
  598. dbgln("big alloc keeps: {}", g_malloc_stats.number_of_big_allocator_keeps);
  599. dbgln("big alloc frees: {}", g_malloc_stats.number_of_big_allocator_frees);
  600. dbgln();
  601. dbgln("full block frees: {}", g_malloc_stats.number_of_freed_full_blocks);
  602. dbgln("number of hot keeps: {}", g_malloc_stats.number_of_hot_keeps);
  603. dbgln("number of cold keeps: {}", g_malloc_stats.number_of_cold_keeps);
  604. dbgln("number of frees: {}", g_malloc_stats.number_of_frees);
  605. }
  606. }