toolchain-wrapper.c 15 KB

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