Heap.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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__ or __APPLE__
  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 < ((size_t)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. #elif __APPLE__
  138. stack_base = (FlatPtr)pthread_get_stackaddr_np(pthread_self());
  139. pthread_attr_t attr = {};
  140. if (int rc = pthread_attr_getstacksize(&attr, &stack_size) != 0) {
  141. fprintf(stderr, "pthread_attr_getstacksize: %s\n", strerror(-rc));
  142. ASSERT_NOT_REACHED();
  143. }
  144. pthread_attr_destroy(&attr);
  145. #endif
  146. FlatPtr stack_reference = reinterpret_cast<FlatPtr>(&dummy);
  147. FlatPtr stack_top = stack_base + stack_size;
  148. for (FlatPtr stack_address = stack_reference; stack_address < stack_top; stack_address += sizeof(FlatPtr)) {
  149. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  150. possible_pointers.set(data);
  151. }
  152. for (auto possible_pointer : possible_pointers) {
  153. if (!possible_pointer)
  154. continue;
  155. #ifdef HEAP_DEBUG
  156. dbg() << " ? " << (const void*)possible_pointer;
  157. #endif
  158. if (auto* cell = cell_from_possible_pointer(possible_pointer)) {
  159. if (cell->is_live()) {
  160. #ifdef HEAP_DEBUG
  161. dbg() << " ?-> " << (const void*)cell;
  162. #endif
  163. roots.set(cell);
  164. } else {
  165. #ifdef HEAP_DEBUG
  166. dbg() << " #-> " << (const void*)cell;
  167. #endif
  168. }
  169. }
  170. }
  171. }
  172. Cell* Heap::cell_from_possible_pointer(FlatPtr pointer)
  173. {
  174. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<const Cell*>(pointer));
  175. if (m_blocks.find([possible_heap_block](auto& block) { return block.ptr() == possible_heap_block; }) == m_blocks.end())
  176. return nullptr;
  177. return possible_heap_block->cell_from_possible_pointer(pointer);
  178. }
  179. class MarkingVisitor final : public Cell::Visitor {
  180. public:
  181. MarkingVisitor() { }
  182. virtual void visit_impl(Cell* cell)
  183. {
  184. if (cell->is_marked())
  185. return;
  186. #ifdef HEAP_DEBUG
  187. dbg() << " ! " << cell;
  188. #endif
  189. cell->set_marked(true);
  190. cell->visit_children(*this);
  191. }
  192. };
  193. void Heap::mark_live_cells(const HashTable<Cell*>& roots)
  194. {
  195. #ifdef HEAP_DEBUG
  196. dbg() << "mark_live_cells:";
  197. #endif
  198. MarkingVisitor visitor;
  199. for (auto* root : roots)
  200. visitor.visit(root);
  201. }
  202. void Heap::sweep_dead_cells()
  203. {
  204. #ifdef HEAP_DEBUG
  205. dbg() << "sweep_dead_cells:";
  206. #endif
  207. Vector<HeapBlock*, 32> empty_blocks;
  208. for (auto& block : m_blocks) {
  209. bool block_has_live_cells = false;
  210. block->for_each_cell([&](Cell* cell) {
  211. if (cell->is_live()) {
  212. if (!cell->is_marked()) {
  213. #ifdef HEAP_DEBUG
  214. dbg() << " ~ " << cell;
  215. #endif
  216. block->deallocate(cell);
  217. } else {
  218. cell->set_marked(false);
  219. block_has_live_cells = true;
  220. }
  221. }
  222. });
  223. if (!block_has_live_cells)
  224. empty_blocks.append(block);
  225. }
  226. for (auto* block : empty_blocks) {
  227. #ifdef HEAP_DEBUG
  228. dbg() << " - Reclaim HeapBlock @ " << block << ": cell_size=" << block->cell_size();
  229. #endif
  230. m_blocks.remove_first_matching([block](auto& entry) { return entry == block; });
  231. }
  232. #ifdef HEAP_DEBUG
  233. for (auto& block : m_blocks) {
  234. dbg() << " > Live HeapBlock @ " << block << ": cell_size=" << block->cell_size();
  235. }
  236. #endif
  237. }
  238. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  239. {
  240. ASSERT(!m_handles.contains(&impl));
  241. m_handles.set(&impl);
  242. }
  243. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  244. {
  245. ASSERT(m_handles.contains(&impl));
  246. m_handles.remove(&impl);
  247. }
  248. void Heap::did_create_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  249. {
  250. ASSERT(!m_marked_value_lists.contains(&list));
  251. m_marked_value_lists.set(&list);
  252. }
  253. void Heap::did_destroy_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  254. {
  255. ASSERT(m_marked_value_lists.contains(&list));
  256. m_marked_value_lists.remove(&list);
  257. }
  258. void Heap::defer_gc(Badge<DeferGC>)
  259. {
  260. ++m_gc_deferrals;
  261. }
  262. void Heap::undefer_gc(Badge<DeferGC>)
  263. {
  264. ASSERT(m_gc_deferrals > 0);
  265. --m_gc_deferrals;
  266. if (!m_gc_deferrals) {
  267. if (m_should_gc_when_deferral_ends)
  268. collect_garbage();
  269. m_should_gc_when_deferral_ends = false;
  270. }
  271. }
  272. }