OSDN Git Service

It's 2011 now.
[qt-creator-jp/qt-creator-jp.git] / src / shared / symbianutils / tcftrkmessage.cpp
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Contact: Nokia Corporation (qt-info@nokia.com)
8 **
9 ** No Commercial Usage
10 **
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
14 ** this package.
15 **
16 ** GNU Lesser General Public License Usage
17 **
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Nokia gives you certain additional
26 ** rights.  These rights are described in the Nokia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** If you have questions regarding the use of this file, please contact
30 ** Nokia at qt-info@nokia.com.
31 **
32 **************************************************************************/
33
34 #include "tcftrkmessage.h"
35 #include "json.h"
36
37 #include <QtCore/QString>
38 #include <QtCore/QTextStream>
39
40 // Names matching the enum
41 static const char *serviceNamesC[] =
42 { "Locator", "RunControl", "Processes", "Memory", "Settings", "Breakpoints",
43   "Registers", "Logging", "FileSystem", "SymbianInstall",
44   "UnknownService"};
45
46 namespace tcftrk {
47
48 SYMBIANUTILS_EXPORT QString joinByteArrays(const QVector<QByteArray> &a, char sep)
49 {
50     QString rc;
51     const int count = a.size();
52     for (int i = 0; i < count; i++) {
53         if (i)
54             rc += QLatin1Char(sep);
55         rc += QString::fromUtf8(a.at(i));
56     }
57     return rc;
58 }
59
60 static inline bool jsonToBool(const JsonValue& js)
61 {
62     return js.type() == JsonValue::Boolean && js.data() == "true";
63 }
64
65 SYMBIANUTILS_EXPORT const char *serviceName(Services s)
66 {
67     return serviceNamesC[s];
68 }
69
70 SYMBIANUTILS_EXPORT Services serviceFromName(const char *n)
71 {
72     const int count = sizeof(serviceNamesC)/sizeof(char *);
73     for (int i = 0; i < count; i++)
74         if (!qstrcmp(serviceNamesC[i], n))
75             return static_cast<Services>(i);
76     return UnknownService;
77 }
78
79 SYMBIANUTILS_EXPORT QString formatData(const QByteArray &a)
80 {
81     const int columns = 16;
82     QString rc;
83     QTextStream str(&rc);
84     str.setIntegerBase(16);
85     str.setPadChar(QLatin1Char('0'));
86     const unsigned char *start = reinterpret_cast<const unsigned char *>(a.constData());
87     const unsigned char *end = start + a.size();
88     for  (const unsigned char *p = start; p < end ; ) {
89         str << "0x";
90         str.setFieldWidth(4);
91         str << (p - start);
92         str.setFieldWidth(0);
93         str << ' ';
94         QString asc;
95         int c = 0;
96         for ( ; c < columns && p < end; c++, p++) {
97             const unsigned u = *p;
98             str.setFieldWidth(2);
99             str << u;
100             str.setFieldWidth(0);
101             str << ' ';
102             switch (u) {
103             case '\n':
104                 asc += QLatin1String("\\n");
105                 break;
106             case '\r':
107                 asc += QLatin1String("\\r");
108                 break;
109             case '\t':
110                 asc += QLatin1String("\\t");
111                 break;
112             default:
113                 if (u >= 32 && u < 128) {
114                     asc += QLatin1Char(' ');
115                     asc += QLatin1Char(u);
116                 } else {
117                     asc += QLatin1String(" .");
118                 }
119                 break;
120             }
121         }
122         if (const int remainder = columns - c)
123             str << QString(3 * remainder, QLatin1Char(' '));
124         str << ' ' << asc << '\n';
125     }
126     return rc;
127 }
128
129 // ----------- RunControlContext
130 RunControlContext::RunControlContext() :
131         flags(0), resumeFlags(0)
132 {
133 }
134
135 void RunControlContext::clear()
136 {
137     flags =0;
138     resumeFlags = 0;
139     id.clear();
140     osid.clear();
141     parentId.clear();
142 }
143
144 RunControlContext::Type RunControlContext::typeFromTcfId(const QByteArray &id)
145 {
146     // "p12" or "p12.t34"?
147     return id.contains(".t") ? Thread : Process;
148 }
149
150 unsigned RunControlContext::processId() const
151 {
152     return processIdFromTcdfId(id);
153 }
154
155 unsigned RunControlContext::threadId() const
156 {
157     return threadIdFromTcdfId(id);
158 }
159
160 unsigned RunControlContext::processIdFromTcdfId(const QByteArray &id)
161 {
162     // Cut out process id from "p12" or "p12.t34"?
163     if (!id.startsWith('p'))
164         return 0;
165     const int dotPos = id.indexOf('.');
166     const int pLen = dotPos == -1 ? id.size() : dotPos;
167     return id.mid(1, pLen - 1).toUInt();
168 }
169
170 unsigned RunControlContext::threadIdFromTcdfId(const QByteArray &id)
171 {
172     const int tPos = id.indexOf(".t");
173     return tPos != -1 ? id.mid(tPos + 2).toUInt() : uint(0);
174 }
175
176 QByteArray RunControlContext::tcfId(unsigned processId,  unsigned threadId /* = 0 */)
177 {
178     QByteArray rc("p");
179     rc += QByteArray::number(processId);
180     if (threadId) {
181         rc += ".t";
182         rc += QByteArray::number(threadId);
183     }
184     return rc;
185 }
186
187 RunControlContext::Type RunControlContext::type() const
188 {
189     return RunControlContext::typeFromTcfId(id);
190 }
191
192 bool RunControlContext::parse(const JsonValue &val)
193 {
194     clear();
195     if (val.type() != JsonValue::Object)
196         return false;
197     foreach(const JsonValue &c, val.children()) {
198         if (c.name() == "ID") {
199             id = c.data();
200         } else if (c.name() == "OSID") {
201             osid = c.data();
202         } else if (c.name() == "ParentID") {
203             parentId = c.data();
204         }  else if (c.name() == "IsContainer") {
205             if (jsonToBool(c))
206                 flags |= Container;
207         }  else if (c.name() == "CanTerminate") {
208             if (jsonToBool(c))
209                 flags |= CanTerminate;
210         }  else if (c.name() == "CanResume") {
211             resumeFlags = c.data().toUInt();
212         }  else if (c.name() == "HasState") {
213             if (jsonToBool(c))
214                 flags |= HasState;
215         } else if (c.name() == "CanSuspend") {
216             if (jsonToBool(c))
217                 flags |= CanSuspend;
218         }
219     }
220     return true;
221 }
222
223 QString RunControlContext::toString() const
224 {
225     QString rc;
226     QTextStream str(&rc);
227     format(str);
228     return rc;
229 }
230
231 void RunControlContext::format(QTextStream &str) const
232 {
233     str << " id='" << id << "' osid='" << osid
234         << "' parentId='" << parentId <<"' ";
235     if (flags & Container)
236         str << "[container] ";
237     if (flags & HasState)
238         str << "[has state] ";
239     if (flags & CanSuspend)
240         str << "[can suspend] ";
241     if (flags & CanSuspend)
242         str << "[can terminate] ";
243     str.setIntegerBase(16);
244     str << " resume_flags: 0x" <<  resumeFlags;
245     str.setIntegerBase(10);
246 }
247
248 // ------ ModuleLoadEventInfo
249 ModuleLoadEventInfo::ModuleLoadEventInfo() :
250    loaded(false), codeAddress(0), dataAddress(0), requireResume(false)
251 {
252 }
253
254 void ModuleLoadEventInfo::clear()
255 {
256     loaded = requireResume = false;
257     codeAddress = dataAddress =0;
258 }
259
260 bool ModuleLoadEventInfo::parse(const JsonValue &val)
261 {
262     clear();
263     if (val.type() != JsonValue::Object)
264         return false;
265     foreach(const JsonValue &c, val.children()) {
266         if (c.name() == "Name") {
267             name = c.data();
268         } else if (c.name() == "File") {
269             file = c.data();
270         } else if (c.name() == "CodeAddress") {
271             codeAddress = c.data().toULongLong();
272         }  else if (c.name() == "DataAddress") {
273             dataAddress = c.data().toULongLong();
274         }  else if (c.name() == "Loaded") {
275             loaded = jsonToBool(c);
276         }  else if (c.name() == "RequireResume") {
277             requireResume =jsonToBool(c);
278         }
279     }
280     return true;
281 }
282 void ModuleLoadEventInfo::format(QTextStream &str) const
283 {
284     str << "name='" << name << "' file='" << file << "' " <<
285             (loaded ? "[loaded] " : "[not loaded] ");
286     if (requireResume)
287         str << "[requires resume] ";
288     str.setIntegerBase(16);
289     str  << " code: 0x" << codeAddress << " data: 0x" << dataAddress;
290     str.setIntegerBase(10);
291 }
292
293 // ---------------------- Breakpoint
294
295 // Types matching enum
296 static const char *breakPointTypesC[] = {"Software", "Hardware", "Auto"};
297
298 Breakpoint::Breakpoint(quint64 loc) :
299     type(Auto), enabled(true), ignoreCount(0), location(loc), size(1), thumb(true)
300 {
301     if (loc)
302         id = idFromLocation(location);
303 }
304
305 void Breakpoint::setContextId(unsigned processId, unsigned threadId)
306 {
307     contextIds = QVector<QByteArray>(1, RunControlContext::tcfId(processId, threadId));
308 }
309
310 QByteArray Breakpoint::idFromLocation(quint64 loc)
311 {
312     return QByteArray("BP_0x") + QByteArray::number(loc, 16);
313 }
314
315 QString Breakpoint::toString() const
316 {
317     QString rc;
318     QTextStream str(&rc);
319     str.setIntegerBase(16);
320     str << "Breakpoint '" << id << "' "  << breakPointTypesC[type] << " for contexts '"
321             << joinByteArrays(contextIds, ',') << "' at 0x" << location;
322     str.setIntegerBase(10);
323     str << " size " << size;
324     if (enabled)
325         str << " [enabled]";
326     if (thumb)
327         str << " [thumb]";
328     if (ignoreCount)
329         str << " IgnoreCount " << ignoreCount;
330     return rc;
331 }
332
333 JsonInputStream &operator<<(JsonInputStream &str, const Breakpoint &b)
334 {
335     if (b.contextIds.isEmpty())
336         qWarning("tcftrk::Breakpoint: No context ids specified");
337
338     str << '{' << "ID" << ':' << QString::fromUtf8(b.id) << ','
339         << "BreakpointType" << ':' << breakPointTypesC[b.type] << ','
340         << "Enabled" << ':' << b.enabled << ','
341         << "IgnoreCount" << ':' << b.ignoreCount << ','
342         << "ContextIds" << ':' << b.contextIds << ','
343         << "Location" << ':' << QString::number(b.location) << ','
344         << "Size"  << ':' << b.size << ','
345         << "THUMB_BREAKPOINT" << ':' << b.thumb
346         << '}';
347     return str;
348 }
349
350 // --- Events
351 TcfTrkEvent::TcfTrkEvent(Type type) : m_type(type)
352 {
353 }
354
355 TcfTrkEvent::~TcfTrkEvent()
356 {
357 }
358
359 TcfTrkEvent::Type TcfTrkEvent::type() const
360 {
361     return m_type;
362 }
363
364 QString TcfTrkEvent::toString() const
365 {
366     return QString();
367 }
368
369 static const char sharedLibrarySuspendReasonC[] = "Shared Library";
370
371 TcfTrkEvent *TcfTrkEvent::parseEvent(Services s, const QByteArray &nameBA, const QVector<JsonValue> &values)
372 {
373     switch (s) {
374     case LocatorService:
375         if (nameBA == "Hello" && values.size() == 1 && values.front().type() == JsonValue::Array) {
376             QStringList services;
377             foreach (const JsonValue &jv, values.front().children())
378                 services.push_back(QString::fromUtf8(jv.data()));
379             return new TcfTrkLocatorHelloEvent(services);
380         }
381         break;
382     case RunControlService:
383         if (values.empty())
384             return 0;
385         // "id/PC/Reason/Data"
386         if (nameBA == "contextSuspended" && values.size() == 4) {
387             const QByteArray idBA = values.at(0).data();
388             const quint64 pc = values.at(1).data().toULongLong();
389             const QByteArray reasonBA = values.at(2).data();
390             QByteArray messageBA;
391             // Module load: Special
392             if (reasonBA == sharedLibrarySuspendReasonC) {
393                 ModuleLoadEventInfo info;
394                 if (!info.parse(values.at(3)))
395                     return 0;
396                 return new TcfTrkRunControlModuleLoadContextSuspendedEvent(idBA, reasonBA, pc, info);
397             } else {
398                 // hash containing a 'message'-key with a verbose crash message.
399                 if (values.at(3).type() == JsonValue::Object && values.at(3).childCount()
400                     && values.at(3).children().at(0).type() == JsonValue::String)
401                     messageBA = values.at(3).children().at(0).data();
402             }
403             return new TcfTrkRunControlContextSuspendedEvent(idBA, reasonBA, messageBA, pc);
404         } // "contextSuspended"
405         if (nameBA == "contextAdded")
406             return TcfTrkRunControlContextAddedEvent::parseEvent(values);
407         if (nameBA == "contextRemoved" && values.front().type() == JsonValue::Array) {
408             QVector<QByteArray> ids;
409             foreach(const JsonValue &c, values.front().children())
410                 ids.push_back(c.data());
411             return new TcfTrkRunControlContextRemovedEvent(ids);
412         }
413         break;
414     case LoggingService:
415         if (nameBA == "write" && values.size() >= 2)
416             return new TcfTrkLoggingWriteEvent(values.at(0).data(), values.at(1).data());
417         break;
418    default:
419         break;
420     }
421     return 0;
422 }
423
424 // -------------- TcfTrkServiceHelloEvent
425 TcfTrkLocatorHelloEvent::TcfTrkLocatorHelloEvent(const QStringList &s) :
426     TcfTrkEvent(LocatorHello),
427     m_services(s)
428 {
429 }
430
431 QString TcfTrkLocatorHelloEvent::toString() const
432 {
433     return QLatin1String("ServiceHello: ") + m_services.join(QLatin1String(", "));
434 }
435
436 // --------------  Logging event
437
438 TcfTrkLoggingWriteEvent::TcfTrkLoggingWriteEvent(const QByteArray &console, const QByteArray &message) :
439     TcfTrkEvent(LoggingWriteEvent), m_console(console), m_message(message)
440 {
441 }
442
443 QString TcfTrkLoggingWriteEvent::toString() const
444 {
445     QByteArray msgBA = m_console;
446     msgBA += ": ";
447     msgBA += m_message;
448     return QString::fromUtf8(msgBA);
449 }
450
451 // -------------- TcfTrkIdEvent
452 TcfTrkIdEvent::TcfTrkIdEvent(Type t, const QByteArray &id) :
453    TcfTrkEvent(t), m_id(id)
454 {
455 }
456
457 // ---------- TcfTrkIdsEvent
458 TcfTrkIdsEvent::TcfTrkIdsEvent(Type t, const QVector<QByteArray> &ids) :
459     TcfTrkEvent(t), m_ids(ids)
460 {
461 }
462
463 QString TcfTrkIdsEvent::joinedIdString(const char sep) const
464 {
465     return joinByteArrays(m_ids, sep);
466 }
467
468 //  ---------------- TcfTrkRunControlContextAddedEvent
469 TcfTrkRunControlContextAddedEvent::TcfTrkRunControlContextAddedEvent(const RunControlContexts &c) :
470         TcfTrkEvent(RunControlContextAdded), m_contexts(c)
471 {
472 }
473
474 TcfTrkRunControlContextAddedEvent
475         *TcfTrkRunControlContextAddedEvent::parseEvent(const QVector<JsonValue> &values)
476 {
477     // Parse array of contexts
478     if (values.size() < 1 || values.front().type() != JsonValue::Array)
479         return 0;
480
481     RunControlContexts contexts;
482     foreach (const JsonValue &v, values.front().children()) {
483         RunControlContext context;
484         if (context.parse(v))
485             contexts.push_back(context);
486     }
487     return new TcfTrkRunControlContextAddedEvent(contexts);
488 }
489
490 QString TcfTrkRunControlContextAddedEvent::toString() const
491 {
492     QString rc;
493     QTextStream str(&rc);
494     str << "RunControl: " << m_contexts.size() << " context(s) "
495         << (type() == RunControlContextAdded ? "added" : "removed")
496         << '\n';
497     foreach (const RunControlContext &c, m_contexts) {
498         c.format(str);
499         str << '\n';
500     }
501     return rc;
502 }
503
504 // --------------- TcfTrkRunControlContextRemovedEvent
505 TcfTrkRunControlContextRemovedEvent::TcfTrkRunControlContextRemovedEvent(const QVector<QByteArray> &ids) :
506         TcfTrkIdsEvent(RunControlContextRemoved, ids)
507 {
508 }
509
510 QString TcfTrkRunControlContextRemovedEvent::toString() const
511 {
512     return QLatin1String("RunControl: Removed contexts '") + joinedIdString() + ("'.");
513 }
514
515 // --------------- TcfTrkRunControlContextSuspendedEvent
516 TcfTrkRunControlContextSuspendedEvent::TcfTrkRunControlContextSuspendedEvent(const QByteArray &id,
517                                                                              const QByteArray &reason,
518                                                                              const QByteArray &message,
519                                                                              quint64 pc) :
520         TcfTrkIdEvent(RunControlSuspended, id), m_pc(pc), m_reason(reason), m_message(message)
521 {
522 }
523
524 TcfTrkRunControlContextSuspendedEvent::TcfTrkRunControlContextSuspendedEvent(Type t,
525                                                                              const QByteArray &id,
526                                                                              const QByteArray &reason,
527                                                                              quint64 pc) :
528         TcfTrkIdEvent(t, id), m_pc(pc), m_reason(reason)
529 {
530 }
531
532 void TcfTrkRunControlContextSuspendedEvent::format(QTextStream &str) const
533 {
534     str.setIntegerBase(16);
535     str << "RunControl: '" << idString()  << "' suspended at 0x"
536             << m_pc << ": '" << m_reason << "'.";
537     str.setIntegerBase(10);
538     if (!m_message.isEmpty())
539         str << " (" <<m_message << ')';
540 }
541
542 QString TcfTrkRunControlContextSuspendedEvent::toString() const
543 {
544     QString rc;
545     QTextStream str(&rc);
546     format(str);
547     return rc;
548 }
549
550 TcfTrkRunControlContextSuspendedEvent::Reason TcfTrkRunControlContextSuspendedEvent::reason() const
551 {
552     if (m_reason == sharedLibrarySuspendReasonC)
553         return ModuleLoad;
554     if (m_reason == "Breakpoint")
555         return BreakPoint;
556     // 'Data abort exception'/'Thread has panicked' ... unfortunately somewhat unspecific.
557     if (m_reason.contains("exception") || m_reason.contains("panick"))
558         return Crash;
559     return Other;
560 }
561
562 TcfTrkRunControlModuleLoadContextSuspendedEvent::TcfTrkRunControlModuleLoadContextSuspendedEvent(const QByteArray &id,
563                                                                                                  const QByteArray &reason,
564                                                                                                  quint64 pc,
565                                                                                                  const ModuleLoadEventInfo &mi) :
566     TcfTrkRunControlContextSuspendedEvent(RunControlModuleLoadSuspended, id, reason, pc),
567     m_mi(mi)
568 {
569 }
570
571 QString TcfTrkRunControlModuleLoadContextSuspendedEvent::toString() const
572 {
573     QString rc;
574     QTextStream str(&rc);
575     TcfTrkRunControlContextSuspendedEvent::format(str);
576     str <<  ' ';
577     m_mi.format(str);
578     return rc;
579 }
580
581
582 } // namespace tcftrk