malloc.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/InlineLinkedList.h>
  27. #include <AK/LogStream.h>
  28. #include <AK/ScopedValueRollback.h>
  29. #include <AK/Vector.h>
  30. #include <LibThread/Lock.h>
  31. #include <assert.h>
  32. #include <mallocdefs.h>
  33. #include <serenity.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <sys/internals.h>
  38. #include <sys/mman.h>
  39. // FIXME: Thread safety.
  40. //#define MALLOC_DEBUG
  41. #define RECYCLE_BIG_ALLOCATIONS
  42. #define PAGE_ROUND_UP(x) ((((size_t)(x)) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1)))
  43. ALWAYS_INLINE static void ue_notify_malloc(const void* ptr, size_t size)
  44. {
  45. send_secret_data_to_userspace_emulator(1, size, (FlatPtr)ptr);
  46. }
  47. ALWAYS_INLINE static void ue_notify_free(const void* ptr)
  48. {
  49. send_secret_data_to_userspace_emulator(2, (FlatPtr)ptr, 0);
  50. }
  51. ALWAYS_INLINE static void ue_notify_realloc(const void* ptr, size_t size)
  52. {
  53. send_secret_data_to_userspace_emulator(3, size, (FlatPtr)ptr);
  54. }
  55. static LibThread::Lock& malloc_lock()
  56. {
  57. static u32 lock_storage[sizeof(LibThread::Lock) / sizeof(u32)];
  58. return *reinterpret_cast<LibThread::Lock*>(&lock_storage);
  59. }
  60. constexpr size_t number_of_chunked_blocks_to_keep_around_per_size_class = 4;
  61. constexpr size_t number_of_big_blocks_to_keep_around_per_size_class = 8;
  62. static bool s_log_malloc = false;
  63. static bool s_scrub_malloc = true;
  64. static bool s_scrub_free = true;
  65. static bool s_profiling = false;
  66. struct MallocStats {
  67. size_t number_of_malloc_calls;
  68. size_t number_of_big_allocator_hits;
  69. size_t number_of_big_allocator_purge_hits;
  70. size_t number_of_big_allocs;
  71. size_t number_of_empty_block_hits;
  72. size_t number_of_empty_block_purge_hits;
  73. size_t number_of_block_allocs;
  74. size_t number_of_blocks_full;
  75. size_t number_of_free_calls;
  76. size_t number_of_big_allocator_keeps;
  77. size_t number_of_big_allocator_frees;
  78. size_t number_of_freed_full_blocks;
  79. size_t number_of_keeps;
  80. size_t number_of_frees;
  81. };
  82. static MallocStats g_malloc_stats = {};
  83. struct Allocator {
  84. size_t size { 0 };
  85. size_t block_count { 0 };
  86. size_t empty_block_count { 0 };
  87. ChunkedBlock* empty_blocks[number_of_chunked_blocks_to_keep_around_per_size_class] { nullptr };
  88. InlineLinkedList<ChunkedBlock> usable_blocks;
  89. InlineLinkedList<ChunkedBlock> full_blocks;
  90. };
  91. struct BigAllocator {
  92. Vector<BigAllocationBlock*, number_of_big_blocks_to_keep_around_per_size_class> blocks;
  93. };
  94. // Allocators will be initialized in __malloc_init.
  95. // We can not rely on global constructors to initialize them,
  96. // because they must be initialized before other global constructors
  97. // are run. Similarly, we can not allow global destructors to destruct
  98. // them. We could have used AK::NeverDestoyed to prevent the latter,
  99. // but it would have not helped with the former.
  100. static u8 g_allocators_storage[sizeof(Allocator) * num_size_classes];
  101. static u8 g_big_allocators_storage[sizeof(BigAllocator)];
  102. static inline Allocator (&allocators())[num_size_classes]
  103. {
  104. return reinterpret_cast<Allocator(&)[num_size_classes]>(g_allocators_storage);
  105. }
  106. static inline BigAllocator (&big_allocators())[1]
  107. {
  108. return reinterpret_cast<BigAllocator(&)[1]>(g_big_allocators_storage);
  109. }
  110. static Allocator* allocator_for_size(size_t size, size_t& good_size)
  111. {
  112. for (size_t i = 0; size_classes[i]; ++i) {
  113. if (size <= size_classes[i]) {
  114. good_size = size_classes[i];
  115. return &allocators()[i];
  116. }
  117. }
  118. good_size = PAGE_ROUND_UP(size);
  119. return nullptr;
  120. }
  121. #ifdef RECYCLE_BIG_ALLOCATIONS
  122. static BigAllocator* big_allocator_for_size(size_t size)
  123. {
  124. if (size == 65536)
  125. return &big_allocators()[0];
  126. return nullptr;
  127. }
  128. #endif
  129. extern "C" {
  130. static void* os_alloc(size_t size, const char* name)
  131. {
  132. auto* ptr = serenity_mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0, ChunkedBlock::block_size, name);
  133. ASSERT(ptr != MAP_FAILED);
  134. return ptr;
  135. }
  136. static void os_free(void* ptr, size_t size)
  137. {
  138. int rc = munmap(ptr, size);
  139. assert(rc == 0);
  140. }
  141. static void* malloc_impl(size_t size)
  142. {
  143. LOCKER(malloc_lock());
  144. if (s_log_malloc)
  145. dbgprintf("LibC: malloc(%zu)\n", size);
  146. if (!size)
  147. return nullptr;
  148. g_malloc_stats.number_of_malloc_calls++;
  149. size_t good_size;
  150. auto* allocator = allocator_for_size(size, good_size);
  151. if (!allocator) {
  152. size_t real_size = round_up_to_power_of_two(sizeof(BigAllocationBlock) + size, ChunkedBlock::block_size);
  153. #ifdef RECYCLE_BIG_ALLOCATIONS
  154. if (auto* allocator = big_allocator_for_size(real_size)) {
  155. if (!allocator->blocks.is_empty()) {
  156. g_malloc_stats.number_of_big_allocator_hits++;
  157. auto* block = allocator->blocks.take_last();
  158. int rc = madvise(block, real_size, MADV_SET_NONVOLATILE);
  159. bool this_block_was_purged = rc == 1;
  160. if (rc < 0) {
  161. perror("madvise");
  162. ASSERT_NOT_REACHED();
  163. }
  164. if (mprotect(block, real_size, PROT_READ | PROT_WRITE) < 0) {
  165. perror("mprotect");
  166. ASSERT_NOT_REACHED();
  167. }
  168. if (this_block_was_purged) {
  169. g_malloc_stats.number_of_big_allocator_purge_hits++;
  170. new (block) BigAllocationBlock(real_size);
  171. }
  172. ue_notify_malloc(&block->m_slot[0], size);
  173. return &block->m_slot[0];
  174. }
  175. }
  176. #endif
  177. g_malloc_stats.number_of_big_allocs++;
  178. auto* block = (BigAllocationBlock*)os_alloc(real_size, "malloc: BigAllocationBlock");
  179. new (block) BigAllocationBlock(real_size);
  180. ue_notify_malloc(&block->m_slot[0], size);
  181. return &block->m_slot[0];
  182. }
  183. ChunkedBlock* block = nullptr;
  184. for (block = allocator->usable_blocks.head(); block; block = block->next()) {
  185. if (block->free_chunks())
  186. break;
  187. }
  188. if (!block && allocator->empty_block_count) {
  189. g_malloc_stats.number_of_empty_block_hits++;
  190. block = allocator->empty_blocks[--allocator->empty_block_count];
  191. int rc = madvise(block, ChunkedBlock::block_size, MADV_SET_NONVOLATILE);
  192. bool this_block_was_purged = rc == 1;
  193. if (rc < 0) {
  194. perror("madvise");
  195. ASSERT_NOT_REACHED();
  196. }
  197. rc = mprotect(block, ChunkedBlock::block_size, PROT_READ | PROT_WRITE);
  198. if (rc < 0) {
  199. perror("mprotect");
  200. ASSERT_NOT_REACHED();
  201. }
  202. if (this_block_was_purged) {
  203. g_malloc_stats.number_of_empty_block_purge_hits++;
  204. new (block) ChunkedBlock(good_size);
  205. }
  206. allocator->usable_blocks.append(block);
  207. }
  208. if (!block) {
  209. g_malloc_stats.number_of_block_allocs++;
  210. char buffer[64];
  211. snprintf(buffer, sizeof(buffer), "malloc: ChunkedBlock(%zu)", good_size);
  212. block = (ChunkedBlock*)os_alloc(ChunkedBlock::block_size, buffer);
  213. new (block) ChunkedBlock(good_size);
  214. allocator->usable_blocks.append(block);
  215. ++allocator->block_count;
  216. }
  217. --block->m_free_chunks;
  218. void* ptr = block->m_freelist;
  219. ASSERT(ptr);
  220. block->m_freelist = block->m_freelist->next;
  221. if (block->is_full()) {
  222. g_malloc_stats.number_of_blocks_full++;
  223. #ifdef MALLOC_DEBUG
  224. dbgprintf("Block %p is now full in size class %zu\n", block, good_size);
  225. #endif
  226. allocator->usable_blocks.remove(block);
  227. allocator->full_blocks.append(block);
  228. }
  229. #ifdef MALLOC_DEBUG
  230. dbgprintf("LibC: allocated %p (chunk in block %p, size %zu)\n", ptr, block, block->bytes_per_chunk());
  231. #endif
  232. if (s_scrub_malloc)
  233. memset(ptr, MALLOC_SCRUB_BYTE, block->m_size);
  234. ue_notify_malloc(ptr, size);
  235. return ptr;
  236. }
  237. static void free_impl(void* ptr)
  238. {
  239. ScopedValueRollback rollback(errno);
  240. if (!ptr)
  241. return;
  242. g_malloc_stats.number_of_free_calls++;
  243. LOCKER(malloc_lock());
  244. void* block_base = (void*)((FlatPtr)ptr & ChunkedBlock::ChunkedBlock::block_mask);
  245. size_t magic = *(size_t*)block_base;
  246. if (magic == MAGIC_BIGALLOC_HEADER) {
  247. auto* block = (BigAllocationBlock*)block_base;
  248. #ifdef RECYCLE_BIG_ALLOCATIONS
  249. if (auto* allocator = big_allocator_for_size(block->m_size)) {
  250. if (allocator->blocks.size() < number_of_big_blocks_to_keep_around_per_size_class) {
  251. g_malloc_stats.number_of_big_allocator_keeps++;
  252. allocator->blocks.append(block);
  253. size_t this_block_size = block->m_size;
  254. if (mprotect(block, this_block_size, PROT_NONE) < 0) {
  255. perror("mprotect");
  256. ASSERT_NOT_REACHED();
  257. }
  258. if (madvise(block, this_block_size, MADV_SET_VOLATILE) != 0) {
  259. perror("madvise");
  260. ASSERT_NOT_REACHED();
  261. }
  262. return;
  263. }
  264. }
  265. #endif
  266. g_malloc_stats.number_of_big_allocator_frees++;
  267. os_free(block, block->m_size);
  268. return;
  269. }
  270. assert(magic == MAGIC_PAGE_HEADER);
  271. auto* block = (ChunkedBlock*)block_base;
  272. #ifdef MALLOC_DEBUG
  273. dbgprintf("LibC: freeing %p in allocator %p (size=%zu, used=%zu)\n", ptr, block, block->bytes_per_chunk(), block->used_chunks());
  274. #endif
  275. if (s_scrub_free)
  276. memset(ptr, FREE_SCRUB_BYTE, block->bytes_per_chunk());
  277. auto* entry = (FreelistEntry*)ptr;
  278. entry->next = block->m_freelist;
  279. block->m_freelist = entry;
  280. if (block->is_full()) {
  281. size_t good_size;
  282. auto* allocator = allocator_for_size(block->m_size, good_size);
  283. #ifdef MALLOC_DEBUG
  284. dbgprintf("Block %p no longer full in size class %zu\n", block, good_size);
  285. #endif
  286. g_malloc_stats.number_of_freed_full_blocks++;
  287. allocator->full_blocks.remove(block);
  288. allocator->usable_blocks.prepend(block);
  289. }
  290. ++block->m_free_chunks;
  291. if (!block->used_chunks()) {
  292. size_t good_size;
  293. auto* allocator = allocator_for_size(block->m_size, good_size);
  294. if (allocator->block_count < number_of_chunked_blocks_to_keep_around_per_size_class) {
  295. #ifdef MALLOC_DEBUG
  296. dbgprintf("Keeping block %p around for size class %zu\n", block, good_size);
  297. #endif
  298. g_malloc_stats.number_of_keeps++;
  299. allocator->usable_blocks.remove(block);
  300. allocator->empty_blocks[allocator->empty_block_count++] = block;
  301. mprotect(block, ChunkedBlock::block_size, PROT_NONE);
  302. madvise(block, ChunkedBlock::block_size, MADV_SET_VOLATILE);
  303. return;
  304. }
  305. #ifdef MALLOC_DEBUG
  306. dbgprintf("Releasing block %p for size class %zu\n", block, good_size);
  307. #endif
  308. g_malloc_stats.number_of_frees++;
  309. allocator->usable_blocks.remove(block);
  310. --allocator->block_count;
  311. os_free(block, ChunkedBlock::block_size);
  312. }
  313. }
  314. [[gnu::flatten]] void* malloc(size_t size)
  315. {
  316. void* ptr = malloc_impl(size);
  317. if (s_profiling)
  318. perf_event(PERF_EVENT_MALLOC, size, reinterpret_cast<FlatPtr>(ptr));
  319. return ptr;
  320. }
  321. [[gnu::flatten]] void free(void* ptr)
  322. {
  323. if (s_profiling)
  324. perf_event(PERF_EVENT_FREE, reinterpret_cast<FlatPtr>(ptr), 0);
  325. ue_notify_free(ptr);
  326. free_impl(ptr);
  327. }
  328. void* calloc(size_t count, size_t size)
  329. {
  330. size_t new_size = count * size;
  331. auto* ptr = malloc(new_size);
  332. if (ptr)
  333. memset(ptr, 0, new_size);
  334. return ptr;
  335. }
  336. size_t malloc_size(void* ptr)
  337. {
  338. if (!ptr)
  339. return 0;
  340. LOCKER(malloc_lock());
  341. void* page_base = (void*)((FlatPtr)ptr & ChunkedBlock::block_mask);
  342. auto* header = (const CommonHeader*)page_base;
  343. auto size = header->m_size;
  344. if (header->m_magic == MAGIC_BIGALLOC_HEADER)
  345. size -= sizeof(CommonHeader);
  346. else
  347. ASSERT(header->m_magic == MAGIC_PAGE_HEADER);
  348. return size;
  349. }
  350. void* realloc(void* ptr, size_t size)
  351. {
  352. if (!ptr)
  353. return malloc(size);
  354. if (!size)
  355. return nullptr;
  356. LOCKER(malloc_lock());
  357. auto existing_allocation_size = malloc_size(ptr);
  358. if (size <= existing_allocation_size) {
  359. ue_notify_realloc(ptr, size);
  360. return ptr;
  361. }
  362. auto* new_ptr = malloc(size);
  363. if (new_ptr) {
  364. memcpy(new_ptr, ptr, min(existing_allocation_size, size));
  365. free(ptr);
  366. }
  367. return new_ptr;
  368. }
  369. void __malloc_init()
  370. {
  371. new (&malloc_lock()) LibThread::Lock();
  372. if (getenv("LIBC_NOSCRUB_MALLOC"))
  373. s_scrub_malloc = false;
  374. if (getenv("LIBC_NOSCRUB_FREE"))
  375. s_scrub_free = false;
  376. if (getenv("LIBC_LOG_MALLOC"))
  377. s_log_malloc = true;
  378. if (getenv("LIBC_PROFILE_MALLOC"))
  379. s_profiling = true;
  380. for (size_t i = 0; i < num_size_classes; ++i) {
  381. new (&allocators()[i]) Allocator();
  382. allocators()[i].size = size_classes[i];
  383. }
  384. new (&big_allocators()[0])(BigAllocator);
  385. }
  386. void serenity_dump_malloc_stats()
  387. {
  388. dbgln("# malloc() calls: {}", g_malloc_stats.number_of_malloc_calls);
  389. dbgln();
  390. dbgln("big alloc hits: {}", g_malloc_stats.number_of_big_allocator_hits);
  391. dbgln("big alloc hits that were purged: {}", g_malloc_stats.number_of_big_allocator_purge_hits);
  392. dbgln("big allocs: {}", g_malloc_stats.number_of_big_allocs);
  393. dbgln();
  394. dbgln("empty block hits: {}", g_malloc_stats.number_of_empty_block_hits);
  395. dbgln("empty block hits that were purged: {}", g_malloc_stats.number_of_empty_block_purge_hits);
  396. dbgln("block allocs: {}", g_malloc_stats.number_of_block_allocs);
  397. dbgln("filled blocks: {}", g_malloc_stats.number_of_blocks_full);
  398. dbgln();
  399. dbgln("# free() calls: {}", g_malloc_stats.number_of_free_calls);
  400. dbgln();
  401. dbgln("big alloc keeps: {}", g_malloc_stats.number_of_big_allocator_keeps);
  402. dbgln("big alloc frees: {}", g_malloc_stats.number_of_big_allocator_frees);
  403. dbgln();
  404. dbgln("full block frees: {}", g_malloc_stats.number_of_freed_full_blocks);
  405. dbgln("number of keeps: {}", g_malloc_stats.number_of_keeps);
  406. dbgln("number of frees: {}", g_malloc_stats.number_of_frees);
  407. }
  408. }