Heap.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. for (auto& vector : m_marked_vectors) {
  106. for (auto* cell : vector.cells())
  107. roots.set(cell);
  108. }
  109. if constexpr (HEAP_DEBUG) {
  110. dbgln("gather_roots:");
  111. for (auto* root : roots)
  112. dbgln(" + {}", root);
  113. }
  114. }
  115. __attribute__((no_sanitize("address"))) void Heap::gather_conservative_roots(HashTable<Cell*>& roots)
  116. {
  117. FlatPtr dummy;
  118. dbgln_if(HEAP_DEBUG, "gather_conservative_roots:");
  119. jmp_buf buf;
  120. setjmp(buf);
  121. HashTable<FlatPtr> possible_pointers;
  122. auto* raw_jmp_buf = reinterpret_cast<FlatPtr const*>(buf);
  123. for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); i += sizeof(FlatPtr))
  124. possible_pointers.set(raw_jmp_buf[i]);
  125. auto stack_reference = bit_cast<FlatPtr>(&dummy);
  126. auto& stack_info = m_vm.stack_info();
  127. for (FlatPtr stack_address = stack_reference; stack_address < stack_info.top(); stack_address += sizeof(FlatPtr)) {
  128. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  129. possible_pointers.set(data);
  130. }
  131. HashTable<HeapBlock*> all_live_heap_blocks;
  132. for_each_block([&](auto& block) {
  133. all_live_heap_blocks.set(&block);
  134. return IterationDecision::Continue;
  135. });
  136. for (auto possible_pointer : possible_pointers) {
  137. if (!possible_pointer)
  138. continue;
  139. dbgln_if(HEAP_DEBUG, " ? {}", (const void*)possible_pointer);
  140. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<const Cell*>(possible_pointer));
  141. if (all_live_heap_blocks.contains(possible_heap_block)) {
  142. if (auto* cell = possible_heap_block->cell_from_possible_pointer(possible_pointer)) {
  143. if (cell->state() == Cell::State::Live) {
  144. dbgln_if(HEAP_DEBUG, " ?-> {}", (const void*)cell);
  145. roots.set(cell);
  146. } else {
  147. dbgln_if(HEAP_DEBUG, " #-> {}", (const void*)cell);
  148. }
  149. }
  150. }
  151. }
  152. }
  153. class MarkingVisitor final : public Cell::Visitor {
  154. public:
  155. MarkingVisitor() { }
  156. virtual void visit_impl(Cell& cell) override
  157. {
  158. if (cell.is_marked())
  159. return;
  160. dbgln_if(HEAP_DEBUG, " ! {}", &cell);
  161. #ifdef JS_TRACK_ZOMBIE_CELLS
  162. if (cell.state() == Cell::State::Zombie) {
  163. dbgln("BUG! Marking a zombie cell, {} @ {:p}", cell.class_name(), &cell);
  164. cell.vm().dump_backtrace();
  165. VERIFY_NOT_REACHED();
  166. }
  167. #endif
  168. cell.set_marked(true);
  169. cell.visit_edges(*this);
  170. }
  171. };
  172. void Heap::mark_live_cells(const HashTable<Cell*>& roots)
  173. {
  174. dbgln_if(HEAP_DEBUG, "mark_live_cells:");
  175. MarkingVisitor visitor;
  176. for (auto* root : roots)
  177. visitor.visit(root);
  178. for (auto& inverse_root : m_uprooted_cells)
  179. inverse_root->set_marked(false);
  180. m_uprooted_cells.clear();
  181. }
  182. void Heap::sweep_dead_cells(bool print_report, const Core::ElapsedTimer& measurement_timer)
  183. {
  184. dbgln_if(HEAP_DEBUG, "sweep_dead_cells:");
  185. Vector<HeapBlock*, 32> empty_blocks;
  186. Vector<HeapBlock*, 32> full_blocks_that_became_usable;
  187. size_t collected_cells = 0;
  188. size_t live_cells = 0;
  189. size_t collected_cell_bytes = 0;
  190. size_t live_cell_bytes = 0;
  191. for_each_block([&](auto& block) {
  192. bool block_has_live_cells = false;
  193. bool block_was_full = block.is_full();
  194. block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
  195. if (!cell->is_marked()) {
  196. dbgln_if(HEAP_DEBUG, " ~ {}", cell);
  197. #ifdef JS_TRACK_ZOMBIE_CELLS
  198. if (m_zombify_dead_cells) {
  199. cell->set_state(Cell::State::Zombie);
  200. cell->did_become_zombie();
  201. } else {
  202. #endif
  203. block.deallocate(cell);
  204. #ifdef JS_TRACK_ZOMBIE_CELLS
  205. }
  206. #endif
  207. ++collected_cells;
  208. collected_cell_bytes += block.cell_size();
  209. } else {
  210. cell->set_marked(false);
  211. block_has_live_cells = true;
  212. ++live_cells;
  213. live_cell_bytes += block.cell_size();
  214. }
  215. });
  216. if (!block_has_live_cells)
  217. empty_blocks.append(&block);
  218. else if (block_was_full != block.is_full())
  219. full_blocks_that_became_usable.append(&block);
  220. return IterationDecision::Continue;
  221. });
  222. for (auto& weak_container : m_weak_containers)
  223. weak_container.remove_dead_cells({});
  224. for (auto* block : empty_blocks) {
  225. dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", block, block->cell_size());
  226. allocator_for_size(block->cell_size()).block_did_become_empty({}, *block);
  227. }
  228. for (auto* block : full_blocks_that_became_usable) {
  229. dbgln_if(HEAP_DEBUG, " - HeapBlock usable again @ {}: cell_size={}", block, block->cell_size());
  230. allocator_for_size(block->cell_size()).block_did_become_usable({}, *block);
  231. }
  232. if constexpr (HEAP_DEBUG) {
  233. for_each_block([&](auto& block) {
  234. dbgln(" > Live HeapBlock @ {}: cell_size={}", &block, block.cell_size());
  235. return IterationDecision::Continue;
  236. });
  237. }
  238. int time_spent = measurement_timer.elapsed();
  239. if (print_report) {
  240. size_t live_block_count = 0;
  241. for_each_block([&](auto&) {
  242. ++live_block_count;
  243. return IterationDecision::Continue;
  244. });
  245. dbgln("Garbage collection report");
  246. dbgln("=============================================");
  247. dbgln(" Time spent: {} ms", time_spent);
  248. dbgln(" Live cells: {} ({} bytes)", live_cells, live_cell_bytes);
  249. dbgln("Collected cells: {} ({} bytes)", collected_cells, collected_cell_bytes);
  250. dbgln(" Live blocks: {} ({} bytes)", live_block_count, live_block_count * HeapBlock::block_size);
  251. dbgln(" Freed blocks: {} ({} bytes)", empty_blocks.size(), empty_blocks.size() * HeapBlock::block_size);
  252. dbgln("=============================================");
  253. }
  254. }
  255. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  256. {
  257. VERIFY(!m_handles.contains(impl));
  258. m_handles.append(impl);
  259. }
  260. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  261. {
  262. VERIFY(m_handles.contains(impl));
  263. m_handles.remove(impl);
  264. }
  265. void Heap::did_create_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  266. {
  267. VERIFY(!m_marked_value_lists.contains(list));
  268. m_marked_value_lists.append(list);
  269. }
  270. void Heap::did_destroy_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  271. {
  272. VERIFY(m_marked_value_lists.contains(list));
  273. m_marked_value_lists.remove(list);
  274. }
  275. void Heap::did_create_marked_vector(Badge<MarkedVectorBase>, MarkedVectorBase& vector)
  276. {
  277. VERIFY(!m_marked_vectors.contains(vector));
  278. m_marked_vectors.append(vector);
  279. }
  280. void Heap::did_destroy_marked_vector(Badge<MarkedVectorBase>, MarkedVectorBase& vector)
  281. {
  282. VERIFY(m_marked_vectors.contains(vector));
  283. m_marked_vectors.remove(vector);
  284. }
  285. void Heap::did_create_weak_container(Badge<WeakContainer>, WeakContainer& set)
  286. {
  287. VERIFY(!m_weak_containers.contains(set));
  288. m_weak_containers.append(set);
  289. }
  290. void Heap::did_destroy_weak_container(Badge<WeakContainer>, WeakContainer& set)
  291. {
  292. VERIFY(m_weak_containers.contains(set));
  293. m_weak_containers.remove(set);
  294. }
  295. void Heap::defer_gc(Badge<DeferGC>)
  296. {
  297. ++m_gc_deferrals;
  298. }
  299. void Heap::undefer_gc(Badge<DeferGC>)
  300. {
  301. VERIFY(m_gc_deferrals > 0);
  302. --m_gc_deferrals;
  303. if (!m_gc_deferrals) {
  304. if (m_should_gc_when_deferral_ends)
  305. collect_garbage();
  306. m_should_gc_when_deferral_ends = false;
  307. }
  308. }
  309. void Heap::uproot_cell(Cell* cell)
  310. {
  311. m_uprooted_cells.append(cell);
  312. }
  313. }