malloc.cpp 14 KB

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