qtcprocess.cpp 56.4 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
Oswald Buddenhagen's avatar
Oswald Buddenhagen 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.
Oswald Buddenhagen's avatar
Oswald Buddenhagen 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
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
29
30
31
32

#include "qtcprocess.h"
#include "stringutils.h"

33
#include <utils/qtcassert.h>
34
#include <utils/hostosinfo.h>
35

36
37
38
#include <QDir>
#include <QDebug>
#include <QCoreApplication>
39
#include <QStack>
Friedemann Kleint's avatar
Friedemann Kleint committed
40

41
42
43
44
#ifdef Q_OS_WIN
#include <qt_windows.h>
#endif

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

// The main state of the Unix shell parser
enum MxQuoting { MxBasic, MxSingleQuote, MxDoubleQuote, MxParen, MxSubst, MxGroup, MxMath };

struct MxState
{
    MxQuoting current;
    // Bizarrely enough, double quoting has an impact on the behavior of some
    // complex expressions within the quoted string.
    bool dquote;
};
QT_BEGIN_NAMESPACE
Q_DECLARE_TYPEINFO(MxState, Q_PRIMITIVE_TYPE);
QT_END_NAMESPACE

// Pushed state for the case where a $(()) expansion turns out bogus
struct MxSave
{
    QString str;
    int pos, varPos;
};
QT_BEGIN_NAMESPACE
Q_DECLARE_TYPEINFO(MxSave, Q_MOVABLE_TYPE);
QT_END_NAMESPACE

namespace Utils {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
71

72
73
74
/*!
    \class Utils::QtcProcess

75
76
    \brief The QtcProcess class provides functionality for dealing with
    shell-quoted process arguments.
77
*/
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
78

79
inline static bool isMetaCharWin(ushort c)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
80
81
82
83
84
85
86
87
88
{
    static const uchar iqm[] = {
        0x00, 0x00, 0x00, 0x00, 0x40, 0x03, 0x00, 0x50,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10
    }; // &()<>|

    return (c < sizeof(iqm) * 8) && (iqm[c / 8] & (1 << (c & 7)));
}

89
static void envExpandWin(QString &args, const Environment *env, const QString *pwd)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
{
    static const QString cdName = QLatin1String("CD");
    int off = 0;
  next:
    for (int prev = -1, that;
         (that = args.indexOf(QLatin1Char('%'), off)) >= 0;
         prev = that, off = that + 1) {
        if (prev >= 0) {
            const QString var = args.mid(prev + 1, that - prev - 1).toUpper();
            const QString val = (var == cdName && pwd && !pwd->isEmpty())
                                    ? QDir::toNativeSeparators(*pwd) : env->value(var);
            if (!val.isEmpty()) { // Empty values are impossible, so this is an existence check
                args.replace(prev, that - prev + 1, val);
                off = prev + val.length();
                goto next;
            }
        }
    }
}

110
111
static QtcProcess::Arguments prepareArgsWin(const QString &_args, QtcProcess::SplitError *err,
                                            const Environment *env, const QString *pwd)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
112
113
114
115
{
    QString args(_args);

    if (env) {
116
        envExpandWin(args, env, pwd);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
117
118
119
    } else {
        if (args.indexOf(QLatin1Char('%')) >= 0) {
            if (err)
120
121
                *err = QtcProcess::FoundMeta;
            return QtcProcess::Arguments::createWindowsArgs(QString());
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
        }
    }

    if (!args.isEmpty() && args.unicode()[0].unicode() == '@')
        args.remove(0, 1);

    for (int p = 0; p < args.length(); p++) {
        ushort c = args.unicode()[p].unicode();
        if (c == '^') {
            args.remove(p, 1);
        } else if (c == '"') {
            do {
                if (++p == args.length())
                    break; // For cmd, this is no error.
            } while (args.unicode()[p].unicode() != '"');
137
        } else if (isMetaCharWin(c)) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
138
            if (err)
139
140
                *err = QtcProcess::FoundMeta;
            return QtcProcess::Arguments::createWindowsArgs(QString());
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
141
142
143
144
        }
    }

    if (err)
145
146
        *err = QtcProcess::SplitOk;
    return QtcProcess::Arguments::createWindowsArgs(args);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
147
148
}

149
inline static bool isWhiteSpaceWin(ushort c)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
150
151
152
153
{
    return c == ' ' || c == '\t';
}

154
static QStringList doSplitArgsWin(const QString &args, QtcProcess::SplitError *err)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
155
156
157
158
159
160
161
162
163
164
165
166
{
    QStringList ret;

    if (err)
        *err = QtcProcess::SplitOk;

    int p = 0;
    const int length = args.length();
    forever {
        forever {
            if (p == length)
                return ret;
167
            if (!isWhiteSpaceWin(args.unicode()[p].unicode()))
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
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
                break;
            ++p;
        }

        QString arg;
        bool inquote = false;
        forever {
            bool copy = true; // copy this char
            int bslashes = 0; // number of preceding backslashes to insert
            while (p < length && args.unicode()[p] == QLatin1Char('\\')) {
                ++p;
                ++bslashes;
            }
            if (p < length && args.unicode()[p] == QLatin1Char('"')) {
                if (!(bslashes & 1)) {
                    // Even number of backslashes, so the quote is not escaped.
                    if (inquote) {
                        if (p + 1 < length && args.unicode()[p + 1] == QLatin1Char('"')) {
                            // This is not documented on MSDN.
                            // Two consecutive quotes make a literal quote. Brain damage:
                            // this still closes the quoting, so a 3rd quote is required,
                            // which makes the runtime's quoting run out of sync with the
                            // shell's one unless the 2nd quote is escaped.
                            ++p;
                        } else {
                            // Closing quote
                            copy = false;
                        }
                        inquote = false;
                    } else {
                        // Opening quote
                        copy = false;
                        inquote = true;
                    }
                }
                bslashes >>= 1;
            }

            while (--bslashes >= 0)
                arg.append(QLatin1Char('\\'));

209
            if (p == length || (!inquote && isWhiteSpaceWin(args.unicode()[p].unicode()))) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
                ret.append(arg);
                if (inquote) {
                    if (err)
                        *err = QtcProcess::BadQuoting;
                    return QStringList();
                }
                break;
            }

            if (copy)
                arg.append(args.unicode()[p]);
            ++p;
        }
    }
    //not reached
}

