File: V8GCController.cpp

package info (click to toggle)
qtwebkit 2.3.4.dfsg-10
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 290,632 kB
  • sloc: cpp: 1,417,515; python: 85,048; ansic: 39,357; perl: 38,862; ruby: 10,313; objc: 9,505; xml: 8,679; asm: 3,864; yacc: 2,458; sh: 1,237; lex: 813; makefile: 592; java: 228; php: 79
file content (426 lines) | stat: -rw-r--r-- 15,161 bytes parent folder | download | duplicates (3)
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*
 * Copyright (C) 2009 Google Inc. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * 
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * 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.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * 
 * 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
 * OWNER 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 "config.h"
#include "V8GCController.h"

#include "Attr.h"
#include "HTMLImageElement.h"
#include "MemoryUsageSupport.h"
#include "TraceEvent.h"
#include "V8AbstractEventListener.h"
#include "V8Binding.h"
#include "V8MessagePort.h"
#include "V8MutationObserver.h"
#include "V8Node.h"
#include "V8RecursionScope.h"
#include "WrapperTypeInfo.h"
#include <algorithm>

namespace WebCore {

class ImplicitConnection {
public:
    ImplicitConnection(void* root, v8::Persistent<v8::Value> wrapper)
        : m_root(root)
        , m_wrapper(wrapper)
    {
    }

    void* root() const { return m_root; }
    v8::Persistent<v8::Value> wrapper() const { return m_wrapper; }

private:
    void* m_root;
    v8::Persistent<v8::Value> m_wrapper;
};

bool operator<(const ImplicitConnection& left, const ImplicitConnection& right)
{
    return left.root() < right.root();
}

class WrapperGrouper {
public:
    WrapperGrouper()
    {
        m_liveObjects.append(V8PerIsolateData::current()->ensureLiveRoot());
    }

    void addToGroup(void* root, v8::Persistent<v8::Value> wrapper)
    {
        m_connections.append(ImplicitConnection(root, wrapper));
    }

    void keepAlive(v8::Persistent<v8::Value> wrapper)
    {
        m_liveObjects.append(wrapper);
    }

    void apply()
    {
        if (m_liveObjects.size() > 1)
            v8::V8::AddObjectGroup(m_liveObjects.data(), m_liveObjects.size());

        std::sort(m_connections.begin(), m_connections.end());
        Vector<v8::Persistent<v8::Value> > group;
        size_t i = 0;
        while (i < m_connections.size()) {
            void* root = m_connections[i].root();

            do {
                group.append(m_connections[i++].wrapper());
            } while (i < m_connections.size() && root == m_connections[i].root());

            if (group.size() > 1)
                v8::V8::AddObjectGroup(group.data(), group.size(), 0);

            group.shrink(0);
        }
    }

private:
    Vector<v8::Persistent<v8::Value> > m_liveObjects;
    Vector<ImplicitConnection> m_connections;
};

// FIXME: This should use opaque GC roots.
static void addImplicitReferencesForNodeWithEventListeners(Node* node, v8::Persistent<v8::Object> wrapper)
{
    ASSERT(node->hasEventListeners());

    Vector<v8::Persistent<v8::Value> > listeners;

    EventListenerIterator iterator(node);
    while (EventListener* listener = iterator.nextListener()) {
        if (listener->type() != EventListener::JSEventListenerType)
            continue;
        V8AbstractEventListener* v8listener = static_cast<V8AbstractEventListener*>(listener);
        if (!v8listener->hasExistingListenerObject())
            continue;
        listeners.append(v8listener->existingListenerObjectPersistentHandle());
    }

    if (listeners.isEmpty())
        return;

    v8::V8::AddImplicitReferences(wrapper, listeners.data(), listeners.size());
}

void* V8GCController::opaqueRootForGC(Node* node)
{
    if (node->inDocument() || (node->hasTagName(HTMLNames::imgTag) && static_cast<HTMLImageElement*>(node)->hasPendingActivity()))
        return node->document();

    if (node->isAttributeNode()) {
        Node* ownerElement = static_cast<Attr*>(node)->ownerElement();
        if (!ownerElement)
            return node;
        node = ownerElement;
    }

    while (Node* parent = node->parentOrHostNode())
        node = parent;

    return node;
}

class WrapperVisitor : public v8::PersistentHandleVisitor {
public:
    virtual void VisitPersistentHandle(v8::Persistent<v8::Value> value, uint16_t classId) OVERRIDE
    {
        ASSERT(value->IsObject());
        v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>::Cast(value);

        if (classId != v8DOMNodeClassId && classId != v8DOMObjectClassId)
            return;

        ASSERT(V8DOMWrapper::maybeDOMWrapper(value));

        if (value.IsIndependent())
            return;

        WrapperTypeInfo* type = V8DOMWrapper::domWrapperType(wrapper);
        void* object = toNative(wrapper);

        if (V8MessagePort::info.equals(type)) {
            // Mark each port as in-use if it's entangled. For simplicity's sake,
            // we assume all ports are remotely entangled, since the Chromium port
            // implementation can't tell the difference.
            MessagePort* port = static_cast<MessagePort*>(object);
            if (port->isEntangled() || port->hasPendingActivity())
                m_grouper.keepAlive(wrapper);
#if ENABLE(MUTATION_OBSERVERS)
        } else if (V8MutationObserver::info.equals(type)) {
            // FIXME: Allow opaqueRootForGC to operate on multiple roots and move this logic into V8MutationObserverCustom.
            MutationObserver* observer = static_cast<MutationObserver*>(object);
            HashSet<Node*> observedNodes = observer->getObservedNodes();
            for (HashSet<Node*>::iterator it = observedNodes.begin(); it != observedNodes.end(); ++it)
                m_grouper.addToGroup(V8GCController::opaqueRootForGC(*it), wrapper);
#endif // ENABLE(MUTATION_OBSERVERS)
        } else {
            ActiveDOMObject* activeDOMObject = type->toActiveDOMObject(wrapper);
            if (activeDOMObject && activeDOMObject->hasPendingActivity())
                m_grouper.keepAlive(wrapper);
        }

        if (classId == v8DOMNodeClassId) {
            ASSERT(V8Node::HasInstance(wrapper));
            ASSERT(!wrapper.IsIndependent());

            Node* node = static_cast<Node*>(object);

            if (node->hasEventListeners())
                addImplicitReferencesForNodeWithEventListeners(node, wrapper);

            m_grouper.addToGroup(V8GCController::opaqueRootForGC(node), wrapper);
        } else if (classId == v8DOMObjectClassId) {
            m_grouper.addToGroup(type->opaqueRootForGC(object, wrapper), wrapper);
        } else {
            ASSERT_NOT_REACHED();
        }
    }

