Heap.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 <LibCore/ElapsedTimer.h>
  29. #include <LibJS/Heap/Handle.h>
  30. #include <LibJS/Heap/Heap.h>
  31. #include <LibJS/Heap/HeapBlock.h>
  32. #include <LibJS/Interpreter.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, bool print_report)
  76. {
  77. Core::ElapsedTimer collection_measurement_timer;
  78. collection_measurement_timer.start();
  79. if (collection_type == CollectionType::CollectGarbage) {
  80. if (m_gc_deferrals) {
  81. m_should_gc_when_deferral_ends = true;
  82. return;
  83. }
  84. HashTable<Cell*> roots;
  85. gather_roots(roots);
  86. mark_live_cells(roots);
  87. }
  88. sweep_dead_cells(print_report, collection_measurement_timer);
  89. }
  90. void Heap::gather_roots(HashTable<Cell*>& roots)
  91. {
  92. m_interpreter.gather_roots({}, roots);
  93. gather_conservative_roots(roots);
  94. for (auto* handle : m_handles)
  95. roots.set(handle->cell());
  96. for (auto* list : m_marked_value_lists) {
  97. for (auto& value : list->values()) {
  98. if (value.is_cell())
  99. roots.set(value.as_cell());
  100. }
  101. }
  102. #ifdef HEAP_DEBUG
  103. dbg() << "gather_roots:";
  104. for (auto* root : roots) {
  105. dbg() << " + " << root;
  106. }
  107. #endif
  108. }
  109. void Heap::gather_conservative_roots(HashTable<Cell*>& roots)
  110. {
  111. FlatPtr dummy;
  112. #ifdef HEAP_DEBUG
  113. dbg() << "gather_conservative_roots:";
  114. #endif
  115. jmp_buf buf;
  116. setjmp(buf);
  117. HashTable<FlatPtr> possible_pointers;
  118. const FlatPtr* raw_jmp_buf = reinterpret_cast<const FlatPtr*>(buf);
  119. for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); i += sizeof(FlatPtr))
  120. possible_pointers.set(raw_jmp_buf[i]);
  121. FlatPtr stack_base;
  122. size_t stack_size;
  123. #ifdef __serenity__
  124. if (get_stack_bounds(&stack_base, &stack_size) < 0) {
  125. perror("get_stack_bounds");
  126. ASSERT_NOT_REACHED();
  127. }
  128. #elif __linux__
  129. pthread_attr_t attr = {};
  130. if (int rc = pthread_getattr_np(pthread_self(), &attr) != 0) {
  131. fprintf(stderr, "pthread_getattr_np: %s\n", strerror(-rc));
  132. ASSERT_NOT_REACHED();
  133. }
  134. if (int rc = pthread_attr_getstack(&attr, (void**)&stack_base, &stack_size) != 0) {
  135. fprintf(stderr, "pthread_attr_getstack: %s\n", strerror(-rc));
  136. ASSERT_NOT_REACHED();
  137. }
  138. pthread_attr_destroy(&attr);
  139. #elif __APPLE__
  140. stack_base = (FlatPtr)pthread_get_stackaddr_np(pthread_self());
  141. pthread_attr_t attr = {};
  142. if (int rc = pthread_attr_getstacksize(&attr, &stack_size) != 0) {
  143. fprintf(stderr, "pthread_attr_getstacksize: %s\n", strerror(-rc));
  144. ASSERT_NOT_REACHED();
  145. }
  146. pthread_attr_destroy(&attr);
  147. #endif
  148. FlatPtr stack_reference = reinterpret_cast<FlatPtr>(&dummy);
  149. FlatPtr stack_top = stack_base + stack_size;
  150. for (FlatPtr stack_address = stack_reference; stack_address < stack_top; stack_address += sizeof(FlatPtr)) {
  151. auto data = *reinterpret_cast<FlatPtr*>(stack_address);
  152. possible_pointers.set(data);
  153. }
  154. for (auto possible_pointer : possible_pointers) {
  155. if (!possible_pointer)
  156. continue;
  157. #ifdef HEAP_DEBUG
  158. dbg() << " ? " << (const void*)possible_pointer;
  159. #endif
  160. if (auto* cell = cell_from_possible_pointer(possible_pointer)) {
  161. if (cell->is_live()) {
  162. #ifdef HEAP_DEBUG
  163. dbg() << " ?-> " << (const void*)cell;
  164. #endif
  165. roots.set(cell);
  166. } else {
  167. #ifdef HEAP_DEBUG
  168. dbg() << " #-> " << (const void*)cell;
  169. #endif
  170. }
  171. }
  172. }
  173. }
  174. Cell* Heap::cell_from_possible_pointer(FlatPtr pointer)
  175. {
  176. auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<const Cell*>(pointer));
  177. if (m_blocks.find([possible_heap_block](auto& block) { return block.ptr() == possible_heap_block; }) == m_blocks.end())
  178. return nullptr;
  179. return possible_heap_block->cell_from_possible_pointer(pointer);
  180. }
  181. class MarkingVisitor final : public Cell::Visitor {
  182. public:
  183. MarkingVisitor() { }
  184. virtual void visit_impl(Cell* cell)
  185. {
  186. if (cell->is_marked())
  187. return;
  188. #ifdef HEAP_DEBUG
  189. dbg() << " ! " << cell;
  190. #endif
  191. cell->set_marked(true);
  192. cell->visit_children(*this);
  193. }
  194. };
  195. void Heap::mark_live_cells(const HashTable<Cell*>& roots)
  196. {
  197. #ifdef HEAP_DEBUG
  198. dbg() << "mark_live_cells:";
  199. #endif
  200. MarkingVisitor visitor;
  201. for (auto* root : roots)
  202. visitor.visit(root);
  203. }
  204. void Heap::sweep_dead_cells(bool print_report, const Core::ElapsedTimer& measurement_timer)
  205. {
  206. #ifdef HEAP_DEBUG
  207. dbg() << "sweep_dead_cells:";
  208. #endif
  209. Vector<HeapBlock*, 32> empty_blocks;
  210. size_t collected_cells = 0;
  211. size_t live_cells = 0;
  212. size_t collected_cell_bytes = 0;
  213. size_t live_cell_bytes = 0;
  214. for (auto& block : m_blocks) {
  215. bool block_has_live_cells = false;
  216. block->for_each_cell([&](Cell* cell) {
  217. if (cell->is_live()) {
  218. if (!cell->is_marked()) {
  219. #ifdef HEAP_DEBUG
  220. dbg() << " ~ " << cell;
  221. #endif
  222. block->deallocate(cell);
  223. ++collected_cells;
  224. collected_cell_bytes += block->cell_size();
  225. } else {
  226. cell->set_marked(false);
  227. block_has_live_cells = true;
  228. ++live_cells;
  229. live_cell_bytes += block->cell_size();
  230. }
  231. }
  232. });
  233. if (!block_has_live_cells)
  234. empty_blocks.append(block);
  235. }
  236. for (auto* block : empty_blocks) {
  237. #ifdef HEAP_DEBUG
  238. dbg() << " - Reclaim HeapBlock @ " << block << ": cell_size=" << block->cell_size();
  239. #endif
  240. m_blocks.remove_first_matching([block](auto& entry) { return entry == block; });
  241. }
  242. #ifdef HEAP_DEBUG
  243. for (auto& block : m_blocks) {
  244. dbg() << " > Live HeapBlock @ " << block << ": cell_size=" << block->cell_size();
  245. }
  246. #endif
  247. int time_spent = measurement_timer.elapsed();
  248. if (print_report) {
  249. dbg() << "Garbage collection report";
  250. dbg() << "=============================================";
  251. dbg() << " Time spent: " << time_spent << " ms";
  252. dbg() << " Live cells: " << live_cells << " (" << live_cell_bytes << " bytes)";
  253. dbg() << "Collected cells: " << collected_cells << " (" << collected_cell_bytes << " bytes)";
  254. dbg() << " Live blocks: " << m_blocks.size() << " (" << m_blocks.size() * HeapBlock::block_size << " bytes)";
  255. dbg() << " Freed blocks: " << empty_blocks.size() << " (" << empty_blocks.size() * HeapBlock::block_size << " bytes)";
  256. dbg() << "=============================================";
  257. }
  258. }
  259. void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
  260. {
  261. ASSERT(!m_handles.contains(&impl));
  262. m_handles.set(&impl);
  263. }
  264. void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
  265. {
  266. ASSERT(m_handles.contains(&impl));
  267. m_handles.remove(&impl);
  268. }
  269. void Heap::did_create_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  270. {
  271. ASSERT(!m_marked_value_lists.contains(&list));
  272. m_marked_value_lists.set(&list);
  273. }
  274. void Heap::did_destroy_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
  275. {
  276. ASSERT(m_marked_value_lists.contains(&list));
  277. m_marked_value_lists.remove(&list);
  278. }
  279. void Heap::defer_gc(Badge<DeferGC>)
  280. {
  281. ++m_gc_deferrals;
  282. }
  283. void Heap::undefer_gc(Badge<DeferGC>)
  284. {
  285. ASSERT(m_gc_deferrals > 0);
  286. --m_gc_deferrals;
  287. if (!m_gc_deferrals) {
  288. if (m_should_gc_when_deferral_ends)
  289. collect_garbage();
  290. m_should_gc_when_deferral_ends = false;
  291. }
  292. }
  293. }