Heap.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 <LibJS/SafeFunction.h>
  20. #include <setjmp.h>
  21. #ifdef AK_OS_SERENITY
  22. # include <serenity.h>
  23. #endif
  24. namespace JS {
  25. #ifdef AK_OS_SERENITY
  26. static int gc_perf_string_id;
  27. #endif
  28. // NOTE: We keep a per-thread list of custom ranges. This hinges on the assumption that there is one JS VM per thread.
  29. static __thread HashMap<FlatPtr*, size_t>* s_custom_ranges_for_conservative_scan = nullptr;
  30. Heap::Heap(VM& vm)
  31. : m_vm(vm)
  32. {
  33. #ifdef AK_OS_SERENITY
  34. auto gc_signpost_string = "Garbage collection"sv;
  35. gc_perf_string_id = perf_register_string(gc_signpost_string.characters_without_null_termination(), gc_signpost_string.length());
  36. #endif
  37. if constexpr (HeapBlock::min_possible_cell_size <= 16) {
  38. m_allocators.append(make<CellAllocator>(16));
  39. }
  40. static_assert(HeapBlock::min_possible_cell_size <= 24, "Heap Cell tracking uses too much data!");
  41. m_allocators.append(make<CellAllocator>(32));
  42. m_allocators.append(make<CellAllocator>(64));
  43. m_allocators.append(make<CellAllocator>(96));
  44. m_allocators.append(make<CellAllocator>(128));
  45. m_allocators.append(make<CellAllocator>(256));
  46. m_allocators.append(make<CellAllocator>(512));
  47. m_allocators.append(make<CellAllocator>(1024));
  48. m_allocators.append(make<CellAllocator>(3072));
  49. }
  50. Heap::~Heap()
  51. {
  52. vm().string_cache().clear();
  53. vm().deprecated_string_cache().clear();
  54. collect_garbage(CollectionType::CollectEverything);
  55. }
  56. ALWAYS_INLINE CellAllocator& Heap::allocator_for_size(size_t cell_size)
  57. {
  58. for (auto& allocator : m_allocators) {
  59. if (allocator->cell_size() >= cell_size)
  60. return *allocator;
  61. }
  62. dbgln("Cannot get CellAllocator for cell size {}, largest available is {}!", cell_size, m_allocators.last()->cell_size());
  63. VERIFY_NOT_REACHED();
  64. }
  65. Cell* Heap::allocate_cell(size_t size)
  66. {
  67. if (should_collect_on_every_allocation()) {
  68. collect_garbage();
  69. } else if (m_allocations_since_last_gc > m_max_allocations_between_gc) {
  70. m_allocations_since_last_gc = 0;
  71. collect_garbage();
  72. } else {
  73. ++m_allocations_since_last_gc;
  74. }
  75. auto& allocator = allocator_for_size(size);
  76. return allocator.allocate_cell(*this);
  77. }
  78. void Heap::collect_garbage(CollectionType collection_type, bool print_report)
  79. {
  80. VERIFY(!m_collecting_garbage);
  81. TemporaryChange change(m_collecting_garbage, true);
  82. #ifdef AK_OS_SERENITY
  83. static size_t global_gc_counter = 0;
  84. perf_event(PERF_EVENT_SIGNPOST, gc_perf_string_id, global_gc_counter++);
  85. #endif
  86. Core::ElapsedTimer collection_measurement_timer;
  87. if (print_report)
  88. collection_measurement_timer.start();
  89. if (collection_type == CollectionType::CollectGarbage) {
  90. if (m_gc_deferrals) {
  91. m_should_gc_when_deferral_ends = true;
  92. return;
  93. }
  94. HashTable<Cell*> roots;
  95. gather_roots(roots);
  96. mark_live_cells(roots);
  97. }
  98. finalize_unmarked_cells();
  99. sweep_dead_cells(print_report, collection_measurement_timer);
  100. }
  101. void Heap::gather_roots(HashTable<Cell*>& roots)
  102. {
  103. vm().gather_roots(roots);
  104. gather_conservative_roots(roots);
  105. for (auto& handle : m_handles)
  106. roots.set(handle.cell());
  107. for (auto& vector : m_marked_vectors)
  108. vector.gather_roots(roots);
  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. auto add_possible_value = [&](FlatPtr data) {
  124. if constexpr (sizeof(FlatPtr*) == sizeof(Value)) {
  125. // Because Value stores pointers in non-canonical form we have to check if the top bytes
  126. // match any pointer-backed tag, in that case we have to extract the pointer to its
  127. // canonical form and add that as a possible pointer.
  128. if ((data & SHIFTED_IS_CELL_PATTERN) == SHIFTED_IS_CELL_PATTERN)
  129. possible_pointers.set(Value::extract_pointer_bits(data));
  130. else
  131. possible_pointers.set(data);
  132. } else {
  133. static_assert((sizeof(Value) % sizeof(FlatPtr*)) == 0);
  134. // In the 32-bit case we will look at the top and bottom part of Value separately we just
  135. // add both the upper and lower bytes as possible pointers.
  136. possible_pointers.set(data);
  137. }
  138. };
  139. for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); ++i)
  140. add_possible_value(raw_jmp_buf[i]);
  141. auto stack_reference = bit_cast<FlatPtr>(&dummy);
  142. auto& stack_info = m_vm.stack_info();
  143. for (FlatPtr stack_address = stack_reference; stack_address < stack_info.top(); stack_address += sizeof(FlatPtr)) {
  144. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  145. add_possible_value(data);
  146. }
  147. // NOTE: If we have any custom ranges registered, scan those as well.
  148. // This is where JS::SafeFunction closures get marked.
  149. if (s_custom_ranges_for_conservative_scan) {
  150. for (auto& custom_range : *s_custom_ranges_for_conservative_scan) {
  151. for (size_t i = 0; i < (custom_range.value / sizeof(FlatPtr)); ++i) {
  152. add_possible_value(custom_range.key[i]);
  153. }
  154. }
  155. }
  156. HashTable<HeapBlock*> all_live_heap_blocks;
  157. for_each_block([&](auto& block) {
  158. all_live_heap_blocks.set(&block);
  159. return IterationDecision::Continue;
  160. });
  161. for (auto possible_pointer : possible_pointers) {
  162. if (!possible_pointer)
  163. continue;
  164. dbgln_if(HEAP_DEBUG, " ? {}", (void const*)possible_pointer);
  165. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<Cell const*>(possible_pointer));
  166. if (all_live_heap_blocks.contains(possible_heap_block)) {
  167. if (auto* cell = possible_heap_block->cell_from_possible_pointer(possible_pointer)) {
  168. if (cell->state() == Cell::State::Live) {
  169. dbgln_if(HEAP_DEBUG, " ?-> {}", (void const*)cell);
  170. roots.set(cell);
  171. } else {
  172. dbgln_if(HEAP_DEBUG, " #-> {}", (void const*)cell);
  173. }
  174. }
  175. }
  176. }
  177. }
  178. class MarkingVisitor final : public Cell::Visitor {
  179. public:
  180. explicit MarkingVisitor(HashTable<Cell*> const& roots)
  181. {
  182. for (auto* root : roots) {
  183. visit(root);
  184. }
  185. }
  186. virtual void visit_impl(Cell& cell) override
  187. {
  188. if (cell.is_marked())
  189. return;
  190. dbgln_if(HEAP_DEBUG, " ! {}", &cell);
  191. cell.set_marked(true);
  192. m_work_queue.append(cell);
  193. }
  194. void mark_all_live_cells()
  195. {
  196. while (!m_work_queue.is_empty()) {
  197. m_work_queue.take_last().visit_edges(*this);
  198. }
  199. }
  200. private:
  201. Vector<Cell&> m_work_queue;
  202. };
  203. void Heap::mark_live_cells(HashTable<Cell*> const& roots)
  204. {
  205. dbgln_if(HEAP_DEBUG, "mark_live_cells:");
  206. MarkingVisitor visitor(roots);
  207. visitor.mark_all_live_cells();
  208. for (auto& inverse_root : m_uprooted_cells)
  209. inverse_root->set_marked(false);
  210. m_uprooted_cells.clear();
  211. }
  212. bool Heap::cell_must_survive_garbage_collection(Cell const& cell)
  213. {
  214. if (!cell.overrides_must_survive_garbage_collection({}))
  215. return false;
  216. return cell.must_survive_garbage_collection();
  217. }
  218. void Heap::finalize_unmarked_cells()
  219. {
  220. for_each_block([&](auto& block) {
  221. block.template for_each_cell_in_state<Cell::State::Live>([](Cell* cell) {
  222. if (!cell->is_marked() && !cell_must_survive_garbage_collection(*cell))
  223. cell->finalize();
  224. });
  225. return IterationDecision::Continue;
  226. });
  227. }
  228. void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measurement_timer)
  229. {
  230. dbgln_if(HEAP_DEBUG, "sweep_dead_cells:");
  231. Vector<HeapBlock*, 32> empty_blocks;
  232. Vector<HeapBlock*, 32> full_blocks_that_became_usable;
  233. size_t collected_cells = 0;
  234. size_t live_cells = 0;
  235. size_t collected_cell_bytes = 0;
  236. size_t live_cell_bytes = 0;
  237. for_each_block([&](auto& block) {
  238. bool block_has_live_cells = false;
  239. bool block_was_full = block.is_full();
  240. block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
  241. if (!cell->is_marked() && !cell_must_survive_garbage_collection(*cell)) {
  242. dbgln_if(HEAP_DEBUG, " ~ {}", cell);
  243. block.deallocate(cell);
  244. ++collected_cells;
  245. collected_cell_bytes += block.cell_size();
  246. } else {
  247. cell->set_marked(false);
  248. block_has_live_cells = true;
  249. ++live_cells;
  250. live_cell_bytes += block.cell_size();
  251. }
  252. });
  253. if (!block_has_live_cells)
  254. empty_blocks.append(&block);
  255. else if (block_was_full != block.is_full())
  256. full_blocks_that_became_usable.append(&block);
  257. return IterationDecision::Continue;
  258. });
  259. for (auto& weak_container : m_weak_containers)
  260. weak_container.remove_dead_cells({});
  261. for (auto* block : empty_blocks) {
  262. dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", block, block->cell_size());
  263. allocator_for_size(block->cell_size()).block_did_become_empty({}, *block);
  264. }
  265. for (auto* block : full_blocks_that_became_usable) {
  266. dbgln_if(HEAP_DEBUG, " - HeapBlock usable again @ {}: cell_size={}", block, block->cell_size());
  267. allocator_for_size(block->cell_size()).block_did_become_usable({}, *block);
  268. }
  269. if constexpr (HEAP_DEBUG) {
  270. for_each_block([&](auto& block) {
  271. dbgln(" > Live HeapBlock @ {}: cell_size={}", &block, block.cell_size());
  272. return IterationDecision::Continue;
  273. });
  274. }
  275. if (print_report) {
  276. Time const time_spent = measurement_timer.elapsed_time();
  277. size_t live_block_count = 0;
  278. for_each_block([&](auto&) {
  279. ++live_block_count;
  280. return IterationDecision::Continue;
  281. });
  282. dbgln("Garbage collection report");
  283. dbgln("=============================================");
  284. dbgln(" Time spent: {} ms", time_spent.to_milliseconds());
  285. dbgln(" Live cells: {} ({} bytes)", live_cells, live_cell_bytes);
  286. dbgln("Collected cells: {} ({} bytes)", collected_cells, collected_cell_bytes);
  287. dbgln(" Live blocks: {} ({} bytes)", live_block_count, live_block_count * HeapBlock::block_size);
  288. dbgln(" Freed blocks: {} ({} bytes)", empty_blocks.size(), empty_blocks.size() * HeapBlock::block_size);
  289. dbgln("=============================================");
  290. }
  291. }
  292. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  293. {
  294. VERIFY(!m_handles.contains(impl));
  295. m_handles.append(impl);
  296. }
  297. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  298. {
  299. VERIFY(m_handles.contains(impl));
  300. m_handles.remove(impl);
  301. }
  302. void Heap::did_create_marked_vector(Badge<MarkedVectorBase>, MarkedVectorBase& vector)
  303. {
  304. VERIFY(!m_marked_vectors.contains(vector));
  305. m_marked_vectors.append(vector);
  306. }
  307. void Heap::did_destroy_marked_vector(Badge<MarkedVectorBase>, MarkedVectorBase& vector)
  308. {
  309. VERIFY(m_marked_vectors.contains(vector));
  310. m_marked_vectors.remove(vector);
  311. }
  312. void Heap::did_create_weak_container(Badge<WeakContainer>, WeakContainer& set)
  313. {
  314. VERIFY(!m_weak_containers.contains(set));
  315. m_weak_containers.append(set);
  316. }
  317. void Heap::did_destroy_weak_container(Badge<WeakContainer>, WeakContainer& set)
  318. {
  319. VERIFY(m_weak_containers.contains(set));
  320. m_weak_containers.remove(set);
  321. }
  322. void Heap::defer_gc(Badge<DeferGC>)
  323. {
  324. ++m_gc_deferrals;
  325. }
  326. void Heap::undefer_gc(Badge<DeferGC>)
  327. {
  328. VERIFY(m_gc_deferrals > 0);
  329. --m_gc_deferrals;
  330. if (!m_gc_deferrals) {
  331. if (m_should_gc_when_deferral_ends)
  332. collect_garbage();
  333. m_should_gc_when_deferral_ends = false;
  334. }
  335. }
  336. void Heap::uproot_cell(Cell* cell)
  337. {
  338. m_uprooted_cells.append(cell);
  339. }
  340. void register_safe_function_closure(void* base, size_t size)
  341. {
  342. if (!s_custom_ranges_for_conservative_scan) {
  343. // FIXME: This per-thread HashMap is currently leaked on thread exit.
  344. s_custom_ranges_for_conservative_scan = new HashMap<FlatPtr*, size_t>;
  345. }
  346. auto result = s_custom_ranges_for_conservative_scan->set(reinterpret_cast<FlatPtr*>(base), size);
  347. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  348. }
  349. void unregister_safe_function_closure(void* base, size_t)
  350. {
  351. VERIFY(s_custom_ranges_for_conservative_scan);
  352. bool did_remove = s_custom_ranges_for_conservative_scan->remove(reinterpret_cast<FlatPtr*>(base));
  353. VERIFY(did_remove);
  354. }
  355. }