summaryrefslogtreecommitdiff
path: root/src/tools/iostool/main.cpp
blob: 323e31c79abf44727f707d449ee394b917454f8f (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
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
468
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include <qglobal.h>
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#include <QApplication>
#else
#include <QGuiApplication>
#endif
#include <QTextStream>
#include <QDebug>
#include <QXmlStreamWriter>
#include <QFile>
#include <QMapIterator>
#include <QScopedArrayPointer>
#include <QTcpServer>
#include <QSocketNotifier>
#include <QTcpSocket>

#include "iosdevicemanager.h"
#include <sys/types.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#ifdef Q_OS_UNIX
#include <unistd.h>
#include <fcntl.h>
#endif

static const bool debugGdbEchoServer = false;

class IosTool: public QObject {
    Q_OBJECT
public:
    IosTool(QObject *parent = 0);
    virtual ~IosTool();
    void run(const QStringList &args);
    void doExit(int errorCode = 0);
    void writeMsg(const char *msg);
    void writeMsg(const QString &msg);
    void stopXml(int errorCode);
private slots:
    void isTransferringApp(const QString &bundlePath, const QString &deviceId, int progress,
                           const QString &info);
    void didTransferApp(const QString &bundlePath, const QString &deviceId,
                        Ios::IosDeviceManager::OpStatus status);
    void didStartApp(const QString &bundlePath, const QString &deviceId,
                     Ios::IosDeviceManager::OpStatus status, int gdbFd);
    void deviceInfo(const QString &deviceId, const Ios::IosDeviceManager::Dict &info);
    void appOutput(const QString &output);
    void errorMsg(const QString &msg);
    void handleNewConnection();
    void handleGdbServerSocketHasData(int socket);
    void handleCreatorHasData();
    void handleCreatorHasError(QAbstractSocket::SocketError error);
private:
    bool startServer();
    void stopGdbServer(int errorCode = 0);

    int maxProgress;
    int opLeft;
    bool debug;
    bool ipv6;
    bool inAppOutput;
    bool splitAppOutput; // as QXmlStreamReader reports the text attributes atomically it is better to split
    Ios::IosDeviceManager::AppOp appOp;
    QFile outFile;
    QXmlStreamWriter out;
    int gdbFileDescriptor;
    QTcpSocket *creatorSocket;
    QSocketNotifier *gdbServerNotifier;
    QTcpServer gdbServer;
};

IosTool::IosTool(QObject *parent):
    QObject(parent),
    maxProgress(0),
    opLeft(0),
    debug(false),
    ipv6(false),
    inAppOutput(false),
    splitAppOutput(true),
    appOp(Ios::IosDeviceManager::None),
    outFile(),
    out(&outFile),
    gdbFileDescriptor(-1),
    creatorSocket(0),
    gdbServerNotifier(0)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    outFile.open(stdout, QIODevice::WriteOnly, QFile::DontCloseHandle);
#else
    outFile.open(stdout, QIODevice::WriteOnly, QFileDevice::DontCloseHandle);
#endif
    out.setAutoFormatting(true);
    out.setCodec("UTF-8");
}

