Heap.cpp 11 KB

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