2
1

toolchain-wrapper.c 15 KB

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