Debugger: Move server into it's own thread
[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 <private/qdeclarativeengine_p.h>
45 #include <private/qv8profiler_p.h>
46
47 #include <QtCore/QHash>
48
49 QT_BEGIN_NAMESPACE
50
51 Q_GLOBAL_STATIC(QV8ProfilerService, v8ProfilerInstance)
52
53 class ByteArrayOutputStream : public v8::OutputStream
54 {
55     QByteArray *_buffer;
56 public:
57     ByteArrayOutputStream(QByteArray *buffer)
58         : v8::OutputStream(),
59           _buffer(buffer) {}
60     void EndOfStream() {}
61     WriteResult WriteAsciiChunk(char *data, int size)
62     {
63         QByteArray b(data, size);
64         _buffer->append(b);
65         return kContinue;
66     }
67 };
68
69 // convert to a QByteArray that can be sent to the debug client
70 QByteArray QV8ProfilerData::toByteArray() const
71 {
72     QByteArray data;
73     //### using QDataStream is relatively expensive
74     QDataStream ds(&data, QIODevice::WriteOnly);
75     ds << messageType << filename << functionname << lineNumber << totalTime << selfTime << treeLevel;
76
77     return data;
78 }
79
80 class QV8ProfilerServicePrivate : public QDeclarativeDebugServicePrivate
81 {
82     Q_DECLARE_PUBLIC(QV8ProfilerService)
83
84 public:
85     QV8ProfilerServicePrivate()
86         :initialized(false)
87         , isolate(0)
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     v8::Isolate *isolate;
101 };
102
103 QV8ProfilerService::QV8ProfilerService(QObject *parent)
104     : QDeclarativeDebugService(*(new QV8ProfilerServicePrivate()), QLatin1String("V8Profiler"), parent)
105 {
106     Q_D(QV8ProfilerService);
107     if (status() == Enabled) {
108         // ,block mode, client attached
109         while (!d->initialized)
110             waitForMessage();
111     }
112 }
113
114 QV8ProfilerService::~QV8ProfilerService()
115 {
116 }
117
118 QV8ProfilerService *QV8ProfilerService::instance()
119 {
120     return v8ProfilerInstance();
121 }
122
123 void QV8ProfilerService::addEngine(QDeclarativeEngine *engine)
124 {
125     Q_D(QV8ProfilerService);
126     Q_ASSERT(engine);
127     Q_ASSERT(!d->engines.contains(engine));
128
129     d->engines.append(engine);
130 }
131
132 void QV8ProfilerService::removeEngine(QDeclarativeEngine *engine)
133 {
134     Q_D(QV8ProfilerService);
135     Q_ASSERT(engine);
136     Q_ASSERT(d->engines.contains(engine));
137
138     d->engines.removeOne(engine);
139 }
140
141 void QV8ProfilerService::messageReceived(const QByteArray &message)
142 {
143     Q_D(QV8ProfilerService);
144
145     QDataStream ds(message);
146     QByteArray command;
147     QByteArray option;
148     QByteArray title;
149     ds >> command >> option;
150
151     if (!d->isolate) {
152         d->isolate = v8::Isolate::New();
153         v8::Isolate::Scope scope(d->isolate);
154         v8::V8::Initialize();
155     }
156
157     v8::Isolate::Scope scope(d->isolate);
158
159     if (command == "V8PROFILER") {
160         ds >>  title;
161         if (option == "start") {
162             startProfiling(QString::fromUtf8(title));
163         } else if (option == "stop") {
164             stopProfiling(QString::fromUtf8(title));
165             sendProfilingData();
166         }
167         d->initialized = true;
168     }
169
170     if (command == "V8SNAPSHOT") {
171         if (option == "full")
172             d->takeSnapshot(v8::HeapSnapshot::kFull);
173         else if (option == "delete") {
174             v8::HeapProfiler::DeleteAllSnapshots();
175         }
176     }
177
178     QDeclarativeDebugService::messageReceived(message);
179 }
180
181 void QV8ProfilerService::startProfiling(const QString &title)
182 {
183     // Start Profiling
184     v8::HandleScope handle_scope;
185     v8::Handle<v8::String> v8title = v8::String::New(reinterpret_cast<const uint16_t*>(title.data()), title.size());
186     v8::CpuProfiler::StartProfiling(v8title);
187 }
188
189 void QV8ProfilerService::stopProfiling(const QString &title)
190 {
191     Q_D(QV8ProfilerService);
192     // Stop profiling
193     v8::HandleScope handle_scope;
194     v8::Handle<v8::String> v8title = v8::String::New(reinterpret_cast<const uint16_t*>(title.data()), title.size());
195     const v8::CpuProfile *cpuProfile = v8::CpuProfiler::StopProfiling(v8title);
196     if (cpuProfile) {
197         // can happen at start
198         const v8::CpuProfileNode *rootNode = cpuProfile->GetTopDownRoot();
199         d->printProfileTree(rootNode);
200     }
201 }
202
203 void QV8ProfilerService::sendProfilingData()
204 {
205     Q_D(QV8ProfilerService);
206     // Send messages to client
207     d->sendMessages();
208 }
209
210 void QV8ProfilerServicePrivate::printProfileTree(const v8::CpuProfileNode *node, int level)
211 {
212     for (int index = 0 ; index < node->GetChildrenCount() ; index++) {
213         const v8::CpuProfileNode* childNode = node->GetChild(index);
214         if (QV8Engine::toStringStatic(childNode->GetScriptResourceName()).length() > 0) {
215
216             QV8ProfilerData rd = {(int)QV8ProfilerService::V8Entry, QV8Engine::toStringStatic(childNode->GetScriptResourceName()),
217                 QV8Engine::toStringStatic(childNode->GetFunctionName()),
218                 childNode->GetLineNumber(), childNode->GetTotalTime(), childNode->GetSelfTime(), level};
219             m_data.append(rd);
220
221             // different nodes might have common children: fix at client side
222             if (childNode->GetChildrenCount() > 0) {
223                 printProfileTree(childNode, level+1);
224             }
225         }
226     }
227 }
228
229 void QV8ProfilerServicePrivate::takeSnapshot(v8::HeapSnapshot::Type snapshotType)
230 {
231     Q_Q(QV8ProfilerService);
232
233     v8::HandleScope scope;
234     v8::Local<v8::String> title = v8::String::New("");
235
236     QByteArray jsonSnapshot;
237     ByteArrayOutputStream bos(&jsonSnapshot);
238     const v8::HeapSnapshot *snapshot = v8::HeapProfiler::TakeSnapshot(title, snapshotType);
239     snapshot->Serialize(&bos, v8::HeapSnapshot::kJSON);
240
241     QByteArray data;
242     QDataStream ds(&data, QIODevice::WriteOnly);
243     ds << (int)QV8ProfilerService::V8Snapshot << jsonSnapshot;
244
245     q->sendMessage(data);
246 }
247
248 void QV8ProfilerServicePrivate::sendMessages()
249 {
250     Q_Q(QV8ProfilerService);
251
252     for (int i = 0; i < m_data.count(); ++i)
253         q->sendMessage(m_data.at(i).toByteArray());
254     m_data.clear();
255
256     //indicate completion
257     QByteArray data;
258     QDataStream ds(&data, QIODevice::WriteOnly);
259     ds << (int)QV8ProfilerService::V8Complete;
260
261     q->sendMessage(data);
262 }
263
264
265 QT_END_NAMESPACE