Heap.cpp 14 KB

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