toolchain-wrapper.c 15 KB

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