Heap.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 <LibJS/Heap/Handle.h>
  29. #include <LibJS/Heap/Heap.h>
  30. #include <LibJS/Heap/HeapBlock.h>
  31. #include <LibJS/Interpreter.h>
  32. #include <LibJS/Runtime/MarkedValueList.h>
  33. #include <LibJS/Runtime/Object.h>
  34. #include <setjmp.h>
  35. #include <stdio.h>
  36. #ifdef __serenity__
  37. # include <serenity.h>
  38. #elif __linux__
  39. # include <pthread.h>
  40. #endif
  41. #ifdef __serenity__
  42. //#define HEAP_DEBUG
  43. #endif
  44. namespace JS {
  45. Heap::Heap(Interpreter& interpreter)
  46. : m_interpreter(interpreter)
  47. {
  48. }
  49. Heap::~Heap()
  50. {
  51. collect_garbage(CollectionType::CollectEverything);
  52. }
  53. Cell* Heap::allocate_cell(size_t size)
  54. {
  55. if (should_collect_on_every_allocation()) {
  56. collect_garbage();
  57. } else if (m_allocations_since_last_gc > m_max_allocations_between_gc) {
  58. m_allocations_since_last_gc = 0;
  59. collect_garbage();
  60. } else {
  61. ++m_allocations_since_last_gc;
  62. }
  63. for (auto& block : m_blocks) {
  64. if (size > block->cell_size())
  65. continue;
  66. if (auto* cell = block->allocate())
  67. return cell;
  68. }
  69. size_t cell_size = round_up_to_power_of_two(size, 16);
  70. auto block = HeapBlock::create_with_cell_size(*this, cell_size);
  71. auto* cell = block->allocate();
  72. m_blocks.append(move(block));
  73. return cell;
  74. }
  75. void Heap::collect_garbage(CollectionType collection_type)
  76. {
  77. if (collection_type == CollectionType::CollectGarbage) {
  78. if (m_gc_deferrals) {
  79. m_should_gc_when_deferral_ends = true;
  80. return;
  81. }
  82. HashTable<Cell*> roots;
  83. gather_roots(roots);
  84. mark_live_cells(roots);
  85. }
  86. sweep_dead_cells();
  87. }
  88. void Heap::gather_roots(HashTable<Cell*>& roots)
  89. {
  90. m_interpreter.gather_roots({}, roots);
  91. gather_conservative_roots(roots);
  92. for (auto* handle : m_handles)
  93. roots.set(handle->cell());
  94. for (auto* list : m_marked_value_lists) {
  95. for (auto& value : list->values()) {
  96. if (value.is_cell())
  97. roots.set(value.as_cell());
  98. }
  99. }
  100. #ifdef HEAP_DEBUG
  101. dbg() << "gather_roots:";
  102. for (auto* root : roots) {
  103. dbg() << " + " << root;
  104. }
  105. #endif
  106. }
  107. void Heap::gather_conservative_roots(HashTable<Cell*>& roots)
  108. {
  109. FlatPtr dummy;
  110. #ifdef HEAP_DEBUG
  111. dbg() << "gather_conservative_roots:";
  112. #endif
  113. jmp_buf buf;
  114. setjmp(buf);
  115. HashTable<FlatPtr> possible_pointers;
  116. const FlatPtr* raw_jmp_buf = reinterpret_cast<const FlatPtr*>(buf);
  117. for (size_t i = 0; i < sizeof(buf) / sizeof(FlatPtr); i += sizeof(FlatPtr))
  118. possible_pointers.set(raw_jmp_buf[i]);
  119. FlatPtr stack_base;
  120. size_t stack_size;
  121. #ifdef __serenity__
  122. if (get_stack_bounds(&stack_base, &stack_size) < 0) {
  123. perror("get_stack_bounds");
  124. ASSERT_NOT_REACHED();
  125. }
  126. #elif __linux__
  127. pthread_attr_t attr = {};
  128. if (int rc = pthread_getattr_np(pthread_self(), &attr) != 0) {
  129. fprintf(stderr, "pthread_getattr_np: %s\n", strerror(-rc));
  130. ASSERT_NOT_REACHED();
  131. }
  132. if (int rc = pthread_attr_getstack(&attr, (void**)&stack_base, &stack_size) != 0) {
  133. fprintf(stderr, "pthread_attr_getstack: %s\n", strerror(-rc));
  134. ASSERT_NOT_REACHED();
  135. }
  136. pthread_attr_destroy(&attr);
  137. #endif
  138. FlatPtr stack_reference = reinterpret_cast<FlatPtr>(&dummy);
  139. FlatPtr stack_top = stack_base + stack_size;
  140. for (FlatPtr stack_address = stack_reference; stack_address < stack_top; stack_address += sizeof(FlatPtr)) {
  141. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  142. possible_pointers.set(data);
  143. }
  144. for (auto possible_pointer : possible_pointers) {
  145. if (!possible_pointer)
  146. continue;
  147. #ifdef HEAP_DEBUG
  148. dbg() << " ? " << (const void*)possible_pointer;
  149. #endif
  150. if (auto* cell = cell_from_possible_pointer(possible_pointer)) {
  151. if (cell->is_live()) {
  152. #ifdef HEAP_DEBUG
  153. dbg() << " ?-> " << (const void*)cell;
  154. #endif
  155. roots.set(cell);
  156. } else {
  157. #ifdef HEAP_DEBUG
  158. dbg() << " #-> " << (const void*)cell;
  159. #endif
  160. }
  161. }
  162. }
  163. }
  164. Cell* Heap::cell_from_possible_pointer(FlatPtr pointer)
  165. {
  166. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<const Cell*>(pointer));
  167. if (m_blocks.find([possible_heap_block](auto& block) { return block.ptr() == possible_heap_block; }) == m_blocks.end())
  168. return nullptr;
  169. return possible_heap_block->cell_from_possible_pointer(pointer);
  170. }
  171. class MarkingVisitor final : public Cell::Visitor {
  172. public:
  173. MarkingVisitor() {}
  174. virtual void visit_impl(Cell* cell)
  175. {
  176. if (cell->is_marked())
  177. return;
  178. #ifdef HEAP_DEBUG
  179. dbg() << " ! " << cell;
  180. #endif
  181. cell->set_marked(true);
  182. cell->visit_children(*this);
  183. }
  184. };
  185. void Heap::mark_live_cells(const HashTable<Cell*>& roots)
  186. {
  187. #ifdef HEAP_DEBUG
  188. dbg() << "mark_live_cells:";
  189. #endif
  190. MarkingVisitor visitor;
  191. for (auto* root : roots)
  192. visitor.visit(root);
  193. }
  194. void Heap::sweep_dead_cells()
  195. {
  196. #ifdef HEAP_DEBUG
  197. dbg() << "sweep_dead_cells:";
  198. #endif
  199. Vector<HeapBlock*, 32> empty_blocks;
  200. for (auto& block : m_blocks) {
  201. bool block_has_live_cells = false;
  202. block->for_each_cell([&](Cell* cell) {
  203. if (cell->is_live()) {
  204. if (!cell->is_marked()) {
  205. #ifdef HEAP_DEBUG
  206. dbg() << " ~ " << cell;
  207. #endif
  208. block->deallocate(cell);
  209. } else {
  210. cell->set_marked(false);
  211. block_has_live_cells = true;
  212. }
  213. }
  214. });
  215. if (!block_has_live_cells)
  216. empty_blocks.append(block);
  217. }
  218. for (auto* block : empty_blocks) {
  219. #ifdef HEAP_DEBUG
  220. dbg() << " - Reclaim HeapBlock @ " << block << ": cell_size=" << block->cell_size();
  221. #endif
  222. m_blocks.remove_first_matching([block](auto& entry) { return entry == block; });
  223. }
  224. #ifdef HEAP_DEBUG
  225. for (auto& block : m_blocks) {
  226. dbg() << " > Live HeapBlock @ " << block << ": cell_size=" << block->cell_size();
  227. }
  228. #endif
  229. }
  230. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  231. {
  232. ASSERT(!m_handles.contains(&impl));
  233. m_handles.set(&impl);
  234. }
  235. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  236. {
  237. ASSERT(m_handles.contains(&impl));
  238. m_handles.remove(&impl);
  239. }
  240. void Heap::did_create_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  241. {
  242. ASSERT(!m_marked_value_lists.contains(&list));
  243. m_marked_value_lists.set(&list);
  244. }
  245. void Heap::did_destroy_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  246. {
  247. ASSERT(m_marked_value_lists.contains(&list));
  248. m_marked_value_lists.remove(&list);
  249. }
  250. void Heap::defer_gc(Badge<DeferGC>)
  251. {
  252. ++m_gc_deferrals;
  253. }
  254. void Heap::undefer_gc(Badge<DeferGC>)
  255. {
  256. ASSERT(m_gc_deferrals > 0);
  257. --m_gc_deferrals;
  258. if (!m_gc_deferrals) {
  259. if (m_should_gc_when_deferral_ends)
  260. collect_garbage();
  261. m_should_gc_when_deferral_ends = false;
  262. }
  263. }
  264. }