Heap.cpp 14 KB

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