pdbengine.cpp 25.6 KB
Newer Older
hjk's avatar
hjk committed
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).
hjk's avatar
hjk committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
hjk's avatar
hjk committed
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.
hjk's avatar
hjk committed
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
29
** Nokia at qt-info@nokia.com.
hjk's avatar
hjk committed
30 31 32 33 34 35 36
**
**************************************************************************/

#define QT_NO_CAST_FROM_ASCII

#include "pdbengine.h"

Friedemann Kleint's avatar
Friedemann Kleint committed
37
#include "debuggerstartparameters.h"
hjk's avatar
hjk committed
38
#include "debuggeractions.h"
hjk's avatar
hjk committed
39
#include "debuggercore.h"
hjk's avatar
hjk committed
40
#include "debuggerdialogs.h"
41 42
#include "debuggerplugin.h"
#include "debuggerstringutils.h"
43
#include "debuggertooltipmanager.h"
44

hjk's avatar
hjk committed
45 46 47 48 49 50
#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
#include "stackhandler.h"
#include "watchhandler.h"
#include "watchutils.h"
51

hjk's avatar
hjk committed
52 53 54 55 56
#include "../gdb/gdbmi.h"

#include <utils/qtcassert.h>

#include <texteditor/itexteditor.h>
57
#include <coreplugin/idocument.h>
hjk's avatar
hjk committed
58 59
#include <coreplugin/icore.h>

60 61 62 63 64 65
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTimer>
#include <QVariant>
hjk's avatar
hjk committed
66

67 68 69
#include <QApplication>
#include <QMessageBox>
#include <QToolTip>
hjk's avatar
hjk committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91


#define DEBUG_SCRIPT 1
#if DEBUG_SCRIPT
#   define SDEBUG(s) qDebug() << s
#else
#   define SDEBUG(s)
#endif
# define XSDEBUG(s) qDebug() << s


#define CB(callback) &PdbEngine::callback, STRINGIFY(callback)

