2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
32 #include "bindings/core/v8/V8GCController.h"
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"
59 // FIXME: This should use opaque GC roots.
60 static void addReferencesForNodeWithEventListeners(v8::Isolate* isolate, Node* node, const v8::Persistent<v8::Object>& wrapper)
62 ASSERT(node->hasEventListeners());
64 EventListenerIterator iterator(node);
65 while (EventListener* listener = iterator.nextListener()) {
66 if (listener->type() != EventListener::JSEventListenerType)
68 V8AbstractEventListener* v8listener = static_cast<V8AbstractEventListener*>(listener);
69 if (!v8listener->hasExistingListenerObject())
72 isolate->SetReference(wrapper, v8::Persistent<v8::Value>::Cast(v8listener->existingListenerObjectPersistentHandle()));
76 Node* V8GCController::opaqueRootForGC(Node* node, v8::Isolate*)
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();
90 if (node->isAttributeNode()) {
91 Node* ownerElement = toAttr(node)->ownerElement();
97 while (Node* parent = node->parentOrShadowHostOrTemplateHostNode())
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 {
107 explicit MinorGCWrapperVisitor(v8::Isolate* isolate)
111 virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) OVERRIDE
113 // A minor DOM GC can collect only Nodes.
114 if (classId != v8DOMNodeClassId)
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)
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())
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())
149 // FIXME: Remove the special handling for SVG context elements.
150 if (node->isSVGElement() && toSVGElement(node)->isContextElement())
153 m_nodesInNewSpace.append(node);
154 node->markV8CollectableDuringMinorGC();
158 void notifyFinished()
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();
171 bool traverseTree(Node* rootNode, WillBeHeapVector<RawPtrWillBeMember<Node>, initialNodeVectorSize>* partiallyDependentNodes)
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.
184 node->clearV8CollectableDuringMinorGC();
185 partiallyDependentNodes->append(node);
187 if (ShadowRoot* shadowRoot = node->youngestShadowRoot()) {
188 if (!traverseTree(shadowRoot, partiallyDependentNodes))
190 } else if (node->isShadowRoot()) {
191 if (ShadowRoot* shadowRoot = toShadowRoot(node)->olderShadowRoot()) {
192 if (!traverseTree(shadowRoot, partiallyDependentNodes))
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))
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))
218 void gcTree(v8::Isolate* isolate, Node* startNode)
220 WillBeHeapVector<RawPtrWillBeMember<Node>, initialNodeVectorSize> partiallyDependentNodes;
222 Node* node = startNode;
223 while (Node* parent = node->parentOrShadowHostOrTemplateHostNode())
226 if (!traverseTree(node, &partiallyDependentNodes))
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())
234 Node* groupRoot = partiallyDependentNodes[0];
235 for (size_t i = 0; i < partiallyDependentNodes.size(); i++) {
236 partiallyDependentNodes[i]->markAsDependentGroup(groupRoot, isolate);
240 WillBePersistentHeapVector<RawPtrWillBeMember<Node> > m_nodesInNewSpace;
241 v8::Isolate* m_isolate;
244 class MajorGCWrapperVisitor : public v8::PersistentHandleVisitor {
246 explicit MajorGCWrapperVisitor(v8::Isolate* isolate, bool constructRetainedObjectInfos)
248 , m_liveRootGroupIdSet(false)
249 , m_constructRetainedObjectInfos(constructRetainedObjectInfos)
253 virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) OVERRIDE
255 if (classId != v8DOMNodeClassId && classId != v8DOMObjectClassId)
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));
264 if (value->IsIndependent())
267 const WrapperTypeInfo* type = toWrapperTypeInfo(*wrapper);
269 ActiveDOMObject* activeDOMObject = type->toActiveDOMObject(*wrapper);
270 if (activeDOMObject && activeDOMObject->hasPendingActivity())
271 m_isolate->SetObjectGroupId(*value, liveRootId());
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);
285 ASSERT_NOT_REACHED();
289 void notifyFinished()
291 if (!m_constructRetainedObjectInfos)
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));
306 v8::UniqueId liveRootId()
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;
318 v8::Isolate* m_isolate;
319 WillBePersistentHeapVector<RawPtrWillBeMember<Node> > m_groupsWhichNeedRetainerInfo;
320 bool m_liveRootGroupIdSet;
321 bool m_constructRetainedObjectInfos;
324 static unsigned long long usedHeapSize(v8::Isolate* isolate)
326 v8::HeapStatistics heapStatistics;
327 isolate->GetHeapStatistics(&heapStatistics);
328 return heapStatistics.used_heap_size();
331 void V8GCController::gcPrologue(v8::GCType type, v8::GCCallbackFlags flags)
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);
342 void V8GCController::minorGCPrologue(v8::Isolate* isolate)
344 TRACE_EVENT_BEGIN0("v8", "minorGC");
345 if (isMainThread()) {
346 ScriptForbiddenScope::enter();
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();
354 V8PerIsolateData::from(isolate)->setPreviousSamplingState(TRACE_EVENT_GET_SAMPLING_STATE());
355 TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8MinorGC");
359 // Create object groups for DOM tree nodes.
360 void V8GCController::majorGCPrologue(bool constructRetainedObjectInfos, v8::Isolate* isolate)
362 v8::HandleScope scope(isolate);
363 TRACE_EVENT_BEGIN0("v8", "majorGC");
364 if (isMainThread()) {
365 ScriptForbiddenScope::enter();
367 TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "DOMMajorGC");
368 MajorGCWrapperVisitor visitor(isolate, constructRetainedObjectInfos);
369 v8::V8::VisitHandlesWithClassIds(&visitor);
370 visitor.notifyFinished();
372 V8PerIsolateData::from(isolate)->setPreviousSamplingState(TRACE_EVENT_GET_SAMPLING_STATE());
373 TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8MajorGC");
375 MajorGCWrapperVisitor visitor(isolate, constructRetainedObjectInfos);
376 v8::V8::VisitHandlesWithClassIds(&visitor);
377 visitor.notifyFinished();
381 void V8GCController::gcEpilogue(v8::GCType type, v8::GCCallbackFlags flags)
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);
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.
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);
406 // Forces a precise GC at the end of the current event loop.
407 Heap::setForcePreciseGCForTesting();
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());
414 void V8GCController::minorGCEpilogue(v8::Isolate* isolate)
416 TRACE_EVENT_END0("v8", "minorGC");
417 if (isMainThread()) {
418 TRACE_EVENT_SET_NONCONST_SAMPLING_STATE(V8PerIsolateData::from(isolate)->previousSamplingState());
419 ScriptForbiddenScope::exit();
423 void V8GCController::majorGCEpilogue(v8::Isolate* isolate)
425 v8::HandleScope scope(isolate);
427 TRACE_EVENT_END0("v8", "majorGC");
428 if (isMainThread()) {
429 TRACE_EVENT_SET_NONCONST_SAMPLING_STATE(V8PerIsolateData::from(isolate)->previousSamplingState());
430 ScriptForbiddenScope::exit();
434 void V8GCController::collectGarbage(v8::Isolate* isolate)
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();
443 void V8GCController::reportDOMMemoryUsageToV8(v8::Isolate* isolate)
448 static size_t lastUsageReportedToV8 = 0;
450 size_t currentUsage = Partitions::currentDOMMemoryUsage();
451 int64_t diff = static_cast<int64_t>(currentUsage) - static_cast<int64_t>(lastUsageReportedToV8);
452 isolate->AdjustAmountOfExternalAllocatedMemory(diff);
454 lastUsageReportedToV8 = currentUsage;