consoleprocess_win.cpp 10.4 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 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
** Commercial Usage
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18
19
20
21
22
23
** 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.
24
**
25
26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

30
31
#include "consoleprocess.h"

32
#include <QtCore/QCoreApplication>
con's avatar
con committed
33
#include <QtCore/QDir>
34
#include <QtCore/QTemporaryFile>
con's avatar
con committed
35
#include <QtCore/QAbstractEventDispatcher>
36
37
38
#include <QtCore/private/qwineventnotifier_p.h>

#include <QtNetwork/QLocalSocket>
con's avatar
con committed
39

40
#include <stdlib.h>
con's avatar
con committed
41

42
using namespace Core::Utils;
con's avatar
con committed
43
44
45
46

ConsoleProcess::ConsoleProcess(QObject *parent)
    : QObject(parent)
{
47
48
    m_debug = false;
    m_appPid = 0;
con's avatar
con committed
49
    m_pid = 0;
50
51
52
53
54
55
56
    m_hInferior = NULL;
    m_tempFile = 0;
    m_stubSocket = 0;
    processFinishedNotifier = 0;
    inferiorFinishedNotifier = 0;

    connect(&m_stubServer, SIGNAL(newConnection()), SLOT(stubConnectionAvailable()));
con's avatar
con committed
57
58
59
60
61
62
63
64
65
}

ConsoleProcess::~ConsoleProcess()
{
    stop();
}

bool ConsoleProcess::start(const QString &program, const QStringList &args)
{
66
    if (isRunning())
con's avatar
con committed
67
68
        return false;

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
    QString err = stubServerListen();
    if (!err.isEmpty()) {
        emit processError(tr("Cannot set up comm channel: %1").arg(err));
        return false;
    }

    if (!environment().isEmpty()) {
        m_tempFile = new QTemporaryFile();
        if (!m_tempFile->open()) {
            stubServerShutdown();
            emit processError(tr("Cannot create temp file: %1").arg(m_tempFile->errorString()));
            delete m_tempFile;
            m_tempFile = 0;
            return false;
        }
        QTextStream out(m_tempFile);
        out.setCodec("UTF-16LE");
        out.setGenerateByteOrderMark(false);
        foreach (const QString &var, fixEnvironment(environment()))
            out << var << QChar(0);
        out << QChar(0);
    }

con's avatar
con committed
92
93
94
95
96
97
98
    STARTUPINFO si;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    m_pid = new PROCESS_INFORMATION;
    ZeroMemory(m_pid, sizeof(PROCESS_INFORMATION));

99
100
101
102
103
104
105
106
107
108
109
110
111
112
    QString workDir = QDir::toNativeSeparators(workingDirectory());
    if (!workDir.isEmpty() && !workDir.endsWith('\\'))
        workDir.append('\\');

    QStringList stubArgs;
    stubArgs << (m_debug ? "debug" : "exec")
             << m_stubServer.fullServerName()
             << workDir
             << (m_tempFile ? m_tempFile->fileName() : 0)
             << createCommandline(program, args)
             << tr("Press <RETURN> to close this window...");

    QString cmdLine = createCommandline(
            QCoreApplication::applicationDirPath() + "/qtcreator_process_stub.exe", stubArgs);
con's avatar
con committed
113
114

    bool success = CreateProcessW(0, (WCHAR*)cmdLine.utf16(),
115
116
                                  0, 0, FALSE, CREATE_NEW_CONSOLE,
                                  0, 0,
con's avatar
con committed
117
118
119
                                  &si, m_pid);

    if (!success) {
120
121
122
123
124
        delete m_pid;
        m_pid = 0;
        delete m_tempFile;
        m_tempFile = 0;
        stubServerShutdown();
con's avatar
con committed
125
126
127
128
        emit processError(tr("The process could not be started!"));
        return false;
    }

129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
    processFinishedNotifier = new QWinEventNotifier(m_pid->hProcess, this);
    connect(processFinishedNotifier, SIGNAL(activated(HANDLE)), SLOT(stubExited()));
    emit wrapperStarted();
    return true;
}

void ConsoleProcess::stop()
{
    if (m_hInferior != NULL) {
        TerminateProcess(m_hInferior, (unsigned)-1);
        cleanupInferior();
    }
    if (m_pid) {
        TerminateProcess(m_pid->hProcess, (unsigned)-1);
        WaitForSingleObject(m_pid->hProcess, INFINITE);
        cleanupStub();
con's avatar
con committed
145
146
147
148
149
    }
}

bool ConsoleProcess::isRunning() const
{
150
    return m_pid != 0;
con's avatar
con committed
151
152
}

153
QString ConsoleProcess::stubServerListen()
con's avatar
con committed
154
{
155
156
157
158
159
    if (m_stubServer.listen(QString::fromLatin1("creator-%1-%2")
                            .arg(QCoreApplication::applicationPid())
                            .arg(rand())))
        return QString();
    return m_stubServer.errorString();
con's avatar
con committed
160
161
}

162
void ConsoleProcess::stubServerShutdown()
con's avatar
con committed
163
{
164
165
166
167
168
    delete m_stubSocket;
    m_stubSocket = 0;
    if (m_stubServer.isListening())
        m_stubServer.close();
}
con's avatar
con committed
169

170
171
172
173
void ConsoleProcess::stubConnectionAvailable()
{
    m_stubSocket = m_stubServer.nextPendingConnection();
    connect(m_stubSocket, SIGNAL(readyRead()), SLOT(readStubOutput()));
con's avatar
con committed
174
175
}

