synchronousprocess.cpp 10.6 KB
Newer Older
con's avatar
con committed
1
2
3
4
/***************************************************************************
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
7
8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
10
11
**
** Non-Open Source Usage
**
con's avatar
con committed
12
13
14
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
15
16
17
18
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
con's avatar
con committed
19
20
21
22
23
24
25
26
27
28
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
29
** rights. These rights are described in the Nokia Qt GPL Exception
30
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
31
32
**
***************************************************************************/
con's avatar
con committed
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

#include "synchronousprocess.h"

#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtCore/QEventLoop>
#include <QtCore/QTextCodec>

#include <QtGui/QApplication>

enum { debug = 0 };

enum { defaultMaxHangTimerCount = 10 };

namespace Core {
namespace Utils {

// ----------- SynchronousProcessResponse
SynchronousProcessResponse::SynchronousProcessResponse() :
   result(StartFailed),
   exitCode(-1)
{
}

void SynchronousProcessResponse::clear()
{
    result = StartFailed;
    exitCode = -1;
    stdOut.clear();
    stdErr.clear();
}

QWORKBENCH_UTILS_EXPORT QDebug operator<<(QDebug str, const SynchronousProcessResponse& r)
{
    QDebug nsp = str.nospace();
    nsp << "SynchronousProcessResponse: result=" << r.result << " ex=" << r.exitCode << '\n'
        << r.stdOut.size() << " bytes stdout, stderr=" << r.stdErr << '\n';
    return str;
}

// Data for one channel buffer (stderr/stdout)
struct ChannelBuffer {
    ChannelBuffer();
    void clearForRun();
    QByteArray linesRead();

    QByteArray data;
    bool firstData;
    bool bufferedSignalsEnabled;
    bool firstBuffer;
    int bufferPos;
};

ChannelBuffer::ChannelBuffer() :
    firstData(true),
    bufferedSignalsEnabled(false),
    firstBuffer(true),
    bufferPos(0)
{
}

void ChannelBuffer::clearForRun()
{
    firstData = true;
    firstBuffer = true;
    bufferPos = 0;
}

/* Check for complete lines read from the device and return them, moving the
 * buffer position. This is based on the assumption that '\n' is the new line
 * marker in any sane codec. */
QByteArray ChannelBuffer::linesRead()
{
    // Any new lines?
    const int lastLineIndex = data.lastIndexOf('\n');
    if (lastLineIndex == -1 || lastLineIndex <= bufferPos)
        return QByteArray();
    const int nextBufferPos = lastLineIndex + 1;
    const QByteArray lines = data.mid(bufferPos, nextBufferPos - bufferPos);
    bufferPos = nextBufferPos;
    return lines;
}

// ----------- SynchronousProcessPrivate
struct SynchronousProcessPrivate {
    SynchronousProcessPrivate();
    void clearForRun();

    QTextCodec *m_stdOutCodec;
    QProcess m_process;
    QTimer m_timer;
    QEventLoop m_eventLoop;
    SynchronousProcessResponse m_result;
    int m_hangTimerCount;
    int m_maxHangTimerCount;
128
    bool m_startFailure;
con's avatar
con committed
129
130
131
132
133
134
135
136

    ChannelBuffer m_stdOut;
    ChannelBuffer m_stdErr;
};

SynchronousProcessPrivate::SynchronousProcessPrivate() :
    m_stdOutCodec(0),
    m_hangTimerCount(0),
137
138
    m_maxHangTimerCount(defaultMaxHangTimerCount),
    m_startFailure(false)
con's avatar
con committed
139
140
141
142
143
144
145
146
147
{
}

void SynchronousProcessPrivate::clearForRun()
{
    m_hangTimerCount = 0;
    m_stdOut.clearForRun();
    m_stdErr.clearForRun();
    m_result.clear();
148
    m_startFailure = false;
con's avatar
con committed
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
}

// ----------- SynchronousProcess
SynchronousProcess::SynchronousProcess() :
    m_d(new SynchronousProcessPrivate)
{
    m_d->m_timer.setInterval(1000);
    connect(&m_d->m_timer, SIGNAL(timeout()), this, SLOT(slotTimeout()));
    connect(&m_d->m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus)));
    connect(&m_d->m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError)));
    connect(&m_d->m_process, SIGNAL(readyReadStandardOutput()),
            this, SLOT(stdOutReady()));
    connect(&m_d->m_process, SIGNAL(readyReadStandardError()),
            this, SLOT(stdErrReady()));
}

