aboutsummaryrefslogtreecommitdiffstats
path: root/src/tools/iostool/iostool.cpp
blob: 56648a2fd5bed8d287b7ae6a634c9c8e3c531a43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** 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
** 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.
**
** 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.
**
****************************************************************************/

#include "iostool.h"

#include "relayserver.h"
#include "gdbrunner.h"

#include <QCommandLineParser>
#include <QCoreApplication>
#include <QRegularExpression>
#include <QTimer>
#include <QThread>

namespace Ios {

IosTool::IosTool(QObject *parent):
    QObject(parent),
    m_xmlWriter(&m_outputFile)
{
    m_outputFile.open(stdout, QIODevice::WriteOnly, QFileDevice::DontCloseHandle);
    m_xmlWriter.setAutoFormatting(true);
}

IosTool::~IosTool()
{
}

void IosTool::run(const QStringList &args)
{
    IosDeviceManager *manager = IosDeviceManager::instance();
    QString deviceId;
    QString bundlePath;
    bool deviceInfo = false;
    bool printHelp = false;
    int timeout = 1000;
    QStringList extraArgs;

    m_xmlWriter.writeStartDocument();
    m_xmlWriter.writeStartElement(QLatin1String("query_result"));

    QCommandLineParser cmdLineParser;
    cmdLineParser.setOptionsAfterPositionalArgumentsMode(QCommandLineParser::ParseAsPositionalArguments);
    cmdLineParser.setApplicationDescription("iOS Deployment and run helper");

    const QList<QCommandLineOption> options{
        QCommandLineOption(QStringList{"h", "help"}),
        QCommandLineOption(QStringList{"i", "id"}, "target device id", "id"),
        QCommandLineOption(QStringList{"b", "bundle"}, "path to the target bundle.app", "bundle"),
        QCommandLineOption("delta-path", "path to the deploy delta directory", "delta-path"),
        QCommandLineOption("install", "Install a bundle on a device"),
        QCommandLineOption(QStringList{"r", "run"}, "Run the bundle on the device"),
        QCommandLineOption(QStringList{"d", "debug"}, "Debug the bundle on the device"),
        QCommandLineOption("device-info", "Retrieve information about the selected device"),
        QCommandLineOption(QStringList{"t", "timeout"}, "Operation timeout (s)", "timeout"),
        QCommandLineOption(QStringList{"v", "verbose"}, "Verbose output"),
    };

    cmdLineParser.addOptions(options);

    cmdLineParser.process(args);

    if (cmdLineParser.isSet("verbose"))
        m_echoRelays = true;

    if (cmdLineParser.isSet("id"))
        deviceId = cmdLineParser.value("id");

    if (cmdLineParser.isSet("bundle"))
        bundlePath = cmdLineParser.value("bundle");

    if (cmdLineParser.isSet("delta-path"))
        m_deltasPath = cmdLineParser.value("delta-path");

    if (cmdLineParser.isSet("install")) {
        m_requestedOperation = IosDeviceManager::AppOp(m_requestedOperation
                                                       | IosDeviceManager::Install);
    }
    else if (cmdLineParser.isSet("run")) {
        m_requestedOperation = IosDeviceManager::AppOp(m_requestedOperation | IosDeviceManager::Run);
    }

    if (cmdLineParser.isSet("debug")) {
        m_requestedOperation = IosDeviceManager::AppOp(m_requestedOperation | IosDeviceManager::Run);
        m_debug = true;
    }

    if (cmdLineParser.isSet("device-info"))
        deviceInfo = true;

    if (cmdLineParser.isSet("timeout")) {
        bool ok = false;
        timeout = cmdLineParser.value("timeout").toInt(&ok);
        if (!ok || timeout < 0) {
            writeMsg("timeout value should be an integer");
            printHelp = true;
        }
    }

    extraArgs = cmdLineParser.positionalArguments();

    if (printHelp || cmdLineParser.isSet("help")) {
        m_xmlWriter.writeStartElement(QLatin1String("msg"));
        m_xmlWriter.writeCharacters(
            QLatin1String("iostool [--id <device_id>] [--bundle <bundle.app>] [--delta-path] "
                          "[--install] [--run] [--debug]\n"));
        m_xmlWriter.writeCharacters(QLatin1String(
            "    [--device-info] [--timeout <timeout_in_ms>] [--verbose]\n")); // to do pass in env as stub does
        m_xmlWriter.writeCharacters(QLatin1String("    [-- <arguments for the target app>]"));
        m_xmlWriter.writeEndElement();
        doExit(-1);
        return;
    }

    m_outputFile.flush();
    connect(manager, &IosDeviceManager::isTransferringApp, this, &IosTool::isTransferringApp);
    connect(manager, &IosDeviceManager::didTransferApp, this, &IosTool::didTransferApp);
    connect(manager, &IosDeviceManager::didStartApp, this, &IosTool::didStartApp);
    connect(manager, &IosDeviceManager::deviceInfo, this, &IosTool::deviceInfo);
    connect(manager, &IosDeviceManager::appOutput, this, &IosTool::appOutput);
    connect(manager, &IosDeviceManager::errorMsg, this, &IosTool::errorMsg);
    manager->watchDevices();
    const QRegularExpression qmlPortRe(QLatin1String("-qmljsdebugger=port:([0-9]+)"));
    for (const QString &arg : extraArgs) {
        const QRegularExpressionMatch match = qmlPortRe.match(arg);
        if (match.hasMatch()) {
            bool ok;
            int qmlPort = match.captured(1).toInt(&ok);
            if (ok && qmlPort > 0 && qmlPort <= 0xFFFF)
                m_qmlPort = match.captured(1);
            break;
        }
    }
    if (deviceInfo) {
        if (!bundlePath.isEmpty())
            writeMsg("--device-info overrides --bundle");
        ++m_operationsRemaining;
        manager->requestDeviceInfo(deviceId, timeout);
    } else if (!bundlePath.isEmpty()) {
        switch (m_requestedOperation) {
        case IosDeviceManager::None:
            break;
        case IosDeviceManager::Install:
        case IosDeviceManager::Run:
            ++m_operationsRemaining;
            break;
        case IosDeviceManager::InstallAndRun:
            m_operationsRemaining += 2;
            break;
        }
        m_maxProgress = 200;
        manager->requestAppOp(bundlePath, extraArgs, m_requestedOperation, deviceId, timeout, m_deltasPath);
    }
    if (m_operationsRemaining == 0)
        doExit(0);
}

void IosTool::stopXml(int errorCode)
{
    QMutexLocker l(&m_xmlMutex);
    m_xmlWriter.writeEmptyElement(QLatin1String("exit"));
    m_xmlWriter.writeAttribute(QLatin1String("code"), QString::number(errorCode));
    m_xmlWriter.writeEndElement(); // result element (hopefully)
    m_xmlWriter.writeEndDocument();
    m_outputFile.flush();
}

void IosTool::doExit(int errorCode)
{
    stopXml(errorCode);
    QCoreApplication::exit(errorCode); // sometime does not really exit
    exit(errorCode);
}

void IosTool::isTransferringApp(const QString &bundlePath, const QString &deviceId, int progress,
                                const QString &info)
{
    Q_UNUSED(bundlePath)
    Q_UNUSED(deviceId)
    QMutexLocker l(&m_xmlMutex);
    m_xmlWriter.writeStartElement(QLatin1String("status"));
    m_xmlWriter.writeAttribute(QLatin1String("progress"), QString::number(progress));
    m_xmlWriter.writeAttribute(QLatin1String("max_progress"), QString::number(m_maxProgress));
    m_xmlWriter.writeCharacters(info);
    m_xmlWriter.writeEndElement();
    m_outputFile.flush();
}

void IosTool::didTransferApp(const QString &bundlePath, const QString &deviceId,
                             IosDeviceManager::OpStatus status)
{
    Q_UNUSED(bundlePath)
    Q_UNUSED(deviceId)
    {
        QMutexLocker l(&m_xmlMutex);
        if (status == IosDeviceManager::Success) {
            m_xmlWriter.writeStartElement(QLatin1String("status"));
            m_xmlWriter.writeAttribute(QLatin1String("progress"), QString::number(m_maxProgress));
            m_xmlWriter.writeAttribute(QLatin1String("max_progress"), QString::number(m_maxProgress));
            m_xmlWriter.writeCharacters(QLatin1String("App Transferred"));
            m_xmlWriter.writeEndElement();
        }
        m_xmlWriter.writeEmptyElement(QLatin1String("app_transfer"));
        m_xmlWriter.writeAttribute(QLatin1String("status"),
                           (status == IosDeviceManager::Success) ?
                               QLatin1String("SUCCESS") :
                               QLatin1String("FAILURE"));
        //out.writeCharacters(QString()); // trigger a complete closing of the empty element
        m_outputFile.flush();
    }
    if (status != IosDeviceManager::Success || --m_operationsRemaining == 0)
        doExit((status == IosDeviceManager::Success) ? 0 : -1);
}

void IosTool::didStartApp(const QString &bundlePath, const QString &deviceId,
                          IosDeviceManager::OpStatus status, ServiceConnRef conn, int gdbFd,
                          DeviceSession *deviceSession)
{
    Q_UNUSED(bundlePath)
    Q_UNUSED(deviceId)
    {
        QMutexLocker l(&m_xmlMutex);
        m_xmlWriter.writeEmptyElement(QLatin1String("app_started"));
        m_xmlWriter.writeAttribute(QLatin1String("status"),
                           (status == IosDeviceManager::Success) ?
                               QLatin1String("SUCCESS") :
                               QLatin1String("FAILURE"));
        //out.writeCharacters(QString()); // trigger a complete closing of the empty element
        m_outputFile.flush();
    }
    if (status != IosDeviceManager::Success || m_requestedOperation == IosDeviceManager::Install) {
        doExit();
        return;
    }
    if (gdbFd <= 0) {
        writeMsg("no gdb connection");
        doExit(-2);
        return;
    }
    if (m_requestedOperation != IosDeviceManager::InstallAndRun && m_requestedOperation != IosDeviceManager::Run) {
        writeMsg(QString::fromLatin1("unexpected appOp value %1").arg(m_requestedOperation));
        doExit(-3);
        return;
    }
    if (deviceSession) {
        int qmlPort = deviceSession->qmljsDebugPort();
        if (qmlPort) {
            m_qmlServer = std::make_unique<QmlRelayServer>(this, qmlPort, deviceSession);
            m_qmlServer->startServer();
        }
    }
    if (m_debug) {
        m_gdbServer = std::make_unique<GdbRelayServer>(this, gdbFd, conn);
        if (!m_gdbServer->startServer()) {
            doExit(-4);
            return;
        }
    }
    {
        QMutexLocker l(&m_xmlMutex);
        m_xmlWriter.writeStartElement(QLatin1String("server_ports"));
        m_xmlWriter.writeAttribute(QLatin1String("gdb_server"),
                           QString::number(m_gdbServer ? m_gdbServer->serverPort() : -1));
        m_xmlWriter.writeAttribute(QLatin1String("qml_server"),
                           QString::number(m_qmlServer ? m_qmlServer->serverPort() : -1));
        m_xmlWriter.writeEndElement();
        m_outputFile.flush();
    }
    if (!m_debug) {
        m_gdbRunner = std::make_unique<GdbRunner>(this, conn);

        // we should not stop the event handling of the main thread
        // all output moves to the new thread (other option would be to signal it back)
        QThread *gdbProcessThread = new QThread();
        m_gdbRunner->moveToThread(gdbProcessThread);
        QObject::connect(gdbProcessThread, &QThread::started, m_gdbRunner.get(), &GdbRunner::run);
        QObject::connect(m_gdbRunner.get(), &GdbRunner::finished, gdbProcessThread, &QThread::quit);
        QObject::connect(gdbProcessThread, &QThread::finished,
                         gdbProcessThread, &QObject::deleteLater);
        gdbProcessThread->start();

        new std::thread([this]() -> void { readStdin();});
    }
}

void IosTool::writeMsg(const char *msg)
{
    writeMsg(QString::fromLatin1(msg));
}

void IosTool::writeMsg(const QString &msg)
{
    QMutexLocker l(&m_xmlMutex);
    m_xmlWriter.writeStartElement(QLatin1String("msg"));
    writeTextInElement(msg);
    m_xmlWriter.writeCharacters(QLatin1String("\n"));
    m_xmlWriter.writeEndElement();
    m_outputFile.flush();
}

void IosTool::writeMaybeBin(const QString &extraMsg, const char *msg, quintptr len)
{
    char *buf2 = new char[len * 2 + 4];
    buf2[0] = '[';
    const char toHex[] = "0123456789abcdef";
    for (quintptr i = 0; i < len; ++i) {
        buf2[2 * i + 1] = toHex[(0xF & (msg[i] >> 4))];
        buf2[2 * i + 2] = toHex[(0xF & msg[i])];
    }
    buf2[2 * len + 1] = ']';
    buf2[2 * len + 2] = ' ';
    buf2[2 * len + 3] = 0;

    QMutexLocker l(&m_xmlMutex);
    m_xmlWriter.writeStartElement(QLatin1String("msg"));
    m_xmlWriter.writeCharacters(extraMsg);
    m_xmlWriter.writeCharacters(QLatin1String(buf2));
    for (quintptr i = 0; i < len; ++i) {
        if (msg[i] < 0x20 || msg[i] > 0x7f)
            buf2[i] = '_';
        else
            buf2[i] = msg[i];
    }
    buf2[len] = 0;
    m_xmlWriter.writeCharacters(QLatin1String(buf2));
    delete[] buf2;
    m_xmlWriter.writeEndElement();
    m_outputFile.flush();
}

void IosTool::deviceInfo(const QString &deviceId, const IosDeviceManager::Dict &devInfo)
{
    Q_UNUSED(deviceId)
    {
        QMutexLocker l(&m_xmlMutex);
        m_xmlWriter.writeTextElement(QLatin1String("device_id"), deviceId);
        m_xmlWriter.writeStartElement(QLatin1String("device_info"));
        for (auto i = devInfo.cbegin(); i != devInfo.cend(); ++i) {
            m_xmlWriter.writeStartElement(QLatin1String("item"));
            m_xmlWriter.writeTextElement(QLatin1String("key"), i.key());
            m_xmlWriter.writeTextElement(QLatin1String("value"), i.value());
            m_xmlWriter.writeEndElement();
        }
        m_xmlWriter.writeEndElement();
        m_outputFile.flush();
    }
    doExit();
}

void IosTool::writeTextInElement(const QString &output)
{
    const QRegularExpression controlCharRe(QLatin1String("[\x01-\x08]|\x0B|\x0C|[\x0E-\x1F]|\\0000"));
    int pos = 0;
    int oldPos = 0;

    while ((pos = output.indexOf(controlCharRe, pos)) != -1) {
        QMutexLocker l(&m_xmlMutex);
        m_xmlWriter.writeCharacters(output.mid(oldPos, pos - oldPos));
        m_xmlWriter.writeEmptyElement(QLatin1String("control_char"));
        m_xmlWriter.writeAttribute(QLatin1String("code"), QString::number(output.at(pos).toLatin1()));
        pos += 1;
        oldPos = pos;
    }
    m_xmlWriter.writeCharacters(output.mid(oldPos, output.length() - oldPos));
}

void IosTool::appOutput(const QString &output)
{
    QMutexLocker l(&m_xmlMutex);
    if (!m_inAppOutput)
        m_xmlWriter.writeStartElement(QLatin1String("app_output"));
    writeTextInElement(output);
    if (!m_inAppOutput)
        m_xmlWriter.writeEndElement();
    m_outputFile.flush();
}

void IosTool::readStdin()
{
    int c = getchar();
    if (c == 'k') {
        QMetaObject::invokeMethod(this, "stopGdbRunner");
        errorMsg(QLatin1String("iostool: Killing inferior.\n"));
    } else if (c != EOF) {
        errorMsg(QLatin1String("iostool: Unexpected character in stdin, stop listening.\n"));
    }
}

void IosTool::errorMsg(const QString &msg)
{
    writeMsg(msg);
}

void IosTool::stopGdbRunner()
{
    if (m_gdbRunner) {
        m_gdbRunner->stop(0);
        QTimer::singleShot(100, this, &IosTool::stopGdbRunner2);
    }
}

void IosTool::stopGdbRunner2()
{
    if (m_gdbRunner)
        m_gdbRunner->stop(1);
}

void IosTool::stopRelayServers(int errorCode)
{
    if (echoRelays())
        writeMsg("gdbServerStops");
    if (m_qmlServer)
        m_qmlServer->stopServer();
    if (m_gdbServer)
        m_gdbServer->stopServer();
    doExit(errorCode);
}

}