malloc.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. #include <AK/Bitmap.h>
  2. #include <AK/InlineLinkedList.h>
  3. #include <AK/ScopedValueRollback.h>
  4. #include <AK/Vector.h>
  5. #include <LibCore/CLock.h>
  6. #include <assert.h>
  7. #include <mallocdefs.h>
  8. #include <serenity.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <sys/mman.h>
  12. // FIXME: Thread safety.
  13. //#define MALLOC_DEBUG
  14. #define RECYCLE_BIG_ALLOCATIONS
  15. #define MAGIC_PAGE_HEADER 0x42657274
  16. #define MAGIC_BIGALLOC_HEADER 0x42697267
  17. #define PAGE_ROUND_UP(x) ((((size_t)(x)) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1)))
  18. static CLock& malloc_lock()
  19. {
  20. static u32 lock_storage[sizeof(CLock) / sizeof(u32)];
  21. return *reinterpret_cast<CLock*>(&lock_storage);
  22. }
  23. static const int number_of_chunked_blocks_to_keep_around_per_size_class = 32;
  24. static const int number_of_big_blocks_to_keep_around_per_size_class = 8;
  25. static bool s_log_malloc = false;
  26. static bool s_scrub_malloc = true;
  27. static bool s_scrub_free = true;
  28. static unsigned short size_classes[] = { 8, 16, 32, 64, 128, 252, 508, 1016, 2036, 0 };
  29. static constexpr size_t num_size_classes = sizeof(size_classes) / sizeof(unsigned short);
  30. struct CommonHeader {
  31. size_t m_magic;
  32. size_t m_size;
  33. };
  34. struct BigAllocationBlock : public CommonHeader {
  35. BigAllocationBlock(size_t size)
  36. {
  37. m_magic = MAGIC_BIGALLOC_HEADER;
  38. m_size = size;
  39. }
  40. unsigned char* m_slot[0];
  41. };
  42. struct FreelistEntry {
  43. FreelistEntry* next;
  44. };
  45. struct ChunkedBlock : public CommonHeader
  46. , public InlineLinkedListNode<ChunkedBlock> {
  47. ChunkedBlock(size_t bytes_per_chunk)
  48. {
  49. m_magic = MAGIC_PAGE_HEADER;
  50. m_size = bytes_per_chunk;
  51. m_free_chunks = chunk_capacity();
  52. m_freelist = (FreelistEntry*)chunk(0);
  53. for (size_t i = 0; i < chunk_capacity(); ++i) {
  54. auto* entry = (FreelistEntry*)chunk(i);
  55. if (i != chunk_capacity() - 1)
  56. entry->next = (FreelistEntry*)chunk(i + 1);
  57. else
  58. entry->next = nullptr;
  59. }
  60. }
  61. ChunkedBlock* m_prev { nullptr };
  62. ChunkedBlock* m_next { nullptr };
  63. FreelistEntry* m_freelist { nullptr };
  64. unsigned short m_free_chunks { 0 };
  65. unsigned char m_slot[0];
  66. void* chunk(int index)
  67. {
  68. return &m_slot[index * m_size];
  69. }
  70. bool is_full() const { return m_free_chunks == 0; }
  71. size_t bytes_per_chunk() const { return m_size; }
  72. size_t free_chunks() const { return m_free_chunks; }
  73. size_t used_chunks() const { return chunk_capacity() - m_free_chunks; }
  74. size_t chunk_capacity() const { return (PAGE_SIZE - sizeof(ChunkedBlock)) / m_size; }
  75. };
  76. struct Allocator {
  77. size_t size { 0 };
  78. size_t block_count { 0 };
  79. InlineLinkedList<ChunkedBlock> usable_blocks;
  80. InlineLinkedList<ChunkedBlock> full_blocks;
  81. };
  82. struct BigAllocator {
  83. Vector<BigAllocationBlock*, number_of_big_blocks_to_keep_around_per_size_class> blocks;
  84. };
  85. static Allocator g_allocators[num_size_classes];
  86. static BigAllocator g_big_allocators[1];
  87. static Allocator* allocator_for_size(size_t size, size_t& good_size)
  88. {
  89. for (int i = 0; size_classes[i]; ++i) {
  90. if (size <= size_classes[i]) {
  91. good_size = size_classes[i];
  92. return &g_allocators[i];
  93. }
  94. }
  95. good_size = PAGE_ROUND_UP(size);
  96. return nullptr;
  97. }
  98. static BigAllocator* big_allocator_for_size(size_t size)
  99. {
  100. if (size == 4096)
  101. return &g_big_allocators[0];
  102. return nullptr;
  103. }
  104. extern "C" {
  105. size_t malloc_good_size(size_t size)
  106. {
  107. for (int i = 0; size_classes[i]; ++i) {
  108. if (size < size_classes[i])
  109. return size_classes[i];
  110. }
  111. return PAGE_ROUND_UP(size);
  112. }
  113. static void* os_alloc(size_t size, const char* name)
  114. {
  115. return mmap_with_name(nullptr, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0, name);
  116. }
  117. static void os_free(void* ptr, size_t size)
  118. {
  119. int rc = munmap(ptr, size);
  120. assert(rc == 0);
  121. }
  122. void* malloc(size_t size)
  123. {
  124. LOCKER(malloc_lock());
  125. if (s_log_malloc)
  126. dbgprintf("LibC: malloc(%u)\n", size);
  127. if (!size)
  128. return nullptr;
  129. size_t good_size;
  130. auto* allocator = allocator_for_size(size, good_size);
  131. if (!allocator) {
  132. size_t real_size = PAGE_ROUND_UP(sizeof(BigAllocationBlock) + size);
  133. #ifdef RECYCLE_BIG_ALLOCATIONS
  134. if (auto* allocator = big_allocator_for_size(real_size)) {
  135. if (!allocator->blocks.is_empty()) {
  136. auto* block = allocator->blocks.take_last();
  137. return &block->m_slot[0];
  138. }
  139. }
  140. #endif
  141. auto* block = (BigAllocationBlock*)os_alloc(real_size, "malloc: BigAllocationBlock");
  142. new (block) BigAllocationBlock(real_size);
  143. return &block->m_slot[0];
  144. }
  145. ChunkedBlock* block = nullptr;
  146. for (block = allocator->usable_blocks.head(); block; block = block->next()) {
  147. if (block->free_chunks())
  148. break;
  149. }
  150. if (!block) {
  151. char buffer[64];
  152. snprintf(buffer, sizeof(buffer), "malloc: ChunkedBlock(%zu)", good_size);
  153. block = (ChunkedBlock*)os_alloc(PAGE_SIZE, buffer);
  154. new (block) ChunkedBlock(good_size);
  155. allocator->usable_blocks.append(block);
  156. ++allocator->block_count;
  157. }
  158. --block->m_free_chunks;
  159. void* ptr = block->m_freelist;
  160. block->m_freelist = block->m_freelist->next;
  161. if (block->is_full()) {
  162. #ifdef MALLOC_DEBUG
  163. dbgprintf("Block %p is now full in size class %u\n", block, good_size);
  164. #endif
  165. allocator->usable_blocks.remove(block);
  166. allocator->full_blocks.append(block);
  167. }
  168. #ifdef MALLOC_DEBUG
  169. dbgprintf("LibC: allocated %p (chunk in block %p, size %u)\n", ptr, block, block->bytes_per_chunk());
  170. #endif
  171. if (s_scrub_malloc)
  172. memset(ptr, MALLOC_SCRUB_BYTE, block->m_size);
  173. return ptr;
  174. }
  175. void free(void* ptr)
  176. {
  177. ScopedValueRollback rollback(errno);
  178. if (!ptr)
  179. return;
  180. LOCKER(malloc_lock());
  181. void* page_base = (void*)((uintptr_t)ptr & (uintptr_t)~0xfff);
  182. size_t magic = *(size_t*)page_base;
  183. if (magic == MAGIC_BIGALLOC_HEADER) {
  184. auto* block = (BigAllocationBlock*)page_base;
  185. #ifdef RECYCLE_BIG_ALLOCATIONS
  186. if (auto* allocator = big_allocator_for_size(block->m_size)) {
  187. if (allocator->blocks.size() < number_of_big_blocks_to_keep_around_per_size_class) {
  188. allocator->blocks.append(block);
  189. return;
  190. }
  191. }
  192. #endif
  193. os_free(block, block->m_size);
  194. return;
  195. }
  196. assert(magic == MAGIC_PAGE_HEADER);
  197. auto* block = (ChunkedBlock*)page_base;
  198. #ifdef MALLOC_DEBUG
  199. dbgprintf("LibC: freeing %p in allocator %p (size=%u, used=%u)\n", ptr, block, block->bytes_per_chunk(), block->used_chunks());
  200. #endif
  201. if (s_scrub_free)
  202. memset(ptr, FREE_SCRUB_BYTE, block->bytes_per_chunk());
  203. auto* entry = (FreelistEntry*)ptr;
  204. entry->next = block->m_freelist;
  205. block->m_freelist = entry;
  206. if (block->is_full()) {
  207. size_t good_size;
  208. auto* allocator = allocator_for_size(block->m_size, good_size);
  209. #ifdef MALLOC_DEBUG
  210. dbgprintf("Block %p no longer full in size class %u\n", block, good_size);
  211. #endif
  212. allocator->full_blocks.remove(block);
  213. allocator->usable_blocks.prepend(block);
  214. }
  215. ++block->m_free_chunks;
  216. if (!block->used_chunks()) {
  217. size_t good_size;
  218. auto* allocator = allocator_for_size(block->m_size, good_size);
  219. if (allocator->block_count < number_of_chunked_blocks_to_keep_around_per_size_class) {
  220. #ifdef MALLOC_DEBUG
  221. dbgprintf("Keeping block %p around for size class %u\n", block, good_size);
  222. #endif
  223. if (allocator->usable_blocks.tail() != block) {
  224. #ifdef MALLOC_DEBUG
  225. dbgprintf("Moving block %p to tail of list for size class %u\n", block, good_size);
  226. #endif
  227. allocator->usable_blocks.remove(block);
  228. allocator->usable_blocks.append(block);
  229. }
  230. return;
  231. }
  232. #ifdef MALLOC_DEBUG
  233. dbgprintf("Releasing block %p for size class %u\n", block, good_size);
  234. #endif
  235. allocator->usable_blocks.remove(block);
  236. --allocator->block_count;
  237. os_free(block, PAGE_SIZE);
  238. }
  239. }
  240. void* calloc(size_t count, size_t size)
  241. {
  242. size_t new_size = count * size;
  243. auto* ptr = malloc(new_size);
  244. memset(ptr, 0, new_size);
  245. return ptr;
  246. }
  247. size_t malloc_size(void* ptr)
  248. {
  249. if (!ptr)
  250. return 0;
  251. LOCKER(malloc_lock());
  252. void* page_base = (void*)((uintptr_t)ptr & (uintptr_t)~0xfff);
  253. auto* header = (const CommonHeader*)page_base;
  254. auto size = header->m_size;
  255. if (header->m_magic == MAGIC_BIGALLOC_HEADER)
  256. size -= sizeof(CommonHeader);
  257. return size;
  258. }
  259. void* realloc(void* ptr, size_t size)
  260. {
  261. if (!ptr)
  262. return malloc(size);
  263. LOCKER(malloc_lock());
  264. auto existing_allocation_size = malloc_size(ptr);
  265. if (size <= existing_allocation_size)
  266. return ptr;
  267. auto* new_ptr = malloc(size);
  268. memcpy(new_ptr, ptr, min(existing_allocation_size, size));
  269. free(ptr);
  270. return new_ptr;
  271. }
  272. void __malloc_init()
  273. {
  274. new (&malloc_lock()) CLock();
  275. if (getenv("LIBC_NOSCRUB_MALLOC"))
  276. s_scrub_malloc = false;
  277. if (getenv("LIBC_NOSCRUB_FREE"))
  278. s_scrub_free = false;
  279. if (getenv("LIBC_LOG_MALLOC"))
  280. s_log_malloc = true;
  281. }
  282. }