Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / core / v8 / V8GCController.cpp
1 /*
2  * Copyright (C) 2009 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "bindings/core/v8/V8GCController.h"
33
34 #include "bindings/core/v8/RetainedDOMInfo.h"
35 #include "bindings/core/v8/V8AbstractEventListener.h"
36 #include "bindings/core/v8/V8Binding.h"
37 #include "bindings/core/v8/V8MutationObserver.h"
38 #include "bindings/core/v8/V8Node.h"
39 #include "bindings/core/v8/V8ScriptRunner.h"
40 #include "bindings/core/v8/WrapperTypeInfo.h"
41 #include "core/dom/Attr.h"
42 #include "core/dom/Document.h"
43 #include "core/dom/NodeTraversal.h"
44 #include "core/dom/TemplateContentDocumentFragment.h"
45 #include "core/dom/shadow/ElementShadow.h"
46 #include "core/dom/shadow/ShadowRoot.h"
47 #include "core/html/HTMLImageElement.h"
48 #include "core/html/HTMLTemplateElement.h"
49 #include "core/html/imports/HTMLImportsController.h"
50 #include "core/inspector/InspectorTraceEvents.h"
51 #include "core/svg/SVGElement.h"
52 #include "platform/Partitions.h"
53 #include "platform/TraceEvent.h"
54 #include "wtf/Vector.h"
55 #include <algorithm>
56
57 namespace blink {
58
59 // FIXME: This should use opaque GC roots.
60 static void addReferencesForNodeWithEventListeners(v8::Isolate* isolate, Node* node, const v8::Persistent<v8::Object>& wrapper)
61 {
62     ASSERT(node->hasEventListeners());
63
64     EventListenerIterator iterator(node);
65     while (EventListener* listener = iterator.nextListener()) {
66         if (listener->type() != EventListener::JSEventListenerType)
67             continue;
68         V8AbstractEventListener* v8listener = static_cast<V8AbstractEventListener*>(listener);
69         if (!v8listener->hasExistingListenerObject())
70             continue;
71
72         isolate->SetReference(wrapper, v8::Persistent<v8::Value>::Cast(v8listener->existingListenerObjectPersistentHandle()));
73     }
74 }
75
76 Node* V8GCController::opaqueRootForGC(Node* node, v8::Isolate*)
77 {
78     ASSERT(node);
79     // FIXME: Remove the special handling for image elements.
80     // The same special handling is in V8GCController::gcTree().
81     // Maybe should image elements be active DOM nodes?
82     // See https://code.google.com/p/chromium/issues/detail?id=164882
83     if (node->inDocument() || (isHTMLImageElement(*node) && toHTMLImageElement(*node).hasPendingActivity())) {
84         Document& document = node->document();
85         if (HTMLImportsController* controller = document.importsController())
86             return controller->master();
87         return &document;
88     }
89
90     if (node->isAttributeNode()) {
91         Node* ownerElement = toAttr(node)->ownerElement();
92         if (!ownerElement)
93             return node;
94         node = ownerElement;
95     }
96
97     while (Node* parent = node->parentOrShadowHostOrTemplateHostNode())
98         node = parent;
99
100     return node;
101 }
102
103 // Regarding a minor GC algorithm for DOM nodes, see this document:
104 // https://docs.google.com/a/google.com/presentation/d/1uifwVYGNYTZDoGLyCb7sXa7g49mWNMW2gaWvMN5NLk8/edit#slide=id.p
105 class MinorGCWrapperVisitor : public v8::PersistentHandleVisitor {
106 public:
107     explicit MinorGCWrapperVisitor(v8::Isolate* isolate)
108         : m_isolate(isolate)
109     { }
110
111     virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) OVERRIDE
112     {
113         // A minor DOM GC can collect only Nodes.
114         if (classId != v8DOMNodeClassId)
115             return;
116
117         // To make minor GC cycle time bounded, we limit the number of wrappers handled
118         // by each minor GC cycle to 10000. This value was selected so that the minor
119         // GC cycle time is bounded to 20 ms in a case where the new space size
120         // is 16 MB and it is full of wrappers (which is almost the worst case).
121         // Practically speaking, as far as I crawled real web applications,
122         // the number of wrappers handled by each minor GC cycle is at most 3000.
123         // So this limit is mainly for pathological micro benchmarks.
124         const unsigned wrappersHandledByEachMinorGC = 10000;
125         if (m_nodesInNewSpace.size() >= wrappersHandledByEachMinorGC)
126             return;
127
128         // Casting to a Handle is safe here, since the Persistent doesn't get GCd
129         // during the GC prologue.
130         ASSERT((*reinterpret_cast<v8::Handle<v8::Value>*>(value))->IsObject());
131         v8::Handle<v8::Object>* wrapper = reinterpret_cast<v8::Handle<v8::Object>*>(value);
132         ASSERT(V8DOMWrapper::isDOMWrapper(*wrapper));
133         ASSERT(V8Node::hasInstance(*wrapper, m_isolate));
134         Node* node = V8Node::toNative(*wrapper);
135         // A minor DOM GC can handle only node wrappers in the main world.
136         // Note that node->wrapper().IsEmpty() returns true for nodes that
137         // do not have wrappers in the main world.
138         if (node->containsWrapper()) {
139             const WrapperTypeInfo* type = toWrapperTypeInfo(*wrapper);
140             ActiveDOMObject* activeDOMObject = type->toActiveDOMObject(*wrapper);
141             if (activeDOMObject && activeDOMObject->hasPendingActivity())
142                 return;
143             // FIXME: Remove the special handling for image elements.
144             // The same special handling is in V8GCController::opaqueRootForGC().
145             // Maybe should image elements be active DOM nodes?
146             // See https://code.google.com/p/chromium/issues/detail?id=164882
147             if (isHTMLImageElement(*node) && toHTMLImageElement(*node).hasPendingActivity())
148                 return;
149             // FIXME: Remove the special handling for SVG context elements.
150             if (node->isSVGElement() && toSVGElement(node)->isContextElement())
151                 return;
152
153             m_nodesInNewSpace.append(node);
154             node->markV8CollectableDuringMinorGC();
155         }
156     }
157
158     void notifyFinished()
159     {
160         for (size_t i = 0; i < m_nodesInNewSpace.size(); i++) {
161             Node* node = m_nodesInNewSpace[i];
162             ASSERT(node->containsWrapper());
163             if (node->isV8CollectableDuringMinorGC()) { // This branch is just for performance.
164                 gcTree(m_isolate, node);
165                 node->clearV8CollectableDuringMinorGC();
166             }
167         }
168     }
169
170 private:
171     bool traverseTree(Node* rootNode, WillBeHeapVector<RawPtrWillBeMember<Node>, initialNodeVectorSize>* partiallyDependentNodes)
172     {
173         // To make each minor GC time bounded, we might need to give up
174         // traversing at some point for a large DOM tree. That being said,
175         // I could not observe the need even in pathological test cases.
176         for (Node* node = rootNode; node; node = NodeTraversal::next(*node)) {
177             if (node->containsWrapper()) {
178                 if (!node->isV8CollectableDuringMinorGC()) {
179                     // This node is not in the new space of V8. This indicates that
180                     // the minor GC cannot anyway judge reachability of this DOM tree.
181                     // Thus we give up traversing the DOM tree.
182                     return false;
183                 }
184                 node->clearV8CollectableDuringMinorGC();
185                 partiallyDependentNodes->append(node);
186             }
187             if (ShadowRoot* shadowRoot = node->youngestShadowRoot()) {
188                 if (!traverseTree(shadowRoot, partiallyDependentNodes))
189                     return false;
190             } else if (node->isShadowRoot()) {
191                 if (ShadowRoot* shadowRoot = toShadowRoot(node)->olderShadowRoot()) {
192                     if (!traverseTree(shadowRoot, partiallyDependentNodes))
193                         return false;
194                 }
195             }
196             // <template> has a |content| property holding a DOM fragment which we must traverse,
197             // just like we do for the shadow trees above.
198             if (isHTMLTemplateElement(*node)) {
199                 if (!traverseTree(toHTMLTemplateElement(*node).content(), partiallyDependentNodes))
200                     return false;
201             }
202
203             // Document maintains the list of imported documents through HTMLImportsController.
204             if (node->isDocumentNode()) {
205                 Document* document = toDocument(node);
206                 HTMLImportsController* controller = document->importsController();
207                 if (controller && document == controller->master()) {
208                     for (unsigned i = 0; i < controller->loaderCount(); ++i) {
209                         if (!traverseTree(controller->loaderDocumentAt(i), partiallyDependentNodes))
210                             return false;
211                     }
212                 }
213             }
214         }
215         return true;
216     }
217
218     void gcTree(v8::Isolate* isolate, Node* startNode)
219     {
220         WillBeHeapVector<RawPtrWillBeMember<Node>, initialNodeVectorSize> partiallyDependentNodes;
221
222         Node* node = startNode;
223         while (Node* parent = node->parentOrShadowHostOrTemplateHostNode())
224             node = parent;
225
226         if (!traverseTree(node, &partiallyDependentNodes))
227             return;
228
229         // We completed the DOM tree traversal. All wrappers in the DOM tree are
230         // stored in partiallyDependentNodes and are expected to exist in the new space of V8.
231         // We report those wrappers to V8 as an object group.
232         if (!partiallyDependentNodes.size())
233             return;
234         Node* groupRoot = partiallyDependentNodes[0];
235         for (size_t i = 0; i < partiallyDependentNodes.size(); i++) {
236             partiallyDependentNodes[i]->markAsDependentGroup(groupRoot, isolate);
237         }
238     }
239
240     WillBePersistentHeapVector<RawPtrWillBeMember<Node> > m_nodesInNewSpace;
241     v8::Isolate* m_isolate;
242 };
243
244 class MajorGCWrapperVisitor : public v8::PersistentHandleVisitor {
245 public:
246     explicit MajorGCWrapperVisitor(v8::Isolate* isolate, bool constructRetainedObjectInfos)
247         : m_isolate(isolate)
248         , m_liveRootGroupIdSet(false)
249         , m_constructRetainedObjectInfos(constructRetainedObjectInfos)
250     {
251     }
252
253     virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) OVERRIDE
254     {
255         if (classId != v8DOMNodeClassId && classId != v8DOMObjectClassId)
256             return;
257
258         // Casting to a Handle is safe here, since the Persistent doesn't get GCd
259         // during the GC prologue.
260         ASSERT((*reinterpret_cast<v8::Handle<v8::Value>*>(value))->IsObject());
261         v8::Handle<v8::Object>* wrapper = reinterpret_cast<v8::Handle<v8::Object>*>(value);
262         ASSERT(V8DOMWrapper::isDOMWrapper(*wrapper));
263
264         if (value->IsIndependent())
265             return;
266
267         const WrapperTypeInfo* type = toWrapperTypeInfo(*wrapper);
268
269         ActiveDOMObject* activeDOMObject = type->toActiveDOMObject(*wrapper);
270         if (activeDOMObject && activeDOMObject->hasPendingActivity())
271             m_isolate->SetObjectGroupId(*value, liveRootId());
272
273         if (classId == v8DOMNodeClassId) {
274             ASSERT(V8Node::hasInstance(*wrapper, m_isolate));
275             Node* node = V8Node::toNative(*wrapper);
276             if (node->hasEventListeners())
277                 addReferencesForNodeWithEventListeners(m_isolate, node, v8::Persistent<v8::Object>::Cast(*value));
278             Node* root = V8GCController::opaqueRootForGC(node, m_isolate);
279             m_isolate->SetObjectGroupId(*value, v8::UniqueId(reinterpret_cast<intptr_t>(root)));
280             if (m_constructRetainedObjectInfos)
281                 m_groupsWhichNeedRetainerInfo.append(root);
282         } else if (classId == v8DOMObjectClassId) {
283             type->visitDOMWrapper(toInternalPointer(*wrapper), v8::Persistent<v8::Object>::Cast(*value), m_isolate);
284         } else {
285             ASSERT_NOT_REACHED();
286         }
287     }
288
289     void notifyFinished()
290     {
291         if (!m_constructRetainedObjectInfos)
292             return;
293         std::sort(m_groupsWhichNeedRetainerInfo.begin(), m_groupsWhichNeedRetainerInfo.end());
294         Node* alreadyAdded = 0;
295         v8::HeapProfiler* profiler = m_isolate->GetHeapProfiler();
296         for (size_t i = 0; i < m_groupsWhichNeedRetainerInfo.size(); ++i) {
297             Node* root = m_groupsWhichNeedRetainerInfo[i];
298             if (root != alreadyAdded) {
299                 profiler->SetRetainedObjectInfo(v8::UniqueId(reinterpret_cast<intptr_t>(root)), new RetainedDOMInfo(root));
300                 alreadyAdded = root;
301             }
302         }
303     }
304
305 private:
306     v8::UniqueId liveRootId()
307     {
308         const v8::Persistent<v8::Value>& liveRoot = V8PerIsolateData::from(m_isolate)->ensureLiveRoot();
309         const intptr_t* idPointer = reinterpret_cast<const intptr_t*>(&liveRoot);
310         v8::UniqueId id(*idPointer);
311         if (!m_liveRootGroupIdSet) {
312             m_isolate->SetObjectGroupId(liveRoot, id);
313             m_liveRootGroupIdSet = true;
314         }
315         return id;
316     }
317
318     v8::Isolate* m_isolate;
319     WillBePersistentHeapVector<RawPtrWillBeMember<Node> > m_groupsWhichNeedRetainerInfo;
320     bool m_liveRootGroupIdSet;
321     bool m_constructRetainedObjectInfos;
322 };
323
324 static unsigned long long usedHeapSize(v8::Isolate* isolate)
325 {
326     v8::HeapStatistics heapStatistics;
327     isolate->GetHeapStatistics(&heapStatistics);
328     return heapStatistics.used_heap_size();
329 }
330
331 void V8GCController::gcPrologue(v8::GCType type, v8::GCCallbackFlags flags)
332 {
333     // FIXME: It would be nice if the GC callbacks passed the Isolate directly....
334     v8::Isolate* isolate = v8::Isolate::GetCurrent();
335     TRACE_EVENT_BEGIN1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "GCEvent", "usedHeapSizeBefore", usedHeapSize(isolate));
336     if (type == v8::kGCTypeScavenge)
337         minorGCPrologue(isolate);
338     else if (type == v8::kGCTypeMarkSweepCompact)
339         majorGCPrologue(flags & v8::kGCCallbackFlagConstructRetainedObjectInfos, isolate);
340 }
341
342 void V8GCController::minorGCPrologue(v8::Isolate* isolate)
343 {
344     TRACE_EVENT_BEGIN0("v8", "minorGC");
345     if (isMainThread()) {
346         ScriptForbiddenScope::enter();
347         {
348             TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "DOMMinorGC");
349             v8::HandleScope scope(isolate);
350             MinorGCWrapperVisitor visitor(isolate);
351             v8::V8::VisitHandlesForPartialDependence(isolate, &visitor);
352             visitor.notifyFinished();
353         }
354         V8PerIsolateData::from(isolate)->setPreviousSamplingState(TRACE_EVENT_GET_SAMPLING_STATE());
355         TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8MinorGC");
356     }
357 }
358
359 // Create object groups for DOM tree nodes.
360 void V8GCController::majorGCPrologue(bool constructRetainedObjectInfos, v8::Isolate* isolate)
361 {
362     v8::HandleScope scope(isolate);
363     TRACE_EVENT_BEGIN0("v8", "majorGC");
364     if (isMainThread()) {
365         ScriptForbiddenScope::enter();
366         {
367             TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "DOMMajorGC");
368             MajorGCWrapperVisitor visitor(isolate, constructRetainedObjectInfos);
369             v8::V8::VisitHandlesWithClassIds(&visitor);
370             visitor.notifyFinished();
371         }
372         V8PerIsolateData::from(isolate)->setPreviousSamplingState(TRACE_EVENT_GET_SAMPLING_STATE());
373         TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8MajorGC");
374     } else {
375         MajorGCWrapperVisitor visitor(isolate, constructRetainedObjectInfos);
376         v8::V8::VisitHandlesWithClassIds(&visitor);
377         visitor.notifyFinished();
378     }
379 }
380
381 void V8GCController::gcEpilogue(v8::GCType type, v8::GCCallbackFlags flags)
382 {
383     // FIXME: It would be nice if the GC callbacks passed the Isolate directly....
384     v8::Isolate* isolate = v8::Isolate::GetCurrent();
385     if (type == v8::kGCTypeScavenge)
386         minorGCEpilogue(isolate);
387     else if (type == v8::kGCTypeMarkSweepCompact)
388         majorGCEpilogue(isolate);
389
390     // Forces a Blink heap garbage collection when a garbage collection
391     // was forced from V8. This is used for tests that force GCs from
392     // JavaScript to verify that objects die when expected.
393     if (flags & v8::kGCCallbackFlagForced) {
394         // This single GC is not enough for two reasons:
395         //   (1) The GC is not precise because the GC scans on-stack pointers conservatively.
396         //   (2) One GC is not enough to break a chain of persistent handles. It's possible that
397         //       some heap allocated objects own objects that contain persistent handles
398         //       pointing to other heap allocated objects. To break the chain, we need multiple GCs.
399         //
400         // Regarding (1), we force a precise GC at the end of the current event loop. So if you want
401         // to collect all garbage, you need to wait until the next event loop.
402         // Regarding (2), it would be OK in practice to trigger only one GC per gcEpilogue, because
403         // GCController.collectAll() forces 7 V8's GC.
404         Heap::collectGarbage(ThreadState::HeapPointersOnStack);
405
406         // Forces a precise GC at the end of the current event loop.
407         Heap::setForcePreciseGCForTesting();
408     }
409
410     TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "GCEvent", "usedHeapSizeAfter", usedHeapSize(isolate));
411     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", "data", InspectorUpdateCountersEvent::data());
412 }
413
414 void V8GCController::minorGCEpilogue(v8::Isolate* isolate)
415 {
416     TRACE_EVENT_END0("v8", "minorGC");
417     if (isMainThread()) {
418         TRACE_EVENT_SET_NONCONST_SAMPLING_STATE(V8PerIsolateData::from(isolate)->previousSamplingState());
419         ScriptForbiddenScope::exit();
420     }
421 }
422
423 void V8GCController::majorGCEpilogue(v8::Isolate* isolate)
424 {
425     v8::HandleScope scope(isolate);
426
427     TRACE_EVENT_END0("v8", "majorGC");
428     if (isMainThread()) {
429         TRACE_EVENT_SET_NONCONST_SAMPLING_STATE(V8PerIsolateData::from(isolate)->previousSamplingState());
430         ScriptForbiddenScope::exit();
431     }
432 }
433
434 void V8GCController::collectGarbage(v8::Isolate* isolate)
435 {
436     v8::HandleScope handleScope(isolate);
437     RefPtr<ScriptState> scriptState = ScriptState::create(v8::Context::New(isolate), DOMWrapperWorld::create());
438     ScriptState::Scope scope(scriptState.get());
439     V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, "if (gc) gc();"), isolate);
440     scriptState->disposePerContextData();
441 }
442
443 void V8GCController::reportDOMMemoryUsageToV8(v8::Isolate* isolate)
444 {
445     if (!isMainThread())
446         return;
447
448     static size_t lastUsageReportedToV8 = 0;
449
450     size_t currentUsage = Partitions::currentDOMMemoryUsage();
451     int64_t diff = static_cast<int64_t>(currentUsage) - static_cast<int64_t>(lastUsageReportedToV8);
452     isolate->AdjustAmountOfExternalAllocatedMemory(diff);
453
454     lastUsageReportedToV8 = currentUsage;
455 }
456
457 } // namespace blink