f72a9bda2fa35e9793b1a608208be1bdb50ba9af
[platform/upstream/ccache.git] / ccache.c
1 // ccache -- a fast C/C++ compiler cache
2 //
3 // Copyright (C) 2002-2007 Andrew Tridgell
4 // Copyright (C) 2009-2018 Joel Rosdahl
5 //
6 // This program is free software; you can redistribute it and/or modify it
7 // under the terms of the GNU General Public License as published by the Free
8 // Software Foundation; either version 3 of the License, or (at your option)
9 // any later version.
10 //
11 // This program is distributed in the hope that it will be useful, but WITHOUT
12 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 // more details.
15 //
16 // You should have received a copy of the GNU General Public License along with
17 // this program; if not, write to the Free Software Foundation, Inc., 51
18 // Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
20 #include "ccache.h"
21 #include "compopt.h"
22 #ifdef HAVE_GETOPT_LONG
23 #include <getopt.h>
24 #else
25 #include "getopt_long.h"
26 #endif
27 #include "hashtable.h"
28 #include "hashtable_itr.h"
29 #include "hashutil.h"
30 #include "language.h"
31 #include "manifest.h"
32
33 #define STRINGIFY(x) #x
34 #define TO_STRING(x) STRINGIFY(x)
35
36 static const char VERSION_TEXT[] =
37   MYNAME " version %s\n"
38   "\n"
39   "Copyright (C) 2002-2007 Andrew Tridgell\n"
40   "Copyright (C) 2009-2018 Joel Rosdahl\n"
41   "\n"
42   "This program is free software; you can redistribute it and/or modify it under\n"
43   "the terms of the GNU General Public License as published by the Free Software\n"
44   "Foundation; either version 3 of the License, or (at your option) any later\n"
45   "version.\n";
46
47 static const char USAGE_TEXT[] =
48   "Usage:\n"
49   "    " MYNAME " [options]\n"
50   "    " MYNAME " compiler [compiler options]\n"
51   "    compiler [compiler options]          (via symbolic link)\n"
52   "\n"
53   "Options:\n"
54   "    -c, --cleanup         delete old files and recalculate size counters\n"
55   "                          (normally not needed as this is done automatically)\n"
56   "    -C, --clear           clear the cache completely (except configuration)\n"
57   "    -F, --max-files=N     set maximum number of files in cache to N (use 0 for\n"
58   "                          no limit)\n"
59   "    -M, --max-size=SIZE   set maximum size of cache to SIZE (use 0 for no\n"
60   "                          limit); available suffixes: k, M, G, T (decimal) and\n"
61   "                          Ki, Mi, Gi, Ti (binary); default suffix: G\n"
62   "    -o, --set-config=K=V  set configuration key K to value V\n"
63   "    -p, --print-config    print current configuration options\n"
64   "    -s, --show-stats      show statistics summary\n"
65   "    -z, --zero-stats      zero statistics counters\n"
66   "\n"
67   "    -h, --help            print this help text\n"
68   "    -V, --version         print version and copyright information\n"
69   "\n"
70   "See also <https://ccache.samba.org>.\n";
71
72 // Global configuration data.
73 struct conf *conf = NULL;
74
75 // Where to write configuration changes.
76 char *primary_config_path = NULL;
77
78 // Secondary, read-only configuration file (if any).
79 char *secondary_config_path = NULL;
80
81 // Current working directory taken from $PWD, or getcwd() if $PWD is bad.
82 char *current_working_dir = NULL;
83
84 // The original argument list.
85 static struct args *orig_args;
86
87 // The source file.
88 static char *input_file;
89
90 // The output file being compiled to.
91 static char *output_obj;
92
93 // The path to the dependency file (implicit or specified with -MF).
94 static char *output_dep;
95
96 // The path to the coverage file (implicit when using -ftest-coverage).
97 static char *output_cov;
98
99 // Diagnostic generation information (clang). Contains pathname if not NULL.
100 static char *output_dia = NULL;
101
102 // Split dwarf information (GCC 4.8 andup). Contains pathname if not NULL.
103 static char *output_dwo = NULL;
104
105 // Array for storing -arch options.
106 #define MAX_ARCH_ARGS 10
107 static size_t arch_args_size = 0;
108 static char *arch_args[MAX_ARCH_ARGS] = {NULL};
109
110 // Name (represented as a struct file_hash) of the file containing the cached
111 // object code.
112 static struct file_hash *cached_obj_hash;
113
114 // Full path to the file containing the cached object code
115 // (cachedir/a/b/cdef[...]-size.o).
116 static char *cached_obj;
117
118 // Full path to the file containing the standard error output
119 // (cachedir/a/b/cdef[...]-size.stderr).
120 static char *cached_stderr;
121
122 // Full path to the file containing the dependency information
123 // (cachedir/a/b/cdef[...]-size.d).
124 static char *cached_dep;
125
126 // Full path to the file containing the coverage information
127 // (cachedir/a/b/cdef[...]-size.gcno).
128 static char *cached_cov;
129
130 // Full path to the file containing the diagnostic information (for clang)
131 // (cachedir/a/b/cdef[...]-size.dia).
132 static char *cached_dia;
133
134 // Full path to the file containing the split dwarf (for GCC 4.8 and above)
135 // (cachedir/a/b/cdef[...]-size.dwo).
136 //
137 // Contains NULL if -gsplit-dwarf is not given.
138 static char *cached_dwo;
139
140 // using_split_dwarf is true if "-gsplit-dwarf" is given to the compiler (GCC
141 // 4.8 and up).
142 bool using_split_dwarf = false;
143
144 // Full path to the file containing the manifest
145 // (cachedir/a/b/cdef[...]-size.manifest).
146 static char *manifest_path;
147
148 // Time of compilation. Used to see if include files have changed after
149 // compilation.
150 time_t time_of_compilation;
151
152 // Files included by the preprocessor and their hashes/sizes. Key: file path.
153 // Value: struct file_hash.
154 static struct hashtable *included_files = NULL;
155
156 // Uses absolute path for some include files.
157 static bool has_absolute_include_headers = false;
158
159 // List of headers to ignore.
160 static char **ignore_headers;
161
162 // Size of headers to ignore list.
163 static size_t ignore_headers_len;
164
165 // Is the compiler being asked to output debug info?
166 static bool generating_debuginfo;
167
168 // Is the compiler being asked to output dependencies?
169 static bool generating_dependencies;
170
171 // Is the compiler being asked to output coverage?
172 static bool generating_coverage;
173
174 // Relocating debuginfo in the format old=new.
175 static char **debug_prefix_maps = NULL;
176
177 // Size of debug_prefix_maps list.
178 static size_t debug_prefix_maps_len = 0;
179
180 // Is the compiler being asked to output coverage data (.gcda) at runtime?
181 static bool profile_arcs;
182
183 // Name of the custom profile directory (default: object dirname).
184 static char *profile_dir;
185
186 // The name of the temporary preprocessed file.
187 static char *i_tmpfile;
188
189 // Are we compiling a .i or .ii file directly?
190 static bool direct_i_file;
191
192 // The name of the cpp stderr file.
193 static char *cpp_stderr;
194
195 // Full path to the statistics file in the subdirectory where the cached result
196 // belongs (<cache_dir>/<x>/stats).
197 char *stats_file = NULL;
198
199 // Whether the output is a precompiled header.
200 bool output_is_precompiled_header = false;
201
202 // Profile generation / usage information.
203 static char *profile_dir = NULL;
204 static bool profile_use = false;
205 static bool profile_generate = false;
206
207 // Whether we are using a precompiled header (either via -include, #include or
208 // clang's -include-pch or -include-pth).
209 static bool using_precompiled_header = false;
210
211 // The .gch/.pch/.pth file used for compilation.
212 static char *included_pch_file = NULL;
213
214 // How long (in microseconds) to wait before breaking a stale lock.
215 unsigned lock_staleness_limit = 2000000;
216
217 enum fromcache_call_mode {
218         FROMCACHE_DIRECT_MODE,
219         FROMCACHE_CPP_MODE
220 };
221
222 struct pending_tmp_file {
223         char *path;
224         struct pending_tmp_file *next;
225 };
226
227 // Temporary files to remove at program exit.
228 static struct pending_tmp_file *pending_tmp_files = NULL;
229
230 #ifndef _WIN32
231 static sigset_t fatal_signal_set;
232
233 // PID of currently executing compiler that we have started, if any. 0 means no
234 // ongoing compilation.
235 static pid_t compiler_pid = 0;
236 #endif
237
238 // This is a string that identifies the current "version" of the hash sum
239 // computed by ccache. If, for any reason, we want to force the hash sum to be
240 // different for the same input in a new ccache version, we can just change
241 // this string. A typical example would be if the format of one of the files
242 // stored in the cache changes in a backwards-incompatible way.
243 static const char HASH_PREFIX[] = "3";
244
245 static void
246 add_prefix(struct args *args, char *prefix_command)
247 {
248         if (str_eq(prefix_command, "")) {
249                 return;
250         }
251
252         struct args *prefix = args_init(0, NULL);
253         char *e = x_strdup(prefix_command);
254         char *saveptr = NULL;
255         for (char *tok = strtok_r(e, " ", &saveptr);
256              tok;
257              tok = strtok_r(NULL, " ", &saveptr)) {
258                 char *p;
259
260                 p = find_executable(tok, MYNAME);
261                 if (!p) {
262                         fatal("%s: %s", tok, strerror(errno));
263                 }
264
265                 args_add(prefix, p);
266                 free(p);
267         }
268         free(e);
269
270         cc_log("Using command-line prefix %s", prefix_command);
271         for (int i = prefix->argc; i != 0; i--) {
272                 args_add_prefix(args, prefix->argv[i-1]);
273         }
274         args_free(prefix);
275 }
276
277 // Something went badly wrong - just execute the real compiler.
278 static void
279 failed(void)
280 {
281         assert(orig_args);
282
283         args_strip(orig_args, "--ccache-");
284         add_prefix(orig_args, conf->prefix_command);
285
286         cc_log("Failed; falling back to running the real compiler");
287         cc_log_argv("Executing ", orig_args->argv);
288         exitfn_call();
289         execv(orig_args->argv[0], orig_args->argv);
290         fatal("execv of %s failed: %s", orig_args->argv[0], strerror(errno));
291 }
292
293 static const char *
294 temp_dir()
295 {
296         static char *path = NULL;
297         if (path) {
298                 return path; // Memoize
299         }
300         path = conf->temporary_dir;
301         if (str_eq(path, "")) {
302                 path = format("%s/tmp", conf->cache_dir);
303         }
304         return path;
305 }
306
307 void
308 block_signals(void)
309 {
310 #ifndef _WIN32
311         sigprocmask(SIG_BLOCK, &fatal_signal_set, NULL);
312 #endif
313 }
314
315 void
316 unblock_signals(void)
317 {
318 #ifndef _WIN32
319         sigset_t empty;
320         sigemptyset(&empty);
321         sigprocmask(SIG_SETMASK, &empty, NULL);
322 #endif
323 }
324
325 static void
326 add_pending_tmp_file(const char *path)
327 {
328         block_signals();
329         struct pending_tmp_file *e = x_malloc(sizeof(*e));
330         e->path = x_strdup(path);
331         e->next = pending_tmp_files;
332         pending_tmp_files = e;
333         unblock_signals();
334 }
335
336 static void
337 do_clean_up_pending_tmp_files(void)
338 {
339         struct pending_tmp_file *p = pending_tmp_files;
340         while (p) {
341                 // Can't call tmp_unlink here since its cc_log calls aren't signal safe.
342                 unlink(p->path);
343                 p = p->next;
344                 // Leak p->path and p here because clean_up_pending_tmp_files needs to be
345                 // signal safe.
346         }
347 }
348
349 static void
350 clean_up_pending_tmp_files(void)
351 {
352         block_signals();
353         do_clean_up_pending_tmp_files();
354         unblock_signals();
355 }
356
357 #ifndef _WIN32
358 static void
359 signal_handler(int signum)
360 {
361         // Unregister handler for this signal so that we can send the signal to
362         // ourselves at the end of the handler.
363         signal(signum, SIG_DFL);
364
365         // If ccache was killed explicitly, then bring the compiler subprocess (if
366         // any) with us as well.
367         if (signum == SIGTERM
368             && compiler_pid != 0
369             && waitpid(compiler_pid, NULL, WNOHANG) == 0) {
370                 kill(compiler_pid, signum);
371         }
372
373         do_clean_up_pending_tmp_files();
374
375         if (compiler_pid != 0) {
376                 // Wait for compiler subprocess to exit before we snuff it.
377                 waitpid(compiler_pid, NULL, 0);
378         }
379
380         // Resend signal to ourselves to exit properly after returning from the
381         // handler.
382         kill(getpid(), signum);
383 }
384
385 static void
386 register_signal_handler(int signum)
387 {
388         struct sigaction act;
389         memset(&act, 0, sizeof(act));
390         act.sa_handler = signal_handler;
391         act.sa_mask = fatal_signal_set;
392 #ifdef SA_RESTART
393         act.sa_flags = SA_RESTART;
394 #endif
395         sigaction(signum, &act, NULL);
396 }
397
398 static void
399 set_up_signal_handlers(void)
400 {
401         sigemptyset(&fatal_signal_set);
402         sigaddset(&fatal_signal_set, SIGINT);
403         sigaddset(&fatal_signal_set, SIGTERM);
404 #ifdef SIGHUP
405         sigaddset(&fatal_signal_set, SIGHUP);
406 #endif
407 #ifdef SIGQUIT
408         sigaddset(&fatal_signal_set, SIGQUIT);
409 #endif
410
411         register_signal_handler(SIGINT);
412         register_signal_handler(SIGTERM);
413 #ifdef SIGHUP
414         register_signal_handler(SIGHUP);
415 #endif
416 #ifdef SIGQUIT
417         register_signal_handler(SIGQUIT);
418 #endif
419 }
420 #endif // _WIN32
421
422 static void
423 clean_up_internal_tempdir(void)
424 {
425         time_t now = time(NULL);
426         struct stat st;
427         if (x_stat(conf->cache_dir, &st) != 0 || st.st_mtime + 3600 >= now) {
428                 // No cleanup needed.
429                 return;
430         }
431
432         update_mtime(conf->cache_dir);
433
434         DIR *dir = opendir(temp_dir());
435         if (!dir) {
436                 return;
437         }
438
439         struct dirent *entry;
440         while ((entry = readdir(dir))) {
441                 if (str_eq(entry->d_name, ".") || str_eq(entry->d_name, "..")) {
442                         continue;
443                 }
444
445                 char *path = format("%s/%s", temp_dir(), entry->d_name);
446                 if (x_lstat(path, &st) == 0 && st.st_mtime + 3600 < now) {
447                         tmp_unlink(path);
448                 }
449                 free(path);
450         }
451
452         closedir(dir);
453 }
454
455 static char *
456 get_current_working_dir(void)
457 {
458         if (!current_working_dir) {
459                 char *cwd = get_cwd();
460                 if (cwd) {
461                         current_working_dir = x_realpath(cwd);
462                         free(cwd);
463                 }
464                 if (!current_working_dir) {
465                         cc_log("Unable to determine current working directory: %s",
466                                strerror(errno));
467                         failed();
468                 }
469         }
470         return current_working_dir;
471 }
472
473 // Transform a name to a full path into the cache directory, creating needed
474 // sublevels if needed. Caller frees.
475 static char *
476 get_path_in_cache(const char *name, const char *suffix)
477 {
478         char *path = x_strdup(conf->cache_dir);
479         for (unsigned i = 0; i < conf->cache_dir_levels; ++i) {
480                 char *p = format("%s/%c", path, name[i]);
481                 free(path);
482                 path = p;
483         }
484
485         char *result =
486           format("%s/%s%s", path, name + conf->cache_dir_levels, suffix);
487         free(path);
488         return result;
489 }
490
491 // This function hashes an include file and stores the path and hash in the
492 // global included_files variable. If the include file is a PCH, cpp_hash is
493 // also updated. Takes over ownership of path.
494 static void
495 remember_include_file(char *path, struct mdfour *cpp_hash, bool system)
496 {
497         size_t path_len = strlen(path);
498         if (path_len >= 2 && (path[0] == '<' && path[path_len - 1] == '>')) {
499                 // Typically <built-in> or <command-line>.
500                 goto ignore;
501         }
502
503         if (str_eq(path, input_file)) {
504                 // Don't remember the input file.
505                 goto ignore;
506         }
507
508         if (system && (conf->sloppiness & SLOPPY_NO_SYSTEM_HEADERS)) {
509                 // Don't remember this system header.
510                 goto ignore;
511         }
512
513         if (hashtable_search(included_files, path)) {
514                 // Already known include file.
515                 goto ignore;
516         }
517
518 #ifdef _WIN32
519         // stat fails on directories on win32.
520         DWORD attributes = GetFileAttributes(path);
521         if (attributes != INVALID_FILE_ATTRIBUTES &&
522             attributes & FILE_ATTRIBUTE_DIRECTORY) {
523                 goto ignore;
524         }
525 #endif
526
527         struct stat st;
528         if (x_stat(path, &st) != 0) {
529                 goto failure;
530         }
531         if (S_ISDIR(st.st_mode)) {
532                 // Ignore directory, typically $PWD.
533                 goto ignore;
534         }
535         if (!S_ISREG(st.st_mode)) {
536                 // Device, pipe, socket or other strange creature.
537                 cc_log("Non-regular include file %s", path);
538                 goto failure;
539         }
540
541         // Canonicalize path for comparison; clang uses ./header.h.
542         char *canonical = path;
543         size_t canonical_len = path_len;
544         if (canonical[0] == '.' && canonical[1] == '/') {
545                 canonical += 2;
546                 canonical_len -= 2;
547         }
548
549         for (size_t i = 0; i < ignore_headers_len; i++) {
550                 char *ignore = ignore_headers[i];
551                 size_t ignore_len = strlen(ignore);
552                 if (ignore_len > canonical_len) {
553                         continue;
554                 }
555                 if (strncmp(canonical, ignore, ignore_len) == 0
556                     && (ignore[ignore_len-1] == DIR_DELIM_CH
557                         || canonical[ignore_len] == DIR_DELIM_CH
558                         || canonical[ignore_len] == '\0')) {
559                         goto ignore;
560                 }
561         }
562
563         // The comparison using >= is intentional, due to a possible race between
564         // starting compilation and writing the include file. See also the notes
565         // under "Performance" in MANUAL.txt.
566         if (!(conf->sloppiness & SLOPPY_INCLUDE_FILE_MTIME)
567             && st.st_mtime >= time_of_compilation) {
568                 cc_log("Include file %s too new", path);
569                 goto failure;
570         }
571
572         // The same >= logic as above applies to the change time of the file.
573         if (!(conf->sloppiness & SLOPPY_INCLUDE_FILE_CTIME)
574             && st.st_ctime >= time_of_compilation) {
575                 cc_log("Include file %s ctime too new", path);
576                 goto failure;
577         }
578
579         // Let's hash the include file content.
580         struct mdfour fhash;
581         hash_start(&fhash);
582
583         bool is_pch = is_precompiled_header(path);
584         if (is_pch) {
585                 if (!hash_file(&fhash, path)) {
586                         goto failure;
587                 }
588                 struct file_hash pch_hash;
589                 hash_result_as_bytes(&fhash, pch_hash.hash);
590                 pch_hash.size = fhash.totalN;
591                 hash_delimiter(cpp_hash, "pch_hash");
592                 hash_buffer(cpp_hash, pch_hash.hash, sizeof(pch_hash.hash));
593         }
594
595         if (conf->direct_mode) {
596                 if (!is_pch) { // else: the file has already been hashed.
597                         char *source = NULL;
598                         size_t size;
599                         if (st.st_size > 0) {
600                                 if (!read_file(path, st.st_size, &source, &size)) {
601                                         goto failure;
602                                 }
603                         } else {
604                                 source = x_strdup("");
605                                 size = 0;
606                         }
607
608                         int result = hash_source_code_string(conf, &fhash, source, size, path);
609                         free(source);
610                         if (result & HASH_SOURCE_CODE_ERROR
611                             || result & HASH_SOURCE_CODE_FOUND_TIME) {
612                                 goto failure;
613                         }
614                 }
615
616                 struct file_hash *h = x_malloc(sizeof(*h));
617                 hash_result_as_bytes(&fhash, h->hash);
618                 h->size = fhash.totalN;
619                 hashtable_insert(included_files, path, h);
620         } else {
621                 free(path);
622         }
623
624         return;
625
626 failure:
627         if (conf->direct_mode) {
628                 cc_log("Disabling direct mode");
629                 conf->direct_mode = false;
630         }
631         // Fall through.
632 ignore:
633         free(path);
634 }
635
636 // Make a relative path from current working directory to path if path is under
637 // the base directory. Takes over ownership of path. Caller frees.
638 static char *
639 make_relative_path(char *path)
640 {
641         if (str_eq(conf->base_dir, "") || !str_startswith(path, conf->base_dir)) {
642                 return path;
643         }
644
645 #ifdef _WIN32
646         if (path[0] == '/') {
647                 path++;  // Skip leading slash.
648         }
649 #endif
650
651         // x_realpath only works for existing paths, so if path doesn't exist, try
652         // dirname(path) and assemble the path afterwards. We only bother to try
653         // canonicalizing one of these two paths since a compiler path argument
654         // typically only makes sense if path or dirname(path) exists.
655         char *path_suffix = NULL;
656         struct stat st;
657         if (stat(path, &st) != 0) {
658                 // path doesn't exist.
659                 char *dir = dirname(path);
660                 if (stat(dir, &st) != 0) {
661                         // And neither does its parent directory, so no action to take.
662                         free(dir);
663                         return path;
664                 }
665                 free(dir);
666                 path_suffix = basename(path);
667                 char *p = path;
668                 path = dirname(path);
669                 free(p);
670         }
671
672         char *canon_path = x_realpath(path);
673         if (canon_path) {
674                 free(path);
675                 char *relpath = get_relative_path(get_current_working_dir(), canon_path);
676                 free(canon_path);
677                 if (path_suffix) {
678                         path = format("%s/%s", relpath, path_suffix);
679                         free(relpath);
680                         free(path_suffix);
681                         return path;
682                 } else {
683                         return relpath;
684                 }
685         } else {
686                 // path doesn't exist, so leave it as it is.
687                 free(path_suffix);
688                 return path;
689         }
690 }
691
692 // This function reads and hashes a file. While doing this, it also does these
693 // things:
694 //
695 // - Makes include file paths for which the base directory is a prefix relative
696 //   when computing the hash sum.
697 // - Stores the paths and hashes of included files in the global variable
698 //   included_files.
699 static bool
700 process_preprocessed_file(struct mdfour *hash, const char *path)
701 {
702         char *data;
703         size_t size;
704         if (!read_file(path, 0, &data, &size)) {
705                 return false;
706         }
707
708         ignore_headers = NULL;
709         ignore_headers_len = 0;
710         if (!str_eq(conf->ignore_headers_in_manifest, "")) {
711                 char *header, *p, *q, *saveptr = NULL;
712                 p = x_strdup(conf->ignore_headers_in_manifest);
713                 q = p;
714                 while ((header = strtok_r(q, PATH_DELIM, &saveptr))) {
715                         ignore_headers = x_realloc(ignore_headers,
716                                                    (ignore_headers_len+1) * sizeof(char *));
717                         ignore_headers[ignore_headers_len++] = x_strdup(header);
718                         q = NULL;
719                 }
720                 free(p);
721         }
722
723         if (!included_files) {
724                 included_files = create_hashtable(1000, hash_from_string, strings_equal);
725         }
726
727         // Bytes between p and q are pending to be hashed.
728         char *p = data;
729         char *q = data;
730         char *end = data + size;
731
732         // There must be at least 7 characters (# 1 "x") left to potentially find an
733         // include file path.
734         while (q < end - 7) {
735                 // Check if we look at a line containing the file name of an included file.
736                 // At least the following formats exist (where N is a positive integer):
737                 //
738                 // GCC:
739                 //
740                 //   # N "file"
741                 //   # N "file" N
742                 //   #pragma GCC pch_preprocess "file"
743                 //
744                 // HP's compiler:
745                 //
746                 //   #line N "file"
747                 //
748                 // AIX's compiler:
749                 //
750                 //   #line N "file"
751                 //   #line N
752                 //
753                 // Note that there may be other lines starting with '#' left after
754                 // preprocessing as well, for instance "#    pragma".
755                 if (q[0] == '#'
756                     // GCC:
757                     && ((q[1] == ' ' && q[2] >= '0' && q[2] <= '9')
758                         // GCC precompiled header:
759                         || (q[1] == 'p'
760                             && str_startswith(&q[2], "ragma GCC pch_preprocess "))
761                         // HP/AIX:
762                         || (q[1] == 'l' && q[2] == 'i' && q[3] == 'n' && q[4] == 'e'
763                             && q[5] == ' '))
764                     && (q == data || q[-1] == '\n')) {
765                         // Workarounds for preprocessor linemarker bugs in GCC version 6.
766                         if (q[2] == '3') {
767                                 if (str_startswith(q, "# 31 \"<command-line>\"\n")) {
768                                         // Bogus extra line with #31, after the regular #1: Ignore the whole
769                                         // line, and continue parsing.
770                                         hash_buffer(hash, p, q - p);
771                                         while (q < end && *q != '\n') {
772                                                 q++;
773                                         }
774                                         q++;
775                                         p = q;
776                                         continue;
777                                 } else if (str_startswith(q, "# 32 \"<command-line>\" 2\n")) {
778                                         // Bogus wrong line with #32, instead of regular #1: Replace the line
779                                         // number with the usual one.
780                                         hash_buffer(hash, p, q - p);
781                                         q += 1;
782                                         q[0] = '#';
783                                         q[1] = ' ';
784                                         q[2] = '1';
785                                         p = q;
786                                 }
787                         }
788
789                         while (q < end && *q != '"' && *q != '\n') {
790                                 q++;
791                         }
792                         if (q < end && *q == '\n') {
793                                 // A newline before the quotation mark -> no match.
794                                 continue;
795                         }
796                         q++;
797                         if (q >= end) {
798                                 cc_log("Failed to parse included file path");
799                                 free(data);
800                                 return false;
801                         }
802                         // q points to the beginning of an include file path
803                         hash_buffer(hash, p, q - p);
804                         p = q;
805                         while (q < end && *q != '"') {
806                                 q++;
807                         }
808                         // Look for preprocessor flags, after the "filename".
809                         bool system = false;
810                         char *r = q + 1;
811                         while (r < end && *r != '\n') {
812                                 if (*r == '3') { // System header.
813                                         system = true;
814                                 }
815                                 r++;
816                         }
817                         // p and q span the include file path.
818                         char *inc_path = x_strndup(p, q - p);
819                         if (!has_absolute_include_headers) {
820                                 has_absolute_include_headers = is_absolute_path(inc_path);
821                         }
822                         inc_path = make_relative_path(inc_path);
823
824                         bool should_hash_inc_path = true;
825                         if (!conf->hash_dir) {
826                                 char *cwd = gnu_getcwd();
827                                 if (str_startswith(inc_path, cwd) && str_endswith(inc_path, "//")) {
828                                         // When compiling with -g or similar, GCC adds the absolute path to
829                                         // CWD like this:
830                                         //
831                                         //   # 1 "CWD//"
832                                         //
833                                         // If the user has opted out of including the CWD in the hash, don't
834                                         // hash it. See also how debug_prefix_map is handled.
835                                         should_hash_inc_path = false;
836                                 }
837                                 free(cwd);
838                         }
839                         if (should_hash_inc_path) {
840                                 hash_string(hash, inc_path);
841                         }
842
843                         remember_include_file(inc_path, hash, system);
844                         p = q; // Everything of interest between p and q has been hashed now.
845                 } else if (q[0] == '.' && q[1] == 'i' && q[2] == 'n' && q[3] == 'c'
846                            && q[4] == 'b' && q[5] == 'i' && q[6] == 'n') {
847                         // An assembler .incbin statement (which could be part of inline
848                         // assembly) refers to an external file. If the file changes, the hash
849                         // should change as well, but finding out what file to hash is too hard
850                         // for ccache, so just bail out.
851                         cc_log("Found unsupported .incbin directive in source code");
852                         stats_update(STATS_UNSUPPORTED_DIRECTIVE);
853                         failed();
854                 } else {
855                         q++;
856                 }
857         }
858
859         hash_buffer(hash, p, (end - p));
860         free(data);
861
862         // Explicitly check the .gch/.pch/.pth file, Clang does not include any
863         // mention of it in the preprocessed output.
864         if (included_pch_file) {
865                 char *path = x_strdup(included_pch_file);
866                 path = make_relative_path(path);
867                 hash_string(hash, path);
868                 remember_include_file(path, hash, false);
869         }
870
871         return true;
872 }
873
874 // Replace absolute paths with relative paths in the provided dependency file.
875 static void
876 use_relative_paths_in_depfile(const char *depfile)
877 {
878         if (str_eq(conf->base_dir, "")) {
879                 cc_log("Base dir not set, skip using relative paths");
880                 return; // nothing to do
881         }
882         if (!has_absolute_include_headers) {
883                 cc_log("No absolute path for included files found, skip using relative"
884                        " paths");
885                 return; // nothing to do
886         }
887
888         FILE *f;
889         f = fopen(depfile, "r");
890         if (!f) {
891                 cc_log("Cannot open dependency file: %s (%s)", depfile, strerror(errno));
892                 return;
893         }
894
895         char *tmp_file = format("%s.tmp", depfile);
896         FILE *tmpf = create_tmp_file(&tmp_file, "w");
897
898         bool result = false;
899         char buf[10000];
900         while (fgets(buf, sizeof(buf), f) && !ferror(tmpf)) {
901                 char *saveptr;
902                 char *token = strtok_r(buf, " \t", &saveptr);
903                 while (token) {
904                         char *relpath;
905                         if (is_absolute_path(token) && str_startswith(token, conf->base_dir)) {
906                                 relpath = make_relative_path(x_strdup(token));
907                                 result = true;
908                         } else {
909                                 relpath = token;
910                         }
911                         if (token != buf) { // This is a dependency file.
912                                 fputc(' ', tmpf);
913                         }
914                         fputs(relpath, tmpf);
915                         if (relpath != token) {
916                                 free(relpath);
917                         }
918                         token = strtok_r(NULL, " \t", &saveptr);
919                 }
920         }
921
922         if (ferror(f)) {
923                 cc_log("Error reading dependency file: %s, skip relative path usage",
924                        depfile);
925                 result = false;
926                 goto out;
927         }
928         if (ferror(tmpf)) {
929                 cc_log("Error writing temporary dependency file: %s, skip relative path"
930                        " usage", tmp_file);
931                 result = false;
932                 goto out;
933         }
934
935 out:
936         fclose(tmpf);
937         fclose(f);
938         if (result) {
939                 if (x_rename(tmp_file, depfile) != 0) {
940                         cc_log("Error renaming dependency file: %s -> %s (%s), skip relative"
941                                " path usage", tmp_file, depfile, strerror(errno));
942                         result = false;
943                 } else {
944                         cc_log("Renamed dependency file: %s -> %s", tmp_file, depfile);
945                 }
946         }
947         if (!result) {
948                 cc_log("Removing temporary dependency file: %s", tmp_file);
949                 x_unlink(tmp_file);
950         }
951         free(tmp_file);
952 }
953
954 // Copy or link a file to the cache.
955 static void
956 put_file_in_cache(const char *source, const char *dest)
957 {
958         assert(!conf->read_only);
959         assert(!conf->read_only_direct);
960
961         bool do_link = conf->hard_link && !conf->compression;
962         if (do_link) {
963                 x_unlink(dest);
964                 int ret = link(source, dest);
965                 if (ret != 0) {
966                         cc_log("Failed to link %s to %s: %s", source, dest, strerror(errno));
967                         cc_log("Falling back to copying");
968                         do_link = false;
969                 }
970         }
971         if (!do_link) {
972                 int ret = copy_file(
973                   source, dest, conf->compression ? conf->compression_level : 0);
974                 if (ret != 0) {
975                         cc_log("Failed to copy %s to %s: %s", source, dest, strerror(errno));
976                         stats_update(STATS_ERROR);
977                         failed();
978                 }
979         }
980
981         cc_log("Stored in cache: %s -> %s", source, dest);
982
983         struct stat st;
984         if (x_stat(dest, &st) != 0) {
985                 stats_update(STATS_ERROR);
986                 failed();
987         }
988         stats_update_size(file_size(&st), 1);
989 }
990
991 // Copy or link a file from the cache.
992 static void
993 get_file_from_cache(const char *source, const char *dest)
994 {
995         int ret;
996         bool do_link = conf->hard_link && !file_is_compressed(source);
997         if (do_link) {
998                 x_unlink(dest);
999                 ret = link(source, dest);
1000         } else {
1001                 ret = copy_file(source, dest, 0);
1002         }
1003
1004         if (ret == -1) {
1005                 if (errno == ENOENT || errno == ESTALE) {
1006                         // Someone removed the file just before we began copying?
1007                         cc_log("Cache file %s just disappeared from cache", source);
1008                         stats_update(STATS_MISSING);
1009                 } else {
1010                         cc_log("Failed to %s %s to %s: %s",
1011                                do_link ? "link" : "copy",
1012                                source,
1013                                dest,
1014                                strerror(errno));
1015                         stats_update(STATS_ERROR);
1016                 }
1017
1018                 // If there was trouble getting a file from the cached result, wipe the
1019                 // whole cached result for consistency.
1020                 x_unlink(cached_stderr);
1021                 x_unlink(cached_obj);
1022                 x_unlink(cached_dep);
1023                 x_unlink(cached_dia);
1024
1025                 failed();
1026         }
1027
1028         cc_log("Created from cache: %s -> %s", source, dest);
1029 }
1030
1031 // Send cached stderr, if any, to stderr.
1032 static void
1033 send_cached_stderr(void)
1034 {
1035         int fd_stderr = open(cached_stderr, O_RDONLY | O_BINARY);
1036         if (fd_stderr != -1) {
1037                 copy_fd(fd_stderr, 2);
1038                 close(fd_stderr);
1039         }
1040 }
1041
1042 // Create or update the manifest file.
1043 void update_manifest_file(void)
1044 {
1045         if (!conf->direct_mode
1046             || !included_files
1047             || conf->read_only
1048             || conf->read_only_direct) {
1049                 return;
1050         }
1051
1052         struct stat st;
1053         size_t old_size = 0; // in bytes
1054         if (stat(manifest_path, &st) == 0) {
1055                 old_size = file_size(&st);
1056         }
1057         if (manifest_put(manifest_path, cached_obj_hash, included_files)) {
1058                 cc_log("Added object file hash to %s", manifest_path);
1059                 update_mtime(manifest_path);
1060                 if (x_stat(manifest_path, &st) == 0) {
1061                         stats_update_size(file_size(&st) - old_size, old_size == 0 ? 1 : 0);
1062                 }
1063         } else {
1064                 cc_log("Failed to add object file hash to %s", manifest_path);
1065         }
1066 }
1067
1068 // Run the real compiler and put the result in cache.
1069 static void
1070 to_cache(struct args *args)
1071 {
1072         char *tmp_stdout = format("%s.tmp.stdout", cached_obj);
1073         int tmp_stdout_fd = create_tmp_fd(&tmp_stdout);
1074         char *tmp_stderr = format("%s.tmp.stderr", cached_obj);
1075         int tmp_stderr_fd = create_tmp_fd(&tmp_stderr);
1076
1077         char *tmp_cov;
1078         if (generating_coverage) {
1079                 char *tmp_aux;
1080                 // GCC has some funny rule about max extension length.
1081                 if (strlen(get_extension(output_obj)) < 6) {
1082                         tmp_aux = remove_extension(output_obj);
1083                 } else {
1084                         tmp_aux = x_strdup(output_obj);
1085                 }
1086                 tmp_cov = format("%s.gcno", tmp_aux);
1087                 free(tmp_aux);
1088         } else {
1089                 tmp_cov = NULL;
1090         }
1091
1092         // GCC (at least 4.8 and 4.9) forms the .dwo file name by removing everything
1093         // after (and including) the last "." from the object file name and then
1094         // appending ".dwo".
1095         char *tmp_dwo = NULL;
1096         if (using_split_dwarf) {
1097                 char *base_name = remove_extension(output_obj);
1098                 tmp_dwo = format("%s.dwo", base_name);
1099                 free(base_name);
1100         }
1101
1102         args_add(args, "-o");
1103         args_add(args, output_obj);
1104
1105         if (output_dia) {
1106                 args_add(args, "--serialize-diagnostics");
1107                 args_add(args, output_dia);
1108         }
1109
1110         // Turn off DEPENDENCIES_OUTPUT when running cc1, because otherwise it will
1111         // emit a line like this:
1112         //
1113         //   tmp.stdout.vexed.732.o: /home/mbp/.ccache/tmp.stdout.vexed.732.i
1114         x_unsetenv("DEPENDENCIES_OUTPUT");
1115
1116         if (conf->run_second_cpp) {
1117                 args_add(args, input_file);
1118         } else {
1119                 args_add(args, i_tmpfile);
1120         }
1121
1122         cc_log("Running real compiler");
1123         int status =
1124           execute(args->argv, tmp_stdout_fd, tmp_stderr_fd, &compiler_pid);
1125         args_pop(args, 3);
1126
1127         struct stat st;
1128         if (x_stat(tmp_stdout, &st) != 0) {
1129                 // The stdout file was removed - cleanup in progress? Better bail out.
1130                 stats_update(STATS_MISSING);
1131                 tmp_unlink(tmp_stdout);
1132                 tmp_unlink(tmp_stderr);
1133                 if (tmp_cov) {
1134                         tmp_unlink(tmp_cov);
1135                 }
1136                 if (tmp_dwo) {
1137                         tmp_unlink(tmp_dwo);
1138                 }
1139                 failed();
1140         }
1141         if (st.st_size != 0) {
1142                 cc_log("Compiler produced stdout");
1143                 stats_update(STATS_STDOUT);
1144                 tmp_unlink(tmp_stdout);
1145                 tmp_unlink(tmp_stderr);
1146                 if (tmp_cov) {
1147                         tmp_unlink(tmp_cov);
1148                 }
1149                 if (tmp_dwo) {
1150                         tmp_unlink(tmp_dwo);
1151                 }
1152                 failed();
1153         }
1154         tmp_unlink(tmp_stdout);
1155
1156         // Merge stderr from the preprocessor (if any) and stderr from the real
1157         // compiler into tmp_stderr.
1158         if (cpp_stderr) {
1159                 char *tmp_stderr2 = format("%s.2", tmp_stderr);
1160                 if (x_rename(tmp_stderr, tmp_stderr2)) {
1161                         cc_log("Failed to rename %s to %s: %s", tmp_stderr, tmp_stderr2,
1162                                strerror(errno));
1163                         failed();
1164                 }
1165
1166                 int fd_cpp_stderr = open(cpp_stderr, O_RDONLY | O_BINARY);
1167                 if (fd_cpp_stderr == -1) {
1168                         cc_log("Failed opening %s: %s", cpp_stderr, strerror(errno));
1169                         failed();
1170                 }
1171
1172                 int fd_real_stderr = open(tmp_stderr2, O_RDONLY | O_BINARY);
1173                 if (fd_real_stderr == -1) {
1174                         cc_log("Failed opening %s: %s", tmp_stderr2, strerror(errno));
1175                         failed();
1176                 }
1177
1178                 int fd_result =
1179                   open(tmp_stderr, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
1180                 if (fd_result == -1) {
1181                         cc_log("Failed opening %s: %s", tmp_stderr, strerror(errno));
1182                         failed();
1183                 }
1184
1185                 copy_fd(fd_cpp_stderr, fd_result);
1186                 copy_fd(fd_real_stderr, fd_result);
1187                 close(fd_cpp_stderr);
1188                 close(fd_real_stderr);
1189                 close(fd_result);
1190                 tmp_unlink(tmp_stderr2);
1191                 free(tmp_stderr2);
1192         }
1193
1194         if (status != 0) {
1195                 cc_log("Compiler gave exit status %d", status);
1196                 stats_update(STATS_STATUS);
1197
1198                 int fd = open(tmp_stderr, O_RDONLY | O_BINARY);
1199                 if (fd != -1) {
1200                         // We can output stderr immediately instead of rerunning the compiler.
1201                         copy_fd(fd, 2);
1202                         close(fd);
1203                         tmp_unlink(tmp_stderr);
1204
1205                         x_exit(status);
1206                 }
1207
1208                 tmp_unlink(tmp_stderr);
1209                 if (tmp_cov) {
1210                         tmp_unlink(tmp_cov);
1211                 }
1212                 if (tmp_dwo) {
1213                         tmp_unlink(tmp_dwo);
1214                 }
1215
1216                 failed();
1217         }
1218
1219         if (stat(output_obj, &st) != 0) {
1220                 cc_log("Compiler didn't produce an object file");
1221                 stats_update(STATS_NOOUTPUT);
1222                 failed();
1223         }
1224         if (st.st_size == 0) {
1225                 cc_log("Compiler produced an empty object file");
1226                 stats_update(STATS_EMPTYOUTPUT);
1227                 failed();
1228         }
1229
1230         if (using_split_dwarf) {
1231                 if (stat(tmp_dwo, &st) != 0) {
1232                         cc_log("Compiler didn't produce a split dwarf file");
1233                         stats_update(STATS_NOOUTPUT);
1234                         failed();
1235                 }
1236                 if (st.st_size == 0) {
1237                         cc_log("Compiler produced an empty split dwarf file");
1238                         stats_update(STATS_EMPTYOUTPUT);
1239                         failed();
1240                 }
1241         }
1242
1243         if (x_stat(tmp_stderr, &st) != 0) {
1244                 stats_update(STATS_ERROR);
1245                 failed();
1246         }
1247         if (st.st_size > 0) {
1248                 if (move_uncompressed_file(
1249                       tmp_stderr, cached_stderr,
1250                       conf->compression ? conf->compression_level : 0) != 0) {
1251                         cc_log("Failed to move %s to %s: %s", tmp_stderr, cached_stderr,
1252                                strerror(errno));
1253                         stats_update(STATS_ERROR);
1254                         failed();
1255                 }
1256                 cc_log("Stored in cache: %s", cached_stderr);
1257                 if (!conf->compression
1258                     // If the file was compressed, obtain the size again:
1259                     || x_stat(cached_stderr, &st) == 0) {
1260                         stats_update_size(file_size(&st), 1);
1261                 }
1262         } else {
1263                 tmp_unlink(tmp_stderr);
1264                 if (conf->recache) {
1265                         // If recaching, we need to remove any previous .stderr.
1266                         x_unlink(cached_stderr);
1267                 }
1268         }
1269
1270         if (generating_coverage) {
1271                 // GCC won't generate notes if there is no code.
1272                 if (stat(tmp_cov, &st) != 0 && errno == ENOENT) {
1273                         FILE *f = fopen(cached_cov, "wb");
1274                         cc_log("Creating placeholder: %s", cached_cov);
1275                         if (!f) {
1276                                 cc_log("Failed to create %s: %s", cached_cov, strerror(errno));
1277                                 stats_update(STATS_ERROR);
1278                                 failed();
1279                         }
1280                         fclose(f);
1281                         stats_update_size(0, 1);
1282                 } else {
1283                         put_file_in_cache(tmp_cov, cached_cov);
1284                 }
1285         }
1286
1287         if (output_dia) {
1288                 if (x_stat(output_dia, &st) != 0) {
1289                         stats_update(STATS_ERROR);
1290                         failed();
1291                 }
1292                 if (st.st_size > 0) {
1293                         put_file_in_cache(output_dia, cached_dia);
1294                 }
1295         }
1296
1297         put_file_in_cache(output_obj, cached_obj);
1298
1299         if (using_split_dwarf) {
1300                 assert(tmp_dwo);
1301                 assert(cached_dwo);
1302                 put_file_in_cache(tmp_dwo, cached_dwo);
1303         }
1304
1305         if (generating_dependencies) {
1306                 use_relative_paths_in_depfile(output_dep);
1307                 put_file_in_cache(output_dep, cached_dep);
1308         }
1309         stats_update(STATS_TOCACHE);
1310
1311         // Make sure we have a CACHEDIR.TAG in the cache part of cache_dir. This can
1312         // be done almost anywhere, but we might as well do it near the end as we
1313         // save the stat call if we exit early.
1314         {
1315                 char *first_level_dir = dirname(stats_file);
1316                 if (create_cachedirtag(first_level_dir) != 0) {
1317                         cc_log("Failed to create %s/CACHEDIR.TAG (%s)\n",
1318                                first_level_dir, strerror(errno));
1319                         stats_update(STATS_ERROR);
1320                         failed();
1321                 }
1322                 free(first_level_dir);
1323
1324                 // Remove any CACHEDIR.TAG on the cache_dir level where it was located in
1325                 // previous ccache versions.
1326                 if (getpid() % 1000 == 0) {
1327                         char *path = format("%s/CACHEDIR.TAG", conf->cache_dir);
1328                         x_unlink(path);
1329                         free(path);
1330                 }
1331         }
1332
1333         // Everything OK.
1334         send_cached_stderr();
1335         update_manifest_file();
1336
1337         free(tmp_stderr);
1338         free(tmp_stdout);
1339         free(tmp_cov);
1340         free(tmp_dwo);
1341 }
1342
1343 // Find the object file name by running the compiler in preprocessor mode.
1344 // Returns the hash as a heap-allocated hex string.
1345 static struct file_hash *
1346 get_object_name_from_cpp(struct args *args, struct mdfour *hash)
1347 {
1348         time_of_compilation = time(NULL);
1349
1350         char *path_stderr = format("%s/tmp.cpp_stderr", temp_dir());
1351         int path_stderr_fd = create_tmp_fd(&path_stderr);
1352         add_pending_tmp_file(path_stderr);
1353
1354         char *path_stdout;
1355         int status;
1356         if (direct_i_file) {
1357                 // We are compiling a .i or .ii file - that means we can skip the cpp stage
1358                 // and directly form the correct i_tmpfile.
1359                 path_stdout = input_file;
1360                 status = 0;
1361         } else {
1362                 // Run cpp on the input file to obtain the .i.
1363
1364                 // Limit the basename to 10 characters in order to cope with filesystem with
1365                 // small maximum filename length limits.
1366                 char *input_base = basename(input_file);
1367                 char *tmp = strchr(input_base, '.');
1368                 if (tmp) {
1369                         *tmp = 0;
1370                 }
1371                 if (strlen(input_base) > 10) {
1372                         input_base[10] = 0;
1373                 }
1374
1375                 path_stdout = format("%s/%s.stdout", temp_dir(), input_base);
1376                 int path_stdout_fd = create_tmp_fd(&path_stdout);
1377                 add_pending_tmp_file(path_stdout);
1378
1379                 int args_added = 2;
1380                 args_add(args, "-E");
1381                 if (conf->keep_comments_cpp) {
1382                         args_add(args, "-C");
1383                         args_added = 3;
1384                 }
1385                 args_add(args, input_file);
1386                 add_prefix(args, conf->prefix_command_cpp);
1387                 cc_log("Running preprocessor");
1388                 status = execute(args->argv, path_stdout_fd, path_stderr_fd, &compiler_pid);
1389                 args_pop(args, args_added);
1390         }
1391
1392         if (status != 0) {
1393                 cc_log("Preprocessor gave exit status %d", status);
1394                 stats_update(STATS_PREPROCESSOR);
1395                 failed();
1396         }
1397
1398         if (conf->unify) {
1399                 // When we are doing the unifying tricks we need to include the input file
1400                 // name in the hash to get the warnings right.
1401                 hash_delimiter(hash, "unifyfilename");
1402                 hash_string(hash, input_file);
1403
1404                 hash_delimiter(hash, "unifycpp");
1405                 if (unify_hash(hash, path_stdout) != 0) {
1406                         stats_update(STATS_ERROR);
1407                         cc_log("Failed to unify %s", path_stdout);
1408                         failed();
1409                 }
1410         } else {
1411                 hash_delimiter(hash, "cpp");
1412                 if (!process_preprocessed_file(hash, path_stdout)) {
1413                         stats_update(STATS_ERROR);
1414                         failed();
1415                 }
1416         }
1417
1418         hash_delimiter(hash, "cppstderr");
1419         if (!hash_file(hash, path_stderr)) {
1420                 fatal("Failed to open %s: %s", path_stderr, strerror(errno));
1421         }
1422
1423         if (direct_i_file) {
1424                 i_tmpfile = input_file;
1425         } else {
1426                 // i_tmpfile needs the proper cpp_extension for the compiler to do its
1427                 // thing correctly
1428                 i_tmpfile = format("%s.%s", path_stdout, conf->cpp_extension);
1429                 x_rename(path_stdout, i_tmpfile);
1430                 add_pending_tmp_file(i_tmpfile);
1431         }
1432
1433         if (conf->run_second_cpp) {
1434                 free(path_stderr);
1435         } else {
1436                 // If we are using the CPP trick, we need to remember this stderr data and
1437                 // output it just before the main stderr from the compiler pass.
1438                 cpp_stderr = path_stderr;
1439                 hash_delimiter(hash, "runsecondcpp");
1440                 hash_string(hash, "false");
1441         }
1442
1443         struct file_hash *result = x_malloc(sizeof(*result));
1444         hash_result_as_bytes(hash, result->hash);
1445         result->size = hash->totalN;
1446         return result;
1447 }
1448
1449 static void
1450 update_cached_result_globals(struct file_hash *hash)
1451 {
1452         char *object_name = format_hash_as_string(hash->hash, hash->size);
1453         cached_obj_hash = hash;
1454         cached_obj = get_path_in_cache(object_name, ".o");
1455         cached_stderr = get_path_in_cache(object_name, ".stderr");
1456         cached_dep = get_path_in_cache(object_name, ".d");
1457         cached_cov = get_path_in_cache(object_name, ".gcno");
1458         cached_dia = get_path_in_cache(object_name, ".dia");
1459
1460         if (using_split_dwarf) {
1461                 cached_dwo = get_path_in_cache(object_name, ".dwo");
1462         } else {
1463                 cached_dwo = NULL;
1464         }
1465
1466         stats_file = format("%s/%c/stats", conf->cache_dir, object_name[0]);
1467         free(object_name);
1468 }
1469
1470 // Hash mtime or content of a file, or the output of a command, according to
1471 // the CCACHE_COMPILERCHECK setting.
1472 static void
1473 hash_compiler(struct mdfour *hash, struct stat *st, const char *path,
1474               bool allow_command)
1475 {
1476         if (str_eq(conf->compiler_check, "none")) {
1477                 // Do nothing.
1478         } else if (str_eq(conf->compiler_check, "mtime")) {
1479                 hash_delimiter(hash, "cc_mtime");
1480                 hash_int(hash, st->st_size);
1481                 hash_int(hash, st->st_mtime);
1482         } else if (str_startswith(conf->compiler_check, "string:")) {
1483                 hash_delimiter(hash, "cc_hash");
1484                 hash_string(hash, conf->compiler_check + strlen("string:"));
1485         } else if (str_eq(conf->compiler_check, "content") || !allow_command) {
1486                 hash_delimiter(hash, "cc_content");
1487                 hash_file(hash, path);
1488         } else { // command string
1489                 if (!hash_multicommand_output(
1490                       hash, conf->compiler_check, orig_args->argv[0])) {
1491                         fatal("Failure running compiler check command: %s", conf->compiler_check);
1492                 }
1493         }
1494 }
1495
1496 // Note that these compiler checks are unreliable, so nothing should
1497 // hard-depend on them.
1498
1499 static bool
1500 compiler_is_clang(struct args *args)
1501 {
1502         char *name = basename(args->argv[0]);
1503         bool result = strstr(name, "clang") != NULL;
1504         free(name);
1505         return result;
1506 }
1507
1508 static bool
1509 compiler_is_gcc(struct args *args)
1510 {
1511         char *name = basename(args->argv[0]);
1512         bool result = strstr(name, "gcc") || strstr(name, "g++");
1513         free(name);
1514         return result;
1515 }
1516
1517 // Update a hash sum with information common for the direct and preprocessor
1518 // modes.
1519 static void
1520 calculate_common_hash(struct args *args, struct mdfour *hash)
1521 {
1522         hash_string(hash, HASH_PREFIX);
1523
1524         // We have to hash the extension, as a .i file isn't treated the same by the
1525         // compiler as a .ii file.
1526         hash_delimiter(hash, "ext");
1527         hash_string(hash, conf->cpp_extension);
1528
1529 #ifdef _WIN32
1530         const char *ext = strrchr(args->argv[0], '.');
1531         char full_path_win_ext[MAX_PATH + 1] = {0};
1532         add_exe_ext_if_no_to_fullpath(full_path_win_ext, MAX_PATH, ext,
1533                                       args->argv[0]);
1534         const char *full_path = full_path_win_ext;
1535 #else
1536         const char *full_path = args->argv[0];
1537 #endif
1538
1539         struct stat st;
1540         if (x_stat(full_path, &st) != 0) {
1541                 stats_update(STATS_COMPILER);
1542                 failed();
1543         }
1544
1545         // Hash information about the compiler.
1546         hash_compiler(hash, &st, args->argv[0], true);
1547
1548         // Also hash the compiler name as some compilers use hard links and behave
1549         // differently depending on the real name.
1550         hash_delimiter(hash, "cc_name");
1551         char *p = basename(args->argv[0]);
1552         hash_string(hash, p);
1553         free(p);
1554
1555         // Possibly hash the current working directory.
1556         if (generating_debuginfo && conf->hash_dir) {
1557                 char *cwd = gnu_getcwd();
1558                 for (size_t i = 0; i < debug_prefix_maps_len; i++) {
1559                         char *map = debug_prefix_maps[i];
1560                         char *sep = strchr(map, '=');
1561                         if (sep) {
1562                                 char *old = x_strndup(map, sep - map);
1563                                 char *new = x_strdup(sep + 1);
1564                                 cc_log("Relocating debuginfo cwd %s, from %s to %s", cwd, old, new);
1565                                 if (str_startswith(cwd, old)) {
1566                                         char *dir = format("%s%s", new, cwd + strlen(old));
1567                                         free(cwd);
1568                                         cwd = dir;
1569                                 }
1570                                 free(old);
1571                                 free(new);
1572                         }
1573                 }
1574                 if (cwd) {
1575                         hash_delimiter(hash, "cwd");
1576                         hash_string(hash, cwd);
1577                         free(cwd);
1578                 }
1579         }
1580
1581         // Possibly hash the coverage data file path.
1582         if (generating_coverage && profile_arcs) {
1583                 char *dir = dirname(output_obj);
1584                 if (profile_dir) {
1585                         dir = x_strdup(profile_dir);
1586                 } else {
1587                         char *real_dir = x_realpath(dir);
1588                         free(dir);
1589                         dir = real_dir;
1590                 }
1591                 if (dir) {
1592                         char *base_name = basename(output_obj);
1593                         p = remove_extension(base_name);
1594                         free(base_name);
1595                         char *gcda_path = format("%s/%s.gcda", dir, p);
1596                         cc_log("Hashing coverage path %s", gcda_path);
1597                         free(p);
1598                         hash_delimiter(hash, "gcda");
1599                         hash_string(hash, gcda_path);
1600                         free(dir);
1601                 }
1602         }
1603
1604         if (!str_eq(conf->extra_files_to_hash, "")) {
1605                 char *p = x_strdup(conf->extra_files_to_hash);
1606                 char *q = p;
1607                 char *path;
1608                 char *saveptr = NULL;
1609                 while ((path = strtok_r(q, PATH_DELIM, &saveptr))) {
1610                         cc_log("Hashing extra file %s", path);
1611                         hash_delimiter(hash, "extrafile");
1612                         if (!hash_file(hash, path)) {
1613                                 stats_update(STATS_BADEXTRAFILE);
1614                                 failed();
1615                         }
1616                         q = NULL;
1617                 }
1618                 free(p);
1619         }
1620
1621         // Possibly hash GCC_COLORS (for color diagnostics).
1622         if (compiler_is_gcc(args)) {
1623                 const char *gcc_colors = getenv("GCC_COLORS");
1624                 if (gcc_colors) {
1625                         hash_delimiter(hash, "gcccolors");
1626                         hash_string(hash, gcc_colors);
1627                 }
1628         }
1629 }
1630
1631 // Update a hash sum with information specific to the direct and preprocessor
1632 // modes and calculate the object hash. Returns the object hash on success,
1633 // otherwise NULL. Caller frees.
1634 static struct file_hash *
1635 calculate_object_hash(struct args *args, struct mdfour *hash, int direct_mode)
1636 {
1637         if (direct_mode) {
1638                 hash_delimiter(hash, "manifest version");
1639                 hash_int(hash, MANIFEST_VERSION);
1640         }
1641
1642         // clang will emit warnings for unused linker flags, so we shouldn't skip
1643         // those arguments.
1644         int is_clang = compiler_is_clang(args);
1645
1646         // First the arguments.
1647         for (int i = 1; i < args->argc; i++) {
1648                 // -L doesn't affect compilation (except for clang).
1649                 if (i < args->argc-1 && str_eq(args->argv[i], "-L") && !is_clang) {
1650                         i++;
1651                         continue;
1652                 }
1653                 if (str_startswith(args->argv[i], "-L") && !is_clang) {
1654                         continue;
1655                 }
1656
1657                 // -Wl,... doesn't affect compilation (except for clang).
1658                 if (str_startswith(args->argv[i], "-Wl,") && !is_clang) {
1659                         continue;
1660                 }
1661
1662                 // The -fdebug-prefix-map option may be used in combination with
1663                 // CCACHE_BASEDIR to reuse results across different directories. Skip it
1664                 // from hashing.
1665                 if (str_startswith(args->argv[i], "-fdebug-prefix-map=")) {
1666                         continue;
1667                 }
1668
1669                 // When using the preprocessor, some arguments don't contribute to the
1670                 // hash. The theory is that these arguments will change the output of -E if
1671                 // they are going to have any effect at all. For precompiled headers this
1672                 // might not be the case.
1673                 if (!direct_mode && !output_is_precompiled_header
1674                     && !using_precompiled_header) {
1675                         if (compopt_affects_cpp(args->argv[i])) {
1676                                 if (compopt_takes_arg(args->argv[i])) {
1677                                         i++;
1678                                 }
1679                                 continue;
1680                         }
1681                         if (compopt_short(compopt_affects_cpp, args->argv[i])) {
1682                                 continue;
1683                         }
1684                 }
1685
1686                 // If we're generating dependencies, we make sure to skip the filename of
1687                 // the dependency file, since it doesn't impact the output.
1688                 if (generating_dependencies) {
1689                         if (str_startswith(args->argv[i], "-Wp,")) {
1690                                 if (str_startswith(args->argv[i], "-Wp,-MD,")
1691                                     && !strchr(args->argv[i] + 8, ',')) {
1692                                         hash_string_length(hash, args->argv[i], 8);
1693                                         continue;
1694                                 } else if (str_startswith(args->argv[i], "-Wp,-MMD,")
1695                                            && !strchr(args->argv[i] + 9, ',')) {
1696                                         hash_string_length(hash, args->argv[i], 9);
1697                                         continue;
1698                                 }
1699                         } else if (str_startswith(args->argv[i], "-MF")) {
1700                                 // In either case, hash the "-MF" part.
1701                                 hash_string_length(hash, args->argv[i], 3);
1702
1703                                 bool separate_argument = (strlen(args->argv[i]) == 3);
1704                                 if (separate_argument) {
1705                                         // Next argument is dependency name, so skip it.
1706                                         i++;
1707                                 }
1708                                 continue;
1709                         }
1710                 }
1711
1712                 char *p = NULL;
1713                 if (str_startswith(args->argv[i], "-specs=")) {
1714                         p = args->argv[i] + 7;
1715                 } else if (str_startswith(args->argv[i], "--specs=")) {
1716                         p = args->argv[i] + 8;
1717                 }
1718
1719                 struct stat st;
1720                 if (p && x_stat(p, &st) == 0) {
1721                         // If given an explicit specs file, then hash that file, but don't
1722                         // include the path to it in the hash.
1723                         hash_delimiter(hash, "specs");
1724                         hash_compiler(hash, &st, p, false);
1725                         continue;
1726                 }
1727
1728                 if (str_startswith(args->argv[i], "-fplugin=")
1729                     && x_stat(args->argv[i] + 9, &st) == 0) {
1730                         hash_delimiter(hash, "plugin");
1731                         hash_compiler(hash, &st, args->argv[i] + 9, false);
1732                         continue;
1733                 }
1734
1735                 if (str_eq(args->argv[i], "-Xclang")
1736                     && i + 3 < args->argc
1737                     && str_eq(args->argv[i+1], "-load")
1738                     && str_eq(args->argv[i+2], "-Xclang")
1739                     && x_stat(args->argv[i+3], &st) == 0) {
1740                         hash_delimiter(hash, "plugin");
1741                         hash_compiler(hash, &st, args->argv[i+3], false);
1742                         i += 3;
1743                         continue;
1744                 }
1745
1746                 // All other arguments are included in the hash.
1747                 hash_delimiter(hash, "arg");
1748                 hash_string(hash, args->argv[i]);
1749                 if (i + 1 < args->argc && compopt_takes_arg(args->argv[i])) {
1750                         i++;
1751                         hash_delimiter(hash, "arg");
1752                         hash_string(hash, args->argv[i]);
1753                 }
1754         }
1755
1756         // For profile generation (-fprofile-arcs, -fprofile-generate):
1757         // - hash profile directory
1758         //
1759         // For profile usage (-fprofile-use):
1760         // - hash profile data
1761         //
1762         // -fbranch-probabilities and -fvpt usage is covered by
1763         // -fprofile-generate/-fprofile-use.
1764         //
1765         // The profile directory can be specified as an argument to
1766         // -fprofile-generate=, -fprofile-use= or -fprofile-dir=.
1767         if (profile_generate) {
1768                 if (!profile_dir) {
1769                         profile_dir = get_cwd();
1770                 }
1771                 cc_log("Adding profile directory %s to our hash", profile_dir);
1772                 hash_delimiter(hash, "-fprofile-dir");
1773                 hash_string(hash, profile_dir);
1774         }
1775
1776         if (profile_use) {
1777                 // Calculate gcda name.
1778                 if (!profile_dir) {
1779                         profile_dir = get_cwd();
1780                 }
1781                 char *base_name = remove_extension(output_obj);
1782                 char *gcda_name = format("%s/%s.gcda", profile_dir, base_name);
1783                 cc_log("Adding profile data %s to our hash", gcda_name);
1784                 // Add the gcda to our hash.
1785                 hash_delimiter(hash, "-fprofile-use");
1786                 hash_file(hash, gcda_name);
1787                 free(base_name);
1788                 free(gcda_name);
1789         }
1790
1791         // Adding -arch to hash since cpp output is affected.
1792         for (size_t i = 0; i < arch_args_size; ++i) {
1793                 hash_delimiter(hash, "-arch");
1794                 hash_string(hash, arch_args[i]);
1795         }
1796
1797         struct file_hash *object_hash = NULL;
1798         if (direct_mode) {
1799                 // Hash environment variables that affect the preprocessor output.
1800                 const char *envvars[] = {
1801                         "CPATH",
1802                         "C_INCLUDE_PATH",
1803                         "CPLUS_INCLUDE_PATH",
1804                         "OBJC_INCLUDE_PATH",
1805                         "OBJCPLUS_INCLUDE_PATH", // clang
1806                         NULL
1807                 };
1808                 for (const char **p = envvars; *p; ++p) {
1809                         char *v = getenv(*p);
1810                         if (v) {
1811                                 hash_delimiter(hash, *p);
1812                                 hash_string(hash, v);
1813                         }
1814                 }
1815
1816                 if (!(conf->sloppiness & SLOPPY_FILE_MACRO)) {
1817                         // The source code file or an include file may contain __FILE__, so make
1818                         // sure that the hash is unique for the file name.
1819                         hash_delimiter(hash, "inputfile");
1820                         hash_string(hash, input_file);
1821                 }
1822
1823                 hash_delimiter(hash, "sourcecode");
1824                 int result = hash_source_code_file(conf, hash, input_file);
1825                 if (result & HASH_SOURCE_CODE_ERROR) {
1826                         failed();
1827                 }
1828                 if (result & HASH_SOURCE_CODE_FOUND_TIME) {
1829                         cc_log("Disabling direct mode");
1830                         conf->direct_mode = false;
1831                         return NULL;
1832                 }
1833                 char *manifest_name = hash_result(hash);
1834                 manifest_path = get_path_in_cache(manifest_name, ".manifest");
1835                 free(manifest_name);
1836                 cc_log("Looking for object file hash in %s", manifest_path);
1837                 object_hash = manifest_get(conf, manifest_path);
1838                 if (object_hash) {
1839                         cc_log("Got object file hash from manifest");
1840                 } else {
1841                         cc_log("Did not find object file hash in manifest");
1842                 }
1843         } else {
1844                 if (arch_args_size == 0) {
1845                         object_hash = get_object_name_from_cpp(args, hash);
1846                         cc_log("Got object file hash from preprocessor");
1847                 } else {
1848                         args_add(args, "-arch");
1849                         for (size_t i = 0; i < arch_args_size; ++i) {
1850                                 args_add(args, arch_args[i]);
1851                                 object_hash = get_object_name_from_cpp(args, hash);
1852                                 cc_log("Got object file hash from preprocessor with -arch %s",
1853                                        arch_args[i]);
1854                                 if (i != arch_args_size - 1) {
1855                                         free(object_hash);
1856                                 }
1857                                 args_pop(args, 1);
1858                         }
1859                         args_pop(args, 1);
1860                 }
1861                 if (generating_dependencies) {
1862                         cc_log("Preprocessor created %s", output_dep);
1863                 }
1864         }
1865
1866         return object_hash;
1867 }
1868
1869 // Try to return the compile result from cache. If we can return from cache
1870 // then this function exits with the correct status code, otherwise it returns.
1871 static void
1872 from_cache(enum fromcache_call_mode mode, bool put_object_in_manifest)
1873 {
1874         // The user might be disabling cache hits.
1875         if (conf->recache) {
1876                 return;
1877         }
1878
1879         // We can't trust the objects based on running the preprocessor
1880         // when the output is precompiled headers, as the hash does not
1881         // include the mtime of each included header, breaking compilation
1882         // with clang when the precompiled header is used after touching
1883         // one of the included files.
1884         if (output_is_precompiled_header && mode == FROMCACHE_CPP_MODE) {
1885                 cc_log("Not using preprocessed cached object for precompiled header");
1886                 return;
1887         }
1888
1889         struct stat st;
1890         if (stat(cached_obj, &st) != 0) {
1891                 cc_log("Object file %s not in cache", cached_obj);
1892                 return;
1893         }
1894
1895         // Occasionally, e.g. on hard reset, our cache ends up as just filesystem
1896         // meta-data with no content. Catch an easy case of this.
1897         if (st.st_size == 0) {
1898                 cc_log("Invalid (empty) object file %s in cache", cached_obj);
1899                 x_unlink(cached_obj);
1900                 return;
1901         }
1902
1903         if (using_split_dwarf && !generating_dependencies) {
1904                 assert(output_dwo);
1905         }
1906         if (output_dwo) {
1907                 assert(cached_dwo);
1908                 if (stat(cached_dwo, &st) != 0) {
1909                         cc_log("Split dwarf file %s not in cache", cached_dwo);
1910                         return;
1911                 }
1912                 if (st.st_size == 0) {
1913                         cc_log("Invalid (empty) dwo file %s in cache", cached_dwo);
1914                         x_unlink(cached_dwo);
1915                         x_unlink(cached_obj); // To really invalidate.
1916                         return;
1917                 }
1918         }
1919
1920         // (If mode != FROMCACHE_DIRECT_MODE, the dependency file is created by gcc.)
1921         bool produce_dep_file =
1922           generating_dependencies && mode == FROMCACHE_DIRECT_MODE;
1923
1924         // If the dependency file should be in the cache, check that it is.
1925         if (produce_dep_file && stat(cached_dep, &st) != 0) {
1926                 cc_log("Dependency file %s missing in cache", cached_dep);
1927                 return;
1928         }
1929
1930         // Check if the diagnostic file is there.
1931         if (output_dia && stat(cached_dia, &st) != 0) {
1932                 cc_log("Diagnostic file %s not in cache", cached_dia);
1933                 return;
1934         }
1935
1936         // Copy object file from cache. Do so also for FissionDwarf file, cached_dwo,
1937         // when -gsplit-dwarf is specified.
1938         if (!str_eq(output_obj, "/dev/null")) {
1939                 get_file_from_cache(cached_obj, output_obj);
1940                 if (using_split_dwarf) {
1941                         assert(output_dwo);
1942                         get_file_from_cache(cached_dwo, output_dwo);
1943                 }
1944         }
1945         if (produce_dep_file) {
1946                 get_file_from_cache(cached_dep, output_dep);
1947         }
1948         if (generating_coverage && stat(cached_cov, &st) == 0 && st.st_size > 0) {
1949                 // The compiler won't generate notes if there is no code
1950                 get_file_from_cache(cached_cov, output_cov);
1951         }
1952         if (output_dia) {
1953                 get_file_from_cache(cached_dia, output_dia);
1954         }
1955
1956         // Update modification timestamps to save files from LRU cleanup. Also gives
1957         // files a sensible mtime when hard-linking.
1958         update_mtime(cached_obj);
1959         update_mtime(cached_stderr);
1960         if (produce_dep_file) {
1961                 update_mtime(cached_dep);
1962         }
1963         if (generating_coverage) {
1964                 update_mtime(cached_cov);
1965         }
1966         if (output_dia) {
1967                 update_mtime(cached_dia);
1968         }
1969         if (cached_dwo) {
1970                 update_mtime(cached_dwo);
1971         }
1972
1973         send_cached_stderr();
1974
1975         if (put_object_in_manifest) {
1976                 update_manifest_file();
1977         }
1978
1979         // Log the cache hit.
1980         switch (mode) {
1981         case FROMCACHE_DIRECT_MODE:
1982                 cc_log("Succeeded getting cached result");
1983                 stats_update(STATS_CACHEHIT_DIR);
1984                 break;
1985
1986         case FROMCACHE_CPP_MODE:
1987                 cc_log("Succeeded getting cached result");
1988                 stats_update(STATS_CACHEHIT_CPP);
1989                 break;
1990         }
1991
1992         // And exit with the right status code.
1993         x_exit(0);
1994 }
1995
1996 // Find the real compiler. We just search the PATH to find an executable of the
1997 // same name that isn't a link to ourselves.
1998 static void
1999 find_compiler(char **argv)
2000 {
2001         // We might be being invoked like "ccache gcc -c foo.c".
2002         char *base = basename(argv[0]);
2003         if (same_executable_name(base, MYNAME)) {
2004                 args_remove_first(orig_args);
2005                 free(base);
2006                 if (is_full_path(orig_args->argv[0])) {
2007                         // A full path was given.
2008                         return;
2009                 }
2010                 base = basename(orig_args->argv[0]);
2011         }
2012
2013         // Support user override of the compiler.
2014         if (!str_eq(conf->compiler, "")) {
2015                 base = conf->compiler;
2016         }
2017
2018         char *compiler = find_executable(base, MYNAME);
2019         if (!compiler) {
2020                 stats_update(STATS_COMPILER);
2021                 fatal("Could not find compiler \"%s\" in PATH", base);
2022         }
2023         if (str_eq(compiler, argv[0])) {
2024                 fatal("Recursive invocation (the name of the ccache binary must be \"%s\")",
2025                       MYNAME);
2026         }
2027         orig_args->argv[0] = compiler;
2028 }
2029
2030 bool
2031 is_precompiled_header(const char *path)
2032 {
2033         return str_eq(get_extension(path), ".gch")
2034                || str_eq(get_extension(path), ".pch")
2035                || str_eq(get_extension(path), ".pth");
2036 }
2037
2038 static bool
2039 color_output_possible(void)
2040 {
2041         const char *term_env = getenv("TERM");
2042         return isatty(STDERR_FILENO) && term_env && strcasecmp(term_env, "DUMB") != 0;
2043 }
2044
2045 static bool
2046 detect_pch(const char *option, const char *arg, bool *found_pch)
2047 {
2048         struct stat st;
2049
2050         // Try to be smart about detecting precompiled headers.
2051         char *pch_file = NULL;
2052         if (str_eq(option, "-include-pch") || str_eq(option, "-include-pth")) {
2053                 if (stat(arg, &st) == 0) {
2054                         cc_log("Detected use of precompiled header: %s", arg);
2055                         pch_file = x_strdup(arg);
2056                 }
2057         } else {
2058                 char *gchpath = format("%s.gch", arg);
2059                 if (stat(gchpath, &st) == 0) {
2060                         cc_log("Detected use of precompiled header: %s", gchpath);
2061                         pch_file = x_strdup(gchpath);
2062                 } else {
2063                         char *pchpath = format("%s.pch", arg);
2064                         if (stat(pchpath, &st) == 0) {
2065                                 cc_log("Detected use of precompiled header: %s", pchpath);
2066                                 pch_file = x_strdup(pchpath);
2067                         } else {
2068                                 // clang may use pretokenized headers.
2069                                 char *pthpath = format("%s.pth", arg);
2070                                 if (stat(pthpath, &st) == 0) {
2071                                         cc_log("Detected use of pretokenized header: %s", pthpath);
2072                                         pch_file = x_strdup(pthpath);
2073                                 }
2074                                 free(pthpath);
2075                         }
2076                         free(pchpath);
2077                 }
2078                 free(gchpath);
2079         }
2080
2081         if (pch_file) {
2082                 if (included_pch_file) {
2083                         cc_log("Multiple precompiled headers used: %s and %s\n",
2084                                included_pch_file, pch_file);
2085                         stats_update(STATS_ARGS);
2086                         return false;
2087                 }
2088                 included_pch_file = pch_file;
2089                 *found_pch = true;
2090         }
2091         return true;
2092 }
2093
2094 // Process the compiler options into options suitable for passing to the
2095 // preprocessor and the real compiler. The preprocessor options don't include
2096 // -E; this is added later. Returns true on success, otherwise false.
2097 bool
2098 cc_process_args(struct args *args, struct args **preprocessor_args,
2099                 struct args **compiler_args)
2100 {
2101         bool found_c_opt = false;
2102         bool found_S_opt = false;
2103         bool found_pch = false;
2104         bool found_fpch_preprocess = false;
2105         const char *explicit_language = NULL; // As specified with -x.
2106         const char *file_language;            // As deduced from file extension.
2107         const char *actual_language;          // Language to actually use.
2108         const char *input_charset = NULL;
2109         // Is the dependency makefile name overridden with -MF?
2110         bool dependency_filename_specified = false;
2111         // Is the dependency makefile target name specified with -MT or -MQ?
2112         bool dependency_target_specified = false;
2113         // expanded_args is a copy of the original arguments given to the compiler
2114         // but with arguments from @file and similar constructs expanded. It's only
2115         // used as a temporary data structure to loop over.
2116         struct args *expanded_args = args_copy(args);
2117         // stripped_args essentially contains all original arguments except those
2118         // that only should be passed to the preprocessor (if run_second_cpp is
2119         // false) and except dependency options (like -MD and friends).
2120         struct args *stripped_args = args_init(0, NULL);
2121         // cpp_args contains arguments that were not added to stripped_args, i.e.
2122         // those that should only be passed to the preprocessor if run_second_cpp is
2123         // false. If run_second_cpp is true, they will be passed to the compiler as
2124         // well.
2125         struct args *cpp_args = args_init(0, NULL);
2126         // dep_args contains dependency options like -MD. They only passed to the
2127         // preprocessor, never to the compiler.
2128         struct args *dep_args = args_init(0, NULL);
2129
2130         bool found_color_diagnostics = false;
2131
2132         int argc = expanded_args->argc;
2133         char **argv = expanded_args->argv;
2134         args_add(stripped_args, argv[0]);
2135
2136         bool result = true;
2137         for (int i = 1; i < argc; i++) {
2138                 // The user knows best: just swallow the next arg.
2139                 if (str_eq(argv[i], "--ccache-skip")) {
2140                         i++;
2141                         if (i == argc) {
2142                                 cc_log("--ccache-skip lacks an argument");
2143                                 result = false;
2144                                 goto out;
2145                         }
2146                         args_add(stripped_args, argv[i]);
2147                         continue;
2148                 }
2149
2150                 // Special case for -E.
2151                 if (str_eq(argv[i], "-E")) {
2152                         stats_update(STATS_PREPROCESSING);
2153                         result = false;
2154                         goto out;
2155                 }
2156
2157                 // Handle "@file" argument.
2158                 if (str_startswith(argv[i], "@") || str_startswith(argv[i], "-@")) {
2159                         char *argpath = argv[i] + 1;
2160
2161                         if (argpath[-1] == '-') {
2162                                 ++argpath;
2163                         }
2164                         struct args *file_args = args_init_from_gcc_atfile(argpath);
2165                         if (!file_args) {
2166                                 cc_log("Couldn't read arg file %s", argpath);
2167                                 stats_update(STATS_ARGS);
2168                                 result = false;
2169                                 goto out;
2170                         }
2171
2172                         args_insert(expanded_args, i, file_args, true);
2173                         argc = expanded_args->argc;
2174                         argv = expanded_args->argv;
2175                         i--;
2176                         continue;
2177                 }
2178
2179                 // Handle cuda "-optf" and "--options-file" argument.
2180                 if (str_eq(argv[i], "-optf") || str_eq(argv[i], "--options-file")) {
2181                         if (i == argc - 1) {
2182                                 cc_log("Expected argument after %s", argv[i]);
2183                                 stats_update(STATS_ARGS);
2184                                 result = false;
2185                                 goto out;
2186                         }
2187                         ++i;
2188
2189                         // Argument is a comma-separated list of files.
2190                         char *str_start = argv[i];
2191                         char *str_end = strchr(str_start, ',');
2192                         int index = i + 1;
2193
2194                         if (!str_end) {
2195                                 str_end = str_start + strlen(str_start);
2196                         }
2197
2198                         while (str_end) {
2199                                 *str_end = '\0';
2200                                 struct args *file_args = args_init_from_gcc_atfile(str_start);
2201                                 if (!file_args) {
2202                                         cc_log("Couldn't read cuda options file %s", str_start);
2203                                         stats_update(STATS_ARGS);
2204                                         result = false;
2205                                         goto out;
2206                                 }
2207
2208                                 int new_index = file_args->argc + index;
2209                                 args_insert(expanded_args, index, file_args, false);
2210                                 index = new_index;
2211                                 str_start = str_end;
2212                                 str_end = strchr(str_start, ',');
2213                         }
2214
2215                         argc = expanded_args->argc;
2216                         argv = expanded_args->argv;
2217                         continue;
2218                 }
2219
2220                 // These are always too hard.
2221                 if (compopt_too_hard(argv[i]) || str_startswith(argv[i], "-fdump-")) {
2222                         cc_log("Compiler option %s is unsupported", argv[i]);
2223                         stats_update(STATS_UNSUPPORTED_OPTION);
2224                         result = false;
2225                         goto out;
2226                 }
2227
2228                 // These are too hard in direct mode.
2229                 if (conf->direct_mode && compopt_too_hard_for_direct_mode(argv[i])) {
2230                         cc_log("Unsupported compiler option for direct mode: %s", argv[i]);
2231                         conf->direct_mode = false;
2232                 }
2233
2234                 // -Xarch_* options are too hard.
2235                 if (str_startswith(argv[i], "-Xarch_")) {
2236                         cc_log("Unsupported compiler option :%s", argv[i]);
2237                         stats_update(STATS_UNSUPPORTED_OPTION);
2238                         result = false;
2239                         goto out;
2240                 }
2241
2242                 // Handle -arch options.
2243                 if (str_eq(argv[i], "-arch")) {
2244                         if (arch_args_size == MAX_ARCH_ARGS - 1) {
2245                                 cc_log("Too many -arch compiler options; ccache supports at most %d",
2246                                        MAX_ARCH_ARGS);
2247                                 stats_update(STATS_UNSUPPORTED_OPTION);
2248                                 result = false;
2249                                 goto out;
2250                         }
2251
2252                         ++i;
2253                         arch_args[arch_args_size] = x_strdup(argv[i]); // It will leak.
2254                         ++arch_args_size;
2255                         if (arch_args_size == 2) {
2256                                 conf->run_second_cpp = true;
2257                         }
2258                         continue;
2259                 }
2260
2261                 if (str_eq(argv[i], "-fpch-preprocess")
2262                     || str_eq(argv[i], "-emit-pch")
2263                     || str_eq(argv[i], "-emit-pth")) {
2264                         found_fpch_preprocess = true;
2265                 }
2266
2267                 // We must have -c.
2268                 if (str_eq(argv[i], "-c")) {
2269                         found_c_opt = true;
2270                         continue;
2271                 }
2272
2273                 // -S changes the default extension.
2274                 if (str_eq(argv[i], "-S")) {
2275                         args_add(stripped_args, argv[i]);
2276                         found_S_opt = true;
2277                         continue;
2278                 }
2279
2280                 // Special handling for -x: remember the last specified language before the
2281                 // input file and strip all -x options from the arguments.
2282                 if (str_eq(argv[i], "-x")) {
2283                         if (i == argc - 1) {
2284                                 cc_log("Missing argument to %s", argv[i]);
2285                                 stats_update(STATS_ARGS);
2286                                 result = false;
2287                                 goto out;
2288                         }
2289                         if (!input_file) {
2290                                 explicit_language = argv[i+1];
2291                         }
2292                         i++;
2293                         continue;
2294                 }
2295                 if (str_startswith(argv[i], "-x")) {
2296                         if (!input_file) {
2297                                 explicit_language = &argv[i][2];
2298                         }
2299                         continue;
2300                 }
2301
2302                 // We need to work out where the output was meant to go.
2303                 if (str_eq(argv[i], "-o")) {
2304                         if (i == argc - 1) {
2305                                 cc_log("Missing argument to %s", argv[i]);
2306                                 stats_update(STATS_ARGS);
2307                                 result = false;
2308                                 goto out;
2309                         }
2310                         output_obj = make_relative_path(x_strdup(argv[i+1]));
2311                         i++;
2312                         continue;
2313                 }
2314
2315                 // Alternate form of -o with no space.
2316                 if (str_startswith(argv[i], "-o")) {
2317                         output_obj = make_relative_path(x_strdup(&argv[i][2]));
2318                         continue;
2319                 }
2320
2321                 if (str_eq(argv[i], "-gsplit-dwarf")) {
2322                         cc_log("Enabling caching of dwarf files since -gsplit-dwarf is used");
2323                         using_split_dwarf = true;
2324                         args_add(stripped_args, argv[i]);
2325                         continue;
2326                 }
2327                 if (str_startswith(argv[i], "-fdebug-prefix-map=")) {
2328                         debug_prefix_maps = x_realloc(
2329                                 debug_prefix_maps,
2330                                 (debug_prefix_maps_len + 1) * sizeof(char *));
2331                         debug_prefix_maps[debug_prefix_maps_len++] = x_strdup(argv[i] + 19);
2332                         args_add(stripped_args, argv[i]);
2333                         continue;
2334                 }
2335
2336                 // Debugging is handled specially, so that we know if we can strip line
2337                 // number info.
2338                 if (str_startswith(argv[i], "-g")) {
2339                         generating_debuginfo = true;
2340                         args_add(stripped_args, argv[i]);
2341                         if (conf->unify && !str_eq(argv[i], "-g0")) {
2342                                 cc_log("%s used; disabling unify mode", argv[i]);
2343                                 conf->unify = false;
2344                         }
2345                         if (str_eq(argv[i], "-g3")) {
2346                                 cc_log("%s used; not compiling preprocessed code", argv[i]);
2347                                 conf->run_second_cpp = true;
2348                         }
2349                         continue;
2350                 }
2351
2352                 // These options require special handling, because they behave differently
2353                 // with gcc -E, when the output file is not specified.
2354                 if (str_eq(argv[i], "-MD") || str_eq(argv[i], "-MMD")) {
2355                         generating_dependencies = true;
2356                         args_add(dep_args, argv[i]);
2357                         continue;
2358                 }
2359                 if (str_startswith(argv[i], "-MF")) {
2360                         dependency_filename_specified = true;
2361                         free(output_dep);
2362
2363                         char *arg;
2364                         bool separate_argument = (strlen(argv[i]) == 3);
2365                         if (separate_argument) {
2366                                 // -MF arg
2367                                 if (i == argc - 1) {
2368                                         cc_log("Missing argument to %s", argv[i]);
2369                                         stats_update(STATS_ARGS);
2370                                         result = false;
2371                                         goto out;
2372                                 }
2373                                 arg = argv[i + 1];
2374                                 i++;
2375                         } else {
2376                                 // -MFarg
2377                                 arg = &argv[i][3];
2378                         }
2379                         output_dep = make_relative_path(x_strdup(arg));
2380                         // Keep the format of the args the same.
2381                         if (separate_argument) {
2382                                 args_add(dep_args, "-MF");
2383                                 args_add(dep_args, output_dep);
2384                         } else {
2385                                 char *option = format("-MF%s", output_dep);
2386                                 args_add(dep_args, option);
2387                                 free(option);
2388                         }
2389                         continue;
2390                 }
2391                 if (str_startswith(argv[i], "-MQ") || str_startswith(argv[i], "-MT")) {
2392                         dependency_target_specified = true;
2393
2394                         char *relpath;
2395                         if (strlen(argv[i]) == 3) {
2396                                 // -MQ arg or -MT arg
2397                                 if (i == argc - 1) {
2398                                         cc_log("Missing argument to %s", argv[i]);
2399                                         stats_update(STATS_ARGS);
2400                                         result = false;
2401                                         goto out;
2402                                 }
2403                                 args_add(dep_args, argv[i]);
2404                                 relpath = make_relative_path(x_strdup(argv[i + 1]));
2405                                 args_add(dep_args, relpath);
2406                                 free(relpath);
2407                                 i++;
2408                         } else {
2409                                 char *arg_opt = x_strndup(argv[i], 3);
2410                                 relpath = make_relative_path(x_strdup(argv[i] + 3));
2411                                 char *option = format("%s%s", arg_opt, relpath);
2412                                 args_add(dep_args, option);
2413                                 free(arg_opt);
2414                                 free(relpath);
2415                                 free(option);
2416                         }
2417                         continue;
2418                 }
2419                 if (str_eq(argv[i], "-fprofile-arcs")) {
2420                         profile_arcs = true;
2421                         args_add(stripped_args, argv[i]);
2422                         continue;
2423                 }
2424                 if (str_eq(argv[i], "-ftest-coverage")) {
2425                         generating_coverage = true;
2426                         args_add(stripped_args, argv[i]);
2427                         continue;
2428                 }
2429                 if (str_eq(argv[i], "--coverage") // = -fprofile-arcs -ftest-coverage
2430                     || str_eq(argv[i], "-coverage")) { // Undocumented but still works.
2431                         profile_arcs = true;
2432                         generating_coverage = true;
2433                         args_add(stripped_args, argv[i]);
2434                         continue;
2435                 }
2436                 if (str_startswith(argv[i], "-fprofile-dir=")) {
2437                         profile_dir = x_strdup(argv[i] + 14);
2438                         args_add(stripped_args, argv[i]);
2439                         continue;
2440                 }
2441                 if (str_startswith(argv[i], "--sysroot=")) {
2442                         char *relpath = make_relative_path(x_strdup(argv[i] + 10));
2443                         char *option = format("--sysroot=%s", relpath);
2444                         args_add(stripped_args, option);
2445                         free(relpath);
2446                         free(option);
2447                         continue;
2448                 }
2449                 if (str_startswith(argv[i], "-Wp,")) {
2450                         if (str_eq(argv[i], "-Wp,-P")
2451                             || strstr(argv[i], ",-P,")
2452                             || str_endswith(argv[i], ",-P")) {
2453                                 // -P removes preprocessor information in such a way that the object
2454                                 // file from compiling the preprocessed file will not be equal to the
2455                                 // object file produced when compiling without ccache.
2456                                 cc_log("Too hard option -Wp,-P detected");
2457                                 stats_update(STATS_UNSUPPORTED_OPTION);
2458                                 failed();
2459                         } else if (str_startswith(argv[i], "-Wp,-MD,")
2460                                    && !strchr(argv[i] + 8, ',')) {
2461                                 generating_dependencies = true;
2462                                 dependency_filename_specified = true;
2463                                 free(output_dep);
2464                                 output_dep = make_relative_path(x_strdup(argv[i] + 8));
2465                                 args_add(dep_args, argv[i]);
2466                                 continue;
2467                         } else if (str_startswith(argv[i], "-Wp,-MMD,")
2468                                    && !strchr(argv[i] + 9, ',')) {
2469                                 generating_dependencies = true;
2470                                 dependency_filename_specified = true;
2471                                 free(output_dep);
2472                                 output_dep = make_relative_path(x_strdup(argv[i] + 9));
2473                                 args_add(dep_args, argv[i]);
2474                                 continue;
2475                         } else if (str_startswith(argv[i], "-Wp,-D")
2476                                    && !strchr(argv[i] + 6, ',')) {
2477                                 // Treat it like -D.
2478                                 args_add(cpp_args, argv[i] + 4);
2479                                 continue;
2480                         } else if (str_eq(argv[i], "-Wp,-MP")
2481                                    || (strlen(argv[i]) > 8
2482                                        && str_startswith(argv[i], "-Wp,-M")
2483                                        && argv[i][7] == ','
2484                                        && (argv[i][6] == 'F'
2485                                            || argv[i][6] == 'Q'
2486                                            || argv[i][6] == 'T')
2487                                        && !strchr(argv[i] + 8, ','))) {
2488                                 // TODO: Make argument to MF/MQ/MT relative.
2489                                 args_add(dep_args, argv[i]);
2490                                 continue;
2491                         } else if (conf->direct_mode) {
2492                                 // -Wp, can be used to pass too hard options to the preprocessor.
2493                                 // Hence, disable direct mode.
2494                                 cc_log("Unsupported compiler option for direct mode: %s", argv[i]);
2495                                 conf->direct_mode = false;
2496                         }
2497
2498                         // Any other -Wp,* arguments are only relevant for the preprocessor.
2499                         args_add(cpp_args, argv[i]);
2500                         continue;
2501                 }
2502                 if (str_eq(argv[i], "-MP")) {
2503                         args_add(dep_args, argv[i]);
2504                         continue;
2505                 }
2506
2507                 // Input charset needs to be handled specially.
2508                 if (str_startswith(argv[i], "-finput-charset=")) {
2509                         input_charset = argv[i];
2510                         continue;
2511                 }
2512
2513                 if (str_eq(argv[i], "--serialize-diagnostics")) {
2514                         if (i == argc - 1) {
2515                                 cc_log("Missing argument to %s", argv[i]);
2516                                 stats_update(STATS_ARGS);
2517                                 result = false;
2518                                 goto out;
2519                         }
2520                         output_dia = make_relative_path(x_strdup(argv[i+1]));
2521                         i++;
2522                         continue;
2523                 }
2524
2525                 if (str_startswith(argv[i], "-fprofile-")) {
2526                         char *arg = x_strdup(argv[i]);
2527                         const char *arg_profile_dir = strchr(argv[i], '=');
2528                         if (arg_profile_dir) {
2529                                 // Convert to absolute path.
2530                                 char *dir = x_realpath(arg_profile_dir + 1);
2531                                 if (!dir) {
2532                                         // Directory doesn't exist.
2533                                         dir = x_strdup(arg_profile_dir + 1);
2534                                 }
2535
2536                                 // We can get a better hit rate by using the real path here.
2537                                 free(arg);
2538                                 char *option = x_strndup(argv[i], arg_profile_dir - argv[i]);
2539                                 arg = format("%s=%s", option, dir);
2540                                 cc_log("Rewriting %s to %s", argv[i], arg);
2541                                 free(option);
2542                                 free(dir);
2543                         }
2544
2545                         bool supported_profile_option = false;
2546                         if (str_startswith(argv[i], "-fprofile-generate")
2547                             || str_eq(argv[i], "-fprofile-arcs")) {
2548                                 profile_generate = true;
2549                                 supported_profile_option = true;
2550                         } else if (str_startswith(argv[i], "-fprofile-use")
2551                                    || str_eq(argv[i], "-fbranch-probabilities")) {
2552                                 profile_use = true;
2553                                 supported_profile_option = true;
2554                         } else if (str_eq(argv[i], "-fprofile-dir")) {
2555                                 supported_profile_option = true;
2556                         }
2557
2558                         if (supported_profile_option) {
2559                                 args_add(stripped_args, arg);
2560                                 free(arg);
2561
2562                                 // If the profile directory has already been set, give up... Hard to
2563                                 // know what the user means, and what the compiler will do.
2564                                 if (arg_profile_dir && profile_dir) {
2565                                         cc_log("Profile directory already set; giving up");
2566                                         result = false;
2567                                         goto out;
2568                                 } else if (arg_profile_dir) {
2569                                         cc_log("Setting profile directory to %s", profile_dir);
2570                                         profile_dir = x_strdup(arg_profile_dir);
2571                                 }
2572                                 continue;
2573                         }
2574                         cc_log("Unknown profile option: %s", argv[i]);
2575                         free(arg);
2576                 }
2577
2578                 if (str_eq(argv[i], "-fcolor-diagnostics")
2579                     || str_eq(argv[i], "-fno-color-diagnostics")
2580                     || str_eq(argv[i], "-fdiagnostics-color")
2581                     || str_eq(argv[i], "-fdiagnostics-color=always")
2582                     || str_eq(argv[i], "-fno-diagnostics-color")
2583                     || str_eq(argv[i], "-fdiagnostics-color=never")) {
2584                         args_add(stripped_args, argv[i]);
2585                         found_color_diagnostics = true;
2586                         continue;
2587                 }
2588                 if (str_eq(argv[i], "-fdiagnostics-color=auto")) {
2589                         if (color_output_possible()) {
2590                                 // Output is redirected, so color output must be forced.
2591                                 args_add(stripped_args, "-fdiagnostics-color=always");
2592                                 cc_log("Automatically forcing colors");
2593                         } else {
2594                                 args_add(stripped_args, argv[i]);
2595                         }
2596                         found_color_diagnostics = true;
2597                         continue;
2598                 }
2599
2600                 // Options taking an argument that we may want to rewrite to relative paths
2601                 // to get better hit rate. A secondary effect is that paths in the standard
2602                 // error output produced by the compiler will be normalized.
2603                 if (compopt_takes_path(argv[i])) {
2604                         if (i == argc - 1) {
2605                                 cc_log("Missing argument to %s", argv[i]);
2606                                 stats_update(STATS_ARGS);
2607                                 result = false;
2608                                 goto out;
2609                         }
2610
2611                         if (!detect_pch(argv[i], argv[i+1], &found_pch)) {
2612                                 result = false;
2613                                 goto out;
2614                         }
2615
2616                         char *relpath = make_relative_path(x_strdup(argv[i+1]));
2617                         if (compopt_affects_cpp(argv[i])) {
2618                                 args_add(cpp_args, argv[i]);
2619                                 args_add(cpp_args, relpath);
2620                         } else {
2621                                 args_add(stripped_args, argv[i]);
2622                                 args_add(stripped_args, relpath);
2623                         }
2624                         free(relpath);
2625
2626                         i++;
2627                         continue;
2628                 }
2629
2630                 // Same as above but options with concatenated argument beginning with a
2631                 // slash.
2632                 if (argv[i][0] == '-') {
2633                         char *slash_pos = strchr(argv[i], '/');
2634                         if (slash_pos) {
2635                                 char *option = x_strndup(argv[i], slash_pos - argv[i]);
2636                                 if (compopt_takes_concat_arg(option) && compopt_takes_path(option)) {
2637                                         char *relpath = make_relative_path(x_strdup(slash_pos));
2638                                         char *new_option = format("%s%s", option, relpath);
2639                                         if (compopt_affects_cpp(option)) {
2640                                                 args_add(cpp_args, new_option);
2641                                         } else {
2642                                                 args_add(stripped_args, new_option);
2643                                         }
2644                                         free(new_option);
2645                                         free(relpath);
2646                                         free(option);
2647                                         continue;
2648                                 } else {
2649                                         free(option);
2650                                 }
2651                         }
2652                 }
2653
2654                 // Options that take an argument.
2655                 if (compopt_takes_arg(argv[i])) {
2656                         if (i == argc - 1) {
2657                                 cc_log("Missing argument to %s", argv[i]);
2658                                 stats_update(STATS_ARGS);
2659                                 result = false;
2660                                 goto out;
2661                         }
2662
2663                         if (compopt_affects_cpp(argv[i])) {
2664                                 args_add(cpp_args, argv[i]);
2665                                 args_add(cpp_args, argv[i+1]);
2666                         } else {
2667                                 args_add(stripped_args, argv[i]);
2668                                 args_add(stripped_args, argv[i+1]);
2669                         }
2670
2671                         i++;
2672                         continue;
2673                 }
2674
2675                 // Other options.
2676                 if (argv[i][0] == '-') {
2677                         if (compopt_affects_cpp(argv[i])
2678                             || compopt_prefix_affects_cpp(argv[i])) {
2679                                 args_add(cpp_args, argv[i]);
2680                         } else {
2681                                 args_add(stripped_args, argv[i]);
2682                         }
2683                         continue;
2684                 }
2685
2686                 // If an argument isn't a plain file then assume its an option, not an
2687                 // input file. This allows us to cope better with unusual compiler options.
2688                 struct stat st;
2689                 if (stat(argv[i], &st) != 0 || !S_ISREG(st.st_mode)) {
2690                         cc_log("%s is not a regular file, not considering as input file",
2691                                argv[i]);
2692                         args_add(stripped_args, argv[i]);
2693                         continue;
2694                 }
2695
2696                 if (input_file) {
2697                         if (language_for_file(argv[i])) {
2698                                 cc_log("Multiple input files: %s and %s", input_file, argv[i]);
2699                                 stats_update(STATS_MULTIPLE);
2700                         } else if (!found_c_opt) {
2701                                 cc_log("Called for link with %s", argv[i]);
2702                                 if (strstr(argv[i], "conftest.")) {
2703                                         stats_update(STATS_CONFTEST);
2704                                 } else {
2705                                         stats_update(STATS_LINK);
2706                                 }
2707                         } else {
2708                                 cc_log("Unsupported source extension: %s", argv[i]);
2709                                 stats_update(STATS_SOURCELANG);
2710                         }
2711                         result = false;
2712                         goto out;
2713                 }
2714
2715                 // The source code file path gets put into the notes.
2716                 if (generating_coverage) {
2717                         input_file = x_strdup(argv[i]);
2718                         continue;
2719                 }
2720
2721                 if (is_symlink(argv[i])) {
2722                         // Don't rewrite source file path if it's a symlink since
2723                         // make_relative_path resolves symlinks using realpath(3) and this leads
2724                         // to potentially choosing incorrect relative header files. See the
2725                         // "symlink to source file" test.
2726                         input_file = x_strdup(argv[i]);
2727                 } else {
2728                         // Rewrite to relative to increase hit rate.
2729                         input_file = make_relative_path(x_strdup(argv[i]));
2730                 }
2731         } // for
2732
2733         if (found_S_opt) {
2734                 // Even if -gsplit-dwarf is given, the .dwo file is not generated when -S
2735                 // is also given.
2736                 using_split_dwarf = false;
2737                 cc_log("Disabling caching of dwarf files since -S is used");
2738         }
2739
2740         if (!input_file) {
2741                 cc_log("No input file found");
2742                 stats_update(STATS_NOINPUT);
2743                 result = false;
2744                 goto out;
2745         }
2746
2747         if (found_pch || found_fpch_preprocess) {
2748                 using_precompiled_header = true;
2749                 if (!(conf->sloppiness & SLOPPY_TIME_MACROS)) {
2750                         cc_log("You have to specify \"time_macros\" sloppiness when using"
2751                                " precompiled headers to get direct hits");
2752                         cc_log("Disabling direct mode");
2753                         stats_update(STATS_CANTUSEPCH);
2754                         result = false;
2755                         goto out;
2756                 }
2757         }
2758
2759         if (explicit_language && str_eq(explicit_language, "none")) {
2760                 explicit_language = NULL;
2761         }
2762         file_language = language_for_file(input_file);
2763         if (explicit_language) {
2764                 if (!language_is_supported(explicit_language)) {
2765                         cc_log("Unsupported language: %s", explicit_language);
2766                         stats_update(STATS_SOURCELANG);
2767                         result = false;
2768                         goto out;
2769                 }
2770                 actual_language = explicit_language;
2771         } else {
2772                 actual_language = file_language;
2773         }
2774
2775         output_is_precompiled_header =
2776           actual_language && strstr(actual_language, "-header");
2777
2778         if (output_is_precompiled_header
2779             && !(conf->sloppiness & SLOPPY_PCH_DEFINES)) {
2780                 cc_log("You have to specify \"pch_defines,time_macros\" sloppiness when"
2781                        " creating precompiled headers");
2782                 stats_update(STATS_CANTUSEPCH);
2783                 result = false;
2784                 goto out;
2785         }
2786
2787         if (!found_c_opt && !found_S_opt) {
2788                 if (output_is_precompiled_header) {
2789                         args_add(stripped_args, "-c");
2790                 } else {
2791                         cc_log("No -c option found");
2792                         // I find that having a separate statistic for autoconf tests is useful,
2793                         // as they are the dominant form of "called for link" in many cases.
2794                         if (strstr(input_file, "conftest.")) {
2795                                 stats_update(STATS_CONFTEST);
2796                         } else {
2797                                 stats_update(STATS_LINK);
2798                         }
2799                         result = false;
2800                         goto out;
2801                 }
2802         }
2803
2804         if (!actual_language) {
2805                 cc_log("Unsupported source extension: %s", input_file);
2806                 stats_update(STATS_SOURCELANG);
2807                 result = false;
2808                 goto out;
2809         }
2810
2811         direct_i_file = language_is_preprocessed(actual_language);
2812
2813         if (output_is_precompiled_header && !conf->run_second_cpp) {
2814                 // It doesn't work to create the .gch from preprocessed source.
2815                 cc_log("Creating precompiled header; not compiling preprocessed code");
2816                 conf->run_second_cpp = true;
2817         }
2818
2819         if (str_eq(conf->cpp_extension, "")) {
2820                 const char *p_language = p_language_for_language(actual_language);
2821                 free(conf->cpp_extension);
2822                 conf->cpp_extension = x_strdup(extension_for_language(p_language) + 1);
2823         }
2824
2825         // Don't try to second guess the compilers heuristics for stdout handling.
2826         if (output_obj && str_eq(output_obj, "-")) {
2827                 stats_update(STATS_OUTSTDOUT);
2828                 cc_log("Output file is -");
2829                 result = false;
2830                 goto out;
2831         }
2832
2833         if (!output_obj) {
2834                 if (output_is_precompiled_header) {
2835                         output_obj = format("%s.gch", input_file);
2836                 } else {
2837                         output_obj = basename(input_file);
2838                         char *p = strrchr(output_obj, '.');
2839                         if (!p || !p[1]) {
2840                                 cc_log("Badly formed object filename");
2841                                 stats_update(STATS_ARGS);
2842                                 result = false;
2843                                 goto out;
2844                         }
2845                         p[1] = found_S_opt ? 's' : 'o';
2846                         p[2] = 0;
2847                 }
2848         }
2849
2850         if (using_split_dwarf) {
2851                 char *p = strrchr(output_obj, '.');
2852                 if (!p || !p[1]) {
2853                         cc_log("Badly formed object filename");
2854                         stats_update(STATS_ARGS);
2855                         result = false;
2856                         goto out;
2857                 }
2858
2859                 char *base_name = remove_extension(output_obj);
2860                 output_dwo = format("%s.dwo", base_name);
2861                 free(base_name);
2862         }
2863
2864         // Cope with -o /dev/null.
2865         struct stat st;
2866         if (!str_eq(output_obj, "/dev/null")
2867             && stat(output_obj, &st) == 0
2868             && !S_ISREG(st.st_mode)) {
2869                 cc_log("Not a regular file: %s", output_obj);
2870                 stats_update(STATS_DEVICE);
2871                 result = false;
2872                 goto out;
2873         }
2874
2875         // Some options shouldn't be passed to the real compiler when it compiles
2876         // preprocessed code:
2877         //
2878         // -finput-charset=XXX (otherwise conversion happens twice)
2879         // -x XXX (otherwise the wrong language is selected)
2880         if (input_charset) {
2881                 args_add(cpp_args, input_charset);
2882         }
2883         if (found_pch) {
2884                 args_add(cpp_args, "-fpch-preprocess");
2885         }
2886         if (explicit_language) {
2887                 args_add(cpp_args, "-x");
2888                 args_add(cpp_args, explicit_language);
2889         }
2890
2891         // Since output is redirected, compilers will not color their output by
2892         // default, so force it explicitly if it would be otherwise done.
2893         if (!found_color_diagnostics && color_output_possible()) {
2894                 if (compiler_is_clang(args)) {
2895                         if (!str_eq(actual_language, "assembler")) {
2896                                 args_add(stripped_args, "-fcolor-diagnostics");
2897                                 cc_log("Automatically enabling colors");
2898                         }
2899                 } else if (compiler_is_gcc(args)) {
2900                         // GCC has it since 4.9, but that'd require detecting what GCC version is
2901                         // used for the actual compile. However it requires also GCC_COLORS to be
2902                         // set (and not empty), so use that for detecting if GCC would use
2903                         // colors.
2904                         if (getenv("GCC_COLORS") && getenv("GCC_COLORS")[0] != '\0') {
2905                                 args_add(stripped_args, "-fdiagnostics-color");
2906                                 cc_log("Automatically enabling colors");
2907                         }
2908                 }
2909         }
2910
2911         // Add flags for dependency generation only to the preprocessor command line.
2912         if (generating_dependencies) {
2913                 if (!dependency_filename_specified) {
2914                         char *base_name = remove_extension(output_obj);
2915                         char *default_depfile_name = format("%s.d", base_name);
2916                         free(base_name);
2917                         args_add(dep_args, "-MF");
2918                         args_add(dep_args, default_depfile_name);
2919                         output_dep = make_relative_path(x_strdup(default_depfile_name));
2920                 }
2921
2922                 if (!dependency_target_specified) {
2923                         args_add(dep_args, "-MQ");
2924                         args_add(dep_args, output_obj);
2925                 }
2926         }
2927         if (generating_coverage) {
2928                 char *base_name = remove_extension(output_obj);
2929                 char *default_covfile_name = format("%s.gcno", base_name);
2930                 free(base_name);
2931                 output_cov = make_relative_path(x_strdup(default_covfile_name));
2932         }
2933
2934         *compiler_args = args_copy(stripped_args);
2935         if (conf->run_second_cpp) {
2936                 args_extend(*compiler_args, cpp_args);
2937         } else if (explicit_language) {
2938                 // Workaround for a bug in Apple's patched distcc -- it doesn't properly
2939                 // reset the language specified with -x, so if -x is given, we have to
2940                 // specify the preprocessed language explicitly.
2941                 args_add(*compiler_args, "-x");
2942                 args_add(*compiler_args, p_language_for_language(explicit_language));
2943         }
2944
2945         if (found_c_opt) {
2946                 args_add(*compiler_args, "-c");
2947         }
2948
2949         for (size_t i = 0; i < arch_args_size; ++i) {
2950                 args_add(*compiler_args, "-arch");
2951                 args_add(*compiler_args, arch_args[i]);
2952         }
2953
2954         // Only pass dependency arguments to the preprocesor since Intel's C++
2955         // compiler doesn't produce a correct .d file when compiling preprocessed
2956         // source.
2957         args_extend(cpp_args, dep_args);
2958
2959         *preprocessor_args = args_copy(stripped_args);
2960         args_extend(*preprocessor_args, cpp_args);
2961
2962 out:
2963         args_free(expanded_args);
2964         args_free(stripped_args);
2965         args_free(dep_args);
2966         args_free(cpp_args);
2967         return result;
2968 }
2969
2970 static void
2971 create_initial_config_file(struct conf *conf, const char *path)
2972 {
2973         if (create_parent_dirs(path) != 0) {
2974                 return;
2975         }
2976
2977         unsigned max_files;
2978         uint64_t max_size;
2979         char *stats_dir = format("%s/0", conf->cache_dir);
2980         struct stat st;
2981         if (stat(stats_dir, &st) == 0) {
2982                 stats_get_obsolete_limits(stats_dir, &max_files, &max_size);
2983                 // STATS_MAXFILES and STATS_MAXSIZE was stored for each top directory.
2984                 max_files *= 16;
2985                 max_size *= 16;
2986         } else {
2987                 max_files = 0;
2988                 max_size = conf->max_size;
2989         }
2990         free(stats_dir);
2991
2992         FILE *f = fopen(path, "w");
2993         if (!f) {
2994                 return;
2995         }
2996         if (max_files != 0) {
2997                 fprintf(f, "max_files = %u\n", max_files);
2998                 conf->max_files = max_files;
2999         }
3000         if (max_size != 0) {
3001                 char *size = format_parsable_size_with_suffix(max_size);
3002                 fprintf(f, "max_size = %s\n", size);
3003                 free(size);
3004                 conf->max_size = max_size;
3005         }
3006         fclose(f);
3007 }
3008
3009 // Read config file(s), populate variables, create configuration file in cache
3010 // directory if missing, etc.
3011 static void
3012 initialize(void)
3013 {
3014         conf_free(conf);
3015         conf = conf_create();
3016
3017         char *errmsg;
3018         struct stat st;
3019         char *p = getenv("CCACHE_CONFIGPATH");
3020         if (p) {
3021                 primary_config_path = x_strdup(p);
3022         } else {
3023                 secondary_config_path = format("%s/ccache.conf", TO_STRING(SYSCONFDIR));
3024                 if (!conf_read(conf, secondary_config_path, &errmsg)) {
3025                         if (stat(secondary_config_path, &st) == 0) {
3026                                 fatal("%s", errmsg);
3027                         }
3028                         // Missing config file in SYSCONFDIR is OK.
3029                         free(errmsg);
3030                 }
3031
3032                 if (str_eq(conf->cache_dir, "")) {
3033                         fatal("configuration setting \"cache_dir\" must not be the empty string");
3034                 }
3035                 if ((p = getenv("CCACHE_DIR"))) {
3036                         free(conf->cache_dir);
3037                         conf->cache_dir = strdup(p);
3038                 }
3039                 if (str_eq(conf->cache_dir, "")) {
3040                         fatal("CCACHE_DIR must not be the empty string");
3041                 }
3042
3043                 primary_config_path = format("%s/ccache.conf", conf->cache_dir);
3044         }
3045
3046         bool should_create_initial_config = false;
3047         if (!conf_read(conf, primary_config_path, &errmsg)) {
3048                 if (stat(primary_config_path, &st) == 0) {
3049                         fatal("%s", errmsg);
3050                 }
3051                 should_create_initial_config = true;
3052         }
3053
3054         if (!conf_update_from_environment(conf, &errmsg)) {
3055                 fatal("%s", errmsg);
3056         }
3057
3058         if (conf->disable) {
3059                 should_create_initial_config = false;
3060         }
3061
3062         if (should_create_initial_config) {
3063                 create_initial_config_file(conf, primary_config_path);
3064         }
3065
3066         exitfn_init();
3067         exitfn_add_nullary(stats_flush);
3068         exitfn_add_nullary(clean_up_pending_tmp_files);
3069
3070         cc_log("=== CCACHE %s STARTED =========================================",
3071                CCACHE_VERSION);
3072
3073         if (conf->umask != UINT_MAX) {
3074                 umask(conf->umask);
3075         }
3076 }
3077
3078 // Reset the global state. Used by the test suite.
3079 void
3080 cc_reset(void)
3081 {
3082         conf_free(conf); conf = NULL;
3083         free(primary_config_path); primary_config_path = NULL;
3084         free(secondary_config_path); secondary_config_path = NULL;
3085         free(current_working_dir); current_working_dir = NULL;
3086         for (size_t i = 0; i < debug_prefix_maps_len; i++) {
3087                 free(debug_prefix_maps[i]);
3088                 debug_prefix_maps[i] = NULL;
3089         }
3090         free(debug_prefix_maps); debug_prefix_maps = NULL;
3091         debug_prefix_maps_len = 0;
3092         free(profile_dir); profile_dir = NULL;
3093         free(included_pch_file); included_pch_file = NULL;
3094         args_free(orig_args); orig_args = NULL;
3095         free(input_file); input_file = NULL;
3096         free(output_obj); output_obj = NULL;
3097         free(output_dwo); output_dwo = NULL;
3098         free(output_dep); output_dep = NULL;
3099         free(output_cov); output_cov = NULL;
3100         free(output_dia); output_dia = NULL;
3101         free(cached_obj_hash); cached_obj_hash = NULL;
3102         free(cached_obj); cached_obj = NULL;
3103         free(cached_dwo); cached_dwo = NULL;
3104         free(cached_stderr); cached_stderr = NULL;
3105         free(cached_dep); cached_dep = NULL;
3106         free(cached_cov); cached_cov = NULL;
3107         free(cached_dia); cached_dia = NULL;
3108         free(manifest_path); manifest_path = NULL;
3109         time_of_compilation = 0;
3110         for (size_t i = 0; i < ignore_headers_len; i++) {
3111                 free(ignore_headers[i]);
3112                 ignore_headers[i] = NULL;
3113         }
3114         free(ignore_headers); ignore_headers = NULL;
3115         ignore_headers_len = 0;
3116         if (included_files) {
3117                 hashtable_destroy(included_files, 1); included_files = NULL;
3118         }
3119         has_absolute_include_headers = false;
3120         generating_debuginfo = false;
3121         generating_dependencies = false;
3122         generating_coverage = false;
3123         profile_arcs = false;
3124         free(profile_dir); profile_dir = NULL;
3125         i_tmpfile = NULL;
3126         direct_i_file = false;
3127         free(cpp_stderr); cpp_stderr = NULL;
3128         free(stats_file); stats_file = NULL;
3129         output_is_precompiled_header = false;
3130
3131         conf = conf_create();
3132         using_split_dwarf = false;
3133 }
3134
3135 // Make a copy of stderr that will not be cached, so things like distcc can
3136 // send networking errors to it.
3137 static void
3138 setup_uncached_err(void)
3139 {
3140         int uncached_fd = dup(2);
3141         set_cloexec_flag(uncached_fd);
3142         if (uncached_fd == -1) {
3143                 cc_log("dup(2) failed: %s", strerror(errno));
3144                 failed();
3145         }
3146
3147         // Leak a pointer to the environment.
3148         char *buf = format("UNCACHED_ERR_FD=%d", uncached_fd);
3149         if (putenv(buf) == -1) {
3150                 cc_log("putenv failed: %s", strerror(errno));
3151                 failed();
3152         }
3153 }
3154
3155 static void
3156 configuration_logger(const char *descr, const char *origin, void *context)
3157 {
3158         (void)context;
3159         cc_bulklog("Config: (%s) %s", origin, descr);
3160 }
3161
3162 // The main ccache driver function.
3163 static void
3164 ccache(int argc, char *argv[])
3165 {
3166 #ifndef _WIN32
3167         set_up_signal_handlers();
3168 #endif
3169
3170         orig_args = args_init(argc, argv);
3171
3172         initialize();
3173         find_compiler(argv);
3174
3175         if (str_eq(conf->temporary_dir, "")) {
3176                 clean_up_internal_tempdir();
3177         }
3178
3179         if (!str_eq(conf->log_file, "")) {
3180                 conf_print_items(conf, configuration_logger, NULL);
3181         }
3182
3183         if (conf->disable) {
3184                 cc_log("ccache is disabled");
3185                 failed();
3186         }
3187
3188         setup_uncached_err();
3189
3190         cc_log_argv("Command line: ", argv);
3191         cc_log("Hostname: %s", get_hostname());
3192         cc_log("Working directory: %s", get_current_working_dir());
3193
3194         if (conf->unify) {
3195                 cc_log("Direct mode disabled because unify mode is enabled");
3196                 conf->direct_mode = false;
3197         }
3198
3199         conf->limit_multiple = MIN(MAX(conf->limit_multiple, 0.0), 1.0);
3200
3201         // Arguments (except -E) to send to the preprocessor.
3202         struct args *preprocessor_args;
3203         // Arguments to send to the real compiler.
3204         struct args *compiler_args;
3205         if (!cc_process_args(orig_args, &preprocessor_args, &compiler_args)) {
3206                 failed();
3207         }
3208
3209         cc_log("Source file: %s", input_file);
3210         if (generating_dependencies) {
3211                 cc_log("Dependency file: %s", output_dep);
3212         }
3213         if (generating_coverage) {
3214                 cc_log("Coverage file: %s", output_cov);
3215         }
3216         if (output_dia) {
3217                 cc_log("Diagnostic file: %s", output_dia);
3218         }
3219
3220         if (using_split_dwarf) {
3221                 if (!generating_dependencies) {
3222                         assert(output_dwo);
3223                 }
3224         } else {
3225                 assert(!output_dwo);
3226         }
3227
3228         if (output_dwo) {
3229                 cc_log("Split dwarf file: %s", output_dwo);
3230         }
3231
3232         cc_log("Object file: %s", output_obj);
3233
3234         struct mdfour common_hash;
3235         hash_start(&common_hash);
3236         calculate_common_hash(preprocessor_args, &common_hash);
3237
3238         // Try to find the hash using the manifest.
3239         struct mdfour direct_hash = common_hash;
3240         bool put_object_in_manifest = false;
3241         struct file_hash *object_hash = NULL;
3242         struct file_hash *object_hash_from_manifest = NULL;
3243         if (conf->direct_mode) {
3244                 cc_log("Trying direct lookup");
3245                 object_hash = calculate_object_hash(preprocessor_args, &direct_hash, 1);
3246                 if (object_hash) {
3247                         update_cached_result_globals(object_hash);
3248
3249                         // If we can return from cache at this point then do so.
3250                         from_cache(FROMCACHE_DIRECT_MODE, 0);
3251
3252                         // Wasn't able to return from cache at this point. However, the object
3253                         // was already found in manifest, so don't readd it later.
3254                         put_object_in_manifest = false;
3255
3256                         object_hash_from_manifest = object_hash;
3257                 } else {
3258                         // Add object to manifest later.
3259                         put_object_in_manifest = true;
3260                 }
3261         }
3262
3263         if (conf->read_only_direct) {
3264                 cc_log("Read-only direct mode; running real compiler");
3265                 failed();
3266         }
3267
3268         // Find the hash using the preprocessed output. Also updates included_files.
3269         struct mdfour cpp_hash = common_hash;
3270         object_hash = calculate_object_hash(preprocessor_args, &cpp_hash, 0);
3271         if (!object_hash) {
3272                 fatal("internal error: object hash from cpp returned NULL");
3273         }
3274         update_cached_result_globals(object_hash);
3275
3276         if (object_hash_from_manifest
3277             && !file_hashes_equal(object_hash_from_manifest, object_hash)) {
3278                 // The hash from manifest differs from the hash of the preprocessor output.
3279                 // This could be because:
3280                 //
3281                 // - The preprocessor produces different output for the same input (not
3282                 //   likely).
3283                 // - There's a bug in ccache (maybe incorrect handling of compiler
3284                 //   arguments).
3285                 // - The user has used a different CCACHE_BASEDIR (most likely).
3286                 //
3287                 // The best thing here would probably be to remove the hash entry from the
3288                 // manifest. For now, we use a simpler method: just remove the manifest
3289                 // file.
3290                 cc_log("Hash from manifest doesn't match preprocessor output");
3291                 cc_log("Likely reason: different CCACHE_BASEDIRs used");
3292                 cc_log("Removing manifest as a safety measure");
3293                 x_unlink(manifest_path);
3294
3295                 put_object_in_manifest = true;
3296         }
3297
3298         // If we can return from cache at this point then do.
3299         from_cache(FROMCACHE_CPP_MODE, put_object_in_manifest);
3300
3301         if (conf->read_only) {
3302                 cc_log("Read-only mode; running real compiler");
3303                 failed();
3304         }
3305
3306         add_prefix(compiler_args, conf->prefix_command);
3307
3308         // Run real compiler, sending output to cache.
3309         to_cache(compiler_args);
3310
3311         x_exit(0);
3312 }
3313
3314 static void
3315 configuration_printer(const char *descr, const char *origin, void *context)
3316 {
3317         assert(context);
3318         fprintf(context, "(%s) %s\n", origin, descr);
3319 }
3320
3321 // The main program when not doing a compile.
3322 static int
3323 ccache_main_options(int argc, char *argv[])
3324 {
3325         enum longopts {
3326                 DUMP_MANIFEST
3327         };
3328         static const struct option options[] = {
3329                 {"cleanup",       no_argument,       0, 'c'},
3330                 {"clear",         no_argument,       0, 'C'},
3331                 {"dump-manifest", required_argument, 0, DUMP_MANIFEST},
3332                 {"help",          no_argument,       0, 'h'},
3333                 {"max-files",     required_argument, 0, 'F'},
3334                 {"max-size",      required_argument, 0, 'M'},
3335                 {"set-config",    required_argument, 0, 'o'},
3336                 {"print-config",  no_argument,       0, 'p'},
3337                 {"show-stats",    no_argument,       0, 's'},
3338                 {"version",       no_argument,       0, 'V'},
3339                 {"zero-stats",    no_argument,       0, 'z'},
3340                 {0, 0, 0, 0}
3341         };
3342
3343         int c;
3344         while ((c = getopt_long(argc, argv, "cChF:M:o:psVz", options, NULL)) != -1) {
3345                 switch (c) {
3346                 case DUMP_MANIFEST:
3347                         manifest_dump(optarg, stdout);
3348                         break;
3349
3350                 case 'c': // --cleanup
3351                         initialize();
3352                         clean_up_all(conf);
3353                         printf("Cleaned cache\n");
3354                         break;
3355
3356                 case 'C': // --clear
3357                         initialize();
3358                         wipe_all(conf);
3359                         printf("Cleared cache\n");
3360                         break;
3361
3362                 case 'h': // --help
3363                         fputs(USAGE_TEXT, stdout);
3364                         x_exit(0);
3365
3366                 case 'F': // --max-files
3367                 {
3368                         initialize();
3369                         char *errmsg;
3370                         if (conf_set_value_in_file(primary_config_path, "max_files", optarg,
3371                                                    &errmsg)) {
3372                                 unsigned files = atoi(optarg);
3373                                 if (files == 0) {
3374                                         printf("Unset cache file limit\n");
3375                                 } else {
3376                                         printf("Set cache file limit to %u\n", files);
3377                                 }
3378                         } else {
3379                                 fatal("could not set cache file limit: %s", errmsg);
3380                         }
3381                 }
3382                 break;
3383
3384                 case 'M': // --max-size
3385                 {
3386                         initialize();
3387                         uint64_t size;
3388                         if (!parse_size_with_suffix(optarg, &size)) {
3389                                 fatal("invalid size: %s", optarg);
3390                         }
3391                         char *errmsg;
3392                         if (conf_set_value_in_file(primary_config_path, "max_size", optarg,
3393                                                    &errmsg)) {
3394                                 if (size == 0) {
3395                                         printf("Unset cache size limit\n");
3396                                 } else {
3397                                         char *s = format_human_readable_size(size);
3398                                         printf("Set cache size limit to %s\n", s);
3399                                         free(s);
3400                                 }
3401                         } else {
3402                                 fatal("could not set cache size limit: %s", errmsg);
3403                         }
3404                 }
3405                 break;
3406
3407                 case 'o': // --set-config
3408                 {
3409                         initialize();
3410                         char *p = strchr(optarg, '=');
3411                         if (!p) {
3412                                 fatal("missing equal sign in \"%s\"", optarg);
3413                         }
3414                         char *key = x_strndup(optarg, p - optarg);
3415                         char *value = p + 1;
3416                         char *errmsg;
3417                         if (!conf_set_value_in_file(primary_config_path, key, value, &errmsg)) {
3418                                 fatal("%s", errmsg);
3419                         }
3420                         free(key);
3421                 }
3422                 break;
3423
3424                 case 'p': // --print-config
3425                         initialize();
3426                         conf_print_items(conf, configuration_printer, stdout);
3427                         break;
3428
3429                 case 's': // --show-stats
3430                         initialize();
3431                         stats_summary(conf);
3432                         break;
3433
3434                 case 'V': // --version
3435                         fprintf(stdout, VERSION_TEXT, CCACHE_VERSION);
3436                         x_exit(0);
3437
3438                 case 'z': // --zero-stats
3439                         initialize();
3440                         stats_zero();
3441                         printf("Statistics cleared\n");
3442                         break;
3443
3444                 default:
3445                         fputs(USAGE_TEXT, stderr);
3446                         x_exit(1);
3447                 }
3448         }
3449
3450         return 0;
3451 }
3452
3453 int
3454 ccache_main(int argc, char *argv[])
3455 {
3456         // Check if we are being invoked as "ccache".
3457         char *program_name = basename(argv[0]);
3458         if (same_executable_name(program_name, MYNAME)) {
3459                 if (argc < 2) {
3460                         fputs(USAGE_TEXT, stderr);
3461                         x_exit(1);
3462                 }
3463                 // If the first argument isn't an option, then assume we are being passed a
3464                 // compiler name and options.
3465                 if (argv[1][0] == '-') {
3466                         return ccache_main_options(argc, argv);
3467                 }
3468         }
3469         free(program_name);
3470
3471         ccache(argc, argv);
3472         return 1;
3473 }