watchutils.cpp 31.7 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8 9 10
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
11 12 13 14 15 16
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17
**
con's avatar
con committed
18
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
19
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
20 21
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
22 23 24 25 26
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
27
** If you have questions regarding the use of this file, please contact
28
** Nokia at qt-info@nokia.com.
29 30 31 32
**
**************************************************************************/

#include "watchutils.h"
33 34
#include "watchdata.h"
#include "debuggerstringutils.h"
35
#include "gdb/gdbmi.h"
36

37
#include <utils/qtcassert.h>
38

39 40
#include <coreplugin/ifile.h>

41 42 43 44
#include <texteditor/basetexteditor.h>
#include <texteditor/basetextmark.h>
#include <texteditor/itexteditor.h>
#include <texteditor/texteditorconstants.h>
45
#include <coreplugin/editormanager/editormanager.h>
46 47

#include <cpptools/cpptoolsconstants.h>
48
#include <cpptools/abstracteditorsupport.h>
49

50
#include <cplusplus/ModelManagerInterface.h>
51
#include <cplusplus/ExpressionUnderCursor.h>
52 53 54
#include <cplusplus/Overview.h>
#include <Symbols.h>
#include <Scope.h>
55 56 57

#include <extensionsystem/pluginmanager.h>

58 59 60 61 62 63 64
#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QHash>
#include <QStringList>
#include <QTextStream>
#include <QTime>
65

66 67
#include <QTextCursor>
#include <QPlainTextEdit>
68

69 70 71 72
#include <string.h>
#include <ctype.h>

enum { debug = 0 };
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

// Debug helpers for code model. @todo: Move to some CppTools library?
namespace CPlusPlus {

static void debugCppSymbolRecursion(QTextStream &str, const Overview &o,
                                    const Symbol &s, bool doRecurse = true,
                                    int recursion = 0)
{
    for (int i = 0; i < recursion; i++)
        str << "  ";
    str << "Symbol: " << o.prettyName(s.name()) << " at line " << s.line();
    if (s.isFunction())
        str << " function";
    if (s.isClass())
        str << " class";
    if (s.isDeclaration())
        str << " declaration";
    if (s.isBlock())
        str << " block";
92
    if (doRecurse && s.isScope()) {
Roberto Raggi's avatar
Roberto Raggi committed
93
        const Scope *scoped = s.asScope();
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        const int size =  scoped->memberCount();
        str << " scoped symbol of " << size << '\n';
        for (int m = 0; m < size; m++)
            debugCppSymbolRecursion(str, o, *scoped->memberAt(m), true, recursion + 1);
    } else {
        str << '\n';
    }
}

QDebug operator<<(QDebug d, const Symbol &s)
{
    QString output;
    CPlusPlus::Overview o;
    QTextStream str(&output);
    debugCppSymbolRecursion(str, o, s, true, 0);
    d.nospace() << output;
    return d;
}

QDebug operator<<(QDebug d, const Scope &scope)
{
    QString output;
    Overview o;
    QTextStream str(&output);
Roberto Raggi's avatar
Roberto Raggi committed
118
    const int size =  scope.memberCount();
119
    str << "Scope of " << size;
Roberto Raggi's avatar
Roberto Raggi committed
120
    if (scope.isNamespace())
121
        str << " namespace";
Roberto Raggi's avatar
Roberto Raggi committed
122
    if (scope.isClass())
123
        str << " class";
Roberto Raggi's avatar
Roberto Raggi committed
124
    if (scope.isEnum())
125
        str << " enum";
Roberto Raggi's avatar
Roberto Raggi committed
126
    if (scope.isBlock())
127
        str << " block";
Roberto Raggi's avatar
Roberto Raggi committed
128
    if (scope.isFunction())
129
        str << " function";
Roberto Raggi's avatar
Roberto Raggi committed
130
    if (scope.isFunction())
131
        str << " prototype";
132
#if 0 // ### port me
Roberto Raggi's avatar
Roberto Raggi committed
133
    if (const Symbol *owner = &scope) {
134 135 136 137 138
        str << " owner: ";
        debugCppSymbolRecursion(str, o, *owner, false, 0);
    } else {
        str << " 0-owner\n";
    }
Roberto Raggi's avatar
Roberto Raggi committed
139
#endif
140
    for (int s = 0; s < size; s++)
Roberto Raggi's avatar
Roberto Raggi committed
141
        debugCppSymbolRecursion(str, o, *scope.memberAt(s), true, 2);
142 143 144 145 146
    d.nospace() << output;
    return d;
}
} // namespace CPlusPlus

