iosrunner.cpp 16.4 KB
Newer Older
1 2
/****************************************************************************
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5 6 7 8 9 10 11
**
** This file is part of Qt Creator.
**
** 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.
23 24 25 26 27 28 29 30 31 32
**
****************************************************************************/

#include "iosbuildstep.h"
#include "iosconfigurations.h"
#include "iosdevice.h"
#include "iosmanager.h"
#include "iosrunconfiguration.h"
#include "iosrunner.h"
#include "iossimulator.h"
33
#include "iosconstants.h"
34

hjk's avatar
hjk committed
35 36 37 38
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerkitinformation.h>
#include <debugger/debuggerruncontrol.h>

39
#include <projectexplorer/kitinformation.h>
hjk's avatar
hjk committed
40
#include <projectexplorer/projectexplorerconstants.h>
41
#include <projectexplorer/target.h>
Fawzi Mohamed's avatar
Fawzi Mohamed committed
42
#include <projectexplorer/taskhub.h>
hjk's avatar
hjk committed
43 44
#include <projectexplorer/toolchain.h>

45
#include <qmldebug/qmldebugcommandlinearguments.h>
46

hjk's avatar
hjk committed
47 48 49 50 51 52 53
#include <qtsupport/qtkitinformation.h>

#include <utils/fileutils.h>
#include <utils/qtcprocess.h>
#include <utils/utilsicons.h>

#include <QDateTime>
54 55
#include <QDir>
#include <QMessageBox>
Fawzi Mohamed's avatar
Fawzi Mohamed committed
56
#include <QRegExp>
hjk's avatar
hjk committed
57 58 59
#include <QSettings>
#include <QTcpServer>
#include <QTime>
60

hjk's avatar
hjk committed
61 62 63 64 65 66 67
#include <stdio.h>
#include <fcntl.h>
#ifdef Q_OS_UNIX
#include <unistd.h>
#else
#include <io.h>
#endif
68 69
#include <signal.h>

hjk's avatar
hjk committed
70
using namespace Debugger;
Fawzi Mohamed's avatar
Fawzi Mohamed committed
71
using namespace ProjectExplorer;
hjk's avatar
hjk committed
72
using namespace Utils;
Fawzi Mohamed's avatar
Fawzi Mohamed committed
73

