Heap.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. auto add_possible_value = [&](FlatPtr data) {
  117. if constexpr (sizeof(FlatPtr*) == sizeof(Value)) {
  118. // Because Value stores pointers in non-canonical form we have to check if the top bytes
  119. // match any pointer-backed tag, in that case we have to extract the pointer to its
  120. // canonical form and add that as a possible pointer.
  121. if ((data & SHIFTED_IS_CELL_PATTERN) == SHIFTED_IS_CELL_PATTERN)
  122. possible_pointers.set((u64)(((i64)data << 16) >> 16));
  123. else
  124. possible_pointers.set(data);
  125. } else {
  126. static_assert((sizeof(Value) % sizeof(FlatPtr*)) == 0);
  127. // In the 32-bit case we will look at the top and bottom part of Value separately we just
  128. // add both the upper and lower bytes as possible pointers.
  129. possible_pointers.set(data);
  130. }
  131. };
  132. for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); i += sizeof(FlatPtr))
  133. add_possible_value(raw_jmp_buf[i]);
  134. auto stack_reference = bit_cast<FlatPtr>(&dummy);
  135. auto& stack_info = m_vm.stack_info();
  136. for (FlatPtr stack_address = stack_reference; stack_address < stack_info.top(); stack_address += sizeof(FlatPtr)) {
  137. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  138. add_possible_value(data);
  139. }
  140. HashTable<HeapBlock*> all_live_heap_blocks;
  141. for_each_block([&](auto& block) {
  142. all_live_heap_blocks.set(&block);
  143. return IterationDecision::Continue;
  144. });
  145. for (auto possible_pointer : possible_pointers) {
  146. if (!possible_pointer)
  147. continue;
  148. dbgln_if(HEAP_DEBUG, " ? {}", (void const*)possible_pointer);
  149. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<Cell const*>(possible_pointer));
  150. if (all_live_heap_blocks.contains(possible_heap_block)) {
  151. if (auto* cell = possible_heap_block->cell_from_possible_pointer(possible_pointer)) {
  152. if (cell->state() == Cell::State::Live) {
  153. dbgln_if(HEAP_DEBUG, " ?-> {}", (void const*)cell);
  154. roots.set(cell);
  155. } else {
  156. dbgln_if(HEAP_DEBUG, " #-> {}", (void const*)cell);
  157. }
  158. }
  159. }
  160. }
  161. }
  162. class MarkingVisitor final : public Cell::Visitor {
  163. public:
  164. MarkingVisitor() = default;
  165. virtual void visit_impl(Cell& cell) override
  166. {
  167. if (cell.is_marked())
  168. return;
  169. dbgln_if(HEAP_DEBUG, " ! {}", &cell);
  170. cell.set_marked(true);
  171. cell.visit_edges(*this);
  172. }
  173. };
  174. void Heap::mark_live_cells(HashTable<Cell*> const& roots)
  175. {
  176. dbgln_if(HEAP_DEBUG, "mark_live_cells:");
  177. MarkingVisitor visitor;
  178. for (auto* root : roots)
  179. visitor.visit(root);
  180. for (auto& inverse_root : m_uprooted_cells)
  181. inverse_root->set_marked(false);
  182. m_uprooted_cells.clear();
  183. }
  184. void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measurement_timer)
  185. {
  186. dbgln_if(HEAP_DEBUG, "sweep_dead_cells:");
  187. Vector<HeapBlock*, 32> empty_blocks;
  188. Vector<HeapBlock*, 32> full_blocks_that_became_usable;
  189. size_t collected_cells = 0;
  190. size_t live_cells = 0;
  191. size_t collected_cell_bytes = 0;
  192. size_t live_cell_bytes = 0;
  193. for_each_block([&](auto& block) {
  194. bool block_has_live_cells = false;
  195. bool block_was_full = block.is_full();
  196. block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
  197. if (!cell->is_marked()) {
  198. dbgln_if(HEAP_DEBUG, " ~ {}", cell);
  199. block.deallocate(cell);
  200. ++collected_cells;
  201. collected_cell_bytes += block.cell_size();
  202. } else {
  203. cell->set_marked(false);
  204. block_has_live_cells = true;
  205. ++live_cells;
  206. live_cell_bytes += block.cell_size();
  207. }
  208. });
  209. if (!block_has_live_cells)
  210. empty_blocks.append(&block);
  211. else if (block_was_full != block.is_full())
  212. full_blocks_that_became_usable.append(&block);
  213. return IterationDecision::Continue;
  214. });
  215. for (auto& weak_container : m_weak_containers)
  216. weak_container.remove_dead_cells({});
  217. for (auto* block : empty_blocks) {
  218. dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", block, block->cell_size());
  219. allocator_for_size(block->cell_size()).block_did_become_empty({}, *block);
  220. }
  221. for (auto* block : full_blocks_that_became_usable) {
  222. dbgln_if(HEAP_DEBUG, " - HeapBlock usable again @ {}: cell_size={}", block, block->cell_size());
  223. allocator_for_size(block->cell_size()).block_did_become_usable({}, *block);
  224. }
  225. if constexpr (HEAP_DEBUG) {
  226. for_each_block([&](auto& block) {
  227. dbgln(" > Live HeapBlock @ {}: cell_size={}", &block, block.cell_size());
  228. return IterationDecision::Continue;
  229. });
  230. }
  231. int time_spent = measurement_timer.elapsed();
  232. if (print_report) {
  233. size_t live_block_count = 0;
  234. for_each_block([&](auto&) {
  235. ++live_block_count;
  236. return IterationDecision::Continue;
  237. });
  238. dbgln("Garbage collection report");
  239. dbgln("=============================================");
  240. dbgln(" Time spent: {} ms", time_spent);
  241. dbgln(" Live cells: {} ({} bytes)", live_cells, live_cell_bytes);
  242. dbgln("Collected cells: {} ({} bytes)", collected_cells, collected_cell_bytes);
  243. dbgln(" Live blocks: {} ({} bytes)", live_block_count, live_block_count * HeapBlock::block_size);
  244. dbgln(" Freed blocks: {} ({} bytes)", empty_blocks.size(), empty_blocks.size() * HeapBlock::block_size);
  245. dbgln("=============================================");
  246. }
  247. }
  248. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  249. {
  250. VERIFY(!m_handles.contains(impl));
  251. m_handles.append(impl);
  252. }
  253. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  254. {
  255. VERIFY(m_handles.contains(impl));
  256. m_handles.remove(impl);
  257. }
  258. void Heap::did_create_marked_vector(Badge<MarkedVectorBase>, MarkedVectorBase& vector)
  259. {
  260. VERIFY(!m_marked_vectors.contains(vector));
  261. m_marked_vectors.append(vector);
  262. }
  263. void Heap::did_destroy_marked_vector(Badge<MarkedVectorBase>, MarkedVectorBase& vector)
  264. {
  265. VERIFY(m_marked_vectors.contains(vector));
  266. m_marked_vectors.remove(vector);
  267. }
  268. void Heap::did_create_weak_container(Badge<WeakContainer>, WeakContainer& set)
  269. {
  270. VERIFY(!m_weak_containers.contains(set));
  271. m_weak_containers.append(set);
  272. }
  273. void Heap::did_destroy_weak_container(Badge<WeakContainer>, WeakContainer& set)
  274. {
  275. VERIFY(m_weak_containers.contains(set));
  276. m_weak_containers.remove(set);
  277. }
  278. void Heap::defer_gc(Badge<DeferGC>)
  279. {
  280. ++m_gc_deferrals;
  281. }
  282. void Heap::undefer_gc(Badge<DeferGC>)
  283. {
  284. VERIFY(m_gc_deferrals > 0);
  285. --m_gc_deferrals;
  286. if (!m_gc_deferrals) {
  287. if (m_should_gc_when_deferral_ends)
  288. collect_garbage();
  289. m_should_gc_when_deferral_ends = false;
  290. }
  291. }
  292. void Heap::uproot_cell(Cell* cell)
  293. {
  294. m_uprooted_cells.append(cell);
  295. }
  296. // Temporary helper function as we can't pass a realm directly until Heap::allocate<T>() receives one.
  297. // Heap.h only has a forward declaration of the GlobalObject, so no inlined member access possible.
  298. Realm& realm_from_global_object(GlobalObject& global_object)
  299. {
  300. return *global_object.associated_realm();
  301. }
  302. }