toolchain-wrapper.c 12 KB

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