summaryrefslogtreecommitdiffstats
path: root/src/qtchooser/main.cpp
blob: 1a3aa99ef55e5962432a4e9c499d7db3af8e29a1 (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
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
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
/****************************************************************************
**
** Copyright (C) 2014 Intel Corporation.
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU Lesser General Public License Usage
** 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
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 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 the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

/*
 * This tool is meant to wrap the other Qt tools by searching for different
 * instances of Qt on the system. It's mostly destined to be used on Unix
 * systems other than Mac OS X. For that reason, it uses POSIX APIs and does
 * not try to be compatible with the DOS or Win32 APIs. In particular, it uses
 * opendir(3) and readdir(3) as well as paths exclusively separated by slashes.
 */

#define _CRT_SECURE_NO_WARNINGS
#define _POSIX_C_SOURCE 200809L

#include <algorithm>
#include <set>
#include <string>
#include <vector>

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>

#if defined(_WIN32) || defined(__WIN32__)
#  include <process.h>
#  define execv _execv
#  define stat _stat
#  define PATH_SEP "\\"
#  define EXE_SUFFIX ".exe"
#else
#  include <sys/types.h>
#  include <sys/stat.h>
#  include <dirent.h>
#  include <fcntl.h>
#  include <libgen.h>
#  include <pwd.h>
#  include <unistd.h>
#  define PATH_SEP "/"
#  define EXE_SUFFIX ""
#endif

using namespace std;

static const char myName[] = "qtchooser" EXE_SUFFIX;
static const char confSuffix[] = ".conf";

static const char *argv0;
enum Mode {
    Unknown,
    PrintHelp,
    RunTool,
    ListVersions,
    PrintEnvironment,
    Install
};

enum InstallOptions
{
    GlobalInstall    = 0,
    LocalInstall     = 1,

    NoOverwrite      = 0,
    ForceOverwrite   = 2
};

struct Sdk
{
    string name;
    string configFile;
    string toolsPath;
    string librariesPath;

    bool isValid() const { return !toolsPath.empty(); }
    bool hasTool(const string &targetTool) const;
};

bool Sdk::hasTool(const string &targetTool) const
{
    struct stat st;
    if (toolsPath.empty())
        return false;
    if (stat((toolsPath + PATH_SEP + targetTool).c_str(), &st))
        return false;
#ifdef S_IEXEC
    return (st.st_mode & S_IEXEC);
#endif
    return true;
}

struct ToolWrapper
{
    int printHelp();
    int listVersions();
    int printEnvironment(const string &targetSdk);
    int runTool(const string &targetSdk, const string &targetTool, char **argv);
    int install(const string &sdkName, const string &qmake, int installOptions);

private:
    vector<string> searchPaths() const;

    typedef bool (*VisitFunction)(const string &targetSdk, Sdk &item);
    typedef void (*FinishFunction)(const set<string> &seenSdks);
    Sdk iterateSdks(const string &targetSdk, VisitFunction visit, FinishFunction finish = 0,
                    const string &targetTool = "");
    Sdk selectSdk(const string &targetSdk, const string &targetTool = "");

    static void printSdks(const set<string> &seenNames);
    static bool matchSdk(const string &targetSdk, Sdk &sdk);
};

int ToolWrapper::printHelp()
{
    puts("Usage:\n"
         "  qtchooser { -l | -list-versions | -print-env }\n"
         "  qtchooser -install [-f] [-local] <name> <path-to-qmake>\n"
         "  qtchooser -run-tool=<tool name> [-qt=<Qt version>] [program arguments]\n"
         "  <executable name> [-qt=<Qt version>] [program arguments]\n"
         "\n"
         "Environment variables accepted:\n"
         " QTCHOOSER_RUNTOOL  name of the tool to be run (same as the -run-tool argument)\n"
         " QT_SELECT          version of Qt to be run (same as the -qt argument)\n");
    return 0;
}

int ToolWrapper::listVersions()
{
    iterateSdks(string(), 0, &ToolWrapper::printSdks);
    return 0;
}

int ToolWrapper::printEnvironment(const string &targetSdk)
{
    Sdk sdk = selectSdk(targetSdk);
    if (!sdk.isValid())
        return 1;

    // ### The paths and the name are not escaped, so hopefully no one will be
    // installing Qt on paths containing backslashes or quotes on Unix. Paths
    // with spaces are taken into account by surrounding the arguments with
    // quotes.

    printf("QT_SELECT=\"%s\"\n", sdk.name.c_str());
    printf("QTTOOLDIR=\"%s\"\n", sdk.toolsPath.c_str());
    printf("QTLIBDIR=\"%s\"\n", sdk.librariesPath.c_str());
    return 0;
}

static string userHome()
{
    const char *value = getenv("HOME");
    if (value)
        return value;

#if defined(_WIN32) || defined(__WIN32__)
    // ### FIXME: some Windows-specific code to get the user's home directory
    // using GetUserProfileDirectory (userenv.h / dll)
    return "C:";
#else
    struct passwd *pwd = getpwuid(getuid());
    if (pwd && pwd->pw_dir)
        return pwd->pw_dir;
    return string();
#endif
}

static inline bool beginsWith(const char *haystack, const char *needle)
{
    return strncmp(haystack, needle, strlen(needle)) == 0;
}

static inline bool endsWith(const char *haystack, const char *needle)
{
    size_t haystackLen = strlen(haystack);
    size_t needleLen = strlen(needle);
    if (needleLen > haystackLen)
        return false;
    return strcmp(haystack + haystackLen - needleLen, needle) == 0;
}

bool linksBackToSelf(const char *link, const char *target)
{
#if !defined(_WIN32) && !defined(__WIN32__)
    char buf[512];
    int count = readlink(link, buf, sizeof(buf) - 1);
    if (count >= 0) {
        buf[count] = '\0';
        if (endsWith(buf, target)) {
            fprintf(stderr, "%s: could not exec '%s' since it links to %s itself. Check your installation.\n",
                    target, link, target);
            return true;
        }
    }
#endif
    return false;
}

static bool readLine(FILE *f, string *result)
{
#if _POSIX_VERSION >= 200809L
    size_t len = 0;
    char *line = 0;
    ssize_t read = getline(&line, &len, f);
    if (read < 0) {
        free(line);
        return false;
    }

    line[strlen(line) - 1] = '\0';
    *result = line;
    free(line);
#elif defined(PATH_MAX)
    char buf[PATH_MAX];
    if (!fgets(buf, PATH_MAX - 1, f))
        return false;

    buf[PATH_MAX - 1] = '\0';
    buf[strlen(buf) - 1] = '\0';
    *result = buf;
#else
# error "POSIX < 2008 and no PATH_MAX, fix me"
#endif
    return true;
}

static bool mkparentdir(string name)
{
    // create the dir containing this dir
    size_t pos = name.rfind('/');
    if (pos == string::npos)
        return false;
    name.erase(pos);
    if (mkdir(name.c_str(), 0777) == -1) {
        if (errno != ENOENT)
            return false;
        // try this dir's parent too
        if (!mkparentdir(name))
            return false;
    }
    return true;
}

int ToolWrapper::runTool(const string &targetSdk, const string &targetTool, char **argv)
{
    Sdk sdk = selectSdk(targetSdk, targetTool);
    if (!sdk.isValid())
        return 1;

    string tool = sdk.toolsPath + PATH_SEP + targetTool;
    if (tool[0] == '~')
        tool = userHome() + tool.substr(1);

    // check if the tool is a symlink to ourselves
    if (linksBackToSelf(tool.c_str(), argv0))
        return 1;

    argv[0] = &tool[0];
#ifdef QTCHOOSER_TEST_MODE
    while (*argv)
        printf("%s\n", *argv++);
    return 0;
#else
    execv(argv[0], argv);
#ifdef __APPLE__
    // failed; see if we have a .app package by the same name
    {
        char appPath[PATH_MAX];
        snprintf(appPath, PATH_MAX, "%s.app/Contents/MacOS/%s",
                 argv[0], basename(argv[0]));
        execv(appPath, argv);
    }
#endif
    fprintf(stderr, "%s: could not exec '%s': %s\n",
            argv0, argv[0], strerror(errno));
    return 1;
#endif
}

static const char *to_number(int number)
{
    // obviously not thread-safe
    static char buffer[sizeof "2147483647"];
    snprintf(buffer, sizeof buffer, "%d", number);
    return buffer;
}

int ToolWrapper::install(const string &sdkName, const string &qmake, int installOptions)
{
    if (qmake.size() == 0) {
        fprintf(stderr, "%s: missing option: path to qmake\n", argv0);
        return 1;
    }

    if ((installOptions & ForceOverwrite) == 0) {
        Sdk matchedSdk = iterateSdks(sdkName, &ToolWrapper::matchSdk);
        if (matchedSdk.isValid()) {
            fprintf(stderr, "%s: SDK \"%s\" already exists\n", argv0, sdkName.c_str());
            return 1;
        }
    }

    // first of all, get the bin and lib dirs from qmake
    string bindir, libdir;
    FILE *bin, *lib;
    bin = popen(("'" + qmake + "' -query QT_INSTALL_BINS").c_str(), "r");
    lib = popen(("'" + qmake + "' -query QT_INSTALL_LIBS").c_str(), "r");

    if (!readLine(bin, &bindir) || !readLine(lib, &libdir)\
            || pclose(bin) == -1 || pclose(lib) == -1) {
        fprintf(stderr, "%s: error running %s: %s\n", argv0, qmake.c_str(), strerror(errno));
        return 1;
    }

    const string sdkFileName = sdkName + confSuffix;
    const string fileContents = bindir + "\n" + libdir + "\n";
    string sdkFullPath;

    // get the list of paths to try and install the SDK on the first we are able to;
    // since the list is sorted in search order, we need to try in the reverse order
    const vector<string> paths = searchPaths();
    vector<string>::const_iterator it = paths.end();
    vector<string>::const_iterator prev = it - 1;
    for ( ; it != paths.begin(); it = prev--) {
        sdkFullPath = *prev + sdkFileName;

        // are we trying to install here?
        bool installHere = (installOptions & LocalInstall) == 0 || prev == paths.begin();
        if (!installHere)
            continue;

#ifdef QTCHOOSER_TEST_MODE
        puts(sdkFullPath.c_str());
        puts(fileContents.c_str());
        return 0;
#else
        // we're good, create the SDK name
        string tempname = sdkFullPath + "." + to_number(rand());
        int fd;
        // create a temporary file here
        while (true) {
            fd = ::open(tempname.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0666);
            if (fd == -1 && errno == EEXIST)
                continue;
            if (fd == -1 && errno == ENOENT) {
                // could be because the dir itself doesn't exist
                if (mkparentdir(tempname))
                    continue;
            }
            break;
        }
        if (fd == -1)
            continue;

        size_t bytesWritten = 0;
        while (bytesWritten < fileContents.size()) {
            ssize_t written = ::write(fd, fileContents.data() + bytesWritten, fileContents.size() - bytesWritten);
            if (written == -1) {
                fprintf(stderr, "%s: error writing to \"%s\": %s\n", argv0, tempname.c_str(), strerror(errno));
                ::close(fd);
                return 1;
            }

            bytesWritten += written;
        }

        // atomic rename
        ::close(fd);
        if (rename(tempname.c_str(), sdkFullPath.c_str()) == 0)
            return 0;   // success
#endif
    }

    // if we got here, we failed to create the file
    fprintf(stderr, "%s: could not create SDK: %s: %s\n", argv0, sdkFullPath.c_str(), strerror(errno));
    return 1;
}

static vector<string> stringSplit(const char *source)
{
#if defined(_WIN32) || defined(__WIN32__)
    char listSeparator = ';';
#else
    char listSeparator = ':';
#endif

    vector<string> result;
    if (!*source)
        return result;

    while (true) {
        const char *p = strchr(source, listSeparator);
        if (!p) {
            result.push_back(source);
            return result;
        }

        result.push_back(string(source, p - source));
        source = p + 1;
    }
    return result;
}

static string qgetenv(const char *env, const string &defaultValue = string())
{
    const char *value = getenv(env);
    return value ? string(value) : defaultValue;
}

vector<string> ToolWrapper::searchPaths() const
{
    vector<string> paths;

    string localDir = qgetenv("XDG_CONFIG_HOME", userHome() + PATH_SEP ".config");
    paths.push_back(localDir);

    // search the XDG config location directories
    vector<string> xdgPaths = stringSplit(qgetenv("XDG_CONFIG_DIRS", "/etc/xdg").c_str());
    paths.insert(paths.end(), xdgPaths.begin(), xdgPaths.end());

#if defined(QTCHOOSER_GLOBAL_DIR)
    if (qgetenv("QTCHOOSER_NO_GLOBAL_DIR").empty()) {
        vector<string> globalPaths = stringSplit(QTCHOOSER_GLOBAL_DIR);
        paths.insert(paths.end(), globalPaths.begin(), globalPaths.end());
    }
#endif

    for (vector<string>::iterator it = paths.begin(); it != paths.end(); ++it)
        *it += "/qtchooser/";

    return paths;
}

Sdk ToolWrapper::iterateSdks(const string &targetSdk, VisitFunction visit, FinishFunction finish,
                             const string &targetTool)
{
    vector<string> paths = searchPaths();
    set<string> seenNames;
    Sdk sdk;
    for (vector<string>::iterator it = paths.begin(); it != paths.end(); ++it) {
        const string &path = *it;

        // no ISO C++ or ISO C API for listing directories, so use POSIX
        DIR *dir = opendir(path.c_str());
        if (!dir)
            continue;  // no such dir or not a dir, doesn't matter

        while (struct dirent *d = readdir(dir)) {
#ifdef _DIRENT_HAVE_D_TYPE
            if (d->d_type == DT_DIR)
                continue;
#endif

            size_t fnamelen = strlen(d->d_name);
            if (fnamelen < sizeof(confSuffix))
                continue;
            if (memcmp(d->d_name + fnamelen + 1 - sizeof(confSuffix), confSuffix, sizeof confSuffix - 1) != 0)
                continue;

            if (seenNames.find(d->d_name) != seenNames.end())
                continue;

            seenNames.insert(d->d_name);
            if (targetTool.empty()) {
                sdk.name = d->d_name;
                sdk.name.resize(fnamelen + 1 - sizeof confSuffix);
            } else {
                // To make the check in matchSdk() succeed
                sdk.name = "default";
            }
            sdk.configFile = path + PATH_SEP + d->d_name;
            if (visit && visit(targetSdk, sdk)) {
                // If a tool was requested, but not found here, skip this sdk
                if (!targetTool.empty() && !sdk.hasTool(targetTool))
                    continue;
                return sdk;
            }
        }

        closedir(dir);
    }

    if (finish)
        finish(seenNames);

    return Sdk();
}

// All tools that exist for only one Qt version should be
// here. Other tools in this list are qdbus and qmlscene.
bool fallbackAllowed(const string &tool)
{
    return tool == "qdbus" ||
           tool == "qml" ||
           tool == "qmlimportscanner" ||
           tool == "qmlscene" ||
           tool == "qtdiag" ||
           tool == "qtpaths" ||
           tool == "qtplugininfo";
}

Sdk ToolWrapper::selectSdk(const string &targetSdk, const string &targetTool)
{
    // First, try the requested SDK
    Sdk matchedSdk = iterateSdks(targetSdk, &ToolWrapper::matchSdk);
    if (targetSdk.empty() && !matchedSdk.hasTool(targetTool) && fallbackAllowed(targetTool)) {
        // If a tool was requested, fall back to any SDK that has it
        matchedSdk = iterateSdks(string(), &ToolWrapper::matchSdk, 0, targetTool);
    }
    if (!matchedSdk.isValid()) {
        fprintf(stderr, "%s: could not find a Qt installation of '%s'\n", argv0, targetSdk.c_str());
    }
    return matchedSdk;
}

void ToolWrapper::printSdks(const set<string> &seenNames)
{
    vector<string> sorted;
    copy(seenNames.begin(), seenNames.end(), back_inserter(sorted));
    sort(sorted.begin(), sorted.end());
    vector<string>::const_iterator it = sorted.begin();
    for ( ; it != sorted.end(); ++it) {
        // strip the .conf suffix
        string s = *it;
        s.resize(s.size() - sizeof confSuffix + 1);
        printf("%s\n", s.c_str());
    }
}

bool ToolWrapper::matchSdk(const string &targetSdk, Sdk &sdk)
{
    if (targetSdk == sdk.name || (targetSdk.empty() && sdk.name == "default")) {
        FILE *f = fopen(sdk.configFile.c_str(), "r");
        if (!f) {
            fprintf(stderr, "%s: could not open config file '%s': %s\n",
                    argv0, sdk.configFile.c_str(), strerror(errno));
            exit(1);
        }

        // read the first two lines.
        // 1) the first line contains the path to the Qt tools like qmake
        // 2) the second line contains the path to the Qt libraries
        // further lines are reserved for future enhancement
        if (!readLine(f, &sdk.toolsPath) || !readLine(f, &sdk.librariesPath)) {
            fclose(f);
            return false;
        }

        fclose(f);
        return true;
    }

    return false;
}

int main(int argc, char **argv)
{
    // search the environment for defaults
    Mode operatingMode = Unknown;
    argv0 = basename(argv[0]);
    const char *targetSdk = getenv("QT_SELECT");

    // the default tool is the one in argv[0]
    const char *targetTool = argv0;

    // if argv[0] points back to us, use the environment
    if (strcmp(targetTool, myName) == 0)
        targetTool = getenv("QTCHOOSER_RUNTOOL");
    else
        operatingMode = RunTool;

    // check the arguments to see if there's an override
    int optind = 1;
    for ( ; optind < argc; ++optind) {
        char *arg = argv[optind];
        if (*arg == '-') {
            ++arg;
            if (*arg == '-')
                ++arg;
            if (!*arg) {
                // -- argument, ends our processing
                // but skip this dash-dash argument
                ++optind;
                break;
            } else if (beginsWith(arg, "qt")) {
                // -qtX or -qt=X argument
                arg += 2;
                targetSdk = *arg == '=' ? arg + 1 : arg;
            } else if (!targetTool && beginsWith(arg, "run-tool=")) {
                // -run-tool= argument
                targetTool = arg + strlen("run-tool=");
                operatingMode = RunTool;
            } else {
                // not one of our arguments, must be for the target tool
                break;
            }
        } else {
            // not one of our arguments, must be for the target tool
            break;
        }
    }

    if (!targetSdk)
        targetSdk = "";

    ToolWrapper wrapper;
    if (operatingMode == RunTool || targetTool) {
        if (!targetTool) {
            fprintf(stderr, "%s: no tool selected. Stop.\n", argv0);
            return 1;
        }
        return wrapper.runTool(targetSdk,
                               targetTool,
                               argv + optind - 1);
    }

    // running qtchooser itself
    // check for our arguments
    operatingMode = PrintHelp;
    int installOptions = 0;
    string sdkName;
    string qmakePath;
    for ( ; optind < argc; ++optind) {
        char *arg = argv[optind];
        if (*arg == '-') {
            ++arg;
            if (*arg == '-')
                ++arg;
            // double-dash arguments are OK too
            if (*arg == '-')
                ++arg;
            if (strcmp(arg, "install") == 0) {
                operatingMode = Install;
            } else if (operatingMode == Install && (strcmp(arg, "force") == 0 || strcmp(arg, "f") == 0)) {
                installOptions |= ForceOverwrite;
            } else if (strcmp(arg, "list-versions") == 0 || strcmp(arg, "l") == 0) {
                operatingMode = ListVersions;
            } else if (operatingMode == Install && strcmp(arg, "local") == 0) {
                installOptions |= LocalInstall;
            } else if (beginsWith(arg, "print-env")) {
                operatingMode = PrintEnvironment;
            } else if (strcmp(arg, "help") != 0) {
                fprintf(stderr, "%s: unknown option: %s\n", argv0, arg - 1);
                return 1;
            }
        } else if (operatingMode == Install) {
            if (qmakePath.size()) {
                fprintf(stderr, "%s: install mode takes exactly two arguments; unknown option: %s\n", argv0, arg);
                return 1;
            }
            if (sdkName.size()) {
                qmakePath = arg;
            } else {
                sdkName = strlen(arg) ? arg : "default";
            }
        } else {
            fprintf(stderr, "%s: unknown argument: %s\n", argv0, arg);
            return 1;
        }
    }

    // dispatch
    switch (operatingMode) {
    case RunTool:
    case Unknown:
        // can't happen!
        assert(false);
        return 127;

    case PrintHelp:
        return wrapper.printHelp();

    case PrintEnvironment:
        return wrapper.printEnvironment(targetSdk);

    case ListVersions:
        return wrapper.listVersions();

    case Install:
        return wrapper.install(sdkName, qmakePath, installOptions);
    }
}