IosTool::~IosTool()
{
    delete creatorSocket; // not strictly required
    delete gdbServerNotifier; // not strictly required
}

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

    out.writeStartDocument();
    out.writeStartElement(QLatin1String("query_result"));
    for (int iarg = 1; iarg < args.size(); ++iarg) {
        const QString &arg = args[iarg];
        if (arg == QLatin1String("-device-id")) {
            if (++iarg == args.size()) {
                writeMsg("missing device id value after -device-id");
                printHelp = true;
            }
            deviceId = args.value(iarg);
        } else if (arg == QLatin1String("-bundle")) {
            if (++iarg == args.size()) {
                writeMsg("missing bundle path after -bundle");
                printHelp = true;
            }
            bundlePath = args.value(iarg);
        } else if (arg == QLatin1String("-deploy")) {
            appOp = Ios::IosDeviceManager::AppOp(appOp | Ios::IosDeviceManager::Install);
        } else if (arg == QLatin1String("-run")) {
            appOp = Ios::IosDeviceManager::AppOp(appOp | Ios::IosDeviceManager::Run);
        } else if (arg == QLatin1String("-ipv6")) {
            ipv6 = true;
        } else if (arg == QLatin1String("-debug")) {
            appOp = Ios::IosDeviceManager::AppOp(appOp | Ios::IosDeviceManager::Run);
            debug = true;
        } else if (arg == QLatin1String("-device-info")) {
            deviceInfo = true;
        } else if (arg == QLatin1String("-timeout")) {
            if (++iarg == args.size()) {
                writeMsg("missing timeout value after -timeout");
                printHelp = true;
            }
            bool ok = false;
            int tOut = args.value(iarg).toInt(&ok);
            if (ok && tOut > 0) {
                timeout = tOut;
            } else {
                writeMsg("timeout value should be an integer");
                printHelp = true;
            }
        } else if (arg == QLatin1String("-extra-args")) {
            ++iarg;
            extraArgs = args.mid(iarg, args.size() - iarg);
        } else if (arg == QLatin1String("-help") || arg == QLatin1String("--help")) {
            printHelp = true;
        } else {
            writeMsg(QString::fromLatin1("unexpected argument '%1'").arg(arg));
        }
    }
    if (printHelp) {
        out.writeStartElement(QLatin1String("msg"));
        out.writeCharacters(QLatin1String("iosTool [-device-id <deviceId>] [-bundle <pathToBundle>] [-deploy] [-run] [-debug]\n"));
        out.writeCharacters(QLatin1String("    [-device-info] [-timeout <timeoutIn_ms>]\n")); // to do pass in env as stub does
        out.writeCharacters(QLatin1String("    [-extra-args <arguments for the target app>]"));
        out.writeEndElement();
        doExit(-1);
        return;
    }
    outFile.flush();
    connect(manager,SIGNAL(isTransferringApp(QString,QString,int,QString)),
            SLOT(isTransferringApp(QString,QString,int,QString)));
    connect(manager,SIGNAL(didTransferApp(QString,QString,Ios::IosDeviceManager::OpStatus)),
            SLOT(didTransferApp(QString,QString,Ios::IosDeviceManager::OpStatus)));
    connect(manager,SIGNAL(didStartApp(QString,QString,Ios::IosDeviceManager::OpStatus,int)),
            SLOT(didStartApp(QString,QString,Ios::IosDeviceManager::OpStatus,int)));
    connect(manager,SIGNAL(deviceInfo(QString,Ios::IosDeviceManager::Dict)),
            SLOT(deviceInfo(QString,Ios::IosDeviceManager::Dict)));
    connect(manager,SIGNAL(appOutput(QString)), SLOT(appOutput(QString)));
    connect(manager,SIGNAL(errorMsg(QString)), SLOT(errorMsg(QString)));
    manager->watchDevices();
    if (deviceInfo) {
        if (!bundlePath.isEmpty())
            writeMsg("-device-info overrides bundlePath");
        ++opLeft;
        manager->requestDeviceInfo(deviceId, timeout);
    } else if (!bundlePath.isEmpty()) {
        switch (appOp) {
        case Ios::IosDeviceManager::None:
            break;
        case Ios::IosDeviceManager::Install:
        case Ios::IosDeviceManager::Run:
            ++opLeft;
            break;
        case Ios::IosDeviceManager::InstallAndRun:
            opLeft += 2;
            break;
        }
        maxProgress = 200;
        manager->requestAppOp(bundlePath, extraArgs, appOp, deviceId, timeout);
    }
    if (opLeft == 0)
        doExit(0);
}

void IosTool::stopXml(int errorCode)
{
    out.writeEmptyElement(QLatin1String("exit"));
    out.writeAttribute(QLatin1String("code"), QString::number(errorCode));
    out.writeEndElement(); // result element (hopefully)
    out.writeEndDocument();
    outFile.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);
    out.writeStartElement(QLatin1String("status"));
    out.writeAttribute(QLatin1String("progress"), QString::number(progress));
    out.writeAttribute(QLatin1String("max_progress"), QString::number(maxProgress));
    out.writeCharacters(info);
    out.writeEndElement();
    outFile.flush();
}

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