227
/*!
Leena Miettinen's avatar
Leena Miettinen committed
228
    Splits \a _args according to system shell word splitting and quoting rules.
229
230
231
232
233

    \section1 Unix

    The behavior is based on the POSIX shell and bash:
    \list
Leena Miettinen's avatar
Leena Miettinen committed
234
235
    \li Whitespace splits tokens.
    \li The backslash quotes the following character.
236
    \li A string enclosed in single quotes is not split. No shell meta
237
        characters are interpreted.
238
    \li A string enclosed in double quotes is not split. Within the string,
239
240
241
242
243
244
245
246
        the backslash quotes shell meta characters - if it is followed
        by a "meaningless" character, the backslash is output verbatim.
    \endlist
    If \a abortOnMeta is \c false, only the splitting and quoting rules apply,
    while other meta characters (substitutions, redirections, etc.) are ignored.
    If \a abortOnMeta is \c true, encounters of unhandled meta characters are
    treated as errors.

Leena Miettinen's avatar
Leena Miettinen committed
247
248
249
250
251
252
253
254
    If \a err is not NULL, stores a status code at the pointer target. For more
    information, see \l SplitError.

    If \env is not NULL, performs variable substitution with the
    given environment.

    Returns a list of unquoted words or an empty list if an error occurred.

255
256
257
258
    \section1 Windows

    The behavior is defined by the Microsoft C runtime:
    \list
Leena Miettinen's avatar
Leena Miettinen committed
259
260
    \li Whitespace splits tokens.
    \li A string enclosed in double quotes is not split.
261
    \list
262
        \li 3N double quotes within a quoted string yield N literal quotes.
263
264
           This is not documented on MSDN.
    \endlist
Leena Miettinen's avatar
Leena Miettinen committed
265
    \li Backslashes have special semantics if they are followed by a double quote:
266
    \list
267
268
        \li 2N backslashes + double quote => N backslashes and begin/end quoting
        \li 2N+1 backslashes + double quote => N backslashes + literal quote
269
270
271
272
273
274
275
    \endlist
    \endlist
    Qt and many other implementations comply with this standard, but many do not.

    If \a abortOnMeta is \c true, cmd shell semantics are applied before
    proceeding with word splitting:
    \list
276
    \li Cmd ignores \e all special chars between double quotes.
277
        Note that the quotes are \e not removed at this stage - the
278
        tokenization rules described above still apply.
279
    \li The \c circumflex is the escape char for everything including itself.
280
281
282
283
284
285
    \endlist
    As the quoting levels are independent from each other and have different
    semantics, you need a command line like \c{"foo "\^"" bar"} to get
    \c{foo " bar}.
 */

286
287
288
289

static QStringList splitArgsWin(const QString &_args, bool abortOnMeta,
                                QtcProcess::SplitError *err,
                                const Environment *env, const QString *pwd)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
290
291
{
    if (abortOnMeta) {
292
        QtcProcess::SplitError perr;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
293
294
        if (!err)
            err = &perr;
295
296
        QString args = prepareArgsWin(_args, &perr, env, pwd).toWindowsArgs();
        if (*err != QtcProcess::SplitOk)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
297
            return QStringList();
298
        return doSplitArgsWin(args, err);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
299
300
301
    } else {
        QString args = _args;
        if (env)
302
303
            envExpandWin(args, env, pwd);
        return doSplitArgsWin(args, err);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
304
305
306
307
    }
}


308
static bool isMetaUnix(QChar cUnicode)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
309
310
311
312
313
314
315
316
317
318
319
{
    static const uchar iqm[] = {
        0x00, 0x00, 0x00, 0x00, 0xdc, 0x07, 0x00, 0xd8,
        0x00, 0x00, 0x00, 0x38, 0x01, 0x00, 0x00, 0x38
    }; // \'"$`<>|;&(){}*?#[]

    uint c = cUnicode.unicode();

    return (c < sizeof(iqm) * 8) && (iqm[c / 8] & (1 << (c & 7)));
}

320
321
322
static QStringList splitArgsUnix(const QString &args, bool abortOnMeta,
                                 QtcProcess::SplitError *err,
                                 const Environment *env, const QString *pwd)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
323
324
325
326
327
328
329
330
331
332
333
334
335
{
    static const QString pwdName = QLatin1String("PWD");
    QStringList ret;

    for (int pos = 0; ; ) {
        QChar c;
        do {
            if (pos >= args.length())
                goto okret;
            c = args.unicode()[pos++];
        } while (c.isSpace());
        QString cret;
        bool hadWord = false;
336
337
338
339
340
341
342
343
344
345
        if (c == QLatin1Char('~')) {
            if (pos >= args.length()
                || args.unicode()[pos].isSpace() || args.unicode()[pos] == QLatin1Char('/')) {
                cret = QDir::homePath();
                hadWord = true;
                goto getc;
            } else if (abortOnMeta) {
                goto metaerr;
            }
        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
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
        do {
            if (c == QLatin1Char('\'')) {
                int spos = pos;
                do {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                } while (c != QLatin1Char('\''));
                cret += args.mid(spos, pos-spos-1);
                hadWord = true;
            } else if (c == QLatin1Char('"')) {
                for (;;) {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                  nextq:
                    if (c == QLatin1Char('"'))
                        break;
                    if (c == QLatin1Char('\\')) {
                        if (pos >= args.length())
                            goto quoteerr;
                        c = args.unicode()[pos++];
                        if (c != QLatin1Char('"') &&
                            c != QLatin1Char('\\') &&
                            !(abortOnMeta &&
                              (c == QLatin1Char('$') ||
                               c == QLatin1Char('`'))))
                            cret += QLatin1Char('\\');
                    } else if (c == QLatin1Char('$') && env) {
                        if (pos >= args.length())
                            goto quoteerr;
                        c = args.unicode()[pos++];
                        bool braced = false;
                        if (c == QLatin1Char('{')) {
                            if (pos >= args.length())
                                goto quoteerr;
                            c = args.unicode()[pos++];
                            braced = true;
                        }
                        QString var;
                        while (c.isLetterOrNumber() || c == QLatin1Char('_')) {
                            var += c;
                            if (pos >= args.length())
                                goto quoteerr;
                            c = args.unicode()[pos++];
                        }
                        if (var == pwdName && pwd && !pwd->isEmpty()) {
                            cret += *pwd;
                        } else {
                            Environment::const_iterator vit = env->constFind(var);
                            if (vit == env->constEnd()) {
                                if (abortOnMeta)
                                    goto metaerr; // Assume this is a shell builtin
                            } else {
                                cret += *vit;
                            }
                        }
                        if (!braced)
                            goto nextq;
                        if (c != QLatin1Char('}')) {
                            if (abortOnMeta)
                                goto metaerr; // Assume this is a complex expansion
                            goto quoteerr; // Otherwise it's just garbage
                        }
                        continue;
                    } else if (abortOnMeta &&
                               (c == QLatin1Char('$') ||
                                c == QLatin1Char('`'))) {
                        goto metaerr;
                    }
                    cret += c;
                }
                hadWord = true;
            } else if (c == QLatin1Char('$') && env) {
                if (pos >= args.length())
                    goto quoteerr; // Bash just takes it verbatim, but whatever
                c = args.unicode()[pos++];
                bool braced = false;
                if (c == QLatin1Char('{')) {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                    braced = true;
                }
                QString var;
                while (c.isLetterOrNumber() || c == QLatin1Char('_')) {
                    var += c;
                    if (pos >= args.length()) {
                        if (braced)
                            goto quoteerr;
                        c = QLatin1Char(' ');
                        break;
                    }
                    c = args.unicode()[pos++];
                }
                QString val;
                if (var == pwdName && pwd && !pwd->isEmpty()) {
                    val = *pwd;
                } else {
                    Environment::const_iterator vit = env->constFind(var);
                    if (vit == env->constEnd()) {
                        if (abortOnMeta)
                            goto metaerr; // Assume this is a shell builtin
                    } else {
                        val = *vit;
                    }
                }
                for (int i = 0; i < val.length(); i++) {
                    QChar cc = val.unicode()[i];
                    if (cc == 9 || cc == 10 || cc == 32) {
                        if (hadWord) {
                            ret += cret;
                            cret.clear();
                            hadWord = false;
                        }
                    } else {
                        cret += cc;
                        hadWord = true;
                    }
                }
                if (!braced)
                    goto nextc;
                if (c != QLatin1Char('}')) {
                    if (abortOnMeta)
                        goto metaerr; // Assume this is a complex expansion
                    goto quoteerr; // Otherwise it's just garbage
                }
            } else {
                if (c == QLatin1Char('\\')) {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
478
                } else if (abortOnMeta && isMetaUnix(c)) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
479
480
481
482
483
                    goto metaerr;
                }
                cret += c;
                hadWord = true;
            }
484
          getc:
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
485
486
487
488
489
490
491
492
493
494
495
            if (pos >= args.length())
                break;
            c = args.unicode()[pos++];
          nextc: ;
        } while (!c.isSpace());
        if (hadWord)
            ret += cret;
    }

  okret:
    if (err)
496
        *err = QtcProcess::SplitOk;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
497
498
499
500
    return ret;

  quoteerr:
    if (err)
501
        *err = QtcProcess::BadQuoting;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
502
503
504
505
    return QStringList();

  metaerr:
    if (err)
506
        *err = QtcProcess::FoundMeta;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
    return QStringList();
}

