OSDN Git Service

It's 2011 now.
[qt-creator-jp/qt-creator-jp.git] / src / shared / symbianutils / trkutils.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 "trkutils.h"
35 #include <ctype.h>
36
37 #include <QtCore/QCoreApplication>
38 #include <QtCore/QDebug>
39 #include <QtCore/QDate>
40 #include <QtCore/QDateTime>
41 #include <QtCore/QTime>
42
43 #define logMessage(s)  do { qDebug() << "TRKCLIENT: " << s; } while (0)
44
45 namespace trk {
46
47 Library::Library() : codeseg(0), dataseg(0), pid(0)
48 {
49 }
50
51 Library::Library(const TrkResult &result) : codeseg(0), dataseg(0), pid(0)
52 {
53     if (result.data.size() < 20) {
54         qWarning("Invalid trk creation notification received.");
55         return;
56     }
57
58     const char *data = result.data.constData();
59     pid = extractInt(data + 2);
60     codeseg = extractInt(data + 10);
61     dataseg = extractInt(data + 14);
62     const uint len = extractShort(data + 18);
63     name = result.data.mid(20, len);
64 }
65
66 TrkAppVersion::TrkAppVersion()
67 {
68     reset();
69 }
70
71 void TrkAppVersion::reset()
72 {
73     trkMajor = trkMinor= protocolMajor = protocolMinor = 0;
74 }
75
76 Session::Session()
77 {
78     reset();
79 }
80
81 void Session::reset()
82 {
83     cpuMajor = 0;
84     cpuMinor = 0;
85     bigEndian = 0;
86     defaultTypeSize = 0;
87     fpTypeSize = 0;
88     extended1TypeSize = 0;
89     extended2TypeSize = 0;
90     pid = 0;
91     mainTid = 0;
92     tid = 0;
93     codeseg = 0;
94     dataseg = 0;
95
96     libraries.clear();
97     trkAppVersion.reset();
98 }
99
100 static QString formatCpu(int major, int minor)
101 {
102     //: CPU description of an S60 device
103     //: %1 major verison, %2 minor version
104     //: %3 real name of major verison, %4 real name of minor version
105     const QString str = QCoreApplication::translate("trk::Session", "CPU: v%1.%2%3%4");
106     QString majorStr;
107     QString minorStr;
108     switch (major) {
109     case 0x04:
110         majorStr = " ARM";
111         break;
112     }
113     switch (minor) {
114     case 0x00:
115         minorStr = " 920T";
116         break;
117     }
118     return str.arg(major).arg(minor).arg(majorStr).arg(minorStr);
119  }
120
121 QString formatTrkVersion(const TrkAppVersion &version)
122 {
123     QString str = QCoreApplication::translate("trk::Session",
124                                               "App TRK: v%1.%2 TRK protocol: v%3.%4");
125     str = str.arg(version.trkMajor).arg(version.trkMinor);
126     return str.arg(version.protocolMajor).arg(version.protocolMinor);
127 }
128
129 QString Session::deviceDescription(unsigned verbose) const
130 {
131     if (!cpuMajor)
132         return QString();
133
134     //: s60description
135     //: description of an S60 device
136     //: %1 CPU description, %2 endianness
137     //: %3 default type size (if any), %4 float size (if any)
138     //: %5 TRK version
139     QString msg = QCoreApplication::translate("trk::Session", "%1, %2%3%4, %5");
140     QString endianness = bigEndian
141                          ? QCoreApplication::translate("trk::Session", "big endian")
142                          : QCoreApplication::translate("trk::Session", "little endian");
143     msg = msg.arg(formatCpu(cpuMajor, cpuMinor)).arg(endianness);
144     QString defaultTypeSizeStr;
145     QString fpTypeSizeStr;
146     if (verbose && defaultTypeSize)
147         //: will be inserted into s60description
148         defaultTypeSizeStr = QCoreApplication::translate("trk::Session", ", type size: %1").arg(defaultTypeSize);
149     if (verbose && fpTypeSize)
150         //: will be inserted into s60description
151         fpTypeSizeStr = QCoreApplication::translate("trk::Session", ", float size: %1").arg(fpTypeSize);
152     msg = msg.arg(defaultTypeSizeStr).arg(fpTypeSizeStr);
153     return msg.arg(formatTrkVersion(trkAppVersion));
154 }
155
156 QByteArray Session::gdbLibraryList() const
157 {
158     const int count = libraries.size();
159     QByteArray response = "l<library-list>";
160     for (int i = 0; i != count; ++i) {
161         const trk::Library &lib = libraries.at(i);
162         response += "<library name=\"";
163         response += lib.name;
164         response += "\">";
165         response += "<section address=\"0x";
166         response += trk::hexNumber(lib.codeseg);
167         response += "\"/>";
168         response += "<section address=\"0x";
169         response += trk::hexNumber(lib.dataseg);
170         response += "\"/>";
171         response += "<section address=\"0x";
172         response += trk::hexNumber(lib.dataseg);
173         response += "\"/>";
174         response += "</library>";
175     }
176     response += "</library-list>";
177     return response;
178 }
179
180 QByteArray Session::gdbQsDllInfo(int start, int count) const
181 {
182     // Happens with  gdb 6.4.50.20060226-cvs / CodeSourcery.
183     // Never made it into FSF gdb that got qXfer:libraries:read instead.
184     // http://sourceware.org/ml/gdb/2007-05/msg00038.html
185     // Name=hexname,TextSeg=textaddr[,DataSeg=dataaddr]
186     const int libraryCount = libraries.size();
187     const int end = count < 0 ? libraryCount : qMin(libraryCount, start + count);
188     QByteArray response(1, end == libraryCount ? 'l' : 'm');
189     for (int i = start; i < end; ++i) {
190         if (i != start)
191             response += ';';
192         const Library &lib = libraries.at(i);
193         response += "Name=";
194         response += lib.name.toHex();
195         response += ",TextSeg=";
196         response += hexNumber(lib.codeseg);
197         response += ",DataSeg=";
198         response += hexNumber(lib.dataseg);
199     }
200     return response;
201 }
202
203 QString Session::toString() const
204 {
205     QString rc;
206     QTextStream str(&rc);
207     str << "Session: " << deviceDescription(false) << '\n'
208             << "pid: " << pid <<  "main thread: " << mainTid
209             << " current thread: " << tid << ' ';
210     str.setIntegerBase(16);
211     str << " code: 0x" << codeseg << " data: 0x" << dataseg << '\n';
212     if (const int libCount = libraries.size()) {
213         str << "Libraries:\n";
214         for (int i = 0; i < libCount; i++)
215             str << " #" << i << ' ' << libraries.at(i).name
216                 << " code: 0x" << libraries.at(i).codeseg
217                 << " data: 0x" << libraries.at(i).dataseg << '\n';
218     }
219     if (const int moduleCount = modules.size()) {
220         str << "Modules:\n";
221         for (int i = 0; i < moduleCount; i++)
222             str << " #" << i << ' ' << modules.at(i) << '\n';
223     }
224     str.setIntegerBase(10);
225     if (!addressToBP.isEmpty()) {
226         typedef QHash<uint, uint>::const_iterator BP_ConstIterator;
227         str << "Breakpoints:\n";
228         const BP_ConstIterator cend = addressToBP.constEnd();
229         for (BP_ConstIterator it = addressToBP.constBegin(); it != cend; ++it) {
230             str.setIntegerBase(16);
231             str << "  0x" << it.key();
232             str.setIntegerBase(10);
233             str << ' ' << it.value() << '\n';
234         }
235     }
236
237     return rc;
238 }
239
240 // --------------
241
242 QByteArray decode7d(const QByteArray &ba)
243 {
244     QByteArray res;
245     res.reserve(ba.size());
246     for (int i = 0; i < ba.size(); ++i) {
247         byte c = byte(ba.at(i));
248         if (c == 0x7d) {
249             ++i;
250             c = 0x20 ^ byte(ba.at(i));
251         }
252         res.append(c);
253     }
254     return res;
255 }
256
257 QByteArray encode7d(const QByteArray &ba)
258 {
259     QByteArray res;
260     res.reserve(ba.size() + 2);
261     for (int i = 0; i < ba.size(); ++i) {
262         byte c = byte(ba.at(i));
263         if (c == 0x7e || c == 0x7d) {
264             res.append(0x7d);
265             res.append(0x20 ^ c);
266         } else {
267             res.append(c);
268         }
269     }
270     return res;
271 }
272
273 // FIXME: Use the QByteArray based version below?
274 static inline QString stringFromByte(byte c)
275 {
276     return QString::fromLatin1("%1").arg(c, 2, 16, QChar('0'));
277 }
278
279 SYMBIANUTILS_EXPORT QString stringFromArray(const QByteArray &ba, int maxLen)
280 {
281     QString str;
282     QString ascii;
283     const int size = maxLen == -1 ? ba.size() : qMin(ba.size(), maxLen);
284     for (int i = 0; i < size; ++i) {
285         const int c = byte(ba.at(i));
286         str += QString::fromAscii("%1 ").arg(c, 2, 16, QChar('0'));
287         ascii += QChar(c).isPrint() ? QChar(c) : QChar('.');
288     }
289     if (size != ba.size()) {
290         str += QLatin1String("...");
291         ascii += QLatin1String("...");
292     }
293     return str + QLatin1String("  ") + ascii;
294 }
295
296 SYMBIANUTILS_EXPORT QByteArray hexNumber(uint n, int digits)
297 {
298     QByteArray ba = QByteArray::number(n, 16);
299     if (digits == 0 || ba.size() == digits)
300         return ba;
301     return QByteArray(digits - ba.size(), '0') + ba;
302 }
303
304 SYMBIANUTILS_EXPORT QByteArray hexxNumber(uint n, int digits)
305 {
306     return "0x" + hexNumber(n, digits);
307 }
308
309 TrkResult::TrkResult() :
310     code(0),
311     token(0),
312     isDebugOutput(false)
313 {
314 }
315
316 void TrkResult::clear()
317 {
318     code = token= 0;
319     isDebugOutput = false;
320     data.clear();
321     cookie = QVariant();
322 }
323
324 QString TrkResult::toString() const
325 {
326     QString res = stringFromByte(code);
327     res += QLatin1String(" [");
328     res += stringFromByte(token);
329     res += QLatin1Char(']');
330     res += QLatin1Char(' ');
331     res += stringFromArray(data);
332     return res;
333 }
334
335 QByteArray frameMessage(byte command, byte token, const QByteArray &data, bool serialFrame)
336 {
337     byte s = command + token;
338     for (int i = 0; i != data.size(); ++i)
339         s += data.at(i);
340     byte checksum = 255 - (s & 0xff);
341     //int x = s + ~s;
342     //logMessage("check: " << s << checksum << x;
343
344     QByteArray response;
345     response.reserve(data.size() + 3);
346     response.append(char(command));
347     response.append(char(token));
348     response.append(data);
349     response.append(char(checksum));
350
351     QByteArray encodedData = encode7d(response);
352
353     QByteArray ba;
354     ba.reserve(encodedData.size() + 6);
355     if (serialFrame) {
356         ba.append(char(0x01));
357         ba.append(char(0x90));
358         const ushort encodedSize = encodedData.size() + 2; // 2 x 0x7e
359         appendShort(&ba, encodedSize, BigEndian);
360     }
361     ba.append(char(0x7e));
362     ba.append(encodedData);
363     ba.append(char(0x7e));
364
365     return ba;
366 }
367
368 /* returns 0 if array doesn't represent a result,
369 otherwise returns the length of the result data */
370 ushort isValidTrkResult(const QByteArray &buffer, bool serialFrame, ushort& mux)
371 {
372     if (serialFrame) {
373         // Serial protocol with length info
374         if (buffer.length() < 4)
375             return 0;
376         mux = extractShort(buffer.data());
377         const ushort len = extractShort(buffer.data() + 2);
378         return (buffer.size() >= len + 4) ? len : ushort(0);
379     }
380     // Frameless protocol without length info
381     const char delimiter = char(0x7e);
382     const int firstDelimiterPos = buffer.indexOf(delimiter);
383     // Regular message delimited by 0x7e..0x7e
384     if (firstDelimiterPos == 0) {
385         mux = MuxTrk;
386         const int endPos = buffer.indexOf(delimiter, firstDelimiterPos + 1);
387         return endPos != -1 ? endPos + 1 - firstDelimiterPos : 0;
388     }
389     // Some ASCII log message up to first delimiter or all
390     return firstDelimiterPos != -1 ? firstDelimiterPos : buffer.size();
391 }
392
393 bool extractResult(QByteArray *buffer, bool serialFrame, TrkResult *result, bool &linkEstablishmentMode, QByteArray *rawData)
394 {
395     result->clear();
396     if(rawData)
397         rawData->clear();
398     ushort len = isValidTrkResult(*buffer, serialFrame, result->multiplex);
399     // handle receiving application output, which is not a regular command
400     const int delimiterPos = serialFrame ? 4 : 0;
401     if (linkEstablishmentMode) {
402         //when "hot connecting" a device, we can receive partial frames.
403         //this code resyncs by discarding data until a TRK frame is found
404         while (buffer->length() > delimiterPos
405                && result->multiplex != MuxTextTrace
406                && !(result->multiplex == MuxTrk && buffer->at(delimiterPos) == 0x7e)) {
407             buffer->remove(0,1);
408             len = isValidTrkResult(*buffer, serialFrame, result->multiplex);
409         }
410     }
411     if (!len)
412         return false;
413     if (buffer->at(delimiterPos) != 0x7e) {
414         result->isDebugOutput = true;
415         result->data = buffer->mid(delimiterPos, len);
416         buffer->remove(0, delimiterPos + len);
417         return true;
418     }
419     // FIXME: what happens if the length contains 0xfe?
420     // Assume for now that it passes unencoded!
421     const QByteArray data = decode7d(buffer->mid(delimiterPos + 1, len - 2));
422     if(rawData)
423         *rawData = data;
424     buffer->remove(0, delimiterPos + len);
425
426     byte sum = 0;
427     for (int i = 0; i < data.size(); ++i) // 3 = 2 * 0xfe + sum
428         sum += byte(data.at(i));
429     if (sum != 0xff)
430         logMessage("*** CHECKSUM ERROR: " << byte(sum));
431
432     result->code = data.at(0);
433     result->token = data.at(1);
434     result->data = data.mid(2, data.size() - 3);
435     //logMessage("   REST BUF: " << stringFromArray(*buffer));
436     //logMessage("   CURR DATA: " << stringFromArray(data));
437     //QByteArray prefix = "READ BUF:                                       ";
438     //logMessage((prefix + "HEADER: " + stringFromArray(header).toLatin1()).data());
439     linkEstablishmentMode = false; //have received a good TRK packet, therefore in sync
440     return true;
441 }
442
443 SYMBIANUTILS_EXPORT ushort extractShort(const char *data)
444 {
445     return byte(data[0]) * 256 + byte(data[1]);
446 }
447
448 SYMBIANUTILS_EXPORT uint extractInt(const char *data)
449 {
450     uint res = byte(data[0]);
451     res *= 256; res += byte(data[1]);
452     res *= 256; res += byte(data[2]);
453     res *= 256; res += byte(data[3]);
454     return res;
455 }
456
457 SYMBIANUTILS_EXPORT quint64 extractInt64(const char *data)
458 {
459     quint64 res = byte(data[0]);
460     res <<= 8; res += byte(data[1]);
461     res <<= 8; res += byte(data[2]);
462     res <<= 8; res += byte(data[3]);
463     res <<= 8; res += byte(data[4]);
464     res <<= 8; res += byte(data[5]);
465     res <<= 8; res += byte(data[6]);
466     res <<= 8; res += byte(data[7]);
467     return res;
468 }
469
470 SYMBIANUTILS_EXPORT QString quoteUnprintableLatin1(const QByteArray &ba)
471 {
472     QString res;
473     char buf[10];
474     for (int i = 0, n = ba.size(); i != n; ++i) {
475         const byte c = ba.at(i);
476         if (isprint(c)) {
477             res += c;
478         } else {
479             qsnprintf(buf, sizeof(buf) - 1, "\\%x", int(c));
480             res += buf;
481         }
482     }
483     return res;
484 }
485
486 SYMBIANUTILS_EXPORT void appendShort(QByteArray *ba, ushort s, Endianness endian)
487 {
488     if (endian == BigEndian) {
489         ba->append(s / 256);
490         ba->append(s % 256);
491     } else {
492         ba->append(s % 256);
493         ba->append(s / 256);
494     }
495 }
496
497 SYMBIANUTILS_EXPORT void appendInt(QByteArray *ba, uint i, Endianness endian)
498 {
499     const uchar b3 = i % 256; i /= 256;
500     const uchar b2 = i % 256; i /= 256;
501     const uchar b1 = i % 256; i /= 256;
502     const uchar b0 = i;
503     ba->reserve(ba->size() + 4);
504     if (endian == BigEndian) {
505         ba->append(b0);
506         ba->append(b1);
507         ba->append(b2);
508         ba->append(b3);
509     } else {
510         ba->append(b3);
511         ba->append(b2);
512         ba->append(b1);
513         ba->append(b0);
514     }
515 }
516
517 void appendString(QByteArray *ba, const QByteArray &str, Endianness endian, bool appendNullTerminator)
518 {
519     const int fullSize = str.size() + (appendNullTerminator ? 1 : 0);
520     appendShort(ba, fullSize, endian); // count the terminating \0
521     ba->append(str);
522     if (appendNullTerminator)
523         ba->append('\0');
524 }
525
526 void appendDateTime(QByteArray *ba, QDateTime dateTime, Endianness endian)
527 {
528     // convert the QDateTime to UTC and append its representation to QByteArray
529     // format is the same as in FAT file system
530     dateTime = dateTime.toUTC();
531     const QTime utcTime = dateTime.time();
532     const QDate utcDate = dateTime.date();
533     uint fatDateTime = (utcTime.hour() << 11 | utcTime.minute() << 5 | utcTime.second()/2) << 16;
534     fatDateTime |= (utcDate.year()-1980) << 9 | utcDate.month() << 5 | utcDate.day();
535     appendInt(ba, fatDateTime, endian);
536 }
537
538 QByteArray errorMessage(byte code)
539 {
540     switch (code) {
541         case 0x00: return "No error";
542         case 0x01: return "Generic error in CWDS message";
543         case 0x02: return "Unexpected packet size in send msg";
544         case 0x03: return "Internal error occurred in CWDS";
545         case 0x04: return "Escape followed by frame flag";
546         case 0x05: return "Bad FCS in packet";
547         case 0x06: return "Packet too long";
548         case 0x07: return "Sequence ID not expected (gap in sequence)";
549
550         case 0x10: return "Command not supported";
551         case 0x11: return "Command param out of range";
552         case 0x12: return "An option was not supported";
553         case 0x13: return "Read/write to invalid memory";
554         case 0x14: return "Read/write invalid registers";
555         case 0x15: return "Exception occurred in CWDS";
556         case 0x16: return "Targeted system or thread is running";
557         case 0x17: return "Breakpoint resources (HW or SW) exhausted";
558         case 0x18: return "Requested breakpoint conflicts with existing one";
559
560         case 0x20: return "General OS-related error";
561         case 0x21: return "Request specified invalid process";
562         case 0x22: return "Request specified invalid thread";
563     }
564     return "Unknown error";
565 }
566
567 uint swapEndian(uint in)
568 {
569     return (in>>24) | ((in<<8) & 0x00FF0000) | ((in>>8) & 0x0000FF00) | (in<<24);
570 }
571
572 int TrkResult::errorCode() const
573 {
574     // NAK means always error, else data sized 1 with a non-null element
575     const bool isNAK = code == 0xff;
576     if (data.size() != 1 && !isNAK)
577         return 0;
578     if (const int errorCode = data.at(0))
579         return errorCode;
580     return isNAK ? 0xff : 0;
581 }
582
583 QString TrkResult::errorString() const
584 {
585     // NAK means always error, else data sized 1 with a non-null element
586     if (code == 0xff)
587         return "NAK";
588     if (data.size() < 1)
589         return "Unknown error packet";
590     return errorMessage(data.at(0));
591 }
592
593 } // namespace trk
594