source: trunk/tools/runonphone/symbianutils/trkutils.cpp

Last change on this file was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

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