iostoolhandler.cpp 39.7 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
**
****************************************************************************/

#include "iostoolhandler.h"
#include "iosconfigurations.h"
28
#include "iosconstants.h"
29
#include "iossimulator.h"
30
#include "simulatorcontrol.h"
31

32
#include "debugger/debuggerconstants.h"
33
#include <coreplugin/icore.h>
34 35
#include <utils/qtcassert.h>
#include <utils/fileutils.h>
36
#include <utils/qtcfallthrough.h>
37
#include "utils/runextensions.h"
38
#include "utils/synchronousprocess.h"
39 40

#include <QCoreApplication>
41
#include <QDir>
42
#include <QFileInfo>
43
#include <QFutureWatcher>
44 45 46
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
47
#include <QList>
48
#include <QLoggingCategory>
49
#include <QPointer>
50
#include <QProcess>
Fawzi Mohamed's avatar
Fawzi Mohamed committed
51
#include <QProcessEnvironment>
52 53
#include <QScopedArrayPointer>
#include <QSocketNotifier>
54
#include <QTemporaryFile>
55
#include <QTimer>
56
#include <QXmlStreamReader>
57

58
#include <signal.h>
59 60 61
#include <string.h>
#include <errno.h>

62
static Q_LOGGING_CATEGORY(toolHandlerLog, "qtc.ios.toolhandler")
63 64 65 66 67

namespace Ios {

namespace Internal {

68 69
using namespace std::placeholders;

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
// As per the currrent behavior, any absolute path given to simctl --stdout --stderr where the
// directory after the root also exists on the simulator's file system will map to
// simulator's file system i.e. simctl translates $TMPDIR/somwhere/out.txt to
// your_home_dir/Library/Developer/CoreSimulator/Devices/data/$TMP_DIR/somwhere/out.txt.
// Because /var also exists on simulator's file system.
// Though the log files located at CONSOLE_PATH_TEMPLATE are deleted on
// app exit any leftovers shall be removed on simulator restart.
static QString CONSOLE_PATH_TEMPLATE = QDir::homePath() +
        "/Library/Developer/CoreSimulator/Devices/%1/data/tmp/%2";

class LogTailFiles : public QObject
{
    Q_OBJECT
public:

85 86
    void exec(QFutureInterface<void> &fi, std::shared_ptr<QTemporaryFile> stdoutFile,
                    std::shared_ptr<QTemporaryFile> stderrFile)
87 88 89 90 91 92 93 94 95 96 97 98 99
    {
        if (fi.isCanceled())
            return;

        // The future is canceled when app on simulator is stoped.
        QEventLoop loop;
        QFutureWatcher<void> watcher;
        connect(&watcher, &QFutureWatcher<void>::canceled, [&](){
            loop.quit();
        });
        watcher.setFuture(fi.future());

        // Process to print the console output while app is running.
100
        auto logProcess = [this, fi](QProcess *tailProcess, std::shared_ptr<QTemporaryFile> file) {
101 102 103 104
            QObject::connect(tailProcess, &QProcess::readyReadStandardOutput, [=]() {
                if (!fi.isCanceled())
                    emit logMessage(QString::fromLocal8Bit(tailProcess->readAll()));
            });
105
            tailProcess->start(QStringLiteral("tail"), {"-f", file->fileName()});
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
        };

        auto processDeleter = [](QProcess *process) {
            if (process->state() != QProcess::NotRunning) {
                process->terminate();
                process->waitForFinished();
            }
            delete process;
        };

        std::unique_ptr<QProcess, void(*)(QProcess *)> tailStdout(new QProcess, processDeleter);
        if (stdoutFile)
            logProcess(tailStdout.get(), stdoutFile);

        std::unique_ptr<QProcess, void(*)(QProcess *)> tailStderr(new QProcess, processDeleter);
        if (stderrFile)
            logProcess(tailStderr.get(), stderrFile);

        // Blocks untill tool is deleted or toolexited is called.
        loop.exec();
    }

signals:
    void logMessage(QString message);
};

132 133 134 135 136 137 138 139
struct ParserState {
    enum Kind {
        Msg,
        DeviceId,
        Key,
        Value,
        QueryResult,
        AppOutput,
140
        ControlChar,
141 142
        AppStarted,
        InferiorPid,
Fawzi Mohamed's avatar
Fawzi Mohamed committed
143
        ServerPorts,
144 145 146 147 148 149 150 151 152 153 154 155
        Item,
        Status,
        AppTransfer,
        DeviceInfo,
        Exit
    };
    Kind kind;
    QString elName;
    QString chars;
    QString key;
    QString value;
    QMap<QString,QString> info;
156
    int progress = 0, maxProgress = 0;
Fawzi Mohamed's avatar
Fawzi Mohamed committed
157
    int gdbPort, qmlPort;
158 159 160 161 162 163 164 165
    bool collectChars() {
        switch (kind) {
        case Msg:
        case DeviceId:
        case Key:
        case Value:
        case Status:
        case InferiorPid:
166
        case AppOutput:
167
            return true;
Fawzi Mohamed's avatar
Fawzi Mohamed committed
168
        case ServerPorts:
169
        case QueryResult:
170
        case ControlChar:
171 172 173 174 175
        case AppStarted:
        case AppTransfer:
        case Item:
        case DeviceInfo:
        case Exit:
176
            break;
177
        }
178
        return false;
179 180 181
    }