namespace Debugger {
namespace Internal {

///////////////////////////////////////////////////////////////////////
//
// PdbEngine
//
///////////////////////////////////////////////////////////////////////

92
PdbEngine::PdbEngine(const DebuggerStartParameters &startParameters)
93
    : DebuggerEngine(startParameters, AnyLanguage)
Friedemann Kleint's avatar
Friedemann Kleint committed
94 95 96
{
    setObjectName(QLatin1String("PdbEngine"));
}
hjk's avatar
hjk committed
97 98 99 100

PdbEngine::~PdbEngine()
{}

101
void PdbEngine::executeDebuggerCommand(const QString &command, DebuggerLanguages languages)
hjk's avatar
hjk committed
102
{
103 104
    if (!(languages & CppLanguage))
        return;
105 106
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
    //XSDEBUG("PdbEngine::executeDebuggerCommand:" << command);
hjk's avatar
hjk committed
107
    if (state() == DebuggerNotReady) {
108
        showMessage(_("PDB PROCESS NOT RUNNING, PLAIN CMD IGNORED: ") + command);
hjk's avatar
hjk committed
109 110
        return;
    }
111 112 113 114 115 116 117 118 119 120 121 122 123
    QTC_ASSERT(m_pdbProc.state() == QProcess::Running, notifyEngineIll());
    postCommand(command.toLatin1(), CB(handleExecuteDebuggerCommand));
}

void PdbEngine::handleExecuteDebuggerCommand(const PdbResponse &response)
{
    Q_UNUSED(response);
}

void PdbEngine::postDirectCommand(const QByteArray &command)
{
    QTC_ASSERT(m_pdbProc.state() == QProcess::Running, notifyEngineIll());
    showMessage(_(command), LogInput);
hjk's avatar
hjk committed
124
    m_pdbProc.write(command + '\n');
hjk's avatar
hjk committed
125 126 127 128 129 130 131 132
}

void PdbEngine::postCommand(const QByteArray &command,
//                 PdbCommandFlags flags,
                 PdbCommandCallback callback,
                 const char *callbackName,
                 const QVariant &cookie)
{
133
    QTC_ASSERT(m_pdbProc.state() == QProcess::Running, notifyEngineIll());
hjk's avatar
hjk committed
134 135 136 137 138 139
    PdbCommand cmd;
    cmd.command = command;
    cmd.callback = callback;
    cmd.callbackName = callbackName;
    cmd.cookie = cookie;
    m_commands.enqueue(cmd);
140
    qDebug() << "ENQUEUE: " << command << cmd.callbackName;
141
    showMessage(_(cmd.command), LogInput);
hjk's avatar
hjk committed
142
    m_pdbProc.write(cmd.command + '\n');
hjk's avatar
hjk committed
143 144
}

hjk's avatar
hjk committed
145
void PdbEngine::shutdownInferior()
hjk's avatar
hjk committed
146
{
hjk's avatar
hjk committed
147 148
    QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
    notifyInferiorShutdownOk();
hjk's avatar
hjk committed
149 150
}

hjk's avatar
hjk committed
151
void PdbEngine::shutdownEngine()
hjk's avatar
hjk committed
152
{
hjk's avatar
hjk committed
153
    QTC_ASSERT(state() == EngineShutdownRequested, qDebug() << state());
hjk's avatar
hjk committed
154 155 156
    m_pdbProc.kill();
}

hjk's avatar
hjk committed
157
void PdbEngine::setupEngine()
hjk's avatar
hjk committed
158
{
hjk's avatar
hjk committed
159
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
hjk's avatar
hjk committed
160

161
    m_pdb = _("python");
162
    showMessage(_("STARTING PDB ") + m_pdb);
hjk's avatar
hjk committed
163 164 165

    connect(&m_pdbProc, SIGNAL(error(QProcess::ProcessError)),
        SLOT(handlePdbError(QProcess::ProcessError)));
Robert Loehning's avatar
Robert Loehning committed
166 167
    connect(&m_pdbProc, SIGNAL(finished(int,QProcess::ExitStatus)),
        SLOT(handlePdbFinished(int,QProcess::ExitStatus)));
hjk's avatar
hjk committed
168 169 170 171 172
    connect(&m_pdbProc, SIGNAL(readyReadStandardOutput()),
        SLOT(readPdbStandardOutput()));
    connect(&m_pdbProc, SIGNAL(readyReadStandardError()),
        SLOT(readPdbStandardError()));

173 174 175
    connect(this, SIGNAL(outputReady(QByteArray)),
        SLOT(handleOutput2(QByteArray)), Qt::QueuedConnection);

Tobias Hunger's avatar
Tobias Hunger committed
176
    // We will stop immediately, so setup a proper callback.
hjk's avatar
hjk committed
177
    PdbCommand cmd;
hjk's avatar
hjk committed
178
    cmd.callback = &PdbEngine::handleFirstCommand;
hjk's avatar
hjk committed
179 180
    m_commands.enqueue(cmd);

181
    m_pdbProc.start(m_pdb, QStringList() << _("-i"));
hjk's avatar
hjk committed
182 183 184 185

    if (!m_pdbProc.waitForStarted()) {
        const QString msg = tr("Unable to start pdb '%1': %2")
            .arg(m_pdb, m_pdbProc.errorString());
186
        notifyEngineSetupFailed();
187
        showMessage(_("ADAPTER START FAILED"));
hjk's avatar
hjk committed
188 189
        if (!msg.isEmpty()) {
            const QString title = tr("Adapter start failed");
hjk's avatar
hjk committed
190
            Core::ICore::showWarningWithOptions(title, msg);
hjk's avatar
hjk committed
191
        }
192
        notifyEngineSetupFailed();
hjk's avatar
hjk committed
193 194
        return;
    }
195
    notifyEngineSetupOk();
hjk's avatar
hjk committed
196 197 198 199
}

void PdbEngine::setupInferior()
{
hjk's avatar
hjk committed
200
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
hjk's avatar
hjk committed
201

202 203 204 205 206 207 208 209 210 211
    QString fileName = QFileInfo(startParameters().executable).absoluteFilePath();
    QFile scriptFile(fileName);
    if (!scriptFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
        showMessageBox(QMessageBox::Critical, tr("Python Error"),
            _("Cannot open script file %1:\n%2").
               arg(fileName, scriptFile.errorString()));
        notifyInferiorSetupFailed();
        return;
    }
    notifyInferiorSetupOk();
hjk's avatar
hjk committed
212 213
}

hjk's avatar
hjk committed
214
void PdbEngine::runEngine()
hjk's avatar
hjk committed
215
{
216
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
hjk's avatar
hjk committed
217
    showStatusMessage(tr("Running requested..."), 5000);
218
    const QByteArray dumperSourcePath =
hjk's avatar
hjk committed
219
        Core::ICore::resourcePath().toLocal8Bit() + "/dumper/";
220 221 222 223 224 225 226 227
    QString fileName = QFileInfo(startParameters().executable).absoluteFilePath();
    postDirectCommand("import sys");
    postDirectCommand("sys.argv.append('" + fileName.toLocal8Bit() + "')");
    postDirectCommand("execfile('/usr/bin/pdb')");
    postDirectCommand("execfile('" + dumperSourcePath + "pdumper.py')");
    attemptBreakpointSynchronization();
    notifyEngineRunAndInferiorStopOk();
    continueInferior();
hjk's avatar
hjk committed
228 229 230 231
}

void PdbEngine::interruptInferior()
{
232
    notifyInferiorStopOk();
hjk's avatar
hjk committed
233 234 235 236
}

void PdbEngine::executeStep()
{
237
    resetLocation();
238 239
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
240 241 242 243 244
    postCommand("step", CB(handleUpdateAll));
}

void PdbEngine::executeStepI()
{
245
    resetLocation();
246 247
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
248 249 250 251 252
    postCommand("step", CB(handleUpdateAll));
}

void PdbEngine::executeStepOut()
{
253
    resetLocation();
254 255
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
256 257 258 259 260
    postCommand("finish", CB(handleUpdateAll));
}

void PdbEngine::executeNext()
{
261
    resetLocation();
262 263
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
264 265 266 267 268
    postCommand("next", CB(handleUpdateAll));
}

void PdbEngine::executeNextI()
{
269
    resetLocation();
270 271
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
272 273 274 275 276
    postCommand("next", CB(handleUpdateAll));
}

void PdbEngine::continueInferior()
{
277
    resetLocation();
278 279
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
280 281 282 283
    // Callback will be triggered e.g. when breakpoint is hit.
    postCommand("continue", CB(handleUpdateAll));
}

284
void PdbEngine::executeRunToLine(const ContextData &data)
hjk's avatar
hjk committed
285
{
286
    Q_UNUSED(data)
hjk's avatar
hjk committed
287 288 289 290 291 292 293 294 295
    SDEBUG("FIXME:  PdbEngine::runToLineExec()");
}

void PdbEngine::executeRunToFunction(const QString &functionName)
{
    Q_UNUSED(functionName)
    XSDEBUG("FIXME:  PdbEngine::runToFunctionExec()");
}

296
void PdbEngine::executeJumpToLine(const ContextData &data)
hjk's avatar
hjk committed
297
{
298
    Q_UNUSED(data)
hjk's avatar
hjk committed
299 300 301 302 303
    XSDEBUG("FIXME:  PdbEngine::jumpToLineExec()");
}

void PdbEngine::activateFrame(int frameIndex)
{
304
    resetLocation();
hjk's avatar
hjk committed
305
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
hjk's avatar
hjk committed
306 307
        return;

308 309
    StackHandler *handler = stackHandler();
    int oldIndex = handler->currentIndex();
hjk's avatar
hjk committed
310

311
    //if (frameIndex == handler->stackSize()) {
hjk's avatar
hjk committed
312 313 314 315
    //    reloadFullStack();
    //    return;
    //}

316
    QTC_ASSERT(frameIndex < handler->stackSize(), return);
hjk's avatar
hjk committed
317 318 319 320 321

    if (oldIndex != frameIndex) {
        // Assuming the command always succeeds this saves a roundtrip.
        // Otherwise the lines below would need to get triggered
        // after a response to this -stack-select-frame here.
322
        handler->setCurrentIndex(frameIndex);
hjk's avatar
hjk committed
323 324 325
        //postCommand("-stack-select-frame " + QByteArray::number(frameIndex),
        //    CB(handleStackSelectFrame));
    }
326
    gotoLocation(handler->currentFrame());
hjk's avatar
hjk committed
327 328 329 330 331 332 333
}

void PdbEngine::selectThread(int index)
{
    Q_UNUSED(index)
}

334
bool PdbEngine::acceptsBreakpoint(BreakpointModelId id) const
hjk's avatar
hjk committed
335 336 337 338 339
{
    const QString fileName = breakHandler()->fileName(id);
    return fileName.endsWith(QLatin1String(".py"));
}

340
void PdbEngine::insertBreakpoint(BreakpointModelId id)
hjk's avatar
hjk committed
341
{
342
    BreakHandler *handler = breakHandler();
343
    QTC_CHECK(handler->state(id) == BreakpointInsertRequested);
hjk's avatar
hjk committed
344 345 346 347 348 349 350 351 352 353
    handler->notifyBreakpointInsertProceeding(id);

    QByteArray loc;
    if (handler->type(id) == BreakpointByFunction)
        loc = handler->functionName(id).toLatin1();
    else
        loc = handler->fileName(id).toLocal8Bit() + ':'
         + QByteArray::number(handler->lineNumber(id));

    postCommand("break " + loc, CB(handleBreakInsert), QVariant(id));
hjk's avatar
hjk committed
354 355 356 357 358 359
}

void PdbEngine::handleBreakInsert(const PdbResponse &response)
{
    //qDebug() << "BP RESPONSE: " << response.data;
    // "Breakpoint 1 at /pdb/math.py:10"
360
    BreakpointModelId id(response.cookie.toInt());
361
    BreakHandler *handler = breakHandler();
hjk's avatar
hjk committed
362 363 364 365 366 367 368
    QTC_ASSERT(response.data.startsWith("Breakpoint "), return);
    int pos1 = response.data.indexOf(" at ");
    QTC_ASSERT(pos1 != -1, return);
    QByteArray bpnr = response.data.mid(11, pos1 - 11);
    int pos2 = response.data.lastIndexOf(":");
    QByteArray file = response.data.mid(pos1 + 4, pos2 - pos1 - 4);
    QByteArray line = response.data.mid(pos2 + 1);
hjk's avatar
hjk committed
369
    BreakpointResponse br;
370
    br.id = BreakpointResponseId(bpnr);
371 372
    br.fileName = _(file);
    br.lineNumber = line.toInt();
hjk's avatar
hjk committed
373
    handler->setResponse(id, br);
hjk's avatar
hjk committed
374 375
    QTC_CHECK(!handler->needsChange(id));
    handler->notifyBreakpointInsertOk(id);
hjk's avatar
hjk committed
376 377
}

378
void PdbEngine::removeBreakpoint(BreakpointModelId id)
hjk's avatar
hjk committed
379 380
{
    BreakHandler *handler = breakHandler();
381
    QTC_CHECK(handler->state(id) == BreakpointRemoveRequested);
hjk's avatar
hjk committed
382 383
    handler->notifyBreakpointRemoveProceeding(id);
    BreakpointResponse br = handler->response(id);
384
    showMessage(_("DELETING BP %1 IN %2").arg(br.id.toString())
hjk's avatar
hjk committed
385
        .arg(handler->fileName(id)));
386
    postCommand("clear " + br.id.toByteArray());
hjk's avatar
hjk committed
387 388 389 390
    // Pretend it succeeds without waiting for response.
    handler->notifyBreakpointRemoveOk(id);
}

hjk's avatar
hjk committed
391 392 393 394 395 396 397 398 399 400 401
void PdbEngine::loadSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void PdbEngine::loadAllSymbols()
{
}

void PdbEngine::reloadModules()
{
402
    //postCommand("qdebug('listmodules')", CB(handleListModules));
hjk's avatar
hjk committed
403 404 405 406 407 408
}

void PdbEngine::handleListModules(const PdbResponse &response)
{
    GdbMi out;
    out.fromString(response.data.trimmed());
409
    Modules modules;
hjk's avatar
hjk committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    foreach (const GdbMi &item, out.children()) {
        Module module;
        module.moduleName = _(item.findChild("name").data());
        QString path = _(item.findChild("value").data());
        int pos = path.indexOf(_("' from '"));
        if (pos != -1) {
            path = path.mid(pos + 8);
            if (path.size() >= 2)
                path.chop(2);
        } else if (path.startsWith(_("<module '"))
                && path.endsWith(_("' (built-in)>"))) {
            path = _("(builtin)");
        }
        module.modulePath = path;
        modules.append(module);
    }
426
    modulesHandler()->setModules(modules);
hjk's avatar
hjk committed
427 428
}

hjk's avatar
hjk committed
429
void PdbEngine::requestModuleSymbols(const QString &moduleName)
hjk's avatar
hjk committed
430
{
hjk's avatar
hjk committed
431 432
    postCommand("qdebug('listsymbols','" + moduleName.toLatin1() + "')",
        CB(handleListSymbols), moduleName);
hjk's avatar
hjk committed
433 434
}

hjk's avatar
hjk committed
435 436 437 438
void PdbEngine::handleListSymbols(const PdbResponse &response)
{
    GdbMi out;
    out.fromString(response.data.trimmed());
439
    Symbols symbols;
hjk's avatar
hjk committed
440 441 442 443 444 445
    QString moduleName = response.cookie.toString();
    foreach (const GdbMi &item, out.children()) {
        Symbol symbol;
        symbol.name = _(item.findChild("name").data());
        symbols.append(symbol);
    }
hjk's avatar
hjk committed
446
   debuggerCore()->showModuleSymbols(moduleName, symbols);
hjk's avatar
hjk committed
447
}
hjk's avatar
hjk committed
448 449 450 451 452 453 454 455 456 457 458 459

//////////////////////////////////////////////////////////////////////
//
// Tooltip specific stuff
//
//////////////////////////////////////////////////////////////////////


static WatchData m_toolTip;
static QPoint m_toolTipPos;
static QHash<QString, WatchData> m_toolTipCache;

460
bool PdbEngine::setToolTipExpression(const QPoint &mousePos,
461
    TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
hjk's avatar
hjk committed
462 463 464 465
{
    Q_UNUSED(mousePos)
    Q_UNUSED(editor)

hjk's avatar
hjk committed
466
    if (state() != InferiorStopOk) {
hjk's avatar
hjk committed
467
        //SDEBUG("SUPPRESSING DEBUGGER TOOLTIP, INFERIOR NOT STOPPED");
468
        return false;
hjk's avatar
hjk committed
469 470 471 472
    }
    // Check mime type and get expression (borrowing some C++ - functions)
    const QString javaPythonMimeType =
        QLatin1String("application/javascript");
473
    if (!editor->document() || editor->document()->mimeType() != javaPythonMimeType)
474
        return false;
hjk's avatar
hjk committed
475 476 477

    int line;
    int column;
478
    QString exp = cppExpressionAt(editor, ctx.position, &line, &column);
hjk's avatar
hjk committed
479 480 481 482 483 484 485 486 487 488 489 490 491

/*
    if (m_toolTipCache.contains(exp)) {
        const WatchData & data = m_toolTipCache[exp];
        q->watchHandler()->removeChildren(data.iname);
        insertData(data);
        return;
    }
*/

    QToolTip::hideText();
    if (exp.isEmpty() || exp.startsWith(QLatin1Char('#')))  {
        QToolTip::hideText();
492
        return false;
hjk's avatar
hjk committed
493 494 495 496
    }

    if (!hasLetterOrNumber(exp)) {
        QToolTip::showText(m_toolTipPos, tr("'%1' contains no identifier").arg(exp));
497
        return true;
hjk's avatar
hjk committed
498 499 500 501
    }

    if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"'))) {
        QToolTip::showText(m_toolTipPos, tr("String literal %1").arg(exp));
502
        return true;
hjk's avatar
hjk committed
503 504 505 506 507 508 509 510 511
    }

    if (exp.startsWith(QLatin1String("++")) || exp.startsWith(QLatin1String("--")))
        exp.remove(0, 2);

    if (exp.endsWith(QLatin1String("++")) || exp.endsWith(QLatin1String("--")))
        exp.remove(0, 2);

    if (exp.startsWith(QLatin1Char('<')) || exp.startsWith(QLatin1Char('[')))
512
        return false;
hjk's avatar
hjk committed
513 514 515 516 517

    if (hasSideEffects(exp)) {
        QToolTip::showText(m_toolTipPos,
            tr("Cowardly refusing to evaluate expression '%1' "
               "with potential side effects").arg(exp));
518
        return true;
hjk's avatar
hjk committed
519 520 521
    }

#if 0
hjk's avatar
hjk committed
522
    //if (status() != InferiorStopOk)
hjk's avatar
hjk committed
523 524 525 526 527 528 529 530 531
    //    return;

    // FIXME: 'exp' can contain illegal characters
    m_toolTip = WatchData();
    m_toolTip.exp = exp;
    m_toolTip.name = exp;
    m_toolTip.iname = tooltipIName;
    insertData(m_toolTip);
#endif
532
    return false;
hjk's avatar
hjk committed
533 534 535 536 537 538 539 540 541
}


//////////////////////////////////////////////////////////////////////
//
// Watch specific stuff
//
//////////////////////////////////////////////////////////////////////

542
void PdbEngine::assignValueInDebugger(const Internal::WatchData *, const QString &expression, const QVariant &value)
hjk's avatar
hjk committed
543 544 545
{
    Q_UNUSED(expression);
    Q_UNUSED(value);
546
    SDEBUG("ASSIGNING: " << (expression + QLatin1Char('=') + value.toString()));
hjk's avatar
hjk committed
547
#if 0
548
    m_scriptEngine->evaluate(expression + QLatin1Char('=') + value.toString());
hjk's avatar
hjk committed
549 550 551 552 553
    updateLocals();
#endif
}


554
void PdbEngine::updateWatchData(const WatchData &data, const WatchUpdateFlags &flags)
hjk's avatar
hjk committed
555 556
{
    Q_UNUSED(data);
hjk's avatar
hjk committed
557
    Q_UNUSED(flags);
hjk's avatar
hjk committed
558 559 560 561 562
    updateAll();
}

void PdbEngine::handlePdbError(QProcess::ProcessError error)
{
563
    qDebug() << "HANDLE PDB ERROR";
564
    showMessage(_("HANDLE PDB ERROR"));
hjk's avatar
hjk committed
565 566 567 568 569 570 571 572
    switch (error) {
    case QProcess::Crashed:
        break; // will get a processExited() as well
    // impossible case QProcess::FailedToStart:
    case QProcess::ReadError:
    case QProcess::WriteError:
    case QProcess::Timedout:
    default:
573
        //setState(EngineShutdownRequested, true);
hjk's avatar
hjk committed
574
        m_pdbProc.kill();
575
        showMessageBox(QMessageBox::Critical, tr("Pdb I/O Error"),
hjk's avatar
hjk committed
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
                       errorMessage(error));
        break;
    }
}

QString PdbEngine::errorMessage(QProcess::ProcessError error) const
{
    switch (error) {
        case QProcess::FailedToStart:
            return tr("The Pdb process failed to start. Either the "
                "invoked program '%1' is missing, or you may have insufficient "
                "permissions to invoke the program.")
                .arg(m_pdb);
        case QProcess::Crashed:
            return tr("The Pdb process crashed some time after starting "
                "successfully.");
        case QProcess::Timedout:
            return tr("The last waitFor...() function timed out. "
                "The state of QProcess is unchanged, and you can try calling "
                "waitFor...() again.");
        case QProcess::WriteError:
            return tr("An error occurred when attempting to write "
                "to the Pdb process. For example, the process may not be running, "
                "or it may have closed its input channel.");
        case QProcess::ReadError:
            return tr("An error occurred when attempting to read from "
                "the Pdb process. For example, the process may not be running.");
        default:
            return tr("An unknown error in the Pdb process occurred. ");
    }
}

void PdbEngine::handlePdbFinished(int code, QProcess::ExitStatus type)
{
610
    qDebug() << "PDB FINISHED";
611
    showMessage(_("PDB PROCESS FINISHED, status %1, code %2").arg(type).arg(code));
612
    notifyEngineSpontaneousShutdown();
hjk's avatar
hjk committed
613 614 615 616 617
}

void PdbEngine::readPdbStandardError()
{
    QByteArray err = m_pdbProc.readAllStandardError();
618 619 620 621
    qDebug() << "\nPDB STDERR" << err;
    //qWarning() << "Unexpected pdb stderr:" << err;
    //showMessage(_("Unexpected pdb stderr: " + err));
    //handleOutput(err);
hjk's avatar
hjk committed
622 623 624 625
}

void PdbEngine::readPdbStandardOutput()
{
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    QByteArray out = m_pdbProc.readAllStandardOutput();
    qDebug() << "\nPDB STDOUT" << out;
    handleOutput(out);
}

void PdbEngine::handleOutput(const QByteArray &data)
{
    //qDebug() << "READ: " << data;
    m_inbuffer.append(data);
    qDebug() << "BUFFER FROM: '" << m_inbuffer << "'";
    while (true) {
        int pos = m_inbuffer.indexOf("(Pdb)");
        if (pos == -1)
            pos = m_inbuffer.indexOf(">>>");
        if (pos == -1)
            break;
        QByteArray response = m_inbuffer.left(pos).trimmed();
hjk's avatar
hjk committed
643
        m_inbuffer = m_inbuffer.mid(pos + 6);
644 645 646 647 648 649 650 651 652 653 654 655
        emit outputReady(response);
    }
    qDebug() << "BUFFER LEFT: '" << m_inbuffer << "'";
    //m_inbuffer.clear();
}


void PdbEngine::handleOutput2(const QByteArray &data)
{
    PdbResponse response;
    response.data = data;
    showMessage(_(data));
656
    QTC_ASSERT(!m_commands.isEmpty(), qDebug() << "RESPONSE: " << data; return);
657 658 659 660 661 662 663 664 665
    PdbCommand cmd = m_commands.dequeue();
    response.cookie = cmd.cookie;
    qDebug() << "DEQUE: " << cmd.command << cmd.callbackName;
    if (cmd.callback) {
        //qDebug() << "EXECUTING CALLBACK " << cmd.callbackName
        //    << " RESPONSE: " << response.data;
        (this->*cmd.callback)(response);
    } else {
        qDebug() << "NO CALLBACK FOR RESPONSE: " << response.data;
hjk's avatar
hjk committed
666 667
    }
}
668
/*
hjk's avatar
hjk committed
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
void PdbEngine::handleResponse(const QByteArray &response0)
{
    QByteArray response = response0;
    qDebug() << "RESPONSE: '" << response << "'";
    if (response.startsWith("--Call--")) {
        qDebug() << "SKIPPING '--Call--' MARKER";
        response = response.mid(9);
    }
    if (response.startsWith("--Return--")) {
        qDebug() << "SKIPPING '--Return--' MARKER";
        response = response.mid(11);
    }
    if (response.startsWith("> ")) {
        int pos1 = response.indexOf('(');
        int pos2 = response.indexOf(')', pos1);
        if (pos1 != -1 && pos2 != -1) {
            int lineNumber = response.mid(pos1 + 1, pos2 - pos1 - 1).toInt();
            QByteArray fileName = response.mid(2, pos1 - 2);
687
            qDebug() << " " << pos1 << pos2 << lineNumber << fileName
hjk's avatar
hjk committed
688 689 690 691 692
                << response.mid(pos1 + 1, pos2 - pos1 - 1);
            StackFrame frame;
            frame.file = _(fileName);
            frame.line = lineNumber;
            if (frame.line > 0 && QFileInfo(frame.file).exists()) {
693
                gotoLocation(frame);
694
                notifyInferiorSpontaneousStop();
hjk's avatar
hjk committed
695 696 697 698 699 700
                return;
            }
        }
    }
    qDebug() << "COULD NOT PARSE RESPONSE: '" << response << "'";
}
701
*/
hjk's avatar
hjk committed
702

hjk's avatar
hjk committed
703 704 705 706 707
void PdbEngine::handleFirstCommand(const PdbResponse &response)
{
    Q_UNUSED(response);
}

hjk's avatar
hjk committed
708 709 710
void PdbEngine::handleUpdateAll(const PdbResponse &response)
{
    Q_UNUSED(response);
711
    notifyInferiorSpontaneousStop();
hjk's avatar
hjk committed
712 713 714 715
    updateAll();
}

void PdbEngine::updateAll()
716 717 718 719 720 721
{
    postCommand("bt", CB(handleBacktrace));
    //updateLocals();
}

void PdbEngine::updateLocals()
hjk's avatar
hjk committed
722
{
723
    WatchHandler *handler = watchHandler();
hjk's avatar
hjk committed
724
    handler->beginCycle(true);
hjk's avatar
hjk committed
725 726 727 728 729 730 731 732 733 734 735 736

    QByteArray watchers;
    //if (!m_toolTipExpression.isEmpty())
    //    watchers += m_toolTipExpression.toLatin1()
    //        + '#' + tooltipINameForExpression(m_toolTipExpression.toLatin1());

    QHash<QByteArray, int> watcherNames = handler->watcherNames();
    QHashIterator<QByteArray, int> it(watcherNames);
    while (it.hasNext()) {
        it.next();
        if (!watchers.isEmpty())
            watchers += "##";
737
        watchers += it.key() + "#watch." + QByteArray::number(it.value());
hjk's avatar
hjk committed
738 739 740
    }

    QByteArray options;
hjk's avatar
hjk committed
741
    if (debuggerCore()->boolSetting(UseDebuggingHelpers))
hjk's avatar
hjk committed
742
        options += "fancy,";
hjk's avatar
hjk committed
743
    if (debuggerCore()->boolSetting(AutoDerefPointers))
hjk's avatar
hjk committed
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
        options += "autoderef,";
    if (options.isEmpty())
        options += "defaults,";
    options.chop(1);

    postCommand("qdebug('" + options + "','"
        + handler->expansionRequests() + "','"
        + handler->typeFormatRequests() + "','"
        + handler->individualFormatRequests() + "','"
        + watchers.toHex() + "')", CB(handleListLocals));
}

void PdbEngine::handleBacktrace(const PdbResponse &response)
{
    //qDebug() << " BACKTRACE: '" << response.data << "'";
    // "  /usr/lib/python2.6/bdb.py(368)run()"
    // "-> exec cmd in globals, locals"
    // "  <string>(1)<module>()"
    // "  /python/math.py(19)<module>()"
    // "-> main()"
    // "  /python/math.py(14)main()"
    // "-> print cube(3)"
    // "  /python/math.py(7)cube()"
    // "-> x = square(a)"
    // "> /python/math.py(2)square()"
    // "-> def square(a):"

    // Populate stack view.
772
    StackFrames stackFrames;
hjk's avatar
hjk committed
773 774 775 776 777 778 779 780 781 782
    int level = 0;
    int currentIndex = -1;
    foreach (const QByteArray &line, response.data.split('\n')) {
        //qDebug() << "  LINE: '" << line << "'";
        if (line.startsWith("> ") || line.startsWith("  ")) {
            int pos1 = line.indexOf('(');
            int pos2 = line.indexOf(')', pos1);
            if (pos1 != -1 && pos2 != -1) {
                int lineNumber = line.mid(pos1 + 1, pos2 - pos1 - 1).toInt();
                QByteArray fileName = line.mid(2, pos1 - 2);
783
                //qDebug() << " " << pos1 << pos2 << lineNumber << fileName
hjk's avatar
hjk committed
784 785 786 787 788
                //    << line.mid(pos1 + 1, pos2 - pos1 - 1);
                StackFrame frame;
                frame.file = _(fileName);
                frame.line = lineNumber;
                frame.function = _(line.mid(pos2 + 1));
hjk's avatar
hjk committed
789
                frame.usable = QFileInfo(frame.file).isReadable();
hjk's avatar
hjk committed
790 791 792 793 794 795 796 797 798 799 800
                if (frame.line > 0 && QFileInfo(frame.file).exists()) {
                    if (line.startsWith("> "))
                        currentIndex = level;
                    frame.level = level;
                    stackFrames.prepend(frame);
                    ++level;
                }
            }
        }
    }
    const int frameCount = stackFrames.size();
801 802
    for (int i = 0; i != frameCount; ++i)
        stackFrames[i].level = frameCount - stackFrames[i].level - 1;
803
    stackHandler()->setFrames(stackFrames);
hjk's avatar
hjk committed
804 805 806 807

    // Select current frame.
    if (currentIndex != -1) {
        currentIndex = frameCount - currentIndex - 1;
808
        stackHandler()->setCurrentIndex(currentIndex);
809
        gotoLocation(stackFrames.at(currentIndex));
hjk's avatar
hjk committed
810
    }
811 812

    updateLocals();
hjk's avatar
hjk committed
813 814 815 816 817 818 819 820 821 822 823 824 825
}

void PdbEngine::handleListLocals(const PdbResponse &response)
{
    //qDebug() << " LOCALS: '" << response.data << "'";
    QByteArray out = response.data.trimmed();

    GdbMi all;
    all.fromStringMultiple(out);
    //qDebug() << "ALL: " << all.toString();

    //GdbMi data = all.findChild("data");
    QList<WatchData> list;
826
    WatchHandler *handler = watchHandler();
hjk's avatar
hjk committed
827 828 829 830 831
    foreach (const GdbMi &child, all.children()) {
        WatchData dummy;
        dummy.iname = child.findChild("iname").data();
        dummy.name = _(child.findChild("name").data());
        //qDebug() << "CHILD: " << child.toString();
832
        parseWatchData(handler->expandedINames(), dummy, child, &list);
hjk's avatar
hjk committed
833
    }
834
    handler->insertBulkData(list);
hjk's avatar
hjk committed
835
    handler->endCycle();
hjk's avatar
hjk committed
836 837
}

838
bool PdbEngine::hasCapability(unsigned cap) const
hjk's avatar
hjk committed
839
{
840
    return cap & (ReloadModuleCapability|BreakConditionCapability);
hjk's avatar
hjk committed
841 842
}

843
DebuggerEngine *createPdbEngine(const DebuggerStartParameters &startParameters)
hjk's avatar
hjk committed
844
{
845
    return new PdbEngine(startParameters);
hjk's avatar
hjk committed
846 847 848 849 850
}


} // namespace Internal
} // namespace Debugger