Heap.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Badge.h>
  27. #include <AK/HashTable.h>
  28. #include <AK/StackInfo.h>
  29. #include <AK/TemporaryChange.h>
  30. #include <LibCore/ElapsedTimer.h>
  31. #include <LibJS/Heap/Allocator.h>
  32. #include <LibJS/Heap/Handle.h>
  33. #include <LibJS/Heap/Heap.h>
  34. #include <LibJS/Heap/HeapBlock.h>
  35. #include <LibJS/Interpreter.h>
  36. #include <LibJS/Runtime/Object.h>
  37. #include <setjmp.h>
  38. //#define HEAP_DEBUG
  39. namespace JS {
  40. Heap::Heap(VM& vm)
  41. : m_vm(vm)
  42. {
  43. m_allocators.append(make<Allocator>(16));
  44. m_allocators.append(make<Allocator>(32));
  45. m_allocators.append(make<Allocator>(64));
  46. m_allocators.append(make<Allocator>(128));
  47. m_allocators.append(make<Allocator>(256));
  48. m_allocators.append(make<Allocator>(512));
  49. m_allocators.append(make<Allocator>(1024));
  50. m_allocators.append(make<Allocator>(3172));
  51. }
  52. Heap::~Heap()
  53. {
  54. collect_garbage(CollectionType::CollectEverything);
  55. }
  56. ALWAYS_INLINE Allocator& 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. ASSERT_NOT_REACHED();
  63. }
  64. Cell* Heap::allocate_cell(size_t size)
  65. {
  66. if (should_collect_on_every_allocation()) {
  67. collect_garbage();
  68. } else if (m_allocations_since_last_gc > m_max_allocations_between_gc) {
  69. m_allocations_since_last_gc = 0;
  70. collect_garbage();
  71. } else {
  72. ++m_allocations_since_last_gc;
  73. }
  74. auto& allocator = allocator_for_size(size);
  75. return allocator.allocate_cell(*this);
  76. }
  77. void Heap::collect_garbage(CollectionType collection_type, bool print_report)
  78. {
  79. ASSERT(!m_collecting_garbage);
  80. TemporaryChange change(m_collecting_garbage, true);
  81. Core::ElapsedTimer collection_measurement_timer;
  82. collection_measurement_timer.start();
  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* list : m_marked_value_lists) {
  101. for (auto& value : list->values()) {
  102. if (value.is_cell())
  103. roots.set(value.as_cell());
  104. }
  105. }
  106. #ifdef HEAP_DEBUG
  107. dbg() << "gather_roots:";
  108. for (auto* root : roots) {
  109. dbg() << " + " << root;
  110. }
  111. #endif
  112. }
  113. void Heap::gather_conservative_roots(HashTable<Cell*>& roots)
  114. {
  115. FlatPtr dummy;
  116. #ifdef HEAP_DEBUG
  117. dbg() << "gather_conservative_roots:";
  118. #endif
  119. jmp_buf buf;
  120. setjmp(buf);
  121. HashTable<FlatPtr> possible_pointers;
  122. const FlatPtr* raw_jmp_buf = reinterpret_cast<const FlatPtr*>(buf);
  123. for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); i += sizeof(FlatPtr))
  124. possible_pointers.set(raw_jmp_buf[i]);
  125. FlatPtr stack_reference = reinterpret_cast<FlatPtr>(&dummy);
  126. auto& stack_info = m_vm.stack_info();
  127. for (FlatPtr stack_address = stack_reference; stack_address < stack_info.top(); stack_address += sizeof(FlatPtr)) {
  128. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  129. possible_pointers.set(data);
  130. }
  131. HashTable<HeapBlock*> all_live_heap_blocks;
  132. for_each_block([&](auto& block) {
  133. all_live_heap_blocks.set(&block);
  134. return IterationDecision::Continue;
  135. });
  136. for (auto possible_pointer : possible_pointers) {
  137. if (!possible_pointer)
  138. continue;
  139. #ifdef HEAP_DEBUG
  140. dbg() << " ? " << (const void*)possible_pointer;
  141. #endif
  142. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<const Cell*>(possible_pointer));
  143. if (all_live_heap_blocks.contains(possible_heap_block)) {
  144. if (auto* cell = possible_heap_block->cell_from_possible_pointer(possible_pointer)) {
  145. if (cell->is_live()) {
  146. #ifdef HEAP_DEBUG
  147. dbg() << " ?-> " << (const void*)cell;
  148. #endif
  149. roots.set(cell);
  150. } else {
  151. #ifdef HEAP_DEBUG
  152. dbg() << " #-> " << (const void*)cell;
  153. #endif
  154. }
  155. }
  156. }
  157. }
  158. }
  159. class MarkingVisitor final : public Cell::Visitor {
  160. public:
  161. MarkingVisitor() { }
  162. virtual void visit_impl(Cell* cell)
  163. {
  164. if (cell->is_marked())
  165. return;
  166. #ifdef HEAP_DEBUG
  167. dbg() << " ! " << cell;
  168. #endif
  169. cell->set_marked(true);
  170. cell->visit_edges(*this);
  171. }
  172. };
  173. void Heap::mark_live_cells(const HashTable<Cell*>& roots)
  174. {
  175. #ifdef HEAP_DEBUG
  176. dbg() << "mark_live_cells:";
  177. #endif
  178. MarkingVisitor visitor;
  179. for (auto* root : roots)
  180. visitor.visit(root);
  181. }
  182. void Heap::sweep_dead_cells(bool print_report, const Core::ElapsedTimer& measurement_timer)
  183. {
  184. #ifdef HEAP_DEBUG
  185. dbg() << "sweep_dead_cells:";
  186. #endif
  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.for_each_cell([&](Cell* cell) {
  197. if (cell->is_live()) {
  198. if (!cell->is_marked()) {
  199. #ifdef HEAP_DEBUG
  200. dbg() << " ~ " << cell;
  201. #endif
  202. block.deallocate(cell);
  203. ++collected_cells;
  204. collected_cell_bytes += block.cell_size();
  205. } else {
  206. cell->set_marked(false);
  207. block_has_live_cells = true;
  208. ++live_cells;
  209. live_cell_bytes += block.cell_size();
  210. }
  211. }
  212. });
  213. if (!block_has_live_cells)
  214. empty_blocks.append(&block);
  215. else if (block_was_full != block.is_full())
  216. full_blocks_that_became_usable.append(&block);
  217. return IterationDecision::Continue;
  218. });
  219. for (auto* block : empty_blocks) {
  220. #ifdef HEAP_DEBUG
  221. dbg() << " - HeapBlock empty @ " << block << ": cell_size=" << block->cell_size();
  222. #endif
  223. allocator_for_size(block->cell_size()).block_did_become_empty({}, *block);
  224. }
  225. for (auto* block : full_blocks_that_became_usable) {
  226. #ifdef HEAP_DEBUG
  227. dbg() << " - HeapBlock usable again @ " << block << ": cell_size=" << block->cell_size();
  228. #endif
  229. allocator_for_size(block->cell_size()).block_did_become_usable({}, *block);
  230. }
  231. #ifdef HEAP_DEBUG
  232. for_each_block([&](auto& block) {
  233. dbg() << " > Live HeapBlock @ " << &block << ": cell_size=" << block.cell_size();
  234. return IterationDecision::Continue;
  235. });
  236. #endif
  237. int time_spent = measurement_timer.elapsed();
  238. if (print_report) {
  239. size_t live_block_count = 0;
  240. for_each_block([&](auto&) {
  241. ++live_block_count;
  242. return IterationDecision::Continue;
  243. });
  244. dbgln("Garbage collection report");
  245. dbgln("=============================================");
  246. dbgln(" Time spent: {} ms", time_spent);
  247. dbgln(" Live cells: {} ({} bytes)", live_cells, live_cell_bytes);
  248. dbgln("Collected cells: {} ({} bytes)", collected_cells, collected_cell_bytes);
  249. dbgln(" Live blocks: {} ({} bytes)", live_block_count, live_block_count * HeapBlock::block_size);
  250. dbgln(" Freed blocks: {} ({} bytes)", empty_blocks.size(), empty_blocks.size() * HeapBlock::block_size);
  251. dbgln("=============================================");
  252. }
  253. }
  254. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  255. {
  256. ASSERT(!m_handles.contains(&impl));
  257. m_handles.set(&impl);
  258. }
  259. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  260. {
  261. ASSERT(m_handles.contains(&impl));
  262. m_handles.remove(&impl);
  263. }
  264. void Heap::did_create_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  265. {
  266. ASSERT(!m_marked_value_lists.contains(&list));
  267. m_marked_value_lists.set(&list);
  268. }
  269. void Heap::did_destroy_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  270. {
  271. ASSERT(m_marked_value_lists.contains(&list));
  272. m_marked_value_lists.remove(&list);
  273. }
  274. void Heap::defer_gc(Badge<DeferGC>)
  275. {
  276. ++m_gc_deferrals;
  277. }
  278. void Heap::undefer_gc(Badge<DeferGC>)
  279. {
  280. ASSERT(m_gc_deferrals > 0);
  281. --m_gc_deferrals;
  282. if (!m_gc_deferrals) {
  283. if (m_should_gc_when_deferral_ends)
  284. collect_garbage();
  285. m_should_gc_when_deferral_ends = false;
  286. }
  287. }
  288. }