aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/projectexplorer/consoleprocess_win.cpp
blob: 5b8760cd33effc665673b86ec48edcd2c32fa1a6 (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
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** 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
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** 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
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/

#include <QtCore/QDir>
#include <QtCore/private/qwineventnotifier_p.h>
#include <QtCore/QAbstractEventDispatcher>

#include <Tlhelp32.h>

#include "consoleprocess.h"

using namespace ProjectExplorer::Internal;

ConsoleProcess::ConsoleProcess(QObject *parent)
    : QObject(parent)
{
    m_isRunning = false;
    m_pid = 0;
}

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

void ConsoleProcess::stop()
{
    if (m_pid)
        TerminateProcess(m_pid->hProcess, -1);
    m_isRunning = false;
}

bool ConsoleProcess::start(const QString &program, const QStringList &args)
{
    if (m_isRunning)
        return false;

    STARTUPINFO si;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    if (m_pid) {
        CloseHandle(m_pid->hThread);
        CloseHandle(m_pid->hProcess);
        delete m_pid;
        m_pid = 0;
    }
    m_pid = new PROCESS_INFORMATION;
    ZeroMemory(m_pid, sizeof(PROCESS_INFORMATION));

    QString cmdLine = QLatin1String("cmd /k ")
                      + createCommandline(program, args)
                      + QLatin1String(" & pause & exit");

    bool success = CreateProcessW(0, (WCHAR*)cmdLine.utf16(),
                                  0, 0, TRUE, CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT,
                                  environment().isEmpty() ? 0
                                  : createEnvironment(environment()).data(),
                                  workingDirectory().isEmpty() ? 0
                                  : (WCHAR*)QDir::convertSeparators(workingDirectory()).utf16(),
                                  &si, m_pid);

    if (!success) {
        emit processError(tr("The process could not be started!"));
        return false;
    }

    if (QAbstractEventDispatcher::instance(thread())) {
        processFinishedNotifier = new QWinEventNotifier(m_pid->hProcess, this);
        QObject::connect(processFinishedNotifier, SIGNAL(activated(HANDLE)), this, SLOT(processDied()));
        processFinishedNotifier->setEnabled(true);
    }
    m_isRunning = true;
    emit processStarted();
    return success;
}

bool ConsoleProcess::isRunning() const
{
    return m_isRunning;
}

void ConsoleProcess::processDied()
{
    if (processFinishedNotifier) {
        processFinishedNotifier->setEnabled(false);
        delete processFinishedNotifier;
        processFinishedNotifier = 0;
    }
    delete m_pid;
    m_pid = 0;
    m_isRunning = false;
    emit processStopped();
}

qint64 ConsoleProcess::applicationPID() const
{
    if (m_pid) {
        HANDLE hProcList = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        PROCESSENTRY32 procEntry;
        procEntry.dwSize = sizeof(PROCESSENTRY32);
        DWORD procId = 0;
        BOOL moreProc = Process32First(hProcList, &procEntry);
        while (moreProc) {
            if (procEntry.th32ParentProcessID == m_pid->dwProcessId) {
                procId = procEntry.th32ProcessID;
                break;
            }
            moreProc = Process32Next(hProcList, &procEntry);
        }

        CloseHandle(hProcList);
        return procId;
    }
    return 0;
}

int ConsoleProcess::exitCode() const
{
    DWORD exitCode;
    if (GetExitCodeProcess(m_pid->hProcess, &exitCode))
        return exitCode;
    return -1;
}

QByteArray ConsoleProcess::createEnvironment(const QStringList &env)
{
    QByteArray envlist;
    if (!env.isEmpty()) {
        QStringList envStrings = env;
        int pos = 0;
        // 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)));
        }
#ifdef UNICODE
        if (!(QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based)) {
            for (QStringList::ConstIterator it = envStrings.constBegin(); it != envStrings.constEnd(); it++ ) {
                QString tmp = *it;
                uint tmpSize = sizeof(TCHAR) * (tmp.length()+1);
                envlist.resize(envlist.size() + tmpSize);
                memcpy(envlist.data()+pos, tmp.utf16(), tmpSize);
                pos += tmpSize;
            }
            // add the 2 terminating 0 (actually 4, just to be on the safe side)
            envlist.resize(envlist.size() + 4);
            envlist[pos++] = 0;
            envlist[pos++] = 0;
            envlist[pos++] = 0;
            envlist[pos++] = 0;
        } else
#endif // UNICODE
        {
            for (QStringList::ConstIterator it = envStrings.constBegin(); it != envStrings.constEnd(); it++) {
                QByteArray tmp = (*it).toLocal8Bit();
                uint tmpSize = tmp.length() + 1;
                envlist.resize(envlist.size() + tmpSize);
                memcpy(envlist.data()+pos, tmp.data(), tmpSize);
                pos += tmpSize;
            }
            // add the terminating 0 (actually 2, just to be on the safe side)
            envlist.resize(envlist.size() + 2);
            envlist[pos++] = 0;
            envlist[pos++] = 0;
        }
    }
    return envlist;
}

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;
}