Heap.cpp 10.0 KB

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