summaryrefslogtreecommitdiff
path: root/Libraries/LibJS/Heap/Heap.cpp
blob: a4a131fe5cd8ed49d0c11bb12ff5cc5f6bfd91ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/*
 * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <AK/Badge.h>
#include <AK/HashTable.h>
#include <LibCore/ElapsedTimer.h>
#include <LibJS/Heap/Handle.h>
#include <LibJS/Heap/Heap.h>
#include <LibJS/Heap/HeapBlock.h>
#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/Object.h>
#include <setjmp.h>
#include <stdio.h>

#ifdef __serenity__
#    include <serenity.h>
#elif __linux__ or __APPLE__
#    include <pthread.h>
#endif

#ifdef __serenity__
//#define HEAP_DEBUG
#endif

namespace JS {

Heap::Heap(VM& vm)
    : m_vm(vm)
{
}

Heap::~Heap()
{
    collect_garbage(CollectionType::CollectEverything);
}

Interpreter& Heap::interpreter()
{
    return vm().interpreter();
}

Cell* Heap::allocate_cell(size_t size)
{
    if (should_collect_on_every_allocation()) {
        collect_garbage();
    } else if (m_allocations_since_last_gc > m_max_allocations_between_gc) {
        m_allocations_since_last_gc = 0;
        collect_garbage();
    } else {
        ++m_allocations_since_last_gc;
    }

    for (auto& block : m_blocks) {
        if (size > block->cell_size())
            continue;
        if (auto* cell = block->allocate())
            return cell;
    }

    size_t cell_size = round_up_to_power_of_two(size, 16);
    auto block = HeapBlock::create_with_cell_size(*this, cell_size);
    auto* cell = block->allocate();
    m_blocks.append(move(block));
    return cell;
}

void Heap::collect_garbage(CollectionType collection_type, bool print_report)
{
    Core::ElapsedTimer collection_measurement_timer;
    collection_measurement_timer.start();
    if (collection_type == CollectionType::CollectGarbage) {
        if (m_gc_deferrals) {
            m_should_gc_when_deferral_ends = true;
            return;
        }
        HashTable<Cell*> roots;
        gather_roots(roots);
        mark_live_cells(roots);
    }
    sweep_dead_cells(print_report, collection_measurement_timer);
}

void Heap::gather_roots(HashTable<Cell*>& roots)
{
    vm().gather_roots(roots);
    gather_conservative_roots(roots);

    for (auto* handle : m_handles)
        roots.set(handle->cell());

    for (auto* list : m_marked_value_lists) {
        for (auto& value : list->values()) {
            if (value.is_cell())
                roots.set(value.as_cell());
        }
    }

#ifdef HEAP_DEBUG
    dbg() << "gather_roots:";
    for (auto* root : roots) {
        dbg() << "  + " << root;
    }
#endif
}

void Heap::gather_conservative_roots(HashTable<Cell*>& roots)
{
    FlatPtr dummy;

#ifdef HEAP_DEBUG
    dbg() << "gather_conservative_roots:";
#endif

    jmp_buf buf;
    setjmp(buf);

    HashTable<FlatPtr> possible_pointers;

    const FlatPtr* raw_jmp_buf = reinterpret_cast<const FlatPtr*>(buf);

    for (size_t i = 0; i < ((size_t)sizeof(buf)) / sizeof(FlatPtr); i += sizeof(FlatPtr))
        possible_pointers.set(raw_jmp_buf[i]);

    FlatPtr stack_base;
    size_t stack_size;

#ifdef __serenity__
    if (get_stack_bounds(&stack_base, &stack_size) < 0) {
        perror("get_stack_bounds");
        ASSERT_NOT_REACHED();
    }
#elif __linux__
    pthread_attr_t attr = {};
    if (int rc = pthread_getattr_np(pthread_self(), &attr) != 0) {
        fprintf(stderr, "pthread_getattr_np: %s\n", strerror(-rc));
        ASSERT_NOT_REACHED();
    }
    if (int rc = pthread_attr_getstack(&attr, (void**)&stack_base, &stack_size) != 0) {
        fprintf(stderr, "pthread_attr_getstack: %s\n", strerror(-rc));
        ASSERT_NOT_REACHED();
    }
    pthread_attr_destroy(&attr);
#elif __APPLE__
    stack_base = (FlatPtr)pthread_get_stackaddr_np(pthread_self());
    pthread_attr_t attr = {};
    if (int rc = pthread_attr_getstacksize(&attr, &stack_size) != 0) {
        fprintf(stderr, "pthread_attr_getstacksize: %s\n", strerror(-rc));
        ASSERT_NOT_REACHED();
    }
    pthread_attr_destroy(&attr);
#endif

    FlatPtr stack_reference = reinterpret_cast<FlatPtr>(&dummy);
    FlatPtr stack_top = stack_base + stack_size;

    for (FlatPtr stack_address = stack_reference; stack_address < stack_top; stack_address += sizeof(FlatPtr)) {
        auto data = *reinterpret_cast<FlatPtr*>(stack_address);
        possible_pointers.set(data);
    }

    for (auto possible_pointer : possible_pointers) {
        if (!possible_pointer)
            continue;
#ifdef HEAP_DEBUG
        dbg() << "  ? " << (const void*)possible_pointer;
#endif
        if (auto* cell = cell_from_possible_pointer(possible_pointer)) {
            if (cell->is_live()) {
#ifdef HEAP_DEBUG
                dbg() << "  ?-> " << (const void*)cell;
#endif
                roots.set(cell);
            } else {
#ifdef HEAP_DEBUG
                dbg() << "  #-> " << (const void*)cell;
#endif
            }
        }
    }
}

Cell* Heap::cell_from_possible_pointer(FlatPtr pointer)
{
    auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<const Cell*>(pointer));
    if (m_blocks.find([possible_heap_block](auto& block) { return block.ptr() == possible_heap_block; }) == m_blocks.end())
        return nullptr;
    return possible_heap_block->cell_from_possible_pointer(pointer);
}

class MarkingVisitor final : public Cell::Visitor {
public:
    MarkingVisitor() { }

    virtual void visit_impl(Cell* cell)
    {
        if (cell->is_marked())
            return;
#ifdef HEAP_DEBUG
        dbg() << "  ! " << cell;
#endif
        cell->set_marked(true);
        cell->visit_children(*this);
    }
};

void Heap::mark_live_cells(const HashTable<Cell*>& roots)
{
#ifdef HEAP_DEBUG
    dbg() << "mark_live_cells:";
#endif
    MarkingVisitor visitor;
    for (auto* root : roots)
        visitor.visit(root);
}

void Heap::sweep_dead_cells(bool print_report, const Core::ElapsedTimer& measurement_timer)
{
#ifdef HEAP_DEBUG
    dbg() << "sweep_dead_cells:";
#endif
    Vector<HeapBlock*, 32> empty_blocks;

    size_t collected_cells = 0;
    size_t live_cells = 0;
    size_t collected_cell_bytes = 0;
    size_t live_cell_bytes = 0;

    for (auto& block : m_blocks) {
        bool block_has_live_cells = false;
        block->for_each_cell([&](Cell* cell) {
            if (cell->is_live()) {
                if (!cell->is_marked()) {
#ifdef HEAP_DEBUG
                    dbg() << "  ~ " << cell;
#endif
                    block->deallocate(cell);
                    ++collected_cells;
                    collected_cell_bytes += block->cell_size();
                } else {
                    cell->set_marked(false);
                    block_has_live_cells = true;
                    ++live_cells;
                    live_cell_bytes += block->cell_size();
                }
            }
        });
        if (!block_has_live_cells)
            empty_blocks.append(block);
    }

    for (auto* block : empty_blocks) {
#ifdef HEAP_DEBUG
        dbg() << " - Reclaim HeapBlock @ " << block << ": cell_size=" << block->cell_size();
#endif
        m_blocks.remove_first_matching([block](auto& entry) { return entry == block; });
    }

#ifdef HEAP_DEBUG
    for (auto& block : m_blocks) {
        dbg() << " > Live HeapBlock @ " << block << ": cell_size=" << block->cell_size();
    }
#endif

    int time_spent = measurement_timer.elapsed();

    if (print_report) {
        dbg() << "Garbage collection report";
        dbg() << "=============================================";
        dbg() << "     Time spent: " << time_spent << " ms";
        dbg() << "     Live cells: " << live_cells << " (" << live_cell_bytes << " bytes)";
        dbg() << "Collected cells: " << collected_cells << " (" << collected_cell_bytes << " bytes)";
        dbg() << "    Live blocks: " << m_blocks.size() << " (" << m_blocks.size() * HeapBlock::block_size << " bytes)";
        dbg() << "   Freed blocks: " << empty_blocks.size() << " (" << empty_blocks.size() * HeapBlock::block_size << " bytes)";
        dbg() << "=============================================";
    }
}

void Heap::did_create_handle(Badge<HandleImpl>, HandleImpl& impl)
{
    ASSERT(!m_handles.contains(&impl));
    m_handles.set(&impl);
}

void Heap::did_destroy_handle(Badge<HandleImpl>, HandleImpl& impl)
{
    ASSERT(m_handles.contains(&impl));
    m_handles.remove(&impl);
}

void Heap::did_create_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
{
    ASSERT(!m_marked_value_lists.contains(&list));
    m_marked_value_lists.set(&list);
}

void Heap::did_destroy_marked_value_list(Badge<MarkedValueList>, MarkedValueList& list)
{
    ASSERT(m_marked_value_lists.contains(&list));
    m_marked_value_lists.remove(&list);
}

void Heap::defer_gc(Badge<DeferGC>)
{
    ++m_gc_deferrals;
}

void Heap::undefer_gc(Badge<DeferGC>)
{
    ASSERT(m_gc_deferrals > 0);
    --m_gc_deferrals;

    if (!m_gc_deferrals) {
        if (m_should_gc_when_deferral_ends)
            collect_garbage();
        m_should_gc_when_deferral_ends = false;
    }
}

}