    ParserState(Kind kind) :
Fawzi Mohamed's avatar
Fawzi Mohamed committed
182
        kind(kind), gdbPort(0), qmlPort(0) { }
183 184 185 186 187
};

class IosToolHandlerPrivate
{
public:
188
    explicit IosToolHandlerPrivate(const IosDeviceType &devType, IosToolHandler *q);
189
    virtual ~IosToolHandlerPrivate();
190 191 192 193 194 195
    virtual void requestTransferApp(const QString &bundlePath, const QString &deviceId,
                                    int timeout = 1000) = 0;
    virtual void requestRunApp(const QString &bundlePath, const QStringList &extraArgs,
                               IosToolHandler::RunKind runKind,
                               const QString &deviceId, int timeout = 1000) = 0;
    virtual void requestDeviceInfo(const QString &deviceId, int timeout = 1000) = 0;
196
    virtual bool isRunning() const = 0;
197
    virtual void stop(int errorCode) = 0;
198 199 200 201 202 203 204 205

    // signals
    void isTransferringApp(const QString &bundlePath, const QString &deviceId, int progress,
                           int maxProgress, const QString &info);
    void didTransferApp(const QString &bundlePath, const QString &deviceId,
                        IosToolHandler::OpStatus status);
    void didStartApp(const QString &bundlePath, const QString &deviceId,
                     IosToolHandler::OpStatus status);
206 207
    void gotServerPorts(const QString &bundlePath, const QString &deviceId, Utils::Port gdbPort,
                        Utils::Port qmlPort);
208
    void gotInferiorPid(const QString &bundlePath, const QString &deviceId, qint64 pid);
209 210 211 212
    void deviceInfo(const QString &deviceId, const IosToolHandler::Dict &info);
    void appOutput(const QString &output);
    void errorMsg(const QString &msg);
    void toolExited(int code);
213 214

protected:
215
    IosToolHandler *q;
216 217
    QString m_deviceId;
    QString m_bundlePath;
218
    IosToolHandler::RunKind m_runKind = IosToolHandler::NormalRun;
219
    IosDeviceType m_devType;
220 221 222 223
};

class IosDeviceToolHandlerPrivate : public IosToolHandlerPrivate
{
224 225 226 227 228 229 230 231 232 233 234 235 236
    enum State {
        NonStarted,
        Starting,
        StartedInferior,
        XmlEndProcessed,
        Stopped
    };
    enum Op {
        OpNone,
        OpAppTransfer,
        OpDeviceInfo,
        OpAppRun
    };
237
public:
238
    explicit IosDeviceToolHandlerPrivate(const IosDeviceType &devType, IosToolHandler *q);
239
    ~IosDeviceToolHandlerPrivate();
240 241 242 243 244 245 246 247 248

// IosToolHandlerPrivate overrides
public:
    void requestTransferApp(const QString &bundlePath, const QString &deviceId,
                            int timeout = 1000) override;
    void requestRunApp(const QString &bundlePath, const QStringList &extraArgs,
                       IosToolHandler::RunKind runKind,
                       const QString &deviceId, int timeout = 1000) override;
    void requestDeviceInfo(const QString &deviceId, int timeout = 1000) override;
249 250
    bool isRunning() const override;
    void start(const QString &exe, const QStringList &args);
251 252 253 254 255 256 257
    void stop(int errorCode) override;

private:
    void subprocessError(QProcess::ProcessError error);
    void subprocessFinished(int exitCode, QProcess::ExitStatus exitStatus);
    void subprocessHasData();
    void processXml();
258 259 260 261 262 263 264 265
    void killProcess();

