debuggerruncontrol.cpp 33.5 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
con's avatar
con committed
23
**
hjk's avatar
hjk committed
24
****************************************************************************/
hjk's avatar
hjk committed
25

26
#include "debuggerruncontrol.h"
con's avatar
con committed
27

28
#include "analyzer/analyzermanager.h"
29
#include "console/console.h"
30
#include "debuggeractions.h"
31
#include "debuggercore.h"
32 33
#include "debuggerengine.h"
#include "debuggerkitinformation.h"
34
#include "debuggerplugin.h"
35
#include "debuggerrunconfigurationaspect.h"
36
#include "breakhandler.h"
37
#include "shared/peutils.h"
Friedemann Kleint's avatar
Friedemann Kleint committed
38

hjk's avatar
hjk committed
39
#include <projectexplorer/buildconfiguration.h>
40 41 42
#include <projectexplorer/devicesupport/deviceprocessesdialog.h>
#include <projectexplorer/devicesupport/deviceprocesslist.h>
#include <projectexplorer/environmentaspect.h> // For the environment
con's avatar
con committed
43
#include <projectexplorer/project.h>
hjk's avatar
hjk committed
44
#include <projectexplorer/projectexplorer.h>
45
#include <projectexplorer/projectexplorericons.h>
46
#include <projectexplorer/runnables.h>
47
#include <projectexplorer/session.h>
Tobias Hunger's avatar
Tobias Hunger committed
48
#include <projectexplorer/target.h>
49
#include <projectexplorer/taskhub.h>
50
#include <projectexplorer/toolchain.h>
con's avatar
con committed
51

Kai Koehne's avatar
Kai Koehne committed
52
#include <utils/checkablemessagebox.h>
Orgad Shaneh's avatar
Orgad Shaneh committed
53
#include <utils/fileutils.h>
54
#include <utils/portlist.h>
hjk's avatar
hjk committed
55
#include <utils/qtcassert.h>
56
#include <utils/qtcprocess.h>
57

58
#include <coreplugin/icore.h>
59
#include <coreplugin/coreconstants.h>
60
#include <coreplugin/messagebox.h>
61
#include <qmldebug/qmldebugcommandlinearguments.h>
hjk's avatar
hjk committed
62

63 64
#include <qtsupport/qtkitinformation.h>

65 66
#include <ssh/sshconnection.h>

67
#include <QTcpServer>
con's avatar
con committed
68

69
using namespace Debugger::Internal;
hjk's avatar
hjk committed
70 71
using namespace ProjectExplorer;
using namespace Utils;
72

73 74
enum { debug = 0 };

75
namespace Debugger {
76
namespace Internal {
77

78 79 80 81 82 83
DebuggerEngine *createCdbEngine(QStringList *error, DebuggerStartMode sm);
DebuggerEngine *createGdbEngine(bool useTerminal, DebuggerStartMode sm);
DebuggerEngine *createPdbEngine();
DebuggerEngine *createQmlEngine(bool useTerminal);
DebuggerEngine *createQmlCppEngine(DebuggerEngine *cppEngine, bool useTerminal);
DebuggerEngine *createLldbEngine();
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
class LocalProcessRunner : public RunWorker
{
public:
    LocalProcessRunner(RunControl *runControl, const StandardRunnable &runnable)
        : RunWorker(runControl), m_runnable(runnable)
    {
        connect(&m_proc, &QProcess::errorOccurred,
                this, &LocalProcessRunner::handleError);
        connect(&m_proc, &QProcess::readyReadStandardOutput,
                this, &LocalProcessRunner::handleStandardOutput);
        connect(&m_proc, &QProcess::readyReadStandardError,
                this, &LocalProcessRunner::handleStandardError);
        connect(&m_proc, static_cast<void (QProcess::*)(int)>(&QProcess::finished),
                this, &LocalProcessRunner::handleFinished);
    }

    void start() override
    {
        m_proc.setCommand(m_runnable.executable, m_runnable.commandLineArguments);
        m_proc.start();
    }

    void stop() override
    {
        m_proc.terminate();
    }

    void handleStandardOutput()
    {
        const QByteArray ba = m_proc.readAllStandardOutput();
        const QString msg = QString::fromLocal8Bit(ba, ba.length());
        showMessage(msg, LogOutput);
        showMessage(msg, AppOutput);
    }

    void handleStandardError()
    {
        const QByteArray ba = m_proc.readAllStandardError();
        const QString msg = QString::fromLocal8Bit(ba, ba.length());
        showMessage(msg, LogOutput);
        showMessage(msg, AppError);
    }

    void handleFinished()
    {
        if (m_proc.exitStatus() == QProcess::NormalExit && m_proc.exitCode() == 0) {
            // all good.
            reportDone();
        } else {
            reportFailure(tr("Upload failed: %1").arg(m_proc.errorString()));
        }
    }

