]> rtime.felk.cvut.cz Git - coffee/buildroot.git/blob - toolchain/toolchain-wrapper.c
log4cplus: add C++11 dependencies
[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 #include <time.h>
26 #include <stdbool.h>
27
28 #ifdef BR_CCACHE
29 static char ccache_path[PATH_MAX];
30 #endif
31 static char path[PATH_MAX];
32 static char sysroot[PATH_MAX];
33 /* As would be defined by gcc:
34  *   https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html
35  * sizeof() on string literals includes the terminating \0. */
36 static char _time_[sizeof("-D__TIME__=\"HH:MM:SS\"")];
37 static char _date_[sizeof("-D__DATE__=\"MMM DD YYYY\"")];
38
39 /**
40  * GCC errors out with certain combinations of arguments (examples are
41  * -mfloat-abi={hard|soft} and -m{little|big}-endian), so we have to ensure
42  * that we only pass the predefined one to the real compiler if the inverse
43  * option isn't in the argument list.
44  * This specifies the worst case number of extra arguments we might pass
45  * Currently, we may have:
46  *      -mfloat-abi=
47  *      -march=
48  *      -mcpu=
49  *      -D__TIME__=
50  *      -D__DATE__=
51  *      -Wno-builtin-macro-redefined
52  */
53 #define EXCLUSIVE_ARGS  6
54
55 static char *predef_args[] = {
56 #ifdef BR_CCACHE
57         ccache_path,
58 #endif
59         path,
60         "--sysroot", sysroot,
61 #ifdef BR_ABI
62         "-mabi=" BR_ABI,
63 #endif
64 #ifdef BR_NAN
65         "-mnan=" BR_NAN,
66 #endif
67 #ifdef BR_FPU
68         "-mfpu=" BR_FPU,
69 #endif
70 #ifdef BR_SOFTFLOAT
71         "-msoft-float",
72 #endif /* BR_SOFTFLOAT */
73 #ifdef BR_MODE
74         "-m" BR_MODE,
75 #endif
76 #ifdef BR_64
77         "-m64",
78 #endif
79 #ifdef BR_OMIT_LOCK_PREFIX
80         "-Wa,-momit-lock-prefix=yes",
81 #endif
82 #ifdef BR_NO_FUSED_MADD
83         "-mno-fused-madd",
84 #endif
85 #ifdef BR_FP_CONTRACT_OFF
86         "-ffp-contract=off",
87 #endif
88 #ifdef BR_BINFMT_FLAT
89         "-Wl,-elf2flt",
90 #endif
91 #ifdef BR_MIPS_TARGET_LITTLE_ENDIAN
92         "-EL",
93 #endif
94 #if defined(BR_MIPS_TARGET_BIG_ENDIAN) || defined(BR_ARC_TARGET_BIG_ENDIAN)
95         "-EB",
96 #endif
97 #ifdef BR_ADDITIONAL_CFLAGS
98         BR_ADDITIONAL_CFLAGS
99 #endif
100 };
101
102 /* A {string,length} tuple, to avoid computing strlen() on constants.
103  *  - str must be a \0-terminated string
104  *  - len does not account for the terminating '\0'
105  */
106 struct str_len_s {
107         const char *str;
108         size_t     len;
109 };
110
111 /* Define a {string,length} tuple. Takes an unquoted constant string as
112  * parameter. sizeof() on a string literal includes the terminating \0,
113  * but we don't want to count it.
114  */
115 #define STR_LEN(s) { #s, sizeof(#s)-1 }
116
117 /* List of paths considered unsafe for cross-compilation.
118  *
119  * An unsafe path is one that points to a directory with libraries or
120  * headers for the build machine, which are not suitable for the target.
121  */
122 static const struct str_len_s unsafe_paths[] = {
123         STR_LEN(/lib),
124         STR_LEN(/usr/include),
125         STR_LEN(/usr/lib),
126         STR_LEN(/usr/local/include),
127         STR_LEN(/usr/local/lib),
128         { NULL, 0 },
129 };
130
131 /* Unsafe options are options that specify a potentialy unsafe path,
132  * that will be checked by check_unsafe_path(), below.
133  */
134 static const struct str_len_s unsafe_opts[] = {
135         STR_LEN(-I),
136         STR_LEN(-idirafter),
137         STR_LEN(-iquote),
138         STR_LEN(-isystem),
139         STR_LEN(-L),
140         { NULL, 0 },
141 };
142
143 /* Check if path is unsafe for cross-compilation. Unsafe paths are those
144  * pointing to the standard native include or library paths.
145  *
146  * We print the arguments leading to the failure. For some options, gcc
147  * accepts the path to be concatenated to the argument (e.g. -I/foo/bar)
148  * or separated (e.g. -I /foo/bar). In the first case, we need only print
149  * the argument as it already contains the path (arg_has_path), while in
150  * the second case we need to print both (!arg_has_path).
151  *
152  * If paranoid, exit in error instead of just printing a warning.
153  */
154 static void check_unsafe_path(const char *arg,
155                               const char *path,
156                               int paranoid,
157                               int arg_has_path)
158 {
159         const struct str_len_s *p;
160
161         for (p=unsafe_paths; p->str; p++) {
162                 if (strncmp(path, p->str, p->len))
163                         continue;
164                 fprintf(stderr,
165                         "%s: %s: unsafe header/library path used in cross-compilation: '%s%s%s'\n",
166                         program_invocation_short_name,
167                         paranoid ? "ERROR" : "WARNING",
168                         arg,
169                         arg_has_path ? "" : "' '", /* close single-quote, space, open single-quote */
170                         arg_has_path ? "" : path); /* so that arg and path are properly quoted. */
171                 if (paranoid)
172                         exit(1);
173         }
174 }
175
176 /* Returns false if SOURCE_DATE_EPOCH was not defined in the environment.
177  *
178  * Returns true if SOURCE_DATE_EPOCH is in the environment and represent
179  * a valid timestamp, in which case the timestamp is formatted into the
180  * global variables _date_ and _time_.
181  *
182  * Aborts if SOURCE_DATE_EPOCH was set in the environment but did not
183  * contain a valid timestamp.
184  *
185  * Valid values are defined in the spec:
186  *     https://reproducible-builds.org/specs/source-date-epoch/
187  * but we further restrict them to be positive or null.
188  */
189 bool parse_source_date_epoch_from_env(void)
190 {
191         char *epoch_env, *endptr;
192         time_t epoch;
193         struct tm epoch_tm;
194
195         if ((epoch_env = getenv("SOURCE_DATE_EPOCH")) == NULL)
196                 return false;
197         errno = 0;
198         epoch = (time_t) strtoll(epoch_env, &endptr, 10);
199         /* We just need to test if it is incorrect, but we do not
200          * care why it is incorrect.
201          */
202         if ((errno != 0) || !*epoch_env || *endptr || (epoch < 0)) {
203                 fprintf(stderr, "%s: invalid SOURCE_DATE_EPOCH='%s'\n",
204                         program_invocation_short_name,
205                         epoch_env);
206                 exit(1);
207         }
208         tzset(); /* For localtime_r(), below. */
209         if (localtime_r(&epoch, &epoch_tm) == NULL) {
210                 fprintf(stderr, "%s: cannot parse SOURCE_DATE_EPOCH=%s\n",
211                                 program_invocation_short_name,
212                                 getenv("SOURCE_DATE_EPOCH"));
213                 exit(1);
214         }
215         if (!strftime(_time_, sizeof(_time_), "-D__TIME__=\"%T\"", &epoch_tm)) {
216                 fprintf(stderr, "%s: cannot set time from SOURCE_DATE_EPOCH=%s\n",
217                                 program_invocation_short_name,
218                                 getenv("SOURCE_DATE_EPOCH"));
219                 exit(1);
220         }
221         if (!strftime(_date_, sizeof(_date_), "-D__DATE__=\"%b %e %Y\"", &epoch_tm)) {
222                 fprintf(stderr, "%s: cannot set date from SOURCE_DATE_EPOCH=%s\n",
223                                 program_invocation_short_name,
224                                 getenv("SOURCE_DATE_EPOCH"));
225                 exit(1);
226         }
227         return true;
228 }
229
230 int main(int argc, char **argv)
231 {
232         char **args, **cur, **exec_args;
233         char *relbasedir, *absbasedir;
234         char *progpath = argv[0];
235         char *basename;
236         char *env_debug;
237         char *paranoid_wrapper;
238         int paranoid;
239         int ret, i, count = 0, debug;
240
241         /* Calculate the relative paths */
242         basename = strrchr(progpath, '/');
243         if (basename) {
244                 *basename = '\0';
245                 basename++;
246                 relbasedir = malloc(strlen(progpath) + 7);
247                 if (relbasedir == NULL) {
248                         perror(__FILE__ ": malloc");
249                         return 2;
250                 }
251                 sprintf(relbasedir, "%s/..", argv[0]);
252                 absbasedir = realpath(relbasedir, NULL);
253         } else {
254                 basename = progpath;
255                 absbasedir = malloc(PATH_MAX + 1);
256                 ret = readlink("/proc/self/exe", absbasedir, PATH_MAX);
257                 if (ret < 0) {
258                         perror(__FILE__ ": readlink");
259                         return 2;
260                 }
261                 absbasedir[ret] = '\0';
262                 for (i = ret; i > 0; i--) {
263                         if (absbasedir[i] == '/') {
264                                 absbasedir[i] = '\0';
265                                 if (++count == 2)
266                                         break;
267                         }
268                 }
269         }
270         if (absbasedir == NULL) {
271                 perror(__FILE__ ": realpath");
272                 return 2;
273         }
274
275         /* Fill in the relative paths */
276 #ifdef BR_CROSS_PATH_REL
277         ret = snprintf(path, sizeof(path), "%s/" BR_CROSS_PATH_REL "/%s" BR_CROSS_PATH_SUFFIX, absbasedir, basename);
278 #elif defined(BR_CROSS_PATH_ABS)
279         ret = snprintf(path, sizeof(path), BR_CROSS_PATH_ABS "/%s" BR_CROSS_PATH_SUFFIX, basename);
280 #else
281         ret = snprintf(path, sizeof(path), "%s/bin/%s" BR_CROSS_PATH_SUFFIX, absbasedir, basename);
282 #endif
283         if (ret >= sizeof(path)) {
284                 perror(__FILE__ ": overflow");
285                 return 3;
286         }
287 #ifdef BR_CCACHE
288         ret = snprintf(ccache_path, sizeof(ccache_path), "%s/bin/ccache", absbasedir);
289         if (ret >= sizeof(ccache_path)) {
290                 perror(__FILE__ ": overflow");
291                 return 3;
292         }
293 #endif
294         ret = snprintf(sysroot, sizeof(sysroot), "%s/" BR_SYSROOT, absbasedir);
295         if (ret >= sizeof(sysroot)) {
296                 perror(__FILE__ ": overflow");
297                 return 3;
298         }
299
300         cur = args = malloc(sizeof(predef_args) +
301                             (sizeof(char *) * (argc + EXCLUSIVE_ARGS)));
302         if (args == NULL) {
303                 perror(__FILE__ ": malloc");
304                 return 2;
305         }
306
307         /* start with predefined args */
308         memcpy(cur, predef_args, sizeof(predef_args));
309         cur += sizeof(predef_args) / sizeof(predef_args[0]);
310
311 #ifdef BR_FLOAT_ABI
312         /* add float abi if not overridden in args */
313         for (i = 1; i < argc; i++) {
314                 if (!strncmp(argv[i], "-mfloat-abi=", strlen("-mfloat-abi=")) ||
315                     !strcmp(argv[i], "-msoft-float") ||
316                     !strcmp(argv[i], "-mhard-float"))
317                         break;
318         }
319
320         if (i == argc)
321                 *cur++ = "-mfloat-abi=" BR_FLOAT_ABI;
322 #endif
323
324 #ifdef BR_FP32_MODE
325         /* add fp32 mode if soft-float is not args or hard-float overrides soft-float */
326         int add_fp32_mode = 1;
327         for (i = 1; i < argc; i++) {
328                 if (!strcmp(argv[i], "-msoft-float"))
329                         add_fp32_mode = 0;
330                 else if (!strcmp(argv[i], "-mhard-float"))
331                         add_fp32_mode = 1;
332         }
333
334         if (add_fp32_mode == 1)
335                 *cur++ = "-mfp" BR_FP32_MODE;
336 #endif
337
338 #if defined(BR_ARCH) || \
339     defined(BR_CPU)
340         /* Add our -march/cpu flags, but only if none of
341          * -march/mtune/mcpu are already specified on the commandline
342          */
343         for (i = 1; i < argc; i++) {
344                 if (!strncmp(argv[i], "-march=", strlen("-march=")) ||
345                     !strncmp(argv[i], "-mtune=", strlen("-mtune=")) ||
346                     !strncmp(argv[i], "-mcpu=",  strlen("-mcpu=" )))
347                         break;
348         }
349         if (i == argc) {
350 #ifdef BR_ARCH
351                 *cur++ = "-march=" BR_ARCH;
352 #endif
353 #ifdef BR_CPU
354                 *cur++ = "-mcpu=" BR_CPU;
355 #endif
356         }
357 #endif /* ARCH || CPU */
358
359         if (parse_source_date_epoch_from_env()) {
360                 *cur++ = _time_;
361                 *cur++ = _date_;
362                 /* This has existed since gcc-4.4.0. */
363                 *cur++ = "-Wno-builtin-macro-redefined";
364         }
365
366         paranoid_wrapper = getenv("BR_COMPILER_PARANOID_UNSAFE_PATH");
367         if (paranoid_wrapper && strlen(paranoid_wrapper) > 0)
368                 paranoid = 1;
369         else
370                 paranoid = 0;
371
372         /* Check for unsafe library and header paths */
373         for (i = 1; i < argc; i++) {
374                 const struct str_len_s *opt;
375                 for (opt=unsafe_opts; opt->str; opt++ ) {
376                         /* Skip any non-unsafe option. */
377                         if (strncmp(argv[i], opt->str, opt->len))
378                                 continue;
379
380                         /* Handle both cases:
381                          *  - path is a separate argument,
382                          *  - path is concatenated with option.
383                          */
384                         if (argv[i][opt->len] == '\0') {
385                                 i++;
386                                 if (i == argc)
387                                         break;
388                                 check_unsafe_path(argv[i-1], argv[i], paranoid, 0);
389                         } else
390                                 check_unsafe_path(argv[i], argv[i] + opt->len, paranoid, 1);
391                 }
392         }
393
394         /* append forward args */
395         memcpy(cur, &argv[1], sizeof(char *) * (argc - 1));
396         cur += argc - 1;
397
398         /* finish with NULL termination */
399         *cur = NULL;
400
401         exec_args = args;
402 #ifdef BR_CCACHE
403         if (getenv("BR_NO_CCACHE"))
404                 /* Skip the ccache call */
405                 exec_args++;
406 #endif
407
408         /* Debug the wrapper to see actual arguments passed to
409          * the compiler:
410          * unset, empty, or 0: do not trace
411          * set to 1          : trace all arguments on a single line
412          * set to 2          : trace one argument per line
413          */
414         if ((env_debug = getenv("BR2_DEBUG_WRAPPER"))) {
415                 debug = atoi(env_debug);
416                 if (debug > 0) {
417                         fprintf(stderr, "Toolchain wrapper executing:");
418 #ifdef BR_CCACHE_HASH
419                         fprintf(stderr, "%sCCACHE_COMPILERCHECK='string:" BR_CCACHE_HASH "'",
420                                 (debug == 2) ? "\n    " : " ");
421 #endif
422 #ifdef BR_CCACHE_BASEDIR
423                         fprintf(stderr, "%sCCACHE_BASEDIR='" BR_CCACHE_BASEDIR "'",
424                                 (debug == 2) ? "\n    " : " ");
425 #endif
426                         for (i = 0; exec_args[i]; i++)
427                                 fprintf(stderr, "%s'%s'",
428                                         (debug == 2) ? "\n    " : " ", exec_args[i]);
429                         fprintf(stderr, "\n");
430                 }
431         }
432
433 #ifdef BR_CCACHE_HASH
434         /* Allow compilercheck to be overridden through the environment */
435         if (setenv("CCACHE_COMPILERCHECK", "string:" BR_CCACHE_HASH, 0)) {
436                 perror(__FILE__ ": Failed to set CCACHE_COMPILERCHECK");
437                 return 3;
438         }
439 #endif
440 #ifdef BR_CCACHE_BASEDIR
441         /* Allow compilercheck to be overridden through the environment */
442         if (setenv("CCACHE_BASEDIR", BR_CCACHE_BASEDIR, 0)) {
443                 perror(__FILE__ ": Failed to set CCACHE_BASEDIR");
444                 return 3;
445         }
446 #endif
447
448         if (execv(exec_args[0], exec_args))
449                 perror(path);
450
451         free(args);
452
453         return 2;
454 }