74 75 76
namespace Ios {
namespace Internal {

hjk's avatar
hjk committed
77 78
IosRunner::IosRunner(RunControl *runControl)
    : RunWorker(runControl)
79
{
80 81 82 83
    auto runConfig = qobject_cast<IosRunConfiguration *>(runControl->runConfiguration());
    m_bundleDir = runConfig->bundleDirectory().toString();
    m_arguments = QStringList(runConfig->commandLineArguments());
    m_device = DeviceKitInformation::device(runConfig->target()->kit());
84
    m_deviceType = runConfig->deviceType();
85 86 87 88 89 90 91
}

IosRunner::~IosRunner()
{
    stop();
}

hjk's avatar
hjk committed
92 93 94 95 96 97 98 99 100 101
void IosRunner::setCppDebugging(bool cppDebug)
{
    m_cppDebug = cppDebug;
}

void IosRunner::setQmlDebugging(QmlDebug::QmlDebugServicesPreset qmlDebugServices)
{
    m_qmlDebugServices = qmlDebugServices;
}

102 103 104 105 106 107 108
QString IosRunner::bundlePath()
{
    return m_bundleDir;
}

QStringList IosRunner::extraArgs()
{
Fawzi Mohamed's avatar
Fawzi Mohamed committed
109
    QStringList res = m_arguments;
hjk's avatar
hjk committed
110 111
    if (m_qmlServerPort.isValid())
        res << QmlDebug::qmlDebugTcpArguments(m_qmlDebugServices, m_qmlServerPort);
Fawzi Mohamed's avatar
Fawzi Mohamed committed
112
    return res;
113 114 115 116 117 118 119 120 121 122 123 124
}

QString IosRunner::deviceId()
{
    IosDevice::ConstPtr dev = m_device.dynamicCast<const IosDevice>();
    if (!dev)
        return QString();
    return dev->uniqueDeviceID();
}

IosToolHandler::RunKind IosRunner::runType()
{
Fawzi Mohamed's avatar
Fawzi Mohamed committed
125
    if (m_cppDebug)
126 127 128 129
        return IosToolHandler::DebugRun;
    return IosToolHandler::NormalRun;
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
130 131 132 133 134
bool IosRunner::cppDebug() const
{
    return m_cppDebug;
}

135 136 137 138 139
bool IosRunner::qmlDebug() const
{
    return m_qmlDebugServices != QmlDebug::NoQmlDebugServices;
}

140
QmlDebug::QmlDebugServicesPreset IosRunner::qmlDebugServices() const
Fawzi Mohamed's avatar
Fawzi Mohamed committed
141
{
142
    return m_qmlDebugServices;
Fawzi Mohamed's avatar
Fawzi Mohamed committed
143 144
}

145 146
void IosRunner::start()
{
hjk's avatar
hjk committed
147
    if (m_toolHandler && isAppRunning())
148
        m_toolHandler->stop();
hjk's avatar
hjk committed
149

150
    m_cleanExit = false;
hjk's avatar
hjk committed
151
    m_qmlServerPort = Port();
152
    if (!QFileInfo::exists(m_bundleDir)) {
153 154 155
        TaskHub::addTask(Task::Warning,
                         tr("Could not find %1.").arg(m_bundleDir),
                         ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT);
hjk's avatar
hjk committed
156
        reportFailure();
157 158
        return;
    }
Fawzi Mohamed's avatar
Fawzi Mohamed committed
159 160 161
    if (m_device->type() == Ios::Constants::IOS_DEVICE_TYPE) {
        IosDevice::ConstPtr iosDevice = m_device.dynamicCast<const IosDevice>();
        if (m_device.isNull()) {
hjk's avatar
hjk committed
162
            reportFailure();
Fawzi Mohamed's avatar
Fawzi Mohamed committed
163 164
            return;
        }
165
        if (m_qmlDebugServices != QmlDebug::NoQmlDebugServices)
hjk's avatar
hjk committed
166
            m_qmlServerPort = iosDevice->nextPort();
Fawzi Mohamed's avatar
Fawzi Mohamed committed
167
    } else {
168 169
        IosSimulator::ConstPtr sim = m_device.dynamicCast<const IosSimulator>();
        if (sim.isNull()) {
hjk's avatar
hjk committed
170
            reportFailure();
171 172
            return;
        }
173
        if (m_qmlDebugServices != QmlDebug::NoQmlDebugServices)
hjk's avatar
hjk committed
174
            m_qmlServerPort = sim->nextPort();
175
    }
Fawzi Mohamed's avatar
Fawzi Mohamed committed
176

177
    m_toolHandler = new IosToolHandler(m_deviceType, this);
hjk's avatar
hjk committed
178 179 180 181 182 183 184 185 186 187 188 189
    connect(m_toolHandler, &IosToolHandler::appOutput,
            this, &IosRunner::handleAppOutput);
    connect(m_toolHandler, &IosToolHandler::errorMsg,
            this, &IosRunner::handleErrorMsg);
    connect(m_toolHandler, &IosToolHandler::gotServerPorts,
            this, &IosRunner::handleGotServerPorts);
    connect(m_toolHandler, &IosToolHandler::gotInferiorPid,
            this, &IosRunner::handleGotInferiorPid);
    connect(m_toolHandler, &IosToolHandler::toolExited,
            this, &IosRunner::handleToolExited);
    connect(m_toolHandler, &IosToolHandler::finished,
            this, &IosRunner::handleFinished);
190 191 192 193 194
    m_toolHandler->requestRunApp(bundlePath(), extraArgs(), runType(), deviceId());
}

void IosRunner::stop()
{
hjk's avatar
hjk committed
195
    if (isAppRunning())
196 197 198
        m_toolHandler->stop();
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
199
void IosRunner::handleGotServerPorts(IosToolHandler *handler, const QString &bundlePath,
hjk's avatar
hjk committed
200 201
                                     const QString &deviceId, Port gdbPort,
                                     Port qmlPort)
202
{
hjk's avatar
hjk committed
203
    // Called when debugging on Device.
204
    Q_UNUSED(bundlePath); Q_UNUSED(deviceId);
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

    if (m_toolHandler != handler)
        return;

    m_gdbServerPort = gdbPort;
    m_qmlServerPort = qmlPort;

    bool prerequisiteOk = false;
    if (cppDebug() && qmlDebug())
        prerequisiteOk = m_gdbServerPort.isValid() && m_qmlServerPort.isValid();
    else if (cppDebug())
        prerequisiteOk = m_gdbServerPort.isValid();
    else if (qmlDebug())
        prerequisiteOk = m_qmlServerPort.isValid();
    else
        prerequisiteOk = true; // Not debugging. Ports not required.


    if (prerequisiteOk)
        reportStarted();
    else
        reportFailure(tr("Could not get necessary ports for the debugger connection."));
227 228 229
}

void IosRunner::handleGotInferiorPid(IosToolHandler *handler, const QString &bundlePath,
230
                                     const QString &deviceId, qint64 pid)
231
{
hjk's avatar
hjk committed
232
    // Called when debugging on Simulator.
233
    Q_UNUSED(bundlePath); Q_UNUSED(deviceId);
234 235 236 237

    if (m_toolHandler != handler)
        return;

238
    m_pid = pid;
239 240 241 242
    bool prerequisiteOk = false;
    if (m_pid > 0) {
        prerequisiteOk = true;
    } else {
hjk's avatar
hjk committed
243
        reportFailure(tr("Could not get inferior PID."));
244
        return;
hjk's avatar
hjk committed
245
    }
246 247 248 249 250 251 252 253

    if (qmlDebug())
        prerequisiteOk = m_qmlServerPort.isValid();

    if (prerequisiteOk)
        reportStarted();
    else
        reportFailure(tr("Could not get necessary ports the debugger connection."));
254 255 256 257 258
}

void IosRunner::handleAppOutput(IosToolHandler *handler, const QString &output)
{
    Q_UNUSED(handler);
hjk's avatar
hjk committed
259
    QRegExp qmlPortRe("QML Debugger: Waiting for connection on port ([0-9]+)...");
Fawzi Mohamed's avatar
Fawzi Mohamed committed
260 261
    int index = qmlPortRe.indexIn(output);
    QString res(output);
hjk's avatar
hjk committed
262 263 264 265
    if (index != -1 && m_qmlServerPort.isValid())
       res.replace(qmlPortRe.cap(1), QString::number(m_qmlServerPort.number()));
    appendMessage(output, StdOutFormat);
    appOutput(res);
266 267 268 269 270
}

void IosRunner::handleErrorMsg(IosToolHandler *handler, const QString &msg)
{
    Q_UNUSED(handler);
271
    QString res(msg);
hjk's avatar
hjk committed
272 273
    QString lockedErr ="Unexpected reply: ELocked (454c6f636b6564) vs OK (4f4b)";
    if (msg.contains("AMDeviceStartService returned -402653150")) {
Fawzi Mohamed's avatar
Fawzi Mohamed committed
274 275 276
        TaskHub::addTask(Task::Warning,
                         tr("Run failed. The settings in the Organizer window of Xcode might be incorrect."),
                         ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT);
277
    } else if (res.contains(lockedErr)) {
278 279
        QString message = tr("The device is locked, please unlock.");
        TaskHub::addTask(Task::Error, message,
Fawzi Mohamed's avatar
Fawzi Mohamed committed
280
                         ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT);
281
        res.replace(lockedErr, message);
282
    }
hjk's avatar
hjk committed
283
    QRegExp qmlPortRe("QML Debugger: Waiting for connection on port ([0-9]+)...");
Fawzi Mohamed's avatar
Fawzi Mohamed committed
284
    int index = qmlPortRe.indexIn(msg);
hjk's avatar
hjk committed
285 286 287 288 289
    if (index != -1 && m_qmlServerPort.isValid())
       res.replace(qmlPortRe.cap(1), QString::number(m_qmlServerPort.number()));

    appendMessage(res, StdErrFormat);
    errorMsg(res);
290 291 292 293 294 295 296 297 298 299 300
}

void IosRunner::handleToolExited(IosToolHandler *handler, int code)
{
    Q_UNUSED(handler);
    m_cleanExit = (code == 0);
}

void IosRunner::handleFinished(IosToolHandler *handler)
{
    if (m_toolHandler == handler) {
hjk's avatar
hjk committed
301 302 303 304 305
        if (m_cleanExit)
            appendMessage(tr("Run ended."), NormalMessageFormat);
        else
            appendMessage(tr("Run ended with error."), ErrorMessageFormat);
        m_toolHandler = nullptr;
306 307
    }
    handler->deleteLater();
hjk's avatar
hjk committed
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
    reportStopped();
}

qint64 IosRunner::pid() const
{
    return m_pid;
}

bool IosRunner::isAppRunning() const
{
    return m_toolHandler && m_toolHandler->isRunning();
}

Utils::Port IosRunner::gdbServerPort() const
{
    return m_gdbServerPort;
}

Utils::Port IosRunner::qmlServerPort() const
{
    return m_qmlServerPort;
}

//
// IosRunner
//

IosRunSupport::IosRunSupport(RunControl *runControl)
    : IosRunner(runControl)
{
    runControl->setIcon(Icons::RUN_SMALL_TOOLBAR);
    QString displayName = QString("Run on %1").arg(device().isNull() ? QString() : device()->displayName());
    runControl->setDisplayName(displayName);
}

IosRunSupport::~IosRunSupport()
{
    stop();
}

void IosRunSupport::start()
{
    appendMessage(tr("Starting remote process."), NormalMessageFormat);
    IosRunner::start();
}

void IosRunSupport::stop()
{
    IosRunner::stop();
}

//
hjk's avatar
hjk committed
360
// IosQmlProfilerSupport
hjk's avatar
hjk committed
361 362
//

hjk's avatar
hjk committed
363 364
IosQmlProfilerSupport::IosQmlProfilerSupport(RunControl *runControl)
    : RunWorker(runControl)
hjk's avatar
hjk committed
365 366 367 368 369 370 371 372
{
    setDisplayName("IosAnalyzeSupport");

    auto iosRunConfig = qobject_cast<IosRunConfiguration *>(runControl->runConfiguration());
    StandardRunnable runnable;
    runnable.executable = iosRunConfig->localExecutable().toUserOutput();
    runnable.commandLineArguments = iosRunConfig->commandLineArguments();
    runControl->setDisplayName(iosRunConfig->applicationName());
hjk's avatar
hjk committed
373
    runControl->setRunnable(runnable);
hjk's avatar
hjk committed
374

hjk's avatar
hjk committed
375 376 377
    m_runner = new IosRunner(runControl);
    m_runner->setQmlDebugging(QmlDebug::QmlProfilerServices);
    addDependency(m_runner);
hjk's avatar
hjk committed
378

hjk's avatar
hjk committed
379 380
    m_profiler = runControl->createWorker(runControl->runMode());
    m_profiler->addDependency(this);
hjk's avatar
hjk committed
381 382
}

hjk's avatar
hjk committed
383
void IosQmlProfilerSupport::start()
hjk's avatar
hjk committed
384
{
385
    QUrl serverUrl;
hjk's avatar
hjk committed
386 387 388 389
    QTcpServer server;
    QTC_ASSERT(server.listen(QHostAddress::LocalHost)
               || server.listen(QHostAddress::LocalHostIPv6), return);
    serverUrl.setHost(server.serverAddress().toString());
hjk's avatar
hjk committed
390

hjk's avatar
hjk committed
391 392 393 394 395 396 397
    Port qmlPort = m_runner->qmlServerPort();
    serverUrl.setPort(qmlPort.number());
    m_profiler->recordData("QmlServerUrl", serverUrl);
    if (qmlPort.isValid())
        reportStarted();
    else
        reportFailure(tr("Could not get necessary ports for the profiler connection."));
hjk's avatar
hjk committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
}

//
// IosDebugSupport
//

IosDebugSupport::IosDebugSupport(RunControl *runControl)
    : Debugger::DebuggerRunTool(runControl)
{
    m_runner = new IosRunner(runControl);
    m_runner->setCppDebugging(isCppDebugging());
    m_runner->setQmlDebugging(isQmlDebugging() ? QmlDebug::QmlDebuggerServices : QmlDebug::NoQmlDebugServices);

    addDependency(m_runner);
}

void IosDebugSupport::start()
{
416 417 418 419 420
    if (!m_runner->isAppRunning()) {
        reportFailure(tr("Application not running."));
        return;
    }

hjk's avatar
hjk committed
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
    RunConfiguration *runConfig = runControl()->runConfiguration();

    DebuggerStartParameters params;
    if (device()->type() == Ios::Constants::IOS_DEVICE_TYPE) {
        IosDevice::ConstPtr dev = device().dynamicCast<const IosDevice>();
        params.startMode = AttachToRemoteProcess;
        params.platform = "remote-ios";
        QString osVersion = dev->osVersion();
        FileName deviceSdk1 = FileName::fromString(QDir::homePath()
                                             + "/Library/Developer/Xcode/iOS DeviceSupport/"
                                             + osVersion + "/Symbols");
        QString deviceSdk;
        if (deviceSdk1.toFileInfo().isDir()) {
            deviceSdk = deviceSdk1.toString();
        } else {
            FileName deviceSdk2 = IosConfigurations::developerPath()
                    .appendPath("Platforms/iPhoneOS.platform/DeviceSupport/")
                    .appendPath(osVersion).appendPath("Symbols");
            if (deviceSdk2.toFileInfo().isDir()) {
                deviceSdk = deviceSdk2.toString();
            } else {
                TaskHub::addTask(Task::Warning, tr(
                  "Could not find device specific debug symbols at %1. "
                  "Debugging initialization will be slow until you open the Organizer window of "
                  "Xcode with the device connected to have the symbols generated.")
                                 .arg(deviceSdk1.toUserOutput()),
                                 ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT);
            }
        }
        params.deviceSymbolsRoot = deviceSdk;
    } else {
        params.startMode = AttachExternal;
        params.platform = "ios-simulator";
    }

    auto iosRunConfig = qobject_cast<IosRunConfiguration *>(runConfig);
    params.displayName = iosRunConfig->applicationName();
    params.continueAfterAttach = true;

    Utils::Port gdbServerPort = m_runner->gdbServerPort();
    Utils::Port qmlServerPort = m_runner->qmlServerPort();
    params.attachPID = ProcessHandle(m_runner->pid());

    const bool cppDebug = isCppDebugging();
    const bool qmlDebug = isQmlDebugging();
    if (cppDebug) {
        params.inferior.executable = iosRunConfig->localExecutable().toString();
468
        params.remoteChannel = "connect://localhost:" + gdbServerPort.toString();
hjk's avatar
hjk committed
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

        FileName xcodeInfo = IosConfigurations::developerPath().parentDir().appendPath("Info.plist");
        bool buggyLldb = false;
        if (xcodeInfo.exists()) {
            QSettings settings(xcodeInfo.toString(), QSettings::NativeFormat);
            QStringList version = settings.value(QLatin1String("CFBundleShortVersionString")).toString()
                    .split('.');
            if (version.value(0).toInt() == 5 && version.value(1, QString::number(1)).toInt() == 0)
                buggyLldb = true;
        }
        QString bundlePath = iosRunConfig->bundleDirectory().toString();
        bundlePath.chop(4);
        FileName dsymPath = FileName::fromString(bundlePath.append(".dSYM"));
        if (!dsymPath.exists()) {
            if (buggyLldb)
                TaskHub::addTask(Task::Warning,
                                 tr("Debugging with Xcode 5.0.x can be unreliable without a dSYM. "
                                    "To create one, add a dsymutil deploystep."),
                                 ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT);
        } else if (dsymPath.toFileInfo().lastModified()
                   < QFileInfo(iosRunConfig->localExecutable().toUserOutput()).lastModified()) {
            TaskHub::addTask(Task::Warning,
                             tr("The dSYM %1 seems to be outdated, it might confuse the debugger.")
                             .arg(dsymPath.toUserOutput()),
                             ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT);
        }
    }

    if (qmlDebug) {
        QTcpServer server;
        QTC_ASSERT(server.listen(QHostAddress::LocalHost)
                   || server.listen(QHostAddress::LocalHostIPv6), return);
        params.qmlServer.host = server.serverAddress().toString();
        if (!cppDebug)
            params.startMode = AttachToRemoteServer;
    }

    if (qmlServerPort.isValid()) {
        params.qmlServer.port = qmlServerPort;
        params.inferior.commandLineArguments.replace("%qml_port%", qmlServerPort.toString());
    }

    setStartParameters(params);

    DebuggerRunTool::start();
514 515
}

hjk's avatar
hjk committed
516
void IosDebugSupport::onFinished()
517
{
hjk's avatar
hjk committed
518
    abortDebugger();
519 520 521
}

} // namespace Internal
522
} // namespace Ios