malloc.cpp 14 KB

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