void IosTool::didStartApp(const QString &bundlePath, const QString &deviceId,
                             Ios::IosDeviceManager::OpStatus status, int gdbFd)
{
    Q_UNUSED(bundlePath);
    Q_UNUSED(deviceId);
    out.writeEmptyElement(QLatin1String("app_started"));
    out.writeAttribute(QLatin1String("status"),
                       (status == Ios::IosDeviceManager::Success) ?
                           QLatin1String("SUCCESS") :
                           QLatin1String("FAILURE"));
    //out.writeCharacters(QString()); // trigger a complete closing of the empty element
    outFile.flush();
    if (status != Ios::IosDeviceManager::Success || appOp == Ios::IosDeviceManager::Install) {
        doExit();
        return;
    }
    if (gdbFd <= 0) {
        writeMsg("no gdb connection");
        doExit(-2);
        return;
    }
    if (appOp != Ios::IosDeviceManager::InstallAndRun && appOp != Ios::IosDeviceManager::Run) {
        writeMsg(QString::fromLatin1("unexpected appOp value %1").arg(appOp));
        doExit(-3);
        return;
    }
    if (debug) {
        gdbFileDescriptor=gdbFd;
        if (!startServer()) {
            doExit(-4);
            return;
        }
        out.writeTextElement(QLatin1String("gdb_server_port"),
                             QString::number(gdbServer.serverPort()));
        outFile.flush();
    } else {
        if (!splitAppOutput) {
            out.writeStartElement(QLatin1String("app_output"));
            inAppOutput = true;
        }
        outFile.flush();
        Ios::IosDeviceManager::instance()->processGdbServer(gdbFd);
        if (!splitAppOutput) {
            inAppOutput = false;
            out.writeEndElement();
        }
        outFile.flush();
        close(gdbFd);
        doExit();
    }
}

void IosTool::writeMsg(const char *msg)
{
    out.writeTextElement(QLatin1String("msg"), QLatin1String(msg));
    outFile.flush();
}

void IosTool::writeMsg(const QString &msg)
{
    out.writeTextElement(QLatin1String("msg"), msg);
    outFile.flush();
}

void IosTool::deviceInfo(const QString &deviceId, const Ios::IosDeviceManager::Dict &devInfo)
{
    Q_UNUSED(deviceId);
    out.writeTextElement(QLatin1String("device_id"), deviceId);
    out.writeStartElement(QLatin1String("device_info"));
    QMapIterator<QString,QString> i(devInfo);
    while (i.hasNext()) {
        i.next();
        out.writeStartElement(QLatin1String("item"));
        out.writeTextElement(QLatin1String("key"), i.key());
        out.writeTextElement(QLatin1String("value"), i.value());
        out.writeEndElement();
    }
    out.writeEndElement();
    outFile.flush();
    doExit();
}

void IosTool::appOutput(const QString &output)
{
    if (inAppOutput)
        out.writeCharacters(output);
    else
        out.writeTextElement(QLatin1String("app_output"), output);
    outFile.flush();
}

void IosTool::errorMsg(const QString &msg)
{
    writeMsg(msg + QLatin1Char('\n'));
}

void IosTool::handleNewConnection()
{
    if (creatorSocket) {
        gdbServer.close();
        QTcpSocket *s = gdbServer.nextPendingConnection();
        delete s;
        return;
    }
    creatorSocket = gdbServer.nextPendingConnection();
    connect(creatorSocket, SIGNAL(readyRead()), SLOT(handleCreatorHasData()));
    connect(creatorSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            SLOT(handleCreatorHasError(QAbstractSocket::SocketError)));
    gdbServerNotifier = new QSocketNotifier(gdbFileDescriptor, QSocketNotifier::Read, this);
    connect(gdbServerNotifier, SIGNAL(activated(int)), SLOT(handleGdbServerSocketHasData(int)));
    gdbServer.close();
}

