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/core/v8/ScriptProfiler.h"
34 #include "bindings/core/v8/RetainedDOMInfo.h"
35 #include "bindings/core/v8/ScriptValue.h"
36 #include "bindings/core/v8/V8Binding.h"
37 #include "bindings/core/v8/V8Node.h"
38 #include "bindings/core/v8/V8Window.h"
39 #include "bindings/core/v8/WrapperTypeInfo.h"
40 #include "core/dom/Document.h"
41 #include "core/inspector/BindingVisitors.h"
42 #include "wtf/ThreadSpecific.h"
44 #include <v8-profiler.h>
49 typedef HashMap<String, double> ProfileNameIdleTimeMap;
51 void ScriptProfiler::setSamplingInterval(int intervalUs)
53 v8::Isolate* isolate = v8::Isolate::GetCurrent();
54 v8::CpuProfiler* profiler = isolate->GetCpuProfiler();
56 profiler->SetSamplingInterval(intervalUs);
59 void ScriptProfiler::start(const String& title)
61 ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap();
62 if (profileNameIdleTimeMap->contains(title))
64 profileNameIdleTimeMap->add(title, 0);
66 v8::Isolate* isolate = v8::Isolate::GetCurrent();
67 v8::CpuProfiler* profiler = isolate->GetCpuProfiler();
70 v8::HandleScope handleScope(isolate);
71 profiler->StartProfiling(v8String(isolate, title), true);
74 PassRefPtrWillBeRawPtr<ScriptProfile> ScriptProfiler::stop(const String& title)
76 v8::Isolate* isolate = v8::Isolate::GetCurrent();
77 v8::CpuProfiler* profiler = isolate->GetCpuProfiler();
80 v8::HandleScope handleScope(isolate);
81 v8::CpuProfile* profile = profiler->StopProfiling(v8String(isolate, title));
85 String profileTitle = toCoreString(profile->GetTitle());
86 double idleTime = 0.0;
87 ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap();
88 ProfileNameIdleTimeMap::iterator profileIdleTime = profileNameIdleTimeMap->find(profileTitle);
89 if (profileIdleTime != profileNameIdleTimeMap->end()) {
90 idleTime = profileIdleTime->value * 1000.0;
91 profileNameIdleTimeMap->remove(profileIdleTime);
94 return ScriptProfile::create(profile, idleTime);
97 void ScriptProfiler::collectGarbage()
99 v8::Isolate::GetCurrent()->LowMemoryNotification();
102 ScriptValue ScriptProfiler::objectByHeapObjectId(unsigned id)
104 v8::Isolate* isolate = v8::Isolate::GetCurrent();
105 v8::HeapProfiler* profiler = isolate->GetHeapProfiler();
106 v8::HandleScope handleScope(isolate);
107 v8::Handle<v8::Value> value = profiler->FindObjectById(id);
108 if (value.IsEmpty() || !value->IsObject())
109 return ScriptValue();
111 v8::Handle<v8::Object> object = value.As<v8::Object>();
113 if (object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount) {
114 v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
115 // Skip wrapper boilerplates which are like regular wrappers but don't have
117 if (!wrapper.IsEmpty() && wrapper->IsUndefined())
118 return ScriptValue();
121 ScriptState* scriptState = ScriptState::from(object->CreationContext());
122 return ScriptValue(scriptState, object);
125 unsigned ScriptProfiler::getHeapObjectId(const ScriptValue& value)
127 v8::Isolate* isolate = v8::Isolate::GetCurrent();
128 v8::HeapProfiler* profiler = isolate->GetHeapProfiler();
129 v8::SnapshotObjectId id = profiler->GetObjectId(value.v8Value());
133 void ScriptProfiler::clearHeapObjectIds()
135 v8::Isolate* isolate = v8::Isolate::GetCurrent();
136 v8::HeapProfiler* profiler = isolate->GetHeapProfiler();
137 profiler->ClearObjectIds();
142 class ActivityControlAdapter final : public v8::ActivityControl {
144 ActivityControlAdapter(ScriptProfiler::HeapSnapshotProgress* progress)
145 : m_progress(progress), m_firstReport(true) { }
146 virtual ControlOption ReportProgressValue(int done, int total) override
148 ControlOption result = m_progress->isCanceled() ? kAbort : kContinue;
150 m_firstReport = false;
151 m_progress->Start(total);
153 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 LocalDOMWindow* 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 == WrapperTypeInfo::NodeClassId);
248 if (!wrapper->IsObject())
250 Node* node = V8Node::toImpl(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(WrapperTypeInfo::NodeClassId, &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)
279 virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) override
281 if (classId != WrapperTypeInfo::NodeClassId)
286 v8::HandleScope scope(m_isolate);
287 v8::Local<v8::Object> wrapper = v8::Local<v8::Object>::New(m_isolate, v8::Persistent<v8::Object>::Cast(*value));
288 ASSERT(V8Node::hasInstance(wrapper, m_isolate));
289 ASSERT(wrapper->IsObject());
292 m_visitor->visitNode(toScriptWrappableBase(v8::Persistent<v8::Object>::Cast(*value))->toImpl<Node>());
296 WrappedNodeVisitor* m_visitor;
298 v8::Isolate* m_isolate;
300 } wrapperVisitor(visitor, isolate);
302 v8::V8::VisitHandlesWithClassIds(isolate, &wrapperVisitor);
305 ProfileNameIdleTimeMap* ScriptProfiler::currentProfileNameIdleTimeMap()
307 AtomicallyInitializedStatic(WTF::ThreadSpecific<ProfileNameIdleTimeMap>*, map = new WTF::ThreadSpecific<ProfileNameIdleTimeMap>);
311 void ScriptProfiler::setIdle(bool isIdle)
313 v8::Isolate* isolate = v8::Isolate::GetCurrent();
314 if (v8::CpuProfiler* profiler = isolate->GetCpuProfiler())
315 profiler->SetIdle(isIdle);
320 class HeapXDKStream : public v8::OutputStream {
322 HeapXDKStream(ScriptProfiler::OutputStream* stream) : m_stream(stream) { }
323 virtual void EndOfStream() override { }
325 virtual WriteResult WriteAsciiChunk(char* data, int size) override
331 virtual WriteResult WriteHeapXDKChunk(const char* symbols, int symbolsSize,
332 const char* frames, int framesSize,
333 const char* types, int typesSize,
334 const char* chunks, int chunksSize,
335 const char* retentions,
336 int retentionSize) override
338 m_stream->write(symbols, symbolsSize, frames, framesSize,
339 types, typesSize, chunks, chunksSize,
340 retentions, retentionSize);
345 ScriptProfiler::OutputStream* m_stream;
350 void ScriptProfiler::requestHeapXDKUpdate(ScriptProfiler::OutputStream* stream)
352 HeapXDKStream heapXDKStream(stream);
353 v8::Isolate::GetCurrent()->GetHeapProfiler()->GetHeapXDKStats(
357 void ScriptProfiler::startTrackingHeapObjectsXDK(int stackDepth,
360 v8::Isolate::GetCurrent()->GetHeapProfiler()->StartTrackingHeapObjectsXDK(
361 stackDepth, retentions);
364 PassRefPtr<HeapProfileXDK> ScriptProfiler::stopTrackingHeapObjectsXDK()
366 return HeapProfileXDK::create(
367 v8::Isolate::GetCurrent()
368 ->GetHeapProfiler()->StopTrackingHeapObjectsXDK());