/tags/rel-1.3.39/CCache/ccache.c

# · C · 1388 lines · 1016 code · 188 blank · 184 comment · 309 complexity · d9eb4c55515cac618555479180b7bbac MD5 · raw file

  1. /*
  2. a re-implementation of the compilercache scripts in C
  3. The idea is based on the shell-script compilercache by Erik Thiele <erikyyy@erikyyy.de>
  4. Copyright (C) Andrew Tridgell 2002
  5. Copyright (C) Martin Pool 2003
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software
  16. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. */
  18. #include "ccache.h"
  19. /* verbose mode */
  20. int ccache_verbose = 0;
  21. /* the base cache directory */
  22. char *cache_dir = NULL;
  23. /* the directory for temporary files */
  24. static char *temp_dir = NULL;
  25. /* the debug logfile name, if set */
  26. char *cache_logfile = NULL;
  27. /* the argument list after processing */
  28. static ARGS *stripped_args;
  29. /* the original argument list */
  30. static ARGS *orig_args;
  31. /* the output filename being compiled to */
  32. static char *output_file;
  33. /* the source file */
  34. static char *input_file;
  35. /* the name of the file containing the cached object code */
  36. static char *hashname;
  37. /* the extension of the file after pre-processing */
  38. static const char *i_extension;
  39. /* the name of the temporary pre-processor file */
  40. static char *i_tmpfile;
  41. /* are we compiling a .i or .ii file directly? */
  42. static int direct_i_file;
  43. /* the name of the cpp stderr file */
  44. static char *cpp_stderr;
  45. /* the name of the statistics file */
  46. char *stats_file = NULL;
  47. /* can we safely use the unification hashing backend? */
  48. static int enable_unify;
  49. /* should we strip -c when running the preprocessor only? */
  50. static int strip_c_option;
  51. /* customisation for using the SWIG compiler */
  52. static int swig;
  53. /* a list of supported file extensions, and the equivalent
  54. extension for code that has been through the pre-processor
  55. */
  56. static struct {
  57. char *extension;
  58. char *i_extension;
  59. } extensions[] = {
  60. {"c", "i"},
  61. {"C", "ii"},
  62. {"m", "mi"},
  63. {"cc", "ii"},
  64. {"CC", "ii"},
  65. {"cpp", "ii"},
  66. {"CPP", "ii"},
  67. {"cxx", "ii"},
  68. {"CXX", "ii"},
  69. {"c++", "ii"},
  70. {"C++", "ii"},
  71. {"i", "i"},
  72. {"ii", "ii"},
  73. {NULL, NULL}};
  74. /*
  75. something went badly wrong - just execute the real compiler
  76. */
  77. static void failed(void)
  78. {
  79. char *e;
  80. /* delete intermediate pre-processor file if needed */
  81. if (i_tmpfile) {
  82. if (!direct_i_file) {
  83. unlink(i_tmpfile);
  84. }
  85. free(i_tmpfile);
  86. i_tmpfile = NULL;
  87. }
  88. /* delete the cpp stderr file if necessary */
  89. if (cpp_stderr) {
  90. unlink(cpp_stderr);
  91. free(cpp_stderr);
  92. cpp_stderr = NULL;
  93. }
  94. /* strip any local args */
  95. args_strip(orig_args, "--ccache-");
  96. if ((e=getenv("CCACHE_PREFIX"))) {
  97. char *p = find_executable(e, MYNAME);
  98. if (!p) {
  99. cc_log("could not find executable (%s)\n", e);
  100. perror(e);
  101. exit(1);
  102. }
  103. args_add_prefix(orig_args, p);
  104. }
  105. if (ccache_verbose) {
  106. display_execute_args(orig_args->argv);
  107. }
  108. if (swig) {
  109. putenv("CCACHE_OUTFILES");
  110. }
  111. #ifndef _WIN32
  112. execv(orig_args->argv[0], orig_args->argv);
  113. cc_log("execv returned (%s)!\n", strerror(errno));
  114. perror(orig_args->argv[0]);
  115. exit(1);
  116. #else
  117. /* execv on Windows causes the 'non-regular' testcase to fail, so use Win32 API instead */
  118. {
  119. PROCESS_INFORMATION pinfo;
  120. STARTUPINFO sinfo;
  121. BOOL ret;
  122. DWORD exitcode;
  123. char *args;
  124. ZeroMemory(&pinfo, sizeof(PROCESS_INFORMATION));
  125. ZeroMemory(&sinfo, sizeof(STARTUPINFO));
  126. sinfo.cb = sizeof(STARTUPINFO);
  127. args = argvtos(orig_args->argv);
  128. ret = CreateProcessA(orig_args->argv[0], args, NULL, NULL, TRUE, 0, NULL, NULL,
  129. &sinfo, &pinfo);
  130. if (!ret) {
  131. exitcode = 1;
  132. cc_log("CreateProcessA failed starting %s\n", orig_args->argv[0]);
  133. perror_win32(orig_args->argv[0]);
  134. } else {
  135. WaitForSingleObject(pinfo.hProcess, INFINITE);
  136. GetExitCodeProcess(pinfo.hProcess, &exitcode);
  137. CloseHandle(pinfo.hProcess);
  138. CloseHandle(pinfo.hThread);
  139. }
  140. free(args);
  141. exit(exitcode);
  142. }
  143. #endif
  144. }
  145. /* return a string to be used to distinguish temporary files
  146. this also tries to cope with NFS by adding the local hostname
  147. */
  148. static const char *tmp_string(void)
  149. {
  150. static char *ret;
  151. if (!ret) {
  152. char hostname[200];
  153. strcpy(hostname, "unknown");
  154. #if HAVE_GETHOSTNAME
  155. gethostname(hostname, sizeof(hostname)-1);
  156. #endif
  157. hostname[sizeof(hostname)-1] = 0;
  158. if (asprintf(&ret, "%s.%u", hostname, (unsigned)getpid()) == -1) {
  159. fatal("could not allocate tmp_string");
  160. }
  161. }
  162. return ret;
  163. }
  164. /* update cached file sizes and count helper function for to_cache() */
  165. static void to_cache_stats_helper(struct stat *pstat, char *cached_filename, char *tmp_outfiles, int *files_size, int *cached_files_count)
  166. {
  167. #if ENABLE_ZLIB
  168. /* do an extra stat on the cache file for the size statistics */
  169. if (stat(cached_filename, pstat) != 0) {
  170. cc_log("failed to stat cache files - %s\n", strerror(errno));
  171. stats_update(STATS_ERROR);
  172. if (tmp_outfiles) {
  173. unlink(tmp_outfiles);
  174. }
  175. failed();
  176. }
  177. #else
  178. (void)cached_filename;
  179. (void)tmp_outfiles;
  180. #endif
  181. (*files_size) += file_size(pstat);
  182. (*cached_files_count)++;
  183. }
  184. /* run the real compiler and put the result in cache */
  185. static void to_cache(ARGS *args)
  186. {
  187. char *path_stderr;
  188. char *tmp_stdout, *tmp_stderr, *tmp_outfiles;
  189. struct stat st1;
  190. int status;
  191. int cached_files_count = 0;
  192. int files_size = 0;
  193. x_asprintf(&tmp_stdout, "%s/tmp.stdout.%s", temp_dir, tmp_string());
  194. x_asprintf(&tmp_stderr, "%s/tmp.stderr.%s", temp_dir, tmp_string());
  195. x_asprintf(&tmp_outfiles, "%s/tmp.outfiles.%s", temp_dir, tmp_string());
  196. if (strip_c_option && !swig) {
  197. args_add(stripped_args, "-c");
  198. }
  199. if (output_file) {
  200. args_add(args, "-o");
  201. args_add(args, output_file);
  202. }
  203. /* Turn off DEPENDENCIES_OUTPUT when running cc1, because
  204. * otherwise it will emit a line like
  205. *
  206. * tmp.stdout.vexed.732.o: /home/mbp/.ccache/tmp.stdout.vexed.732.i
  207. *
  208. * unsetenv() is on BSD and Linux but not portable. */
  209. putenv("DEPENDENCIES_OUTPUT");
  210. /* Give SWIG a filename for it to create and populate with a list of files that it generates */
  211. if (swig) {
  212. char *ccache_outfiles;
  213. x_asprintf(&ccache_outfiles, "CCACHE_OUTFILES=%s", tmp_outfiles);
  214. unlink(tmp_outfiles);
  215. if (getenv("CCACHE_OUTFILES") || putenv(ccache_outfiles) == -1) {
  216. cc_log("CCACHE_OUTFILES env variable already set or could not be set\n");
  217. stats_update(STATS_ERROR);
  218. failed();
  219. }
  220. }
  221. if (getenv("CCACHE_CPP2")) {
  222. args_add(args, input_file);
  223. } else {
  224. if (swig) {
  225. args_add(args, "-nopreprocess");
  226. }
  227. args_add(args, i_tmpfile);
  228. }
  229. status = execute(args->argv, tmp_stdout, tmp_stderr);
  230. args_pop(args, 3);
  231. if (stat(tmp_stdout, &st1) != 0 || st1.st_size != 0) {
  232. cc_log("compiler produced stdout for %s\n", input_file);
  233. stats_update(STATS_STDOUT);
  234. unlink(tmp_stdout);
  235. unlink(tmp_stderr);
  236. unlink(tmp_outfiles);
  237. if (!swig) unlink(output_file);
  238. failed();
  239. }
  240. unlink(tmp_stdout);
  241. if (status != 0) {
  242. int fd;
  243. cc_log("compile of %s gave status = %d\n", input_file, status);
  244. stats_update(STATS_STATUS);
  245. fd = open(tmp_stderr, O_RDONLY | O_BINARY);
  246. if (fd != -1) {
  247. if (cpp_stderr) {
  248. /* we might have some stderr from cpp */
  249. int fd2 = open(cpp_stderr, O_RDONLY | O_BINARY);
  250. if (fd2 != -1) {
  251. copy_fd(fd2, 2);
  252. close(fd2);
  253. unlink(cpp_stderr);
  254. cpp_stderr = NULL;
  255. }
  256. }
  257. /* we can use a quick method of
  258. getting the failed output */
  259. copy_fd(fd, 2);
  260. close(fd);
  261. unlink(tmp_stderr);
  262. if (i_tmpfile && !direct_i_file) {
  263. unlink(i_tmpfile);
  264. }
  265. exit(status);
  266. }
  267. unlink(tmp_stderr);
  268. unlink(tmp_outfiles);
  269. if (!swig) unlink(output_file);
  270. failed();
  271. } else {
  272. int hardlink = (getenv("CCACHE_NOCOMPRESS") != 0) && (getenv("CCACHE_HARDLINK") != 0);
  273. if (swig) {
  274. /* read the list of generated files and copy each of them into the cache */
  275. FILE *file;
  276. file = fopen(tmp_outfiles, "r");
  277. if (file) {
  278. char out_filename[FILENAME_MAX + 1];
  279. char out_filename_cache[FILENAME_MAX + 1];
  280. while (fgets(out_filename, FILENAME_MAX, file)) {
  281. char *linefeed = strchr(out_filename, '\n');
  282. if (linefeed) {
  283. char *potential_cr = linefeed - 1;
  284. if (potential_cr >= out_filename && *potential_cr == '\r')
  285. *potential_cr = 0;
  286. *linefeed = 0;
  287. if (cached_files_count == 0) {
  288. strcpy(out_filename_cache, hashname);
  289. } else {
  290. sprintf(out_filename_cache, "%s.%d", hashname, cached_files_count);
  291. }
  292. if (commit_to_cache(out_filename, out_filename_cache, hardlink) != 0) {
  293. fclose(file);
  294. unlink(tmp_outfiles);
  295. failed();
  296. }
  297. to_cache_stats_helper(&st1, out_filename_cache, tmp_outfiles, &files_size, &cached_files_count);
  298. } else {
  299. cached_files_count = 0;
  300. break;
  301. }
  302. }
  303. fclose(file);
  304. if (cached_files_count == 0) {
  305. cc_log("failed to copy output files to cache - internal error\n");
  306. stats_update(STATS_ERROR);
  307. unlink(tmp_outfiles);
  308. failed();
  309. }
  310. /* also copy the (uncompressed) file containing the list of generated files into the cache */
  311. sprintf(out_filename_cache, "%s.outfiles", hashname);
  312. if (stat(tmp_outfiles, &st1) != 0 ||
  313. safe_rename(tmp_outfiles, out_filename_cache) != 0) {
  314. cc_log("failed to copy outfiles file to cache - %s\n", strerror(errno));
  315. stats_update(STATS_ERROR);
  316. unlink(tmp_outfiles);
  317. failed();
  318. }
  319. to_cache_stats_helper(&st1, out_filename_cache, tmp_outfiles, &files_size, &cached_files_count);
  320. unlink(tmp_outfiles);
  321. } else {
  322. cc_log("failed to open temp outfiles file - %s\n", strerror(errno));
  323. stats_update(STATS_ERROR);
  324. failed();
  325. }
  326. } else {
  327. if (commit_to_cache(output_file, hashname, hardlink) != 0) {
  328. failed();
  329. }
  330. to_cache_stats_helper(&st1, hashname, 0, &files_size, &cached_files_count);
  331. }
  332. }
  333. x_asprintf(&path_stderr, "%s.stderr", hashname);
  334. if (stat(tmp_stderr, &st1) != 0 ||
  335. move_file(tmp_stderr, path_stderr) != 0) {
  336. cc_log("failed to rename tmp files - %s\n", strerror(errno));
  337. stats_update(STATS_ERROR);
  338. failed();
  339. }
  340. to_cache_stats_helper(&st1, path_stderr, 0, &files_size, &cached_files_count);
  341. cc_log("Placed %d files for %s into cache\n", cached_files_count, input_file);
  342. stats_tocache(files_size, cached_files_count);
  343. free(tmp_stderr);
  344. free(tmp_stdout);
  345. free(tmp_outfiles);
  346. free(path_stderr);
  347. }
  348. /* find the hash for a command. The hash includes all argument lists,
  349. plus the output from running the compiler with -E */
  350. static void find_hash(ARGS *args)
  351. {
  352. int i;
  353. char *path_stdout, *path_stderr;
  354. char *hash_dir;
  355. char *s;
  356. struct stat st;
  357. int status;
  358. int nlevels = 2;
  359. char *input_base;
  360. char *tmp;
  361. if ((s = getenv("CCACHE_NLEVELS"))) {
  362. nlevels = atoi(s);
  363. if (nlevels < 1) nlevels = 1;
  364. if (nlevels > 8) nlevels = 8;
  365. }
  366. hash_start();
  367. /* when we are doing the unifying tricks we need to include
  368. the input file name in the hash to get the warnings right */
  369. if (enable_unify || swig) {
  370. hash_string(input_file);
  371. }
  372. if (swig) {
  373. if (output_file) {
  374. hash_string(output_file);
  375. }
  376. } else {
  377. /* we have to hash the extension, as a .i file isn't treated the same
  378. by the compiler as a .ii file */
  379. hash_string(i_extension);
  380. }
  381. /* first the arguments */
  382. for (i=1;i<args->argc;i++) {
  383. /* some arguments don't contribute to the hash. The
  384. theory is that these arguments will change the
  385. output of -E if they are going to have any effect
  386. at all, or they only affect linking */
  387. if (i < args->argc-1) {
  388. if (strcmp(args->argv[i], "-I") == 0 ||
  389. strcmp(args->argv[i], "-include") == 0 ||
  390. strcmp(args->argv[i], "-L") == 0 ||
  391. strcmp(args->argv[i], "-D") == 0 ||
  392. strcmp(args->argv[i], "-idirafter") == 0 ||
  393. strcmp(args->argv[i], "-isystem") == 0) {
  394. i++;
  395. continue;
  396. }
  397. }
  398. if (strncmp(args->argv[i], "-I", 2) == 0 ||
  399. strncmp(args->argv[i], "-L", 2) == 0 ||
  400. strncmp(args->argv[i], "-D", 2) == 0 ||
  401. strncmp(args->argv[i], "-idirafter", 10) == 0 ||
  402. strncmp(args->argv[i], "-isystem", 8) == 0) {
  403. continue;
  404. }
  405. if (strncmp(args->argv[i], "--specs=", 8) == 0 &&
  406. stat(args->argv[i]+8, &st) == 0) {
  407. /* if given a explicit specs file, then hash that file, but
  408. don't include the path to it in the hash */
  409. hash_file(args->argv[i]+8);
  410. continue;
  411. }
  412. /* all other arguments are included in the hash */
  413. hash_string(args->argv[i]);
  414. }
  415. /* the compiler driver size and date. This is a simple minded way
  416. to try and detect compiler upgrades. It is not 100% reliable */
  417. if (stat(args->argv[0], &st) != 0) {
  418. cc_log("Couldn't stat the compiler!? (argv[0]='%s')\n", args->argv[0]);
  419. stats_update(STATS_COMPILER);
  420. failed();
  421. }
  422. /* also include the hash of the compiler name - as some compilers
  423. use hard links and behave differently depending on the real name */
  424. if (st.st_nlink > 1) {
  425. hash_string(str_basename(args->argv[0]));
  426. }
  427. hash_int(st.st_size);
  428. hash_int(st.st_mtime);
  429. /* possibly hash the current working directory */
  430. if (getenv("CCACHE_HASHDIR")) {
  431. char *cwd = gnu_getcwd();
  432. if (cwd) {
  433. hash_string(cwd);
  434. free(cwd);
  435. }
  436. }
  437. /* ~/hello.c -> tmp.hello.123.i
  438. limit the basename to 10
  439. characters in order to cope with filesystem with small
  440. maximum filename length limits */
  441. input_base = str_basename(input_file);
  442. tmp = strchr(input_base, '.');
  443. if (tmp != NULL) {
  444. *tmp = 0;
  445. }
  446. if (strlen(input_base) > 10) {
  447. input_base[10] = 0;
  448. }
  449. /* now the run */
  450. x_asprintf(&path_stdout, "%s/%s.tmp.%s.%s", temp_dir,
  451. input_base, tmp_string(),
  452. i_extension);
  453. x_asprintf(&path_stderr, "%s/tmp.cpp_stderr.%s", temp_dir, tmp_string());
  454. if (!direct_i_file) {
  455. /* run cpp on the input file to obtain the .i */
  456. args_add(args, "-E");
  457. args_add(args, input_file);
  458. status = execute(args->argv, path_stdout, path_stderr);
  459. args_pop(args, 2);
  460. } else {
  461. /* we are compiling a .i or .ii file - that means we
  462. can skip the cpp stage and directly form the
  463. correct i_tmpfile */
  464. path_stdout = x_strdup(input_file);
  465. if (create_empty_file(path_stderr) != 0) {
  466. cc_log("failed to create empty stderr file\n");
  467. stats_update(STATS_ERROR);
  468. failed();
  469. }
  470. status = 0;
  471. }
  472. if (status != 0) {
  473. if (!direct_i_file) {
  474. unlink(path_stdout);
  475. }
  476. unlink(path_stderr);
  477. cc_log("the preprocessor gave %d\n", status);
  478. stats_update(STATS_PREPROCESSOR);
  479. failed();
  480. }
  481. /* if the compilation is with -g then we have to include the whole of the
  482. preprocessor output, which means we are sensitive to line number
  483. information. Otherwise we can discard line number info, which makes
  484. us less sensitive to reformatting changes
  485. Note! I have now disabled the unification code by default
  486. as it gives the wrong line numbers for warnings. Pity.
  487. */
  488. if (!enable_unify) {
  489. hash_file(path_stdout);
  490. } else {
  491. if (unify_hash(path_stdout) != 0) {
  492. stats_update(STATS_ERROR);
  493. failed();
  494. }
  495. }
  496. hash_file(path_stderr);
  497. i_tmpfile = path_stdout;
  498. if (!getenv("CCACHE_CPP2")) {
  499. /* if we are using the CPP trick then we need to remember this stderr
  500. data and output it just before the main stderr from the compiler
  501. pass */
  502. cpp_stderr = path_stderr;
  503. } else {
  504. unlink(path_stderr);
  505. free(path_stderr);
  506. }
  507. /* we use a N level subdir for the cache path to reduce the impact
  508. on filesystems which are slow for large directories
  509. */
  510. s = hash_result();
  511. x_asprintf(&hash_dir, "%s/%c", cache_dir, s[0]);
  512. x_asprintf(&stats_file, "%s/stats", hash_dir);
  513. for (i=1; i<nlevels; i++) {
  514. char *p;
  515. if (create_dir(hash_dir) != 0) {
  516. cc_log("failed to create %s\n", hash_dir);
  517. stats_update(STATS_ERROR);
  518. failed();
  519. }
  520. x_asprintf(&p, "%s/%c", hash_dir, s[i]);
  521. free(hash_dir);
  522. hash_dir = p;
  523. }
  524. if (create_dir(hash_dir) != 0) {
  525. cc_log("failed to create %s\n", hash_dir);
  526. stats_update(STATS_ERROR);
  527. failed();
  528. }
  529. x_asprintf(&hashname, "%s/%s", hash_dir, s+nlevels);
  530. free(hash_dir);
  531. }
  532. /*
  533. try to return the compile result from cache. If we can return from
  534. cache then this function exits with the correct status code,
  535. otherwise it returns */
  536. static void from_cache(int first)
  537. {
  538. int fd_stderr, fd_cpp_stderr;
  539. char *stderr_file;
  540. struct stat st;
  541. x_asprintf(&stderr_file, "%s.stderr", hashname);
  542. fd_stderr = open(stderr_file, O_RDONLY | O_BINARY);
  543. if (fd_stderr == -1) {
  544. /* it isn't in cache ... */
  545. free(stderr_file);
  546. return;
  547. }
  548. /* make sure the output is there too */
  549. if (stat(hashname, &st) != 0) {
  550. close(fd_stderr);
  551. unlink(stderr_file);
  552. free(stderr_file);
  553. return;
  554. }
  555. /* the user might be disabling cache hits */
  556. #ifndef ENABLE_ZLIB
  557. /* if the cache file is compressed we must recache */
  558. if ((first && getenv("CCACHE_RECACHE")) ||
  559. test_if_compressed(hashname) == 1)
  560. #else
  561. if (first && getenv("CCACHE_RECACHE"))
  562. #endif
  563. {
  564. close(fd_stderr);
  565. unlink(stderr_file);
  566. free(stderr_file);
  567. return;
  568. }
  569. if (first) {
  570. int hardlink;
  571. int passfail = -1;
  572. /* update timestamps for LRU cleanup
  573. also gives output_file a sensible mtime when hard-linking (for make) */
  574. x_utimes(stderr_file);
  575. hardlink = (getenv("CCACHE_HARDLINK") != 0);
  576. if (swig) {
  577. /* read the list of generated files and copy each of them out of the cache */
  578. FILE *file;
  579. char *outfiles;
  580. x_asprintf(&outfiles, "%s.outfiles", hashname);
  581. file = fopen(outfiles, "r");
  582. if (file) {
  583. char out_filename[FILENAME_MAX + 1];
  584. char out_filename_cache[FILENAME_MAX + 1];
  585. int retrieved_files_count = 0;
  586. x_utimes(outfiles);
  587. while (fgets(out_filename, FILENAME_MAX, file)) {
  588. char *linefeed = strchr(out_filename, '\n');
  589. if (linefeed) {
  590. char *potential_cr = linefeed - 1;
  591. if (potential_cr >= out_filename && *potential_cr == '\r')
  592. *potential_cr = 0;
  593. *linefeed = 0;
  594. if (retrieved_files_count == 0) {
  595. strcpy(out_filename_cache, hashname);
  596. } else {
  597. sprintf(out_filename_cache, "%s.%d", hashname, retrieved_files_count);
  598. }
  599. passfail = retrieve_from_cache(out_filename_cache, out_filename, hardlink);
  600. if (passfail == -1) {
  601. break;
  602. }
  603. retrieved_files_count++;
  604. } else {
  605. cc_log("failed to copy output files from cache - internal error\n");
  606. stats_update(STATS_ERROR);
  607. passfail = -1;
  608. break;
  609. }
  610. }
  611. if (retrieved_files_count == 0) {
  612. cc_log("failed to copy output files from cache - internal error\n");
  613. stats_update(STATS_ERROR);
  614. passfail = -1;
  615. }
  616. fclose(file);
  617. } else {
  618. cc_log("failed to open cached outfiles file - %s\n", strerror(errno));
  619. stats_update(STATS_ERROR);
  620. }
  621. } else {
  622. passfail = retrieve_from_cache(hashname, output_file, hardlink);
  623. }
  624. free(stderr_file);
  625. if (passfail == -1) {
  626. close(fd_stderr);
  627. unlink(stderr_file);
  628. return;
  629. }
  630. }
  631. /* get rid of the intermediate preprocessor file */
  632. if (i_tmpfile) {
  633. if (!direct_i_file) {
  634. unlink(i_tmpfile);
  635. }
  636. free(i_tmpfile);
  637. i_tmpfile = NULL;
  638. }
  639. /* send the cpp stderr, if applicable */
  640. fd_cpp_stderr = open(cpp_stderr, O_RDONLY | O_BINARY);
  641. if (fd_cpp_stderr != -1) {
  642. copy_fd(fd_cpp_stderr, 2);
  643. close(fd_cpp_stderr);
  644. unlink(cpp_stderr);
  645. free(cpp_stderr);
  646. cpp_stderr = NULL;
  647. }
  648. /* send the stderr */
  649. copy_fd(fd_stderr, 2);
  650. close(fd_stderr);
  651. /* and exit with the right status code */
  652. if (first) {
  653. cc_log("got cached result for %s\n", input_file);
  654. stats_update(STATS_CACHED);
  655. }
  656. exit(0);
  657. }
  658. /* find the real compiler. We just search the PATH to find a executable of the
  659. same name that isn't a link to ourselves */
  660. static void find_compiler(int argc, char **argv)
  661. {
  662. char *base;
  663. char *path;
  664. orig_args = args_init(argc, argv);
  665. base = str_basename(argv[0]);
  666. /* we might be being invoked like "ccache gcc -c foo.c" */
  667. if (strcmp(base, MYNAME) == 0) {
  668. args_remove_first(orig_args);
  669. free(base);
  670. if (strchr(argv[1],'/')
  671. #ifdef _WIN32
  672. || strchr(argv[1],'\\')
  673. #endif
  674. ) {
  675. /* a full path was given */
  676. return;
  677. }
  678. base = str_basename(argv[1]);
  679. }
  680. /* support user override of the compiler */
  681. if ((path=getenv("CCACHE_CC"))) {
  682. base = x_strdup(path);
  683. }
  684. orig_args->argv[0] = find_executable(base, MYNAME);
  685. /* can't find the compiler! */
  686. if (!orig_args->argv[0]) {
  687. stats_update(STATS_COMPILER);
  688. cc_log("could not find compiler (%s)\n", base);
  689. perror(base);
  690. exit(1);
  691. }
  692. }
  693. /* check a filename for C/C++ extension. Return the pre-processor
  694. extension */
  695. static const char *check_extension(const char *fname, int *direct_i)
  696. {
  697. int i;
  698. const char *p;
  699. if (direct_i) {
  700. *direct_i = 0;
  701. }
  702. if (swig) return "ii"; /* any file extension is acceptable as input for SWIG */
  703. p = strrchr(fname, '.');
  704. if (!p) return NULL;
  705. p++;
  706. for (i=0; extensions[i].extension; i++) {
  707. if (strcmp(p, extensions[i].extension) == 0) {
  708. if (direct_i && strcmp(p, extensions[i].i_extension) == 0) {
  709. *direct_i = 1;
  710. }
  711. p = getenv("CCACHE_EXTENSION");
  712. if (p) return p;
  713. return extensions[i].i_extension;
  714. }
  715. }
  716. return NULL;
  717. }
  718. /*
  719. process the compiler options to form the correct set of options
  720. for obtaining the preprocessor output
  721. */
  722. static void process_args(int argc, char **argv)
  723. {
  724. int i;
  725. int found_c_opt = 0;
  726. int found_S_opt = 0;
  727. struct stat st;
  728. char *e;
  729. /* is gcc being asked to output dependencies? */
  730. int generating_dependencies = 0;
  731. /* is the dependency makefile name overridden with -MF? */
  732. int dependency_filename_specified = 0;
  733. /* is the dependency makefile target name specified with -MQ or -MF? */
  734. int dependency_target_specified = 0;
  735. stripped_args = args_init(0, NULL);
  736. args_add(stripped_args, argv[0]);
  737. /* -c not required for SWIG */
  738. if (swig) {
  739. found_c_opt = 1;
  740. }
  741. for (i=1; i<argc; i++) {
  742. /* some options will never work ... */
  743. if (strcmp(argv[i], "-E") == 0) {
  744. failed();
  745. }
  746. /* these are too hard */
  747. if (strcmp(argv[i], "-fbranch-probabilities")==0 ||
  748. strcmp(argv[i], "-fprofile-arcs") == 0 ||
  749. strcmp(argv[i], "-ftest-coverage") == 0 ||
  750. strcmp(argv[i], "--coverage") == 0 ||
  751. strcmp(argv[i], "-M") == 0 ||
  752. strcmp(argv[i], "-MM") == 0 ||
  753. strcmp(argv[i], "-x") == 0) {
  754. cc_log("argument %s is unsupported\n", argv[i]);
  755. stats_update(STATS_UNSUPPORTED);
  756. failed();
  757. continue;
  758. }
  759. /* we must have -c */
  760. if (strcmp(argv[i], "-c") == 0) {
  761. if (!strip_c_option) {
  762. args_add(stripped_args, argv[i]);
  763. }
  764. found_c_opt = 1;
  765. continue;
  766. }
  767. /* -S changes the default extension */
  768. if (strcmp(argv[i], "-S") == 0) {
  769. args_add(stripped_args, argv[i]);
  770. found_S_opt = 1;
  771. continue;
  772. }
  773. /* we need to work out where the output was meant to go */
  774. if (strcmp(argv[i], "-o") == 0) {
  775. if (i == argc-1) {
  776. cc_log("missing argument to %s\n", argv[i]);
  777. stats_update(STATS_ARGS);
  778. failed();
  779. }
  780. output_file = argv[i+1];
  781. i++;
  782. continue;
  783. }
  784. /* alternate form of -o, with no space */
  785. if (!swig) { /* some of SWIG's arguments begin with -o */
  786. if (strncmp(argv[i], "-o", 2) == 0) {
  787. output_file = &argv[i][2];
  788. continue;
  789. }
  790. }
  791. /* debugging is handled specially, so that we know if we
  792. can strip line number info
  793. */
  794. if (strncmp(argv[i], "-g", 2) == 0) {
  795. args_add(stripped_args, argv[i]);
  796. if (strcmp(argv[i], "-g0") != 0) {
  797. enable_unify = 0;
  798. }
  799. continue;
  800. }
  801. /* The user knows best: just swallow the next arg */
  802. if (strcmp(argv[i], "--ccache-skip") == 0) {
  803. i++;
  804. if (i == argc) {
  805. failed();
  806. }
  807. args_add(stripped_args, argv[i]);
  808. continue;
  809. }
  810. /* These options require special handling, because they
  811. behave differently with gcc -E, when the output
  812. file is not specified. */
  813. if (strcmp(argv[i], "-MD") == 0 || strcmp(argv[i], "-MMD") == 0) {
  814. generating_dependencies = 1;
  815. } else if (strcmp(argv[i], "-MF") == 0) {
  816. dependency_filename_specified = 1;
  817. } else if (strcmp(argv[i], "-MQ") == 0 || strcmp(argv[i], "-MT") == 0) {
  818. dependency_target_specified = 1;
  819. }
  820. /* the input file is already preprocessed */
  821. if (swig && strcmp(argv[i], "-nopreprocess") == 0) {
  822. direct_i_file = 1;
  823. continue;
  824. }
  825. /* options that take an argument */
  826. {
  827. const char *opts[] = {"-I", "-include", "-imacros", "-iprefix",
  828. "-iwithprefix", "-iwithprefixbefore",
  829. "-L", "-D", "-U", "-x", "-MF",
  830. "-MT", "-MQ", "-isystem", "-aux-info",
  831. "--param", "-A", "-Xlinker", "-u",
  832. "-idirafter",
  833. NULL};
  834. int j;
  835. for (j=0;opts[j];j++) {
  836. if (strcmp(argv[i], opts[j]) == 0) {
  837. if (i == argc-1) {
  838. cc_log("missing argument to %s\n",
  839. argv[i]);
  840. stats_update(STATS_ARGS);
  841. failed();
  842. }
  843. args_add(stripped_args, argv[i]);
  844. args_add(stripped_args, argv[i+1]);
  845. i++;
  846. break;
  847. }
  848. }
  849. if (opts[j]) continue;
  850. }
  851. /* other options */
  852. if (argv[i][0] == '-') {
  853. args_add(stripped_args, argv[i]);
  854. continue;
  855. }
  856. /* if an argument isn't a plain file then assume its
  857. an option, not an input file. This allows us to
  858. cope better with unusual compiler options */
  859. if (stat(argv[i], &st) != 0 || !S_ISREG(st.st_mode)) {
  860. args_add(stripped_args, argv[i]);
  861. continue;
  862. }
  863. if (input_file) {
  864. if (check_extension(argv[i], NULL)) {
  865. cc_log("multiple input files (%s and %s)\n",
  866. input_file, argv[i]);
  867. stats_update(STATS_MULTIPLE);
  868. } else if (!found_c_opt) {
  869. cc_log("called for link with %s\n", argv[i]);
  870. if (strstr(argv[i], "conftest.")) {
  871. stats_update(STATS_CONFTEST);
  872. } else {
  873. stats_update(STATS_LINK);
  874. }
  875. } else {
  876. cc_log("non C/C++ file %s\n", argv[i]);
  877. stats_update(STATS_NOTC);
  878. }
  879. failed();
  880. }
  881. input_file = argv[i];
  882. }
  883. if (!input_file) {
  884. cc_log("No input file found\n");
  885. stats_update(STATS_NOINPUT);
  886. failed();
  887. }
  888. if (swig) {
  889. i_extension = check_extension(input_file, NULL);
  890. } else {
  891. i_extension = check_extension(input_file, &direct_i_file);
  892. }
  893. if (i_extension == NULL) {
  894. cc_log("Not a C/C++ file - %s\n", input_file);
  895. stats_update(STATS_NOTC);
  896. failed();
  897. }
  898. if (!found_c_opt) {
  899. cc_log("No -c option found for %s\n", input_file);
  900. /* I find that having a separate statistic for autoconf tests is useful,
  901. as they are the dominant form of "called for link" in many cases */
  902. if (strstr(input_file, "conftest.")) {
  903. stats_update(STATS_CONFTEST);
  904. } else {
  905. stats_update(STATS_LINK);
  906. }
  907. failed();
  908. }
  909. /* don't try to second guess the compilers heuristics for stdout handling */
  910. if (output_file && strcmp(output_file, "-") == 0) {
  911. stats_update(STATS_OUTSTDOUT);
  912. failed();
  913. }
  914. if (!swig && !output_file) {
  915. char *p;
  916. output_file = x_strdup(input_file);
  917. if ((p = strrchr(output_file, '/'))) {
  918. output_file = p+1;
  919. }
  920. p = strrchr(output_file, '.');
  921. if (!p || !p[1]) {
  922. cc_log("badly formed output_file %s\n", output_file);
  923. stats_update(STATS_ARGS);
  924. failed();
  925. }
  926. p[1] = found_S_opt ? 's' : 'o';
  927. p[2] = 0;
  928. }
  929. /* If dependencies are generated, configure the preprocessor */
  930. if (generating_dependencies && output_file) {
  931. if (!dependency_filename_specified) {
  932. char *default_depfile_name = x_strdup(output_file);
  933. char *p = strrchr(default_depfile_name, '.');
  934. if (p) {
  935. if (strlen(p) < 2) {
  936. cc_log("badly formed dependency file %s\n", output_file);
  937. stats_update(STATS_ARGS);
  938. failed();
  939. return;
  940. }
  941. *p = 0;
  942. }
  943. else {
  944. int len = p - default_depfile_name;
  945. p = x_malloc(len + 3);
  946. strncpy(default_depfile_name, p, len - 1);
  947. free(default_depfile_name);
  948. default_depfile_name = p;
  949. }
  950. strcat(default_depfile_name, ".d");
  951. args_add(stripped_args, "-MF");
  952. args_add(stripped_args, default_depfile_name);
  953. }
  954. if (!dependency_target_specified) {
  955. args_add(stripped_args, "-MT");
  956. args_add(stripped_args, output_file);
  957. }
  958. }
  959. /* cope with -o /dev/null */
  960. if (output_file && strcmp(output_file,"/dev/null") != 0 && stat(output_file, &st) == 0 && !S_ISREG(st.st_mode)) {
  961. cc_log("Not a regular file %s\n", output_file);
  962. stats_update(STATS_DEVICE);
  963. failed();
  964. }
  965. if ((e=getenv("CCACHE_PREFIX"))) {
  966. char *p = find_executable(e, MYNAME);
  967. if (!p) {
  968. cc_log("could not find executable (%s)\n", e);
  969. stats_update(STATS_ENVIRONMMENT);
  970. perror(e);
  971. exit(1);
  972. }
  973. args_add_prefix(stripped_args, p);
  974. }
  975. }
  976. static void detect_swig()
  977. {
  978. char *basename = str_basename(orig_args->argv[0]);
  979. if (strstr(basename, "swig") || getenv("CCACHE_SWIG")) {
  980. swig = 1;
  981. }
  982. free(basename);
  983. }
  984. /* the main ccache driver function */
  985. static void ccache(int argc, char *argv[])
  986. {
  987. /* find the real compiler */
  988. find_compiler(argc, argv);
  989. /* use the real compiler if HOME is not set */
  990. if (!cache_dir) {
  991. cc_log("Unable to determine home directory\n");
  992. cc_log("ccache is disabled\n");
  993. failed();
  994. }
  995. /* we might be disabled */
  996. if (getenv("CCACHE_DISABLE")) {
  997. cc_log("ccache is disabled\n");
  998. failed();
  999. }
  1000. if (getenv("CCACHE_STRIPC")) {
  1001. strip_c_option = 1;
  1002. }
  1003. if (getenv("CCACHE_UNIFY")) {
  1004. enable_unify = 1;
  1005. }
  1006. detect_swig();
  1007. /* process argument list, returning a new set of arguments for pre-processing */
  1008. process_args(orig_args->argc, orig_args->argv);
  1009. /* run with -E to find the hash */
  1010. find_hash(stripped_args);
  1011. /* if we can return from cache at this point then do */
  1012. from_cache(1);
  1013. if (getenv("CCACHE_READONLY")) {
  1014. cc_log("read-only set - doing real compile\n");
  1015. failed();
  1016. }
  1017. /* run real compiler, sending output to cache */
  1018. to_cache(stripped_args);
  1019. /* return from cache */
  1020. from_cache(0);
  1021. /* oh oh! */
  1022. cc_log("secondary from_cache failed!\n");
  1023. stats_update(STATS_ERROR);
  1024. failed();
  1025. }
  1026. static void usage(void)
  1027. {
  1028. printf("%s, a compiler cache including support for SWIG. Version %s\n", MYNAME, CCACHE_VERSION);
  1029. printf("Copyright Andrew Tridgell, 2002\n\n");
  1030. printf("Usage:\n");
  1031. printf("\t" MYNAME " [options]\n");
  1032. printf("\t" MYNAME " compiler [compile options]\n");
  1033. printf("\tcompiler [compile options] (via symbolic link)\n");
  1034. printf("\nOptions:\n");
  1035. printf("-s show statistics summary\n");
  1036. printf("-z zero statistics\n");
  1037. printf("-c run a cache cleanup\n");
  1038. printf("-C clear the cache completely\n");
  1039. printf("-F <maxfiles> set maximum files in cache\n");
  1040. printf("-M <maxsize> set maximum size of cache (use G, M or K)\n");
  1041. printf("-h this help page\n");
  1042. printf("-V print version number\n");
  1043. }
  1044. static void check_cache_dir(void)
  1045. {
  1046. if (!cache_dir) {
  1047. fatal("Unable to determine home directory");
  1048. }
  1049. }
  1050. /* the main program when not doing a compile */
  1051. static int ccache_main(int argc, char *argv[])
  1052. {
  1053. int c;
  1054. size_t v;
  1055. while ((c = getopt(argc, argv, "hszcCF:M:V")) != -1) {
  1056. switch (c) {
  1057. case 'V':
  1058. printf("%s version %s\n", MYNAME, CCACHE_VERSION);
  1059. printf("Copyright Andrew Tridgell 2002\n");
  1060. printf("Released under the GNU GPL v2 or later\n");
  1061. exit(0);
  1062. case 'h':
  1063. usage();
  1064. exit(0);
  1065. case 's':
  1066. check_cache_dir();
  1067. stats_summary();
  1068. break;
  1069. case 'c':
  1070. check_cache_dir();
  1071. cleanup_all(cache_dir);
  1072. printf("Cleaned cache\n");
  1073. break;
  1074. case 'C':
  1075. check_cache_dir();
  1076. wipe_all(cache_dir);
  1077. printf("Cleared cache\n");
  1078. break;
  1079. case 'z':
  1080. check_cache_dir();
  1081. stats_zero();
  1082. printf("Statistics cleared\n");
  1083. break;
  1084. case 'F':
  1085. check_cache_dir();
  1086. v = atoi(optarg);
  1087. if (stats_set_limits(v, -1) == 0) {
  1088. printf("Set cache file limit to %u\n", (unsigned)v);
  1089. } else {
  1090. printf("Could not set cache file limit.\n");
  1091. exit(1);
  1092. }
  1093. break;
  1094. case 'M':
  1095. check_cache_dir();
  1096. v = value_units(optarg);
  1097. if (stats_set_limits(-1, v) == 0) {
  1098. printf("Set cache size limit to %uk\n", (unsigned)v);
  1099. } else {
  1100. printf("Could not set cache size limit.\n");
  1101. exit(1);
  1102. }
  1103. break;
  1104. default:
  1105. usage();
  1106. exit(1);
  1107. }
  1108. }
  1109. return 0;
  1110. }
  1111. /* Make a copy of stderr that will not be cached, so things like
  1112. distcc can send networking errors to it. */
  1113. static void setup_uncached_err(void)
  1114. {
  1115. char *buf;
  1116. int uncached_fd;
  1117. uncached_fd = dup(2);
  1118. if (uncached_fd == -1) {
  1119. cc_log("dup(2) failed\n");
  1120. stats_update(STATS_ERROR);
  1121. failed();
  1122. }
  1123. /* leak a pointer to the environment */
  1124. x_asprintf(&buf, "UNCACHED_ERR_FD=%d", uncached_fd);
  1125. if (putenv(buf) == -1) {
  1126. cc_log("putenv failed\n");
  1127. stats_update(STATS_ERROR);
  1128. failed();
  1129. }
  1130. }
  1131. int main(int argc, char *argv[])
  1132. {
  1133. char *p;
  1134. cache_dir = getenv("CCACHE_DIR");
  1135. if (!cache_dir) {
  1136. const char *home_directory = get_home_directory();
  1137. if (home_directory) {
  1138. x_asprintf(&cache_dir, "%s/.ccache", home_directory);
  1139. }
  1140. }
  1141. cache_logfile = getenv("CCACHE_LOGFILE");
  1142. if (getenv("CCACHE_VERBOSE")) {
  1143. ccache_verbose = 1;
  1144. }
  1145. setup_uncached_err();
  1146. /* the user might have set CCACHE_UMASK */
  1147. p = getenv("CCACHE_UMASK");
  1148. if (p) {
  1149. mode_t mask;
  1150. errno = 0;
  1151. mask = strtol(p, NULL, 8);
  1152. if (errno == 0) {
  1153. umask(mask);
  1154. }
  1155. }
  1156. /* check if we are being invoked as "ccache" */
  1157. if (strlen(argv[0]) >= strlen(MYNAME) &&
  1158. strcmp(argv[0] + strlen(argv[0]) - strlen(MYNAME), MYNAME) == 0) {
  1159. if (argc < 2) {
  1160. usage();
  1161. exit(1);
  1162. }
  1163. /* if the first argument isn't an option, then assume we are
  1164. being passed a compiler name and options */
  1165. if (argv[1][0] == '-') {
  1166. return ccache_main(argc, argv);
  1167. }
  1168. }
  1169. /* make sure the cache dir exists */
  1170. if (cache_dir && (create_dir(cache_dir) != 0)) {
  1171. fprintf(stderr,"ccache: failed to create %s (%s)\n",
  1172. cache_dir, strerror(errno));
  1173. exit(1);
  1174. }
  1175. temp_dir = getenv("CCACHE_TEMPDIR");
  1176. if (!temp_dir) {
  1177. x_asprintf(&temp_dir, "%s/temp", cache_dir);
  1178. /* make sure temp dir exists if not supplied by user */
  1179. if (temp_dir && create_dir(temp_dir) != 0) {
  1180. fprintf(stderr,"ccache: failed to create %s (%s)\n",
  1181. temp_dir, strerror(errno));
  1182. exit(1);
  1183. }
  1184. }
  1185. if (!getenv("CCACHE_READONLY")) {
  1186. if (create_cachedirtag(cache_dir) != 0) {
  1187. fprintf(stderr,"ccache: failed to create %s/CACHEDIR.TAG (%s)\n",
  1188. cache_dir, strerror(errno));
  1189. exit(1);
  1190. }
  1191. }
  1192. ccache(argc, argv);
  1193. return 1;
  1194. }