malloc.cpp 15 KB

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