toolchain-wrapper.c 11 KB

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