classicgdbengine.cpp 52.5 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
8 9 10 11
**
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** 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
28
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
30 31 32 33
**
**************************************************************************/

#include "gdbengine.h"
34
#include "gdbmi.h"
35

Friedemann Kleint's avatar
Friedemann Kleint committed
36
#include "debuggerstartparameters.h"
37 38
#include "abstractgdbadapter.h"
#include "debuggeractions.h"
39
#include "debuggercore.h"
40 41 42 43 44 45
#include "debuggerstringutils.h"

#include "stackhandler.h"
#include "watchhandler.h"

#include <utils/qtcassert.h>
46
#include <utils/savedaction.h>
47
#include <utils/fileutils.h>
48 49 50

#include <QtCore/QFile>
#include <QtCore/QFileInfo>
51
#include <QtGui/QMessageBox>
52

hjk's avatar
hjk committed
53 54 55 56
#if !defined(Q_OS_WIN)
#include <dlfcn.h>
#endif

57 58 59

#define PRECONDITION QTC_ASSERT(!hasPython(), /**/)

60
#define CB(callback) &GdbEngine::callback, STRINGIFY(callback)
61

62 63 64 65 66
enum {
    debugPending = 0,
    debugSubItem = 0,
    debug = 0
};
67 68 69 70

namespace Debugger {
namespace Internal {

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 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 302 303 304 305 306 307 308 309 310 311 312 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 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 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 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
// ----------------- QtDumperHelper::TypeData
DumperHelper::TypeData::TypeData() :
    type(UnknownType),
    isTemplate(false)
{
}

void DumperHelper::TypeData::clear()
{
    isTemplate = false;
    type = UnknownType;
    tmplate.clear();
    inner.clear();
}

// ----------------- QtDumperHelper
DumperHelper::DumperHelper() :
    m_qtVersion(0),
    m_dumperVersion(1.0)
{
    qFill(m_specialSizes, m_specialSizes + SpecialSizeCount, 0);
    setQClassPrefixes(QByteArray());
}

void DumperHelper::clear()
{
    m_nameTypeMap.clear();
    m_qtVersion = 0;
    m_dumperVersion = 1.0;
    m_qtNamespace.clear();
    m_sizeCache.clear();
    qFill(m_specialSizes, m_specialSizes + SpecialSizeCount, 0);
    m_expressionCache.clear();
    setQClassPrefixes(QByteArray());
}

QString DumperHelper::msgDumperOutdated(double requiredVersion, double currentVersion)
{
    return QCoreApplication::translate("QtDumperHelper",
       "Found an outdated version of the debugging helper library (%1); "
       "version %2 is required.").
       arg(currentVersion).arg(requiredVersion);
}

static inline void formatQtVersion(int v, QTextStream &str)
{
    str  << ((v >> 16) & 0xFF) << '.' << ((v >> 8) & 0xFF) << '.' << (v & 0xFF);
}

QString DumperHelper::toString(bool debug) const
{
    if (debug)  {
        QString rc;
        QTextStream str(&rc);
        str << "version=";
        formatQtVersion(m_qtVersion, str);
        str << "dumperversion='" << m_dumperVersion <<  "' namespace='" << m_qtNamespace << "'," << m_nameTypeMap.size() << " known types <type enum>: ";
        const NameTypeMap::const_iterator cend = m_nameTypeMap.constEnd();
        for (NameTypeMap::const_iterator it = m_nameTypeMap.constBegin(); it != cend; ++it) {
            str <<",[" << it.key() << ',' << it.value() << ']';
        }
        str << "\nSpecial size: ";
        for (int i = 0; i < SpecialSizeCount; i++)
            str << ' ' << m_specialSizes[i];
        str << "\nSize cache: ";
        const SizeCache::const_iterator scend = m_sizeCache.constEnd();
        for (SizeCache::const_iterator it = m_sizeCache.constBegin(); it != scend; ++it) {
            str << ' ' << it.key() << '=' << it.value() << '\n';
        }
        str << "\nExpression cache: (" << m_expressionCache.size() << ")\n";
        const ExpressionCache::const_iterator excend = m_expressionCache.constEnd();
        for (ExpressionCache::const_iterator it = m_expressionCache.constBegin(); it != excend; ++it)
            str << "    " << it.key() << ' ' << it.value() << '\n';
        return rc;
    }
    const QString nameSpace = m_qtNamespace.isEmpty()
        ? QCoreApplication::translate("QtDumperHelper", "<none>") : m_qtNamespace;
    return QCoreApplication::translate("QtDumperHelper",
       "%n known types, Qt version: %1, Qt namespace: %2 Dumper version: %3",
       0, QCoreApplication::CodecForTr,
       m_nameTypeMap.size()).arg(qtVersionString(), nameSpace).arg(m_dumperVersion);
}

DumperHelper::Type DumperHelper::simpleType(const QByteArray &simpleType) const
{
    return m_nameTypeMap.value(simpleType, UnknownType);
}

int DumperHelper::qtVersion() const
{
    return m_qtVersion;
}

QByteArray DumperHelper::qtNamespace() const
{
    return m_qtNamespace;
}

int DumperHelper::typeCount() const
{
    return m_nameTypeMap.size();
}

// Look up unnamespaced 'std' types.
static DumperHelper::Type stdType(const QByteArray &type)
{
    if (type == "vector")
        return DumperHelper::StdVectorType;
    if (type == "deque")
        return DumperHelper::StdDequeType;
    if (type == "set")
        return DumperHelper::StdSetType;
    if (type == "stack")
        return DumperHelper::StdStackType;
    if (type == "map")
        return DumperHelper::StdMapType;
    if (type == "basic_string")
        return DumperHelper::StdStringType;
    return DumperHelper::UnknownType;
}

static DumperHelper::Type specialType(QByteArray type)
{
    // Std classes.
    if (type.startsWith("std::"))
        return stdType(type.mid(5));

    // Strip namespace
    // FIXME: that's not a good idea as it makes all namespaces equal.
    const int namespaceIndex = type.lastIndexOf("::");
    if (namespaceIndex == -1) {
        // None ... check for std..
        const DumperHelper::Type sType = stdType(type);
        if (sType != DumperHelper::UnknownType)
            return sType;
    } else {
        type = type.mid(namespaceIndex + 2);
    }

    if (type == "QAbstractItem")
        return DumperHelper::QAbstractItemType;
    if (type == "QMap")
        return DumperHelper::QMapType;
    if (type == "QMapNode")
        return DumperHelper::QMapNodeType;
    if (type == "QMultiMap")
        return DumperHelper::QMultiMapType;
    if (type == "QObject")
        return DumperHelper::QObjectType;
    if (type == "QObjectSignal")
        return DumperHelper::QObjectSignalType;
    if (type == "QObjectSlot")
        return DumperHelper::QObjectSlotType;
    if (type == "QStack")
        return DumperHelper::QStackType;
    if (type == "QVector")
        return DumperHelper::QVectorType;
    if (type == "QWidget")
        return DumperHelper::QWidgetType;
    return DumperHelper::UnknownType;
}

QByteArray DumperHelper::qtVersionString() const
{
    QString rc;
    QTextStream str(&rc);
    formatQtVersion(m_qtVersion, str);
    return rc.toLatin1();
}

// Parse a list of types.
typedef QList<QByteArray> QByteArrayList;

static QByteArray qClassName(const QByteArray &qtNamespace, const char *className)
{
    if (qtNamespace.isEmpty())
        return className;
    QByteArray rc = qtNamespace;
    rc += "::";
    rc += className;
    return rc;
}

static double getDumperVersion(const GdbMi &contents)
{
    const GdbMi dumperVersionG = contents.findChild("dumperversion");
    if (dumperVersionG.type() != GdbMi::Invalid) {
        bool ok;
        const double v = QString::fromAscii(dumperVersionG.data()).toDouble(&ok);
        if (ok)
            return v;
    }
    return 1.0;
}


void DumperHelper::setQClassPrefixes(const QByteArray &qNamespace)
{
    // Prefixes with namespaces
    m_qPointerPrefix = qClassName(qNamespace, "QPointer");
    m_qSharedPointerPrefix = qClassName(qNamespace, "QSharedPointer");
    m_qSharedDataPointerPrefix = qClassName(qNamespace, "QSharedDataPointer");
    m_qWeakPointerPrefix = qClassName(qNamespace, "QWeakPointer");
    m_qListPrefix = qClassName(qNamespace, "QList");
    m_qLinkedListPrefix = qClassName(qNamespace, "QLinkedList");
    m_qVectorPrefix = qClassName(qNamespace, "QVector");
    m_qQueuePrefix = qClassName(qNamespace, "QQueue");
}

bool DumperHelper::parseQuery(const GdbMi &contents)
{
    clear();
    if (debug > 1)
        qDebug() << "parseQuery" << contents.toString(true, 2);

    // Common info, dumper version, etc
    QByteArray ns = contents.findChild("namespace").data();
    setQtNamespace(ns);
    int qtv = 0;
    const GdbMi qtversion = contents.findChild("qtversion");
    if (qtversion.children().size() == 3) {
        qtv = (qtversion.childAt(0).data().toInt() << 16)
                    + (qtversion.childAt(1).data().toInt() << 8)
                    + qtversion.childAt(2).data().toInt();
    }
    m_qtVersion = qtv;
    // Get list of helpers
    QByteArrayList availableSimpleDebuggingHelpers;
    foreach (const GdbMi &item, contents.findChild("dumpers").children())
        availableSimpleDebuggingHelpers.append(item.data());

    // Parse types
    m_nameTypeMap.clear();
    foreach (const QByteArray &type, availableSimpleDebuggingHelpers) {
        const Type t = specialType(type);
        m_nameTypeMap.insert(type, t != UnknownType ? t : SupportedType);
    }

    m_dumperVersion = getDumperVersion(contents);
    // Parse sizes
    foreach (const GdbMi &sizesList, contents.findChild("sizes").children()) {
        const int childCount = sizesList.childCount();
        if (childCount > 1) {
            const int size = sizesList.childAt(0).data().toInt();
            for (int c = 1; c < childCount; c++)
                addSize(sizesList.childAt(c).data(), size);
        }
    }
    // Parse expressions
    foreach (const GdbMi &exprList, contents.findChild("expressions").children())
        if (exprList.childCount() == 2)
            m_expressionCache.insert(exprList.childAt(0).data(),
                                     exprList.childAt(1).data());
    return true;
}

void DumperHelper::addSize(const QByteArray &name, int size)
{
    // Special interest cases
    if (name == "char*") {
        m_specialSizes[PointerSize] = size;
        return;
    }
    const SpecialSizeType st = specialSizeType(name);
    if (st != SpecialSizeCount) {
        m_specialSizes[st] = size;
        return;
    }
    do {
        // CDB helpers
        if (name == "std::string") {
            m_sizeCache.insert("std::basic_string<char,std::char_traits<char>,std::allocator<char> >", size);
            m_sizeCache.insert("basic_string<char,char_traits<char>,allocator<char> >", size);
            break;
        }
        if (name == "std::wstring") {
            m_sizeCache.insert("basic_string<unsigned short,char_traits<unsignedshort>,allocator<unsignedshort> >", size);
            m_sizeCache.insert("std::basic_string<unsigned short,std::char_traits<unsigned short>,std::allocator<unsigned short> >", size);
            break;
        }
    } while (false);
    m_sizeCache.insert(name, size);
}

DumperHelper::Type DumperHelper::type(const QByteArray &typeName) const
{
    const DumperHelper::TypeData td = typeData(typeName);
    return td.type;
}

static bool extractTemplate(const QByteArray &type, QByteArray *tmplate, QByteArray *inner)
{
    // Input "Template<Inner1,Inner2,...>::Foo" will return "Template::Foo" in
    // 'tmplate' and "Inner1@Inner2@..." etc in 'inner'. Result indicates
    // whether parsing was successful
    // Gdb inserts a blank after each comma which we would like to avoid
    tmplate->clear();
    inner->clear();
    if (!type.contains('<'))
        return  false;
    int level = 0;
    bool skipSpace = false;
    const int size = type.size();

    for (int i = 0; i != size; ++i) {
        const char c = type.at(i);
        switch (c) {
        case '<':
            *(level == 0 ? tmplate : inner) += c;
            ++level;
            break;
        case '>':
            --level;
            *(level == 0 ? tmplate : inner) += c;
            break;
        case ',':
            *inner += (level == 1) ? '@' : ',';
            skipSpace = true;
            break;
        default:
            if (!skipSpace || c != ' ') {
                *(level == 0 ? tmplate : inner) += c;
                skipSpace = false;
            }
            break;
        }
    }
    *tmplate = tmplate->trimmed();
    tmplate->replace("<>", "");
    *inner = inner->trimmed();
    // qDebug() << "EXTRACT TEMPLATE: " << *tmplate << *inner << " FROM " << type;
    return !inner->isEmpty();
}

DumperHelper::TypeData DumperHelper::typeData(const QByteArray &typeName) const
{
    TypeData td;
    td.type = UnknownType;
    const Type st = simpleType(typeName);
    if (st != UnknownType) {
        td.isTemplate = false;
        td.type = st;
        return td;
    }
    // Try template
    td.isTemplate = extractTemplate(typeName, &td.tmplate, &td.inner);
    if (!td.isTemplate)
        return td;
    // Check the template type QMap<X,Y> -> 'QMap'
    td.type = simpleType(td.tmplate);
    return td;
}

static QByteArray sizeofTypeExpression(const QByteArray &type)
{
    if (type.endsWith('*'))
        return "sizeof(void*)";
    if (type.endsWith('>'))
        return "sizeof(" + type + ')';
    return "sizeof(" + gdbQuoteTypes(type) + ')';
}

// Format an expression to have the debugger query the
// size. Use size cache if possible
QByteArray DumperHelper::evaluationSizeofTypeExpression(const QByteArray &typeName) const
{
    // Look up special size types
    const SpecialSizeType st = specialSizeType(typeName);
    if (st != SpecialSizeCount) {
        if (const int size = m_specialSizes[st])
            return QByteArray::number(size);
    }
    // Look up size cache
    const SizeCache::const_iterator sit = m_sizeCache.constFind(typeName);
    if (sit != m_sizeCache.constEnd())
        return QByteArray::number(sit.value());
    // Finally have the debugger evaluate
    return sizeofTypeExpression(typeName);
}

DumperHelper::SpecialSizeType DumperHelper::specialSizeType(const QByteArray &typeName) const
{
    if (isPointerType(typeName))
        return PointerSize;
    if (typeName == "int")
        return IntSize;
    if (typeName.startsWith("std::allocator"))
        return StdAllocatorSize;
    if (typeName.startsWith(m_qPointerPrefix))
        return QPointerSize;
    if (typeName.startsWith(m_qSharedPointerPrefix))
        return QSharedPointerSize;
    if (typeName.startsWith(m_qSharedDataPointerPrefix))
        return QSharedDataPointerSize;
    if (typeName.startsWith(m_qWeakPointerPrefix))
        return QWeakPointerSize;
    if (typeName.startsWith(m_qListPrefix))
        return QListSize;
    if (typeName.startsWith(m_qLinkedListPrefix))
        return QLinkedListSize;
    if (typeName.startsWith(m_qVectorPrefix))
        return QVectorSize;
    if (typeName.startsWith(m_qQueuePrefix))
        return QQueueSize;
    return SpecialSizeCount;
}

static inline bool isInteger(const QString &n)
{
    const int size = n.size();
    if (!size)
        return false;
    for (int i = 0; i < size; i++)
        if (!n.at(i).isDigit())
            return false;
    return true;
}

// Return debugger expression to get the offset of a map node.
static inline QByteArray qMapNodeValueOffsetExpression(const QByteArray &type)
{
        return "(size_t)&(('" + type + "'*)0)->value";
}

void DumperHelper::evaluationParameters(const WatchData &data,
    const TypeData &td, QByteArray *inBuffer, QByteArrayList *extraArgsIn) const
{
    enum { maxExtraArgCount = 4 };

    QByteArrayList &extraArgs = *extraArgsIn;

    // See extractTemplate for parameters
    QByteArrayList inners = td.inner.split('@');
    if (inners.at(0).isEmpty())
        inners.clear();
    for (int i = 0; i != inners.size(); ++i)
        inners[i] = inners[i].simplified();

    QString outertype = td.isTemplate ? td.tmplate : data.type;
    // adjust the data extract
    if (outertype == m_qtNamespace + "QWidget")
        outertype = m_qtNamespace + "QObject";

    QString inner = td.inner;
    const QByteArray zero = "0";

    extraArgs.clear();

    if (!inners.empty()) {
        // "generic" template dumpers: passing sizeof(argument)
        // gives already most information the dumpers need
        const int count = qMin(int(maxExtraArgCount), inners.size());
        for (int i = 0; i < count; i++)
            extraArgs.push_back(evaluationSizeofTypeExpression(inners.at(i)));
    }

    // Pad with zeros
    while (extraArgs.size() < maxExtraArgCount)
        extraArgs.push_back("0");

    // in rare cases we need more or less:
    switch (td.type) {
    case QAbstractItemType:
        if (data.dumperFlags.isEmpty()) {
            qWarning("Internal error: empty dumper state '%s'.", data.iname.constData());
        } else {
            inner = data.dumperFlags.mid(1);
        }
        break;
    case QObjectSlotType:
    case QObjectSignalType: {
            // we need the number out of something like
            // iname="local.ob.slots.2" // ".deleteLater()"?
            const int pos = data.iname.lastIndexOf('.');
            const QByteArray slotNumber = data.iname.mid(pos + 1);
            QTC_ASSERT(slotNumber.toInt() != -1, /**/);
            extraArgs[0] = slotNumber;
        }
        break;
    case QMapType:
    case QMultiMapType: {
            QByteArray nodetype;
            if (m_qtVersion >= 0x040500) {
                nodetype = m_qtNamespace + "QMapNode";
                nodetype += data.type.mid(outertype.size());
            } else {
                // FIXME: doesn't work for QMultiMap
                nodetype  = data.type + "::Node";
            }
            //qDebug() << "OUTERTYPE: " << outertype << " NODETYPE: " << nodetype
            //    << "QT VERSION" << m_qtVersion << ((4 << 16) + (5 << 8) + 0);
            extraArgs[2] = evaluationSizeofTypeExpression(nodetype);
            extraArgs[3] = qMapNodeValueOffsetExpression(nodetype);
        }
        break;
    case QMapNodeType:
        extraArgs[2] = evaluationSizeofTypeExpression(data.type);
        extraArgs[3] = qMapNodeValueOffsetExpression(data.type);
        break;
    case StdVectorType:
        //qDebug() << "EXTRACT TEMPLATE: " << outertype << inners;
        if (inners.at(0) == "bool")
            outertype = "std::vector::bool";
        break;
    case StdDequeType:
        extraArgs[1] = "0";
        break;
    case StdStackType:
        // remove 'std::allocator<...>':
        extraArgs[1] = "0";
        break;
    case StdSetType:
        // remove 'std::less<...>':
        extraArgs[1] = "0";
        // remove 'std::allocator<...>':
        extraArgs[2] = "0";
        break;
    case StdMapType: {
            // We need the offset of the second item in the value pair.
            // We read the type of the pair from the allocator argument because
            // that gets the constness "right" (in the sense that gdb/cdb can
            // read it back: "std::allocator<std::pair<Key,Value> >"
            // -> "std::pair<Key,Value>". Different debuggers have varying
            // amounts of terminating blanks...
            extraArgs[2].clear();
            extraArgs[3] = "0";
            QByteArray pairType = inners.at(3);
            int bracketPos = pairType.indexOf('<');
            if (bracketPos != -1)
                pairType.remove(0, bracketPos + 1);
            // We don't want the comparator and the allocator confuse gdb.
            const char closingBracket = '>';
            bracketPos = pairType.lastIndexOf(closingBracket);
            if (bracketPos != -1)
                bracketPos = pairType.lastIndexOf(closingBracket, bracketPos - pairType.size() - 1);
            if (bracketPos != -1)
                pairType.truncate(bracketPos + 1);
            extraArgs[2] = "(size_t)&(('";
            extraArgs[2] += pairType;
            extraArgs[2] += "'*)0)->second";
    }
        break;
    case StdStringType:
        //qDebug() << "EXTRACT TEMPLATE: " << outertype << inners;
        if (inners.at(0) == "char")
            outertype = "std::string";
        else if (inners.at(0) == "wchar_t")
            outertype = "std::wstring";
        qFill(extraArgs, zero);
        break;
    case UnknownType:
        qWarning("Unknown type encountered in %s.\n", Q_FUNC_INFO);
        break;
    case SupportedType:
    case QVectorType:
    case QStackType:
    case QObjectType:
    case QWidgetType:
        break;
    }

    // Look up expressions in the cache
    if (!m_expressionCache.empty()) {
        const ExpressionCache::const_iterator excCend = m_expressionCache.constEnd();
        const QByteArrayList::iterator eend = extraArgs.end();
        for (QByteArrayList::iterator it = extraArgs.begin(); it != eend; ++it) {
            QByteArray &e = *it;
            if (!e.isEmpty() && e != zero && !isInteger(e)) {
                const ExpressionCache::const_iterator eit = m_expressionCache.constFind(e);
                if (eit != excCend)
                    e = eit.value();
            }
        }
    }

    inBuffer->clear();
    inBuffer->append(outertype.toUtf8());
    inBuffer->append('\0');
    inBuffer->append(data.iname);
    inBuffer->append('\0');
    inBuffer->append(data.exp);
    inBuffer->append('\0');
    inBuffer->append(inner.toUtf8());
    inBuffer->append('\0');
    inBuffer->append(data.iname);
    inBuffer->append('\0');

    if (debug)
        qDebug() << '\n' << Q_FUNC_INFO << '\n' << data.toString() << "\n-->" << outertype << td.type << extraArgs;
}

QDebug operator<<(QDebug in, const DumperHelper::TypeData &d)
{
    QDebug nsp = in.nospace();
    nsp << " type=" << d.type << " tpl=" << d.isTemplate;
    if (d.isTemplate)
        nsp << d.tmplate << '<' << d.inner << '>';
    return in;
}

671 672 673 674 675
static bool isAccessSpecifier(const QByteArray &ba)
{
    return ba == "private" || ba == "protected" || ba == "public";
}

676 677 678
// reads a MI-encoded item frome the consolestream
static bool parseConsoleStream(const GdbResponse &response, GdbMi *contents)
{
679
    QByteArray out = response.consoleStreamOutput;
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696

    int markerPos = out.indexOf('"') + 1; // position of 'success marker'
    if (markerPos == 0 || out.at(markerPos) == 'f') {  // 't' or 'f'
        // custom dumper produced no output
        return false;
    }

    out = out.mid(markerPos +  1);
    out = out.left(out.lastIndexOf('"'));
    // optimization: dumper output never needs real C unquoting
    out.replace('\\', "");

    contents->fromStringMultiple(out);
    //qDebug() << "CONTENTS" << contents->toString(true);
    return contents->isValid();
}

697
void GdbEngine::updateLocalsClassic()
698 699
{
    PRECONDITION;
700 701
    m_pendingWatchRequests = 0;
    m_pendingBreakpointRequests = 0;
702 703
    m_processedNames.clear();

704 705
    if (0 && debugPending)
        qDebug() << "\nRESET PENDING";
706
    //m_toolTipCache.clear();
707
    clearToolTip();
708
    watchHandler()->beginCycle();
709 710 711 712 713 714 715 716

    QByteArray level = QByteArray::number(currentFrame());
    // '2' is 'list with type and value'
    QByteArray cmd = "-stack-list-arguments 2 " + level + ' ' + level;
    postCommand(cmd, WatchUpdate,
        CB(handleStackListArgumentsClassic));
    // '2' is 'list with type and value'
    postCommand("-stack-list-locals 2", WatchUpdate,
717
        CB(handleStackListLocalsClassic)); // stage 2/2
718 719 720 721 722 723 724 725 726 727
}

static inline QString msgRetrievingWatchData(int pending)
{
    return GdbEngine::tr("Retrieving data for watch view (%n requests pending)...", 0, pending);
}

void GdbEngine::runDirectDebuggingHelperClassic(const WatchData &data, bool dumpChildren)
{
    Q_UNUSED(dumpChildren)
728
    QByteArray type = data.type;
729 730 731 732 733 734 735 736 737 738 739
    QByteArray cmd;

    if (type == "QString" || type.endsWith("::QString"))
        cmd = "qdumpqstring (&(" + data.exp + "))";
    else if (type == "QStringList" || type.endsWith("::QStringList"))
        cmd = "qdumpqstringlist (&(" + data.exp + "))";

    QVariant var;
    var.setValue(data);
    postCommand(cmd, WatchUpdate, CB(handleDebuggingHelperValue3Classic), var);

740
    showStatusMessage(msgRetrievingWatchData(m_pendingWatchRequests + 1), 10000);
741 742 743 744 745 746 747 748 749 750 751 752 753 754
}

void GdbEngine::runDebuggingHelperClassic(const WatchData &data0, bool dumpChildren)
{
    PRECONDITION;
    if (m_debuggingHelperState != DebuggingHelperAvailable) {
        runDirectDebuggingHelperClassic(data0, dumpChildren);
        return;
    }
    WatchData data = data0;

    // Avoid endless loops created by faulty dumpers.
    QByteArray processedName = QByteArray::number(dumpChildren) + '-' + data.iname;
    if (m_processedNames.contains(processedName)) {
755 756
        showMessage(
            _("<Breaking endless loop for " + data.iname + '>'), LogMiscInput);
757 758 759 760
        data.setAllUnneeded();
        data.setValue(_("<unavailable>"));
        data.setHasChildren(false);
        insertData(data);
761
        return;
762 763 764 765
    }
    m_processedNames.insert(processedName);

    QByteArray params;
766
    QList<QByteArray> extraArgs;
767
    const DumperHelper::TypeData td = m_dumperHelper.typeData(data0.type);
Friedemann Kleint's avatar
Friedemann Kleint committed
768
    m_dumperHelper.evaluationParameters(data, td, &params, &extraArgs);
769 770 771 772 773 774 775

    //int protocol = (data.iname.startsWith("watch") && data.type == "QImage") ? 3 : 2;
    //int protocol = data.iname.startsWith("watch") ? 3 : 2;
    const int protocol = 2;
    //int protocol = isDisplayedIName(data.iname) ? 3 : 2;

    QByteArray addr;
776 777
    if (data.address)
        addr = "(void*)" + data.hexAddress();
778
    else if (data.exp.isEmpty()) // happens e.g. for QAbstractItem
779
        addr = QByteArray(1, '0');
780 781 782 783 784
    else
        addr = "&(" + data.exp + ')';

    sendWatchParameters(params);

785 786 787 788 789 790 791
    QByteArray cmd = "call (void*)qDumpObjectData440("
        + QByteArray::number(protocol)
        + ",0,"
        + addr
        + ','
        + (dumpChildren ? '1' : '0');
    foreach (const QByteArray &ex, extraArgs)
792
        cmd += ',' + ex;
793
    cmd += ')';
794

795
    postCommand(cmd, WatchUpdate | NonCriticalResponse);
796

797
    showStatusMessage(msgRetrievingWatchData(m_pendingWatchRequests + 1), 10000);
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812

    // retrieve response
    postCommand("p (char*)&qDumpOutBuffer", WatchUpdate,
        CB(handleDebuggingHelperValue2Classic), qVariantFromValue(data));
}

void GdbEngine::createGdbVariableClassic(const WatchData &data)
{
    PRECONDITION;
    if (data.iname == "local.flist.0") {
        int i = 1;
        Q_UNUSED(i);
    }
    postCommand("-var-delete \"" + data.iname + '"', WatchUpdate);
    QByteArray exp = data.exp;
813 814
    if (exp.isEmpty() && data.address)
        exp = "*(" + gdbQuoteTypes(data.type) + "*)" + data.hexAddress();
815 816 817 818 819 820 821 822 823
    QVariant val = QVariant::fromValue<WatchData>(data);
    postCommand("-var-create \"" + data.iname + "\" * \"" + exp + '"',
        WatchUpdate, CB(handleVarCreate), val);
}

void GdbEngine::updateSubItemClassic(const WatchData &data0)
{
    PRECONDITION;
    WatchData data = data0;
824 825
    if (debugSubItem)
        qDebug() << "UPDATE SUBITEM:" << data.toString();
826 827 828 829 830 831 832 833
    QTC_ASSERT(data.isValid(), return);

    // in any case we need the type first
    if (data.isTypeNeeded()) {
        // This should only happen if we don't have a variable yet.
        // Let's play safe, though.
        if (!data.variable.isEmpty()) {
            // Update: It does so for out-of-scope watchers.
Tobias Hunger's avatar
Tobias Hunger committed
834
#            if 1
835 836
            qDebug() << "FIXME: GdbEngine::updateSubItem:"
                 << data.toString() << "should not happen";
Tobias Hunger's avatar
Tobias Hunger committed
837
#            else
838 839 840 841 842
            data.setType(WatchData::msgNotInScope());
            data.setValue(WatchData::msgNotInScope());
            data.setHasChildren(false);
            insertData(data);
            return;
Tobias Hunger's avatar
Tobias Hunger committed
843
#            endif
844 845 846 847 848 849 850 851 852
        }
        // The WatchVarCreate handler will receive type information
        // and re-insert a WatchData item with correct type, so
        // we will not re-enter this bit.
        // FIXME: Concurrency issues?
        createGdbVariableClassic(data);
        return;
    }

853
    // We should have a type now. This is relied upon further below.
854 855
    QTC_ASSERT(!data.type.isEmpty(), return);

856
    // A common case that can be easily solved.
857 858
    if (data.isChildrenNeeded() && isPointerType(data.type)
        && !hasDebuggingHelperForType(data.type)) {
859 860 861
        // We sometimes know what kind of children pointers have.
        if (debugSubItem)
            qDebug() << "IT'S A POINTER";
862

hjk's avatar
hjk committed
863
        if (debuggerCore()->boolSetting(AutoDerefPointers)) {
864 865
            // Try automatic dereferentiation
            data.exp = "(*(" + data.exp + "))";
866
            data.type = data.type + '.'; // FIXME: fragile HACK to avoid recursion
867 868
            if (data.value.startsWith("0x"))
                data.value = "@" + data.value;
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
            insertData(data);
        } else {
            data.setChildrenUnneeded();
            insertData(data);
            WatchData data1;
            data1.iname = data.iname + ".*";
            data1.name = QLatin1Char('*') + data.name;
            data1.exp = "(*(" + data.exp + "))";
            data1.type = stripPointerType(data.type);
            data1.setValueNeeded();
            data1.setChildrenUnneeded();
            insertData(data1);
        }
        return;
    }

    if (data.isValueNeeded() && hasDebuggingHelperForType(data.type)) {
886 887
        if (debugSubItem)
            qDebug() << "UPDATE SUBITEM: CUSTOMVALUE";
888
        runDebuggingHelperClassic(data,
889
            watchHandler()->isExpandedIName(data.iname));
890 891 892 893 894
        return;
    }

/*
    if (data.isValueNeeded() && data.exp.isEmpty()) {
895 896
        if (debugSubItem)
            qDebug() << "UPDATE SUBITEM: NO EXPRESSION?";
897 898 899 900 901 902 903
        data.setError("<no expression given>");
        insertData(data);
        return;
    }
*/

    if (data.isValueNeeded() && data.variable.isEmpty()) {
904 905
        if (debugSubItem)
            qDebug() << "UPDATE SUBITEM: VARIABLE NEEDED FOR VALUE";
906 907 908 909 910 911 912 913
        createGdbVariableClassic(data);
        // the WatchVarCreate handler will re-insert a WatchData
        // item, with valueNeeded() set.
        return;
    }

    if (data.isValueNeeded()) {
        QTC_ASSERT(!data.variable.isEmpty(), return); // tested above
914 915
        if (debugSubItem)
            qDebug() << "UPDATE SUBITEM: VALUE";
916
        QByteArray cmd = "-var-evaluate-expression \"" + data.iname + '"';
917 918
        postCommand(cmd, WatchUpdate,
            CB(handleEvaluateExpressionClassic), QVariant::fromValue(data));
919 920 921 922
        return;
    }

    if (data.isChildrenNeeded() && hasDebuggingHelperForType(data.type)) {
923 924
        if (debugSubItem)
            qDebug() << "UPDATE SUBITEM: CUSTOMVALUE WITH CHILDREN";
925 926 927 928 929
        runDebuggingHelperClassic(data, true);
        return;
    }

    if (data.isChildrenNeeded() && data.variable.isEmpty()) {
930 931
        if (debugSubItem)
            qDebug() << "UPDATE SUBITEM: VARIABLE NEEDED FOR CHILDREN";
932 933 934 935 936 937 938 939 940
        createGdbVariableClassic(data);
        // the WatchVarCreate handler will re-insert a WatchData
        // item, with childrenNeeded() set.
        return;
    }

    if (data.isChildrenNeeded()) {
        QTC_ASSERT(!data.variable.isEmpty(), return); // tested above
        QByteArray cmd = "-var-list-children --all-values \"" + data.variable + '"';
941 942
        postCommand(cmd, WatchUpdate,
            CB(handleVarListChildrenClassic), QVariant::fromValue(data));
943 944 945 946
        return;
    }

    if (data.isHasChildrenNeeded() && hasDebuggingHelperForType(data.type)) {
947 948
        if (debugSubItem)
            qDebug() << "UPDATE SUBITEM: CUSTOMVALUE WITH CHILDREN";
949
        runDebuggingHelperClassic(data, watchHandler()->isExpandedIName(data.iname));
950 951 952 953 954
        return;
    }

//#if !X
    if (data.isHasChildrenNeeded() && data.variable.isEmpty()) {
955 956
        if (debugSubItem)
            qDebug() << "UPDATE SUBITEM: VARIABLE NEEDED FOR CHILDCOUNT";
957 958 959 960 961 962 963 964 965 966 967
        createGdbVariableClassic(data);
        // the WatchVarCreate handler will re-insert a WatchData
        // item, with childrenNeeded() set.
        return;
    }
//#endif

    if (data.isHasChildrenNeeded()) {
        QTC_ASSERT(!data.variable.isEmpty(), return); // tested above
        QByteArray cmd = "-var-list-children --all-values \"" + data.variable + '"';
        postCommand(cmd, Discardable,
968
            CB(handleVarListChildrenClassic), QVariant::fromValue(data));
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
        return;
    }

    qDebug() << "FIXME: UPDATE SUBITEM:" << data.toString();
    QTC_ASSERT(false, return);
}

void GdbEngine::handleDebuggingHelperValue2Classic(const GdbResponse &response)
{
    PRECONDITION;
    WatchData data = response.cookie.value<WatchData>();
    QTC_ASSERT(data.isValid(), return);

    // The real dumper might have aborted without giving any answers.
    // Remove traces of the question, too.
    if (m_cookieForToken.contains(response.token - 1)) {
        m_cookieForToken.remove(response.token - 1);
986
        showMessage(_("DETECTING LOST COMMAND %1").arg(response.token - 1));
987
        --m_pendingWatchRequests;
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
        data.setError(WatchData::msgNotInScope());
        insertData(data);
        return;
    }

    //qDebug() << "CUSTOM VALUE RESULT:" << response.toString();
    //qDebug() << "FOR DATA:" << data.toString() << response.resultClass;
    if (response.resultClass != GdbResultDone) {
        qDebug() << "STRANGE CUSTOM DUMPER RESULT DATA:" << data.toString();
        return;
    }

    GdbMi contents;
    if (!parseConsoleStream(response, &contents)) {
        data.setError(WatchData::msgNotInScope());
        insertData(data);
        return;
    }

    setWatchDataType(data, response.data.findChild("type"));
    setWatchDataDisplayedType(data, response.data.findChild("displaytype"));
    QList<WatchData> list;
1010
    parseWatchData(watchHandler()->expandedINames(), data, contents, &list);
1011 1012
    //for (int i = 0; i != list.size(); ++i)
    //    qDebug() << "READ: " << list.at(i).toString();
1013
    watchHandler()->insertBulkData(list);
1014 1015 1016 1017 1018 1019
}

void GdbEngine::handleDebuggingHelperValue3Classic(const GdbResponse &response)
{
    if (response.resultClass == GdbResultDone) {
        WatchData data = response.cookie.value<WatchData>();
1020
        QByteArray out = response.consoleStreamOutput;
1021 1022 1023 1024 1025 1026 1027
        while (out.endsWith(' ') || out.endsWith('\n'))
            out.chop(1);
        QList<QByteArray> list = out.split(' ');
        if (list.isEmpty()) {
            data.setError(WatchData::msgNotInScope());
            data.setAllUnneeded();
            insertData(data);
1028 1029
        } else if (data.type == "QString"
                || data.type.endsWith("::QString")) {
1030 1031 1032 1033 1034 1035 1036 1037 1038
            QList<QByteArray> list = out.split(' ');
            QString str;
            int l = out.isEmpty() ? 0 : list.size();
            for (int i = 0; i < l; ++i)
                 str.append(list.at(i).toInt());
            data.setValue(_c('"') + str + _c('"'));
            data.setHasChildren(false);
            data.setAllUnneeded();
            insertData(data);
1039 1040
        } else if (data.type == "QStringList"
                || data.type.endsWith("::QStringList")) {
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
            if (out.isEmpty()) {
                data.setValue(tr("<0 items>"));
                data.setHasChildren(false);
                data.setAllUnneeded();
                insertData(data);
            } else {
                int l = list.size();
                //: In string list
                data.setValue(tr("<%n items>", 0, l));
                data.setHasChildren(!list.empty());
                data.setAllUnneeded();
                insertData(data);
                for (int i = 0; i < l; ++i) {
                    WatchData data1;
                    data1.name = _("[%1]").arg(i);
                    data1.type = data.type.left(data.type.size() - 4);
                    data1.iname = data.iname + '.' + QByteArray::number(i);
1058 1059 1060 1061 1062 1063 1064
                    const QByteArray &addressSpec = list.at(i);
                    if (addressSpec.startsWith("0x")) {
                        data.setHexAddress(addressSpec);
                    } else {
                        data.dumperFlags = addressSpec; // Item model dumpers pull tricks
                    }
                    data1.exp = "((" + gdbQuoteTypes(data1.type) + "*)" + addressSpec + ')';
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
                    data1.setHasChildren(false);
                    data1.setValueNeeded();
                    QByteArray cmd = "qdumpqstring (" + data1.exp + ')';
                    QVariant var;
                    var.setValue(data1);
                    postCommand(cmd, WatchUpdate,
                        CB(handleDebuggingHelperValue3Classic), var);
                }
            }
        } else {
            data.setError(WatchData::msgNotInScope());
            data.setAllUnneeded();
            insertData(data);
        }
    } else {
        WatchData data = response.cookie.value<WatchData>();
        data.setError(WatchData::msgNotInScope());
        data.setAllUnneeded();
        insertData(data);
    }
}

void GdbEngine::tryLoadDebuggingHelpersClassic()
{
    PRECONDITION;
    if (m_gdbAdapter->dumperHandling() == AbstractGdbAdapter::DumperNotAvailable) {
        // Load at least gdb macro based dumpers.
        m_debuggingHelperState = DebuggingHelperLoadTried;
1093
        postCommand(Utils::FileReader::fetchQrc(_(":/gdb/gdbmacros.txt")));
1094 1095 1096
        return;
    }

1097 1098
    if (debugPending)
        qDebug() << "TRY LOAD CUSTOM DUMPERS";
1099 1100 1101 1102 1103 1104
    m_debuggingHelperState = DebuggingHelperUnavailable;
    if (!checkDebuggingHelpersClassic())
        return;

    m_debuggingHelperState = DebuggingHelperLoadTried;
    QByteArray dlopenLib;
1105 1106 1107
    const DebuggerStartMode startMode = startParameters().startMode;
    if (startMode == AttachToRemote || startMode == StartRemoteGdb)
        dlopenLib = startParameters().remoteDumperLib;
1108
    else
1109
        dlopenLib = qtDumperLibraryName().toLocal8Bit();
hjk's avatar
hjk committed
1110

1111
    // Do not use STRINGIFY for RTLD_NOW as we really want to expand that to a number.
hjk's avatar
hjk committed
1112 1113
#if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
    // We are using Python on Windows and Symbian.
hjk's avatar
hjk committed
1114
    QTC_ASSERT(false, /**/);
1115 1116 1117
#elif defined(Q_OS_MAC)
    //postCommand("sharedlibrary libc"); // for malloc
    //postCommand("sharedlibrary libdl"); // for dlopen
1118
    const QByteArray flag = QByteArray::number(RTLD_NOW);
1119
    postCommand("call (void)dlopen(\"" + GdbMi::escapeCString(dlopenLib)
hjk's avatar
hjk committed
1120
                + "\", " + flag + ")",
1121 1122 1123 1124
        CB(handleDebuggingHelperSetup));
    //postCommand("sharedlibrary " + dotEscape(dlopenLib));
#else
    //postCommand("p dlopen");
1125
    const QByteArray flag = QByteArray::number(RTLD_NOW);
1126 1127 1128
    postCommand("sharedlibrary libc"); // for malloc
    postCommand("sharedlibrary libdl"); // for dlopen
    postCommand("call (void*)dlopen(\"" + GdbMi::escapeCString(dlopenLib)
hjk's avatar
hjk committed
1129
                + "\", " + flag + ")",
1130
        CB(handleDebuggingHelperSetup));
1131
    // Some older systems like CentOS 4.6 prefer this:
1132
    postCommand("call (void*)__dlopen(\"" + GdbMi::escapeCString(dlopenLib)
hjk's avatar
hjk committed
1133
                + "\", " + flag + ")",
1134 1135 1136
        CB(handleDebuggingHelperSetup));
    postCommand("sharedlibrary " + dotEscape(dlopenLib));
#endif
hjk's avatar
hjk committed
1137
    tryQueryDebuggingHelpersClassic();
1138 1139 1140 1141 1142
}

void GdbEngine::tryQueryDebuggingHelpersClassic()
{
    PRECONDITION;
1143
    // Retrieve list of dumpable classes.
1144 1145 1146 1147 1148 1149 1150 1151 1152
    postCommand("call (void*)qDumpObjectData440(1,0,0,0,0,0,0,0)");
    postCommand("p (char*)&qDumpOutBuffer",
        CB(handleQueryDebuggingHelperClassic));
}

// Called from CoreAdapter and AttachAdapter
void GdbEngine::updateAllClassic()
{
    PRECONDITION;
1153 1154
    if (debugPending)
        qDebug() << "UPDATING ALL\n";
1155 1156
    QTC_ASSERT(state() == InferiorUnrunnable || state() == InferiorStopOk,
        qDebug() << state());
1157 1158 1159 1160 1161
    tryLoadDebuggingHelpersClassic();
    reloadModulesInternal();
    postCommand("-stack-list-frames", WatchUpdate,
        CB(handleStackListFrames),
        QVariant::fromValue<StackCookie>(StackCookie(false, true)));
1162
    stackHandler()->setCurrentIndex(0);
1163
    if (supportsThreads())
1164
        postCommand("-thread-list-ids", WatchUpdate, CB(handleThreadListIds), 0);
1165
    reloadRegisters();
1166
    updateLocals();
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
}

void GdbEngine::setDebuggingHelperStateClassic(DebuggingHelperState s)
{
    PRECONDITION;
    m_debuggingHelperState = s;
}

void GdbEngine::handleStackListArgumentsClassic(const GdbResponse &response)
{
    PRECONDITION;
    // stage 1/2

    // Linux:
    // 12^done,stack-args=
    //   [frame={level="0",args=[
    //     {name="argc",type="int",value="1"},
    //     {name="argv",type="char **",value="(char **) 0x7..."}]}]
    // Mac:
    // 78^done,stack-args=
    //    {frame={level="0",args={
    //      varobj=
    //        {exp="this",value="0x38a2fab0",name="var21",numchild="3",
    //             type="CurrentDocumentFind *  const",typecode="PTR",
    //             dynamic_type="",in_scope="true",block_start_addr="0x3938e946",
    //             block_end_addr="0x3938eb2d"},
    //      varobj=
    //         {exp="before",value="@0xbfffb9f8: {d = 0x3a7f2a70}",
    //              name="var22",numchild="1",type="const QString  ...} }}}
    //
    // In both cases, iterating over the children of stack-args/frame/args
    // is ok.
    m_currentFunctionArgs.clear();
    if (response.resultClass == GdbResultDone) {
        const GdbMi list = response.data.findChild("stack-args");
        const GdbMi frame = list.findChild("frame");
        const GdbMi args = frame.findChild("args");
        m_currentFunctionArgs = args.children();
    } else {
1206 1207
        // Seems to occur on "RedHat 4 based Linux" gdb 7.0.1:
        // ^error,msg="Cannot access memory at address 0x0"
1208
        showMessage(_("UNEXPECTED RESPONSE: ") + response.toString());
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    }
}

void GdbEngine::handleStackListLocalsClassic(const GdbResponse &response)
{
    PRECONDITION;
    // stage 2/2

    // There could be shadowed variables
    QList<GdbMi> locals = response.data.findChild("locals").children();
    locals += m_currentFunctionArgs;
    QMap<QByteArray, int> seen;
    // If desired, retrieve list of uninitialized variables looking at
    // the current frame. This is invoked first time after a stop from
    // handleStop1, which passes on the frame as cookie. The whole stack
    // is not known at this point.
    QStringList uninitializedVariables;
hjk's avatar
hjk committed
1226
    if (debuggerCore()->action(UseCodeModel)->isChecked()) {
1227 1228 1229 1230
        const StackFrame frame =
            qVariantCanConvert<Debugger::Internal::StackFrame>(response.cookie)
                ? qVariantValue<Debugger::Internal::StackFrame>(response.cookie)
                : stackHandler()->currentFrame();
1231
        if (frame.isUsable())
1232
            getUninitializedVariables(debuggerCore()->cppCodeModelSnapshot(),
1233 1234 1235 1236 1237 1238 1239 1240 1241
                                      frame.function, frame.file, frame.line,
                                      &uninitializedVariables);
    }
    QList<WatchData> list;
    foreach (const GdbMi &item, locals) {
        const WatchData data = localVariable(item, uninitializedVariables, &seen);
        if (data.isValid())
            list.push_back(data);
    }
1242 1243 1244 1245 1246 1247 1248 1249 1250

    if (!m_resultVarName.isEmpty()) {
        WatchData rd;
        rd.iname = "return.0";
        rd.name = "return";
        rd.exp = m_resultVarName;
        list.append(rd);
    }

1251 1252
    watchHandler()->insertBulkData(list);
    watchHandler()->updateWatchers();
1253 1254 1255 1256 1257
}

bool GdbEngine::checkDebuggingHelpersClassic()
{
    PRECONDITION;
1258
    if (!qtDumperLibraryEnabled())
1259 1260
        return false;
    const QString lib = qtDumperLibraryName();
1261 1262 1263 1264 1265 1266 1267
    if (QFileInfo(lib).exists())
        return true;
    const QStringList &locations = qtDumperLibraryLocations();
    const QString loc = locations.join(QLatin1String(", "));
    const QString msg = tr("The debugging helper library was not found at %1.")
            .arg(loc);
    showMessage(msg);
1268 1269 1270
    // This can happen for remote debugging.
    if (!locations.isEmpty())
        showQtDumperLibraryWarning(msg); // This might build the library.
1271
    return QFileInfo(lib).exists();
1272 1273 1274 1275 1276 1277 1278 1279 1280
}

void GdbEngine::handleQueryDebuggingHelperClassic(const GdbResponse &response)
{
    const double dumperVersionRequired = 1.0;
    //qDebug() << "DATA DUMPER TRIAL:" << response.toString();

    GdbMi contents;
    QTC_ASSERT(parseConsoleStream(response, &contents), qDebug() << response.toString());
hjk's avatar
hjk committed
1281
    const bool ok = m_dumperHelper.parseQuery(contents)
1282 1283 1284 1285 1286 1287
        && m_dumperHelper.typeCount();
    if (ok) {
        // Get version and sizes from dumpers. Expression cache
        // currently causes errors.
        const double dumperVersion = getDumperVersion(contents);
        if (dumperVersion < dumperVersionRequired) {
1288
            showQtDumperLibraryWarning(
1289
                DumperHelper::msgDumperOutdated(dumperVersionRequired, dumperVersion));
1290 1291 1292 1293 1294 1295 1296
            m_debuggingHelperState = DebuggingHelperUnavailable;
            return;
        }
        m_debuggingHelperState = DebuggingHelperAvailable;
        const QString successMsg = tr("Dumper version %1, %n custom dumpers found.",
            0, m_dumperHelper.typeCount()).arg(dumperVersion);
        showStatusMessage(successMsg);
1297 1298

        // Sanity check for Qt version of dumpers and debuggee.
1299
        QByteArray ns = m_dumperHelper.qtNamespace();
1300 1301 1302
        postCommand("-var-create A@ * '" + ns + "qVersion'()",
            CB(handleDebuggingHelperVersionCheckClassic));
        postCommand("-var-delete A@");
1303
    } else {
hjk's avatar
hjk committed
1304 1305
        // Retry if thread has not terminated yet.
        m_debuggingHelperState = DebuggingHelperUnavailable;
1306 1307 1308 1309 1310
        showStatusMessage(tr("Debugging helpers not found."));
    }
    //qDebug() << m_dumperHelper.toString(true);
    //qDebug() << m_availableSimpleDebuggingHelpers << "DATA DUMPERS AVAILABLE";
}
hjk's avatar
hjk committed
1311

1312 1313 1314 1315 1316 1317
void GdbEngine::handleDebuggingHelperVersionCheckClassic(const GdbResponse &response)
{
    if (response.resultClass == GdbResultDone) {
        QString value = _(response.data.findChild("value").data());
        QString debuggeeQtVersion = value.section(QLatin1Char('"'), 1, 1);
        QString dumperQtVersion = m_dumperHelper.qtVersionString();
1318 1319 1320 1321 1322 1323
        if (debuggeeQtVersion.isEmpty()) {
            showMessage(_("DUMPER VERSION CHECK SKIPPED, NO qVersion() OUTPUT IN")
                + response.toString());
        } else if (dumperQtVersion.isEmpty()) {
            showMessage(_("DUMPER VERSION CHECK SKIPPED, NO VERSION STRING"));
        } else if (dumperQtVersion != debuggeeQtVersion) {
1324
            showMessageBox(QMessageBox::Warning,
1325 1326 1327 1328 1329 1330
                tr("Debugging helpers: Qt version mismatch"),
                tr("The Qt version used to build the debugging helpers (%1) "
                   "does not match the Qt version used to build the debugged "
                   "application (%2).\nThis might yield incorrect results.")
                    .arg(dumperQtVersion).arg(debuggeeQtVersion));
        } else {
1331
            showMessage(_("DUMPER VERSION CHECK SUCCESSFUL: ")
1332 1333 1334
                         + dumperQtVersion);
        }
    } else {
1335
        showMessage("DUMPER VERSION CHECK NOT COMPLETED");
1336 1337 1338
    }
}

1339
void GdbEngine::handleVarListChildrenHelperClassic(const GdbMi &item,
1340
    const WatchData &parent, int sortId)
1341 1342 1343 1344 1345 1346
{
    //qDebug() <<  "VAR_LIST_CHILDREN: PARENT" << parent.toString();
    //qDebug() <<  "VAR_LIST_CHILDREN: ITEM" << item.toString();
    QByteArray exp = item.findChild("exp").data();
    QByteArray name = item.findChild("name").data();
    if (isAccessSpecifier(exp)) {
1347
        // Suppress 'private'/'protected'/'public' level.
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        WatchData data;
        data.variable = name;
        data.iname = parent.iname;
        //data.iname = data.variable;
        data.exp = parent.exp;
        data.setTypeUnneeded();
        data.setValueUnneeded();
        data.setHasChildrenUnneeded();
        data.setChildrenUnneeded();
        QByteArray cmd = "-var-list-children --all-values \"" + data.variable + '"';
        //iname += '.' + exp;
        postCommand(cmd, WatchUpdate,
            CB(handleVarListChildrenClassic), QVariant::fromValue(data));
1361 1362 1363
    } else if (!startsWithDigit(exp)
            && item.findChild("numchild").data() == "0") {
        // Happens for structs without data, e.g. interfaces.
1364 1365 1366 1367 1368
        WatchData data;
        data.name = _(exp);
        data.iname = parent.iname + '.' + data.name.toLatin1();
        data.variable = name;
        setWatchDataType(data, item.findChild("type"));
1369
        setWatchDataValue(data, item);
1370
        setWatchDataAddress(data, item.findChild("addr"), GdbMi());
1371 1372 1373
        data.setHasChildren(false);
        insertData(data);
    } else if (parent.iname.endsWith('.')) {
1374
        // Happens with anonymous unions.
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
        WatchData data;
        data.iname = name;
        QByteArray cmd = "-var-list-children --all-values \"" + data.variable + '"';
        postCommand(cmd, WatchUpdate,
            CB(handleVarListChildrenClassic), QVariant::fromValue(data));
    } else if (exp == "staticMetaObject") {
        //    && item.findChild("type").data() == "const QMetaObject")
        // FIXME: Namespaces?
        // { do nothing }    FIXME: make configurable?
        // special "clever" hack to avoid clutter in the GUI.
        // I am not sure this is a good idea...
    } else {
1387
        // Suppress 'private'/'protected'/'public' level.
1388 1389 1390
        WatchData data;
        data.iname = parent.iname + '.' + exp;
        data.variable = name;
1391
        data.sortId = sortId;
1392
        setWatchDataType(data, item.findChild("type"));
1393
        setWatchDataValue(data, item);
1394
        setWatchDataAddress(data, item.findChild("addr"), GdbMi());
1395
        setWatchDataChildCount(data, item.findChild("numchild"));
1396
        if (!watchHandler()->isExpandedIName(data.iname))
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
            data.setChildrenUnneeded();

        data.name = _(exp);
        if (data.type == data.name) {
            if (isPointerType(parent.type)) {
                data.exp = "*(" + parent.exp + ')';
                data.name = _("*") + parent.name;
            } else {
                // A type we derive from? gdb crashes when creating variables here
                data.exp = parent.exp;
            }
1408
        } else if (exp.startsWith('*')) {
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
            // A pointer
            data.exp = "*(" + parent.exp + ')';
        } else if (startsWithDigit(data.name)) {
            // An array. No variables needed?
            data.name = _c('[') + data.name + _c(']');
            data.exp = parent.exp + '[' + exp + ']';
        } else if (0 && parent.name.endsWith(_c('.'))) {
            // Happens with anonymous unions
            data.exp = parent.exp + data.name.toLatin1();
            //data.name = "<anonymous union>";
        } else if (exp.isEmpty()) {
            // Happens with anonymous unions
            data.exp = parent.exp;
            data.name = tr("<n/a>");
            data.iname = parent.iname + ".@";
1424
            data.type = tr("<anonymous union>").toUtf8();
1425 1426
        } else {
            // A structure. Hope there's nothing else...
1427
            data.exp = '(' + parent.exp + ")." + data.name.toLatin1();
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
        }

        if (hasDebuggingHelperForType(data.type)) {
            // we do not trust gdb if we have a custom dumper
            data.setValueNeeded();
            data.setHasChildrenNeeded();
        }

        //qDebug() <<  "VAR_LIST_CHILDREN: PARENT 3" << parent.toString();
        //qDebug() <<  "VAR_LIST_CHILDREN: APPENDEE" << data.toString();
        insertData(data);
    }
}

void GdbEngine::handleVarListChildrenClassic(const GdbResponse &response)
{
    //WatchResultCounter dummy(this, WatchVarListChildren);
    WatchData data = response.cookie.value<WatchData>();
    if (!data.isValid())
        return;
    if (response.resultClass == GdbResultDone) {
        //qDebug() <<  "VAR_LIST_CHILDREN: PARENT" << data.toString();
1450
        QList<GdbMi> children = response.data.findChild("children").children();
1451

1452 1453
        for (int i = 0; i != children.size(); ++i)
            handleVarListChildrenHelperClassic(children.at(i), data, i);
1454

1455
        if (children.isEmpty()) {