2 * Copyright (c) 2011, 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/v8/ScriptProfiler.h"
36 #include "bindings/v8/RetainedDOMInfo.h"
37 #include "bindings/v8/ScriptObject.h"
38 #include "bindings/v8/V8Binding.h"
39 #include "bindings/v8/WrapperTypeInfo.h"
40 #include "core/dom/Document.h"
41 #include "core/inspector/BindingVisitors.h"
43 #include <v8-profiler.h>
46 #include "wtf/ThreadSpecific.h"
50 typedef HashMap<String, double> ProfileNameIdleTimeMap;
52 void ScriptProfiler::setSamplingInterval(int intervalUs)
54 v8::Isolate* isolate = v8::Isolate::GetCurrent();
55 v8::CpuProfiler* profiler = isolate->GetCpuProfiler();
57 profiler->SetSamplingInterval(intervalUs);
60 void ScriptProfiler::start(const String& title)
62 ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap();
63 if (profileNameIdleTimeMap->contains(title))
65 profileNameIdleTimeMap->add(title, 0);
67 v8::Isolate* isolate = v8::Isolate::GetCurrent();
68 v8::CpuProfiler* profiler = isolate->GetCpuProfiler();
71 v8::HandleScope handleScope(isolate);
72 profiler->StartProfiling(v8String(isolate, title), true);
75 PassRefPtr<ScriptProfile> ScriptProfiler::stop(const String& title)
77 v8::Isolate* isolate = v8::Isolate::GetCurrent();
78 v8::CpuProfiler* profiler = isolate->GetCpuProfiler();
81 v8::HandleScope handleScope(isolate);
82 v8::CpuProfile* profile = profiler->StopProfiling(v8String(isolate, title));
86 String profileTitle = toCoreString(profile->GetTitle());
87 double idleTime = 0.0;
88 ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap();
89 ProfileNameIdleTimeMap::iterator profileIdleTime = profileNameIdleTimeMap->find(profileTitle);
90 if (profileIdleTime != profileNameIdleTimeMap->end()) {
91 idleTime = profileIdleTime->value * 1000.0;
92 profileNameIdleTimeMap->remove(profileIdleTime);
95 return ScriptProfile::create(profile, idleTime);
98 void ScriptProfiler::collectGarbage()
100 v8::V8::LowMemoryNotification();
103 ScriptObject ScriptProfiler::objectByHeapObjectId(unsigned id)
105 v8::Isolate* isolate = v8::Isolate::GetCurrent();
106 v8::HeapProfiler* profiler = isolate->GetHeapProfiler();
107 v8::HandleScope handleScope(isolate);
108 v8::Handle<v8::Value> value = profiler->FindObjectById(id);
109 if (value.IsEmpty() || !value->IsObject())
110 return ScriptObject();
112 v8::Handle<v8::Object> object = value.As<v8::Object>();
114 if (object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount) {
115 v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
116 // Skip wrapper boilerplates which are like regular wrappers but don't have
118 if (!wrapper.IsEmpty() && wrapper->IsUndefined())
119 return ScriptObject();
122 ScriptState* scriptState = ScriptState::from(object->CreationContext());
123 return ScriptObject(scriptState, object);
126 unsigned ScriptProfiler::getHeapObjectId(const ScriptValue& value)
128 v8::Isolate* isolate = v8::Isolate::GetCurrent();
129 v8::HeapProfiler* profiler = isolate->GetHeapProfiler();
130 v8::SnapshotObjectId id = profiler->GetObjectId(value.v8Value());
134 void ScriptProfiler::clearHeapObjectIds()
136 v8::Isolate* isolate = v8::Isolate::GetCurrent();
137 v8::HeapProfiler* profiler = isolate->GetHeapProfiler();
138 profiler->ClearObjectIds();
143 class ActivityControlAdapter FINAL : public v8::ActivityControl {
145 ActivityControlAdapter(ScriptProfiler::HeapSnapshotProgress* progress)
146 : m_progress(progress), m_firstReport(true) { }
147 virtual ControlOption ReportProgressValue(int done, int total) OVERRIDE
149 ControlOption result = m_progress->isCanceled() ? kAbort : kContinue;
151 m_firstReport = false;
152 m_progress->Start(total);
154 m_progress->Worked(done);
160 ScriptProfiler::HeapSnapshotProgress* m_progress;
164 class GlobalObjectNameResolver FINAL : public v8::HeapProfiler::ObjectNameResolver {
166 virtual const char* GetName(v8::Handle<v8::Object> object) OVERRIDE
168 DOMWindow* window = toDOMWindow(object, v8::Isolate::GetCurrent());
171 CString url = window->document()->url().string().utf8();
172 m_strings.append(url);
177 Vector<CString> m_strings;
182 void ScriptProfiler::startTrackingHeapObjects(bool trackAllocations)
184 v8::Isolate::GetCurrent()->GetHeapProfiler()->StartTrackingHeapObjects(trackAllocations);
189 class HeapStatsStream : public v8::OutputStream {
191 HeapStatsStream(ScriptProfiler::OutputStream* stream) : m_stream(stream) { }
192 virtual void EndOfStream() OVERRIDE { }
194 virtual WriteResult WriteAsciiChunk(char* data, int size) OVERRIDE
200 virtual WriteResult WriteHeapStatsChunk(v8::HeapStatsUpdate* updateData, int count) OVERRIDE
202 Vector<uint32_t> rawData(count * 3);
203 for (int i = 0; i < count; ++i) {
205 rawData[offset] = updateData[i].index;
206 rawData[offset + 1] = updateData[i].count;
207 rawData[offset + 2] = updateData[i].size;
209 m_stream->write(rawData.data(), rawData.size());
214 ScriptProfiler::OutputStream* m_stream;
219 unsigned ScriptProfiler::requestHeapStatsUpdate(ScriptProfiler::OutputStream* stream)
221 HeapStatsStream heapStatsStream(stream);
222 return v8::Isolate::GetCurrent()->GetHeapProfiler()->GetHeapStats(&heapStatsStream);
225 void ScriptProfiler::stopTrackingHeapObjects()
227 v8::Isolate::GetCurrent()->GetHeapProfiler()->StopTrackingHeapObjects();
230 // FIXME: This method should receive a ScriptState, from which we should retrieve an Isolate.
231 PassRefPtr<ScriptHeapSnapshot> ScriptProfiler::takeHeapSnapshot(const String& title, HeapSnapshotProgress* control)
233 v8::Isolate* isolate = v8::Isolate::GetCurrent();
234 v8::HeapProfiler* profiler = isolate->GetHeapProfiler();
237 v8::HandleScope handleScope(isolate);
239 ActivityControlAdapter adapter(control);
240 GlobalObjectNameResolver resolver;
241 const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot(v8String(isolate, title), &adapter, &resolver);
242 return snapshot ? ScriptHeapSnapshot::create(snapshot) : nullptr;
245 static v8::RetainedObjectInfo* retainedDOMInfo(uint16_t classId, v8::Handle<v8::Value> wrapper)
247 ASSERT(classId == v8DOMNodeClassId);
248 if (!wrapper->IsObject())
250 Node* node = V8Node::toNative(wrapper.As<v8::Object>());
251 return node ? new RetainedDOMInfo(node) : 0;
254 void ScriptProfiler::initialize()
256 v8::Isolate* isolate = v8::Isolate::GetCurrent();
257 v8::HeapProfiler* profiler = isolate->GetHeapProfiler();
259 profiler->SetWrapperClassInfoProvider(v8DOMNodeClassId, &retainedDOMInfo);
262 void ScriptProfiler::visitNodeWrappers(WrappedNodeVisitor* visitor)
264 // visitNodeWrappers() should receive a ScriptState and retrieve an Isolate
265 // from the ScriptState.
266 v8::Isolate* isolate = v8::Isolate::GetCurrent();
267 v8::HandleScope handleScope(isolate);
269 class DOMNodeWrapperVisitor : public v8::PersistentHandleVisitor {
271 DOMNodeWrapperVisitor(WrappedNodeVisitor* visitor, v8::Isolate* isolate)
277 virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) OVERRIDE
279 if (classId != v8DOMNodeClassId)
281 // Casting to Handle is safe here, since the Persistent cannot get
282 // GCd during visiting.
283 v8::Handle<v8::Object>* wrapper = reinterpret_cast<v8::Handle<v8::Object>*>(value);
284 ASSERT_UNUSED(m_isolate, V8Node::hasInstance(*wrapper, m_isolate));
285 ASSERT((*wrapper)->IsObject());
286 m_visitor->visitNode(V8Node::toNative(*wrapper));
290 WrappedNodeVisitor* m_visitor;
291 v8::Isolate* m_isolate;
292 } wrapperVisitor(visitor, isolate);
294 v8::V8::VisitHandlesWithClassIds(&wrapperVisitor);
297 ProfileNameIdleTimeMap* ScriptProfiler::currentProfileNameIdleTimeMap()
299 AtomicallyInitializedStatic(WTF::ThreadSpecific<ProfileNameIdleTimeMap>*, map = new WTF::ThreadSpecific<ProfileNameIdleTimeMap>);
303 void ScriptProfiler::setIdle(bool isIdle)
305 v8::Isolate* isolate = v8::Isolate::GetCurrent();
306 if (v8::CpuProfiler* profiler = isolate->GetCpuProfiler())
307 profiler->SetIdle(isIdle);
310 } // namespace WebCore