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  */
check_unsafe_path(const char * arg,const char * path,int arg_has_path)158 static void check_unsafe_path(const char *arg,
159 			      const char *path,
160 			      int arg_has_path)
161 {
162 	const struct str_len_s *p;
163 
164 	for (p=unsafe_paths; p->str; p++) {
165 		if (strncmp(path, p->str, p->len))
166 			continue;
167 		fprintf(stderr,
168 			"%s: ERROR: unsafe header/library path used in cross-compilation: '%s%s%s'\n",
169 			program_invocation_short_name,
170 			arg,
171 			arg_has_path ? "" : "' '", /* close single-quote, space, open single-quote */
172 			arg_has_path ? "" : path); /* so that arg and path are properly quoted. */
173 		exit(1);
174 	}
175 }
176 
177 #ifdef BR_NEED_SOURCE_DATE_EPOCH
178 /* Returns false if SOURCE_DATE_EPOCH was not defined in the environment.
179  *
180  * Returns true if SOURCE_DATE_EPOCH is in the environment and represent
181  * a valid timestamp, in which case the timestamp is formatted into the
182  * global variables _date_ and _time_.
183  *
184  * Aborts if SOURCE_DATE_EPOCH was set in the environment but did not
185  * contain a valid timestamp.
186  *
187  * Valid values are defined in the spec:
188  *     https://reproducible-builds.org/specs/source-date-epoch/
189  * but we further restrict them to be positive or null.
190  */
parse_source_date_epoch_from_env(void)191 bool parse_source_date_epoch_from_env(void)
192 {
193 	char *epoch_env, *endptr;
194 	time_t epoch;
195 	struct tm epoch_tm;
196 
197 	if ((epoch_env = getenv("SOURCE_DATE_EPOCH")) == NULL)
198 		return false;
199 	errno = 0;
200 	epoch = (time_t) strtoll(epoch_env, &endptr, 10);
201 	/* We just need to test if it is incorrect, but we do not
202 	 * care why it is incorrect.
203 	 */
204 	if ((errno != 0) || !*epoch_env || *endptr || (epoch < 0)) {
205 		fprintf(stderr, "%s: invalid SOURCE_DATE_EPOCH='%s'\n",
206 			program_invocation_short_name,
207 			epoch_env);
208 		exit(1);
209 	}
210 	tzset(); /* For localtime_r(), below. */
211 	if (localtime_r(&epoch, &epoch_tm) == NULL) {
212 		fprintf(stderr, "%s: cannot parse SOURCE_DATE_EPOCH=%s\n",
213 				program_invocation_short_name,
214 				getenv("SOURCE_DATE_EPOCH"));
215 		exit(1);
216 	}
217 	if (!strftime(_time_, sizeof(_time_), "-D__TIME__=\"%T\"", &epoch_tm)) {
218 		fprintf(stderr, "%s: cannot set time from SOURCE_DATE_EPOCH=%s\n",
219 				program_invocation_short_name,
220 				getenv("SOURCE_DATE_EPOCH"));
221 		exit(1);
222 	}
223 	if (!strftime(_date_, sizeof(_date_), "-D__DATE__=\"%b %e %Y\"", &epoch_tm)) {
224 		fprintf(stderr, "%s: cannot set date from SOURCE_DATE_EPOCH=%s\n",
225 				program_invocation_short_name,
226 				getenv("SOURCE_DATE_EPOCH"));
227 		exit(1);
228 	}
229 	return true;
230 }
231 #else
parse_source_date_epoch_from_env(void)232 bool parse_source_date_epoch_from_env(void)
233 {
234 	/* The compiler is recent enough to handle SOURCE_DATE_EPOCH itself
235 	 * so we do not need to do anything here.
236 	 */
237 	return false;
238 }
239 #endif
240 
main(int argc,char ** argv)241 int main(int argc, char **argv)
242 {
243 	char **args, **cur, **exec_args;
244 	char *relbasedir, *absbasedir;
245 	char *progpath = argv[0];
246 	char *basename;
247 	char *env_debug;
248 	int ret, i, count = 0, debug = 0, found_shared = 0;
249 
250 	/* Debug the wrapper to see arguments it was called with.
251 	 * If environment variable BR2_DEBUG_WRAPPER is:
252 	 * unset, empty, or 0: do not trace
253 	 * set to 1          : trace all arguments on a single line
254 	 * set to 2          : trace one argument per line
255 	 */
256 	if ((env_debug = getenv("BR2_DEBUG_WRAPPER"))) {
257 		debug = atoi(env_debug);
258 	}
259 	if (debug > 0) {
260 		fprintf(stderr, "Toolchain wrapper was called with:");
261 		for (i = 0; i < argc; i++)
262 			fprintf(stderr, "%s'%s'",
263 				(debug == 2) ? "\n    " : " ", argv[i]);
264 		fprintf(stderr, "\n");
265 	}
266 
267 	/* Calculate the relative paths */
268 	basename = strrchr(progpath, '/');
269 	if (basename) {
270 		*basename = '\0';
271 		basename++;
272 		relbasedir = malloc(strlen(progpath) + 7);
273 		if (relbasedir == NULL) {
274 			perror(__FILE__ ": malloc");
275 			return 2;
276 		}
277 		sprintf(relbasedir, "%s/..", argv[0]);
278 		absbasedir = realpath(relbasedir, NULL);
279 	} else {
280 		basename = progpath;
281 		absbasedir = malloc(PATH_MAX + 1);
282 		ret = readlink("/proc/self/exe", absbasedir, PATH_MAX);
283 		if (ret < 0) {
284 			perror(__FILE__ ": readlink");
285 			return 2;
286 		}
287 		absbasedir[ret] = '\0';
288 		for (i = ret; i > 0; i--) {
289 			if (absbasedir[i] == '/') {
290 				absbasedir[i] = '\0';
291 				if (++count == 2)
292 					break;
293 			}
294 		}
295 	}
296 	if (absbasedir == NULL) {
297 		perror(__FILE__ ": realpath");
298 		return 2;
299 	}
300 
301 	/* Fill in the relative paths */
302 #ifdef BR_CROSS_PATH_REL
303 	ret = snprintf(path, sizeof(path), "%s/" BR_CROSS_PATH_REL "/%s" BR_CROSS_PATH_SUFFIX, absbasedir, basename);
304 #elif defined(BR_CROSS_PATH_ABS)
305 	ret = snprintf(path, sizeof(path), BR_CROSS_PATH_ABS "/%s" BR_CROSS_PATH_SUFFIX, basename);
306 #else
307 	ret = snprintf(path, sizeof(path), "%s/bin/%s" BR_CROSS_PATH_SUFFIX, absbasedir, basename);
308 #endif
309 	if (ret >= sizeof(path)) {
310 		perror(__FILE__ ": overflow");
311 		return 3;
312 	}
313 #ifdef BR_CCACHE
314 	ret = snprintf(ccache_path, sizeof(ccache_path), "%s/bin/ccache", absbasedir);
315 	if (ret >= sizeof(ccache_path)) {
316 		perror(__FILE__ ": overflow");
317 		return 3;
318 	}
319 #endif
320 	ret = snprintf(sysroot, sizeof(sysroot), "%s/" BR_SYSROOT, absbasedir);
321 	if (ret >= sizeof(sysroot)) {
322 		perror(__FILE__ ": overflow");
323 		return 3;
324 	}
325 
326 	cur = args = malloc(sizeof(predef_args) +
327 			    (sizeof(char *) * (argc + EXCLUSIVE_ARGS)));
328 	if (args == NULL) {
329 		perror(__FILE__ ": malloc");
330 		return 2;
331 	}
332 
333 	/* start with predefined args */
334 	memcpy(cur, predef_args, sizeof(predef_args));
335 	cur += sizeof(predef_args) / sizeof(predef_args[0]);
336 
337 #ifdef BR_FLOAT_ABI
338 	/* add float abi if not overridden in args */
339 	for (i = 1; i < argc; i++) {
340 		if (!strncmp(argv[i], "-mfloat-abi=", strlen("-mfloat-abi=")) ||
341 		    !strcmp(argv[i], "-msoft-float") ||
342 		    !strcmp(argv[i], "-mhard-float"))
343 			break;
344 	}
345 
346 	if (i == argc)
347 		*cur++ = "-mfloat-abi=" BR_FLOAT_ABI;
348 #endif
349 
350 #ifdef BR_FP32_MODE
351 	/* add fp32 mode if soft-float is not args or hard-float overrides soft-float */
352 	int add_fp32_mode = 1;
353 	for (i = 1; i < argc; i++) {
354 		if (!strcmp(argv[i], "-msoft-float"))
355 			add_fp32_mode = 0;
356 		else if (!strcmp(argv[i], "-mhard-float"))
357 			add_fp32_mode = 1;
358 	}
359 
360 	if (add_fp32_mode == 1)
361 		*cur++ = "-mfp" BR_FP32_MODE;
362 #endif
363 
364 #if defined(BR_ARCH) || \
365     defined(BR_CPU)
366 	/* Add our -march/cpu flags, but only if none of
367 	 * -march/mtune/mcpu are already specified on the commandline
368 	 */
369 	for (i = 1; i < argc; i++) {
370 		if (!strncmp(argv[i], "-march=", strlen("-march=")) ||
371 		    !strncmp(argv[i], "-mtune=", strlen("-mtune=")) ||
372 		    !strncmp(argv[i], "-mcpu=",  strlen("-mcpu=" )))
373 			break;
374 	}
375 	if (i == argc) {
376 #ifdef BR_ARCH
377 		*cur++ = "-march=" BR_ARCH;
378 #endif
379 #ifdef BR_CPU
380 		*cur++ = "-mcpu=" BR_CPU;
381 #endif
382 	}
383 #endif /* ARCH || CPU */
384 
385 	if (parse_source_date_epoch_from_env()) {
386 		*cur++ = _time_;
387 		*cur++ = _date_;
388 		/* This has existed since gcc-4.4.0. */
389 		*cur++ = "-Wno-builtin-macro-redefined";
390 	}
391 
392 #ifdef BR2_PIC_PIE
393 	/* Patterned after Fedora/Gentoo hardening approaches.
394 	 * https://fedoraproject.org/wiki/Changes/Harden_All_Packages
395 	 * https://wiki.gentoo.org/wiki/Hardened/Toolchain#Position_Independent_Executables_.28PIEs.29
396 	 *
397 	 * A few checks are added to allow disabling of PIE
398 	 * 1) -fno-pie and -no-pie are used by other distros to disable PIE in
399 	 *    cases where the compiler enables it by default. The logic below
400 	 *    maintains that behavior.
401 	 *         Ref: https://wiki.ubuntu.com/SecurityTeam/PIE
402 	 * 2) A check for -fno-PIE has been used in older Linux Kernel builds
403 	 *    in a similar way to -fno-pie or -no-pie.
404 	 * 3) A check is added for Kernel and U-boot defines
405 	 *    (-D__KERNEL__ and -D__UBOOT__).
406 	 */
407 	for (i = 1; i < argc; i++) {
408 		/* Apply all incompatible link flag and disable checks first */
409 		if (!strcmp(argv[i], "-r") ||
410 		    !strcmp(argv[i], "-Wl,-r") ||
411 		    !strcmp(argv[i], "-static") ||
412 		    !strcmp(argv[i], "-D__KERNEL__") ||
413 		    !strcmp(argv[i], "-D__UBOOT__") ||
414 		    !strcmp(argv[i], "-fno-pie") ||
415 		    !strcmp(argv[i], "-fno-PIE") ||
416 		    !strcmp(argv[i], "-no-pie"))
417 			break;
418 		/* Record that shared was present which disables -pie but don't
419 		 * break out of loop as a check needs to occur that possibly
420 		 * still allows -fPIE to be set
421 		 */
422 		if (!strcmp(argv[i], "-shared"))
423 			found_shared = 1;
424 	}
425 
426 	if (i == argc) {
427 		/* Compile and link condition checking have been kept split
428 		 * between these two loops, as there maybe already are valid
429 		 * compile flags set for position independence. In that case
430 		 * the wrapper just adds the -pie for link.
431 		 */
432 		for (i = 1; i < argc; i++) {
433 			if (!strcmp(argv[i], "-fpie") ||
434 			    !strcmp(argv[i], "-fPIE") ||
435 			    !strcmp(argv[i], "-fpic") ||
436 			    !strcmp(argv[i], "-fPIC"))
437 				break;
438 		}
439 		/* Both args below can be set at compile/link time
440 		 * and are ignored correctly when not used
441 		 */
442 		if (i == argc)
443 			*cur++ = "-fPIE";
444 
445 		if (!found_shared)
446 			*cur++ = "-pie";
447 	}
448 #endif
449 	/* Are we building the Linux Kernel or U-Boot? */
450 	for (i = 1; i < argc; i++) {
451 		if (!strcmp(argv[i], "-D__KERNEL__") ||
452 		    !strcmp(argv[i], "-D__UBOOT__"))
453 			break;
454 	}
455 	if (i == argc) {
456 		/* https://wiki.gentoo.org/wiki/Hardened/Toolchain#Mark_Read-Only_Appropriate_Sections */
457 #ifdef BR2_RELRO_PARTIAL
458 		*cur++ = "-Wl,-z,relro";
459 #endif
460 #ifdef BR2_RELRO_FULL
461 		*cur++ = "-Wl,-z,now";
462 		*cur++ = "-Wl,-z,relro";
463 #endif
464 	}
465 
466 	/* Check for unsafe library and header paths */
467 	for (i = 1; i < argc; i++) {
468 		const struct str_len_s *opt;
469 		for (opt=unsafe_opts; opt->str; opt++ ) {
470 			/* Skip any non-unsafe option. */
471 			if (strncmp(argv[i], opt->str, opt->len))
472 				continue;
473 
474 			/* Handle both cases:
475 			 *  - path is a separate argument,
476 			 *  - path is concatenated with option.
477 			 */
478 			if (argv[i][opt->len] == '\0') {
479 				i++;
480 				if (i == argc)
481 					break;
482 				check_unsafe_path(argv[i-1], argv[i], 0);
483 			} else
484 				check_unsafe_path(argv[i], argv[i] + opt->len, 1);
485 		}
486 	}
487 
488 	/* append forward args */
489 	memcpy(cur, &argv[1], sizeof(char *) * (argc - 1));
490 	cur += argc - 1;
491 
492 	/* finish with NULL termination */
493 	*cur = NULL;
494 
495 	exec_args = args;
496 #ifdef BR_CCACHE
497 	/* If BR2_USE_CCACHE is set and its value is 1, enable ccache
498 	 * usage */
499 	char *br_use_ccache = getenv("BR2_USE_CCACHE");
500 	bool ccache_enabled = br_use_ccache && !strncmp(br_use_ccache, "1", strlen("1"));
501 
502 	if (ccache_enabled) {
503 #ifdef BR_CCACHE_HASH
504 		/* Allow compilercheck to be overridden through the environment */
505 		if (setenv("CCACHE_COMPILERCHECK", "string:" BR_CCACHE_HASH, 0)) {
506 			perror(__FILE__ ": Failed to set CCACHE_COMPILERCHECK");
507 			return 3;
508 		}
509 #endif
510 #ifdef BR_CCACHE_BASEDIR
511 		/* Allow compilercheck to be overridden through the environment */
512 		if (setenv("CCACHE_BASEDIR", BR_CCACHE_BASEDIR, 0)) {
513 			perror(__FILE__ ": Failed to set CCACHE_BASEDIR");
514 			return 3;
515 		}
516 #endif
517 	} else
518 		/* ccache is disabled, skip it */
519 		exec_args++;
520 #endif
521 
522 	/* Debug the wrapper to see final arguments passed to the real compiler. */
523 	if (debug > 0) {
524 		fprintf(stderr, "Toolchain wrapper executing:");
525 #ifdef BR_CCACHE_HASH
526 		if (ccache_enabled)
527 			fprintf(stderr, "%sCCACHE_COMPILERCHECK='string:" BR_CCACHE_HASH "'",
528 				(debug == 2) ? "\n    " : " ");
529 #endif
530 #ifdef BR_CCACHE_BASEDIR
531 		if (ccache_enabled)
532 			fprintf(stderr, "%sCCACHE_BASEDIR='" BR_CCACHE_BASEDIR "'",
533 				(debug == 2) ? "\n    " : " ");
534 #endif
535 		for (i = 0; exec_args[i]; i++)
536 			fprintf(stderr, "%s'%s'",
537 				(debug == 2) ? "\n    " : " ", exec_args[i]);
538 		fprintf(stderr, "\n");
539 	}
540 
541 	if (execv(exec_args[0], exec_args))
542 		perror(path);
543 
544 	free(args);
545 
546 	return 2;
547 }
548