inline static bool isSpecialCharUnix(ushort c)
{
    // Chars that should be quoted (TM). This includes:
    static const uchar iqm[] = {
        0xff, 0xff, 0xff, 0xff, 0xdf, 0x07, 0x00, 0xd8,
        0x00, 0x00, 0x00, 0x38, 0x01, 0x00, 0x00, 0x78
    }; // 0-32 \'"$`<>|;&(){}*?#!~[]

    return (c < sizeof(iqm) * 8) && (iqm[c / 8] & (1 << (c & 7)));
}

inline static bool hasSpecialCharsUnix(const QString &arg)
{
    for (int x = arg.length() - 1; x >= 0; --x)
        if (isSpecialCharUnix(arg.unicode()[x].unicode()))
            return true;
    return false;
}

529
530
531
532
533
534
535
536
537
538
QStringList QtcProcess::splitArgs(const QString &args, OsType osType,
                                  bool abortOnMeta, QtcProcess::SplitError *err,
                                  const Environment *env, const QString *pwd)
{
    if (osType == OsTypeWindows)
        return splitArgsWin(args, abortOnMeta, err, env, pwd);
    else
        return splitArgsUnix(args, abortOnMeta, err, env, pwd);
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
539
540
541
542
543
544
545
546
547
548
549
550
551
552
QString QtcProcess::quoteArgUnix(const QString &arg)
{
    if (!arg.length())
        return QString::fromLatin1("''");

    QString ret(arg);
    if (hasSpecialCharsUnix(ret)) {
        ret.replace(QLatin1Char('\''), QLatin1String("'\\''"));
        ret.prepend(QLatin1Char('\''));
        ret.append(QLatin1Char('\''));
    }
    return ret;
}

553
static bool isSpecialCharWin(ushort c)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
554
555
556
557
558
559
560
561
562
563
564
565
566
{
    // Chars that should be quoted (TM). This includes:
    // - control chars & space
    // - the shell meta chars "&()<>^|
    // - the potential separators ,;=
    static const uchar iqm[] = {
        0xff, 0xff, 0xff, 0xff, 0x45, 0x13, 0x00, 0x78,
        0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x10
    };

    return (c < sizeof(iqm) * 8) && (iqm[c / 8] & (1 << (c & 7)));
}

567
static bool hasSpecialCharsWin(const QString &arg)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
568
569
{
    for (int x = arg.length() - 1; x >= 0; --x)
570
        if (isSpecialCharWin(arg.unicode()[x].unicode()))
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
571
572
573
574
            return true;
    return false;
}

575
static QString quoteArgWin(const QString &arg)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
576
577
578
579
580
{
    if (!arg.length())
        return QString::fromLatin1("\"\"");

    QString ret(arg);
581
    if (hasSpecialCharsWin(ret)) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
582
583
584
585
586
587
588
        // Quotes are escaped and their preceding backslashes are doubled.
        // It's impossible to escape anything inside a quoted string on cmd
        // level, so the outer quoting must be "suspended".
        ret.replace(QRegExp(QLatin1String("(\\\\*)\"")), QLatin1String("\"\\1\\1\\^\"\""));
        // 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\"
589
590
591
592
        int i = ret.length();
        while (i > 0 && ret.at(i - 1) == QLatin1Char('\\'))
            --i;
        ret.insert(i, QLatin1Char('"'));
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
593
594
595
596
597
598
599
        ret.prepend(QLatin1Char('"'));
    }
    // FIXME: Without this, quoting is not foolproof. But it needs support in the process setup, etc.
    //ret.replace('%', QLatin1String("%PERCENT_SIGN%"));
    return ret;
}

600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
QtcProcess::Arguments QtcProcess::prepareArgs(const QString &cmd, SplitError *err, OsType osType,
                                   const Environment *env, const QString *pwd)
{
    if (osType == OsTypeWindows)
        return prepareArgsWin(cmd, err, env, pwd);
    else
        return Arguments::createUnixArgs(splitArgs(cmd, osType, true, err, env, pwd));
}


QString QtcProcess::quoteArg(const QString &arg, OsType osType)
{
    if (osType == OsTypeWindows)
        return quoteArgWin(arg);
    else
        return quoteArgUnix(arg);
}

