cd8a5110742280091878e54c3668a17d6eca5210
[ghc-hetmet.git] / driver / gcc / gcc.c
1
2 #include "getLocation.h"
3 #include <process.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <stdarg.h>
7
8 static void die(char *msg) {
9     fprintf(stderr, "%s", msg);
10     exit(1);
11 }
12
13 static char *mkString(const char *fmt, ...) {
14     char *p;
15     int i, j;
16     va_list argp;
17
18     va_start(argp, fmt);
19     i = vsnprintf(p, 0, fmt, argp);
20     va_end(argp);
21
22     if (i < 0) {
23         die("snprintf failed\n");
24     }
25
26     p = malloc(i + 1);
27     if (p == NULL) {
28         die("malloc failed\n");
29     }
30
31     va_start(argp, fmt);
32     j = vsnprintf(p, i + 1, fmt, argp);
33     va_end(argp);
34     if (i < 0) {
35         die("snprintf failed\n");
36     }
37
38     return p;
39 }
40
41 char *quote(char *str) {
42     char *quotedStr;
43     char *p;
44     int i;
45
46     quotedStr = malloc(2 * strlen(str) + 2 + 1);
47     if (quotedStr == NULL) {
48         die("malloc failed\n");
49     }
50     p = quotedStr;
51     *p++ = '"';
52     while (*str) {
53         if (*str == '"') {
54             *p++ = '\\';
55         }
56         *p++ = *str++;
57     }
58     *p++ = '"';
59     *p = '\0';
60
61     return quotedStr;
62 }
63
64 int main(int argc, char** argv) {
65     char *p;
66     char *binDir;
67     char *exePath;
68     char *bArg;
69     char **newArgv;
70     int i, j, ret;
71
72     binDir = getExecutablePath();
73     exePath = mkString("%s/realgcc.exe", binDir);
74
75     /* Without these -B args, gcc will still work. However, if you
76        have a mingw installation in c:/mingw then it will use files
77        from that in preference to the in-tree files. */
78
79     newArgv = malloc(sizeof(char *) * (argc + 4 + 1));
80     newArgv[0] = quote(exePath);
81     newArgv[1] = quote(mkString("-B%s", binDir));
82     newArgv[2] = quote(mkString("-B%s/../lib", binDir));
83     newArgv[3] = quote(mkString("-B%s/../lib/gcc/mingw32/3.4.5", binDir));
84     newArgv[4] = quote(mkString("-B%s/../libexec/gcc/mingw32/3.4.5", binDir));
85     for (i = 1; i < argc; i++) {
86         newArgv[4 + i] = quote(argv[i]);
87     }
88     newArgv[4 + argc] = NULL;
89     // execv(exePath, argv);
90     ret = spawnv(_P_WAIT, exePath, (const char* const*)newArgv);
91     if (errno) {
92         die("Spawn failed\n");
93     }
94     exit(ret);
95 }