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 * -Wl,-z,now
53 * -Wl,-z,relro
54 * -fPIE
55 * -pie
56 */
57 #define EXCLUSIVE_ARGS 10
58
59 static char *predef_args[] = {
60 #ifdef BR_CCACHE
61 ccache_path,
62 #endif
63 path,
64 "--sysroot", sysroot,
65 #ifdef BR_ABI
66 "-mabi=" BR_ABI,
67 #endif
68 #ifdef BR_NAN
69 "-mnan=" BR_NAN,
70 #endif
71 #ifdef BR_FPU
72 "-mfpu=" BR_FPU,
73 #endif
74 #ifdef BR_SOFTFLOAT
75 "-msoft-float",
76 #endif /* BR_SOFTFLOAT */
77 #ifdef BR_MODE
78 "-m" BR_MODE,
79 #endif
80 #ifdef BR_64
81 "-m64",
82 #endif
83 #ifdef BR_OMIT_LOCK_PREFIX
84 "-Wa,-momit-lock-prefix=yes",
85 #endif
86 #ifdef BR_NO_FUSED_MADD
87 "-mno-fused-madd",
88 #endif
89 #ifdef BR_FP_CONTRACT_OFF
90 "-ffp-contract=off",
91 #endif
92 #ifdef BR_BINFMT_FLAT
93 "-Wl,-elf2flt",
94 #endif
95 #ifdef BR_MIPS_TARGET_LITTLE_ENDIAN
96 "-EL",
97 #endif
98 #if defined(BR_MIPS_TARGET_BIG_ENDIAN) || defined(BR_ARC_TARGET_BIG_ENDIAN)
99 "-EB",
100 #endif
101 #ifdef BR_ADDITIONAL_CFLAGS
102 BR_ADDITIONAL_CFLAGS
103 #endif
104 };
105
106 /* A {string,length} tuple, to avoid computing strlen() on constants.
107 * - str must be a \0-terminated string
108 * - len does not account for the terminating '\0'
109 */
110 struct str_len_s {
111 const char *str;
112 size_t len;
113 };
114
115 /* Define a {string,length} tuple. Takes an unquoted constant string as
116 * parameter. sizeof() on a string literal includes the terminating \0,
117 * but we don't want to count it.
118 */
119 #define STR_LEN(s) { #s, sizeof(#s)-1 }
120
121 /* List of paths considered unsafe for cross-compilation.
122 *
123 * An unsafe path is one that points to a directory with libraries or
124 * headers for the build machine, which are not suitable for the target.
125 */
126 static const struct str_len_s unsafe_paths[] = {
127 STR_LEN(/lib),
128 STR_LEN(/usr/include),
129 STR_LEN(/usr/lib),
130 STR_LEN(/usr/local/include),
131 STR_LEN(/usr/local/lib),
132 STR_LEN(/usr/X11R6/include),
133 STR_LEN(/usr/X11R6/lib),
134 { NULL, 0 },
135 };
136
137 /* Unsafe options are options that specify a potentialy unsafe path,
138 * that will be checked by check_unsafe_path(), below.
139 */
140 static const struct str_len_s unsafe_opts[] = {
141 STR_LEN(-I),
142 STR_LEN(-idirafter),
143 STR_LEN(-iquote),
144 STR_LEN(-isystem),
145 STR_LEN(-L),
146 { NULL, 0 },
147 };
148
149 /* Check if path is unsafe for cross-compilation. Unsafe paths are those
150 * pointing to the standard native include or library paths.
151 *
152 * We print the arguments leading to the failure. For some options, gcc
153 * accepts the path to be concatenated to the argument (e.g. -I/foo/bar)
154 * or separated (e.g. -I /foo/bar). In the first case, we need only print
155 * the argument as it already contains the path (arg_has_path), while in
156 * the second case we need to print both (!arg_has_path).
157 *
158 * If paranoid, exit in error instead of just printing a warning.
159 */
check_unsafe_path(const char * arg,const char * path,int paranoid,int arg_has_path)160 static void check_unsafe_path(const char *arg,
161 const char *path,
162 int paranoid,
163 int arg_has_path)
164 {
165 const struct str_len_s *p;
166
167 for (p=unsafe_paths; p->str; p++) {
168 if (strncmp(path, p->str, p->len))
169 continue;
170 fprintf(stderr,
171 "%s: %s: unsafe header/library path used in cross-compilation: '%s%s%s'\n",
172 program_invocation_short_name,
173 paranoid ? "ERROR" : "WARNING",
174 arg,
175 arg_has_path ? "" : "' '", /* close single-quote, space, open single-quote */
176 arg_has_path ? "" : path); /* so that arg and path are properly quoted. */
177 if (paranoid)
178 exit(1);
179 }
180 }
181
182 #ifdef BR_NEED_SOURCE_DATE_EPOCH
183 /* Returns false if SOURCE_DATE_EPOCH was not defined in the environment.
184 *
185 * Returns true if SOURCE_DATE_EPOCH is in the environment and represent
186 * a valid timestamp, in which case the timestamp is formatted into the
187 * global variables _date_ and _time_.
188 *
189 * Aborts if SOURCE_DATE_EPOCH was set in the environment but did not
190 * contain a valid timestamp.
191 *
192 * Valid values are defined in the spec:
193 * https://reproducible-builds.org/specs/source-date-epoch/
194 * but we further restrict them to be positive or null.
195 */
parse_source_date_epoch_from_env(void)196 bool parse_source_date_epoch_from_env(void)
197 {
198 char *epoch_env, *endptr;
199 time_t epoch;
200 struct tm epoch_tm;
201
202 if ((epoch_env = getenv("SOURCE_DATE_EPOCH")) == NULL)
203 return false;
204 errno = 0;
205 epoch = (time_t) strtoll(epoch_env, &endptr, 10);
206 /* We just need to test if it is incorrect, but we do not
207 * care why it is incorrect.
208 */
209 if ((errno != 0) || !*epoch_env || *endptr || (epoch < 0)) {
210 fprintf(stderr, "%s: invalid SOURCE_DATE_EPOCH='%s'\n",
211 program_invocation_short_name,
212 epoch_env);
213 exit(1);
214 }
215 tzset(); /* For localtime_r(), below. */
216 if (localtime_r(&epoch, &epoch_tm) == NULL) {
217 fprintf(stderr, "%s: cannot parse SOURCE_DATE_EPOCH=%s\n",
218 program_invocation_short_name,
219 getenv("SOURCE_DATE_EPOCH"));
220 exit(1);
221 }
222 if (!strftime(_time_, sizeof(_time_), "-D__TIME__=\"%T\"", &epoch_tm)) {
223 fprintf(stderr, "%s: cannot set time from SOURCE_DATE_EPOCH=%s\n",
224 program_invocation_short_name,
225 getenv("SOURCE_DATE_EPOCH"));
226 exit(1);
227 }
228 if (!strftime(_date_, sizeof(_date_), "-D__DATE__=\"%b %e %Y\"", &epoch_tm)) {
229 fprintf(stderr, "%s: cannot set date from SOURCE_DATE_EPOCH=%s\n",
230 program_invocation_short_name,
231 getenv("SOURCE_DATE_EPOCH"));
232 exit(1);
233 }
234 return true;
235 }
236 #else
parse_source_date_epoch_from_env(void)237 bool parse_source_date_epoch_from_env(void)
238 {
239 /* The compiler is recent enough to handle SOURCE_DATE_EPOCH itself
240 * so we do not need to do anything here.
241 */
242 return false;
243 }
244 #endif
245
main(int argc,char ** argv)246 int main(int argc, char **argv)
247 {
248 char **args, **cur, **exec_args;
249 char *relbasedir, *absbasedir;
250 char *progpath = argv[0];
251 char *basename;
252 char *env_debug;
253 char *paranoid_wrapper;
254 int paranoid;
255 int ret, i, count = 0, debug = 0, found_shared = 0, linker_args = 1;
256
257 /* Debug the wrapper to see arguments it was called with.
258 * If environment variable BR2_DEBUG_WRAPPER is:
259 * unset, empty, or 0: do not trace
260 * set to 1 : trace all arguments on a single line
261 * set to 2 : trace one argument per line
262 */
263 if ((env_debug = getenv("BR2_DEBUG_WRAPPER"))) {
264 debug = atoi(env_debug);
265 }
266 if (debug > 0) {
267 fprintf(stderr, "Toolchain wrapper was called with:");
268 for (i = 0; i < argc; i++)
269 fprintf(stderr, "%s'%s'",
270 (debug == 2) ? "\n " : " ", argv[i]);
271 fprintf(stderr, "\n");
272 }
273
274 /* Calculate the relative paths */
275 basename = strrchr(progpath, '/');
276 if (basename) {
277 *basename = '\0';
278 basename++;
279 relbasedir = malloc(strlen(progpath) + 7);
280 if (relbasedir == NULL) {
281 perror(__FILE__ ": malloc");
282 return 2;
283 }
284 sprintf(relbasedir, "%s/..", argv[0]);
285 absbasedir = realpath(relbasedir, NULL);
286 } else {
287 basename = progpath;
288 absbasedir = malloc(PATH_MAX + 1);
289 ret = readlink("/proc/self/exe", absbasedir, PATH_MAX);
290 if (ret < 0) {
291 perror(__FILE__ ": readlink");
292 return 2;
293 }
294 absbasedir[ret] = '\0';
295 for (i = ret; i > 0; i--) {
296 if (absbasedir[i] == '/') {
297 absbasedir[i] = '\0';
298 if (++count == 2)
299 break;
300 }
301 }
302 }
303 if (absbasedir == NULL) {
304 perror(__FILE__ ": realpath");
305 return 2;
306 }
307
308 /* clang doesn't like linker input when no linking */
309 for (i = 1; i < argc; i++) {
310 if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "-E") ||
311 !strcmp(argv[i], "-s") ||
312 !strcmp(argv[i], "--precompile")) {
313 if (!strncmp(basename, "clang", strlen("clang")))
314 linker_args = 0;
315 break;
316 }
317 }
318
319 /**
320 * Toolchains don't like linker input for '-v' without sources.
321 * It's to hard to handle all those cases, let's focus on a single
322 * '-v' here, since people might use "$CC -v" to dump spec.
323 */
324 if (argc == 2 && !strcmp(argv[1], "-v"))
325 linker_args = 0;
326
327 /* Fill in the relative paths */
328 #ifdef BR_CROSS_PATH_REL
329 ret = snprintf(path, sizeof(path), "%s/" BR_CROSS_PATH_REL "/%s" BR_CROSS_PATH_SUFFIX, absbasedir, basename);
330 #elif defined(BR_CROSS_PATH_ABS)
331 ret = snprintf(path, sizeof(path), BR_CROSS_PATH_ABS "/%s" BR_CROSS_PATH_SUFFIX, basename);
332 #else
333 ret = snprintf(path, sizeof(path), "%s/bin/%s" BR_CROSS_PATH_SUFFIX, absbasedir, basename);
334 #endif
335 if (ret >= sizeof(path)) {
336 perror(__FILE__ ": overflow");
337 return 3;
338 }
339 #ifdef BR_CCACHE
340 ret = snprintf(ccache_path, sizeof(ccache_path), "%s/bin/ccache", absbasedir);
341 if (ret >= sizeof(ccache_path)) {
342 perror(__FILE__ ": overflow");
343 return 3;
344 }
345 #endif
346 ret = snprintf(sysroot, sizeof(sysroot), "%s/" BR_SYSROOT, absbasedir);
347 if (ret >= sizeof(sysroot)) {
348 perror(__FILE__ ": overflow");
349 return 3;
350 }
351
352 cur = args = malloc(sizeof(predef_args) +
353 (sizeof(char *) * (argc + EXCLUSIVE_ARGS)));
354 if (args == NULL) {
355 perror(__FILE__ ": malloc");
356 return 2;
357 }
358
359 /* start with predefined args */
360 memcpy(cur, predef_args, sizeof(predef_args));
361 cur += sizeof(predef_args) / sizeof(predef_args[0]);
362
363 #ifdef BR_FLOAT_ABI
364 /* add float abi if not overridden in args */
365 for (i = 1; i < argc; i++) {
366 if (!strncmp(argv[i], "-mfloat-abi=", strlen("-mfloat-abi=")) ||
367 !strcmp(argv[i], "-msoft-float") ||
368 !strcmp(argv[i], "-mhard-float"))
369 break;
370 }
371
372 if (i == argc)
373 *cur++ = "-mfloat-abi=" BR_FLOAT_ABI;
374 #endif
375
376 #ifdef BR_FP32_MODE
377 /* add fp32 mode if soft-float is not args or hard-float overrides soft-float */
378 int add_fp32_mode = 1;
379 for (i = 1; i < argc; i++) {
380 if (!strcmp(argv[i], "-msoft-float"))
381 add_fp32_mode = 0;
382 else if (!strcmp(argv[i], "-mhard-float"))
383 add_fp32_mode = 1;
384 }
385
386 if (add_fp32_mode == 1)
387 *cur++ = "-mfp" BR_FP32_MODE;
388 #endif
389
390 #if defined(BR_ARCH) || \
391 defined(BR_CPU)
392 /* Add our -march/cpu flags, but only if none of
393 * -march/mtune/mcpu are already specified on the commandline
394 */
395 for (i = 1; i < argc; i++) {
396 if (!strncmp(argv[i], "-march=", strlen("-march=")) ||
397 !strncmp(argv[i], "-mtune=", strlen("-mtune=")) ||
398 !strncmp(argv[i], "-mcpu=", strlen("-mcpu=" )))
399 break;
400 }
401 if (i == argc) {
402 #ifdef BR_ARCH
403 *cur++ = "-march=" BR_ARCH;
404 #endif
405 #ifdef BR_CPU
406 *cur++ = "-mcpu=" BR_CPU;
407 #endif
408 }
409 #endif /* ARCH || CPU */
410
411 if (parse_source_date_epoch_from_env()) {
412 *cur++ = _time_;
413 *cur++ = _date_;
414 /* This has existed since gcc-4.4.0. */
415 *cur++ = "-Wno-builtin-macro-redefined";
416 }
417
418 #ifdef BR2_PIC_PIE
419 /* Patterned after Fedora/Gentoo hardening approaches.
420 * https://fedoraproject.org/wiki/Changes/Harden_All_Packages
421 * https://wiki.gentoo.org/wiki/Hardened/Toolchain#Position_Independent_Executables_.28PIEs.29
422 *
423 * A few checks are added to allow disabling of PIE
424 * 1) -fno-pie and -no-pie are used by other distros to disable PIE in
425 * cases where the compiler enables it by default. The logic below
426 * maintains that behavior.
427 * Ref: https://wiki.ubuntu.com/SecurityTeam/PIE
428 * 2) A check for -fno-PIE has been used in older Linux Kernel builds
429 * in a similar way to -fno-pie or -no-pie.
430 * 3) A check is added for Kernel and U-boot defines
431 * (-D__KERNEL__ and -D__UBOOT__).
432 */
433 for (i = 1; i < argc; i++) {
434 /* Apply all incompatible link flag and disable checks first */
435 if (!strcmp(argv[i], "-r") ||
436 !strcmp(argv[i], "-Wl,-r") ||
437 !strcmp(argv[i], "-static") ||
438 !strcmp(argv[i], "-D__KERNEL__") ||
439 !strcmp(argv[i], "-D__UBOOT__") ||
440 !strcmp(argv[i], "-fno-pie") ||
441 !strcmp(argv[i], "-fno-PIE") ||
442 !strcmp(argv[i], "-no-pie"))
443 break;
444 /* Record that shared was present which disables -pie but don't
445 * break out of loop as a check needs to occur that possibly
446 * still allows -fPIE to be set
447 */
448 if (!strcmp(argv[i], "-shared"))
449 found_shared = 1;
450 }
451
452 if (i == argc) {
453 /* Compile and link condition checking have been kept split
454 * between these two loops, as there maybe already are valid
455 * compile flags set for position independence. In that case
456 * the wrapper just adds the -pie for link.
457 */
458 for (i = 1; i < argc; i++) {
459 if (!strcmp(argv[i], "-fpie") ||
460 !strcmp(argv[i], "-fPIE") ||
461 !strcmp(argv[i], "-fpic") ||
462 !strcmp(argv[i], "-fPIC"))
463 break;
464 }
465 /* Both args below can be set at compile/link time
466 * and are ignored correctly when not used
467 */
468 if (i == argc)
469 *cur++ = "-fPIE";
470
471 if (!found_shared)
472 *cur++ = "-pie";
473 }
474 #endif
475 /* Are we building the Linux Kernel or U-Boot? */
476 for (i = 1; i < argc; i++) {
477 if (!strcmp(argv[i], "-D__KERNEL__") ||
478 !strcmp(argv[i], "-D__UBOOT__"))
479 break;
480 }
481 if (i == argc) {
482 /* https://wiki.gentoo.org/wiki/Hardened/Toolchain#Mark_Read-Only_Appropriate_Sections */
483 #ifdef BR2_RELRO_PARTIAL
484 *cur++ = "-Wl,-z,relro";
485 #endif
486 #ifdef BR2_RELRO_FULL
487 *cur++ = "-Wl,-z,now";
488 *cur++ = "-Wl,-z,relro";
489 #endif
490 }
491
492 /* filter out linker args */
493 if (!linker_args) {
494 for (i = 0; args + i != cur;) {
495 if (!strncmp(args[i], "-Wl,", strlen("-Wl,")) ||
496 !strcmp(args[i], "-pie") ||
497 !strcmp(args[i], "-no-pie")) {
498 cur--;
499 args[i] = *cur;
500 continue;
501 }
502
503 i++;
504 }
505 }
506
507 paranoid_wrapper = getenv("BR_COMPILER_PARANOID_UNSAFE_PATH");
508 if (paranoid_wrapper && strlen(paranoid_wrapper) > 0)
509 paranoid = 1;
510 else
511 paranoid = 0;
512
513 /* Check for unsafe library and header paths */
514 for (i = 1; i < argc; i++) {
515 const struct str_len_s *opt;
516 for (opt=unsafe_opts; opt->str; opt++ ) {
517 /* Skip any non-unsafe option. */
518 if (strncmp(argv[i], opt->str, opt->len))
519 continue;
520
521 /* Handle both cases:
522 * - path is a separate argument,
523 * - path is concatenated with option.
524 */
525 if (argv[i][opt->len] == '\0') {
526 i++;
527 if (i == argc)
528 break;
529 check_unsafe_path(argv[i-1], argv[i], paranoid, 0);
530 } else
531 check_unsafe_path(argv[i], argv[i] + opt->len, paranoid, 1);
532 }
533 }
534
535 /* append forward args */
536 memcpy(cur, &argv[1], sizeof(char *) * (argc - 1));
537 cur += argc - 1;
538
539 /* finish with NULL termination */
540 *cur = NULL;
541
542 exec_args = args;
543 #ifdef BR_CCACHE
544 if (getenv("BR_NO_CCACHE"))
545 /* Skip the ccache call */
546 exec_args++;
547 #endif
548
549 /* Debug the wrapper to see final arguments passed to the real compiler. */
550 if (debug > 0) {
551 fprintf(stderr, "Toolchain wrapper executing:");
552 #ifdef BR_CCACHE_HASH
553 fprintf(stderr, "%sCCACHE_COMPILERCHECK='string:" BR_CCACHE_HASH "'",
554 (debug == 2) ? "\n " : " ");
555 #endif
556 #ifdef BR_CCACHE_BASEDIR
557 fprintf(stderr, "%sCCACHE_BASEDIR='" BR_CCACHE_BASEDIR "'",
558 (debug == 2) ? "\n " : " ");
559 #endif
560 for (i = 0; exec_args[i]; i++)
561 fprintf(stderr, "%s'%s'",
562 (debug == 2) ? "\n " : " ", exec_args[i]);
563 fprintf(stderr, "\n");
564 }
565
566 #ifdef BR_CCACHE_HASH
567 /* Allow compilercheck to be overridden through the environment */
568 if (setenv("CCACHE_COMPILERCHECK", "string:" BR_CCACHE_HASH, 0)) {
569 perror(__FILE__ ": Failed to set CCACHE_COMPILERCHECK");
570 return 3;
571 }
572 #endif
573 #ifdef BR_CCACHE_BASEDIR
574 /* Allow compilercheck to be overridden through the environment */
575 if (setenv("CCACHE_BASEDIR", BR_CCACHE_BASEDIR, 0)) {
576 perror(__FILE__ ": Failed to set CCACHE_BASEDIR");
577 return 3;
578 }
579 #endif
580
581 if (execv(exec_args[0], exec_args))
582 perror(path);
583
584 free(args);
585
586 return 2;
587 }
588