QV8Profiler service
[profile/ivi/qtdeclarative.git] / src / declarative / debugger / qv8profilerservice.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the QtDeclarative module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qv8profilerservice_p.h"
43 #include "qdeclarativedebugservice_p_p.h"
44 #include "qdeclarativeengine_p.h"
45 #include "private/qv8profiler_p.h"
46 #include "qjsconverter_p.h"
47
48 #include <QtCore/QHash>
49
50 QT_BEGIN_NAMESPACE
51
52 Q_GLOBAL_STATIC(QV8ProfilerService, v8ServiceInstance)
53
54 class ByteArrayOutputStream : public v8::OutputStream
55 {
56     QByteArray *_buffer;
57 public:
58     ByteArrayOutputStream(QByteArray *buffer)
59         : v8::OutputStream(),
60           _buffer(buffer) {}
61     void EndOfStream() {}
62     WriteResult WriteAsciiChunk(char *data, int size)
63     {
64         QByteArray b(data, size);
65         _buffer->append(b);
66         return kContinue;
67     }
68 };
69
70 // convert to a QByteArray that can be sent to the debug client
71 QByteArray QV8ProfilerData::toByteArray() const
72 {
73     QByteArray data;
74     //### using QDataStream is relatively expensive
75     QDataStream ds(&data, QIODevice::WriteOnly);
76     ds << messageType << filename << functionname << lineNumber << totalTime << selfTime << treeLevel;
77
78     return data;
79 }
80
81 class QV8ProfilerServicePrivate : public QDeclarativeDebugServicePrivate
82 {
83     Q_DECLARE_PUBLIC(QV8ProfilerService)
84
85 public:
86     QV8ProfilerServicePrivate()
87         :initialized(false)
88     {
89     }
90
91     void takeSnapshot(v8::HeapSnapshot::Type);
92
93     void printProfileTree(const v8::CpuProfileNode *node, int level = 0);
94     void sendMessages();
95
96     QList<QV8ProfilerData> m_data;
97
98     bool initialized;
99     QList<QDeclarativeEngine *> engines;
100 };
101
102 QV8ProfilerService::QV8ProfilerService(QObject *parent)
103     : QDeclarativeDebugService(*(new QV8ProfilerServicePrivate()), QLatin1String("V8Profiler"), parent)
104 {
105     Q_D(QV8ProfilerService);
106     if (status() == Enabled) {
107         // ,block mode, client attached
108         while (!d->initialized)
109             waitForMessage();
110     }
111 }
112
113 QV8ProfilerService::~QV8ProfilerService()
114 {
115 }
116
117 QV8ProfilerService *QV8ProfilerService::instance()
118 {
119     return v8ServiceInstance();
120 }
121
122 void QV8ProfilerService::addEngine(QDeclarativeEngine *engine)
123 {
124     Q_D(QV8ProfilerService);
125     Q_ASSERT(engine);
126     Q_ASSERT(!d->engines.contains(engine));
127
128     d->engines.append(engine);
129 }
130
131 void QV8ProfilerService::removeEngine(QDeclarativeEngine *engine)
132 {
133     Q_D(QV8ProfilerService);
134     Q_ASSERT(engine);
135     Q_ASSERT(d->engines.contains(engine));
136
137     d->engines.removeOne(engine);
138 }
139
140 void QV8ProfilerService::messageReceived(const QByteArray &message)
141 {
142     Q_D(QV8ProfilerService);
143
144     QDataStream ds(message);
145     QByteArray command;
146     QByteArray option;
147     QByteArray title;
148     ds >> command >> option;
149
150     if (command == "V8PROFILER") {
151         ds >>  title;
152         if (option == "start") {
153             d->initialized = true;
154             startProfiling(QString::fromUtf8(title));
155         } else if (option == "stop") {
156             stopProfiling(QString::fromUtf8(title));
157             // Send messages to client
158             d->sendMessages();
159         }
160     }
161
162     if (command == "V8SNAPSHOT") {
163             QByteArray snapshotType;
164             ds >> snapshotType;
165
166             if (snapshotType == "aggregated")
167                 d->takeSnapshot(v8::HeapSnapshot::kAggregated);
168             else if (snapshotType == "full")
169                 d->takeSnapshot(v8::HeapSnapshot::kFull);
170         } else if (command == "deletesnapshots") {
171             v8::HeapProfiler::DeleteAllSnapshots();
172         }
173
174     QDeclarativeDebugService::messageReceived(message);
175 }
176
177 void QV8ProfilerService::startProfiling(const QString &title)
178 {
179     // Start Profiling
180     v8::HandleScope handle_scope;
181     v8::Handle<v8::String> v8title = v8::String::New(reinterpret_cast<const uint16_t*>(title.data()), title.size());
182     v8::CpuProfiler::StartProfiling(v8title);
183 }
184
185 void QV8ProfilerService::stopProfiling(const QString &title)
186 {
187     Q_D(QV8ProfilerService);
188     // Stop profiling
189     v8::HandleScope handle_scope;
190     v8::Handle<v8::String> v8title = v8::String::New(reinterpret_cast<const uint16_t*>(title.data()), title.size());
191     const v8::CpuProfile *cpuProfile = v8::CpuProfiler::StopProfiling(v8title);
192     const v8::CpuProfileNode *rootNode = cpuProfile->GetTopDownRoot();
193
194     d->printProfileTree(rootNode);
195 }
196
197 void QV8ProfilerServicePrivate::printProfileTree(const v8::CpuProfileNode *node, int level)
198 {
199     for (int index = 0 ; index < node->GetChildrenCount() ; index++) {
200         const v8::CpuProfileNode* childNode = node->GetChild(index);
201         if (QV8Engine::toStringStatic(childNode->GetScriptResourceName()).length() > 0) {
202
203             QV8ProfilerData rd = {(int)QV8ProfilerService::V8Entry, QV8Engine::toStringStatic(childNode->GetScriptResourceName()),
204                 QV8Engine::toStringStatic(childNode->GetFunctionName()),
205                 childNode->GetLineNumber(), childNode->GetTotalTime(), childNode->GetSelfTime(), level};
206             m_data.append(rd);
207
208             // different nodes might have common children: fix at client side
209             if (childNode->GetChildrenCount() > 0) {
210                 printProfileTree(childNode, level+1);
211             }
212         }
213     }
214 }
215
216 void QV8ProfilerServicePrivate::takeSnapshot(v8::HeapSnapshot::Type snapshotType)
217 {
218     Q_Q(QV8ProfilerService);
219
220     v8::HandleScope scope;
221     v8::Local<v8::String> title = v8::String::New("");
222
223     const v8::HeapSnapshot *snapshot = v8::HeapProfiler::TakeSnapshot(title, snapshotType);
224
225     QByteArray data;
226     QDataStream ds(&data, QIODevice::WriteOnly);
227     ds << (int)QV8ProfilerService::V8Snapshot;
228
229     ByteArrayOutputStream bos(&data);
230     snapshot->Serialize(&bos, v8::HeapSnapshot::kJSON);
231
232     q->sendMessage(data);
233 }
234
235 void QV8ProfilerServicePrivate::sendMessages()
236 {
237     Q_Q(QV8ProfilerService);
238
239     for (int i = 0; i < m_data.count(); ++i)
240         q->sendMessage(m_data.at(i).toByteArray());
241     m_data.clear();
242
243     //indicate completion
244     QByteArray data;
245     QDataStream ds(&data, QIODevice::WriteOnly);
246     ds << (int)QV8ProfilerService::V8Complete;
247
248     q->sendMessage(data);
249 }
250
251
252 QT_END_NAMESPACE