malloc.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. return nullptr;
  137. g_malloc_stats.number_of_malloc_calls++;
  138. size_t good_size;
  139. auto* allocator = allocator_for_size(size, good_size);
  140. if (!allocator) {
  141. size_t real_size = round_up_to_power_of_two(sizeof(BigAllocationBlock) + size, ChunkedBlock::block_size);
  142. #ifdef RECYCLE_BIG_ALLOCATIONS
  143. if (auto* allocator = big_allocator_for_size(real_size)) {
  144. if (!allocator->blocks.is_empty()) {
  145. g_malloc_stats.number_of_big_allocator_hits++;
  146. auto* block = allocator->blocks.take_last();
  147. int rc = madvise(block, real_size, MADV_SET_NONVOLATILE);
  148. bool this_block_was_purged = rc == 1;
  149. if (rc < 0) {
  150. perror("madvise");
  151. VERIFY_NOT_REACHED();
  152. }
  153. if (mprotect(block, real_size, PROT_READ | PROT_WRITE) < 0) {
  154. perror("mprotect");
  155. VERIFY_NOT_REACHED();
  156. }
  157. if (this_block_was_purged) {
  158. g_malloc_stats.number_of_big_allocator_purge_hits++;
  159. new (block) BigAllocationBlock(real_size);
  160. }
  161. ue_notify_malloc(&block->m_slot[0], size);
  162. return &block->m_slot[0];
  163. }
  164. }
  165. #endif
  166. g_malloc_stats.number_of_big_allocs++;
  167. auto* block = (BigAllocationBlock*)os_alloc(real_size, "malloc: BigAllocationBlock");
  168. new (block) BigAllocationBlock(real_size);
  169. ue_notify_malloc(&block->m_slot[0], size);
  170. return &block->m_slot[0];
  171. }
  172. ChunkedBlock* block = nullptr;
  173. for (block = allocator->usable_blocks.head(); block; block = block->next()) {
  174. if (block->free_chunks())
  175. break;
  176. }
  177. if (!block && allocator->empty_block_count) {
  178. g_malloc_stats.number_of_empty_block_hits++;
  179. block = allocator->empty_blocks[--allocator->empty_block_count];
  180. int rc = madvise(block, ChunkedBlock::block_size, MADV_SET_NONVOLATILE);
  181. bool this_block_was_purged = rc == 1;
  182. if (rc < 0) {
  183. perror("madvise");
  184. VERIFY_NOT_REACHED();
  185. }
  186. rc = mprotect(block, ChunkedBlock::block_size, PROT_READ | PROT_WRITE);
  187. if (rc < 0) {
  188. perror("mprotect");
  189. VERIFY_NOT_REACHED();
  190. }
  191. if (this_block_was_purged) {
  192. g_malloc_stats.number_of_empty_block_purge_hits++;
  193. new (block) ChunkedBlock(good_size);
  194. }
  195. allocator->usable_blocks.append(block);
  196. }
  197. if (!block) {
  198. g_malloc_stats.number_of_block_allocs++;
  199. char buffer[64];
  200. snprintf(buffer, sizeof(buffer), "malloc: ChunkedBlock(%zu)", good_size);
  201. block = (ChunkedBlock*)os_alloc(ChunkedBlock::block_size, buffer);
  202. new (block) ChunkedBlock(good_size);
  203. allocator->usable_blocks.append(block);
  204. ++allocator->block_count;
  205. }
  206. --block->m_free_chunks;
  207. void* ptr = block->m_freelist;
  208. VERIFY(ptr);
  209. block->m_freelist = block->m_freelist->next;
  210. if (block->is_full()) {
  211. g_malloc_stats.number_of_blocks_full++;
  212. dbgln_if(MALLOC_DEBUG, "Block {:p} is now full in size class {}", block, good_size);
  213. allocator->usable_blocks.remove(block);
  214. allocator->full_blocks.append(block);
  215. }
  216. dbgln_if(MALLOC_DEBUG, "LibC: allocated {:p} (chunk in block {:p}, size {})", ptr, block, block->bytes_per_chunk());
  217. if (s_scrub_malloc && caller_will_initialize_memory == CallerWillInitializeMemory::No)
  218. memset(ptr, MALLOC_SCRUB_BYTE, block->m_size);
  219. ue_notify_malloc(ptr, size);
  220. return ptr;
  221. }
  222. static void free_impl(void* ptr)
  223. {
  224. ScopedValueRollback rollback(errno);
  225. if (!ptr)
  226. return;
  227. g_malloc_stats.number_of_free_calls++;
  228. LOCKER(malloc_lock());
  229. void* block_base = (void*)((FlatPtr)ptr & ChunkedBlock::ChunkedBlock::block_mask);
  230. size_t magic = *(size_t*)block_base;
  231. if (magic == MAGIC_BIGALLOC_HEADER) {
  232. auto* block = (BigAllocationBlock*)block_base;
  233. #ifdef RECYCLE_BIG_ALLOCATIONS
  234. if (auto* allocator = big_allocator_for_size(block->m_size)) {
  235. if (allocator->blocks.size() < number_of_big_blocks_to_keep_around_per_size_class) {
  236. g_malloc_stats.number_of_big_allocator_keeps++;
  237. allocator->blocks.append(block);
  238. size_t this_block_size = block->m_size;
  239. if (mprotect(block, this_block_size, PROT_NONE) < 0) {
  240. perror("mprotect");
  241. VERIFY_NOT_REACHED();
  242. }
  243. if (madvise(block, this_block_size, MADV_SET_VOLATILE) != 0) {
  244. perror("madvise");
  245. VERIFY_NOT_REACHED();
  246. }
  247. return;
  248. }
  249. }
  250. #endif
  251. g_malloc_stats.number_of_big_allocator_frees++;
  252. os_free(block, block->m_size);
  253. return;
  254. }
  255. assert(magic == MAGIC_PAGE_HEADER);
  256. auto* block = (ChunkedBlock*)block_base;
  257. dbgln_if(MALLOC_DEBUG, "LibC: freeing {:p} in allocator {:p} (size={}, used={})", ptr, block, block->bytes_per_chunk(), block->used_chunks());
  258. if (s_scrub_free)
  259. memset(ptr, FREE_SCRUB_BYTE, block->bytes_per_chunk());
  260. auto* entry = (FreelistEntry*)ptr;
  261. entry->next = block->m_freelist;
  262. block->m_freelist = entry;
  263. if (block->is_full()) {
  264. size_t good_size;
  265. auto* allocator = allocator_for_size(block->m_size, good_size);
  266. dbgln_if(MALLOC_DEBUG, "Block {:p} no longer full in size class {}", block, good_size);
  267. g_malloc_stats.number_of_freed_full_blocks++;
  268. allocator->full_blocks.remove(block);
  269. allocator->usable_blocks.prepend(block);
  270. }
  271. ++block->m_free_chunks;
  272. if (!block->used_chunks()) {
  273. size_t good_size;
  274. auto* allocator = allocator_for_size(block->m_size, good_size);
  275. if (allocator->block_count < number_of_chunked_blocks_to_keep_around_per_size_class) {
  276. dbgln_if(MALLOC_DEBUG, "Keeping block {:p} around for size class {}", block, good_size);
  277. g_malloc_stats.number_of_keeps++;
  278. allocator->usable_blocks.remove(block);
  279. allocator->empty_blocks[allocator->empty_block_count++] = block;
  280. mprotect(block, ChunkedBlock::block_size, PROT_NONE);
  281. madvise(block, ChunkedBlock::block_size, MADV_SET_VOLATILE);
  282. return;
  283. }
  284. dbgln_if(MALLOC_DEBUG, "Releasing block {:p} for size class {}", block, good_size);
  285. g_malloc_stats.number_of_frees++;
  286. allocator->usable_blocks.remove(block);
  287. --allocator->block_count;
  288. os_free(block, ChunkedBlock::block_size);
  289. }
  290. }
  291. [[gnu::flatten]] void* malloc(size_t size)
  292. {
  293. void* ptr = malloc_impl(size, CallerWillInitializeMemory::No);
  294. if (s_profiling)
  295. perf_event(PERF_EVENT_MALLOC, size, reinterpret_cast<FlatPtr>(ptr));
  296. return ptr;
  297. }
  298. [[gnu::flatten]] void free(void* ptr)
  299. {
  300. if (s_profiling)
  301. perf_event(PERF_EVENT_FREE, reinterpret_cast<FlatPtr>(ptr), 0);
  302. ue_notify_free(ptr);
  303. free_impl(ptr);
  304. }
  305. void* calloc(size_t count, size_t size)
  306. {
  307. size_t new_size = count * size;
  308. auto* ptr = malloc_impl(new_size, CallerWillInitializeMemory::Yes);
  309. if (ptr)
  310. memset(ptr, 0, new_size);
  311. return ptr;
  312. }
  313. size_t malloc_size(void* ptr)
  314. {
  315. if (!ptr)
  316. return 0;
  317. LOCKER(malloc_lock());
  318. void* page_base = (void*)((FlatPtr)ptr & ChunkedBlock::block_mask);
  319. auto* header = (const CommonHeader*)page_base;
  320. auto size = header->m_size;
  321. if (header->m_magic == MAGIC_BIGALLOC_HEADER)
  322. size -= sizeof(CommonHeader);
  323. else
  324. VERIFY(header->m_magic == MAGIC_PAGE_HEADER);
  325. return size;
  326. }
  327. void* realloc(void* ptr, size_t size)
  328. {
  329. if (!ptr)
  330. return malloc(size);
  331. if (!size)
  332. return nullptr;
  333. LOCKER(malloc_lock());
  334. auto existing_allocation_size = malloc_size(ptr);
  335. if (size <= existing_allocation_size) {
  336. ue_notify_realloc(ptr, size);
  337. return ptr;
  338. }
  339. auto* new_ptr = malloc(size);
  340. if (new_ptr) {
  341. memcpy(new_ptr, ptr, min(existing_allocation_size, size));
  342. free(ptr);
  343. }
  344. return new_ptr;
  345. }
  346. void __malloc_init()
  347. {
  348. new (&malloc_lock()) LibThread::Lock();
  349. s_in_userspace_emulator = (int)syscall(SC_emuctl, 0) != -ENOSYS;
  350. if (s_in_userspace_emulator) {
  351. // Don't bother scrubbing memory if we're running in UE since it
  352. // keeps track of heap memory anyway.
  353. s_scrub_malloc = false;
  354. s_scrub_free = false;
  355. }
  356. if (secure_getenv("LIBC_NOSCRUB_MALLOC"))
  357. s_scrub_malloc = false;
  358. if (secure_getenv("LIBC_NOSCRUB_FREE"))
  359. s_scrub_free = false;
  360. if (secure_getenv("LIBC_LOG_MALLOC"))
  361. s_log_malloc = true;
  362. if (secure_getenv("LIBC_PROFILE_MALLOC"))
  363. s_profiling = true;
  364. for (size_t i = 0; i < num_size_classes; ++i) {
  365. new (&allocators()[i]) Allocator();
  366. allocators()[i].size = size_classes[i];
  367. }
  368. new (&big_allocators()[0])(BigAllocator);
  369. }
  370. void serenity_dump_malloc_stats()
  371. {
  372. dbgln("# malloc() calls: {}", g_malloc_stats.number_of_malloc_calls);
  373. dbgln();
  374. dbgln("big alloc hits: {}", g_malloc_stats.number_of_big_allocator_hits);
  375. dbgln("big alloc hits that were purged: {}", g_malloc_stats.number_of_big_allocator_purge_hits);
  376. dbgln("big allocs: {}", g_malloc_stats.number_of_big_allocs);
  377. dbgln();
  378. dbgln("empty block hits: {}", g_malloc_stats.number_of_empty_block_hits);
  379. dbgln("empty block hits that were purged: {}", g_malloc_stats.number_of_empty_block_purge_hits);
  380. dbgln("block allocs: {}", g_malloc_stats.number_of_block_allocs);
  381. dbgln("filled blocks: {}", g_malloc_stats.number_of_blocks_full);
  382. dbgln();
  383. dbgln("# free() calls: {}", g_malloc_stats.number_of_free_calls);
  384. dbgln();
  385. dbgln("big alloc keeps: {}", g_malloc_stats.number_of_big_allocator_keeps);
  386. dbgln("big alloc frees: {}", g_malloc_stats.number_of_big_allocator_frees);
  387. dbgln();
  388. dbgln("full block frees: {}", g_malloc_stats.number_of_freed_full_blocks);
  389. dbgln("number of keeps: {}", g_malloc_stats.number_of_keeps);
  390. dbgln("number of frees: {}", g_malloc_stats.number_of_frees);
  391. }
  392. }