147 148 149
namespace Debugger {
namespace Internal {

150 151 152 153 154 155 156 157 158 159
bool isEditorDebuggable(Core::IEditor *editor)
{
    // Only blacklist Qml. Whitelisting would fail on C++ code in files
    // with strange names, more harm would be done this way.
    //   IFile *file = editor->file();
    //   return !(file && file->mimeType() == "application/x-qml");
    // Nowadays, even Qml is debuggable.
    return editor;
}

160
QByteArray dotEscape(QByteArray str)
161
{
162 163 164
    str.replace(' ', '.');
    str.replace('\\', '.');
    str.replace('/', '.');
165 166 167 168 169 170 171 172 173 174
    return str;
}

QString currentTime()
{
    return QTime::currentTime().toString(QLatin1String("hh:mm:ss.zzz"));
}

bool isSkippableFunction(const QString &funcName, const QString &fileName)
{
175
    if (fileName.endsWith(QLatin1String("/qobject.cpp")))
176
        return true;
177
    if (fileName.endsWith(QLatin1String("/moc_qobject.cpp")))
178
        return true;
179
    if (fileName.endsWith(QLatin1String("/qmetaobject.cpp")))
180
        return true;
181
    if (fileName.endsWith(QLatin1String("/qmetaobject_p.h")))
182
        return true;
183 184 185
    if (fileName.endsWith(QLatin1String(".moc")))
        return true;

186
    if (funcName.endsWith(QLatin1String("::qt_metacall")))
187
        return true;
188
    if (funcName.endsWith(QLatin1String("::d_func")))
189
        return true;
190
    if (funcName.endsWith(QLatin1String("::q_func")))
191
        return true;
192 193 194 195 196 197 198 199

    return false;
}

bool isLeavableFunction(const QString &funcName, const QString &fileName)
{
    if (funcName.endsWith(QLatin1String("QObjectPrivate::setCurrentSender")))
        return true;
200 201
    if (funcName.endsWith(QLatin1String("QMutexPool::get")))
        return true;
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246

    if (fileName.endsWith(QLatin1String(".cpp"))) {
        if (fileName.endsWith(QLatin1String("/qmetaobject.cpp"))
                && funcName.endsWith(QLatin1String("QMetaObject::methodOffset")))
            return true;
        if (fileName.endsWith(QLatin1String("/qobject.cpp"))
                && (funcName.endsWith(QLatin1String("QObjectConnectionListVector::at"))
                    || funcName.endsWith(QLatin1String("~QObject"))))
            return true;
        if (fileName.endsWith(QLatin1String("/qmutex.cpp")))
            return true;
        if (fileName.endsWith(QLatin1String("/qthread.cpp")))
            return true;
        if (fileName.endsWith(QLatin1String("/qthread_unix.cpp")))
            return true;
    } else if (fileName.endsWith(QLatin1String(".h"))) {

        if (fileName.endsWith(QLatin1String("/qobject.h")))
            return true;
        if (fileName.endsWith(QLatin1String("/qmutex.h")))
            return true;
        if (fileName.endsWith(QLatin1String("/qvector.h")))
            return true;
        if (fileName.endsWith(QLatin1String("/qlist.h")))
            return true;
        if (fileName.endsWith(QLatin1String("/qhash.h")))
            return true;
        if (fileName.endsWith(QLatin1String("/qmap.h")))
            return true;
        if (fileName.endsWith(QLatin1String("/qshareddata.h")))
            return true;
        if (fileName.endsWith(QLatin1String("/qstring.h")))
            return true;
        if (fileName.endsWith(QLatin1String("/qglobal.h")))
            return true;

    } else {

        if (fileName.contains(QLatin1String("/qbasicatomic")))
            return true;
        if (fileName.contains(QLatin1String("/qorderedmutexlocker_p")))
            return true;
        if (fileName.contains(QLatin1String("/qatomic")))
            return true;
    }
247 248 249 250

    return false;
}

251 252 253 254 255 256 257
bool isLetterOrNumber(char c)
{
    return (c >= 'a' && c <= 'z')
        || (c >= 'A' && c <= 'Z')
        || (c >= '0' && c <= '9');
}

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
bool hasLetterOrNumber(const QString &exp)
{
    const QChar underscore = QLatin1Char('_');
    for (int i = exp.size(); --i >= 0; )
        if (exp.at(i).isLetterOrNumber() || exp.at(i) == underscore)
            return true;
    return false;
}

bool hasSideEffects(const QString &exp)
{
    // FIXME: complete?
    return exp.contains(QLatin1String("-="))
        || exp.contains(QLatin1String("+="))
        || exp.contains(QLatin1String("/="))
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
273
        || exp.contains(QLatin1String("%="))
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        || exp.contains(QLatin1String("*="))
        || exp.contains(QLatin1String("&="))
        || exp.contains(QLatin1String("|="))
        || exp.contains(QLatin1String("^="))
        || exp.contains(QLatin1String("--"))
        || exp.contains(QLatin1String("++"));
}

bool isKeyWord(const QString &exp)
{
    // FIXME: incomplete
    return exp == QLatin1String("class")
        || exp == QLatin1String("const")
        || exp == QLatin1String("do")
        || exp == QLatin1String("if")
        || exp == QLatin1String("return")
        || exp == QLatin1String("struct")
        || exp == QLatin1String("template")
        || exp == QLatin1String("void")
        || exp == QLatin1String("volatile")
        || exp == QLatin1String("while");
}

bool startsWithDigit(const QString &str)
{
    return !str.isEmpty() && str.at(0).isDigit();
}

302
QByteArray stripPointerType(QByteArray type)
303
{
304
    if (type.endsWith('*'))
305
        type.chop(1);
306
    if (type.endsWith("* const"))
307
        type.chop(7);
308
    if (type.endsWith(' '))
309 310 311 312
        type.chop(1);
    return type;
}

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
/* getUninitializedVariables(): Get variables that are not initialized
 * at a certain line of a function from the code model to be able to
 * indicate them as not in scope in the locals view.
 * Find document + function in the code model, do a double check and
 * collect declarative symbols that are in the function past or on
 * the current line. blockRecursion() recurses up the scopes
 * and collect symbols declared past or on the current line.
 * Recursion goes up from the innermost scope, keeping a map
 * of occurrences seen, to be able to derive the names of
 * shadowed variables as the debugger sees them:
\code
int x;             // Occurrence (1), should be reported as "x <shadowed 1>"
if (true) {
   int x = 5; (2)  // Occurrence (2), should be reported as "x"
}
\endcode
 */

typedef QHash<QString, int> SeenHash;

static void blockRecursion(const CPlusPlus::Overview &overview,
                           const CPlusPlus::Scope *scope,
                           unsigned line,
                           QStringList *uninitializedVariables,
                           SeenHash *seenHash,
                           int level = 0)
{
340 341 342
    // Go backwards in case someone has identical variables in the same scope.
    // Fixme: loop variables or similar are currently seen in the outer scope
    for (int s = scope->memberCount() - 1; s >= 0; --s){
Roberto Raggi's avatar
Roberto Raggi committed
343
        const CPlusPlus::Symbol *symbol = scope->memberAt(s);
344 345 346 347 348 349 350 351 352
        if (symbol->isDeclaration()) {
            // Find out about shadowed symbols by bookkeeping
            // the already seen occurrences in a hash.
            const QString name = overview.prettyName(symbol->name());
            SeenHash::iterator it = seenHash->find(name);
            if (it == seenHash->end()) {
                it = seenHash->insert(name, 0);
            } else {
                ++(it.value());
353
            }
354 355 356 357 358 359 360
            // Is the declaration on or past the current line, that is,
            // the variable not initialized.
            if (symbol->line() >= line)
                uninitializedVariables->push_back(WatchData::shadowedName(name, it.value()));
        }
    }
    // Next block scope.
Roberto Raggi's avatar
Roberto Raggi committed
361
    if (const CPlusPlus::Scope *enclosingScope = scope->enclosingBlock())
362 363 364 365 366 367 368 369 370 371 372 373 374
        blockRecursion(overview, enclosingScope, line, uninitializedVariables, seenHash, level + 1);
}

// Inline helper with integer error return codes.
static inline
int getUninitializedVariablesI(const CPlusPlus::Snapshot &snapshot,
                               const QString &functionName,
                               const QString &file,
                               int line,
                               QStringList *uninitializedVariables)
{
    uninitializedVariables->clear();
    // Find document
375
    if (snapshot.isEmpty() || functionName.isEmpty() || file.isEmpty() || line < 1)
376
        return 1;
377 378
    const CPlusPlus::Snapshot::const_iterator docIt = snapshot.find(file);
    if (docIt == snapshot.end())
379 380 381 382
        return 2;
    const CPlusPlus::Document::Ptr doc = docIt.value();
    // Look at symbol at line and find its function. Either it is the
    // function itself or some expression/variable.
383
    const CPlusPlus::Symbol *symbolAtLine = doc->lastVisibleSymbolAt(line, 0);
384 385
    if (!symbolAtLine)
        return 4;
386 387
    // First figure out the function to do a safety name check
    // and the innermost scope at cursor position
388
    const CPlusPlus::Function *function = 0;
389 390
    const CPlusPlus::Scope *innerMostScope = 0;
    if (symbolAtLine->isFunction()) {
391
        function = symbolAtLine->asFunction();
392 393
        if (function->memberCount() == 1) // Skip over function block
            if (CPlusPlus::Block *block = function->memberAt(0)->asBlock())
Roberto Raggi's avatar
Roberto Raggi committed
394
                innerMostScope = block;
395
    } else {
Roberto Raggi's avatar
Roberto Raggi committed
396 397
        if (const CPlusPlus::Scope *functionScope = symbolAtLine->enclosingFunction()) {
            function = functionScope->asFunction();
398
            innerMostScope = symbolAtLine->isBlock() ?
Roberto Raggi's avatar
Roberto Raggi committed
399 400
                             symbolAtLine->asBlock() :
                             symbolAtLine->enclosingBlock();
401
        }
402
    }
403
    if (!function || !innerMostScope)
404 405 406 407 408 409 410 411 412 413 414 415 416
        return 7;
    // Compare function names with a bit off fuzz,
    // skipping modules from a CDB symbol "lib!foo" or namespaces
    // that the code model does not show at this point
    CPlusPlus::Overview overview;
    const QString name = overview.prettyName(function->name());
    if (!functionName.endsWith(name))
        return 11;
    if (functionName.size() > name.size()) {
        const char previousChar = functionName.at(functionName.size() - name.size() - 1).toLatin1();
        if (previousChar != ':' && previousChar != '!' )
            return 11;
    }
417
    // Starting from the innermost block scope, collect declarations.
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    SeenHash seenHash;
    blockRecursion(overview, innerMostScope, line, uninitializedVariables, &seenHash);
    return 0;
}

bool getUninitializedVariables(const CPlusPlus::Snapshot &snapshot,
                               const QString &function,
                               const QString &file,
                               int line,
                               QStringList *uninitializedVariables)
{
    const int rc = getUninitializedVariablesI(snapshot, function, file, line, uninitializedVariables);
    if (debug) {
        QString msg;
        QTextStream str(&msg);
        str << "getUninitializedVariables() " << function << ' ' << file << ':' << line
                << " returns (int) " << rc << " '"
                << uninitializedVariables->join(QString(QLatin1Char(','))) << '\'';
        if (rc)
437
            str << " of " << snapshot.size() << " documents";
438 439 440 441 442
        qDebug() << msg;
    }
    return rc == 0;
}

443
QByteArray gdbQuoteTypes(const QByteArray &type)
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
{
    // gdb does not understand sizeof(Core::IFile*).
    // "sizeof('Core::IFile*')" is also not acceptable,
    // it needs to be "sizeof('Core::IFile'*)"
    //
    // We never will have a perfect solution here (even if we had a full blown
    // C++ parser as we do not have information on what is a type and what is
    // a variable name. So "a<b>::c" could either be two comparisons of values
    // 'a', 'b' and '::c', or a nested type 'c' in a template 'a<b>'. We
    // assume here it is the latter.
    //return type;

    // (*('myns::QPointer<myns::QObject>*'*)0x684060)" is not acceptable
    // (*('myns::QPointer<myns::QObject>'**)0x684060)" is acceptable
    if (isPointerType(type))
459
        return gdbQuoteTypes(stripPointerType(type)) + '*';
460

461 462
    QByteArray accu;
    QByteArray result;
463 464
    int templateLevel = 0;

465 466 467 468
    const char colon = ':';
    const char singleQuote = '\'';
    const char lessThan = '<';
    const char greaterThan = '>';
469
    for (int i = 0; i != type.size(); ++i) {
470 471
        const char c = type.at(i);
        if (isLetterOrNumber(c) || c == '_' || c == colon || c == ' ') {
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
            accu += c;
        } else if (c == lessThan) {
            ++templateLevel;
            accu += c;
        } else if (c == greaterThan) {
            --templateLevel;
            accu += c;
        } else if (templateLevel > 0) {
            accu += c;
        } else {
            if (accu.contains(colon) || accu.contains(lessThan))
                result += singleQuote + accu + singleQuote;
            else
                result += accu;
            accu.clear();
            result += c;
        }
    }
    if (accu.contains(colon) || accu.contains(lessThan))
        result += singleQuote + accu + singleQuote;
    else
        result += accu;
    //qDebug() << "GDB_QUOTING" << type << " TO " << result;

    return result;
}

499
bool isSymbianIntType(const QByteArray &type)
500
{
501
    return type == "TInt" || type == "TBool";
502 503
}

504 505
// Utilities to decode string data returned by the dumper helpers.

506
QString quoteUnprintableLatin1(const QByteArray &ba)
507 508 509 510 511 512
{
    QString res;
    char buf[10];
    for (int i = 0, n = ba.size(); i != n; ++i) {
        const unsigned char c = ba.at(i);
        if (isprint(c)) {
513
            res += QLatin1Char(c);
514 515
        } else {
            qsnprintf(buf, sizeof(buf) - 1, "\\%x", int(c));
516
            res += QLatin1String(buf);
517 518 519 520 521
        }
    }
    return res;
}

522 523 524 525 526 527 528 529 530 531
static QDate dateFromData(int jd)
{
    return jd ? QDate::fromJulianDay(jd) : QDate();
}

static QTime timeFromData(int ms)
{
    return ms == -1 ? QTime() : QTime(0, 0, 0, 0).addMSecs(ms);
}

hjk's avatar
hjk committed
532
QString decodeData(const QByteArray &ba, int encoding)
533 534
{
    switch (encoding) {
535
        case Unencoded8Bit: // 0
hjk's avatar
hjk committed
536
            return quoteUnprintableLatin1(ba);
537
        case Base64Encoded8BitWithQuotes: { // 1, used for QByteArray
538 539
            const QChar doubleQuote(QLatin1Char('"'));
            QString rc = doubleQuote;
hjk's avatar
hjk committed
540
            rc += quoteUnprintableLatin1(QByteArray::fromBase64(ba));
541 542 543
            rc += doubleQuote;
            return rc;
        }
544
        case Base64Encoded16BitWithQuotes: { // 2, used for QString
545
            const QChar doubleQuote(QLatin1Char('"'));
546
            const QByteArray decodedBa = QByteArray::fromBase64(ba);
547
            QString rc = doubleQuote;
548 549
            rc += QString::fromUtf16(reinterpret_cast<const ushort *>
                (decodedBa.data()), decodedBa.size() / 2);
550 551 552
            rc += doubleQuote;
            return rc;
        }
553
        case Base64Encoded32BitWithQuotes: { // 3
554
            const QByteArray decodedBa = QByteArray::fromBase64(ba);
555 556
            const QChar doubleQuote(QLatin1Char('"'));
            QString rc = doubleQuote;
557 558
            rc += QString::fromUcs4(reinterpret_cast<const uint *>
                (decodedBa.data()), decodedBa.size() / 4);
559 560 561
            rc += doubleQuote;
            return rc;
        }
562
        case Base64Encoded16Bit: { // 4, without quotes (see 2)
563
            const QByteArray decodedBa = QByteArray::fromBase64(ba);
564 565
            return QString::fromUtf16(reinterpret_cast<const ushort *>
                (decodedBa.data()), decodedBa.size() / 2);
566
        }
567
        case Base64Encoded8Bit: { // 5, without quotes (see 1)
568 569
            return quoteUnprintableLatin1(QByteArray::fromBase64(ba));
        }
570
        case Hex2EncodedLatin1WithQuotes: { // 6, %02x encoded 8 bit Latin1 data
hjk's avatar
hjk committed
571 572 573 574
            const QChar doubleQuote(QLatin1Char('"'));
            const QByteArray decodedBa = QByteArray::fromHex(ba);
            return doubleQuote + QString::fromLatin1(decodedBa) + doubleQuote;
        }
575
        case Hex4EncodedLittleEndianWithQuotes: { // 7, %04x encoded 16 bit data
576
            const QChar doubleQuote(QLatin1Char('"'));
577
            const QByteArray decodedBa = QByteArray::fromHex(ba);
578 579
            return doubleQuote + QString::fromUtf16(reinterpret_cast<const ushort *>
                (decodedBa.data()), decodedBa.size() / 2) + doubleQuote;
580
        }
581
        case Hex8EncodedLittleEndianWithQuotes: { // 8, %08x encoded 32 bit data
582 583 584 585 586
            const QChar doubleQuote(QLatin1Char('"'));
            const QByteArray decodedBa = QByteArray::fromHex(ba);
            return doubleQuote + QString::fromUcs4(reinterpret_cast<const uint *>
                (decodedBa.data()), decodedBa.size() / 4) + doubleQuote;
        }
587
        case Hex2EncodedUtf8WithQuotes: { // 9, %02x encoded 8 bit UTF-8 data
588 589 590 591
            const QChar doubleQuote(QLatin1Char('"'));
            const QByteArray decodedBa = QByteArray::fromHex(ba);
            return doubleQuote + QString::fromUtf8(decodedBa) + doubleQuote;
        }
592
        case Hex8EncodedBigEndian: { // 10, %08x encoded 32 bit data
593 594 595 596 597 598 599 600 601 602 603 604 605
            const QChar doubleQuote(QLatin1Char('"'));
            QByteArray decodedBa = QByteArray::fromHex(ba);
            for (int i = 0; i < decodedBa.size(); i += 4) {
                char c = decodedBa.at(i);
                decodedBa[i] = decodedBa.at(i + 3);
                decodedBa[i + 3] = c;
                c = decodedBa.at(i + 1);
                decodedBa[i + 1] = decodedBa.at(i + 2);
                decodedBa[i + 2] = c;
            }
            return doubleQuote + QString::fromUcs4(reinterpret_cast<const uint *>
                (decodedBa.data()), decodedBa.size() / 4) + doubleQuote;
        }
606
        case Hex4EncodedBigEndianWithQuotes: { // 11, %04x encoded 16 bit data
607 608 609 610 611 612 613
            const QChar doubleQuote(QLatin1Char('"'));
            QByteArray decodedBa = QByteArray::fromHex(ba);
            for (int i = 0; i < decodedBa.size(); i += 2) {
                char c = decodedBa.at(i);
                decodedBa[i] = decodedBa.at(i + 1);
                decodedBa[i + 1] = c;
            }
614 615
            return doubleQuote + QString::fromUtf16(reinterpret_cast<const ushort *>
                (decodedBa.data()), decodedBa.size() / 2) + doubleQuote;
616
        }
617
        case Hex4EncodedLittleEndianWithoutQuotes: { // 12, see 7, without quotes
Arvid Ephraim Picciani's avatar
Arvid Ephraim Picciani committed
618 619 620 621
            const QByteArray decodedBa = QByteArray::fromHex(ba);
            return QString::fromUtf16(reinterpret_cast<const ushort *>
                (decodedBa.data()), decodedBa.size() / 2);
        }
622
        case Hex2EncodedLocal8BitWithQuotes: { // 13, %02x encoded 8 bit UTF-8 data
623 624 625 626
            const QChar doubleQuote(QLatin1Char('"'));
            const QByteArray decodedBa = QByteArray::fromHex(ba);
            return doubleQuote + QString::fromLocal8Bit(decodedBa) + doubleQuote;
        }
627 628 629 630 631 632 633 634 635 636 637 638 639 640
        case JulianDate: { // 14, an integer count
            const QDate date = dateFromData(ba.toInt());
            return date.toString(Qt::TextDate);
        }
        case MillisecondsSinceMidnight: {
            const QTime time = timeFromData(ba.toInt());
            return time.toString(Qt::TextDate);
        }
        case JulianDateAndMillisecondsSinceMidnight: {
            const int p = ba.indexOf('/');
            const QDate date = dateFromData(ba.left(p).toInt());
            const QTime time = timeFromData(ba.mid(p + 1 ).toInt());
            return QDateTime(date, time).toString(Qt::TextDate);
        }
641
    }
hjk's avatar
hjk committed
642
    qDebug() << "ENCODING ERROR: " << encoding;
643 644 645
    return QCoreApplication::translate("Debugger", "<Encoding error>");
}

646 647 648
// Editor tooltip support
bool isCppEditor(Core::IEditor *editor)
{
hjk's avatar
hjk committed
649 650 651 652 653 654 655 656 657
    using namespace CppTools::Constants;
    const Core::IFile *file = editor->file();
    if (!file)
        return false;
    const QByteArray mimeType = file->mimeType().toLatin1();
    return mimeType == C_SOURCE_MIMETYPE
        || mimeType == CPP_SOURCE_MIMETYPE
        || mimeType == CPP_HEADER_MIMETYPE
        || mimeType == OBJECTIVE_CPP_SOURCE_MIMETYPE;
658 659 660 661 662 663
}

// Return the Cpp expression, and, if desired, the function
QString cppExpressionAt(TextEditor::ITextEditor *editor, int pos,
                        int *line, int *column, QString *function /* = 0 */)
{
hjk's avatar
hjk committed
664
    using namespace CppTools;
665
    using namespace CPlusPlus;
666 667 668 669 670 671
    *line = *column = 0;
    if (function)
        function->clear();

    const QPlainTextEdit *plaintext = qobject_cast<QPlainTextEdit*>(editor->widget());
    if (!plaintext)
672
        return QString();
673 674

    QString expr = plaintext->textCursor().selectedText();
675
    CppModelManagerInterface *modelManager = CppModelManagerInterface::instance();
676
    if (expr.isEmpty() && modelManager) {
677 678 679 680 681 682 683 684
        QTextCursor tc(plaintext->document());
        tc.setPosition(pos);

        const QChar ch = editor->characterAt(pos);
        if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
            tc.movePosition(QTextCursor::EndOfWord);

        // Fetch the expression's code.
Erik Verbruggen's avatar
Erik Verbruggen committed
685
        CPlusPlus::ExpressionUnderCursor expressionUnderCursor;
686
        expr = expressionUnderCursor(tc);
687
        *column = tc.positionInBlock();
688 689 690
        *line = tc.blockNumber();
    } else {
        const QTextCursor tc = plaintext->textCursor();
691
        *column = tc.positionInBlock();
692
        *line = tc.blockNumber();
693
    }
694 695 696

    if (function && !expr.isEmpty())
        if (const Core::IFile *file = editor->file())
697
            if (modelManager)
hjk's avatar
hjk committed
698 699
                *function = AbstractEditorSupport::functionAt(modelManager,
                    file->fileName(), *line, *column);
700

701
    return expr;
702 703
}

704 705 706 707 708 709 710 711
QString cppFunctionAt(const QString &fileName, int line)
{
    using namespace CppTools;
    using namespace CPlusPlus;
    CppModelManagerInterface *modelManager = CppModelManagerInterface::instance();
    return AbstractEditorSupport::functionAt(modelManager,
                                             fileName, line, 1);
}
hjk's avatar
hjk committed
712

713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
//////////////////////////////////////////////////////////////////////
//
// GdbMi interaction
//
//////////////////////////////////////////////////////////////////////

void setWatchDataValue(WatchData &data, const GdbMi &item)
{
    GdbMi value = item.findChild("value");
    if (value.isValid()) {
        int encoding = item.findChild("valueencoded").data().toInt();
        data.setValue(decodeData(value.data(), encoding));
    } else {
        data.setValueNeeded();
    }
}

void setWatchDataValueToolTip(WatchData &data, const GdbMi &mi,
    int encoding)
{
    if (mi.isValid())
        data.setValueToolTip(decodeData(mi.data(), encoding));
}

void setWatchDataChildCount(WatchData &data, const GdbMi &mi)
{
    if (mi.isValid())
        data.setHasChildren(mi.data().toInt() > 0);
}

void setWatchDataValueEnabled(WatchData &data, const GdbMi &mi)
{
    if (mi.data() == "true")
        data.valueEnabled = true;
    else if (mi.data() == "false")
        data.valueEnabled = false;
}

hjk's avatar
hjk committed
751
static void setWatchDataValueEditable(WatchData &data, const GdbMi &mi)
752 753 754 755 756 757 758
{
    if (mi.data() == "true")
        data.valueEditable = true;
    else if (mi.data() == "false")
        data.valueEditable = false;
}

hjk's avatar
hjk committed
759
static void setWatchDataExpression(WatchData &data, const GdbMi &mi)
760 761 762 763 764
{
    if (mi.isValid())
        data.exp = mi.data();
}

765
static void setWatchDataAddress(WatchData &data, quint64 address, quint64 origAddress = 0)
hjk's avatar
hjk committed
766
{
767 768 769
    if (origAddress) { // Gdb dumpers reports the dereferenced address as origAddress
        data.address = origAddress;
        data.referencingAddress = address;
hjk's avatar
hjk committed
770
    } else {
771
        data.address = address;
hjk's avatar
hjk committed
772
    }
hjk's avatar
hjk committed
773 774 775 776 777 778 779 780
    if (data.exp.isEmpty() && !data.dumperFlags.startsWith('$')) {
        if (data.iname.startsWith("local.") && data.iname.count('.') == 1)
            // Solve one common case of adding 'class' in
            // *(class X*)0xdeadbeef for gdb.
            data.exp = data.name.toLatin1();
        else
            data.exp = "*(" + gdbQuoteTypes(data.type) + "*)" +data.hexAddress();
    }
hjk's avatar
hjk committed
781 782
}

783
void setWatchDataAddress(WatchData &data, const GdbMi &addressMi, const GdbMi &origAddressMi)
784
{
785 786 787 788 789 790 791
    if (!addressMi.isValid())
        return;
    const QByteArray addressBA = addressMi.data();
    if (!addressBA.startsWith("0x")) { // Item model dumpers pull tricks.
        data.dumperFlags = addressBA;
        return;
    }
792 793
    const quint64 address = addressMi.toAddress();
    const quint64 origAddress = origAddressMi.toAddress();
794
    setWatchDataAddress(data, address, origAddress);
795 796
}

hjk's avatar
hjk committed
797
static void setWatchDataSize(WatchData &data, const GdbMi &mi)
798 799 800 801 802 803 804 805 806
{
    if (mi.isValid()) {
        bool ok = false;
        const unsigned size = mi.data().toUInt(&ok);
        if (ok)
            data.size = size;
    }
}

807 808 809 810
// Find the "type" and "displayedtype" children of root and set up type.
void setWatchDataType(WatchData &data, const GdbMi &item)
{
    if (item.isValid())
811
        data.setType(item.data());
812 813 814 815 816 817 818 819 820 821 822
    else if (data.type.isEmpty())
        data.setTypeNeeded();
}

void setWatchDataDisplayedType(WatchData &data, const GdbMi &item)
{
    if (item.isValid())
        data.displayedType = _(item.data());
}

void parseWatchData(const QSet<QByteArray> &expandedINames,
823
    const WatchData &data0, const GdbMi &item,
824
    QList<WatchData> *list)
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
{
    //qDebug() << "HANDLE CHILDREN: " << data0.toString() << item.toString();
    WatchData data = data0;
    bool isExpanded = expandedINames.contains(data.iname);
    if (!isExpanded)
        data.setChildrenUnneeded();

    GdbMi children = item.findChild("children");
    if (children.isValid() || !isExpanded)
        data.setChildrenUnneeded();

    setWatchDataType(data, item.findChild("type"));
    GdbMi mi = item.findChild("editvalue");
    if (mi.isValid())
        data.editvalue = mi.data();
    mi = item.findChild("editformat");
    if (mi.isValid())
        data.editformat = mi.data().toInt();
    mi = item.findChild("typeformats");
    if (mi.isValid())
        data.typeFormats = QString::fromUtf8(mi.data());
846 847 848 849 850 851
    mi = item.findChild("bitpos");
    if (mi.isValid())
        data.bitpos = mi.data().toInt();
    mi = item.findChild("bitsize");
    if (mi.isValid())
        data.bitsize = mi.data().toInt();
852 853

    setWatchDataValue(data, item);
854
    setWatchDataAddress(data, item.findChild("addr"), item.findChild("origaddr"));
855
    setWatchDataSize(data, item.findChild("size"));
856 857 858 859 860 861 862 863 864
    setWatchDataExpression(data, item.findChild("exp"));
    setWatchDataValueEnabled(data, item.findChild("valueenabled"));
    setWatchDataValueEditable(data, item.findChild("valueeditable"));
    setWatchDataChildCount(data, item.findChild("numchild"));
    //qDebug() << "\nAPPEND TO LIST: " << data.toString() << "\n";
    list->append(data);

    bool ok = false;
    qulonglong addressBase = item.findChild("addrbase").data().toULongLong(&ok, 0);
865
    qulonglong addressStep = item.findChild("addrstep").data().toULongLong(&ok, 0);
866 867 868 869 870 871 872

    // Try not to repeat data too often.
    WatchData childtemplate;
    setWatchDataType(childtemplate, item.findChild("childtype"));
    setWatchDataChildCount(childtemplate, item.findChild("childnumchild"));
    //qDebug() << "CHILD TEMPLATE:" << childtemplate.toString();

873 874
    for (int i = 0, n = children.children().size(); i != n; ++i) {
        const GdbMi &child = children.children().at(i);
875
        WatchData data1 = childtemplate;
876
        data1.sortId = i;
877 878 879 880 881 882
        GdbMi name = child.findChild("name");
        if (name.isValid())
            data1.name = _(name.data());
        else
            data1.name = QString::number(i);
        GdbMi iname = child.findChild("iname");
883
        if (iname.isValid()) {
884
            data1.iname = iname.data();
885 886 887 888 889
        } else {
            data1.iname = data.iname;
            data1.iname += '.';
            data1.iname += data1.name.toLatin1();
        }
890
        if (!data1.name.isEmpty() && data1.name.at(0).isDigit())
891
            data1.name = QLatin1Char('[') + data1.name + QLatin1Char(']');
892
        if (addressStep) {
893
            setWatchDataAddress(data1, addressBase);
894 895 896 897 898 899 900 901 902 903 904 905 906
            addressBase += addressStep;
        }
        QByteArray key = child.findChild("key").data();
        if (!key.isEmpty()) {
            int encoding = child.findChild("keyencoded").data().toInt();
            QString skey = decodeData(key, encoding);
            if (skey.size() > 13) {
                skey = skey.left(12);
                skey += _("...");
            }
            //data1.name += " (" + skey + ")";
            data1.name = skey;
        }
907
        parseWatchData(expandedINames, data1, child, list);
908 909 910 911
    }
}


hjk's avatar
hjk committed
912 913
} // namespace Internal
} // namespace Debugger