SynchronousProcess::~SynchronousProcess()
{
    delete m_d;
}

void SynchronousProcess::setTimeout(int timeoutMS)
{
    m_d->m_maxHangTimerCount = qMax(2, timeoutMS / 1000);
}

int SynchronousProcess::timeout() const
{
    return 1000 * m_d->m_maxHangTimerCount;
}

void SynchronousProcess::setStdOutCodec(QTextCodec *c)
{
    m_d->m_stdOutCodec = c;
}

QTextCodec *SynchronousProcess::stdOutCodec() const
{
    return m_d->m_stdOutCodec;
}

bool SynchronousProcess::stdOutBufferedSignalsEnabled() const
{
    return m_d->m_stdOut.bufferedSignalsEnabled;
}

void SynchronousProcess::setStdOutBufferedSignalsEnabled(bool v)
{
    m_d->m_stdOut.bufferedSignalsEnabled = v;
}

bool SynchronousProcess::stdErrBufferedSignalsEnabled() const
{
    return m_d->m_stdErr.bufferedSignalsEnabled;
}

void SynchronousProcess::setStdErrBufferedSignalsEnabled(bool v)
{
    m_d->m_stdErr.bufferedSignalsEnabled = v;
}

QStringList SynchronousProcess::environment() const
{
    return m_d->m_process.environment();
}

void SynchronousProcess::setEnvironment(const QStringList &e)
{
    m_d->m_process.setEnvironment(e);
}

SynchronousProcessResponse SynchronousProcess::run(const QString &binary,
                                                 const QStringList &args)
{
    if (debug)
        qDebug() << '>' << Q_FUNC_INFO << binary << args;

    m_d->clearForRun();

228
229
230
    // On Windows, start failure is triggered immediately if the
    // executable cannot be found in the path. Do not start the
    // event loop in that case.
con's avatar
con committed
231
    m_d->m_process.start(binary, args, QIODevice::ReadOnly);
232
233
234
235
236
237
238
239
240
241
242
243
244
245
    if (!m_d->m_startFailure) {
        m_d->m_timer.start();
        QApplication::setOverrideCursor(Qt::WaitCursor);
        m_d->m_eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
        if (m_d->m_result.result == SynchronousProcessResponse::Finished || m_d->m_result.result == SynchronousProcessResponse::FinishedError) {
            processStdOut(false);
            processStdErr(false);
        }

        m_d->m_result.stdOut = convertStdOut(m_d->m_stdOut.data);
        m_d->m_result.stdErr = convertStdErr(m_d->m_stdErr.data);

        m_d->m_timer.stop();
        QApplication::restoreOverrideCursor();
con's avatar
con committed
246
247
248
249
250
251
252
253
254
255
    }

    if (debug)
        qDebug() << '<' << Q_FUNC_INFO << binary << m_d->m_result;
    return  m_d->m_result;
}

void SynchronousProcess::slotTimeout()
{
    if (++m_d->m_hangTimerCount > m_d->m_maxHangTimerCount) {
256
257
        if (debug)
            qDebug() << Q_FUNC_INFO << "HANG detected, killing";
con's avatar
con committed
258
259
        m_d->m_process.kill();
        m_d->m_result.result = SynchronousProcessResponse::Hang;
260
261
262
    } else {
        if (debug)
            qDebug() << Q_FUNC_INFO << m_d->m_hangTimerCount;
con's avatar
con committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    }
}