    void notifyFinished()
    {
        m_grouper.apply();
    }

private:
    WrapperGrouper m_grouper;
};

// Regarding a minor GC algorithm for DOM nodes, see this document:
// https://docs.google.com/a/google.com/presentation/d/1uifwVYGNYTZDoGLyCb7sXa7g49mWNMW2gaWvMN5NLk8/edit#slide=id.p
//
// m_edenNodes stores nodes that have wrappers that have been created since the last minor/major GC.
Vector<Node*>* V8GCController::m_edenNodes = 0;

static void gcTree(Node* startNode)
{
    Vector<v8::Persistent<v8::Value>, initialNodeVectorSize> newSpaceWrappers;

    // We traverse a DOM tree in the DFS order starting from startNode.
    // The traversal order does not matter for correctness but does matter for performance.
    Node* node = startNode;
    // To make each minor GC time bounded, we might need to give up
    // traversing at some point for a large DOM tree. That being said,
    // I could not observe the need even in pathological test cases.
    do {
        ASSERT(node);
        if (!node->wrapper().IsEmpty()) {
            if (!node->isV8CollectableDuringMinorGC()) {
                // The fact that we encounter a node that is not in the Eden space
                // implies that its wrapper might be in the old space of V8.
                // This indicates that the minor GC cannot anyway judge reachability
                // of this DOM tree. Thus we give up traversing the DOM tree.
                return;
            }
            // A once traversed node is removed from the Eden space.
            node->setV8CollectableDuringMinorGC(false);
            newSpaceWrappers.append(node->wrapper());
        }
        if (node->firstChild()) {
            node = node->firstChild();
            continue;
        }
        while (!node->nextSibling()) {
            if (!node->parentNode())
                break;
            node = node->parentNode();
        }
        if (node->parentNode())
            node = node->nextSibling();
    } while (node != startNode);

    // We completed the DOM tree traversal. All wrappers in the DOM tree are
    // stored in newSpaceWrappers and are expected to exist in the new space of V8.
    // We report those wrappers to V8 as an object group.
    for (size_t i = 0; i < newSpaceWrappers.size(); i++)
        newSpaceWrappers[i].MarkPartiallyDependent();
    if (newSpaceWrappers.size() > 0)
        v8::V8::AddObjectGroup(&newSpaceWrappers[0], newSpaceWrappers.size());
}

void V8GCController::didCreateWrapperForNode(Node* node)
{
    // To make minor GC cycle time bounded, we limit the number of wrappers handled
    // by each minor GC cycle to 10000. This value was selected so that the minor
    // GC cycle time is bounded to 20 ms in a case where the new space size
    // is 16 MB and it is full of wrappers (which is almost the worst case).
    // Practically speaking, as far as I crawled real web applications,
    // the number of wrappers handled by each minor GC cycle is at most 3000.
    // So this limit is mainly for pathological micro benchmarks.
    const unsigned wrappersHandledByEachMinorGC = 10000;
    ASSERT(!node->wrapper().IsEmpty());
    if (!m_edenNodes)
        m_edenNodes = adoptPtr(new Vector<Node*>).leakPtr();
    if (m_edenNodes->size() <= wrappersHandledByEachMinorGC) {
        // A node of a newly created wrapper is put into the Eden space.
        m_edenNodes->append(node);
        node->setV8CollectableDuringMinorGC(true);
    }
}

void V8GCController::gcPrologue(v8::GCType type, v8::GCCallbackFlags flags)
{
    if (type == v8::kGCTypeScavenge)
        minorGCPrologue();
    else if (type == v8::kGCTypeMarkSweepCompact)
        majorGCPrologue();

    if (isMainThreadOrGCThread() && m_edenNodes) {
        // The Eden space is cleared at every minor/major GC.
        m_edenNodes->clear();
    }
}

void V8GCController::minorGCPrologue()
{
    if (isMainThreadOrGCThread() && m_edenNodes) {
        for (size_t i = 0; i < m_edenNodes->size(); i++) {
            ASSERT(!m_edenNodes->at(i)->wrapper().IsEmpty());
            if (m_edenNodes->at(i)->isV8CollectableDuringMinorGC()) // This branch is just for performance.
                gcTree(m_edenNodes->at(i));
        }
    }
}

// Create object groups for DOM tree nodes.
void V8GCController::majorGCPrologue()
{
    TRACE_EVENT_BEGIN0("v8", "GC");

    v8::HandleScope scope;

    WrapperVisitor visitor;
    v8::V8::VisitHandlesWithClassIds(&visitor);
    visitor.notifyFinished();

    V8PerIsolateData* data = V8PerIsolateData::current();
    data->stringCache()->clearOnGC();
}

static int workingSetEstimateMB = 0;

static Mutex& workingSetEstimateMBMutex()
{
    AtomicallyInitializedStatic(Mutex&, mutex = *new Mutex);
    return mutex;
}

void V8GCController::gcEpilogue(v8::GCType type, v8::GCCallbackFlags flags)
{
    if (type == v8::kGCTypeScavenge)
        minorGCEpilogue();
    else if (type == v8::kGCTypeMarkSweepCompact)
        majorGCEpilogue();
}

void V8GCController::minorGCEpilogue()
{
}

void V8GCController::majorGCEpilogue()
{
    v8::HandleScope scope;

    // The GC can happen on multiple threads in case of dedicated workers which run in-process.
    {
        MutexLocker locker(workingSetEstimateMBMutex());
        workingSetEstimateMB = MemoryUsageSupport::actualMemoryUsageMB();
    }

    TRACE_EVENT_END0("v8", "GC");
}

void V8GCController::checkMemoryUsage()
{
    const int lowMemoryUsageMB = MemoryUsageSupport::lowMemoryUsageMB();
    const int highMemoryUsageMB = MemoryUsageSupport::highMemoryUsageMB();
    const int highUsageDeltaMB = MemoryUsageSupport::highUsageDeltaMB();
    int memoryUsageMB = MemoryUsageSupport::memoryUsageMB();
    int workingSetEstimateMBCopy;
    {
        MutexLocker locker(workingSetEstimateMBMutex());
        workingSetEstimateMBCopy = workingSetEstimateMB;
    }
    if (memoryUsageMB > lowMemoryUsageMB && memoryUsageMB > 2 * workingSetEstimateMBCopy) {
        // Memory usage is large and doubled since the last GC.
        // Check if we need to send low memory notification.
        v8::HeapStatistics heapStatistics;
        v8::V8::GetHeapStatistics(&heapStatistics);
        int heapSizeMB = heapStatistics.total_heap_size() >> 20;
        // Do not send low memory notification if V8 heap size is more than 7/8
        // of total memory usage. Let V8 to schedule GC itself in this case.
        if (heapSizeMB < memoryUsageMB / 8 * 7)
            v8::V8::LowMemoryNotification();
    } else if (memoryUsageMB > highMemoryUsageMB && memoryUsageMB > workingSetEstimateMBCopy + highUsageDeltaMB) {
        // We are approaching OOM and memory usage increased by highUsageDeltaMB since the last GC.
        v8::V8::LowMemoryNotification();
    }
}

void V8GCController::hintForCollectGarbage()
{
    V8PerIsolateData* data = V8PerIsolateData::current();
    if (!data->shouldCollectGarbageSoon())
        return;
    const int longIdlePauseInMS = 1000;
    data->clearShouldCollectGarbageSoon();
    v8::V8::ContextDisposedNotification();
    v8::V8::IdleNotification(longIdlePauseInMS);
}

void V8GCController::collectGarbage()
{
    v8::HandleScope handleScope;

    ScopedPersistent<v8::Context> context;

    context.adopt(v8::Context::New());
    if (context.isEmpty())
        return;

    {
        v8::Context::Scope scope(context.get());
        v8::Local<v8::String> source = v8::String::New("if (gc) gc();");
        v8::Local<v8::String> name = v8::String::New("gc");
        v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
        if (!script.IsEmpty()) {
            V8RecursionScope::MicrotaskSuppression scope;
            script->Run();
        }
    }

    context.clear();
}

}  // namespace WebCore