malloc.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/InlineLinkedList.h>
  8. #include <AK/ScopedValueRollback.h>
  9. #include <AK/Vector.h>
  10. #include <LibELF/AuxiliaryVector.h>
  11. #include <LibThread/Lock.h>
  12. #include <assert.h>
  13. #include <errno.h>
  14. #include <mallocdefs.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. // FIXME: Thread safety.
  23. #define RECYCLE_BIG_ALLOCATIONS
  24. #define PAGE_ROUND_UP(x) ((((size_t)(x)) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1)))
  25. static LibThread::Lock& malloc_lock()
  26. {
  27. static u32 lock_storage[sizeof(LibThread::Lock) / sizeof(u32)];
  28. return *reinterpret_cast<LibThread::Lock*>(&lock_storage);
  29. }
  30. constexpr size_t number_of_chunked_blocks_to_keep_around_per_size_class = 4;
  31. constexpr size_t number_of_big_blocks_to_keep_around_per_size_class = 8;
  32. static bool s_log_malloc = false;
  33. static bool s_scrub_malloc = true;
  34. static bool s_scrub_free = true;
  35. static bool s_profiling = false;
  36. static bool s_in_userspace_emulator = false;
  37. ALWAYS_INLINE static void ue_notify_malloc(const void* ptr, size_t size)
  38. {
  39. if (s_in_userspace_emulator)
  40. syscall(SC_emuctl, 1, size, (FlatPtr)ptr);
  41. }
  42. ALWAYS_INLINE static void ue_notify_free(const void* ptr)
  43. {
  44. if (s_in_userspace_emulator)
  45. syscall(SC_emuctl, 2, (FlatPtr)ptr, 0);
  46. }
  47. ALWAYS_INLINE static void ue_notify_realloc(const void* ptr, size_t size)
  48. {
  49. if (s_in_userspace_emulator)
  50. syscall(SC_emuctl, 3, size, (FlatPtr)ptr);
  51. }
  52. struct MallocStats {
  53. size_t number_of_malloc_calls;
  54. size_t number_of_big_allocator_hits;
  55. size_t number_of_big_allocator_purge_hits;
  56. size_t number_of_big_allocs;
  57. size_t number_of_empty_block_hits;
  58. size_t number_of_empty_block_purge_hits;
  59. size_t number_of_block_allocs;
  60. size_t number_of_blocks_full;
  61. size_t number_of_free_calls;
  62. size_t number_of_big_allocator_keeps;
  63. size_t number_of_big_allocator_frees;
  64. size_t number_of_freed_full_blocks;
  65. size_t number_of_keeps;
  66. size_t number_of_frees;
  67. };
  68. static MallocStats g_malloc_stats = {};
  69. struct Allocator {
  70. size_t size { 0 };
  71. size_t block_count { 0 };
  72. size_t empty_block_count { 0 };
  73. ChunkedBlock* empty_blocks[number_of_chunked_blocks_to_keep_around_per_size_class] { nullptr };
  74. InlineLinkedList<ChunkedBlock> usable_blocks;
  75. InlineLinkedList<ChunkedBlock> full_blocks;
  76. };
  77. struct BigAllocator {
  78. Vector<BigAllocationBlock*, number_of_big_blocks_to_keep_around_per_size_class> blocks;
  79. };
  80. // Allocators will be initialized in __malloc_init.
  81. // We can not rely on global constructors to initialize them,
  82. // because they must be initialized before other global constructors
  83. // are run. Similarly, we can not allow global destructors to destruct
  84. // them. We could have used AK::NeverDestoyed to prevent the latter,
  85. // but it would have not helped with the former.
  86. static u8 g_allocators_storage[sizeof(Allocator) * size_classes.size()];
  87. static u8 g_big_allocators_storage[sizeof(BigAllocator)];
  88. static inline Allocator (&allocators())[size_classes.size()]
  89. {
  90. return reinterpret_cast<Allocator(&)[size_classes.size()]>(g_allocators_storage);
  91. }
  92. static inline BigAllocator (&big_allocators())[1]
  93. {
  94. return reinterpret_cast<BigAllocator(&)[1]>(g_big_allocators_storage);
  95. }
  96. static Allocator* allocator_for_size(size_t size, size_t& good_size)
  97. {
  98. for (size_t i = 0; size_classes[i]; ++i) {
  99. if (size <= size_classes[i]) {
  100. good_size = size_classes[i];
  101. return &allocators()[i];
  102. }
  103. }
  104. good_size = PAGE_ROUND_UP(size);
  105. return nullptr;
  106. }
  107. #ifdef RECYCLE_BIG_ALLOCATIONS
  108. static BigAllocator* big_allocator_for_size(size_t size)
  109. {
  110. if (size == 65536)
  111. return &big_allocators()[0];
  112. return nullptr;
  113. }
  114. #endif
  115. extern "C" {
  116. static void* os_alloc(size_t size, const char* name)
  117. {
  118. auto* ptr = serenity_mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0, ChunkedBlock::block_size, name);
  119. VERIFY(ptr != MAP_FAILED);
  120. return ptr;
  121. }
  122. static void os_free(void* ptr, size_t size)
  123. {
  124. int rc = munmap(ptr, size);
  125. assert(rc == 0);
  126. }
  127. enum class CallerWillInitializeMemory {
  128. No,
  129. Yes,
  130. };
  131. static void* malloc_impl(size_t size, CallerWillInitializeMemory caller_will_initialize_memory)
  132. {
  133. LibThread::Locker locker(malloc_lock());
  134. if (s_log_malloc)
  135. dbgln("LibC: malloc({})", size);
  136. if (!size) {
  137. // Legally we could just return a null pointer here, but this is more
  138. // compatible with existing software.
  139. size = 1;
  140. }
  141. g_malloc_stats.number_of_malloc_calls++;
  142. size_t good_size;
  143. auto* allocator = allocator_for_size(size, good_size);
  144. if (!allocator) {
  145. size_t real_size = round_up_to_power_of_two(sizeof(BigAllocationBlock) + size, ChunkedBlock::block_size);
  146. #ifdef RECYCLE_BIG_ALLOCATIONS
  147. if (auto* allocator = big_allocator_for_size(real_size)) {
  148. if (!allocator->blocks.is_empty()) {
  149. g_malloc_stats.number_of_big_allocator_hits++;
  150. auto* block = allocator->blocks.take_last();
  151. int rc = madvise(block, real_size, MADV_SET_NONVOLATILE);
  152. bool this_block_was_purged = rc == 1;
  153. if (rc < 0) {
  154. perror("madvise");
  155. VERIFY_NOT_REACHED();
  156. }
  157. if (mprotect(block, real_size, PROT_READ | PROT_WRITE) < 0) {
  158. perror("mprotect");
  159. VERIFY_NOT_REACHED();
  160. }
  161. if (this_block_was_purged) {
  162. g_malloc_stats.number_of_big_allocator_purge_hits++;
  163. new (block) BigAllocationBlock(real_size);
  164. }
  165. ue_notify_malloc(&block->m_slot[0], size);
  166. return &block->m_slot[0];
  167. }
  168. }
  169. #endif
  170. g_malloc_stats.number_of_big_allocs++;
  171. auto* block = (BigAllocationBlock*)os_alloc(real_size, "malloc: BigAllocationBlock");
  172. new (block) BigAllocationBlock(real_size);
  173. ue_notify_malloc(&block->m_slot[0], size);
  174. return &block->m_slot[0];
  175. }
  176. ChunkedBlock* block = nullptr;
  177. for (block = allocator->usable_blocks.head(); block; block = block->next()) {
  178. if (block->free_chunks())
  179. break;
  180. }
  181. if (!block && allocator->empty_block_count) {
  182. g_malloc_stats.number_of_empty_block_hits++;
  183. block = allocator->empty_blocks[--allocator->empty_block_count];
  184. int rc = madvise(block, ChunkedBlock::block_size, MADV_SET_NONVOLATILE);
  185. bool this_block_was_purged = rc == 1;
  186. if (rc < 0) {
  187. perror("madvise");
  188. VERIFY_NOT_REACHED();
  189. }
  190. rc = mprotect(block, ChunkedBlock::block_size, PROT_READ | PROT_WRITE);
  191. if (rc < 0) {
  192. perror("mprotect");
  193. VERIFY_NOT_REACHED();
  194. }
  195. if (this_block_was_purged) {
  196. g_malloc_stats.number_of_empty_block_purge_hits++;
  197. new (block) ChunkedBlock(good_size);
  198. }
  199. allocator->usable_blocks.append(block);
  200. }
  201. if (!block) {
  202. g_malloc_stats.number_of_block_allocs++;
  203. char buffer[64];
  204. snprintf(buffer, sizeof(buffer), "malloc: ChunkedBlock(%zu)", good_size);
  205. block = (ChunkedBlock*)os_alloc(ChunkedBlock::block_size, buffer);
  206. new (block) ChunkedBlock(good_size);
  207. allocator->usable_blocks.append(block);
  208. ++allocator->block_count;
  209. }
  210. --block->m_free_chunks;
  211. void* ptr = block->m_freelist;
  212. if (ptr) {
  213. block->m_freelist = block->m_freelist->next;
  214. } else {
  215. ptr = block->m_slot + block->m_next_lazy_freelist_index * block->m_size;
  216. block->m_next_lazy_freelist_index++;
  217. }
  218. VERIFY(ptr);
  219. if (block->is_full()) {
  220. g_malloc_stats.number_of_blocks_full++;
  221. dbgln_if(MALLOC_DEBUG, "Block {:p} is now full in size class {}", block, good_size);
  222. allocator->usable_blocks.remove(block);
  223. allocator->full_blocks.append(block);
  224. }
  225. dbgln_if(MALLOC_DEBUG, "LibC: allocated {:p} (chunk in block {:p}, size {})", ptr, block, block->bytes_per_chunk());
  226. if (s_scrub_malloc && caller_will_initialize_memory == CallerWillInitializeMemory::No)
  227. memset(ptr, MALLOC_SCRUB_BYTE, block->m_size);
  228. ue_notify_malloc(ptr, size);
  229. return ptr;
  230. }
  231. static void free_impl(void* ptr)
  232. {
  233. ScopedValueRollback rollback(errno);
  234. if (!ptr)
  235. return;
  236. g_malloc_stats.number_of_free_calls++;
  237. LibThread::Locker locker(malloc_lock());
  238. void* block_base = (void*)((FlatPtr)ptr & ChunkedBlock::ChunkedBlock::block_mask);
  239. size_t magic = *(size_t*)block_base;
  240. if (magic == MAGIC_BIGALLOC_HEADER) {
  241. auto* block = (BigAllocationBlock*)block_base;
  242. #ifdef RECYCLE_BIG_ALLOCATIONS
  243. if (auto* allocator = big_allocator_for_size(block->m_size)) {
  244. if (allocator->blocks.size() < number_of_big_blocks_to_keep_around_per_size_class) {
  245. g_malloc_stats.number_of_big_allocator_keeps++;
  246. allocator->blocks.append(block);
  247. size_t this_block_size = block->m_size;
  248. if (mprotect(block, this_block_size, PROT_NONE) < 0) {
  249. perror("mprotect");
  250. VERIFY_NOT_REACHED();
  251. }
  252. if (madvise(block, this_block_size, MADV_SET_VOLATILE) != 0) {
  253. perror("madvise");
  254. VERIFY_NOT_REACHED();
  255. }
  256. return;
  257. }
  258. }
  259. #endif
  260. g_malloc_stats.number_of_big_allocator_frees++;
  261. os_free(block, block->m_size);
  262. return;
  263. }
  264. assert(magic == MAGIC_PAGE_HEADER);
  265. auto* block = (ChunkedBlock*)block_base;
  266. dbgln_if(MALLOC_DEBUG, "LibC: freeing {:p} in allocator {:p} (size={}, used={})", ptr, block, block->bytes_per_chunk(), block->used_chunks());
  267. if (s_scrub_free)
  268. memset(ptr, FREE_SCRUB_BYTE, block->bytes_per_chunk());
  269. auto* entry = (FreelistEntry*)ptr;
  270. entry->next = block->m_freelist;
  271. block->m_freelist = entry;
  272. if (block->is_full()) {
  273. size_t good_size;
  274. auto* allocator = allocator_for_size(block->m_size, good_size);
  275. dbgln_if(MALLOC_DEBUG, "Block {:p} no longer full in size class {}", block, good_size);
  276. g_malloc_stats.number_of_freed_full_blocks++;
  277. allocator->full_blocks.remove(block);
  278. allocator->usable_blocks.prepend(block);
  279. }
  280. ++block->m_free_chunks;
  281. if (!block->used_chunks()) {
  282. size_t good_size;
  283. auto* allocator = allocator_for_size(block->m_size, good_size);
  284. if (allocator->block_count < number_of_chunked_blocks_to_keep_around_per_size_class) {
  285. dbgln_if(MALLOC_DEBUG, "Keeping block {:p} around for size class {}", block, good_size);
  286. g_malloc_stats.number_of_keeps++;
  287. allocator->usable_blocks.remove(block);
  288. allocator->empty_blocks[allocator->empty_block_count++] = block;
  289. mprotect(block, ChunkedBlock::block_size, PROT_NONE);
  290. madvise(block, ChunkedBlock::block_size, MADV_SET_VOLATILE);
  291. return;
  292. }
  293. dbgln_if(MALLOC_DEBUG, "Releasing block {:p} for size class {}", block, good_size);
  294. g_malloc_stats.number_of_frees++;
  295. allocator->usable_blocks.remove(block);
  296. --allocator->block_count;
  297. os_free(block, ChunkedBlock::block_size);
  298. }
  299. }
  300. [[gnu::flatten]] void* malloc(size_t size)
  301. {
  302. void* ptr = malloc_impl(size, CallerWillInitializeMemory::No);
  303. if (s_profiling)
  304. perf_event(PERF_EVENT_MALLOC, size, reinterpret_cast<FlatPtr>(ptr));
  305. return ptr;
  306. }
  307. [[gnu::flatten]] void free(void* ptr)
  308. {
  309. if (s_profiling)
  310. perf_event(PERF_EVENT_FREE, reinterpret_cast<FlatPtr>(ptr), 0);
  311. ue_notify_free(ptr);
  312. free_impl(ptr);
  313. }
  314. void* calloc(size_t count, size_t size)
  315. {
  316. size_t new_size = count * size;
  317. auto* ptr = malloc_impl(new_size, CallerWillInitializeMemory::Yes);
  318. if (ptr)
  319. memset(ptr, 0, new_size);
  320. return ptr;
  321. }
  322. size_t malloc_size(void* ptr)
  323. {
  324. if (!ptr)
  325. return 0;
  326. LibThread::Locker locker(malloc_lock());
  327. void* page_base = (void*)((FlatPtr)ptr & ChunkedBlock::block_mask);
  328. auto* header = (const CommonHeader*)page_base;
  329. auto size = header->m_size;
  330. if (header->m_magic == MAGIC_BIGALLOC_HEADER)
  331. size -= sizeof(CommonHeader);
  332. else
  333. VERIFY(header->m_magic == MAGIC_PAGE_HEADER);
  334. return size;
  335. }
  336. size_t malloc_good_size(size_t size)
  337. {
  338. size_t good_size;
  339. allocator_for_size(size, good_size);
  340. return good_size;
  341. }
  342. void* realloc(void* ptr, size_t size)
  343. {
  344. if (!ptr)
  345. return malloc(size);
  346. if (!size)
  347. return nullptr;
  348. LibThread::Locker locker(malloc_lock());
  349. auto existing_allocation_size = malloc_size(ptr);
  350. if (size <= existing_allocation_size) {
  351. ue_notify_realloc(ptr, size);
  352. return ptr;
  353. }
  354. auto* new_ptr = malloc(size);
  355. if (new_ptr) {
  356. memcpy(new_ptr, ptr, min(existing_allocation_size, size));
  357. free(ptr);
  358. }
  359. return new_ptr;
  360. }
  361. void __malloc_init()
  362. {
  363. new (&malloc_lock()) LibThread::Lock();
  364. s_in_userspace_emulator = (int)syscall(SC_emuctl, 0) != -ENOSYS;
  365. if (s_in_userspace_emulator) {
  366. // Don't bother scrubbing memory if we're running in UE since it
  367. // keeps track of heap memory anyway.
  368. s_scrub_malloc = false;
  369. s_scrub_free = false;
  370. }
  371. if (secure_getenv("LIBC_NOSCRUB_MALLOC"))
  372. s_scrub_malloc = false;
  373. if (secure_getenv("LIBC_NOSCRUB_FREE"))
  374. s_scrub_free = false;
  375. if (secure_getenv("LIBC_LOG_MALLOC"))
  376. s_log_malloc = true;
  377. if (secure_getenv("LIBC_PROFILE_MALLOC"))
  378. s_profiling = true;
  379. for (size_t i = 0; i < size_classes.size(); ++i) {
  380. new (&allocators()[i]) Allocator();
  381. allocators()[i].size = size_classes[i];
  382. }
  383. new (&big_allocators()[0])(BigAllocator);
  384. }
  385. void serenity_dump_malloc_stats()
  386. {
  387. dbgln("# malloc() calls: {}", g_malloc_stats.number_of_malloc_calls);
  388. dbgln();
  389. dbgln("big alloc hits: {}", g_malloc_stats.number_of_big_allocator_hits);
  390. dbgln("big alloc hits that were purged: {}", g_malloc_stats.number_of_big_allocator_purge_hits);
  391. dbgln("big allocs: {}", g_malloc_stats.number_of_big_allocs);
  392. dbgln();
  393. dbgln("empty block hits: {}", g_malloc_stats.number_of_empty_block_hits);
  394. dbgln("empty block hits that were purged: {}", g_malloc_stats.number_of_empty_block_purge_hits);
  395. dbgln("block allocs: {}", g_malloc_stats.number_of_block_allocs);
  396. dbgln("filled blocks: {}", g_malloc_stats.number_of_blocks_full);
  397. dbgln();
  398. dbgln("# free() calls: {}", g_malloc_stats.number_of_free_calls);
  399. dbgln();
  400. dbgln("big alloc keeps: {}", g_malloc_stats.number_of_big_allocator_keeps);
  401. dbgln("big alloc frees: {}", g_malloc_stats.number_of_big_allocator_frees);
  402. dbgln();
  403. dbgln("full block frees: {}", g_malloc_stats.number_of_freed_full_blocks);
  404. dbgln("number of keeps: {}", g_malloc_stats.number_of_keeps);
  405. dbgln("number of frees: {}", g_malloc_stats.number_of_frees);
  406. }
  407. }