Heap.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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/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>(128));
  41. m_allocators.append(make<CellAllocator>(256));
  42. m_allocators.append(make<CellAllocator>(512));
  43. m_allocators.append(make<CellAllocator>(1024));
  44. m_allocators.append(make<CellAllocator>(3072));
  45. }
  46. Heap::~Heap()
  47. {
  48. vm().string_cache().clear();
  49. collect_garbage(CollectionType::CollectEverything);
  50. }
  51. ALWAYS_INLINE CellAllocator& Heap::allocator_for_size(size_t cell_size)
  52. {
  53. for (auto& allocator : m_allocators) {
  54. if (allocator->cell_size() >= cell_size)
  55. return *allocator;
  56. }
  57. dbgln("Cannot get CellAllocator for cell size {}, largest available is {}!", cell_size, m_allocators.last()->cell_size());
  58. VERIFY_NOT_REACHED();
  59. }
  60. Cell* Heap::allocate_cell(size_t size)
  61. {
  62. if (should_collect_on_every_allocation()) {
  63. collect_garbage();
  64. } else if (m_allocations_since_last_gc > m_max_allocations_between_gc) {
  65. m_allocations_since_last_gc = 0;
  66. collect_garbage();
  67. } else {
  68. ++m_allocations_since_last_gc;
  69. }
  70. auto& allocator = allocator_for_size(size);
  71. return allocator.allocate_cell(*this);
  72. }
  73. void Heap::collect_garbage(CollectionType collection_type, bool print_report)
  74. {
  75. VERIFY(!m_collecting_garbage);
  76. TemporaryChange change(m_collecting_garbage, true);
  77. #ifdef __serenity__
  78. static size_t global_gc_counter = 0;
  79. perf_event(PERF_EVENT_SIGNPOST, gc_perf_string_id, global_gc_counter++);
  80. #endif
  81. auto collection_measurement_timer = Core::ElapsedTimer::start_new();
  82. if (collection_type == CollectionType::CollectGarbage) {
  83. if (m_gc_deferrals) {
  84. m_should_gc_when_deferral_ends = true;
  85. return;
  86. }
  87. HashTable<Cell*> roots;
  88. gather_roots(roots);
  89. mark_live_cells(roots);
  90. }
  91. sweep_dead_cells(print_report, collection_measurement_timer);
  92. }
  93. void Heap::gather_roots(HashTable<Cell*>& roots)
  94. {
  95. vm().gather_roots(roots);
  96. gather_conservative_roots(roots);
  97. for (auto& handle : m_handles)
  98. roots.set(handle.cell());
  99. for (auto& list : m_marked_value_lists) {
  100. for (auto& value : list.values()) {
  101. if (value.is_cell())
  102. roots.set(&value.as_cell());
  103. }
  104. }
  105. if constexpr (HEAP_DEBUG) {
  106. dbgln("gather_roots:");
  107. for (auto* root : roots)
  108. dbgln(" + {}", root);
  109. }
  110. }
  111. __attribute__((no_sanitize("address"))) void Heap::gather_conservative_roots(HashTable<Cell*>& roots)
  112. {
  113. FlatPtr dummy;
  114. dbgln_if(HEAP_DEBUG, "gather_conservative_roots:");
  115. jmp_buf buf;
  116. setjmp(buf);
  117. HashTable<FlatPtr> possible_pointers;
  118. auto* raw_jmp_buf = reinterpret_cast<FlatPtr const*>(buf);
  119. for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); i += sizeof(FlatPtr))
  120. possible_pointers.set(raw_jmp_buf[i]);
  121. auto stack_reference = bit_cast<FlatPtr>(&dummy);
  122. auto& stack_info = m_vm.stack_info();
  123. for (FlatPtr stack_address = stack_reference; stack_address < stack_info.top(); stack_address += sizeof(FlatPtr)) {
  124. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  125. possible_pointers.set(data);
  126. }
  127. HashTable<HeapBlock*> all_live_heap_blocks;
  128. for_each_block([&](auto& block) {
  129. all_live_heap_blocks.set(&block);
  130. return IterationDecision::Continue;
  131. });
  132. for (auto possible_pointer : possible_pointers) {
  133. if (!possible_pointer)
  134. continue;
  135. dbgln_if(HEAP_DEBUG, " ? {}", (const void*)possible_pointer);
  136. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<const Cell*>(possible_pointer));
  137. if (all_live_heap_blocks.contains(possible_heap_block)) {
  138. if (auto* cell = possible_heap_block->cell_from_possible_pointer(possible_pointer)) {
  139. if (cell->state() == Cell::State::Live) {
  140. dbgln_if(HEAP_DEBUG, " ?-> {}", (const void*)cell);
  141. roots.set(cell);
  142. } else {
  143. dbgln_if(HEAP_DEBUG, " #-> {}", (const void*)cell);
  144. }
  145. }
  146. }
  147. }
  148. }
  149. class MarkingVisitor final : public Cell::Visitor {
  150. public:
  151. MarkingVisitor() { }
  152. virtual void visit_impl(Cell& cell)
  153. {
  154. if (cell.is_marked())
  155. return;
  156. dbgln_if(HEAP_DEBUG, " ! {}", &cell);
  157. #ifdef JS_TRACK_ZOMBIE_CELLS
  158. if (cell.state() == Cell::State::Zombie) {
  159. dbgln("BUG! Marking a zombie cell, {} @ {:p}", cell.class_name(), &cell);
  160. cell.vm().dump_backtrace();
  161. VERIFY_NOT_REACHED();
  162. }
  163. #endif
  164. cell.set_marked(true);
  165. cell.visit_edges(*this);
  166. }
  167. };
  168. void Heap::mark_live_cells(const HashTable<Cell*>& roots)
  169. {
  170. dbgln_if(HEAP_DEBUG, "mark_live_cells:");
  171. MarkingVisitor visitor;
  172. for (auto* root : roots)
  173. visitor.visit(root);
  174. for (auto& inverse_root : m_uprooted_cells)
  175. inverse_root->set_marked(false);
  176. m_uprooted_cells.clear();
  177. }
  178. void Heap::sweep_dead_cells(bool print_report, const Core::ElapsedTimer& measurement_timer)
  179. {
  180. dbgln_if(HEAP_DEBUG, "sweep_dead_cells:");
  181. Vector<HeapBlock*, 32> empty_blocks;
  182. Vector<HeapBlock*, 32> full_blocks_that_became_usable;
  183. size_t collected_cells = 0;
  184. size_t live_cells = 0;
  185. size_t collected_cell_bytes = 0;
  186. size_t live_cell_bytes = 0;
  187. for_each_block([&](auto& block) {
  188. bool block_has_live_cells = false;
  189. bool block_was_full = block.is_full();
  190. block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
  191. if (!cell->is_marked()) {
  192. dbgln_if(HEAP_DEBUG, " ~ {}", cell);
  193. #ifdef JS_TRACK_ZOMBIE_CELLS
  194. if (m_zombify_dead_cells) {
  195. cell->set_state(Cell::State::Zombie);
  196. cell->did_become_zombie();
  197. } else {
  198. #endif
  199. block.deallocate(cell);
  200. #ifdef JS_TRACK_ZOMBIE_CELLS
  201. }
  202. #endif
  203. ++collected_cells;
  204. collected_cell_bytes += block.cell_size();
  205. } else {
  206. cell->set_marked(false);
  207. block_has_live_cells = true;
  208. ++live_cells;
  209. live_cell_bytes += block.cell_size();
  210. }
  211. });
  212. if (!block_has_live_cells)
  213. empty_blocks.append(&block);
  214. else if (block_was_full != block.is_full())
  215. full_blocks_that_became_usable.append(&block);
  216. return IterationDecision::Continue;
  217. });
  218. for (auto& weak_container : m_weak_containers)
  219. weak_container.remove_dead_cells({});
  220. for (auto* block : empty_blocks) {
  221. dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", block, block->cell_size());
  222. allocator_for_size(block->cell_size()).block_did_become_empty({}, *block);
  223. }
  224. for (auto* block : full_blocks_that_became_usable) {
  225. dbgln_if(HEAP_DEBUG, " - HeapBlock usable again @ {}: cell_size={}", block, block->cell_size());
  226. allocator_for_size(block->cell_size()).block_did_become_usable({}, *block);
  227. }
  228. if constexpr (HEAP_DEBUG) {
  229. for_each_block([&](auto& block) {
  230. dbgln(" > Live HeapBlock @ {}: cell_size={}", &block, block.cell_size());
  231. return IterationDecision::Continue;
  232. });
  233. }
  234. int time_spent = measurement_timer.elapsed();
  235. if (print_report) {
  236. size_t live_block_count = 0;
  237. for_each_block([&](auto&) {
  238. ++live_block_count;
  239. return IterationDecision::Continue;
  240. });
  241. dbgln("Garbage collection report");
  242. dbgln("=============================================");
  243. dbgln(" Time spent: {} ms", time_spent);
  244. dbgln(" Live cells: {} ({} bytes)", live_cells, live_cell_bytes);
  245. dbgln("Collected cells: {} ({} bytes)", collected_cells, collected_cell_bytes);
  246. dbgln(" Live blocks: {} ({} bytes)", live_block_count, live_block_count * HeapBlock::block_size);
  247. dbgln(" Freed blocks: {} ({} bytes)", empty_blocks.size(), empty_blocks.size() * HeapBlock::block_size);
  248. dbgln("=============================================");
  249. }
  250. }
  251. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  252. {
  253. VERIFY(!m_handles.contains(impl));
  254. m_handles.append(impl);
  255. }
  256. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  257. {
  258. VERIFY(m_handles.contains(impl));
  259. m_handles.remove(impl);
  260. }
  261. void Heap::did_create_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  262. {
  263. VERIFY(!m_marked_value_lists.contains(list));
  264. m_marked_value_lists.append(list);
  265. }
  266. void Heap::did_destroy_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  267. {
  268. VERIFY(m_marked_value_lists.contains(list));
  269. m_marked_value_lists.remove(list);
  270. }
  271. void Heap::did_create_weak_container(Badge<WeakContainer>, WeakContainer& set)
  272. {
  273. VERIFY(!m_weak_containers.contains(set));
  274. m_weak_containers.append(set);
  275. }
  276. void Heap::did_destroy_weak_container(Badge<WeakContainer>, WeakContainer& set)
  277. {
  278. VERIFY(m_weak_containers.contains(set));
  279. m_weak_containers.remove(set);
  280. }
  281. void Heap::defer_gc(Badge<DeferGC>)
  282. {
  283. ++m_gc_deferrals;
  284. }
  285. void Heap::undefer_gc(Badge<DeferGC>)
  286. {
  287. VERIFY(m_gc_deferrals > 0);
  288. --m_gc_deferrals;
  289. if (!m_gc_deferrals) {
  290. if (m_should_gc_when_deferral_ends)
  291. collect_garbage();
  292. m_should_gc_when_deferral_ends = false;
  293. }
  294. }
  295. void Heap::uproot_cell(Cell* cell)
  296. {
  297. m_uprooted_cells.append(cell);
  298. }
  299. }