Heap.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Badge.h>
  7. #include <AK/Debug.h>
  8. #include <AK/HashTable.h>
  9. #include <AK/StackInfo.h>
  10. #include <AK/TemporaryChange.h>
  11. #include <LibCore/ElapsedTimer.h>
  12. #include <LibJS/Heap/CellAllocator.h>
  13. #include <LibJS/Heap/Handle.h>
  14. #include <LibJS/Heap/Heap.h>
  15. #include <LibJS/Heap/HeapBlock.h>
  16. #include <LibJS/Interpreter.h>
  17. #include <LibJS/Runtime/Object.h>
  18. #include <LibJS/Runtime/WeakContainer.h>
  19. #include <setjmp.h>
  20. #ifdef __serenity__
  21. # include <serenity.h>
  22. #endif
  23. namespace JS {
  24. #ifdef __serenity__
  25. static int gc_perf_string_id;
  26. #endif
  27. Heap::Heap(VM& vm)
  28. : m_vm(vm)
  29. {
  30. #ifdef __serenity__
  31. auto gc_signpost_string = "Garbage collection"sv;
  32. gc_perf_string_id = perf_register_string(gc_signpost_string.characters_without_null_termination(), gc_signpost_string.length());
  33. #endif
  34. if constexpr (HeapBlock::min_possible_cell_size <= 16) {
  35. m_allocators.append(make<CellAllocator>(16));
  36. }
  37. static_assert(HeapBlock::min_possible_cell_size <= 24, "Heap Cell tracking uses too much data!");
  38. m_allocators.append(make<CellAllocator>(32));
  39. m_allocators.append(make<CellAllocator>(64));
  40. m_allocators.append(make<CellAllocator>(96));
  41. m_allocators.append(make<CellAllocator>(128));
  42. m_allocators.append(make<CellAllocator>(256));
  43. m_allocators.append(make<CellAllocator>(512));
  44. m_allocators.append(make<CellAllocator>(1024));
  45. m_allocators.append(make<CellAllocator>(3072));
  46. }
  47. Heap::~Heap()
  48. {
  49. vm().string_cache().clear();
  50. collect_garbage(CollectionType::CollectEverything);
  51. }
  52. ALWAYS_INLINE CellAllocator& Heap::allocator_for_size(size_t cell_size)
  53. {
  54. for (auto& allocator : m_allocators) {
  55. if (allocator->cell_size() >= cell_size)
  56. return *allocator;
  57. }
  58. dbgln("Cannot get CellAllocator for cell size {}, largest available is {}!", cell_size, m_allocators.last()->cell_size());
  59. VERIFY_NOT_REACHED();
  60. }
  61. Cell* Heap::allocate_cell(size_t size)
  62. {
  63. if (should_collect_on_every_allocation()) {
  64. collect_garbage();
  65. } else if (m_allocations_since_last_gc > m_max_allocations_between_gc) {
  66. m_allocations_since_last_gc = 0;
  67. collect_garbage();
  68. } else {
  69. ++m_allocations_since_last_gc;
  70. }
  71. auto& allocator = allocator_for_size(size);
  72. return allocator.allocate_cell(*this);
  73. }
  74. void Heap::collect_garbage(CollectionType collection_type, bool print_report)
  75. {
  76. VERIFY(!m_collecting_garbage);
  77. TemporaryChange change(m_collecting_garbage, true);
  78. #ifdef __serenity__
  79. static size_t global_gc_counter = 0;
  80. perf_event(PERF_EVENT_SIGNPOST, gc_perf_string_id, global_gc_counter++);
  81. #endif
  82. auto collection_measurement_timer = Core::ElapsedTimer::start_new();
  83. if (collection_type == CollectionType::CollectGarbage) {
  84. if (m_gc_deferrals) {
  85. m_should_gc_when_deferral_ends = true;
  86. return;
  87. }
  88. HashTable<Cell*> roots;
  89. gather_roots(roots);
  90. mark_live_cells(roots);
  91. }
  92. sweep_dead_cells(print_report, collection_measurement_timer);
  93. }
  94. void Heap::gather_roots(HashTable<Cell*>& roots)
  95. {
  96. vm().gather_roots(roots);
  97. gather_conservative_roots(roots);
  98. for (auto& handle : m_handles)
  99. roots.set(handle.cell());
  100. for (auto& vector : m_marked_vectors)
  101. vector.gather_roots(roots);
  102. if constexpr (HEAP_DEBUG) {
  103. dbgln("gather_roots:");
  104. for (auto* root : roots)
  105. dbgln(" + {}", root);
  106. }
  107. }
  108. __attribute__((no_sanitize("address"))) void Heap::gather_conservative_roots(HashTable<Cell*>& roots)
  109. {
  110. FlatPtr dummy;
  111. dbgln_if(HEAP_DEBUG, "gather_conservative_roots:");
  112. jmp_buf buf;
  113. setjmp(buf);
  114. HashTable<FlatPtr> possible_pointers;
  115. auto* raw_jmp_buf = reinterpret_cast<FlatPtr const*>(buf);
  116. for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); i += sizeof(FlatPtr))
  117. possible_pointers.set(raw_jmp_buf[i]);
  118. auto stack_reference = bit_cast<FlatPtr>(&dummy);
  119. auto& stack_info = m_vm.stack_info();
  120. for (FlatPtr stack_address = stack_reference; stack_address < stack_info.top(); stack_address += sizeof(FlatPtr)) {
  121. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  122. possible_pointers.set(data);
  123. }
  124. HashTable<HeapBlock*> all_live_heap_blocks;
  125. for_each_block([&](auto& block) {
  126. all_live_heap_blocks.set(&block);
  127. return IterationDecision::Continue;
  128. });
  129. for (auto possible_pointer : possible_pointers) {
  130. if (!possible_pointer)
  131. continue;
  132. dbgln_if(HEAP_DEBUG, " ? {}", (void const*)possible_pointer);
  133. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<Cell const*>(possible_pointer));
  134. if (all_live_heap_blocks.contains(possible_heap_block)) {
  135. if (auto* cell = possible_heap_block->cell_from_possible_pointer(possible_pointer)) {
  136. if (cell->state() == Cell::State::Live) {
  137. dbgln_if(HEAP_DEBUG, " ?-> {}", (void const*)cell);
  138. roots.set(cell);
  139. } else {
  140. dbgln_if(HEAP_DEBUG, " #-> {}", (void const*)cell);
  141. }
  142. }
  143. }
  144. }
  145. }
  146. class MarkingVisitor final : public Cell::Visitor {
  147. public:
  148. MarkingVisitor() = default;
  149. virtual void visit_impl(Cell& cell) override
  150. {
  151. if (cell.is_marked())
  152. return;
  153. dbgln_if(HEAP_DEBUG, " ! {}", &cell);
  154. cell.set_marked(true);
  155. cell.visit_edges(*this);
  156. }
  157. };
  158. void Heap::mark_live_cells(HashTable<Cell*> const& roots)
  159. {
  160. dbgln_if(HEAP_DEBUG, "mark_live_cells:");
  161. MarkingVisitor visitor;
  162. for (auto* root : roots)
  163. visitor.visit(root);
  164. for (auto& inverse_root : m_uprooted_cells)
  165. inverse_root->set_marked(false);
  166. m_uprooted_cells.clear();
  167. }
  168. void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measurement_timer)
  169. {
  170. dbgln_if(HEAP_DEBUG, "sweep_dead_cells:");
  171. Vector<HeapBlock*, 32> empty_blocks;
  172. Vector<HeapBlock*, 32> full_blocks_that_became_usable;
  173. size_t collected_cells = 0;
  174. size_t live_cells = 0;
  175. size_t collected_cell_bytes = 0;
  176. size_t live_cell_bytes = 0;
  177. for_each_block([&](auto& block) {
  178. bool block_has_live_cells = false;
  179. bool block_was_full = block.is_full();
  180. block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
  181. if (!cell->is_marked()) {
  182. dbgln_if(HEAP_DEBUG, " ~ {}", cell);
  183. block.deallocate(cell);
  184. ++collected_cells;
  185. collected_cell_bytes += block.cell_size();
  186. } else {
  187. cell->set_marked(false);
  188. block_has_live_cells = true;
  189. ++live_cells;
  190. live_cell_bytes += block.cell_size();
  191. }
  192. });
  193. if (!block_has_live_cells)
  194. empty_blocks.append(&block);
  195. else if (block_was_full != block.is_full())
  196. full_blocks_that_became_usable.append(&block);
  197. return IterationDecision::Continue;
  198. });
  199. for (auto& weak_container : m_weak_containers)
  200. weak_container.remove_dead_cells({});
  201. for (auto* block : empty_blocks) {
  202. dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", block, block->cell_size());
  203. allocator_for_size(block->cell_size()).block_did_become_empty({}, *block);
  204. }
  205. for (auto* block : full_blocks_that_became_usable) {
  206. dbgln_if(HEAP_DEBUG, " - HeapBlock usable again @ {}: cell_size={}", block, block->cell_size());
  207. allocator_for_size(block->cell_size()).block_did_become_usable({}, *block);
  208. }
  209. if constexpr (HEAP_DEBUG) {
  210. for_each_block([&](auto& block) {
  211. dbgln(" > Live HeapBlock @ {}: cell_size={}", &block, block.cell_size());
  212. return IterationDecision::Continue;
  213. });
  214. }
  215. int time_spent = measurement_timer.elapsed();
  216. if (print_report) {
  217. size_t live_block_count = 0;
  218. for_each_block([&](auto&) {
  219. ++live_block_count;
  220. return IterationDecision::Continue;
  221. });
  222. dbgln("Garbage collection report");
  223. dbgln("=============================================");
  224. dbgln(" Time spent: {} ms", time_spent);
  225. dbgln(" Live cells: {} ({} bytes)", live_cells, live_cell_bytes);
  226. dbgln("Collected cells: {} ({} bytes)", collected_cells, collected_cell_bytes);
  227. dbgln(" Live blocks: {} ({} bytes)", live_block_count, live_block_count * HeapBlock::block_size);
  228. dbgln(" Freed blocks: {} ({} bytes)", empty_blocks.size(), empty_blocks.size() * HeapBlock::block_size);
  229. dbgln("=============================================");
  230. }
  231. }
  232. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  233. {
  234. VERIFY(!m_handles.contains(impl));
  235. m_handles.append(impl);
  236. }
  237. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  238. {
  239. VERIFY(m_handles.contains(impl));
  240. m_handles.remove(impl);
  241. }
  242. void Heap::did_create_marked_vector(Badge<MarkedVectorBase>, MarkedVectorBase& vector)
  243. {
  244. VERIFY(!m_marked_vectors.contains(vector));
  245. m_marked_vectors.append(vector);
  246. }
  247. void Heap::did_destroy_marked_vector(Badge<MarkedVectorBase>, MarkedVectorBase& vector)
  248. {
  249. VERIFY(m_marked_vectors.contains(vector));
  250. m_marked_vectors.remove(vector);
  251. }
  252. void Heap::did_create_weak_container(Badge<WeakContainer>, WeakContainer& set)
  253. {
  254. VERIFY(!m_weak_containers.contains(set));
  255. m_weak_containers.append(set);
  256. }
  257. void Heap::did_destroy_weak_container(Badge<WeakContainer>, WeakContainer& set)
  258. {
  259. VERIFY(m_weak_containers.contains(set));
  260. m_weak_containers.remove(set);
  261. }
  262. void Heap::defer_gc(Badge<DeferGC>)
  263. {
  264. ++m_gc_deferrals;
  265. }
  266. void Heap::undefer_gc(Badge<DeferGC>)
  267. {
  268. VERIFY(m_gc_deferrals > 0);
  269. --m_gc_deferrals;
  270. if (!m_gc_deferrals) {
  271. if (m_should_gc_when_deferral_ends)
  272. collect_garbage();
  273. m_should_gc_when_deferral_ends = false;
  274. }
  275. }
  276. void Heap::uproot_cell(Cell* cell)
  277. {
  278. m_uprooted_cells.append(cell);
  279. }
  280. }