void SynchronousProcess::finished(int exitCode, QProcess::ExitStatus e)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << exitCode << e;
    m_d->m_hangTimerCount = 0;
    switch (e) {
    case QProcess::NormalExit:
        m_d->m_result.result = exitCode ? SynchronousProcessResponse::FinishedError : SynchronousProcessResponse::Finished;
        m_d->m_result.exitCode = exitCode;
        break;
    case QProcess::CrashExit:
277
278
279
        // Was hang detected before and killed?
        if (m_d->m_result.result != SynchronousProcessResponse::Hang)
            m_d->m_result.result = SynchronousProcessResponse::TerminatedAbnormally;
con's avatar
con committed
280
281
282
283
284
285
286
287
288
289
290
        m_d->m_result.exitCode = -1;
        break;
    }
    m_d->m_eventLoop.quit();
}

void SynchronousProcess::error(QProcess::ProcessError e)
{
    m_d->m_hangTimerCount = 0;
    if (debug)
        qDebug() << Q_FUNC_INFO << e;
291
292
293
294
    // Was hang detected before and killed?
    if (m_d->m_result.result != SynchronousProcessResponse::Hang)
        m_d->m_result.result = SynchronousProcessResponse::StartFailed;
    m_d->m_startFailure = true;
con's avatar
con committed
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
    m_d->m_eventLoop.quit();
}

void SynchronousProcess::stdOutReady()
{
    m_d->m_hangTimerCount = 0;
    processStdOut(true);
}

void SynchronousProcess::stdErrReady()
{
    m_d->m_hangTimerCount = 0;
    processStdErr(true);
}

QString SynchronousProcess::convertStdErr(const QByteArray &ba)
{
hjk's avatar
hjk committed
312
    return QString::fromLocal8Bit(ba.constData(), ba.size()).remove(QLatin1Char('\r'));
con's avatar
con committed
313
314
315
316
}

QString SynchronousProcess::convertStdOut(const QByteArray &ba) const
{
hjk's avatar
hjk committed
317
    QString stdOut = m_d->m_stdOutCodec ? m_d->m_stdOutCodec->toUnicode(ba) : QString::fromLocal8Bit(ba.constData(), ba.size());
con's avatar
con committed
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
    return stdOut.remove(QLatin1Char('\r'));
}

void SynchronousProcess::processStdOut(bool emitSignals)
{
    // Handle binary data
    const QByteArray ba = m_d->m_process.readAllStandardOutput();
    if (debug > 1)
        qDebug() << Q_FUNC_INFO << emitSignals << ba;
    if (!ba.isEmpty()) {
        m_d->m_stdOut.data += ba;
        if (emitSignals) {
            // Emit binary signals
            emit stdOut(ba, m_d->m_stdOut.firstData);
            m_d->m_stdOut.firstData = false;
            // Buffered. Emit complete lines?
            if (m_d->m_stdOut.bufferedSignalsEnabled) {
                const QByteArray lines = m_d->m_stdOut.linesRead();
                if (!lines.isEmpty()) {
                    emit stdOutBuffered(convertStdOut(lines), m_d->m_stdOut.firstBuffer);
                    m_d->m_stdOut.firstBuffer = false;
                }
            }
        }
    }
}

void SynchronousProcess::processStdErr(bool emitSignals)
{
    // Handle binary data
    const QByteArray ba = m_d->m_process.readAllStandardError();
    if (debug > 1)
        qDebug() << Q_FUNC_INFO << emitSignals << ba;
    if (!ba.isEmpty()) {
        m_d->m_stdErr.data += ba;
        if (emitSignals) {
            // Emit binary signals
            emit stdErr(ba, m_d->m_stdErr.firstData);
            m_d->m_stdErr.firstData = false;
            if (m_d->m_stdErr.bufferedSignalsEnabled) {
                // Buffered. Emit complete lines?
                const QByteArray lines = m_d->m_stdErr.linesRead();
                if (!lines.isEmpty()) {
                    emit stdErrBuffered(convertStdErr(lines), m_d->m_stdErr.firstBuffer);
                    m_d->m_stdErr.firstBuffer = false;
                }
            }
        }
    }
}

hjk's avatar
hjk committed
369
370
} // namespace Utils
} // namespace Core