Heap.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. dbgln("gather_roots:");
  108. for (auto* root : roots)
  109. dbgln(" + {}", root);
  110. #endif
  111. }
  112. void Heap::gather_conservative_roots(HashTable<Cell*>& roots)
  113. {
  114. FlatPtr dummy;
  115. #ifdef HEAP_DEBUG
  116. dbgln("gather_conservative_roots:");
  117. #endif
  118. jmp_buf buf;
  119. setjmp(buf);
  120. HashTable<FlatPtr> possible_pointers;
  121. const FlatPtr* raw_jmp_buf = reinterpret_cast<const FlatPtr*>(buf);
  122. for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); i += sizeof(FlatPtr))
  123. possible_pointers.set(raw_jmp_buf[i]);
  124. FlatPtr stack_reference = reinterpret_cast<FlatPtr>(&dummy);
  125. auto& stack_info = m_vm.stack_info();
  126. for (FlatPtr stack_address = stack_reference; stack_address < stack_info.top(); stack_address += sizeof(FlatPtr)) {
  127. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  128. possible_pointers.set(data);
  129. }
  130. HashTable<HeapBlock*> all_live_heap_blocks;
  131. for_each_block([&](auto& block) {
  132. all_live_heap_blocks.set(&block);
  133. return IterationDecision::Continue;
  134. });
  135. for (auto possible_pointer : possible_pointers) {
  136. if (!possible_pointer)
  137. continue;
  138. #ifdef HEAP_DEBUG
  139. dbgln(" ? {}", (const void*)possible_pointer);
  140. #endif
  141. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<const Cell*>(possible_pointer));
  142. if (all_live_heap_blocks.contains(possible_heap_block)) {
  143. if (auto* cell = possible_heap_block->cell_from_possible_pointer(possible_pointer)) {
  144. if (cell->is_live()) {
  145. #ifdef HEAP_DEBUG
  146. dbgln(" ?-> {}", (const void*)cell);
  147. #endif
  148. roots.set(cell);
  149. } else {
  150. #ifdef HEAP_DEBUG
  151. dbgln(" #-> {}", (const void*)cell);
  152. #endif
  153. }
  154. }
  155. }
  156. }
  157. }
  158. class MarkingVisitor final : public Cell::Visitor {
  159. public:
  160. MarkingVisitor() { }
  161. virtual void visit_impl(Cell* cell)
  162. {
  163. if (cell->is_marked())
  164. return;
  165. #ifdef HEAP_DEBUG
  166. dbgln(" ! {}", cell);
  167. #endif
  168. cell->set_marked(true);
  169. cell->visit_edges(*this);
  170. }
  171. };
  172. void Heap::mark_live_cells(const HashTable<Cell*>& roots)
  173. {
  174. #ifdef HEAP_DEBUG
  175. dbgln("mark_live_cells:");
  176. #endif
  177. MarkingVisitor visitor;
  178. for (auto* root : roots)
  179. visitor.visit(root);
  180. }
  181. void Heap::sweep_dead_cells(bool print_report, const Core::ElapsedTimer& measurement_timer)
  182. {
  183. #ifdef HEAP_DEBUG
  184. dbgln("sweep_dead_cells:");
  185. #endif
  186. Vector<HeapBlock*, 32> empty_blocks;
  187. Vector<HeapBlock*, 32> full_blocks_that_became_usable;
  188. size_t collected_cells = 0;
  189. size_t live_cells = 0;
  190. size_t collected_cell_bytes = 0;
  191. size_t live_cell_bytes = 0;
  192. for_each_block([&](auto& block) {
  193. bool block_has_live_cells = false;
  194. bool block_was_full = block.is_full();
  195. block.for_each_cell([&](Cell* cell) {
  196. if (cell->is_live()) {
  197. if (!cell->is_marked()) {
  198. #ifdef HEAP_DEBUG
  199. dbgln(" ~ {}", cell);
  200. #endif
  201. block.deallocate(cell);
  202. ++collected_cells;
  203. collected_cell_bytes += block.cell_size();
  204. } else {
  205. cell->set_marked(false);
  206. block_has_live_cells = true;
  207. ++live_cells;
  208. live_cell_bytes += block.cell_size();
  209. }
  210. }
  211. });
  212. if (!block_has_live_cells)
  213. empty_blocks.append(&block);
  214. else if (block_was_full != block.is_full())
  215. full_blocks_that_became_usable.append(&block);
  216. return IterationDecision::Continue;
  217. });
  218. for (auto* block : empty_blocks) {
  219. #ifdef HEAP_DEBUG
  220. dbgln(" - HeapBlock empty @ {}: cell_size={}", block, block->cell_size());
  221. #endif
  222. allocator_for_size(block->cell_size()).block_did_become_empty({}, *block);
  223. }
  224. for (auto* block : full_blocks_that_became_usable) {
  225. #ifdef HEAP_DEBUG
  226. dbgln(" - HeapBlock usable again @ {}: cell_size={}", block, block->cell_size());
  227. #endif
  228. allocator_for_size(block->cell_size()).block_did_become_usable({}, *block);
  229. }
  230. #ifdef HEAP_DEBUG
  231. for_each_block([&](auto& block) {
  232. dbgln(" > Live HeapBlock @ {}: cell_size={}", &block, block.cell_size());
  233. return IterationDecision::Continue;
  234. });
  235. #endif
  236. int time_spent = measurement_timer.elapsed();
  237. if (print_report) {
  238. size_t live_block_count = 0;
  239. for_each_block([&](auto&) {
  240. ++live_block_count;
  241. return IterationDecision::Continue;
  242. });
  243. dbgln("Garbage collection report");
  244. dbgln("=============================================");
  245. dbgln(" Time spent: {} ms", time_spent);
  246. dbgln(" Live cells: {} ({} bytes)", live_cells, live_cell_bytes);
  247. dbgln("Collected cells: {} ({} bytes)", collected_cells, collected_cell_bytes);
  248. dbgln(" Live blocks: {} ({} bytes)", live_block_count, live_block_count * HeapBlock::block_size);
  249. dbgln(" Freed blocks: {} ({} bytes)", empty_blocks.size(), empty_blocks.size() * HeapBlock::block_size);
  250. dbgln("=============================================");
  251. }
  252. }
  253. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  254. {
  255. ASSERT(!m_handles.contains(&impl));
  256. m_handles.set(&impl);
  257. }
  258. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  259. {
  260. ASSERT(m_handles.contains(&impl));
  261. m_handles.remove(&impl);
  262. }
  263. void Heap::did_create_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  264. {
  265. ASSERT(!m_marked_value_lists.contains(&list));
  266. m_marked_value_lists.set(&list);
  267. }
  268. void Heap::did_destroy_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  269. {
  270. ASSERT(m_marked_value_lists.contains(&list));
  271. m_marked_value_lists.remove(&list);
  272. }
  273. void Heap::defer_gc(Badge<DeferGC>)
  274. {
  275. ++m_gc_deferrals;
  276. }
  277. void Heap::undefer_gc(Badge<DeferGC>)
  278. {
  279. ASSERT(m_gc_deferrals > 0);
  280. --m_gc_deferrals;
  281. if (!m_gc_deferrals) {
  282. if (m_should_gc_when_deferral_ends)
  283. collect_garbage();
  284. m_should_gc_when_deferral_ends = false;
  285. }
  286. }
  287. }