androidrunner.cpp 14.7 KB
Newer Older
BogDan Vatra's avatar
BogDan Vatra committed
1
2
/**************************************************************************
**
3
** Copyright (c) 2014 BogDan Vatra <bog_dan_ro@yahoo.com>
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
BogDan Vatra's avatar
BogDan Vatra committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
BogDan Vatra's avatar
BogDan Vatra committed
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** 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.
BogDan Vatra's avatar
BogDan Vatra committed
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** 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
BogDan Vatra's avatar
BogDan Vatra committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
BogDan Vatra's avatar
BogDan Vatra committed
29
30
31

#include "androidrunner.h"

32
#include "androiddeployqtstep.h"
BogDan Vatra's avatar
BogDan Vatra committed
33
34
35
#include "androidconfigurations.h"
#include "androidglobal.h"
#include "androidrunconfiguration.h"
Tobias Hunger's avatar
Tobias Hunger committed
36
37
#include "androidmanager.h"

38
#include <debugger/debuggerrunconfigurationaspect.h>
Tobias Hunger's avatar
Tobias Hunger committed
39
#include <projectexplorer/target.h>
40
#include <qtsupport/qtkitinformation.h>
hjk's avatar
hjk committed
41
#include <utils/qtcassert.h>
BogDan Vatra's avatar
BogDan Vatra committed
42

43
#include <QDir>
BogDan Vatra's avatar
BogDan Vatra committed
44
45
#include <QTime>
#include <QtConcurrentRun>
hjk's avatar
hjk committed
46
#include <QTemporaryFile>
Aurindam Jana's avatar
Aurindam Jana committed
47
#include <QTcpServer>
BogDan Vatra's avatar
BogDan Vatra committed
48
49
50
51

namespace Android {
namespace Internal {

hjk's avatar
hjk committed
52
53
typedef QLatin1String _;

Aurindam Jana's avatar
Aurindam Jana committed
54
55
56
AndroidRunner::AndroidRunner(QObject *parent,
                             AndroidRunConfiguration *runConfig,
                             ProjectExplorer::RunMode runMode)
BogDan Vatra's avatar
BogDan Vatra committed
57
58
    : QThread(parent)
{
59
    m_tries = 0;
60
61
    Debugger::DebuggerRunConfigurationAspect *aspect
            = runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
Aurindam Jana's avatar
Aurindam Jana committed
62
    const bool debuggingMode = runMode == ProjectExplorer::DebugRunMode;
63
64
    m_useCppDebugger = debuggingMode && aspect->useCppDebugger();
    m_useQmlDebugger = debuggingMode && aspect->useQmlDebugger();
hjk's avatar
hjk committed
65
66
67
68
    QString channel = runConfig->remoteChannel();
    QTC_CHECK(channel.startsWith(QLatin1Char(':')));
    m_localGdbServerPort = channel.mid(1).toUShort();
    QTC_CHECK(m_localGdbServerPort);
Aurindam Jana's avatar
Aurindam Jana committed
69
70
    m_useQmlProfiler = runMode == ProjectExplorer::QmlProfilerRunMode;
    if (m_useQmlDebugger || m_useQmlProfiler) {
Aurindam Jana's avatar
Aurindam Jana committed
71
72
73
74
75
        QTcpServer server;
        QTC_ASSERT(server.listen(QHostAddress::LocalHost)
                   || server.listen(QHostAddress::LocalHostIPv6),
                   qDebug() << tr("No free ports available on host for QML debugging."));
        m_qmlPort = server.serverPort();
76
77
    } else {
        m_qmlPort = -1;
Aurindam Jana's avatar
Aurindam Jana committed
78
    }
Tobias Hunger's avatar
Tobias Hunger committed
79
    ProjectExplorer::Target *target = runConfig->target();
80
    m_useLocalQtLibs = AndroidManager::useLocalLibs(target);
81
    if (m_useLocalQtLibs) {
82
83
84
85
        int deviceApiLevel = AndroidManager::minimumSDK(target);
        m_localLibs = AndroidManager::loadLocalLibs(target, deviceApiLevel);
        m_localJars = AndroidManager::loadLocalJars(target, deviceApiLevel);
        m_localJarsInitClasses = AndroidManager::loadLocalJarsInitClasses(target, deviceApiLevel);
BogDan Vatra's avatar
BogDan Vatra committed
86
    }
Tobias Hunger's avatar
Tobias Hunger committed
87
    m_intentName = AndroidManager::intentName(target);
BogDan Vatra's avatar
BogDan Vatra committed
88
    m_packageName = m_intentName.left(m_intentName.indexOf(QLatin1Char('/')));
89
90

    m_deviceSerialNumber = AndroidManager::deviceSerialNumber(target);
BogDan Vatra's avatar
BogDan Vatra committed
91
    m_processPID = -1;
Daniel Teske's avatar
Daniel Teske committed
92
    m_adb = AndroidConfigurations::currentConfig().adbToolPath().toString();
hjk's avatar
hjk committed
93
94
95
96
97
98
    m_selector = AndroidDeviceInfo::adbSelector(m_deviceSerialNumber);

    QString packageDir = _("/data/data/") + m_packageName;
    m_pingFile = packageDir + _("/debug-ping");
    m_pongFile = _("/data/local/tmp/qt/debug-pong-") + m_packageName;
    m_gdbserverSocket = packageDir + _("/debug-socket");
99
100
    const QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
    if (version && version->qtVersion() >=  QtSupport::QtVersionNumber(5, 4, 0))
101
102
103
104
        m_gdbserverPath = packageDir + _("/lib/libgdbserver.so");
    else
        m_gdbserverPath = packageDir + _("/lib/gdbserver");

105

hjk's avatar
hjk committed
106
107
108
109
110
111
112
113
    m_gdbserverCommand = m_gdbserverPath + _(" --multi +") + m_gdbserverSocket;
    // Detect busybox, as we need to pass -w to ps to get wide output.
    QProcess psProc;
    psProc.start(m_adb, selector() << _("shell") << _("readlink") << _("$(which ps)"));
    psProc.waitForFinished();
    QByteArray which = psProc.readAll();
    m_isBusyBox = which.startsWith("busybox");

114
115
    m_checkPIDTimer.setInterval(1000);

BogDan Vatra's avatar
BogDan Vatra committed
116
    connect(&m_adbLogcatProcess, SIGNAL(readyReadStandardOutput()), SLOT(logcatReadStandardOutput()));
hjk's avatar
hjk committed
117
118
    connect(&m_adbLogcatProcess, SIGNAL(readyReadStandardError()), SLOT(logcatReadStandardError()));
    connect(&m_checkPIDTimer, SIGNAL(timeout()), SLOT(checkPID()));
BogDan Vatra's avatar
BogDan Vatra committed
119
120
121
122
}

AndroidRunner::~AndroidRunner()
{
hjk's avatar
hjk committed
123
    //stop();
BogDan Vatra's avatar
BogDan Vatra committed
124
125
}

hjk's avatar
hjk committed
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
static int extractPidFromChunk(const QByteArray &chunk, int from)
{
    int pos1 = chunk.indexOf(' ', from);
    if (pos1 == -1)
        return -1;
    while (chunk[pos1] == ' ')
        ++pos1;
    int pos3 = chunk.indexOf(' ', pos1);
    int pid = chunk.mid(pos1, pos3 - pos1).toInt();
    return pid;
}

static int extractPid(const QString &exeName, const QByteArray &psOutput)
{
    const QByteArray needle = exeName.toUtf8() + '\r';
    const int to = psOutput.indexOf(needle);
    if (to == -1)
        return -1;
    const int from = psOutput.lastIndexOf('\n', to);
    if (from == -1)
        return -1;
    return extractPidFromChunk(psOutput, from);
}

QByteArray AndroidRunner::runPs()
BogDan Vatra's avatar
BogDan Vatra committed
151
152
{
    QProcess psProc;
hjk's avatar
hjk committed
153
154
155
156
157
158
159
160
161
    QStringList args = m_selector;
    args << _("shell") << _("ps");
    if (m_isBusyBox)
        args << _("-w");

    psProc.start(m_adb, args);
    psProc.waitForFinished();
    return psProc.readAll();
}
162

hjk's avatar
hjk committed
163
164
165
166
void AndroidRunner::checkPID()
{
    QByteArray psOut = runPs();
    m_processPID = extractPid(m_packageName, psOut);
167

168
    if (m_processPID == -1) {
169
170
171
        if (m_wasStarted) {
            m_wasStarted = false;
            m_checkPIDTimer.stop();
172
            emit remoteProcessFinished(QLatin1String("\n\n") + tr("\"%1\" died.").arg(m_packageName));
173
174
        } else {
            if (++m_tries > 3)
175
                emit remoteProcessFinished(QLatin1String("\n\n") + tr("Unable to start \"%1\".").arg(m_packageName));
176
177
178
179
180
181
182
183
184
185
186
187
188
        }
    } else if (!m_wasStarted){
        if (m_useCppDebugger) {
            // This will be funneled to the engine to actually start and attach
            // gdb. Afterwards this ends up in handleRemoteDebuggerRunning() below.
            QByteArray serverChannel = ':' + QByteArray::number(m_localGdbServerPort);
            emit remoteServerRunning(serverChannel, m_processPID);
        } else if (m_useQmlDebugger) {
            // This will be funneled to the engine to actually start and attach
            // gdb. Afterwards this ends up in handleRemoteDebuggerRunning() below.
            QByteArray serverChannel = QByteArray::number(m_qmlPort);
            emit remoteServerRunning(serverChannel, m_processPID);
        } else if (m_useQmlProfiler) {
189
            emit remoteProcessStarted(-1, m_qmlPort);
190
191
192
193
194
        } else {
            // Start without debugging.
            emit remoteProcessStarted(-1, -1);
        }
        m_wasStarted = true;
195
        logcatReadStandardOutput();
196
    }
hjk's avatar
hjk committed
197
}
BogDan Vatra's avatar
BogDan Vatra committed
198

hjk's avatar
hjk committed
199
200
201
void AndroidRunner::forceStop()
{
    QProcess proc;
202
203
    proc.start(m_adb, selector() << _("shell") << _("am") << _("force-stop")
               << m_packageName);
hjk's avatar
hjk committed
204
    proc.waitForFinished();
BogDan Vatra's avatar
BogDan Vatra committed
205

206
    // try killing it via kill -9
hjk's avatar
hjk committed
207
208
209
210
211
212
213
214
215
216
    const QByteArray out = runPs();
    int from = 0;
    while (1) {
        const int to = out.indexOf('\n', from);
        if (to == -1)
            break;
        QString line = QString::fromUtf8(out.data() + from, to - from - 1);
        if (line.endsWith(m_packageName) || line.endsWith(m_gdbserverPath)) {
            int pid = extractPidFromChunk(out, from);
            adbKill(pid);
BogDan Vatra's avatar
BogDan Vatra committed
217
        }
hjk's avatar
hjk committed
218
        from = to + 1;
BogDan Vatra's avatar
BogDan Vatra committed
219
220
221
222
223
    }
}

void AndroidRunner::start()
{
hjk's avatar
hjk committed
224
225
    m_adbLogcatProcess.start(m_adb, selector() << _("logcat"));
    QtConcurrent::run(this, &AndroidRunner::asyncStart);
BogDan Vatra's avatar
BogDan Vatra committed
226
227
228
229
230
}

void AndroidRunner::asyncStart()
{
    QMutexLocker locker(&m_mutex);
hjk's avatar
hjk committed
231
232
    forceStop();

233
    if (m_useCppDebugger) {
hjk's avatar
hjk committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        // Remove pong file.
        QProcess adb;
        adb.start(m_adb, selector() << _("shell") << _("rm") << m_pongFile);
        adb.waitForFinished();
    }

    QStringList args = selector();
    args << _("shell") << _("am") << _("start") << _("-n") << m_intentName;

    if (m_useCppDebugger) {
        QProcess adb;
        adb.start(m_adb, selector() << _("forward")
                  << QString::fromLatin1("tcp:%1").arg(m_localGdbServerPort)
                  << _("localfilesystem:") + m_gdbserverSocket);
        if (!adb.waitForStarted()) {
            emit remoteProcessFinished(tr("Failed to forward C++ debugging ports. Reason: %1.").arg(adb.errorString()));
BogDan Vatra's avatar
BogDan Vatra committed
250
251
            return;
        }
252
        if (!adb.waitForFinished(10000)) {
253
            emit remoteProcessFinished(tr("Failed to forward C++ debugging ports."));
BogDan Vatra's avatar
BogDan Vatra committed
254
255
            return;
        }
hjk's avatar
hjk committed
256
257
258
259
260
261

        args << _("-e") << _("debug_ping") << _("true");
        args << _("-e") << _("ping_file") << m_pingFile;
        args << _("-e") << _("pong_file") << m_pongFile;
        args << _("-e") << _("gdbserver_command") << m_gdbserverCommand;
        args << _("-e") << _("gdbserver_socket") << m_gdbserverSocket;
BogDan Vatra's avatar
BogDan Vatra committed
262
    }
Aurindam Jana's avatar
Aurindam Jana committed
263
264

    if (m_useQmlDebugger || m_useQmlProfiler) {
hjk's avatar
hjk committed
265
        // currently forward to same port on device and host
Aurindam Jana's avatar
Aurindam Jana committed
266
        const QString port = QString::fromLatin1("tcp:%1").arg(m_qmlPort);
hjk's avatar
hjk committed
267
268
269
270
        QProcess adb;
        adb.start(m_adb, selector() << _("forward") << port << port);
        if (!adb.waitForStarted()) {
            emit remoteProcessFinished(tr("Failed to forward QML debugging ports. Reason: %1.").arg(adb.errorString()));
271
272
            return;
        }
hjk's avatar
hjk committed
273
        if (!adb.waitForFinished()) {
274
            emit remoteProcessFinished(tr("Failed to forward QML debugging ports."));
275
276
            return;
        }
hjk's avatar
hjk committed
277
        args << _("-e") << _("qml_debug") << _("true");
Aurindam Jana's avatar
Aurindam Jana committed
278
        args << _("-e") << _("qmljsdebugger") << QString::fromLatin1("port:%1,block").arg(m_qmlPort);
279
    }
BogDan Vatra's avatar
BogDan Vatra committed
280
    if (m_useLocalQtLibs) {
hjk's avatar
hjk committed
281
282
283
284
        args << _("-e") << _("use_local_qt_libs") << _("true");
        args << _("-e") << _("libs_prefix") << _("/data/local/tmp/qt/");
        args << _("-e") << _("load_local_libs") << m_localLibs;
        args << _("-e") << _("load_local_jars") << m_localJars;
285
        if (!m_localJarsInitClasses.isEmpty())
hjk's avatar
hjk committed
286
            args << _("-e") << _("static_init_classes") << m_localJarsInitClasses;
BogDan Vatra's avatar
BogDan Vatra committed
287
288
    }

hjk's avatar
hjk committed
289
290
291
292
    QProcess adb;
    adb.start(m_adb, args);
    if (!adb.waitForStarted()) {
        emit remoteProcessFinished(tr("Failed to start the activity. Reason: %1.").arg(adb.errorString()));
BogDan Vatra's avatar
BogDan Vatra committed
293
294
        return;
    }
295
    if (!adb.waitForFinished(10000)) {
hjk's avatar
hjk committed
296
        adb.terminate();
297
        emit remoteProcessFinished(tr("Unable to start \"%1\".").arg(m_packageName));
BogDan Vatra's avatar
BogDan Vatra committed
298
299
        return;
    }
hjk's avatar
hjk committed
300

Aurindam Jana's avatar
Aurindam Jana committed
301
    if (m_useCppDebugger) {
hjk's avatar
hjk committed
302
303
304

        // Handling ping.
        for (int i = 0; ; ++i) {
305
            QTemporaryFile tmp(QDir::tempPath() + _("/pingpong"));
hjk's avatar
hjk committed
306
307
308
309
310
311
312
313
314
315
316
317
318
319
            tmp.open();
            tmp.close();

            QProcess process;
            process.start(m_adb, selector() << _("pull") << m_pingFile << tmp.fileName());
            process.waitForFinished();

            QFile res(tmp.fileName());
            const bool doBreak = res.size();
            res.remove();
            if (doBreak)
                break;

            if (i == 20) {
320
                emit remoteProcessFinished(tr("Unable to start \"%1\".").arg(m_packageName));
hjk's avatar
hjk committed
321
322
323
324
325
326
                return;
            }
            qDebug() << "WAITING FOR " << tmp.fileName();
            QThread::msleep(500);
        }

BogDan Vatra's avatar
BogDan Vatra committed
327
    }
hjk's avatar
hjk committed
328

329
330
    m_tries = 0;
    m_wasStarted = false;
331
    QMetaObject::invokeMethod(&m_checkPIDTimer, "start");
BogDan Vatra's avatar
BogDan Vatra committed
332
333
}

Aurindam Jana's avatar
Aurindam Jana committed
334
void AndroidRunner::handleRemoteDebuggerRunning()
BogDan Vatra's avatar
BogDan Vatra committed
335
{
Aurindam Jana's avatar
Aurindam Jana committed
336
    if (m_useCppDebugger) {
337
        QTemporaryFile tmp(QDir::tempPath() + _("/pingpong"));
Aurindam Jana's avatar
Aurindam Jana committed
338
        tmp.open();
hjk's avatar
hjk committed
339

Aurindam Jana's avatar
Aurindam Jana committed
340
341
342
        QProcess process;
        process.start(m_adb, selector() << _("push") << tmp.fileName() << m_pongFile);
        process.waitForFinished();
hjk's avatar
hjk committed
343

Aurindam Jana's avatar
Aurindam Jana committed
344
345
346
        QTC_CHECK(m_processPID != -1);
    }
    emit remoteProcessStarted(m_localGdbServerPort, m_qmlPort);
BogDan Vatra's avatar
BogDan Vatra committed
347
348
}

BogDan Vatra's avatar
BogDan Vatra committed
349
void AndroidRunner::stop()
BogDan Vatra's avatar
BogDan Vatra committed
350
351
352
{
    QMutexLocker locker(&m_mutex);
    m_checkPIDTimer.stop();
353
    m_tries = 0;
hjk's avatar
hjk committed
354
    if (m_processPID != -1) {
355
        forceStop();
356
        emit remoteProcessFinished(QLatin1String("\n\n") + tr("\"%1\" terminated.").arg(m_packageName));
BogDan Vatra's avatar
BogDan Vatra committed
357
    }
hjk's avatar
hjk committed
358
    //QObject::disconnect(&m_adbLogcatProcess, 0, this, 0);
BogDan Vatra's avatar
BogDan Vatra committed
359
    m_adbLogcatProcess.kill();
hjk's avatar
hjk committed
360
    m_adbLogcatProcess.waitForFinished();
BogDan Vatra's avatar
BogDan Vatra committed
361
362
}

363
void AndroidRunner::logcatProcess(const QByteArray &text, QByteArray &buffer, bool onlyError)
BogDan Vatra's avatar
BogDan Vatra committed
364
{
365
    QList<QByteArray> lines = text.split('\n');
366
    // lines always contains at least one item
367
    lines[0].prepend(buffer);
368
369
    if (!lines.last().endsWith('\n')) {
        // incomplete line
370
        buffer = lines.last();
371
372
        lines.removeLast();
    } else {
373
        buffer.clear();
374
375
    }

376
    QByteArray pid(QString::fromLatin1("%1):").arg(m_processPID).toLatin1());
377
    foreach (QByteArray line, lines) {
BogDan Vatra's avatar
BogDan Vatra committed
378
379
        if (!line.contains(pid))
            continue;
380
381
382
        if (line.endsWith('\r'))
            line.chop(1);
        line.append('\n');
383
384
        if (onlyError || line.startsWith("F/")
                || line.startsWith("E/")
385
386
                || line.startsWith("D/Qt")
                || line.startsWith("W/"))
BogDan Vatra's avatar
BogDan Vatra committed
387
388
389
390
391
392
393
            emit remoteErrorOutput(line);
        else
            emit remoteOutput(line);

    }
}

394
395
396
397
398
399
400
401
402
403
404
405
void AndroidRunner::logcatReadStandardError()
{
    if (m_processPID != -1)
        logcatProcess(m_adbLogcatProcess.readAllStandardError(), m_stderrBuffer, true);
}

void AndroidRunner::logcatReadStandardOutput()
{
    if (m_processPID != -1)
        logcatProcess(m_adbLogcatProcess.readAllStandardOutput(), m_stdoutBuffer, false);
}

hjk's avatar
hjk committed
406
void AndroidRunner::adbKill(qint64 pid)
BogDan Vatra's avatar
BogDan Vatra committed
407
{
hjk's avatar
hjk committed
408
409
410
411
412
413
414
415
416
417
418
419
420
    {
        QProcess process;
        process.start(m_adb, selector() << _("shell")
            << _("kill") << QLatin1String("-9") << QString::number(pid));
        process.waitForFinished();
    }
    {
        QProcess process;
        process.start(m_adb, selector() << _("shell")
            << _("run-as") << m_packageName
            << _("kill") << QLatin1String("-9") << QString::number(pid));
        process.waitForFinished();
    }
BogDan Vatra's avatar
BogDan Vatra committed
421
422
423
424
425
426
427
428
}

QString AndroidRunner::displayName() const
{
    return m_packageName;
}

} // namespace Internal
429
} // namespace Android