void QtcProcess::addArg(QString *args, const QString &arg, OsType osType)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
619
620
621
{
    if (!args->isEmpty())
        *args += QLatin1Char(' ');
622
    *args += quoteArg(arg, osType);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
623
624
}

625
QString QtcProcess::joinArgs(const QStringList &args, OsType osType)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
626
627
628
{
    QString ret;
    foreach (const QString &arg, args)
629
        addArg(&ret, arg, osType);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
    return ret;
}

void QtcProcess::addArgs(QString *args, const QString &inArgs)
{
    if (!inArgs.isEmpty()) {
        if (!args->isEmpty())
            *args += QLatin1Char(' ');
        *args += inArgs;
    }
}

void QtcProcess::addArgs(QString *args, const QStringList &inArgs)
{
    foreach (const QString &arg, inArgs)
        addArg(args, arg);
}

bool QtcProcess::prepareCommand(const QString &command, const QString &arguments,
649
                                QString *outCmd, Arguments *outArgs, OsType osType,
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
650
651
652
                                const Environment *env, const QString *pwd)
{
    QtcProcess::SplitError err;
653
    *outArgs = QtcProcess::prepareArgs(arguments, &err, osType, env, pwd);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
654
655
656
    if (err == QtcProcess::SplitOk) {
        *outCmd = command;
    } else {
657
658
659
660
661
662
663
664
665
666
667
668
669
        if (osType == OsTypeWindows) {
            *outCmd = QString::fromLatin1(qgetenv("COMSPEC"));
            *outArgs = Arguments::createWindowsArgs(QLatin1String("/v:off /s /c \"")
                    + quoteArg(QDir::toNativeSeparators(command)) + QLatin1Char(' ') + arguments
                    + QLatin1Char('"'));
        } else {
            if (err != QtcProcess::FoundMeta)
                return false;
            *outCmd = QLatin1String("/bin/sh");
            *outArgs = Arguments::createUnixArgs(QStringList()
                            << QLatin1String("-c")
                            << (quoteArg(command) + QLatin1Char(' ') + arguments));
        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
670
671
672
673
674
675
676
    }
    return true;
}

void QtcProcess::start()
{
    Environment env;
677
    const OsType osType = HostOsInfo::hostOs();
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
678
    if (m_haveEnv) {
Friedemann Kleint's avatar
Friedemann Kleint committed
679
680
        if (m_environment.size() == 0)
            qWarning("QtcProcess::start: Empty environment set when running '%s'.", qPrintable(m_command));
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
681
        env = m_environment;
682
683
684
685

        // If the process environemnt has no libraryPath,
        // Qt will copy creator's libraryPath into the process environment.
        // That's brain dead, and we work around it
686
687
688
689
690
691
        if (osType != OsTypeWindows) {  // a.k.a "Unixoid"
            const QString libraryPath =
                QLatin1String(osType == OsTypeMac ? "DYLD_LIBRARY_PATH" : "LD_LIBRARY_PATH");
            if (env.constFind(libraryPath) == env.constEnd())
                env.set(libraryPath, QString());
        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
692
693
694
695
696
697
698
        QProcess::setEnvironment(env.toStringList());
    } else {
        env = Environment::systemEnvironment();
    }

    const QString &workDir = workingDirectory();
    QString command;
699
700
701
    QtcProcess::Arguments arguments;
    bool success = prepareCommand(m_command, m_arguments, &command, &arguments, osType, &env, &workDir);
    if (osType == OsTypeWindows) {
hjk's avatar
hjk committed
702
703
704
705
706
707
708
        QString args;
        if (m_useCtrlCStub) {
            args = QtcProcess::quoteArg(QDir::toNativeSeparators(command));
            command = QCoreApplication::applicationDirPath()
                    + QLatin1String("/qtcreator_ctrlc_stub.exe");
        }
        QtcProcess::addArgs(&args, arguments.toWindowsArgs());
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
709
#ifdef Q_OS_WIN
710
        setNativeArguments(args);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
711
#endif
hjk's avatar
hjk committed
712
713
714
        // Note: Arguments set with setNativeArgs will be appended to the ones
        // passed with start() below.
        QProcess::start(command, QStringList());
715
716
717
718
719
720
721
722
723
724
    } else {
        if (!success) {
            setErrorString(tr("Error in command line."));
            // Should be FailedToStart, but we cannot set the process error from the outside,
            // so it would be inconsistent.
            emit error(QProcess::UnknownError);
            return;
        }
        QProcess::start(command, arguments.toUnixArgs());
    }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
725
726
}

727
#ifdef Q_OS_WIN
728
static BOOL sendMessage(UINT message, HWND hwnd, LPARAM lParam)
729
730
731
{
    DWORD dwProcessID;
    GetWindowThreadProcessId(hwnd, &dwProcessID);
732
    if ((DWORD)lParam == dwProcessID) {
733
        SendNotifyMessage(hwnd, message, 0, 0);
734
735
736
737
        return FALSE;
    }
    return TRUE;
}
738
739
740
741
742
743
744
745
746
747
748
749

BOOL CALLBACK sendShutDownMessageToAllWindowsOfProcess_enumWnd(HWND hwnd, LPARAM lParam)
{
    static UINT uiShutDownMessage = RegisterWindowMessage(L"qtcctrlcstub_shutdown");
    return sendMessage(uiShutDownMessage, hwnd, lParam);
}

BOOL CALLBACK sendInterruptMessageToAllWindowsOfProcess_enumWnd(HWND hwnd, LPARAM lParam)
{
    static UINT uiInterruptMessage = RegisterWindowMessage(L"qtcctrlcstub_interrupt");
    return sendMessage(uiInterruptMessage, hwnd, lParam);
}
750
751
752
753
754
755
756
757
758
759
760
761
#endif

void QtcProcess::terminate()
{
#ifdef Q_OS_WIN
    if (m_useCtrlCStub)
        EnumWindows(sendShutDownMessageToAllWindowsOfProcess_enumWnd, pid()->dwProcessId);
    else
#endif
    QProcess::terminate();
}

762
763
void QtcProcess::interrupt()
{
764
#ifdef Q_OS_WIN
765
766
    QTC_ASSERT(m_useCtrlCStub, return);
    EnumWindows(sendInterruptMessageToAllWindowsOfProcess_enumWnd, pid()->dwProcessId);
767
#endif
768
}
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
769
770
771

// This function assumes that the resulting string will be quoted.
// That's irrelevant if it does not contain quotes itself.
772
static int quoteArgInternalWin(QString &ret, int bslashes)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
{
    // Quotes are escaped and their preceding backslashes are doubled.
    // It's impossible to escape anything inside a quoted string on cmd
    // level, so the outer quoting must be "suspended".
    const QChar bs(QLatin1Char('\\')), dq(QLatin1Char('"'));
    for (int p = 0; p < ret.length(); p++) {
        if (ret.at(p) == bs) {
            bslashes++;
        } else {
            if (ret.at(p) == dq) {
                if (bslashes) {
                    ret.insert(p, QString(bslashes, bs));
                    p += bslashes;
                }
                ret.insert(p, QLatin1String("\"\\^\""));
                p += 4;
            }
            bslashes = 0;
        }
    }
    return bslashes;
}


// TODO: This documentation is relevant for end-users. Where to put it?
/**
 * Perform safe macro expansion (substitution) on a string for use
 * in shell commands.
 *
 * \section Unix notes
 *
 * Explicitly supported shell constructs:
 *   \\ '' "" {} () $(()) ${} $() ``
 *
 * Implicitly supported shell constructs:
 *   (())
 *
 * Unsupported shell constructs that will cause problems:
 * \list
 * \li Shortened \c{case $v in pat)} syntax. Use \c{case $v in (pat)} instead.
 * \li Bash-style \c{$""} and \c{$''} string quoting syntax.
 * \endlist
 *
 * The rest of the shell (incl. bash) syntax is simply ignored,
 * as it is not expected to cause problems.
 *
 * Security considerations:
 * \list
 * \li Backslash-escaping an expando is treated as a quoting error
 * \li Do not put expandos into double quoted substitutions:
 *     \badcode
 *       "${VAR:-%{macro}}"
 *     \endcode
 * \li Do not put expandos into command line arguments which are nested
 *     shell commands:
 *     \badcode
 *       sh -c 'foo \%{file}'
 *     \endcode
 *     \goodcode
 *       file=\%{file} sh -c 'foo "$file"'
 *     \endcode
 * \endlist
 *
 * \section Windows notes
 *
 * All quoting syntax supported by splitArgs() is supported here as well.
 * Additionally, command grouping via parentheses is recognized - note
 * however, that the parser is much stricter about unquoted parentheses
 * than cmd itself.
 * The rest of the cmd syntax is simply ignored, as it is not expected
 * to cause problems.
 *
 * Security considerations:
 * \list
 * \li Circumflex-escaping an expando is treated as a quoting error
 * \li Closing double quotes right before expandos and opening double quotes
 *     right after expandos are treated as quoting errors
 * \li Do not put expandos into nested commands:
 *     \badcode
 *       for /f "usebackq" \%v in (`foo \%{file}`) do \@echo \%v
 *     \endcode
 * \li A macro's value must not contain anything which may be interpreted
 *     as an environment variable expansion. A solution is replacing any
 *     percent signs with a fixed string like \c{\%PERCENT_SIGN\%} and
 *     injecting \c{PERCENT_SIGN=\%} into the shell's environment.
 * \li Enabling delayed environment variable expansion (cmd /v:on) should have
 *     no security implications, but may still wreak havoc due to the
 *     need for doubling circumflexes if any exclamation marks are present,
 *     and the need to circumflex-escape the exclamation marks themselves.
 * \endlist
 *
 * \param cmd pointer to the string in which macros are expanded in-place
 * \param mx pointer to a macro expander instance
 * \return false if the string could not be parsed and therefore no safe
 *   substitution was possible
 */
869
bool QtcProcess::expandMacros(QString *cmd, AbstractMacroExpander *mx, OsType osType)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
870
871
872
873
874
875
876
877
878
879
880
881
882
{
    QString str = *cmd;
    if (str.isEmpty())
        return true;

    QString rsts;
    int varLen;
    int varPos = 0;
    if (!(varLen = mx->findMacro(str, &varPos, &rsts)))
        return true;

    int pos = 0;

883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
    if (osType == OsTypeWindows) {
        enum { // cmd.exe parsing state
            ShellBasic, // initial state
            ShellQuoted, // double-quoted state => *no* other meta chars are interpreted
            ShellEscaped // circumflex-escaped state => next char is not interpreted
        } shellState = ShellBasic;
        enum { // CommandLineToArgv() parsing state and some more
            CrtBasic, // initial state
            CrtNeedWord, // after empty expando; insert empty argument if whitespace follows
            CrtInWord, // in non-whitespace
            CrtClosed, // previous char closed the double-quoting
            CrtHadQuote, // closed double-quoting after an expando
            // The remaining two need to be numerically higher
            CrtQuoted, // double-quoted state => spaces don't split tokens
            CrtNeedQuote // expando opened quote; close if no expando follows
        } crtState = CrtBasic;
        int bslashes = 0; // previous chars were manual backslashes
        int rbslashes = 0; // trailing backslashes in replacement
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
901

902
903
904
905
906
907
908
909
910
911
912
913
914
915
        forever {
            if (pos == varPos) {
                if (shellState == ShellEscaped)
                    return false; // Circumflex'd quoted expando would be Bad (TM).
                if ((shellState == ShellQuoted) != (crtState == CrtQuoted))
                    return false; // CRT quoting out of sync with shell quoting. Ahoy to Redmond.
                rbslashes += bslashes;
                bslashes = 0;
                if (crtState < CrtQuoted) {
                    if (rsts.isEmpty()) {
                        if (crtState == CrtBasic) {
                            // Outside any quoting and the string is empty, so put
                            // a pair of quotes. Delaying that is just pedantry.
                            crtState = CrtNeedWord;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
916
917
                        }
                    } else {
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
                        if (hasSpecialCharsWin(rsts)) {
                            if (crtState == CrtClosed) {
                                // Quoted expando right after closing quote. Can't do that.
                                return false;
                            }
                            int tbslashes = quoteArgInternalWin(rsts, 0);
                            rsts.prepend(QLatin1Char('"'));
                            if (rbslashes)
                                rsts.prepend(QString(rbslashes, QLatin1Char('\\')));
                            crtState = CrtNeedQuote;
                            rbslashes = tbslashes;
                        } else {
                            crtState = CrtInWord; // We know that this string contains no spaces.
                            // We know that this string contains no quotes,
                            // so the function won't make a mess.
                            rbslashes = quoteArgInternalWin(rsts, rbslashes);
                        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
935
                    }
936
937
                } else {
                    rbslashes = quoteArgInternalWin(rsts, rbslashes);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
938
                }
939
940
941
942
943
944
945
946
947
                str.replace(pos, varLen, rsts);
                pos += rsts.length();
                varPos = pos;
                if (!(varLen = mx->findMacro(str, &varPos, &rsts))) {
                    // Don't leave immediately, as we may be in CrtNeedWord state which could
                    // be still resolved, or we may have inserted trailing backslashes.
                    varPos = INT_MAX;
                }
                continue;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
948
            }
949
950
951
952
953
954
            if (crtState == CrtNeedQuote) {
                if (rbslashes) {
                    str.insert(pos, QString(rbslashes, QLatin1Char('\\')));
                    pos += rbslashes;
                    varPos += rbslashes;
                    rbslashes = 0;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
955
                }
956
957
958
959
960
961
962
963
                str.insert(pos, QLatin1Char('"'));
                pos++;
                varPos++;
                crtState = CrtHadQuote;
            }
            ushort cc = str.unicode()[pos].unicode();
            if (shellState == ShellBasic && cc == '^') {
                shellState = ShellEscaped;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
964
            } else {
965
966
967
968
969
970
                if (!cc || cc == ' ' || cc == '\t') {
                    if (crtState < CrtQuoted) {
                        if (crtState == CrtNeedWord) {
                            str.insert(pos, QLatin1String("\"\""));
                            pos += 2;
                            varPos += 2;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
971
                        }
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
                        crtState = CrtBasic;
                    }
                    if (!cc)
                        break;
                    bslashes = 0;
                    rbslashes = 0;
                } else {
                    if (cc == '\\') {
                        bslashes++;
                        if (crtState < CrtQuoted)
                            crtState = CrtInWord;
                    } else {
                        if (cc == '"') {
                            if (shellState != ShellEscaped)
                                shellState = (shellState == ShellQuoted) ? ShellBasic : ShellQuoted;
                            if (rbslashes) {
                                // Offset -1: skip possible circumflex. We have at least
                                // one backslash, so a fixed offset is ok.
                                str.insert(pos - 1, QString(rbslashes, QLatin1Char('\\')));
                                pos += rbslashes;
                                varPos += rbslashes;
                            }
                            if (!(bslashes & 1)) {
                                // Even number of backslashes, so the quote is not escaped.
                                switch (crtState) {
                                case CrtQuoted:
                                    // Closing quote
                                    crtState = CrtClosed;
                                    break;
                                case CrtClosed:
                                    // Two consecutive quotes make a literal quote - and
                                    // still close quoting. See QtcProcess::quoteArg().
                                    crtState = CrtInWord;
                                    break;
                                case CrtHadQuote:
                                    // Opening quote right after quoted expando. Can't do that.
                                    return false;
                                default:
                                    // Opening quote
                                    crtState = CrtQuoted;
                                    break;
                                }
                            } else if (crtState < CrtQuoted) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1015
1016
1017
1018
1019
                                crtState = CrtInWord;
                            }
                        } else if (crtState < CrtQuoted) {
                            crtState = CrtInWord;
                        }
1020
1021
                        bslashes = 0;
                        rbslashes = 0;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1022
1023
                    }
                }
1024
1025
1026
1027
                if (varPos == INT_MAX && !rbslashes)
                    break;
                if (shellState == ShellEscaped)
                    shellState = ShellBasic;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1028
            }
1029
            pos++;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1030
        }
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
    } else {
        // !Windows
        MxState state = { MxBasic, false };
        QStack<MxState> sstack;
        QStack<MxSave> ostack;

        while (pos < str.length()) {
            if (pos == varPos) {
                // Our expansion rules trigger in any context
                if (state.dquote) {
                    // We are within a double-quoted string. Escape relevant meta characters.
                    rsts.replace(QRegExp(QLatin1String("([$`\"\\\\])")), QLatin1String("\\\\1"));
                } else if (state.current == MxSingleQuote) {
                    // We are within a single-quoted string. "Suspend" single-quoting and put a
                    // single escaped quote for each single quote inside the string.
                    rsts.replace(QLatin1Char('\''), QLatin1String("'\\''"));
                } else if (rsts.isEmpty() || hasSpecialCharsUnix(rsts)) {
                    // String contains "quote-worthy" characters. Use single quoting - but
                    // that choice is arbitrary.
                    rsts.replace(QLatin1Char('\''), QLatin1String("'\\''"));
                    rsts.prepend(QLatin1Char('\''));
                    rsts.append(QLatin1Char('\''));
                } // Else just use the string verbatim.
                str.replace(pos, varLen, rsts);
                pos += rsts.length();
                varPos = pos;
                if (!(varLen = mx->findMacro(str, &varPos, &rsts)))
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1058
                    break;
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
                continue;
            }
            ushort cc = str.unicode()[pos].unicode();
            if (state.current == MxSingleQuote) {
                // Single quoted context - only the single quote has any special meaning.
                if (cc == '\'')
                    state = sstack.pop();
            } else if (cc == '\\') {
                // In any other context, the backslash starts an escape.
                pos += 2;
                if (varPos < pos)
                    return false; // Backslash'd quoted expando would be Bad (TM).
                continue;
            } else if (cc == '$') {
                cc = str.unicode()[++pos].unicode();
                if (cc == '(') {
                    sstack.push(state);
                    if (str.unicode()[pos + 1].unicode() == '(') {
                        // $(( starts a math expression. This may also be a $( ( in fact,
                        // so we push the current string and offset on a stack so we can retry.
                        MxSave sav = { str, pos + 2, varPos };
                        ostack.push(sav);
                        state.current = MxMath;
                        pos += 2;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1083
                        continue;
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
                    } else {
                        // $( starts a command substitution. This actually "opens a new context"
                        // which overrides surrounding double quoting.
                        state.current = MxParen;
                        state.dquote = false;
                    }
                } else if (cc == '{') {
                    // ${ starts a "braced" variable substitution.
                    sstack.push(state);
                    state.current = MxSubst;
                } // Else assume that a "bare" variable substitution has started
            } else if (cc == '`') {
                // Backticks are evil, as every shell interprets escapes within them differently,
                // which is a danger for the quoting of our own expansions.
                // So we just apply *our* rules (which match bash) and transform it into a POSIX
                // command substitution which has clear semantics.
                str.replace(pos, 1, QLatin1String("$( " )); // add space -> avoid creating $((
                varPos += 2;
                int pos2 = pos += 3;
                forever {
                    if (pos2 >= str.length())
                        return false; // Syntax error - unterminated backtick expression.
                    cc = str.unicode()[pos2].unicode();
                    if (cc == '`')
                        break;
                    if (cc == '\\') {
                        cc = str.unicode()[++pos2].unicode();
                        if (cc == '$' || cc == '`' || cc == '\\' ||
                            (cc == '"' && state.dquote))
                        {
                            str.remove(pos2 - 1, 1);
                            if (varPos >= pos2)
                                varPos--;
                            continue;
                        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1119
                    }
1120
                    pos2++;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1121
                }
1122
                str[pos2] = QLatin1Char(')');
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1123
                sstack.push(state);
1124
1125
1126
1127
1128
1129
                state.current = MxParen;
                state.dquote = false;
                continue;
            } else if (state.current == MxDoubleQuote) {
                // (Truly) double quoted context - only remaining special char is the closing quote.
                if (cc == '"')
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1130
                    state = sstack.pop();
1131
1132
1133
            } else if (cc == '\'') {
                // Start single quote if we are not in "inherited" double quoted context.
                if (!state.dquote) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1134
                    sstack.push(state);
1135
                    state.current = MxSingleQuote;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1136
                }
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
            } else if (cc == '"') {
                // Same for double quoting.
                if (!state.dquote) {
                    sstack.push(state);
                    state.current = MxDoubleQuote;
                    state.dquote = true;
                }
            } else if (state.current == MxSubst) {
                // "Braced" substitution context - only remaining special char is the closing brace.
                if (cc == '}')
                    state = sstack.pop();
            } else if (cc == ')') {
                if (state.current == MxMath) {
                    if (str.unicode()[pos + 1].unicode() == ')') {
                        state = sstack.pop();
                        pos += 2;
                    } else {
                        // False hit: the $(( was a $( ( in fact.
                        // ash does not care (and will complain), but bash actually parses it.
                        varPos = ostack.top().varPos;
                        pos = ostack.top().pos;
                        str = ostack.top().str;
                        ostack.pop();
                        state.current = MxParen;
                        state.dquote = false;
                        sstack.push(state);
                    }
                    continue;
                } else if (state.current == MxParen) {
                    state = sstack.pop();
                } else {
                    break; // Syntax error - excess closing parenthesis.
                }
            } else if (cc == '}') {
                if (state.current == MxGroup)
                    state = sstack.pop();
                else
                    break; // Syntax error - excess closing brace.
            } else if (cc == '(') {
                // Context-saving command grouping.
                sstack.push(state);
                state.current = MxParen;
            } else if (cc == '{') {
                // Plain command grouping.
                sstack.push(state);
                state.current = MxGroup;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1183
            }
1184
            pos++;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1185
        }
1186
        // FIXME? May complain if (!sstack.empty()), but we don't really care anyway.
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1187
1188
1189
1190
1191
1192
    }

    *cmd = str;
    return true;
}

1193
QString QtcProcess::expandMacros(const QString &str, AbstractMacroExpander *mx, OsType osType)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1194
1195
{
    QString ret = str;
1196
    expandMacros(&ret, mx, osType);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
    return ret;
}

bool QtcProcess::ArgIterator::next()
{
    // We delay the setting of m_prev so we can still delete the last argument
    // after we find that there are no more arguments. It's a bit of a hack ...
    int prev = m_pos;

    m_simple = true;
    m_value.clear();

1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
    if (m_osType == OsTypeWindows) {
        enum { // cmd.exe parsing state
            ShellBasic, // initial state
            ShellQuoted, // double-quoted state => *no* other meta chars are interpreted
            ShellEscaped // circumflex-escaped state => next char is not interpreted
        } shellState = ShellBasic;
        enum { // CommandLineToArgv() parsing state and some more
            CrtBasic, // initial state
            CrtInWord, // in non-whitespace
            CrtClosed, // previous char closed the double-quoting
            CrtQuoted // double-quoted state => spaces don't split tokens
        } crtState = CrtBasic;
        enum { NoVar, NewVar, FullVar } varState = NoVar; // inside a potential env variable expansion
        int bslashes = 0; // number of preceding backslashes

        for (;; m_pos++) {
            ushort cc = m_pos < m_str->length() ? m_str->unicode()[m_pos].unicode() : 0;
            if (shellState == ShellBasic && cc == '^') {
                varState = NoVar;
                shellState = ShellEscaped;
            } else if ((shellState == ShellBasic && isMetaCharWin(cc)) || !cc) { // A "bit" simplistic ...
                // We ignore crtQuote state here. Whatever ...
              doReturn:
                if (m_simple)
                    while (--bslashes >= 0)
                        m_value += QLatin1Char('\\');
                else
                    m_value.clear();
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1237
                if (crtState != CrtBasic) {
1238
1239
                    m_prev = prev;
                    return true;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1240
                }
1241
                return false;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1242
            } else {
1243
1244
1245
1246
1247
                if (crtState != CrtQuoted && (cc == ' ' || cc == '\t')) {
                    if (crtState != CrtBasic) {
                        // We'll lose shellQuote state here. Whatever ...
                        goto doReturn;
                    }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1248
                } else {
1249
1250
1251
                    if (cc == '\\') {
                        bslashes++;
                        if (crtState != CrtQuoted)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1252
                            crtState = CrtInWord;
1253
                        varState = NoVar;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1254
                    } else {
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
                        if (cc == '"') {
                            varState = NoVar;
                            if (shellState != ShellEscaped)
                                shellState = (shellState == ShellQuoted) ? ShellBasic : ShellQuoted;
                            int obslashes = bslashes;
                            bslashes >>= 1;
                            if (!(obslashes & 1)) {
                                // Even number of backslashes, so the quote is not escaped.
                                switch (crtState) {
                                case CrtQuoted:
                                    // Closing quote
                                    crtState = CrtClosed;
                                    continue;
                                case CrtClosed:
                                    // Two consecutive quotes make a literal quote - and
                                    // still close quoting. See quoteArg().
                                    crtState = CrtInWord;
                                    break;
                                default:
                                    // Opening quote
                                    crtState = CrtQuoted;
                                    continue;
                                }
                            } else if (crtState != CrtQuoted) {
                                crtState = CrtInWord;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1280
                            }
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
                        } else {
                            if (cc == '%') {
                                if (varState == FullVar) {
                                    m_simple = false;
                                    varState = NoVar;
                                } else {
                                    varState = NewVar;
                                }
                            } else if (varState != NoVar) {
                                // This check doesn't really reflect cmd reality, but it is an
                                // approximation of what would be sane.
                                varState = (cc == '_' || cc == '-' || cc == '.'
                                         || QChar(cc).isLetterOrNumber()) ? FullVar : NoVar;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1294

1295
1296
1297
                            }
                            if (crtState != CrtQuoted)
                                crtState = CrtInWord;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1298
                        }
1299
1300
1301
                        for (; bslashes > 0; bslashes--)
                            m_value += QLatin1Char('\\');
                        m_value += QChar(cc);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1302
1303
                    }
                }
1304
1305
                if (shellState == ShellEscaped)
                    shellState = ShellBasic;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1306
1307
            }
        }
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
    } else {
        MxState state = { MxBasic, false };
        QStack<MxState> sstack;
        QStack<int> ostack;
        bool hadWord = false;

        for (; m_pos < m_str->length(); m_pos++) {
            ushort cc = m_str->unicode()[m_pos].unicode();
            if (state.current == MxSingleQuote) {
                if (cc == '\'') {
                    state = sstack.pop();
                    continue;
                }
            } else if (cc == '\\') {
                if (++m_pos >= m_str->length())
                    break;
                cc = m_str->unicode()[m_pos].unicode();
                if (state.dquote && cc != '"' && cc != '\\' && cc != '$' && cc != '`')
                    m_value += QLatin1Char('\\');
            } else if (cc == '$') {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1328
1329
                if (++m_pos >= m_str->length())
                    break;
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
                cc = m_str->unicode()[m_pos].unicode();
                if (cc == '(') {
                    sstack.push(state);
                    if (++m_pos >= m_str->length())
                        break;
                    if (m_str->unicode()[m_pos].unicode() == '(') {
                        ostack.push(m_pos);
                        state.current = MxMath;
                    } else {
                        state.dquote = false;
                        state.current = MxParen;
                        // m_pos too far by one now - whatever.
                    }
                } else if (cc == '{') {
                    sstack.push(state);
                    state.current = MxSubst;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1346
1347
1348
                } else {
                    // m_pos too far by one now - whatever.
                }
1349
                m_simple = false;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1350
1351
                hadWord = true;
                continue;
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
            } else if (cc == '`') {
                forever {
                    if (++m_pos >= m_str->length()) {
                        m_simple = false;
                        m_prev = prev;
                        return true;
                    }
                    cc = m_str->unicode()[m_pos].unicode();
                    if (cc == '`')
                        break;
                    if (cc == '\\')
                        m_pos++; // m_pos may be too far by one now - whatever.
                }
                m_simple = false;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1366
1367
                hadWord = true;
                continue;
1368
1369
            } else if (state.current == MxDoubleQuote) {
                if (cc == '"') {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1370
                    state = sstack.pop();
1371
1372
1373
1374
                    continue;
                }
            } else if (cc == '\'') {
                if (!state.dquote) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1375
                    sstack.push(state);
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
                    state.current = MxSingleQuote;
                    hadWord = true;
                    continue;
                }
            } else if (cc == '"') {
                if (!state.dquote) {
                    sstack.push(state);
                    state.dquote = true;
                    state.current = MxDoubleQuote;
                    hadWord = true;
                    continue;
                }
            } else if (state.current == MxSubst) {
                if (cc == '}')
                    state = sstack.pop();
                continue; // Not simple anyway
            } else if (cc == ')') {
                if (state.current == MxMath) {
                    if (++m_pos >= m_str->length())
                        break;
                    if (m_str->unicode()[m_pos].unicode() == ')') {
                        ostack.pop();
                        state = sstack.pop();
                    } else {
                        // false hit: the $(( was a $( ( in fact.
                        // ash does not care, but bash does.
                        m_pos = ostack.pop();
                        state.current = MxParen;
                        state.dquote = false;
                        sstack.push(state);
                    }
                    continue;
                } else if (state.current == MxParen) {
                    state = sstack.pop();
                    continue;
                } else {
                    break;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1413
1414
                }
#if 0 // MxGroup is impossible, see below.
1415
1416
1417
1418
1419
            } else if (cc == '}') {
                if (state.current == MxGroup) {
                    state = sstack.pop();
                    continue;
                }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1420
#endif
1421
1422
1423
1424
1425
            } else if (cc == '(') {
                sstack.push(state);
                state.current = MxParen;
                m_simple = false;
                hadWord = true;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1426
#if 0 // Should match only at the beginning of a command, which we never have currently.
1427
1428
1429
1430
1431
            } else if (cc == '{') {
                sstack.push(state);
                state.current = MxGroup;
                m_simple = false;
                hadWord = true;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1432
                continue;
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
#endif
            } else if (cc == '<' || cc == '>' || cc == '&' || cc == '|' || cc == ';') {
                if (sstack.isEmpty())
                    break;
            } else if (cc == ' ' || cc == '\t') {
                if (!hadWord)
                    continue;
                if (sstack.isEmpty())
                    break;
            }
            m_value += QChar(cc);
            hadWord = true;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1445
        }
1446
1447
1448
1449
1450
1451
1452
1453
        // TODO: Possibly complain here if (!sstack.empty())
        if (!m_simple)
            m_value.clear();
        if (hadWord) {
            m_prev = prev;
            return true;
        }
        return false;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
    }
}

void QtcProcess::ArgIterator::deleteArg()
{
    if (!m_prev)
        while (m_pos < m_str->length() && m_str->at(m_pos).isSpace())
            m_pos++;
    m_str->remove(m_prev, m_pos - m_prev);
    m_pos = m_prev;
}

void QtcProcess::ArgIterator::appendArg(const QString &str)
{
    const QString qstr = quoteArg(str);
    if (!m_pos)
        m_str->insert(0, qstr + QLatin1Char(' '));
    else
        m_str->insert(m_pos, QLatin1Char(' ') + qstr);
    m_pos += qstr.length() + 1;
}
hjk's avatar
hjk committed
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485

QTCREATOR_UTILS_EXPORT unsigned long qPidToPid(const Q_PID qpid)
{
#ifdef Q_OS_WIN
    const PROCESS_INFORMATION *processInfo = reinterpret_cast<const PROCESS_INFORMATION*>(qpid);
    return processInfo->dwProcessId;
#else
    return qpid;
#endif
}

1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
QtcProcess::Arguments QtcProcess::Arguments::createWindowsArgs(const QString &args)
{
    Arguments result;
    result.m_windowsArgs = args;
    result.m_isWindows = true;
    return result;
}

QtcProcess::Arguments QtcProcess::Arguments::createUnixArgs(const QStringList &args)
{
    Arguments result;
    result.m_unixArgs = args;
    result.m_isWindows = false;
    return result;
}

QString QtcProcess::Arguments::toWindowsArgs() const
{
    QTC_CHECK(m_isWindows);
    return m_windowsArgs;
}

QStringList QtcProcess::Arguments::toUnixArgs() const
{
    QTC_CHECK(!m_isWindows);
    return m_unixArgs;
}

QString QtcProcess::Arguments::toString() const
{
    if (m_isWindows)
        return m_windowsArgs;
    else
        return QtcProcess::joinArgs(m_unixArgs, OsTypeLinux);
}

hjk's avatar
hjk committed
1522
} // namespace Utils