    QTimer killTimer;
    std::shared_ptr<QProcess> process;
    State state = NonStarted;
    Op op = OpNone;
    QXmlStreamReader outputParser;
    QList<ParserState> stack;
266 267
};

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
/****************************************************************************
 * Flow to install an app on simulator:-
 *      +------------------+
 *      |   Transfer App   |
 *      +--------+---------+
 *               |
 *               v
 *     +---------+----------+             +--------------------------------+
 *     |  SimulatorRunning  +---No------> +SimulatorControl::startSimulator|
 *     +---------+----------+             +--------+-----------------------+
 *              Yes                                |
 *               |                                 |
 *               v                                 |
 * +---------+--------------------+                |
 * | SimulatorControl::installApp | <--------------+
 * +------------------------------+
 *
 *
 *
 * Flow to launch an app on Simulator:-
 *            +---------+
 *            | Run App |
 *            +----+----+
 *                 |
 *                 v
 *       +-------------------+             +----------------------------- - --+
 *       | SimulatorRunning? +---NO------> + SimulatorControl::startSimulator |
 *       +--------+----------+             +----------------+-----------------+
 *                YES                                       |
 *                 |                                        |
 *                 v                                        |
299 300 301 302
 * +---------+------------------------------+               |
 * | SimulatorControl::launchAppOnSimulator | <-------------+
 * +----------------------------------------+
 *
303
 ***************************************************************************/
304 305 306
class IosSimulatorToolHandlerPrivate : public IosToolHandlerPrivate
{
public:
307
    explicit IosSimulatorToolHandlerPrivate(const IosDeviceType &devType, IosToolHandler *q);
308
    ~IosSimulatorToolHandlerPrivate();
309 310 311

// IosToolHandlerPrivate overrides
public:
312
    void requestTransferApp(const QString &appBundlePath, const QString &deviceIdentifier,
313
                            int timeout = 1000) override;
314
    void requestRunApp(const QString &appBundlePath, const QStringList &extraArgs,
315 316 317
                       IosToolHandler::RunKind runKind,
                       const QString &deviceIdentifier, int timeout = 1000) override;
    void requestDeviceInfo(const QString &deviceId, int timeout = 1000) override;
318
    bool isRunning() const override;
319 320
    void stop(int errorCode) override;

321
private:
322
    void installAppOnSimulator();
323
    void launchAppOnSimulator(const QStringList &extraArgs);
324 325
    bool isResponseValid(const SimulatorControl::ResponseData &responseData);

326
private:
327
    qint64 m_pid = -1;
328
    SimulatorControl *simCtl;
329
    LogTailFiles outputLogger;
330
    QList<QFuture<void>> futureList;
331 332
};

333
IosToolHandlerPrivate::IosToolHandlerPrivate(const IosDeviceType &devType,
334
                                             Ios::IosToolHandler *q) :
335
    q(q),
336
    m_devType(devType)
337 338 339
{
}

340 341 342 343
IosToolHandlerPrivate::~IosToolHandlerPrivate()
{
}

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
// signals
void IosToolHandlerPrivate::isTransferringApp(const QString &bundlePath, const QString &deviceId,
                                              int progress, int maxProgress, const QString &info)
{
    emit q->isTransferringApp(q, bundlePath, deviceId, progress, maxProgress, info);
}

void IosToolHandlerPrivate::didTransferApp(const QString &bundlePath, const QString &deviceId,
                    Ios::IosToolHandler::OpStatus status)
{
    emit q->didTransferApp(q, bundlePath, deviceId, status);
}

void IosToolHandlerPrivate::didStartApp(const QString &bundlePath, const QString &deviceId,
                                        IosToolHandler::OpStatus status)
{
    emit q->didStartApp(q, bundlePath, deviceId, status);
}

363 364
void IosToolHandlerPrivate::gotServerPorts(const QString &bundlePath, const QString &deviceId,
                                           Utils::Port gdbPort, Utils::Port qmlPort)
365
{
Fawzi Mohamed's avatar
Fawzi Mohamed committed
366
    emit q->gotServerPorts(q, bundlePath, deviceId, gdbPort, qmlPort);
367 368 369
}

void IosToolHandlerPrivate::gotInferiorPid(const QString &bundlePath, const QString &deviceId,
370
                                           qint64 pid)
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
{
    emit q->gotInferiorPid(q, bundlePath, deviceId, pid);
}

void IosToolHandlerPrivate::deviceInfo(const QString &deviceId,
                                       const Ios::IosToolHandler::Dict &info)
{
    emit q->deviceInfo(q, deviceId, info);
}

void IosToolHandlerPrivate::appOutput(const QString &output)
{
    emit q->appOutput(q, output);
}

void IosToolHandlerPrivate::errorMsg(const QString &msg)
{
    emit q->errorMsg(q, msg);
}

void IosToolHandlerPrivate::toolExited(int code)
{
    emit q->toolExited(q, code);
}

396
void IosDeviceToolHandlerPrivate::subprocessError(QProcess::ProcessError error)
397
{
398
    if (state != Stopped)
399
        errorMsg(IosToolHandler::tr("iOS tool error %1").arg(error));
400 401
    stop(-1);
    if (error == QProcess::FailedToStart) {
402
        qCDebug(toolHandlerLog) << "IosToolHandler::finished(" << this << ")";
403
        emit q->finished(q);
404 405 406
    }
}

407
void IosDeviceToolHandlerPrivate::subprocessFinished(int exitCode, QProcess::ExitStatus exitStatus)
408
{
409
    stop((exitStatus == QProcess::NormalExit) ? exitCode : -1 );
410
    qCDebug(toolHandlerLog) << "IosToolHandler::finished(" << this << ")";
411
    killTimer.stop();
412
    emit q->finished(q);
413 414
}

415
void IosDeviceToolHandlerPrivate::processXml()
416 417 418
{
    while (!outputParser.atEnd()) {
        QXmlStreamReader::TokenType tt = outputParser.readNext();
419
        //qCDebug(toolHandlerLog) << "processXml, tt=" << tt;
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
        switch (tt) {
        case QXmlStreamReader::NoToken:
            // The reader has not yet read anything.
            continue;
        case QXmlStreamReader::Invalid:
            // An error has occurred, reported in error() and errorString().
            break;
        case QXmlStreamReader::StartDocument:
            // The reader reports the XML version number in documentVersion(), and the encoding
            // as specified in the XML document in documentEncoding(). If the document is declared
            // standalone, isStandaloneDocument() returns true; otherwise it returns false.
            break;
        case QXmlStreamReader::EndDocument:
            // The reader reports the end of the document.
            // state = XmlEndProcessed;
            break;
        case QXmlStreamReader::StartElement:
            // The reader reports the start of an element with namespaceUri() and name(). Empty
            // elements are also reported as StartElement, followed directly by EndElement.
            // The convenience function readElementText() can be called to concatenate all content
            // until the corresponding EndElement. Attributes are reported in attributes(),
            // namespace declarations in namespaceDeclarations().
        {
            QStringRef elName = outputParser.name();
            if (elName == QLatin1String("msg")) {
                stack.append(ParserState(ParserState::Msg));
            } else if (elName == QLatin1String("exit")) {
                stack.append(ParserState(ParserState::Exit));
                toolExited(outputParser.attributes().value(QLatin1String("code"))
                           .toString().toInt());
            } else if (elName == QLatin1String("device_id")) {
                stack.append(ParserState(ParserState::DeviceId));
            } else if (elName == QLatin1String("key")) {
                stack.append(ParserState(ParserState::Key));
            } else if (elName == QLatin1String("value")) {
                stack.append(ParserState(ParserState::Value));
            } else if (elName == QLatin1String("query_result")) {
                stack.append(ParserState(ParserState::QueryResult));
            } else if (elName == QLatin1String("app_output")) {
                stack.append(ParserState(ParserState::AppOutput));
460 461
            } else if (elName == QLatin1String("control_char")) {
                QXmlStreamAttributes attributes = outputParser.attributes();
462
                QChar c[1] = {QChar::fromLatin1(static_cast<char>(attributes.value(QLatin1String("code")).toString().toInt()))};
463 464 465 466
                if (stack.size() > 0 && stack.last().collectChars())
                    stack.last().chars.append(c[0]);
                stack.append(ParserState(ParserState::ControlChar));
                break;
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
            } else if (elName == QLatin1String("item")) {
                stack.append(ParserState(ParserState::Item));
            } else if (elName == QLatin1String("status")) {
                ParserState pState(ParserState::Status);
                QXmlStreamAttributes attributes = outputParser.attributes();
                pState.progress = attributes.value(QLatin1String("progress")).toString().toInt();
                pState.maxProgress = attributes.value(QLatin1String("max_progress")).toString().toInt();
                stack.append(pState);
            } else if (elName == QLatin1String("app_started")) {
                stack.append(ParserState(ParserState::AppStarted));
                QXmlStreamAttributes attributes = outputParser.attributes();
                QStringRef statusStr = attributes.value(QLatin1String("status"));
                Ios::IosToolHandler::OpStatus status = Ios::IosToolHandler::Unknown;
                if (statusStr.compare(QLatin1String("success"), Qt::CaseInsensitive) == 0)
                    status = Ios::IosToolHandler::Success;
                else if (statusStr.compare(QLatin1String("failure"), Qt::CaseInsensitive) == 0)
                    status = Ios::IosToolHandler::Failure;
484
                didStartApp(m_bundlePath, m_deviceId, status);
485 486 487 488 489 490 491 492 493
            } else if (elName == QLatin1String("app_transfer")) {
                stack.append(ParserState(ParserState::AppTransfer));
                QXmlStreamAttributes attributes = outputParser.attributes();
                QStringRef statusStr = attributes.value(QLatin1String("status"));
                Ios::IosToolHandler::OpStatus status = Ios::IosToolHandler::Unknown;
                if (statusStr.compare(QLatin1String("success"), Qt::CaseInsensitive) == 0)
                    status = Ios::IosToolHandler::Success;
                else if (statusStr.compare(QLatin1String("failure"), Qt::CaseInsensitive) == 0)
                    status = Ios::IosToolHandler::Failure;
494
                emit didTransferApp(m_bundlePath, m_deviceId, status);
495
            } else if (elName == QLatin1String("device_info") || elName == QLatin1String("deviceinfo")) {
496 497 498
                stack.append(ParserState(ParserState::DeviceInfo));
            } else if (elName == QLatin1String("inferior_pid")) {
                stack.append(ParserState(ParserState::InferiorPid));
Fawzi Mohamed's avatar
Fawzi Mohamed committed
499 500 501
            } else if (elName == QLatin1String("server_ports")) {
                stack.append(ParserState(ParserState::ServerPorts));
                QXmlStreamAttributes attributes = outputParser.attributes();
502 503 504 505
                Utils::Port gdbServerPort(
                            attributes.value(QLatin1String("gdb_server")).toString().toInt());
                Utils::Port qmlServerPort(
                            attributes.value(QLatin1String("qml_server")).toString().toInt());
506
                gotServerPorts(m_bundlePath, m_deviceId, gdbServerPort, qmlServerPort);
507
            } else {
508
                qCWarning(toolHandlerLog) << "unexpected element " << elName;
509 510 511 512 513 514 515 516 517 518 519 520 521
            }
            break;
        }
        case QXmlStreamReader::EndElement:
            // The reader reports the end of an element with namespaceUri() and name().
        {
            ParserState p = stack.last();
            stack.removeLast();
            switch (p.kind) {
            case ParserState::Msg:
                errorMsg(p.chars);
                break;
            case ParserState::DeviceId:
522 523
                if (m_deviceId.isEmpty())
                    m_deviceId = p.chars;
524
                else
525
                    QTC_CHECK(m_deviceId.compare(p.chars, Qt::CaseInsensitive) == 0);
526 527 528 529 530 531 532 533
                break;
            case ParserState::Key:
                stack.last().key = p.chars;
                break;
            case ParserState::Value:
                stack.last().value = p.chars;
                break;
            case ParserState::Status:
534
                isTransferringApp(m_bundlePath, m_deviceId, p.progress, p.maxProgress, p.chars);
535 536 537
                break;
            case ParserState::QueryResult:
                state = XmlEndProcessed;
538 539
                stop(0);
                return;
540
            case ParserState::AppOutput:
541 542 543
                appOutput(p.chars);
                break;
            case ParserState::ControlChar:
544 545 546 547 548 549 550 551 552
                break;
            case ParserState::AppStarted:
                break;
            case ParserState::AppTransfer:
                break;
            case ParserState::Item:
                stack.last().info.insert(p.key, p.value);
                break;
            case ParserState::DeviceInfo:
553
                deviceInfo(m_deviceId, p.info);
554 555 556 557
                break;
            case ParserState::Exit:
                break;
            case ParserState::InferiorPid:
558
                gotInferiorPid(m_bundlePath, m_deviceId, p.chars.toLongLong());
559
                break;
Fawzi Mohamed's avatar
Fawzi Mohamed committed
560
            case ParserState::ServerPorts:
Fawzi Mohamed's avatar
Fawzi Mohamed committed
561
                break;
562 563 564 565 566 567 568 569 570
            }
            break;
        }
        case QXmlStreamReader::Characters:
            // The reader reports characters in text(). If the characters are all white-space,
            // isWhitespace() returns true. If the characters stem from a CDATA section,
            // isCDATA() returns true.
            if (stack.isEmpty())
                break;
571
            if (stack.last().collectChars())
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
                stack.last().chars.append(outputParser.text());
            break;
        case QXmlStreamReader::Comment:
            // The reader reports a comment in text().
            break;
        case QXmlStreamReader::DTD:
            // The reader reports a DTD in text(), notation declarations in notationDeclarations(),
            // and entity declarations in entityDeclarations(). Details of the DTD declaration are
            // reported in in dtdName(), dtdPublicId(), and dtdSystemId().
            break;
        case QXmlStreamReader::EntityReference:
            // The reader reports an entity reference that could not be resolved. The name of
            // the reference is reported in name(), the replacement text in text().
            break;
        case QXmlStreamReader::ProcessingInstruction:
            break;
        }
    }
    if (outputParser.hasError()
            && outputParser.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
592
        qCWarning(toolHandlerLog) << "error parsing iosTool output:" << outputParser.errorString();
593
        stop(-1);
594 595 596
    }
}

597 598 599 600 601 602
void IosDeviceToolHandlerPrivate::killProcess()
{
    if (isRunning())
        process->kill();
}

603
void IosDeviceToolHandlerPrivate::subprocessHasData()
604
{
605
    qCDebug(toolHandlerLog) << "subprocessHasData, state:" << state;
606 607 608
    while (true) {
        switch (state) {
        case NonStarted:
609
            qCWarning(toolHandlerLog) << "IosToolHandler unexpected state in subprocessHasData: NonStarted";
610
            Q_FALLTHROUGH();
611 612 613 614
        case Starting:
        case StartedInferior:
            // read some data
        {
Fawzi Mohamed's avatar
Fawzi Mohamed committed
615
            char buf[200];
616 617
            while (isRunning()) {
                qint64 rRead = process->read(buf, sizeof(buf));
Fawzi Mohamed's avatar
Fawzi Mohamed committed
618
                if (rRead == -1) {
619
                    stop(-1);
620 621
                    return;
                }
Fawzi Mohamed's avatar
Fawzi Mohamed committed
622
                if (rRead == 0)
623
                    return;
624
                qCDebug(toolHandlerLog) << "subprocessHasData read " << QByteArray(buf, rRead);
Fawzi Mohamed's avatar
Fawzi Mohamed committed
625 626
                outputParser.addData(QByteArray(buf, rRead));
                processXml();
627
            }
628
            break;
Fawzi Mohamed's avatar
Fawzi Mohamed committed
629 630
        }
        case XmlEndProcessed:
631
            stop(0);
632 633 634 635 636 637 638 639 640
            return;
        case Stopped:
            return;
        }
    }
}

// IosDeviceToolHandlerPrivate

641
IosDeviceToolHandlerPrivate::IosDeviceToolHandlerPrivate(const IosDeviceType &devType,
642 643
                                                         IosToolHandler *q)
    : IosToolHandlerPrivate(devType, q)
644
{
645 646
    killTimer.setSingleShot(true);

647
    auto deleter = [](QProcess *p) {
648 649 650 651 652
        if (p->state() != QProcess::NotRunning) {
            p->kill();
            if (!p->waitForFinished(2000))
                p->terminate();
        }
653 654 655
        delete p;
    };
    process = std::shared_ptr<QProcess>(new QProcess, deleter);
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678

    // Prepare & set process Environment.
    QProcessEnvironment env(QProcessEnvironment::systemEnvironment());
    foreach (const QString &k, env.keys())
        if (k.startsWith(QLatin1String("DYLD_")))
            env.remove(k);
    QStringList frameworkPaths;
    Utils::FileName xcPath = IosConfigurations::developerPath();
    QString privateFPath = xcPath.appendPath(QLatin1String("Platforms/iPhoneSimulator.platform/Developer/Library/PrivateFrameworks")).toFileInfo().canonicalFilePath();
    if (!privateFPath.isEmpty())
        frameworkPaths << privateFPath;
    QString otherFPath = xcPath.appendPath(QLatin1String("../OtherFrameworks")).toFileInfo().canonicalFilePath();
    if (!otherFPath.isEmpty())
        frameworkPaths << otherFPath;
    QString sharedFPath = xcPath.appendPath(QLatin1String("../SharedFrameworks")).toFileInfo().canonicalFilePath();
    if (!sharedFPath.isEmpty())
        frameworkPaths << sharedFPath;
    frameworkPaths << QLatin1String("/System/Library/Frameworks")
                   << QLatin1String("/System/Library/PrivateFrameworks");
    env.insert(QLatin1String("DYLD_FALLBACK_FRAMEWORK_PATH"), frameworkPaths.join(QLatin1Char(':')));
    qCDebug(toolHandlerLog) << "IosToolHandler runEnv:" << env.toStringList();
    process->setProcessEnvironment(env);

679
    QObject::connect(process.get(), &QProcess::readyReadStandardOutput,
680 681
                     std::bind(&IosDeviceToolHandlerPrivate::subprocessHasData,this));

682
    QObject::connect(process.get(), static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
683 684
                     std::bind(&IosDeviceToolHandlerPrivate::subprocessFinished,this, _1,_2));

685
    QObject::connect(process.get(), &QProcess::errorOccurred,
686 687 688 689
                     std::bind(&IosDeviceToolHandlerPrivate::subprocessError, this, _1));

    QObject::connect(&killTimer, &QTimer::timeout, std::bind(&IosDeviceToolHandlerPrivate::killProcess, this));
}
690

691 692 693 694 695 696 697 698 699 700 701 702 703 704
IosDeviceToolHandlerPrivate::~IosDeviceToolHandlerPrivate()
{
    if (isRunning()) {
        // Disconnect the signals to avoid notifications while destructing.
        // QTCREATORBUG-18147
        process->disconnect();
        // Quit ios-tool gracefully before kill is executed.
        process->write("k\n\r");
        process->closeWriteChannel();
        // Give some time to ios-tool to finish.
        process->waitForFinished(2000);
    }
}

705 706 707
void IosDeviceToolHandlerPrivate::requestTransferApp(const QString &bundlePath,
                                                     const QString &deviceId, int timeout)
{
708 709
    m_bundlePath = bundlePath;
    m_deviceId = deviceId;
710
    QStringList args;
711 712 713
    args << QLatin1String("--id") << deviceId << QLatin1String("--bundle")
         << bundlePath << QLatin1String("--timeout") << QString::number(timeout)
         << QLatin1String("--install");
714 715 716 717 718 719 720 721
    start(IosToolHandler::iosDeviceToolPath(), args);
}

void IosDeviceToolHandlerPrivate::requestRunApp(const QString &bundlePath,
                                                const QStringList &extraArgs,
                                                IosToolHandler::RunKind runType,
                                                const QString &deviceId, int timeout)
{
722 723 724
    m_bundlePath = bundlePath;
    m_deviceId = deviceId;
    m_runKind = runType;
725
    QStringList args;
726 727
    args << QLatin1String("--id") << deviceId << QLatin1String("--bundle")
         << bundlePath << QLatin1String("--timeout") << QString::number(timeout);
728 729
    switch (runType) {
    case IosToolHandler::NormalRun:
730
        args << QLatin1String("--run");
731 732
        break;
    case IosToolHandler::DebugRun:
733
        args << QLatin1String("--debug");
734 735
        break;
    }
736
    args << QLatin1String("--args") << extraArgs;
737 738 739 740 741 742
    op = OpAppRun;
    start(IosToolHandler::iosDeviceToolPath(), args);
}

void IosDeviceToolHandlerPrivate::requestDeviceInfo(const QString &deviceId, int timeout)
{
743
    m_deviceId = deviceId;
744
    QStringList args;
745
    args << QLatin1String("--id") << m_deviceId << QLatin1String("--device-info")
746
         << QLatin1String("--timeout") << QString::number(timeout);
747 748 749 750
    op = OpDeviceInfo;
    start(IosToolHandler::iosDeviceToolPath(), args);
}

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
bool IosDeviceToolHandlerPrivate::isRunning() const
{
    return process && (process->state() != QProcess::NotRunning);
}

void IosDeviceToolHandlerPrivate::start(const QString &exe, const QStringList &args)
{
    Q_ASSERT(process);
    QTC_CHECK(state == NonStarted);
    state = Starting;
    qCDebug(toolHandlerLog) << "running " << exe << args;
    process->start(exe, args);
    state = StartedInferior;
}

766 767

void IosDeviceToolHandlerPrivate::stop(int errorCode)
768
{
769 770 771 772 773 774
    qCDebug(toolHandlerLog) << "IosToolHandlerPrivate::stop";
    State oldState = state;
    state = Stopped;
    switch (oldState) {
    case NonStarted:
        qCWarning(toolHandlerLog) << "IosToolHandler::stop() when state was NonStarted";
775
        Q_FALLTHROUGH();
776 777 778 779 780 781
    case Starting:
        switch (op){
        case OpNone:
            qCWarning(toolHandlerLog) << "IosToolHandler::stop() when op was OpNone";
            break;
        case OpAppTransfer:
782
            didTransferApp(m_bundlePath, m_deviceId, IosToolHandler::Failure);
783 784
            break;
        case OpAppRun:
785
            didStartApp(m_bundlePath, m_deviceId, IosToolHandler::Failure);
786 787 788 789
            break;
        case OpDeviceInfo:
            break;
        }
790
        Q_FALLTHROUGH();
791 792 793 794 795 796 797 798 799 800 801 802
    case StartedInferior:
    case XmlEndProcessed:
        toolExited(errorCode);
        break;
    case Stopped:
        return;
    }
    if (isRunning()) {
        process->write("k\n\r");
        process->closeWriteChannel();
        killTimer.start(1500);
    }
803 804
}

805

806 807
// IosSimulatorToolHandlerPrivate

808
IosSimulatorToolHandlerPrivate::IosSimulatorToolHandlerPrivate(const IosDeviceType &devType,
809
                                                         IosToolHandler *q)
810 811 812
    : IosToolHandlerPrivate(devType, q),
      simCtl(new SimulatorControl)
{
813 814
    QObject::connect(&outputLogger, &LogTailFiles::logMessage,
                     std::bind(&IosToolHandlerPrivate::appOutput, this, _1));
815
}
816

817 818 819 820 821 822 823 824 825
IosSimulatorToolHandlerPrivate::~IosSimulatorToolHandlerPrivate()
{
    foreach (auto f, futureList) {
        if (!f.isFinished())
            f.cancel();
    }
    delete simCtl;
}
void IosSimulatorToolHandlerPrivate::requestTransferApp(const QString &appBundlePath,
826
                                                        const QString &deviceIdentifier, int timeout)
827 828
{
    Q_UNUSED(timeout);
829 830 831
    m_bundlePath = appBundlePath;
    m_deviceId = deviceIdentifier;
    isTransferringApp(m_bundlePath, m_deviceId, 0, 100, "");
832 833 834 835 836 837 838

    auto onSimulatorStart = [this](const SimulatorControl::ResponseData &response) {
        if (!isResponseValid(response))
            return;

        if (response.success) {
            installAppOnSimulator();
839
        } else {
840
            errorMsg(IosToolHandler::tr("Application install on simulator failed. Simulator not running."));
841
            didTransferApp(m_bundlePath, m_deviceId, IosToolHandler::Failure);
842
            emit q->finished(q);
843
        }
844
    };
845

846
    if (SimulatorControl::isSimulatorRunning(m_deviceId))
847 848
        installAppOnSimulator();
    else
849
        futureList << Utils::onResultReady(simCtl->startSimulator(m_deviceId), onSimulatorStart);
850
}
851

852
void IosSimulatorToolHandlerPrivate::requestRunApp(const QString &appBundlePath,
853 854
                                                   const QStringList &extraArgs,
                                                   IosToolHandler::RunKind runType,
855
                                                   const QString &deviceIdentifier, int timeout)
856 857
{
    Q_UNUSED(timeout);
858
    Q_UNUSED(deviceIdentifier);
859 860 861
    m_bundlePath = appBundlePath;
    m_deviceId = m_devType.identifier;
    m_runKind = runType;
862

863
    Utils::FileName appBundle = Utils::FileName::fromString(m_bundlePath);
864
    if (!appBundle.exists()) {
865
        errorMsg(IosToolHandler::tr("Application launch on simulator failed. Invalid bundle path %1")
866 867
                 .arg(m_bundlePath));
        didStartApp(m_bundlePath, m_deviceId, Ios::IosToolHandler::Failure);
868 869 870
        return;
    }

871
    auto onSimulatorStart = [this, extraArgs] (const SimulatorControl::ResponseData &response) {
872
        if (!isResponseValid(response))
873 874
            return;
        if (response.success) {
875
            launchAppOnSimulator(extraArgs);
876
        } else {
877
            errorMsg(IosToolHandler::tr("Application launch on simulator failed. Simulator not running."));
878
            didStartApp(m_bundlePath, m_deviceId, Ios::IosToolHandler::Failure);
879
        }
880
    };
881

882
    if (SimulatorControl::isSimulatorRunning(m_deviceId))
883
        launchAppOnSimulator(extraArgs);
884
    else
885
        futureList << Utils::onResultReady(simCtl->startSimulator(m_deviceId), onSimulatorStart);
886 887 888 889 890
}

void IosSimulatorToolHandlerPrivate::requestDeviceInfo(const QString &deviceId, int timeout)
{
    Q_UNUSED(timeout);
891
    Q_UNUSED(deviceId);
892 893
}

894 895 896 897
bool IosSimulatorToolHandlerPrivate::isRunning() const
{
#ifdef Q_OS_UNIX
    return m_pid > 0 && (kill(m_pid, 0) == 0);
Christian Stenger's avatar
Christian Stenger committed
898
#else
899 900 901 902
    return false;
#endif
}

903
void IosSimulatorToolHandlerPrivate::stop(int errorCode)
904
{
905 906 907 908 909
#ifdef Q_OS_UNIX
    if (m_pid > 0)
        kill(m_pid, SIGKILL);
#endif
    m_pid = -1;
910 911 912 913 914
    foreach (auto f, futureList) {
        if (!f.isFinished())
            f.cancel();
    }

915
    toolExited(errorCode);
916
    q->finished(q);
917 918
}

919 920 921 922 923 924 925
void IosSimulatorToolHandlerPrivate::installAppOnSimulator()
{
    auto onResponseAppInstall = [this](const SimulatorControl::ResponseData &response) {
        if (!isResponseValid(response))
            return;

        if (response.success) {
926 927
            isTransferringApp(m_bundlePath, m_deviceId, 100, 100, "");
            didTransferApp(m_bundlePath, m_deviceId, IosToolHandler::Success);
928
        } else {
929
            errorMsg(IosToolHandler::tr("Application install on simulator failed. %1")
930
                     .arg(QString::fromLocal8Bit(response.commandOutput)));
931
            didTransferApp(m_bundlePath, m_deviceId, IosToolHandler::Failure);
932 933 934 935
        }
        emit q->finished(q);
    };

936 937 938
    isTransferringApp(m_bundlePath, m_deviceId, 20, 100, "");
    auto installFuture = simCtl->installApp(m_deviceId, Utils::FileName::fromString(m_bundlePath));
    futureList << Utils::onResultReady(installFuture, onResponseAppInstall);
939 940
}

941
void IosSimulatorToolHandlerPrivate::launchAppOnSimulator(const QStringList &extraArgs)
942
{
943
    const Utils::FileName appBundle = Utils::FileName::fromString(m_bundlePath);
944
    const QString bundleId = SimulatorControl::bundleIdentifier(appBundle);
945
    const bool debugRun = m_runKind == IosToolHandler::DebugRun;
946
    bool captureConsole = IosConfigurations::xcodeVersion() >= QVersionNumber(8);
947 948
    std::shared_ptr<QTemporaryFile> stdoutFile;
    std::shared_ptr<QTemporaryFile> stderrFile;
949 950

    if (captureConsole) {
951
        const QString fileTemplate = CONSOLE_PATH_TEMPLATE.arg(m_deviceId).arg(bundleId);
952 953
        stdoutFile.reset(new QTemporaryFile(fileTemplate + ".stdout"));
        stderrFile.reset(new QTemporaryFile(fileTemplate + ".stderr"));
954 955 956 957 958 959 960 961 962 963 964

        captureConsole = stdoutFile->open() && stderrFile->open();
        if (!captureConsole)
            errorMsg(IosToolHandler::tr("Cannot capture console output from %1. "
                                        "Error redirecting output to %2.*")
                     .arg(bundleId).arg(fileTemplate));
    } else {
        errorMsg(IosToolHandler::tr("Cannot capture console output from %1. "
                    "Install Xcode 8 or later.").arg(bundleId));
    }

965 966 967
    auto monitorPid = [this](QFutureInterface<void> &fi, qint64 pid) {
#ifdef Q_OS_UNIX
        do {
968 969
            // Poll every 1 sec to check whether the app is running.
            QThread::msleep(1000);
970
        } while (!fi.isCanceled() && kill(pid, 0) == 0);
Thomas Hartmann's avatar
Thomas Hartmann committed
971 972
#else
    Q_UNUSED(pid);
973
#endif
974 975 976 977
        // Future is cancelled if the app is stopped from the qt creator.
        if (!fi.isCanceled())
            stop(0);
    };
978

979
    auto onResponseAppLaunch = [=](const SimulatorControl::ResponseData &response) {
980 981
        if (!isResponseValid(response))
            return;
982
        if (response.success) {
983 984 985
            m_pid = response.pID;
            gotInferiorPid(m_bundlePath, m_deviceId, response.pID);
            didStartApp(m_bundlePath, m_deviceId, Ios::IosToolHandler::Success);
986
            // Start monitoring app's life signs.
987 988 989 990
            futureList << Utils::runAsync(monitorPid, response.pID);
            if (captureConsole)
                futureList << Utils::runAsync(&LogTailFiles::exec, &outputLogger, stdoutFile,
                                              stderrFile);
991
        } else {
992
            m_pid = -1;
993
            errorMsg(IosToolHandler::tr("Application launch on simulator failed. %1")
994
                     .arg(QString::fromLocal8Bit(response.commandOutput)));
995
            didStartApp(m_bundlePath, m_deviceId, Ios::IosToolHandler::Failure);
996 997 998 999
            stop(-1);
            q->finished(q);
        }
    };
1000 1001

    futureList << Utils::onResultReady(
1002
                      simCtl->launchApp(m_deviceId, bundleId, debugRun, extraArgs,
1003 1004 1005
                                        captureConsole ? stdoutFile->fileName() : QString(),
                                        captureConsole ? stderrFile->fileName() : QString()),
                      onResponseAppLaunch);
1006 1007 1008 1009
}

bool IosSimulatorToolHandlerPrivate::isResponseValid(const SimulatorControl::ResponseData &responseData)
{
1010
    if (responseData.simUdid.compare(m_deviceId) != 0) {
1011 1012 1013
        errorMsg(IosToolHandler::tr("Invalid simulator response. Device Id mismatch. "
                                    "Device Id = %1 Response Id = %2")
                 .arg(responseData.simUdid)
1014
                 .arg(m_deviceId));
1015 1016 1017 1018 1019 1020
        emit q->finished(q);
        return false;
    }
    return true;
}

1021 1022 1023 1024
} // namespace Internal

QString IosToolHandler::iosDeviceToolPath()
{
1025
    QString res = Core::ICore::libexecPath() + QLatin1String("/ios/iostool");
1026 1027 1028
    return res;
}

1029
IosToolHandler::IosToolHandler(const Internal::IosDeviceType &devType, QObject *parent) :
1030 1031
    QObject(parent)
{
1032
    if (devType.type == Internal::IosDeviceType::IosDevice)
1033 1034 1035 1036 1037
        d = new Internal::IosDeviceToolHandlerPrivate(devType, this);
    else
        d = new Internal::IosSimulatorToolHandlerPrivate(devType, this);
}

1038 1039 1040 1041 1042
IosToolHandler::~IosToolHandler()
{
    delete d;
}

1043 1044
void IosToolHandler::stop()
{
1045
    d->stop(-1);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
}

void IosToolHandler::requestTransferApp(const QString &bundlePath, const QString &deviceId,
                                        int timeout)
{
    d->requestTransferApp(bundlePath, deviceId, timeout);
}

void IosToolHandler::requestRunApp(const QString &bundlePath, const QStringList &extraArgs,
                                   RunKind runType, const QString &deviceId, int timeout)
{
    d->requestRunApp(bundlePath, extraArgs, runType, deviceId, timeout);
}

void IosToolHandler::requestDeviceInfo(const QString &deviceId, int timeout)
{
    d->requestDeviceInfo(deviceId, timeout);
}

1065
bool IosToolHandler::isRunning() const
1066 1067 1068 1069 1070
{
    return d->isRunning();
}

} // namespace Ios
1071 1072

#include "iostoolhandler.moc"