]> rtime.felk.cvut.cz Git - coffee/buildroot.git/blob - toolchain/toolchain-wrapper.c
dd77c111314a9422d1f18b581facbfe69a159b37
[coffee/buildroot.git] / toolchain / toolchain-wrapper.c
1 /**
2  * Buildroot wrapper for toolchains. This simply executes the real toolchain
3  * with a number of arguments (sysroot/arch/..) hardcoded, to ensure the
4  * toolchain uses the correct configuration.
5  * The hardcoded path arguments are defined relative to the actual location
6  * of the binary.
7  *
8  * (C) 2011 Peter Korsgaard <jacmet@sunsite.dk>
9  * (C) 2011 Daniel Nyström <daniel.nystrom@timeterminal.se>
10  * (C) 2012 Arnout Vandecappelle (Essensium/Mind) <arnout@mind.be>
11  * (C) 2013 Spenser Gilliland <spenser@gillilanding.com>
12  *
13  * This file is licensed under the terms of the GNU General Public License
14  * version 2.  This program is licensed "as is" without any warranty of any
15  * kind, whether express or implied.
16  */
17
18 #define _GNU_SOURCE
19 #include <stdio.h>
20 #include <string.h>
21 #include <limits.h>
22 #include <unistd.h>
23 #include <stdlib.h>
24 #include <errno.h>
25
26 #ifdef BR_CCACHE
27 static char ccache_path[PATH_MAX];
28 #endif
29 static char path[PATH_MAX];
30 static char sysroot[PATH_MAX];
31
32 /**
33  * GCC errors out with certain combinations of arguments (examples are
34  * -mfloat-abi={hard|soft} and -m{little|big}-endian), so we have to ensure
35  * that we only pass the predefined one to the real compiler if the inverse
36  * option isn't in the argument list.
37  * This specifies the worst case number of extra arguments we might pass
38  * Currently, we have:
39  *      -mfloat-abi=
40  *      -march=
41  *      -mcpu=
42  */
43 #define EXCLUSIVE_ARGS  3
44
45 static char *predef_args[] = {
46 #ifdef BR_CCACHE
47         ccache_path,
48 #endif
49         path,
50         "--sysroot", sysroot,
51 #ifdef BR_ABI
52         "-mabi=" BR_ABI,
53 #endif
54 #ifdef BR_NAN
55         "-mnan=" BR_NAN,
56 #endif
57 #ifdef BR_FPU
58         "-mfpu=" BR_FPU,
59 #endif
60 #ifdef BR_SOFTFLOAT
61         "-msoft-float",
62 #endif /* BR_SOFTFLOAT */
63 #ifdef BR_MODE
64         "-m" BR_MODE,
65 #endif
66 #ifdef BR_64
67         "-m64",
68 #endif
69 #ifdef BR_OMIT_LOCK_PREFIX
70         "-Wa,-momit-lock-prefix=yes",
71 #endif
72 #ifdef BR_NO_FUSED_MADD
73         "-mno-fused-madd",
74 #endif
75 #ifdef BR_BINFMT_FLAT
76         "-Wl,-elf2flt",
77 #endif
78 #ifdef BR_MIPS_TARGET_LITTLE_ENDIAN
79         "-EL",
80 #endif
81 #if defined(BR_MIPS_TARGET_BIG_ENDIAN) || defined(BR_ARC_TARGET_BIG_ENDIAN)
82         "-EB",
83 #endif
84 #ifdef BR_ADDITIONAL_CFLAGS
85         BR_ADDITIONAL_CFLAGS
86 #endif
87 };
88
89 /* A {string,length} tuple, to avoid computing strlen() on constants.
90  *  - str must be a \0-terminated string
91  *  - len does not account for the terminating '\0'
92  */
93 struct str_len_s {
94         const char *str;
95         size_t     len;
96 };
97
98 /* Define a {string,length} tuple. Takes an unquoted constant string as
99  * parameter. sizeof() on a string literal includes the terminating \0,
100  * but we don't want to count it.
101  */
102 #define STR_LEN(s) { #s, sizeof(#s)-1 }
103
104 /* List of paths considered unsafe for cross-compilation.
105  *
106  * An unsafe path is one that points to a directory with libraries or
107  * headers for the build machine, which are not suitable for the target.
108  */
109 static const struct str_len_s unsafe_paths[] = {
110         STR_LEN(/lib),
111         STR_LEN(/usr/include),
112         STR_LEN(/usr/lib),
113         STR_LEN(/usr/local/include),
114         STR_LEN(/usr/local/lib),
115         { NULL, 0 },
116 };
117
118 /* Unsafe options are options that specify a potentialy unsafe path,
119  * that will be checked by check_unsafe_path(), below.
120  */
121 static const struct str_len_s unsafe_opts[] = {
122         STR_LEN(-I),
123         STR_LEN(-idirafter),
124         STR_LEN(-iquote),
125         STR_LEN(-isystem),
126         STR_LEN(-L),
127         { NULL, 0 },
128 };
129
130 /* Check if path is unsafe for cross-compilation. Unsafe paths are those
131  * pointing to the standard native include or library paths.
132  *
133  * We print the arguments leading to the failure. For some options, gcc
134  * accepts the path to be concatenated to the argument (e.g. -I/foo/bar)
135  * or separated (e.g. -I /foo/bar). In the first case, we need only print
136  * the argument as it already contains the path (arg_has_path), while in
137  * the second case we need to print both (!arg_has_path).
138  *
139  * If paranoid, exit in error instead of just printing a warning.
140  */
141 static void check_unsafe_path(const char *arg,
142                               const char *path,
143                               int paranoid,
144                               int arg_has_path)
145 {
146         const struct str_len_s *p;
147
148         for (p=unsafe_paths; p->str; p++) {
149                 if (strncmp(path, p->str, p->len))
150                         continue;
151                 fprintf(stderr,
152                         "%s: %s: unsafe header/library path used in cross-compilation: '%s%s%s'\n",
153                         program_invocation_short_name,
154                         paranoid ? "ERROR" : "WARNING",
155                         arg,
156                         arg_has_path ? "" : "' '", /* close single-quote, space, open single-quote */
157                         arg_has_path ? "" : path); /* so that arg and path are properly quoted. */
158                 if (paranoid)
159                         exit(1);
160         }
161 }
162
163 int main(int argc, char **argv)
164 {
165         char **args, **cur, **exec_args;
166         char *relbasedir, *absbasedir;
167         char *progpath = argv[0];
168         char *basename;
169         char *env_debug;
170         char *paranoid_wrapper;
171         int paranoid;
172         int ret, i, count = 0, debug;
173
174         /* Calculate the relative paths */
175         basename = strrchr(progpath, '/');
176         if (basename) {
177                 *basename = '\0';
178                 basename++;
179                 relbasedir = malloc(strlen(progpath) + 7);
180                 if (relbasedir == NULL) {
181                         perror(__FILE__ ": malloc");
182                         return 2;
183                 }
184                 sprintf(relbasedir, "%s/..", argv[0]);
185                 absbasedir = realpath(relbasedir, NULL);
186         } else {
187                 basename = progpath;
188                 absbasedir = malloc(PATH_MAX + 1);
189                 ret = readlink("/proc/self/exe", absbasedir, PATH_MAX);
190                 if (ret < 0) {
191                         perror(__FILE__ ": readlink");
192                         return 2;
193                 }
194                 absbasedir[ret] = '\0';
195                 for (i = ret; i > 0; i--) {
196                         if (absbasedir[i] == '/') {
197                                 absbasedir[i] = '\0';
198                                 if (++count == 2)
199                                         break;
200                         }
201                 }
202         }
203         if (absbasedir == NULL) {
204                 perror(__FILE__ ": realpath");
205                 return 2;
206         }
207
208         /* Fill in the relative paths */
209 #ifdef BR_CROSS_PATH_REL
210         ret = snprintf(path, sizeof(path), "%s/" BR_CROSS_PATH_REL "/%s" BR_CROSS_PATH_SUFFIX, absbasedir, basename);
211 #elif defined(BR_CROSS_PATH_ABS)
212         ret = snprintf(path, sizeof(path), BR_CROSS_PATH_ABS "/%s" BR_CROSS_PATH_SUFFIX, basename);
213 #else
214         ret = snprintf(path, sizeof(path), "%s/bin/%s" BR_CROSS_PATH_SUFFIX, absbasedir, basename);
215 #endif
216         if (ret >= sizeof(path)) {
217                 perror(__FILE__ ": overflow");
218                 return 3;
219         }
220 #ifdef BR_CCACHE
221         ret = snprintf(ccache_path, sizeof(ccache_path), "%s/bin/ccache", absbasedir);
222         if (ret >= sizeof(ccache_path)) {
223                 perror(__FILE__ ": overflow");
224                 return 3;
225         }
226 #endif
227         ret = snprintf(sysroot, sizeof(sysroot), "%s/" BR_SYSROOT, absbasedir);
228         if (ret >= sizeof(sysroot)) {
229                 perror(__FILE__ ": overflow");
230                 return 3;
231         }
232
233         cur = args = malloc(sizeof(predef_args) +
234                             (sizeof(char *) * (argc + EXCLUSIVE_ARGS)));
235         if (args == NULL) {
236                 perror(__FILE__ ": malloc");
237                 return 2;
238         }
239
240         /* start with predefined args */
241         memcpy(cur, predef_args, sizeof(predef_args));
242         cur += sizeof(predef_args) / sizeof(predef_args[0]);
243
244 #ifdef BR_FLOAT_ABI
245         /* add float abi if not overridden in args */
246         for (i = 1; i < argc; i++) {
247                 if (!strncmp(argv[i], "-mfloat-abi=", strlen("-mfloat-abi=")) ||
248                     !strcmp(argv[i], "-msoft-float") ||
249                     !strcmp(argv[i], "-mhard-float"))
250                         break;
251         }
252
253         if (i == argc)
254                 *cur++ = "-mfloat-abi=" BR_FLOAT_ABI;
255 #endif
256
257 #ifdef BR_FP32_MODE
258         /* add fp32 mode if soft-float is not args or hard-float overrides soft-float */
259         int add_fp32_mode = 1;
260         for (i = 1; i < argc; i++) {
261                 if (!strcmp(argv[i], "-msoft-float"))
262                         add_fp32_mode = 0;
263                 else if (!strcmp(argv[i], "-mhard-float"))
264                         add_fp32_mode = 1;
265         }
266
267         if (add_fp32_mode == 1)
268                 *cur++ = "-mfp" BR_FP32_MODE;
269 #endif
270
271 #if defined(BR_ARCH) || \
272     defined(BR_CPU)
273         /* Add our -march/cpu flags, but only if none of
274          * -march/mtune/mcpu are already specified on the commandline
275          */
276         for (i = 1; i < argc; i++) {
277                 if (!strncmp(argv[i], "-march=", strlen("-march=")) ||
278                     !strncmp(argv[i], "-mtune=", strlen("-mtune=")) ||
279                     !strncmp(argv[i], "-mcpu=",  strlen("-mcpu=" )))
280                         break;
281         }
282         if (i == argc) {
283 #ifdef BR_ARCH
284                 *cur++ = "-march=" BR_ARCH;
285 #endif
286 #ifdef BR_CPU
287                 *cur++ = "-mcpu=" BR_CPU;
288 #endif
289         }
290 #endif /* ARCH || CPU */
291
292         paranoid_wrapper = getenv("BR_COMPILER_PARANOID_UNSAFE_PATH");
293         if (paranoid_wrapper && strlen(paranoid_wrapper) > 0)
294                 paranoid = 1;
295         else
296                 paranoid = 0;
297
298         /* Check for unsafe library and header paths */
299         for (i = 1; i < argc; i++) {
300                 const struct str_len_s *opt;
301                 for (opt=unsafe_opts; opt->str; opt++ ) {
302                         /* Skip any non-unsafe option. */
303                         if (strncmp(argv[i], opt->str, opt->len))
304                                 continue;
305
306                         /* Handle both cases:
307                          *  - path is a separate argument,
308                          *  - path is concatenated with option.
309                          */
310                         if (argv[i][opt->len] == '\0') {
311                                 i++;
312                                 if (i == argc)
313                                         break;
314                                 check_unsafe_path(argv[i-1], argv[i], paranoid, 0);
315                         } else
316                                 check_unsafe_path(argv[i], argv[i] + opt->len, paranoid, 1);
317                 }
318         }
319
320         /* append forward args */
321         memcpy(cur, &argv[1], sizeof(char *) * (argc - 1));
322         cur += argc - 1;
323
324         /* finish with NULL termination */
325         *cur = NULL;
326
327         exec_args = args;
328 #ifdef BR_CCACHE
329         if (getenv("BR_NO_CCACHE"))
330                 /* Skip the ccache call */
331                 exec_args++;
332 #endif
333
334         /* Debug the wrapper to see actual arguments passed to
335          * the compiler:
336          * unset, empty, or 0: do not trace
337          * set to 1          : trace all arguments on a single line
338          * set to 2          : trace one argument per line
339          */
340         if ((env_debug = getenv("BR2_DEBUG_WRAPPER"))) {
341                 debug = atoi(env_debug);
342                 if (debug > 0) {
343                         fprintf(stderr, "Toolchain wrapper executing:");
344 #ifdef BR_CCACHE_HASH
345                         fprintf(stderr, "%sCCACHE_COMPILERCHECK='string:" BR_CCACHE_HASH "'",
346                                 (debug == 2) ? "\n    " : " ");
347 #endif
348 #ifdef BR_CCACHE_BASEDIR
349                         fprintf(stderr, "%sCCACHE_BASEDIR='" BR_CCACHE_BASEDIR "'",
350                                 (debug == 2) ? "\n    " : " ");
351 #endif
352                         for (i = 0; exec_args[i]; i++)
353                                 fprintf(stderr, "%s'%s'",
354                                         (debug == 2) ? "\n    " : " ", exec_args[i]);
355                         fprintf(stderr, "\n");
356                 }
357         }
358
359 #ifdef BR_CCACHE_HASH
360         /* Allow compilercheck to be overridden through the environment */
361         if (setenv("CCACHE_COMPILERCHECK", "string:" BR_CCACHE_HASH, 0)) {
362                 perror(__FILE__ ": Failed to set CCACHE_COMPILERCHECK");
363                 return 3;
364         }
365 #endif
366 #ifdef BR_CCACHE_BASEDIR
367         /* Allow compilercheck to be overridden through the environment */
368         if (setenv("CCACHE_BASEDIR", BR_CCACHE_BASEDIR, 0)) {
369                 perror(__FILE__ ": Failed to set CCACHE_BASEDIR");
370                 return 3;
371         }
372 #endif
373
374         if (execv(exec_args[0], exec_args))
375                 perror(path);
376
377         free(args);
378
379         return 2;
380 }