boards/nanopi-neo: update defconfig
[buildroot-gz.git] / toolchain / toolchain-wrapper.c
blobeb4ee8de4ac11d771599c6b614e10fb6ec5ac139
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.
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>
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.
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>
27 #ifdef BR_CCACHE
28 static char ccache_path[PATH_MAX];
29 #endif
30 static char path[PATH_MAX];
31 static char sysroot[PATH_MAX];
32 static char source_time[sizeof("-D__TIME__=\"HH:MM:SS\"")];
33 static char source_date[sizeof("-D__DATE__=\"MMM DD YYYY\"")];
35 /**
36 * GCC errors out with certain combinations of arguments (examples are
37 * -mfloat-abi={hard|soft} and -m{little|big}-endian), so we have to ensure
38 * that we only pass the predefined one to the real compiler if the inverse
39 * option isn't in the argument list.
40 * This specifies the worst case number of extra arguments we might pass
41 * Currently, we have:
42 * -mfloat-abi=
43 * -march=
44 * -mcpu=
45 * -D__TIME__=
46 * -D__DATE__=
47 * -Wno-builtin-macro-redefined
49 #define EXCLUSIVE_ARGS 6
51 static char *predef_args[] = {
52 #ifdef BR_CCACHE
53 ccache_path,
54 #endif
55 path,
56 "--sysroot", sysroot,
57 #ifdef BR_ABI
58 "-mabi=" BR_ABI,
59 #endif
60 #ifdef BR_FPU
61 "-mfpu=" BR_FPU,
62 #endif
63 #ifdef BR_SOFTFLOAT
64 "-msoft-float",
65 #endif /* BR_SOFTFLOAT */
66 #ifdef BR_MODE
67 "-m" BR_MODE,
68 #endif
69 #ifdef BR_64
70 "-m64",
71 #endif
72 #ifdef BR_OMIT_LOCK_PREFIX
73 "-Wa,-momit-lock-prefix=yes",
74 #endif
75 #ifdef BR_NO_FUSED_MADD
76 "-mno-fused-madd",
77 #endif
78 #ifdef BR_BINFMT_FLAT
79 "-Wl,-elf2flt",
80 #endif
81 #ifdef BR_MIPS_TARGET_LITTLE_ENDIAN
82 "-EL",
83 #endif
84 #if defined(BR_MIPS_TARGET_BIG_ENDIAN) || defined(BR_ARC_TARGET_BIG_ENDIAN)
85 "-EB",
86 #endif
87 #ifdef BR_ADDITIONAL_CFLAGS
88 BR_ADDITIONAL_CFLAGS
89 #endif
92 /* A {string,length} tuple, to avoid computing strlen() on constants.
93 * - str must be a \0-terminated string
94 * - len does not account for the terminating '\0'
96 struct str_len_s {
97 const char *str;
98 size_t len;
101 /* Define a {string,length} tuple. Takes an unquoted constant string as
102 * parameter. sizeof() on a string literal includes the terminating \0,
103 * but we don't want to count it.
105 #define STR_LEN(s) { #s, sizeof(#s)-1 }
107 /* List of paths considered unsafe for cross-compilation.
109 * An unsafe path is one that points to a directory with libraries or
110 * headers for the build machine, which are not suitable for the target.
112 static const struct str_len_s unsafe_paths[] = {
113 STR_LEN(/lib),
114 STR_LEN(/usr/include),
115 STR_LEN(/usr/lib),
116 STR_LEN(/usr/local/include),
117 STR_LEN(/usr/local/lib),
118 { NULL, 0 },
121 /* Unsafe options are options that specify a potentialy unsafe path,
122 * that will be checked by check_unsafe_path(), below.
124 static const struct str_len_s unsafe_opts[] = {
125 STR_LEN(-I),
126 STR_LEN(-idirafter),
127 STR_LEN(-iquote),
128 STR_LEN(-isystem),
129 STR_LEN(-L),
130 { NULL, 0 },
133 /* Check if path is unsafe for cross-compilation. Unsafe paths are those
134 * pointing to the standard native include or library paths.
136 * We print the arguments leading to the failure. For some options, gcc
137 * accepts the path to be concatenated to the argument (e.g. -I/foo/bar)
138 * or separated (e.g. -I /foo/bar). In the first case, we need only print
139 * the argument as it already contains the path (arg_has_path), while in
140 * the second case we need to print both (!arg_has_path).
142 * If paranoid, exit in error instead of just printing a warning.
144 static void check_unsafe_path(const char *arg,
145 const char *path,
146 int paranoid,
147 int arg_has_path)
149 const struct str_len_s *p;
151 for (p=unsafe_paths; p->str; p++) {
152 if (strncmp(path, p->str, p->len))
153 continue;
154 fprintf(stderr,
155 "%s: %s: unsafe header/library path used in cross-compilation: '%s%s%s'\n",
156 program_invocation_short_name,
157 paranoid ? "ERROR" : "WARNING",
158 arg,
159 arg_has_path ? "" : "' '", /* close single-quote, space, open single-quote */
160 arg_has_path ? "" : path); /* so that arg and path are properly quoted. */
161 if (paranoid)
162 exit(1);
166 /* Read SOURCE_DATE_EPOCH from environment to have a deterministic
167 * timestamp to replace embedded current dates to get reproducible
168 * results. Returns -1 if SOURCE_DATE_EPOCH is not defined.
170 static time_t get_source_date_epoch()
172 char *source_date_epoch;
173 long long epoch;
174 char *endptr;
176 source_date_epoch = getenv("SOURCE_DATE_EPOCH");
177 if (!source_date_epoch)
178 return (time_t) -1;
180 errno = 0;
181 epoch = strtoll(source_date_epoch, &endptr, 10);
182 if ((errno == ERANGE && (epoch == LLONG_MAX || epoch == LLONG_MIN))
183 || (errno != 0 && epoch == 0)) {
184 fprintf(stderr, "environment variable $SOURCE_DATE_EPOCH: "
185 "strtoll: %s\n", strerror(errno));
186 exit(2);
188 if (endptr == source_date_epoch) {
189 fprintf(stderr, "environment variable $SOURCE_DATE_EPOCH: "
190 "no digits were found: %s\n", endptr);
191 exit(2);
193 if (*endptr != '\0') {
194 fprintf(stderr, "environment variable $SOURCE_DATE_EPOCH: "
195 "trailing garbage: %s\n", endptr);
196 exit(2);
198 if (epoch < 0) {
199 fprintf(stderr, "environment variable $SOURCE_DATE_EPOCH: "
200 "value must be nonnegative: %lld \n", epoch);
201 exit(2);
204 return (time_t) epoch;
207 int main(int argc, char **argv)
209 char **args, **cur, **exec_args;
210 char *relbasedir, *absbasedir;
211 char *progpath = argv[0];
212 char *basename;
213 char *env_debug;
214 char *paranoid_wrapper;
215 int paranoid;
216 int ret, i, count = 0, debug;
217 time_t source_date_epoch;
219 /* Calculate the relative paths */
220 basename = strrchr(progpath, '/');
221 if (basename) {
222 *basename = '\0';
223 basename++;
224 relbasedir = malloc(strlen(progpath) + 7);
225 if (relbasedir == NULL) {
226 perror(__FILE__ ": malloc");
227 return 2;
229 sprintf(relbasedir, "%s/../..", argv[0]);
230 absbasedir = realpath(relbasedir, NULL);
231 } else {
232 basename = progpath;
233 absbasedir = malloc(PATH_MAX + 1);
234 ret = readlink("/proc/self/exe", absbasedir, PATH_MAX);
235 if (ret < 0) {
236 perror(__FILE__ ": readlink");
237 return 2;
239 absbasedir[ret] = '\0';
240 for (i = ret; i > 0; i--) {
241 if (absbasedir[i] == '/') {
242 absbasedir[i] = '\0';
243 if (++count == 3)
244 break;
248 if (absbasedir == NULL) {
249 perror(__FILE__ ": realpath");
250 return 2;
253 /* Fill in the relative paths */
254 #ifdef BR_CROSS_PATH_REL
255 ret = snprintf(path, sizeof(path), "%s/" BR_CROSS_PATH_REL "/%s" BR_CROSS_PATH_SUFFIX, absbasedir, basename);
256 #elif defined(BR_CROSS_PATH_ABS)
257 ret = snprintf(path, sizeof(path), BR_CROSS_PATH_ABS "/%s" BR_CROSS_PATH_SUFFIX, basename);
258 #else
259 ret = snprintf(path, sizeof(path), "%s/usr/bin/%s" BR_CROSS_PATH_SUFFIX, absbasedir, basename);
260 #endif
261 if (ret >= sizeof(path)) {
262 perror(__FILE__ ": overflow");
263 return 3;
265 #ifdef BR_CCACHE
266 ret = snprintf(ccache_path, sizeof(ccache_path), "%s/usr/bin/ccache", absbasedir);
267 if (ret >= sizeof(ccache_path)) {
268 perror(__FILE__ ": overflow");
269 return 3;
271 #endif
272 ret = snprintf(sysroot, sizeof(sysroot), "%s/" BR_SYSROOT, absbasedir);
273 if (ret >= sizeof(sysroot)) {
274 perror(__FILE__ ": overflow");
275 return 3;
278 cur = args = malloc(sizeof(predef_args) +
279 (sizeof(char *) * (argc + EXCLUSIVE_ARGS)));
280 if (args == NULL) {
281 perror(__FILE__ ": malloc");
282 return 2;
285 /* start with predefined args */
286 memcpy(cur, predef_args, sizeof(predef_args));
287 cur += sizeof(predef_args) / sizeof(predef_args[0]);
289 #ifdef BR_FLOAT_ABI
290 /* add float abi if not overridden in args */
291 for (i = 1; i < argc; i++) {
292 if (!strncmp(argv[i], "-mfloat-abi=", strlen("-mfloat-abi=")) ||
293 !strcmp(argv[i], "-msoft-float") ||
294 !strcmp(argv[i], "-mhard-float"))
295 break;
298 if (i == argc)
299 *cur++ = "-mfloat-abi=" BR_FLOAT_ABI;
300 #endif
302 #if defined(BR_ARCH) || \
303 defined(BR_CPU)
304 /* Add our -march/cpu flags, but only if none of
305 * -march/mtune/mcpu are already specified on the commandline
307 for (i = 1; i < argc; i++) {
308 if (!strncmp(argv[i], "-march=", strlen("-march=")) ||
309 !strncmp(argv[i], "-mtune=", strlen("-mtune=")) ||
310 !strncmp(argv[i], "-mcpu=", strlen("-mcpu=" )))
311 break;
313 if (i == argc) {
314 #ifdef BR_ARCH
315 *cur++ = "-march=" BR_ARCH;
316 #endif
317 #ifdef BR_CPU
318 *cur++ = "-mcpu=" BR_CPU;
319 #endif
321 #endif /* ARCH || CPU */
323 source_date_epoch = get_source_date_epoch();
324 if (source_date_epoch != -1) {
325 struct tm *tm = localtime(&source_date_epoch);
326 if (!tm) {
327 perror("__FILE__: localtime");
328 return 3;
330 ret = strftime(source_time, sizeof(source_time), "-D__TIME__=\"%T\"", tm);
331 if (!ret) {
332 perror("__FILE__: overflow");
333 return 3;
335 *cur++ = source_time;
336 ret = strftime(source_date, sizeof(source_date), "-D__DATE__=\"%b %e %Y\"", tm);
337 if (!ret) {
338 perror("__FILE__: overflow");
339 return 3;
341 *cur++ = source_date;
342 *cur++ = "-Wno-builtin-macro-redefined";
345 paranoid_wrapper = getenv("BR_COMPILER_PARANOID_UNSAFE_PATH");
346 if (paranoid_wrapper && strlen(paranoid_wrapper) > 0)
347 paranoid = 1;
348 else
349 paranoid = 0;
351 /* Check for unsafe library and header paths */
352 for (i = 1; i < argc; i++) {
353 const struct str_len_s *opt;
354 for (opt=unsafe_opts; opt->str; opt++ ) {
355 /* Skip any non-unsafe option. */
356 if (strncmp(argv[i], opt->str, opt->len))
357 continue;
359 /* Handle both cases:
360 * - path is a separate argument,
361 * - path is concatenated with option.
363 if (argv[i][opt->len] == '\0') {
364 i++;
365 if (i == argc)
366 break;
367 check_unsafe_path(argv[i-1], argv[i], paranoid, 0);
368 } else
369 check_unsafe_path(argv[i], argv[i] + opt->len, paranoid, 1);
373 /* append forward args */
374 memcpy(cur, &argv[1], sizeof(char *) * (argc - 1));
375 cur += argc - 1;
377 /* finish with NULL termination */
378 *cur = NULL;
380 exec_args = args;
381 #ifdef BR_CCACHE
382 if (getenv("BR_NO_CCACHE"))
383 /* Skip the ccache call */
384 exec_args++;
385 #endif
387 /* Debug the wrapper to see actual arguments passed to
388 * the compiler:
389 * unset, empty, or 0: do not trace
390 * set to 1 : trace all arguments on a single line
391 * set to 2 : trace one argument per line
393 if ((env_debug = getenv("BR2_DEBUG_WRAPPER"))) {
394 debug = atoi(env_debug);
395 if (debug > 0) {
396 fprintf(stderr, "Toolchain wrapper executing:");
397 #ifdef BR_CCACHE_HASH
398 fprintf(stderr, "%sCCACHE_COMPILERCHECK='string:" BR_CCACHE_HASH "'",
399 (debug == 2) ? "\n " : " ");
400 #endif
401 #ifdef BR_CCACHE_BASEDIR
402 fprintf(stderr, "%sCCACHE_BASEDIR='" BR_CCACHE_BASEDIR "'",
403 (debug == 2) ? "\n " : " ");
404 #endif
405 for (i = 0; exec_args[i]; i++)
406 fprintf(stderr, "%s'%s'",
407 (debug == 2) ? "\n " : " ", exec_args[i]);
408 fprintf(stderr, "\n");
412 #ifdef BR_CCACHE_HASH
413 /* Allow compilercheck to be overridden through the environment */
414 if (setenv("CCACHE_COMPILERCHECK", "string:" BR_CCACHE_HASH, 0)) {
415 perror(__FILE__ ": Failed to set CCACHE_COMPILERCHECK");
416 return 3;
418 #endif
419 #ifdef BR_CCACHE_BASEDIR
420 /* Allow compilercheck to be overridden through the environment */
421 if (setenv("CCACHE_BASEDIR", BR_CCACHE_BASEDIR, 0)) {
422 perror(__FILE__ ": Failed to set CCACHE_BASEDIR");
423 return 3;
425 #endif
427 if (execv(exec_args[0], exec_args))
428 perror(path);
430 free(args);
432 return 2;