176
static QString errorMsg(int code)
con's avatar
con committed
177
{
178
179
180
181
182
183
184
185
    LPVOID lpMsgBuf;

    int len = FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, (DWORD)code, 0, (LPTSTR)&lpMsgBuf, 0, NULL);
    QString ret = QString::fromUtf16((ushort *)lpMsgBuf, len);
    LocalFree(lpMsgBuf);
    return ret;
con's avatar
con committed
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
void ConsoleProcess::readStubOutput()
{
    while (m_stubSocket->canReadLine()) {
        QByteArray out = m_stubSocket->readLine();
        out.chop(2); // \r\n
        if (out.startsWith("err:chdir ")) {
            emit processError(tr("Cannot change to working directory %1: %2")
                              .arg(workingDirectory(), errorMsg(out.mid(10).toInt())));
        } else if (out.startsWith("err:exec ")) {
            emit processError(tr("Cannot execute %1: %2")
                              .arg(m_executable, errorMsg(out.mid(9).toInt())));
        } else if (out.startsWith("pid ")) {
            // Will not need it any more
            delete m_tempFile;
            m_tempFile = 0;

            m_appPid = out.mid(4).toInt();
            m_hInferior = OpenProcess(
                    SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE,
                    FALSE, m_appPid);
            if (m_hInferior == NULL) {
                emit processError(tr("Cannot obtain a handle to the inferior: %1")
                                  .arg(errorMsg(GetLastError())));
                // Uhm, and now what?
                continue;
con's avatar
con committed
213
            }
214
215
216
217
218
219
220
            inferiorFinishedNotifier = new QWinEventNotifier(m_hInferior, this);
            connect(inferiorFinishedNotifier, SIGNAL(activated(HANDLE)), SLOT(inferiorExited()));
            emit processStarted();
        } else {
            emit processError(tr("Unexpected output from helper program."));
            TerminateProcess(m_pid->hProcess, (unsigned)-1);
            break;
con's avatar
con committed
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
}

void ConsoleProcess::cleanupInferior()
{
    delete inferiorFinishedNotifier;
    inferiorFinishedNotifier = 0;
    CloseHandle(m_hInferior);
    m_hInferior = NULL;
    m_appPid = 0;
}

void ConsoleProcess::inferiorExited()
{
    DWORD chldStatus;

    if (!GetExitCodeProcess(m_hInferior, &chldStatus))
        emit processError(tr("Cannot obtain exit status from inferior: %1")
                          .arg(errorMsg(GetLastError())));
    cleanupInferior();
    m_appStatus = QProcess::NormalExit;
    m_appCode = chldStatus;
    emit processStopped();
}

void ConsoleProcess::cleanupStub()
{
    stubServerShutdown();
    delete processFinishedNotifier;
    processFinishedNotifier = 0;
    CloseHandle(m_pid->hThread);
    CloseHandle(m_pid->hProcess);
    delete m_pid;
    m_pid = 0;
    delete m_tempFile;
    m_tempFile = 0;
}

void ConsoleProcess::stubExited()
{
    // The stub exit might get noticed before we read the pid for the kill.
    if (m_stubSocket && m_stubSocket->state() == QLocalSocket::ConnectedState)
        m_stubSocket->waitForDisconnected();
    cleanupStub();
    if (m_hInferior != NULL) {
        TerminateProcess(m_hInferior, (unsigned)-1);
        cleanupInferior();
        m_appStatus = QProcess::CrashExit;
        m_appCode = -1;
        emit processStopped();
    }
    emit wrapperStopped();
}

QStringList ConsoleProcess::fixEnvironment(const QStringList &env)
{
    QStringList envStrings = env;
    // add PATH if necessary (for DLL loading)
    if (envStrings.filter(QRegExp("^PATH=",Qt::CaseInsensitive)).isEmpty()) {
        QByteArray path = qgetenv("PATH");
        if (!path.isEmpty())
            envStrings.prepend(QString(QLatin1String("PATH=%1")).arg(QString::fromLocal8Bit(path)));
    }
    // add systemroot if needed
    if (envStrings.filter(QRegExp("^SystemRoot=",Qt::CaseInsensitive)).isEmpty()) {
        QByteArray systemRoot = qgetenv("SystemRoot");
        if (!systemRoot.isEmpty())
            envStrings.prepend(QString(QLatin1String("SystemRoot=%1")).arg(QString::fromLocal8Bit(systemRoot)));
    }
    return envStrings;
con's avatar
con committed
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
}

QString ConsoleProcess::createCommandline(const QString &program, const QStringList &args)
{
    QString programName = program;
    if (!programName.startsWith(QLatin1Char('\"')) && !programName.endsWith(QLatin1Char('\"')) && programName.contains(" "))
        programName = "\"" + programName + "\"";
    programName.replace("/", "\\");

    QString cmdLine;
    // add the prgram as the first arrg ... it works better
    cmdLine = programName + " ";
    for (int i = 0; i < args.size(); ++i) {
        QString tmp = args.at(i);
        // in the case of \" already being in the string the \ must also be escaped
        tmp.replace( "\\\"", "\\\\\"" );
        // escape a single " because the arguments will be parsed
        tmp.replace( "\"", "\\\"" );
        if (tmp.isEmpty() || tmp.contains(' ') || tmp.contains('\t')) {
            // The argument must not end with a \ since this would be interpreted
            // as escaping the quote -- rather put the \ behind the quote: e.g.
            // rather use "foo"\ than "foo\"
            QString endQuote("\"");
            int i = tmp.length();
            while (i > 0 && tmp.at(i - 1) == '\\') {
                --i;
                endQuote += "\\";
            }
            cmdLine += QString(" \"") + tmp.left(i) + endQuote;
        } else {
            cmdLine += ' ' + tmp;
        }
    }
    return cmdLine;
}