void IosTool::handleGdbServerSocketHasData(int socket)
{
    gdbServerNotifier->setEnabled(false);
    char buf[255];
    while (true) {
        qptrdiff rRead = read(socket, &buf, sizeof(buf)-1);
        if (rRead == -1) {
            if (errno == EINTR)
                continue;
            if (errno == EAGAIN) {
                gdbServerNotifier->setEnabled(true);
                return;
            }
            errorMsg(qt_error_string(errno));
            close(socket);
            stopGdbServer(-1);
            return;
        }
        if (rRead == 0) {
            stopGdbServer(0);
            return;
        }
        if (debugGdbEchoServer) {
            writeMsg("gdbServerReplies:");
            buf[rRead] = 0;
            writeMsg(buf);
        }
        qint64 pos = 0;
        while (true) {
            qint64 writtenNow = creatorSocket->write(buf + int(pos), rRead);
            if (writtenNow == -1) {
                writeMsg(creatorSocket->errorString());
                stopGdbServer(-1);
                return;
            }
            if (writtenNow < rRead) {
                pos += writtenNow;
                rRead -= qptrdiff(writtenNow);
            } else {
                break;
            }
        }
    }
}

void IosTool::stopGdbServer(int errorCode)
{
    if (debugGdbEchoServer)
        writeMsg("gdbServerStops");
    if (!creatorSocket)
        return;
    if (gdbFileDescriptor > 0) {
        ::close(gdbFileDescriptor);
        gdbFileDescriptor = -1;
        if (gdbServerNotifier)
            delete gdbServerNotifier;
    }
    if (creatorSocket->isOpen())
        creatorSocket->close();
    delete creatorSocket;
    doExit(errorCode);
}

void IosTool::handleCreatorHasData()
{
    char buf[255];
    while (true) {
        qint64 toRead = creatorSocket->bytesAvailable();
        if (qint64(sizeof(buf)-1) < toRead)
            toRead = sizeof(buf)-1;
        qint64 rRead = creatorSocket->read(buf, toRead);
        if (rRead == -1) {
            errorMsg(creatorSocket->errorString());
            stopGdbServer();
            return;
        }
        if (rRead == 0) {
            if (!creatorSocket->isOpen())
                stopGdbServer();
            return;
        }
        int pos = 0;
        int irep = 0;
        if (debugGdbEchoServer) {
            writeMsg("sendToGdbServer:");
            buf[rRead] = 0;
            writeMsg(buf);
        }
        while (true) {
            qptrdiff written = write(gdbFileDescriptor, buf + pos, rRead);
            if (written == -1) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN) {
                    if (++irep > 10) {
                        sleep(1);
                        irep = 0;
                    }
                    continue;
                }
                errorMsg(creatorSocket->errorString());
                stopGdbServer();
                return;
            }
            if (written == 0) {
                stopGdbServer();
                return;
            }
            if (written < rRead) {
                pos += written;
                rRead -= written;
            } else {
                break;
            }
        }
    }
}

void IosTool::handleCreatorHasError(QAbstractSocket::SocketError error)
{
    errorMsg(tr("iOS Debugging connection to creator failed with error %1").arg(error));
    stopGdbServer();
}

bool IosTool::startServer()
{
    if (gdbFileDescriptor <= 0 || gdbServer.isListening() || creatorSocket != 0)
        return false;
    fcntl(gdbFileDescriptor, F_SETFL, fcntl(gdbFileDescriptor, F_GETFL, 0) | O_NONBLOCK);
    gdbServer.setMaxPendingConnections(1);
    connect(&gdbServer, SIGNAL(newConnection()), SLOT(handleNewConnection()));
    if (ipv6)
        return gdbServer.listen(QHostAddress(QHostAddress::LocalHostIPv6), 0);
    else
        return gdbServer.listen(QHostAddress(QHostAddress::LocalHost), 0);
}


int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    QApplication a(argc, argv);
#else
    QGuiApplication a(argc, argv);
#endif
    IosTool tool;
    tool.run(QCoreApplication::arguments());
    int res = a.exec();
    exit(res);
}

#include "main.moc"