Heap.cpp 7.0 KB

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