    void handleError(QProcess::ProcessError error)
    {
        QString msg;
        switch (error) {
        case QProcess::FailedToStart:
            msg = tr("The upload process failed to start. Shell missing?");
            break;
        case QProcess::Crashed:
            msg = tr("The upload process crashed some time after starting "
                     "successfully.");
            break;
        case QProcess::Timedout:
            msg = tr("The last waitFor...() function timed out. "
                     "The state of QProcess is unchanged, and you can try calling "
                     "waitFor...() again.");
            break;
        case QProcess::WriteError:
            msg = tr("An error occurred when attempting to write "
                     "to the upload process. For example, the process may not be running, "
                     "or it may have closed its input channel.");
            break;
        case QProcess::ReadError:
            msg = tr("An error occurred when attempting to read from "
                     "the upload process. For example, the process may not be running.");
            break;
        default:
            msg = tr("An unknown error in the upload process occurred. "
                     "This is the default return value of error().");
        }

        showMessage(msg, StatusBar);
        Core::AsynchronousMessageBox::critical(tr("Error"), msg);
    }

    StandardRunnable m_runnable;
    Utils::QtcProcess m_proc;
};

176 177
} // namespace Internal

178

179 180 181 182 183 184 185
static bool breakOnMainNextTime = false;

void DebuggerRunTool::setBreakOnMainNextTime()
{
    breakOnMainNextTime = true;
}

186 187
void DebuggerRunTool::setStartMode(DebuggerStartMode startMode)
{
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    if (startMode == AttachToQmlServer) {
        m_runParameters.startMode = AttachToRemoteProcess;
        m_runParameters.languages = QmlLanguage;
        m_runParameters.masterEngineType = QmlEngineType;
        m_runParameters.closeMode = KillAtClose;

        // FIXME: This is horribly wrong.
        // get files from all the projects in the session
        QList<Project *> projects = SessionManager::projects();
        if (Project *startupProject = SessionManager::startupProject()) {
            // startup project first
            projects.removeOne(startupProject);
            projects.insert(0, startupProject);
        }
        foreach (Project *project, projects)
            m_runParameters.projectSourceFiles.append(project->files(Project::SourceFiles));
        if (!projects.isEmpty())
            m_runParameters.projectSourceDirectory = projects.first()->projectDirectory().toString();

    } else {
        m_runParameters.startMode = startMode;
    }
210 211 212 213 214 215 216
}

void DebuggerRunTool::setCloseMode(DebuggerCloseMode closeMode)
{
    m_runParameters.closeMode = closeMode;
}

217 218 219 220 221
void DebuggerRunTool::setAttachPid(ProcessHandle pid)
{
    m_runParameters.attachPID = pid;
}

222 223 224 225 226
void DebuggerRunTool::setAttachPid(qint64 pid)
{
    m_runParameters.attachPID = ProcessHandle(pid);
}

227 228 229 230 231
void DebuggerRunTool::setSysRoot(const QString &sysRoot)
{
    m_runParameters.sysRoot = sysRoot;
}

232 233 234 235 236 237 238
void DebuggerRunTool::setSymbolFile(const QString &symbolFile)
{
    if (symbolFile.isEmpty())
        reportFailure(tr("Cannot debug: Local executable is not set."));
    m_runParameters.symbolFile = symbolFile;
}

239
void DebuggerRunTool::setRemoteChannel(const QString &channel)
240 241 242 243
{
    m_runParameters.remoteChannel = channel;
}

244 245 246 247 248
void DebuggerRunTool::setRemoteChannel(const QString &host, int port)
{
    m_runParameters.remoteChannel = QString("%1:%2").arg(host).arg(port);
}

249 250 251 252 253
void DebuggerRunTool::setUseExtendedRemote(bool on)
{
    m_runParameters.useExtendedRemote = on;
}

254 255 256 257 258 259 260 261 262 263
void DebuggerRunTool::setUseContinueInsteadOfRun(bool on)
{
    m_runParameters.useContinueInsteadOfRun = on;
}

void DebuggerRunTool::setUseTargetAsync(bool on)
{
    m_runParameters.useTargetAsync = on;
}

264 265 266 267 268
void DebuggerRunTool::setContinueAfterAttach(bool on)
{
    m_runParameters.continueAfterAttach = on;
}

269 270 271 272 273
void DebuggerRunTool::setSkipExecutableValidation(bool on)
{
    m_runParameters.skipExecutableValidation = on;
}

274 275 276 277 278
void DebuggerRunTool::setUseCtrlCStub(bool on)
{
    m_runParameters.useCtrlCStub = on;
}

279 280 281 282 283 284 285 286 287 288
void DebuggerRunTool::setBreakOnMain(bool on)
{
    m_runParameters.breakOnMain = on;
}

void DebuggerRunTool::setUseTerminal(bool on)
{
    m_runParameters.useTerminal = on;
}

289 290 291 292 293 294 295 296 297 298
void DebuggerRunTool::setCommandsAfterConnect(const QString &commands)
{
    m_runParameters.commandsAfterConnect = commands;
}

void DebuggerRunTool::setCommandsForReset(const QString &commands)
{
    m_runParameters.commandsForReset = commands;
}

299 300
void DebuggerRunTool::setServerStartScript(const QString &serverStartScript)
{
301 302 303 304 305 306 307 308
    if (!serverStartScript.isEmpty()) {
        // Provide script information about the environment
        StandardRunnable serverStarter;
        serverStarter.executable = serverStartScript;
        QtcProcess::addArg(&serverStarter.commandLineArguments, m_runParameters.inferior.executable);
        QtcProcess::addArg(&serverStarter.commandLineArguments, m_runParameters.remoteChannel);
        addStartDependency(new LocalProcessRunner(runControl(), serverStarter));
    }
309 310 311 312 313 314 315
}

void DebuggerRunTool::setDebugInfoLocation(const QString &debugInfoLocation)
{
    m_runParameters.debugInfoLocation = debugInfoLocation;
}

316 317 318 319 320
void DebuggerRunTool::setQmlServer(const QUrl &qmlServer)
{
    m_runParameters.qmlServer = qmlServer;
}

321 322 323 324 325 326 327 328 329 330
void DebuggerRunTool::setIosPlatform(const QString &platform)
{
    m_runParameters.platform = platform;
}

void DebuggerRunTool::setDeviceSymbolsRoot(const QString &deviceSymbolsRoot)
{
    m_runParameters.deviceSymbolsRoot = deviceSymbolsRoot;
}

331 332 333 334 335
void DebuggerRunTool::setTestCase(int testCase)
{
    m_runParameters.testCase = testCase;
}

336 337 338 339 340 341 342 343 344 345
void DebuggerRunTool::setOverrideStartScript(const QString &script)
{
    m_runParameters.overrideStartScript = script;
}

void DebuggerRunTool::setToolChainAbi(const Abi &abi)
{
    m_runParameters.toolChainAbi = abi;
}

346 347 348 349 350 351
void DebuggerRunTool::setInferior(const Runnable &runnable)
{
    QTC_ASSERT(runnable.is<StandardRunnable>(), reportFailure(); return);
    m_runParameters.inferior = runnable.as<StandardRunnable>();
}

352 353 354 355 356
void DebuggerRunTool::setInferiorExecutable(const QString &executable)
{
    m_runParameters.inferior.executable = executable;
}

357 358 359 360 361
void DebuggerRunTool::setRunControlName(const QString &name)
{
    m_runParameters.displayName = name;
}

362 363 364 365 366 367 368 369 370 371 372
void DebuggerRunTool::setStartMessage(const QString &msg)
{
    m_runParameters.startMessage = msg;
}

void DebuggerRunTool::setCoreFileName(const QString &coreFile, bool isSnapshot)
{
    m_runParameters.coreFile = coreFile;
    m_runParameters.isSnapshot = isSnapshot;
}

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
void DebuggerRunTool::appendInferiorCommandLineArgument(const QString &arg)
{
    if (!m_runParameters.inferior.commandLineArguments.isEmpty())
        m_runParameters.inferior.commandLineArguments.append(' ');
    m_runParameters.inferior.commandLineArguments.append(arg);
}

void DebuggerRunTool::prependInferiorCommandLineArgument(const QString &arg)
{
    if (!m_runParameters.inferior.commandLineArguments.isEmpty())
        m_runParameters.inferior.commandLineArguments.prepend(' ');
    m_runParameters.inferior.commandLineArguments.prepend(arg);
}

void DebuggerRunTool::addQmlServerInferiorCommandLineArgumentIfNeeded()
{
    if (isQmlDebugging() && isCppDebugging()) {
        using namespace QmlDebug;
        int qmlServerPort = m_runParameters.qmlServer.port();
        QTC_ASSERT(qmlServerPort > 0, reportFailure(); return);
        QString mode = QString("port:%1").arg(qmlServerPort);
        QString qmlServerArg = qmlDebugCommandLineArguments(QmlDebuggerServices, mode, true);
        prependInferiorCommandLineArgument(qmlServerArg);
    }
}

399 400 401 402 403 404 405 406 407 408
void DebuggerRunTool::setMasterEngineType(DebuggerEngineType engineType)
{
    m_runParameters.masterEngineType = engineType;
}

void DebuggerRunTool::setCrashParameter(const QString &event)
{
    m_runParameters.crashParameter = event;
}

409 410 411 412 413 414 415 416 417 418
void DebuggerRunTool::addExpectedSignal(const QString &signal)
{
    m_runParameters.expectedSignals.append(signal);
}

void DebuggerRunTool::addSearchDirectory(const QString &dir)
{
    m_runParameters.additionalSearchDirectories.append(dir);
}

hjk's avatar
hjk committed
419
static QLatin1String engineTypeName(DebuggerEngineType et)
420 421 422 423 424
{
    switch (et) {
    case Debugger::NoEngineType:
        break;
    case Debugger::GdbEngineType:
hjk's avatar
hjk committed
425
        return QLatin1String("Gdb engine");
426
    case Debugger::CdbEngineType:
hjk's avatar
hjk committed
427
        return QLatin1String("Cdb engine");
428
    case Debugger::PdbEngineType:
hjk's avatar
hjk committed
429
        return QLatin1String("Pdb engine");
430
    case Debugger::QmlEngineType:
hjk's avatar
hjk committed
431
        return QLatin1String("QML engine");
432
    case Debugger::QmlCppEngineType:
hjk's avatar
hjk committed
433
        return QLatin1String("QML C++ engine");
434
    case Debugger::LldbEngineType:
hjk's avatar
hjk committed
435
        return QLatin1String("LLDB command line engine");
436 437 438
    case Debugger::AllEngineTypes:
        break;
    }
hjk's avatar
hjk committed
439
    return QLatin1String("No engine");
440 441
}

442
void DebuggerRunTool::start()
443
{
444
    Debugger::Internal::saveModeToRestore();
445
    Debugger::selectPerspective(Debugger::Constants::CppPerspectiveId);
446 447 448
    TaskHub::clearTasks(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO);
    TaskHub::clearTasks(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME);

449
    // User canceled input dialog asking for executable when working on library project.
450 451 452 453
    if (m_runParameters.startMode == StartInternal
            && m_runParameters.inferior.executable.isEmpty()
            && m_runParameters.interpreter.isEmpty()) {
        reportFailure(tr("No executable specified."));
454 455 456
        return;
    }

457 458 459 460 461 462 463 464 465 466
    // QML and/or mixed are not prepared for it.
    setSupportsReRunning(!(m_runParameters.languages & QmlLanguage));

    // FIXME: Disabled due to Android. Make Android device report available ports instead.
//    int portsUsed = portsUsedByDebugger();
//    if (portsUsed > device()->freePorts().count()) {
//        reportFailure(tr("Cannot debug: Not enough free ports available."));
//        return;
//    }

467
    if (!fixupParameters())
468 469 470 471 472 473 474 475 476 477
        return;

    Utils::globalMacroExpander()->registerFileVariables(
                "DebuggedExecutable", tr("Debugged executable"),
                [this] { return m_runParameters.inferior.executable; }
    );

    runControl()->setDisplayName(m_runParameters.displayName);

    DebuggerEngine *cppEngine = nullptr;
478

479 480 481 482
    switch (m_runParameters.cppEngineType) {
        case GdbEngineType:
            cppEngine = createGdbEngine(m_runParameters.useTerminal, m_runParameters.startMode);
            break;
483 484 485 486 487 488 489 490
        case CdbEngineType: {
            QStringList errors;
            cppEngine = createCdbEngine(&errors, m_runParameters.startMode);
            if (!errors.isEmpty()) {
                reportFailure(errors.join('\n'));
                return;
            }
            }
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
            break;
        case LldbEngineType:
            cppEngine = createLldbEngine();
            break;
        case PdbEngineType: // FIXME: Yes, Python counts as C++...
            cppEngine = createPdbEngine();
            break;
        default:
            QTC_CHECK(false);
            break;
    }

    switch (m_runParameters.masterEngineType) {
        case QmlEngineType:
            m_engine = createQmlEngine(m_runParameters.useTerminal);
            break;
        case QmlCppEngineType:
            if (cppEngine)
                m_engine = createQmlCppEngine(cppEngine, m_runParameters.useTerminal);
            break;
        default:
            m_engine = cppEngine;
            break;
    }

    if (!m_engine) {
517
        reportFailure(DebuggerPlugin::tr("Unable to create a debugging engine of the type \"%1\"").
518 519 520 521 522 523 524
                       arg(engineTypeName(m_runParameters.masterEngineType)));
        return;
    }

    m_engine->setRunTool(this);

    if (m_runParameters.startMode == StartInternal) {
525
        QStringList unhandledIds;
526
        foreach (Breakpoint bp, breakHandler()->allBreakpoints()) {
527
            if (bp.isEnabled() && !m_engine->acceptsBreakpoint(bp))
528
                unhandledIds.append(bp.id().toString());
529 530 531 532 533 534 535
        }
        if (!unhandledIds.isEmpty()) {
            QString warningMessage =
                    DebuggerPlugin::tr("Some breakpoints cannot be handled by the debugger "
                                       "languages currently active, and will be ignored.\n"
                                       "Affected are breakpoints %1")
                    .arg(unhandledIds.join(QLatin1String(", ")));
536

537
            Internal::showMessage(warningMessage, LogWarning);
538

539 540
            static bool checked = true;
            if (checked)
541
                CheckableMessageBox::information(Core::ICore::mainWindow(),
Kai Koehne's avatar
Kai Koehne committed
542 543 544 545
                                                 tr("Debugger"),
                                                 warningMessage,
                                                 tr("&Show this message again."),
                                                 &checked, QDialogButtonBox::Ok);
546 547 548
        }
    }

549
    appendMessage(tr("Debugging starts"), NormalMessageFormat);
550
    Internal::runControlStarted(this);
551
    m_engine->start();
552 553
}

554
void DebuggerRunTool::startFailed()
555
{
556
    appendMessage(tr("Debugging has failed"), NormalMessageFormat);
557
    m_engine->handleStartFailed();
558 559
}

hjk's avatar
hjk committed
560
void DebuggerRunTool::stop()
561
{
hjk's avatar
hjk committed
562
    m_isDying = true;
563
    QTC_ASSERT(m_engine, reportStopped(); return);
hjk's avatar
hjk committed
564
    m_engine->quitDebugger();
565 566
}

567
void DebuggerRunTool::debuggingFinished()
hjk's avatar
hjk committed
568
{
569
    appendMessage(tr("Debugging has finished"), NormalMessageFormat);
570
    Internal::runControlFinished(this);
571
    reportStopped();
hjk's avatar
hjk committed
572 573
}

574 575 576 577 578 579
DebuggerRunParameters &DebuggerRunTool::runParameters()
{
    return m_runParameters;
}

const DebuggerRunParameters &DebuggerRunTool::runParameters() const
hjk's avatar
hjk committed
580
{
581
    return m_runParameters;
hjk's avatar
hjk committed
582 583
}

584 585 586 587 588
int DebuggerRunTool::portsUsedByDebugger() const
{
    return isCppDebugging() + isQmlDebugging();
}

589 590 591 592 593
void DebuggerRunTool::setSolibSearchPath(const QStringList &list)
{
    m_runParameters.solibSearchPath = list;
}

594
void DebuggerRunTool::notifyInferiorIll()
hjk's avatar
hjk committed
595
{
596
    m_engine->notifyInferiorIll();
hjk's avatar
hjk committed
597 598
}

599
void DebuggerRunTool::notifyInferiorExited()
hjk's avatar
hjk committed
600
{
601
    m_engine->notifyInferiorExited();
hjk's avatar
hjk committed
602 603
}

604
void DebuggerRunTool::quitDebugger()
605
{
hjk's avatar
hjk committed
606
    m_isDying = true;
607 608 609 610 611 612
    m_engine->quitDebugger();
}

void DebuggerRunTool::abortDebugger()
{
    m_engine->abortDebugger();
613 614
}

615
bool DebuggerRunTool::fixupParameters()
hjk's avatar
hjk committed
616
{
617
    DebuggerRunParameters &rp = m_runParameters;
618 619
    if (rp.symbolFile.isEmpty())
        rp.symbolFile = rp.inferior.executable;
620

621
    rp.stubEnvironment = rp.inferior.environment; // FIXME: Wrong, but contains DYLD_IMAGE_SUFFIX
622

623 624 625 626
    // Copy over DYLD_IMAGE_SUFFIX etc
    for (auto var : QStringList({"DYLD_IMAGE_SUFFIX", "DYLD_LIBRARY_PATH", "DYLD_FRAMEWORK_PATH"}))
        if (rp.inferior.environment.hasKey(var))
            rp.debugger.environment.set(var, rp.inferior.environment.value(var));
627 628

    // This can happen e.g. when started from the command line.
629 630
    if (rp.languages == NoLanguage)
        rp.languages = CppLanguage;
631 632

    // validate debugger if C++ debugging is enabled
633 634 635
    if (rp.languages & CppLanguage && !rp.validationErrors.isEmpty()) {
        reportFailure(rp.validationErrors.join('\n'));
        return false;
636 637
    }

638
    if (rp.languages & QmlLanguage) {
639 640 641 642 643
        if (device() && device()->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE) {
            if (rp.qmlServer.port() <= 0) {
                rp.qmlServer = ProjectExplorer::urlFromLocalHostAndFreePort();
                if (rp.qmlServer.port() <= 0) {
                    reportFailure(DebuggerPlugin::tr("Not enough free ports for QML debugging."));
644
                    return false;
645
                }
646
            }
647 648
            // Makes sure that all bindings go through the JavaScript engine, so that
            // breakpoints are actually hit!
649 650 651
            const QString optimizerKey = "QML_DISABLE_OPTIMIZER";
            if (!rp.inferior.environment.hasKey(optimizerKey))
                rp.inferior.environment.set(optimizerKey, "1");
652 653 654
        }
    }

655
    if (!boolSetting(AutoEnrichParameters)) {
656 657 658 659 660 661 662 663
        const QString sysroot = rp.sysRoot;
        if (rp.debugInfoLocation.isEmpty())
            rp.debugInfoLocation = sysroot + "/usr/lib/debug";
        if (rp.debugSourceLocation.isEmpty()) {
            QString base = sysroot + "/usr/src/debug/";
            rp.debugSourceLocation.append(base + "qt5base/src/corelib");
            rp.debugSourceLocation.append(base + "qt5base/src/gui");
            rp.debugSourceLocation.append(base + "qt5base/src/network");
664 665 666
        }
    }

667 668
    if (rp.masterEngineType == NoEngineType) {
        if (rp.languages & QmlLanguage) {
669
            QmlDebug::QmlDebugServicesPreset service;
670 671
            if (rp.languages & CppLanguage) {
                if (rp.nativeMixedEnabled) {
672
                    service = QmlDebug::QmlNativeDebuggerServices;
673
                } else {
674
                    rp.masterEngineType = QmlCppEngineType;
675
                    service = QmlDebug::QmlDebuggerServices;
676 677
                }
            } else {
678
                rp.masterEngineType = QmlEngineType;
679
                service = QmlDebug::QmlDebuggerServices;
680
            }
681
            if (rp.startMode != AttachExternal && rp.startMode != AttachCrashedExternal) {
682 683 684 685
                QString qmlarg = (rp.languages & CppLanguage) && rp.nativeMixedEnabled
                        ? QmlDebug::qmlDebugNativeArguments(service, false)
                        : QmlDebug::qmlDebugTcpArguments(service, Port(rp.qmlServer.port()));
                QtcProcess::addArg(&rp.inferior.commandLineArguments, qmlarg);
686
            }
687 688 689
        }
    }

690 691
    if (rp.masterEngineType == NoEngineType)
        rp.masterEngineType = rp.cppEngineType;
692

693 694
    if (rp.startMode == NoStartMode)
        rp.startMode = StartInternal;
695

696
    if (breakOnMainNextTime) {
697
        rp.breakOnMain = true;
698 699
        breakOnMainNextTime = false;
    }
700

701 702 703 704 705 706 707 708 709
    if (HostOsInfo::isWindowsHost()) {
        QtcProcess::SplitError perr;
        rp.inferior.commandLineArguments =
                QtcProcess::prepareArgs(rp.inferior.commandLineArguments, &perr,
                                        HostOsInfo::hostOs(), nullptr,
                                        &rp.inferior.workingDirectory).toWindowsArgs();
        if (perr != QtcProcess::SplitOk) {
            // perr == BadQuoting is never returned on Windows
            // FIXME? QTCREATORBUG-2809
710 711
            reportFailure(DebuggerPlugin::tr("Debugging complex command lines "
                                             "is currently not supported on Windows."));
712 713 714 715
            return false;
        }
    }

716 717 718
    // FIXME: We can't handle terminals yet.
    if (rp.useTerminal && rp.cppEngineType == LldbEngineType) {
        qWarning("Run in Terminal is not supported yet with the LLDB backend");
719 720
        appendMessage(DebuggerPlugin::tr("Run in Terminal is not supported with the LLDB backend."),
                      ErrorMessageFormat);
721 722 723
        rp.useTerminal = false;
    }

724
    return true;
725 726
}

727 728 729 730 731
static DebuggerRunConfigurationAspect *debuggerAspect(const RunControl *runControl)
{
    return runControl->runConfiguration()->extraAspect<DebuggerRunConfigurationAspect>();
}

732 733 734 735 736 737 738 739 740
static bool cppDebugging(const RunControl *runControl)
{
    auto aspect = debuggerAspect(runControl);
    return aspect ? aspect->useCppDebugger() : true; // For cases like valgrind-with-gdb.
}

static bool qmlDebugging(const RunControl *runControl)
{
    auto aspect = debuggerAspect(runControl);
741
    return aspect ? aspect->useQmlDebugger() : false; // For cases like valgrind-with-gdb.
742 743
}

hjk's avatar
hjk committed
744 745
/// DebuggerRunTool

746
DebuggerRunTool::DebuggerRunTool(RunControl *runControl)
747
    : RunWorker(runControl),
748 749
      m_isCppDebugging(cppDebugging(runControl)),
      m_isQmlDebugging(qmlDebugging(runControl))
750
{
751
    setDisplayName("DebuggerRunTool");
752 753 754 755 756 757 758 759 760 761
    runControl->setIcon(ProjectExplorer::Icons::DEBUG_START_SMALL_TOOLBAR);
    runControl->setPromptToStop([](bool *optionalPrompt) {
        return RunControl::showPromptToStopDialog(
            DebuggerRunTool::tr("Close Debugging Session"),
            DebuggerRunTool::tr("A debugging session is still in progress. "
                                "Terminating the session in the current"
                                " state can leave the target in an inconsistent state."
                                " Would you still like to terminate it?"),
                QString(), QString(), optionalPrompt);
    });
762

hjk's avatar
hjk committed
763 764
    Runnable r = runnable();
    if (r.is<StandardRunnable>()) {
765
        m_runParameters.inferior = r.as<StandardRunnable>();
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
        m_runParameters.useTerminal = m_runParameters.inferior.runMode == ApplicationLauncher::Console;
        // Normalize to work around QTBUG-17529 (QtDeclarative fails with 'File name case mismatch'...)
        m_runParameters.inferior.workingDirectory =
                FileUtils::normalizePathName(m_runParameters.inferior.workingDirectory);
    }

    RunConfiguration *runConfig = runControl->runConfiguration();
    QTC_ASSERT(runConfig, return);

    m_runParameters.displayName = runConfig->displayName();

    const Kit *kit = runConfig->target()->kit();
    QTC_ASSERT(kit, return);

    m_runParameters.macroExpander = kit->macroExpander();

    m_runParameters.debugger = DebuggerKitInformation::runnable(kit);
    const QByteArray envBinary = qgetenv("QTC_DEBUGGER_PATH");
    if (!envBinary.isEmpty())
        m_runParameters.debugger.executable = QString::fromLocal8Bit(envBinary);

    if (Project *project = runConfig->target()->project()) {
        m_runParameters.projectSourceDirectory = project->projectDirectory().toString();
        m_runParameters.projectSourceFiles = project->files(Project::SourceFiles);
    }

    m_runParameters.toolChainAbi = ToolChainKitInformation::targetAbi(kit);

    bool ok = false;
    int nativeMixedOverride = qgetenv("QTC_DEBUGGER_NATIVE_MIXED").toInt(&ok);
    if (ok)
        m_runParameters.nativeMixedEnabled = bool(nativeMixedOverride);

    m_runParameters.cppEngineType = DebuggerKitInformation::engineType(kit);
    m_runParameters.sysRoot = SysRootKitInformation::sysRoot(kit).toString();

    // This will only be shown in some cases, but we don't want to access
    // the kit at that time anymore.
    const QList<Task> tasks = DebuggerKitInformation::validateDebugger(kit);
    for (const Task &t : tasks) {
        if (t.type != Task::Warning)
            m_runParameters.validationErrors.append(t.description);
    }

    if (runConfig->property("supportsDebugger").toBool()) {
        const QString mainScript = runConfig->property("mainScript").toString();
        const QString interpreter = runConfig->property("interpreter").toString();
        if (!interpreter.isEmpty() && mainScript.endsWith(".py")) {
            m_runParameters.mainScript = mainScript;
            m_runParameters.interpreter = interpreter;
            const QString args = runConfig->property("arguments").toString();
            if (!args.isEmpty()) {
                if (!m_runParameters.inferior.commandLineArguments.isEmpty())
                    m_runParameters.inferior.commandLineArguments.append(' ');
                m_runParameters.inferior.commandLineArguments.append(args);
            }
            m_runParameters.masterEngineType = PdbEngineType;
        }
    }

    if (auto debuggerAspect = runConfig->extraAspect<DebuggerRunConfigurationAspect>()) {
        m_runParameters.multiProcess = debuggerAspect->useMultiProcess();
        if (m_runParameters.languages == NoLanguage) {
            if (debuggerAspect->useCppDebugger())
                m_runParameters.languages |= CppLanguage;
            if (debuggerAspect->useQmlDebugger())
                m_runParameters.languages |= QmlLanguage;
        }
    }
835 836
}

837 838 839 840 841
DebuggerEngine *DebuggerRunTool::activeEngine() const
{
    return m_engine ? m_engine->activeEngine() : nullptr;
}

842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
class DummyProject : public Project
{
public:
    DummyProject() : Project(QString(""), FileName::fromString("")) {}
};

RunConfiguration *dummyRunConfigForKit(ProjectExplorer::Kit *kit)
{
    QTC_ASSERT(kit, return nullptr); // Caller needs to look for a suitable kit.
    Project *project = SessionManager::startupProject();
    Target *target = project ? project->target(kit) : nullptr;
    if (!target || !target->activeRunConfiguration()) {
        project = new DummyProject; // FIXME: Leaks.
        target = project->createTarget(kit);
    }
    QTC_ASSERT(target, return nullptr);
    auto runConfig = target->activeRunConfiguration();
    return runConfig;
}

DebuggerRunTool *DebuggerRunTool::createFromKit(Kit *kit)
{
    RunConfiguration *runConfig = dummyRunConfigForKit(kit);
    return createFromRunConfiguration(runConfig);
}

void DebuggerRunTool::startRunControl()
{
    ProjectExplorerPlugin::startRunControl(runControl());
}

DebuggerRunTool *DebuggerRunTool::createFromRunConfiguration(RunConfiguration *runConfig)
{
    QTC_ASSERT(runConfig, return nullptr);
    auto runControl = new RunControl(runConfig, ProjectExplorer::Constants::DEBUG_RUN_MODE);
    auto debugger = new DebuggerRunTool(runControl);
    return debugger;
}

881
void DebuggerRunTool::addSolibSearchDir(const QString &str)
882 883
{
    QString path = str;
884 885
    path.replace("%{sysroot}", m_runParameters.sysRoot);
    m_runParameters.solibSearchPath.append(path);
886 887
}

888 889 890 891 892 893 894 895
DebuggerRunTool::~DebuggerRunTool()
{
    disconnect();
    if (m_engine) {
        DebuggerEngine *engine = m_engine;
        m_engine = 0;
        engine->disconnect();
        delete engine;
hjk's avatar
hjk committed
896
    }
897
}
hjk's avatar
hjk committed
898

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
void DebuggerRunTool::showMessage(const QString &msg, int channel, int timeout)
{
    if (channel == ConsoleOutput)
        debuggerConsole()->printItem(ConsoleItem::DefaultType, msg);

    Internal::showMessage(msg, channel, timeout);
    switch (channel) {
    case AppOutput:
        appendMessage(msg, StdOutFormatSameLine);
        break;
    case AppError:
        appendMessage(msg, StdErrFormatSameLine);
        break;
    case AppStuff:
        appendMessage(msg, DebugFormat);
        break;
    default:
        break;
    }
}
hjk's avatar
hjk committed
919

920 921 922 923 924 925
////////////////////////////////////////////////////////////////////////
//
// Externally visible helper.
//
////////////////////////////////////////////////////////////////////////

926 927 928 929 930
// GdbServerPortGatherer

GdbServerPortsGatherer::GdbServerPortsGatherer(RunControl *runControl)
    : RunWorker(runControl)
{
931
    setDisplayName("GdbServerPortsGatherer");
932 933 934 935 936

    connect(&m_portsGatherer, &DeviceUsedPortsGatherer::error,
            this, &RunWorker::reportFailure);
    connect(&m_portsGatherer, &DeviceUsedPortsGatherer::portListReady,
            this, &GdbServerPortsGatherer::handlePortListReady);
937 938 939 940 941 942
}

GdbServerPortsGatherer::~GdbServerPortsGatherer()
{
}

943 944 945 946 947 948 949 950 951 952 953 954 955
QString GdbServerPortsGatherer::gdbServerChannel() const
{
    const QString host = device()->sshParameters().host;
    return QString("%1:%2").arg(host).arg(m_gdbServerPort.number());
}

QUrl GdbServerPortsGatherer::qmlServer() const
{
    QUrl server = device()->toolControlChannel(IDevice::QmlControlChannel);
    server.setPort(m_qmlServerPort.number());
    return server;
}

956 957 958 959 960 961
void GdbServerPortsGatherer::start()
{
    appendMessage(tr("Checking available ports..."), NormalMessageFormat);
    m_portsGatherer.start(device());
}

962 963 964
void GdbServerPortsGatherer::handlePortListReady()
{
    Utils::PortList portList = device()->freePorts();
Jarek Kobus's avatar
Jarek Kobus committed
965
    appendMessage(tr("Found %n free ports.", nullptr, portList.count()), NormalMessageFormat);
966 967 968 969 970 971 972 973 974 975 976 977 978 979
    if (m_useGdbServer) {
        m_gdbServerPort = m_portsGatherer.getNextFreePort(&portList);
        if (!m_gdbServerPort.isValid()) {
            reportFailure(tr("Not enough free ports on device for C++ debugging."));
            return;
        }
    }
    if (m_useQmlServer) {
        m_qmlServerPort = m_portsGatherer.getNextFreePort(&portList);
        if (!m_qmlServerPort.isValid()) {
            reportFailure(tr("Not enough free ports on device for QML debugging."));
            return;
        }
    }
980 981
//    reportDone();
    reportStarted();
982
}
983 984 985

// GdbServerRunner

986
GdbServerRunner::GdbServerRunner(RunControl *runControl, GdbServerPortsGatherer *portsGatherer)
987
   : SimpleTargetRunner(runControl), m_portsGatherer(portsGatherer)
988 989 990 991 992 993 994 995 996 997
{
    setDisplayName("GdbServerRunner");
}

GdbServerRunner::~GdbServerRunner()
{
}

void GdbServerRunner::start()
{
998
    QTC_ASSERT(m_portsGatherer, reportFailure(); return);
999 1000 1001 1002 1003

    StandardRunnable r = runnable().as<StandardRunnable>();
    QStringList args = QtcProcess::splitArgs(r.commandLineArguments, OsTypeLinux);
    QString command;

1004 1005
    const bool isQmlDebugging = m_portsGatherer->useQmlServer();
    const bool isCppDebugging = m_portsGatherer->useGdbServer();
1006 1007 1008

    if (isQmlDebugging) {
        args.prepend(QmlDebug::qmlDebugTcpArguments(QmlDebug::QmlDebuggerServices,
1009
                                                    m_portsGatherer->qmlServerPort()));
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    }

    if (isQmlDebugging && !isCppDebugging) {
        command = r.executable;
    } else {
        command = device()->debugServerPath();
        if (command.isEmpty())
            command = "gdbserver";
        args.clear();
        args.append(QString("--multi"));
1020
        args.append(QString(":%1").arg(m_portsGatherer->gdbServerPort().number()));
1021 1022 1023 1024
    }
    r.executable = command;
    r.commandLineArguments = QtcProcess::joinArgs(args, OsTypeLinux);

1025
    setRunnable(r);
1026

1027
    appendMessage(tr("Starting gdbserver..."), NormalMessageFormat);
1028

1029
    SimpleTargetRunner::start();
1030 1031
}

hjk's avatar
hjk committed
1032
} // namespace Debugger