Heap.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Badge.h>
  8. #include <AK/Debug.h>
  9. #include <AK/HashTable.h>
  10. #include <AK/JsonArray.h>
  11. #include <AK/JsonObject.h>
  12. #include <AK/StackInfo.h>
  13. #include <AK/TemporaryChange.h>
  14. #include <LibCore/ElapsedTimer.h>
  15. #include <LibJS/Bytecode/Interpreter.h>
  16. #include <LibJS/Heap/CellAllocator.h>
  17. #include <LibJS/Heap/Handle.h>
  18. #include <LibJS/Heap/Heap.h>
  19. #include <LibJS/Heap/HeapBlock.h>
  20. #include <LibJS/Runtime/Object.h>
  21. #include <LibJS/Runtime/WeakContainer.h>
  22. #include <LibJS/SafeFunction.h>
  23. #include <setjmp.h>
  24. #ifdef AK_OS_SERENITY
  25. # include <serenity.h>
  26. #endif
  27. #ifdef HAS_ADDRESS_SANITIZER
  28. # include <sanitizer/asan_interface.h>
  29. #endif
  30. namespace JS {
  31. #ifdef AK_OS_SERENITY
  32. static int gc_perf_string_id;
  33. #endif
  34. // NOTE: We keep a per-thread list of custom ranges. This hinges on the assumption that there is one JS VM per thread.
  35. static __thread HashMap<FlatPtr*, size_t>* s_custom_ranges_for_conservative_scan = nullptr;
  36. static __thread HashMap<FlatPtr*, SourceLocation*>* s_safe_function_locations = nullptr;
  37. Heap::Heap(VM& vm)
  38. : HeapBase(vm)
  39. {
  40. #ifdef AK_OS_SERENITY
  41. auto gc_signpost_string = "Garbage collection"sv;
  42. gc_perf_string_id = perf_register_string(gc_signpost_string.characters_without_null_termination(), gc_signpost_string.length());
  43. #endif
  44. if constexpr (HeapBlock::min_possible_cell_size <= 16) {
  45. m_allocators.append(make<CellAllocator>(16));
  46. }
  47. static_assert(HeapBlock::min_possible_cell_size <= 24, "Heap Cell tracking uses too much data!");
  48. m_allocators.append(make<CellAllocator>(32));
  49. m_allocators.append(make<CellAllocator>(64));
  50. m_allocators.append(make<CellAllocator>(96));
  51. m_allocators.append(make<CellAllocator>(128));
  52. m_allocators.append(make<CellAllocator>(256));
  53. m_allocators.append(make<CellAllocator>(512));
  54. m_allocators.append(make<CellAllocator>(1024));
  55. m_allocators.append(make<CellAllocator>(3072));
  56. }
  57. Heap::~Heap()
  58. {
  59. vm().string_cache().clear();
  60. vm().deprecated_string_cache().clear();
  61. collect_garbage(CollectionType::CollectEverything);
  62. }
  63. ALWAYS_INLINE CellAllocator& Heap::allocator_for_size(size_t cell_size)
  64. {
  65. for (auto& allocator : m_allocators) {
  66. if (allocator->cell_size() >= cell_size)
  67. return *allocator;
  68. }
  69. dbgln("Cannot get CellAllocator for cell size {}, largest available is {}!", cell_size, m_allocators.last()->cell_size());
  70. VERIFY_NOT_REACHED();
  71. }
  72. Cell* Heap::allocate_cell(size_t size)
  73. {
  74. if (should_collect_on_every_allocation()) {
  75. m_allocated_bytes_since_last_gc = 0;
  76. collect_garbage();
  77. } else if (m_allocated_bytes_since_last_gc + size > m_gc_bytes_threshold) {
  78. m_allocated_bytes_since_last_gc = 0;
  79. collect_garbage();
  80. }
  81. m_allocated_bytes_since_last_gc += size;
  82. auto& allocator = allocator_for_size(size);
  83. return allocator.allocate_cell(*this);
  84. }
  85. static void add_possible_value(HashMap<FlatPtr, HeapRoot>& possible_pointers, FlatPtr data, HeapRoot origin, FlatPtr min_block_address, FlatPtr max_block_address)
  86. {
  87. if constexpr (sizeof(FlatPtr*) == sizeof(Value)) {
  88. // Because Value stores pointers in non-canonical form we have to check if the top bytes
  89. // match any pointer-backed tag, in that case we have to extract the pointer to its
  90. // canonical form and add that as a possible pointer.
  91. FlatPtr possible_pointer;
  92. if ((data & SHIFTED_IS_CELL_PATTERN) == SHIFTED_IS_CELL_PATTERN)
  93. possible_pointer = Value::extract_pointer_bits(data);
  94. else
  95. possible_pointer = data;
  96. if (possible_pointer < min_block_address || possible_pointer > max_block_address)
  97. return;
  98. possible_pointers.set(possible_pointer, move(origin));
  99. } else {
  100. static_assert((sizeof(Value) % sizeof(FlatPtr*)) == 0);
  101. if (data < min_block_address || data > max_block_address)
  102. return;
  103. // In the 32-bit case we will look at the top and bottom part of Value separately we just
  104. // add both the upper and lower bytes as possible pointers.
  105. possible_pointers.set(data, move(origin));
  106. }
  107. }
  108. void Heap::find_min_and_max_block_addresses(FlatPtr& min_address, FlatPtr& max_address)
  109. {
  110. min_address = explode_byte(0xff);
  111. max_address = 0;
  112. for_each_block([&](auto& block) {
  113. min_address = min(min_address, reinterpret_cast<FlatPtr>(&block));
  114. max_address = max(max_address, reinterpret_cast<FlatPtr>(&block) + HeapBlockBase::block_size);
  115. return IterationDecision::Continue;
  116. });
  117. }
  118. template<typename Callback>
  119. static void for_each_cell_among_possible_pointers(HashTable<HeapBlock*> const& all_live_heap_blocks, HashMap<FlatPtr, HeapRoot>& possible_pointers, Callback callback)
  120. {
  121. for (auto possible_pointer : possible_pointers.keys()) {
  122. if (!possible_pointer)
  123. continue;
  124. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<Cell const*>(possible_pointer));
  125. if (!all_live_heap_blocks.contains(possible_heap_block))
  126. continue;
  127. if (auto* cell = possible_heap_block->cell_from_possible_pointer(possible_pointer)) {
  128. callback(cell, possible_pointer);
  129. }
  130. }
  131. }
  132. class GraphConstructorVisitor final : public Cell::Visitor {
  133. public:
  134. explicit GraphConstructorVisitor(Heap& heap, HashMap<Cell*, HeapRoot> const& roots)
  135. : m_heap(heap)
  136. {
  137. m_heap.find_min_and_max_block_addresses(m_min_block_address, m_max_block_address);
  138. m_heap.for_each_block([&](auto& block) {
  139. m_all_live_heap_blocks.set(&block);
  140. return IterationDecision::Continue;
  141. });
  142. for (auto* root : roots.keys()) {
  143. visit(root);
  144. auto& graph_node = m_graph.ensure(reinterpret_cast<FlatPtr>(root));
  145. graph_node.class_name = root->class_name();
  146. graph_node.root_origin = *roots.get(root);
  147. }
  148. }
  149. virtual void visit_impl(Cell& cell) override
  150. {
  151. if (m_node_being_visited)
  152. m_node_being_visited->edges.set(reinterpret_cast<FlatPtr>(&cell));
  153. if (m_graph.get(reinterpret_cast<FlatPtr>(&cell)).has_value())
  154. return;
  155. m_work_queue.append(cell);
  156. }
  157. virtual void visit_possible_values(ReadonlyBytes bytes) override
  158. {
  159. HashMap<FlatPtr, HeapRoot> possible_pointers;
  160. auto* raw_pointer_sized_values = reinterpret_cast<FlatPtr const*>(bytes.data());
  161. for (size_t i = 0; i < (bytes.size() / sizeof(FlatPtr)); ++i)
  162. add_possible_value(possible_pointers, raw_pointer_sized_values[i], HeapRoot { .type = HeapRoot::Type::HeapFunctionCapturedPointer }, m_min_block_address, m_max_block_address);
  163. for_each_cell_among_possible_pointers(m_all_live_heap_blocks, possible_pointers, [&](Cell* cell, FlatPtr) {
  164. if (m_node_being_visited)
  165. m_node_being_visited->edges.set(reinterpret_cast<FlatPtr>(&cell));
  166. if (m_graph.get(reinterpret_cast<FlatPtr>(&cell)).has_value())
  167. return;
  168. m_work_queue.append(*cell);
  169. });
  170. }
  171. void visit_all_cells()
  172. {
  173. while (!m_work_queue.is_empty()) {
  174. auto ptr = reinterpret_cast<FlatPtr>(&m_work_queue.last());
  175. m_node_being_visited = &m_graph.ensure(ptr);
  176. m_node_being_visited->class_name = m_work_queue.last().class_name();
  177. m_work_queue.take_last().visit_edges(*this);
  178. m_node_being_visited = nullptr;
  179. }
  180. }
  181. void dump()
  182. {
  183. auto graph = AK::JsonObject();
  184. for (auto& it : m_graph) {
  185. AK::JsonArray edges;
  186. for (auto const& value : it.value.edges) {
  187. edges.must_append(DeprecatedString::formatted("{}", value));
  188. }
  189. auto node = AK::JsonObject();
  190. if (it.value.root_origin.has_value()) {
  191. auto type = it.value.root_origin->type;
  192. auto location = it.value.root_origin->location;
  193. switch (type) {
  194. case HeapRoot::Type::Handle:
  195. node.set("root"sv, DeprecatedString::formatted("Handle {} {}:{}", location->function_name(), location->filename(), location->line_number()));
  196. break;
  197. case HeapRoot::Type::MarkedVector:
  198. node.set("root"sv, "MarkedVector");
  199. break;
  200. case HeapRoot::Type::RegisterPointer:
  201. node.set("root"sv, "RegisterPointer");
  202. break;
  203. case HeapRoot::Type::StackPointer:
  204. node.set("root"sv, "StackPointer");
  205. break;
  206. case HeapRoot::Type::VM:
  207. node.set("root"sv, "VM");
  208. break;
  209. case HeapRoot::Type::SafeFunction:
  210. node.set("root"sv, DeprecatedString::formatted("SafeFunction {} {}:{}", location->function_name(), location->filename(), location->line_number()));
  211. break;
  212. default:
  213. VERIFY_NOT_REACHED();
  214. }
  215. }
  216. node.set("class_name"sv, it.value.class_name);
  217. node.set("edges"sv, edges);
  218. graph.set(DeprecatedString::number(it.key), node);
  219. }
  220. dbgln("{}", graph.to_deprecated_string());
  221. }
  222. private:
  223. struct GraphNode {
  224. Optional<HeapRoot> root_origin;
  225. StringView class_name;
  226. HashTable<FlatPtr> edges {};
  227. };
  228. GraphNode* m_node_being_visited { nullptr };
  229. Vector<Cell&> m_work_queue;
  230. HashMap<FlatPtr, GraphNode> m_graph;
  231. Heap& m_heap;
  232. HashTable<HeapBlock*> m_all_live_heap_blocks;
  233. FlatPtr m_min_block_address;
  234. FlatPtr m_max_block_address;
  235. };
  236. void Heap::dump_graph()
  237. {
  238. HashMap<Cell*, HeapRoot> roots;
  239. gather_roots(roots);
  240. GraphConstructorVisitor visitor(*this, roots);
  241. vm().bytecode_interpreter().visit_edges(visitor);
  242. visitor.visit_all_cells();
  243. visitor.dump();
  244. }
  245. void Heap::collect_garbage(CollectionType collection_type, bool print_report)
  246. {
  247. VERIFY(!m_collecting_garbage);
  248. TemporaryChange change(m_collecting_garbage, true);
  249. #ifdef AK_OS_SERENITY
  250. static size_t global_gc_counter = 0;
  251. perf_event(PERF_EVENT_SIGNPOST, gc_perf_string_id, global_gc_counter++);
  252. #endif
  253. Core::ElapsedTimer collection_measurement_timer;
  254. if (print_report)
  255. collection_measurement_timer.start();
  256. if (collection_type == CollectionType::CollectGarbage) {
  257. if (m_gc_deferrals) {
  258. m_should_gc_when_deferral_ends = true;
  259. return;
  260. }
  261. HashMap<Cell*, HeapRoot> roots;
  262. gather_roots(roots);
  263. mark_live_cells(roots);
  264. }
  265. finalize_unmarked_cells();
  266. sweep_dead_cells(print_report, collection_measurement_timer);
  267. }
  268. void Heap::gather_roots(HashMap<Cell*, HeapRoot>& roots)
  269. {
  270. vm().gather_roots(roots);
  271. gather_conservative_roots(roots);
  272. for (auto& handle : m_handles)
  273. roots.set(handle.cell(), HeapRoot { .type = HeapRoot::Type::Handle, .location = &handle.source_location() });
  274. for (auto& vector : m_marked_vectors)
  275. vector.gather_roots(roots);
  276. if constexpr (HEAP_DEBUG) {
  277. dbgln("gather_roots:");
  278. for (auto* root : roots.keys())
  279. dbgln(" + {}", root);
  280. }
  281. }
  282. #ifdef HAS_ADDRESS_SANITIZER
  283. __attribute__((no_sanitize("address"))) void Heap::gather_asan_fake_stack_roots(HashMap<FlatPtr, HeapRoot>& possible_pointers, FlatPtr addr, FlatPtr min_block_address, FlatPtr max_block_address)
  284. {
  285. void* begin = nullptr;
  286. void* end = nullptr;
  287. void* real_stack = __asan_addr_is_in_fake_stack(__asan_get_current_fake_stack(), reinterpret_cast<void*>(addr), &begin, &end);
  288. if (real_stack != nullptr) {
  289. for (auto* real_stack_addr = reinterpret_cast<void const* const*>(begin); real_stack_addr < end; ++real_stack_addr) {
  290. void const* real_address = *real_stack_addr;
  291. if (real_address == nullptr)
  292. continue;
  293. add_possible_value(possible_pointers, reinterpret_cast<FlatPtr>(real_address), HeapRoot { .type = HeapRoot::Type::StackPointer }, min_block_address, max_block_address);
  294. }
  295. }
  296. }
  297. #else
  298. void Heap::gather_asan_fake_stack_roots(HashMap<FlatPtr, HeapRoot>&, FlatPtr, FlatPtr, FlatPtr)
  299. {
  300. }
  301. #endif
  302. __attribute__((no_sanitize("address"))) void Heap::gather_conservative_roots(HashMap<Cell*, HeapRoot>& roots)
  303. {
  304. FlatPtr dummy;
  305. dbgln_if(HEAP_DEBUG, "gather_conservative_roots:");
  306. jmp_buf buf;
  307. setjmp(buf);
  308. HashMap<FlatPtr, HeapRoot> possible_pointers;
  309. auto* raw_jmp_buf = reinterpret_cast<FlatPtr const*>(buf);
  310. FlatPtr min_block_address, max_block_address;
  311. find_min_and_max_block_addresses(min_block_address, max_block_address);
  312. for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); ++i)
  313. add_possible_value(possible_pointers, raw_jmp_buf[i], HeapRoot { .type = HeapRoot::Type::RegisterPointer }, min_block_address, max_block_address);
  314. auto stack_reference = bit_cast<FlatPtr>(&dummy);
  315. auto& stack_info = m_vm.stack_info();
  316. for (FlatPtr stack_address = stack_reference; stack_address < stack_info.top(); stack_address += sizeof(FlatPtr)) {
  317. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  318. add_possible_value(possible_pointers, data, HeapRoot { .type = HeapRoot::Type::StackPointer }, min_block_address, max_block_address);
  319. gather_asan_fake_stack_roots(possible_pointers, data, min_block_address, max_block_address);
  320. }
  321. // NOTE: If we have any custom ranges registered, scan those as well.
  322. // This is where JS::SafeFunction closures get marked.
  323. if (s_custom_ranges_for_conservative_scan) {
  324. for (auto& custom_range : *s_custom_ranges_for_conservative_scan) {
  325. for (size_t i = 0; i < (custom_range.value / sizeof(FlatPtr)); ++i) {
  326. auto safe_function_location = s_safe_function_locations->get(custom_range.key);
  327. add_possible_value(possible_pointers, custom_range.key[i], HeapRoot { .type = HeapRoot::Type::SafeFunction, .location = *safe_function_location }, min_block_address, max_block_address);
  328. }
  329. }
  330. }
  331. HashTable<HeapBlock*> all_live_heap_blocks;
  332. for_each_block([&](auto& block) {
  333. all_live_heap_blocks.set(&block);
  334. return IterationDecision::Continue;
  335. });
  336. for_each_cell_among_possible_pointers(all_live_heap_blocks, possible_pointers, [&](Cell* cell, FlatPtr possible_pointer) {
  337. if (cell->state() == Cell::State::Live) {
  338. dbgln_if(HEAP_DEBUG, " ?-> {}", (void const*)cell);
  339. roots.set(cell, *possible_pointers.get(possible_pointer));
  340. } else {
  341. dbgln_if(HEAP_DEBUG, " #-> {}", (void const*)cell);
  342. }
  343. });
  344. }
  345. class MarkingVisitor final : public Cell::Visitor {
  346. public:
  347. explicit MarkingVisitor(Heap& heap, HashMap<Cell*, HeapRoot> const& roots)
  348. : m_heap(heap)
  349. {
  350. m_heap.find_min_and_max_block_addresses(m_min_block_address, m_max_block_address);
  351. m_heap.for_each_block([&](auto& block) {
  352. m_all_live_heap_blocks.set(&block);
  353. return IterationDecision::Continue;
  354. });
  355. for (auto* root : roots.keys()) {
  356. visit(root);
  357. }
  358. }
  359. virtual void visit_impl(Cell& cell) override
  360. {
  361. if (cell.is_marked())
  362. return;
  363. dbgln_if(HEAP_DEBUG, " ! {}", &cell);
  364. cell.set_marked(true);
  365. m_work_queue.append(cell);
  366. }
  367. virtual void visit_possible_values(ReadonlyBytes bytes) override
  368. {
  369. HashMap<FlatPtr, HeapRoot> possible_pointers;
  370. auto* raw_pointer_sized_values = reinterpret_cast<FlatPtr const*>(bytes.data());
  371. for (size_t i = 0; i < (bytes.size() / sizeof(FlatPtr)); ++i)
  372. add_possible_value(possible_pointers, raw_pointer_sized_values[i], HeapRoot { .type = HeapRoot::Type::HeapFunctionCapturedPointer }, m_min_block_address, m_max_block_address);
  373. for_each_cell_among_possible_pointers(m_all_live_heap_blocks, possible_pointers, [&](Cell* cell, FlatPtr) {
  374. if (cell->is_marked())
  375. return;
  376. if (cell->state() != Cell::State::Live)
  377. return;
  378. cell->set_marked(true);
  379. m_work_queue.append(*cell);
  380. });
  381. }
  382. void mark_all_live_cells()
  383. {
  384. while (!m_work_queue.is_empty()) {
  385. m_work_queue.take_last().visit_edges(*this);
  386. }
  387. }
  388. private:
  389. Heap& m_heap;
  390. Vector<Cell&> m_work_queue;
  391. HashTable<HeapBlock*> m_all_live_heap_blocks;
  392. FlatPtr m_min_block_address;
  393. FlatPtr m_max_block_address;
  394. };
  395. void Heap::mark_live_cells(HashMap<Cell*, HeapRoot> const& roots)
  396. {
  397. dbgln_if(HEAP_DEBUG, "mark_live_cells:");
  398. MarkingVisitor visitor(*this, roots);
  399. vm().bytecode_interpreter().visit_edges(visitor);
  400. visitor.mark_all_live_cells();
  401. for (auto& inverse_root : m_uprooted_cells)
  402. inverse_root->set_marked(false);
  403. m_uprooted_cells.clear();
  404. }
  405. bool Heap::cell_must_survive_garbage_collection(Cell const& cell)
  406. {
  407. if (!cell.overrides_must_survive_garbage_collection({}))
  408. return false;
  409. return cell.must_survive_garbage_collection();
  410. }
  411. void Heap::finalize_unmarked_cells()
  412. {
  413. for_each_block([&](auto& block) {
  414. block.template for_each_cell_in_state<Cell::State::Live>([](Cell* cell) {
  415. if (!cell->is_marked() && !cell_must_survive_garbage_collection(*cell))
  416. cell->finalize();
  417. });
  418. return IterationDecision::Continue;
  419. });
  420. }
  421. void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measurement_timer)
  422. {
  423. dbgln_if(HEAP_DEBUG, "sweep_dead_cells:");
  424. Vector<HeapBlock*, 32> empty_blocks;
  425. Vector<HeapBlock*, 32> full_blocks_that_became_usable;
  426. size_t collected_cells = 0;
  427. size_t live_cells = 0;
  428. size_t collected_cell_bytes = 0;
  429. size_t live_cell_bytes = 0;
  430. for_each_block([&](auto& block) {
  431. bool block_has_live_cells = false;
  432. bool block_was_full = block.is_full();
  433. block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
  434. if (!cell->is_marked() && !cell_must_survive_garbage_collection(*cell)) {
  435. dbgln_if(HEAP_DEBUG, " ~ {}", cell);
  436. block.deallocate(cell);
  437. ++collected_cells;
  438. collected_cell_bytes += block.cell_size();
  439. } else {
  440. cell->set_marked(false);
  441. block_has_live_cells = true;
  442. ++live_cells;
  443. live_cell_bytes += block.cell_size();
  444. }
  445. });
  446. if (!block_has_live_cells)
  447. empty_blocks.append(&block);
  448. else if (block_was_full != block.is_full())
  449. full_blocks_that_became_usable.append(&block);
  450. return IterationDecision::Continue;
  451. });
  452. for (auto& weak_container : m_weak_containers)
  453. weak_container.remove_dead_cells({});
  454. for (auto* block : empty_blocks) {
  455. dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", block, block->cell_size());
  456. allocator_for_size(block->cell_size()).block_did_become_empty({}, *block);
  457. }
  458. for (auto* block : full_blocks_that_became_usable) {
  459. dbgln_if(HEAP_DEBUG, " - HeapBlock usable again @ {}: cell_size={}", block, block->cell_size());
  460. allocator_for_size(block->cell_size()).block_did_become_usable({}, *block);
  461. }
  462. if constexpr (HEAP_DEBUG) {
  463. for_each_block([&](auto& block) {
  464. dbgln(" > Live HeapBlock @ {}: cell_size={}", &block, block.cell_size());
  465. return IterationDecision::Continue;
  466. });
  467. }
  468. m_gc_bytes_threshold = live_cell_bytes > GC_MIN_BYTES_THRESHOLD ? live_cell_bytes : GC_MIN_BYTES_THRESHOLD;
  469. if (print_report) {
  470. Duration const time_spent = measurement_timer.elapsed_time();
  471. size_t live_block_count = 0;
  472. for_each_block([&](auto&) {
  473. ++live_block_count;
  474. return IterationDecision::Continue;
  475. });
  476. dbgln("Garbage collection report");
  477. dbgln("=============================================");
  478. dbgln(" Time spent: {} ms", time_spent.to_milliseconds());
  479. dbgln(" Live cells: {} ({} bytes)", live_cells, live_cell_bytes);
  480. dbgln("Collected cells: {} ({} bytes)", collected_cells, collected_cell_bytes);
  481. dbgln(" Live blocks: {} ({} bytes)", live_block_count, live_block_count * HeapBlock::block_size);
  482. dbgln(" Freed blocks: {} ({} bytes)", empty_blocks.size(), empty_blocks.size() * HeapBlock::block_size);
  483. dbgln("=============================================");
  484. }
  485. }
  486. void Heap::defer_gc()
  487. {
  488. ++m_gc_deferrals;
  489. }
  490. void Heap::undefer_gc()
  491. {
  492. VERIFY(m_gc_deferrals > 0);
  493. --m_gc_deferrals;
  494. if (!m_gc_deferrals) {
  495. if (m_should_gc_when_deferral_ends)
  496. collect_garbage();
  497. m_should_gc_when_deferral_ends = false;
  498. }
  499. }
  500. void Heap::uproot_cell(Cell* cell)
  501. {
  502. m_uprooted_cells.append(cell);
  503. }
  504. void register_safe_function_closure(void* base, size_t size, SourceLocation* location)
  505. {
  506. if (!s_custom_ranges_for_conservative_scan) {
  507. // FIXME: This per-thread HashMap is currently leaked on thread exit.
  508. s_custom_ranges_for_conservative_scan = new HashMap<FlatPtr*, size_t>;
  509. }
  510. if (!s_safe_function_locations) {
  511. s_safe_function_locations = new HashMap<FlatPtr*, SourceLocation*>;
  512. }
  513. auto result = s_custom_ranges_for_conservative_scan->set(reinterpret_cast<FlatPtr*>(base), size);
  514. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  515. result = s_safe_function_locations->set(reinterpret_cast<FlatPtr*>(base), location);
  516. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  517. }
  518. void unregister_safe_function_closure(void* base, size_t, SourceLocation*)
  519. {
  520. VERIFY(s_custom_ranges_for_conservative_scan);
  521. bool did_remove_range = s_custom_ranges_for_conservative_scan->remove(reinterpret_cast<FlatPtr*>(base));
  522. VERIFY(did_remove_range);
  523. bool did_remove_location = s_safe_function_locations->remove(reinterpret_cast<FlatPtr*>(base));
  524. VERIFY(did_remove_location);
  525. }
  526. }