Heap.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /*
  2. * Copyright (c) 2020, 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/Allocator.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 <setjmp.h>
  19. namespace JS {
  20. Heap::Heap(VM& vm)
  21. : m_vm(vm)
  22. {
  23. m_allocators.append(make<Allocator>(16));
  24. m_allocators.append(make<Allocator>(32));
  25. m_allocators.append(make<Allocator>(64));
  26. m_allocators.append(make<Allocator>(128));
  27. m_allocators.append(make<Allocator>(256));
  28. m_allocators.append(make<Allocator>(512));
  29. m_allocators.append(make<Allocator>(1024));
  30. m_allocators.append(make<Allocator>(3072));
  31. }
  32. Heap::~Heap()
  33. {
  34. collect_garbage(CollectionType::CollectEverything);
  35. }
  36. ALWAYS_INLINE Allocator& Heap::allocator_for_size(size_t cell_size)
  37. {
  38. for (auto& allocator : m_allocators) {
  39. if (allocator->cell_size() >= cell_size)
  40. return *allocator;
  41. }
  42. VERIFY_NOT_REACHED();
  43. }
  44. Cell* Heap::allocate_cell(size_t size)
  45. {
  46. if (should_collect_on_every_allocation()) {
  47. collect_garbage();
  48. } else if (m_allocations_since_last_gc > m_max_allocations_between_gc) {
  49. m_allocations_since_last_gc = 0;
  50. collect_garbage();
  51. } else {
  52. ++m_allocations_since_last_gc;
  53. }
  54. auto& allocator = allocator_for_size(size);
  55. return allocator.allocate_cell(*this);
  56. }
  57. void Heap::collect_garbage(CollectionType collection_type, bool print_report)
  58. {
  59. VERIFY(!m_collecting_garbage);
  60. TemporaryChange change(m_collecting_garbage, true);
  61. Core::ElapsedTimer collection_measurement_timer;
  62. collection_measurement_timer.start();
  63. if (collection_type == CollectionType::CollectGarbage) {
  64. if (m_gc_deferrals) {
  65. m_should_gc_when_deferral_ends = true;
  66. return;
  67. }
  68. HashTable<Cell*> roots;
  69. gather_roots(roots);
  70. mark_live_cells(roots);
  71. }
  72. sweep_dead_cells(print_report, collection_measurement_timer);
  73. }
  74. void Heap::gather_roots(HashTable<Cell*>& roots)
  75. {
  76. vm().gather_roots(roots);
  77. gather_conservative_roots(roots);
  78. for (auto* handle : m_handles)
  79. roots.set(handle->cell());
  80. for (auto* list : m_marked_value_lists) {
  81. for (auto& value : list->values()) {
  82. if (value.is_cell())
  83. roots.set(value.as_cell());
  84. }
  85. }
  86. if constexpr (HEAP_DEBUG) {
  87. dbgln("gather_roots:");
  88. for (auto* root : roots)
  89. dbgln(" + {}", root);
  90. }
  91. }
  92. __attribute__((no_sanitize("address"))) void Heap::gather_conservative_roots(HashTable<Cell*>& roots)
  93. {
  94. FlatPtr dummy;
  95. dbgln_if(HEAP_DEBUG, "gather_conservative_roots:");
  96. jmp_buf buf;
  97. setjmp(buf);
  98. HashTable<FlatPtr> possible_pointers;
  99. const FlatPtr* raw_jmp_buf = reinterpret_cast<const FlatPtr*>(buf);
  100. for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); i += sizeof(FlatPtr))
  101. possible_pointers.set(raw_jmp_buf[i]);
  102. FlatPtr stack_reference = reinterpret_cast<FlatPtr>(&dummy);
  103. auto& stack_info = m_vm.stack_info();
  104. for (FlatPtr stack_address = stack_reference; stack_address < stack_info.top(); stack_address += sizeof(FlatPtr)) {
  105. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  106. possible_pointers.set(data);
  107. }
  108. HashTable<HeapBlock*> all_live_heap_blocks;
  109. for_each_block([&](auto& block) {
  110. all_live_heap_blocks.set(&block);
  111. return IterationDecision::Continue;
  112. });
  113. for (auto possible_pointer : possible_pointers) {
  114. if (!possible_pointer)
  115. continue;
  116. dbgln_if(HEAP_DEBUG, " ? {}", (const void*)possible_pointer);
  117. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<const Cell*>(possible_pointer));
  118. if (all_live_heap_blocks.contains(possible_heap_block)) {
  119. if (auto* cell = possible_heap_block->cell_from_possible_pointer(possible_pointer)) {
  120. if (cell->state() == Cell::State::Live) {
  121. dbgln_if(HEAP_DEBUG, " ?-> {}", (const void*)cell);
  122. roots.set(cell);
  123. } else {
  124. dbgln_if(HEAP_DEBUG, " #-> {}", (const void*)cell);
  125. }
  126. }
  127. }
  128. }
  129. }
  130. class MarkingVisitor final : public Cell::Visitor {
  131. public:
  132. MarkingVisitor() { }
  133. virtual void visit_impl(Cell& cell)
  134. {
  135. if (cell.is_marked())
  136. return;
  137. dbgln_if(HEAP_DEBUG, " ! {}", cell);
  138. cell.set_marked(true);
  139. cell.visit_edges(*this);
  140. }
  141. };
  142. void Heap::mark_live_cells(const HashTable<Cell*>& roots)
  143. {
  144. dbgln_if(HEAP_DEBUG, "mark_live_cells:");
  145. MarkingVisitor visitor;
  146. for (auto* root : roots)
  147. visitor.visit(root);
  148. }
  149. void Heap::sweep_dead_cells(bool print_report, const Core::ElapsedTimer& measurement_timer)
  150. {
  151. dbgln_if(HEAP_DEBUG, "sweep_dead_cells:");
  152. Vector<HeapBlock*, 32> empty_blocks;
  153. Vector<HeapBlock*, 32> full_blocks_that_became_usable;
  154. size_t collected_cells = 0;
  155. size_t live_cells = 0;
  156. size_t collected_cell_bytes = 0;
  157. size_t live_cell_bytes = 0;
  158. for_each_block([&](auto& block) {
  159. bool block_has_live_cells = false;
  160. bool block_was_full = block.is_full();
  161. block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
  162. if (!cell->is_marked()) {
  163. dbgln_if(HEAP_DEBUG, " ~ {}", cell);
  164. block.deallocate(cell);
  165. ++collected_cells;
  166. collected_cell_bytes += block.cell_size();
  167. } else {
  168. cell->set_marked(false);
  169. block_has_live_cells = true;
  170. ++live_cells;
  171. live_cell_bytes += block.cell_size();
  172. }
  173. });
  174. if (!block_has_live_cells)
  175. empty_blocks.append(&block);
  176. else if (block_was_full != block.is_full())
  177. full_blocks_that_became_usable.append(&block);
  178. return IterationDecision::Continue;
  179. });
  180. for (auto* block : empty_blocks) {
  181. dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", block, block->cell_size());
  182. allocator_for_size(block->cell_size()).block_did_become_empty({}, *block);
  183. }
  184. for (auto* block : full_blocks_that_became_usable) {
  185. dbgln_if(HEAP_DEBUG, " - HeapBlock usable again @ {}: cell_size={}", block, block->cell_size());
  186. allocator_for_size(block->cell_size()).block_did_become_usable({}, *block);
  187. }
  188. if constexpr (HEAP_DEBUG) {
  189. for_each_block([&](auto& block) {
  190. dbgln(" > Live HeapBlock @ {}: cell_size={}", &block, block.cell_size());
  191. return IterationDecision::Continue;
  192. });
  193. }
  194. int time_spent = measurement_timer.elapsed();
  195. if (print_report) {
  196. size_t live_block_count = 0;
  197. for_each_block([&](auto&) {
  198. ++live_block_count;
  199. return IterationDecision::Continue;
  200. });
  201. dbgln("Garbage collection report");
  202. dbgln("=============================================");
  203. dbgln(" Time spent: {} ms", time_spent);
  204. dbgln(" Live cells: {} ({} bytes)", live_cells, live_cell_bytes);
  205. dbgln("Collected cells: {} ({} bytes)", collected_cells, collected_cell_bytes);
  206. dbgln(" Live blocks: {} ({} bytes)", live_block_count, live_block_count * HeapBlock::block_size);
  207. dbgln(" Freed blocks: {} ({} bytes)", empty_blocks.size(), empty_blocks.size() * HeapBlock::block_size);
  208. dbgln("=============================================");
  209. }
  210. }
  211. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  212. {
  213. VERIFY(!m_handles.contains(&impl));
  214. m_handles.set(&impl);
  215. }
  216. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  217. {
  218. VERIFY(m_handles.contains(&impl));
  219. m_handles.remove(&impl);
  220. }
  221. void Heap::did_create_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  222. {
  223. VERIFY(!m_marked_value_lists.contains(&list));
  224. m_marked_value_lists.set(&list);
  225. }
  226. void Heap::did_destroy_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  227. {
  228. VERIFY(m_marked_value_lists.contains(&list));
  229. m_marked_value_lists.remove(&list);
  230. }
  231. void Heap::defer_gc(Badge<DeferGC>)
  232. {
  233. ++m_gc_deferrals;
  234. }
  235. void Heap::undefer_gc(Badge<DeferGC>)
  236. {
  237. VERIFY(m_gc_deferrals > 0);
  238. --m_gc_deferrals;
  239. if (!m_gc_deferrals) {
  240. if (m_should_gc_when_deferral_ends)
  241. collect_garbage();
  242. m_should_gc_when_deferral_ends = false;
  243. }
  244. }
  245. }