malloc.cpp 24 KB

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