forked from ccache/ccache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathccache.c
3550 lines (3153 loc) · 89.1 KB
/
ccache.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ccache -- a fast C/C++ compiler cache
*
* Copyright (C) 2002-2007 Andrew Tridgell
* Copyright (C) 2009-2016 Joel Rosdahl
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "ccache.h"
#include "compopt.h"
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#else
#include "getopt_long.h"
#endif
#include "hashtable.h"
#include "hashtable_itr.h"
#include "hashutil.h"
#include "language.h"
#include "manifest.h"
#define STRINGIFY(x) #x
#define TO_STRING(x) STRINGIFY(x)
static const char VERSION_TEXT[] =
MYNAME " version %s\n"
"\n"
"Copyright (C) 2002-2007 Andrew Tridgell\n"
"Copyright (C) 2009-2016 Joel Rosdahl\n"
"\n"
"This program is free software; you can redistribute it and/or modify it under\n"
"the terms of the GNU General Public License as published by the Free Software\n"
"Foundation; either version 3 of the License, or (at your option) any later\n"
"version.\n";
static const char USAGE_TEXT[] =
"Usage:\n"
" " MYNAME " [options]\n"
" " MYNAME " compiler [compiler options]\n"
" compiler [compiler options] (via symbolic link)\n"
"\n"
"Options:\n"
" -c, --cleanup delete old files and recalculate size counters\n"
" (normally not needed as this is done automatically)\n"
" -C, --clear clear the cache completely (except configuration)\n"
" -F, --max-files=N set maximum number of files in cache to N (use 0 for\n"
" no limit)\n"
" -M, --max-size=SIZE set maximum size of cache to SIZE (use 0 for no\n"
" limit); available suffixes: k, M, G, T (decimal) and\n"
" Ki, Mi, Gi, Ti (binary); default suffix: G\n"
" -o, --set-config=K=V set configuration key K to value V\n"
" -p, --print-config print current configuration options\n"
" -s, --show-stats show statistics summary\n"
" -z, --zero-stats zero statistics counters\n"
"\n"
" -h, --help print this help text\n"
" -V, --version print version and copyright information\n"
"\n"
"See also <https://ccache.samba.org>.\n";
/* Global configuration data. */
struct conf *conf = NULL;
/* Where to write configuration changes. */
char *primary_config_path = NULL;
/* Secondary, read-only configuration file (if any). */
char *secondary_config_path = NULL;
/* current working directory taken from $PWD, or getcwd() if $PWD is bad */
char *current_working_dir = NULL;
/* the original argument list */
static struct args *orig_args;
/* the source file */
static char *input_file;
/* The output file being compiled to. */
static char *output_obj;
/* The path to the dependency file (implicit or specified with -MF). */
static char *output_dep;
/* The path to the coverage file (implicit when using -ftest-coverage). */
static char *output_cov;
/* Diagnostic generation information (clang). Contains pathname if not
* NULL. */
static char *output_dia = NULL;
/* -gsplit-dwarf support: Split dwarf information (GCC 4.8 and
* up). Contains pathname if not NULL. */
static char *output_dwo = NULL;
/*
* Name (represented as a struct file_hash) of the file containing the cached
* object code.
*/
static struct file_hash *cached_obj_hash;
/*
* Full path to the file containing the cached object code
* (cachedir/a/b/cdef[...]-size.o).
*/
static char *cached_obj;
/*
* Full path to the file containing the standard error output
* (cachedir/a/b/cdef[...]-size.stderr).
*/
static char *cached_stderr;
/*
* Full path to the file containing the dependency information
* (cachedir/a/b/cdef[...]-size.d).
*/
static char *cached_dep;
/*
* Full path to the file containing the coverage information
* (cachedir/a/b/cdef[...]-size.gcno).
*/
static char *cached_cov;
/*
* Full path to the file containing the diagnostic information (for clang)
* (cachedir/a/b/cdef[...]-size.dia).
*/
static char *cached_dia;
/*
* -gsplit-dwarf support:
* Full path to the file containing the split dwarf (for GCC 4.8 and
* above)
* (cachedir/a/b/cdef[...]-size.dwo).
*
* contains NULL if -gsplit-dwarf is not given.
*/
static char *cached_dwo;
/*
* -gsplit-dwarf support:
* using_split_dwarf is true if "-gsplit-dwarf" is given to the
* compiler (GCC 4.8 and up).
*/
bool using_split_dwarf = false;
/*
* Full path to the file containing the manifest
* (cachedir/a/b/cdef[...]-size.manifest).
*/
static char *manifest_path;
/*
* Time of compilation. Used to see if include files have changed after
* compilation.
*/
time_t time_of_compilation;
/*
* Files included by the preprocessor and their hashes/sizes. Key: file path.
* Value: struct file_hash.
*/
static struct hashtable *included_files;
/* uses absolute path for some include files */
static bool has_absolute_include_headers = false;
/* List of headers to ignore */
static char **ignore_headers;
/* Size of headers to ignore list */
static size_t ignore_headers_len;
/* is gcc being asked to output debug info? */
static bool generating_debuginfo;
/* is gcc being asked to output dependencies? */
static bool generating_dependencies;
/* is gcc being asked to output coverage? */
static bool generating_coverage;
/* relocating debuginfo, in the format old=new */
static char *debug_prefix_map = NULL;
/* is gcc being asked to output coverage data (.gcda) at runtime? */
static bool profile_arcs;
/* name of the custom profile directory (default: object dirname) */
static char *profile_dir;
/* the name of the temporary pre-processor file */
static char *i_tmpfile;
/* are we compiling a .i or .ii file directly? */
static bool direct_i_file;
/* the name of the cpp stderr file */
static char *cpp_stderr;
/*
* Full path to the statistics file in the subdirectory where the cached result
* belongs (<cache_dir>/<x>/stats).
*/
char *stats_file = NULL;
/* Whether the output is a precompiled header */
static bool output_is_precompiled_header = false;
/* Profile generation / usage information */
static char *profile_dir = NULL;
static bool profile_use = false;
static bool profile_generate = false;
/*
* Whether we are using a precompiled header (either via -include, #include or
* clang's -include-pch or -include-pth).
*/
static bool using_precompiled_header = false;
/*
* The .gch/.pch/.pth file used for compilation.
*/
static char *included_pch_file = NULL;
/* How long (in microseconds) to wait before breaking a stale lock. */
unsigned lock_staleness_limit = 2000000;
enum fromcache_call_mode {
FROMCACHE_DIRECT_MODE,
FROMCACHE_CPP_MODE
};
struct pending_tmp_file {
char *path;
struct pending_tmp_file *next;
};
/* Temporary files to remove at program exit. */
static struct pending_tmp_file *pending_tmp_files = NULL;
#ifndef _WIN32
static sigset_t fatal_signal_set;
/* PID of currently executing compiler that we have started, if any. 0 means no
* ongoing compilation. */
static pid_t compiler_pid = 0;
#endif
/*
* This is a string that identifies the current "version" of the hash sum
* computed by ccache. If, for any reason, we want to force the hash sum to be
* different for the same input in a new ccache version, we can just change
* this string. A typical example would be if the format of one of the files
* stored in the cache changes in a backwards-incompatible way.
*/
static const char HASH_PREFIX[] = "3";
static void
add_prefix(struct args *args, char *prefix_command)
{
char *e;
char *tok, *saveptr = NULL;
struct args *prefix;
int i;
if (str_eq(prefix_command, "")) {
return;
}
prefix = args_init(0, NULL);
e = x_strdup(prefix_command);
for (tok = strtok_r(e, " ", &saveptr);
tok;
tok = strtok_r(NULL, " ", &saveptr)) {
char *p;
p = find_executable(tok, MYNAME);
if (!p) {
fatal("%s: %s", tok, strerror(errno));
}
args_add(prefix, p);
free(p);
}
free(e);
cc_log("Using command-line prefix %s", prefix_command);
for (i = prefix->argc; i != 0; i--) {
args_add_prefix(args, prefix->argv[i-1]);
}
args_free(prefix);
}
/* Something went badly wrong - just execute the real compiler. */
static void
failed(void)
{
assert(orig_args);
args_strip(orig_args, "--ccache-");
add_prefix(orig_args, conf->prefix_command);
cc_log("Failed; falling back to running the real compiler");
cc_log_argv("Executing ", orig_args->argv);
exitfn_call();
execv(orig_args->argv[0], orig_args->argv);
fatal("execv of %s failed: %s", orig_args->argv[0], strerror(errno));
}
static const char *
temp_dir()
{
static char *path = NULL;
if (path) {
return path; /* Memoize */
}
path = conf->temporary_dir;
if (str_eq(path, "")) {
path = format("%s/tmp", conf->cache_dir);
}
return path;
}
void
block_signals(void)
{
#ifndef _WIN32
sigprocmask(SIG_BLOCK, &fatal_signal_set, NULL);
#endif
}
void
unblock_signals(void)
{
#ifndef _WIN32
sigset_t empty;
sigemptyset(&empty);
sigprocmask(SIG_SETMASK, &empty, NULL);
#endif
}
static void
add_pending_tmp_file(const char *path)
{
struct pending_tmp_file *e;
block_signals();
e = x_malloc(sizeof(*e));
e->path = x_strdup(path);
e->next = pending_tmp_files;
pending_tmp_files = e;
unblock_signals();
}
static void
do_clean_up_pending_tmp_files(void)
{
struct pending_tmp_file *p = pending_tmp_files;
while (p) {
/* Can't call tmp_unlink here since its cc_log calls aren't signal safe. */
unlink(p->path);
p = p->next;
/* Leak p->path and p here because clean_up_pending_tmp_files needs to be
* signal safe. */
}
}
static void
clean_up_pending_tmp_files(void)
{
block_signals();
do_clean_up_pending_tmp_files();
unblock_signals();
}
#ifndef _WIN32
static void
signal_handler(int signum)
{
/* Unregister handler for this signal so that we can send the signal to
* ourselves at the end of the handler. */
signal(signum, SIG_DFL);
/* If ccache was killed explicitly, then bring the compiler subprocess (if
* any) with us as well. */
if (signum == SIGTERM
&& compiler_pid != 0
&& waitpid(compiler_pid, NULL, WNOHANG) == 0) {
kill(compiler_pid, signum);
}
do_clean_up_pending_tmp_files();
if (compiler_pid != 0) {
/* Wait for compiler subprocess to exit before we snuff it. */
waitpid(compiler_pid, NULL, 0);
}
/* Resend signal to ourselves to exit properly after returning from the
* handler. */
kill(getpid(), signum);
}
static void
register_signal_handler(int signum)
{
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = signal_handler;
act.sa_mask = fatal_signal_set;
#ifdef SA_RESTART
act.sa_flags = SA_RESTART;
#endif
sigaction(signum, &act, NULL);
}
static void
set_up_signal_handlers(void)
{
sigemptyset(&fatal_signal_set);
sigaddset(&fatal_signal_set, SIGINT);
sigaddset(&fatal_signal_set, SIGTERM);
#ifdef SIGHUP
sigaddset(&fatal_signal_set, SIGHUP);
#endif
#ifdef SIGQUIT
sigaddset(&fatal_signal_set, SIGQUIT);
#endif
register_signal_handler(SIGINT);
register_signal_handler(SIGTERM);
#ifdef SIGHUP
register_signal_handler(SIGHUP);
#endif
#ifdef SIGQUIT
register_signal_handler(SIGQUIT);
#endif
}
#endif /* _WIN32 */
static void
clean_up_internal_tempdir(void)
{
DIR *dir;
struct dirent *entry;
struct stat st;
time_t now = time(NULL);
if (x_stat(conf->cache_dir, &st) != 0 || st.st_mtime + 3600 >= now) {
/* No cleanup needed. */
return;
}
update_mtime(conf->cache_dir);
dir = opendir(temp_dir());
if (!dir) {
return;
}
while ((entry = readdir(dir))) {
char *path;
if (str_eq(entry->d_name, ".") || str_eq(entry->d_name, "..")) {
continue;
}
path = format("%s/%s", temp_dir(), entry->d_name);
if (x_lstat(path, &st) == 0 && st.st_mtime + 3600 < now) {
tmp_unlink(path);
}
free(path);
}
closedir(dir);
}
static char *
get_current_working_dir(void)
{
if (!current_working_dir) {
char *cwd = get_cwd();
if (cwd) {
current_working_dir = x_realpath(cwd);
free(cwd);
}
if (!current_working_dir) {
cc_log("Unable to determine current working directory: %s",
strerror(errno));
failed();
}
}
return current_working_dir;
}
/*
* Transform a name to a full path into the cache directory, creating needed
* sublevels if needed. Caller frees.
*/
static char *
get_path_in_cache(const char *name, const char *suffix)
{
unsigned i;
char *path;
char *result;
path = x_strdup(conf->cache_dir);
for (i = 0; i < conf->cache_dir_levels; ++i) {
char *p = format("%s/%c", path, name[i]);
free(path);
path = p;
}
result = format("%s/%s%s", path, name + conf->cache_dir_levels, suffix);
free(path);
return result;
}
/*
* This function hashes an include file and stores the path and hash in the
* global included_files variable. If the include file is a PCH, cpp_hash is
* also updated. Takes over ownership of path.
*/
static void
remember_include_file(char *path, struct mdfour *cpp_hash, bool system)
{
#ifdef _WIN32
DWORD attributes;
#endif
struct mdfour fhash;
struct stat st;
char *source = NULL;
size_t size;
bool is_pch;
size_t path_len = strlen(path);
char *canonical;
size_t canonical_len;
char *ignore;
size_t ignore_len;
size_t i;
if (path_len >= 2 && (path[0] == '<' && path[path_len - 1] == '>')) {
/* Typically <built-in> or <command-line>. */
goto ignore;
}
if (str_eq(path, input_file)) {
/* Don't remember the input file. */
goto ignore;
}
if (system && (conf->sloppiness & SLOPPY_NO_SYSTEM_HEADERS)) {
/* Don't remember this system header. */
goto ignore;
}
if (hashtable_search(included_files, path)) {
/* Already known include file. */
goto ignore;
}
#ifdef _WIN32
/* stat fails on directories on win32 */
attributes = GetFileAttributes(path);
if (attributes != INVALID_FILE_ATTRIBUTES &&
attributes & FILE_ATTRIBUTE_DIRECTORY) {
goto ignore;
}
#endif
if (x_stat(path, &st) != 0) {
goto failure;
}
if (S_ISDIR(st.st_mode)) {
/* Ignore directory, typically $PWD. */
goto ignore;
}
if (!S_ISREG(st.st_mode)) {
/* Device, pipe, socket or other strange creature. */
cc_log("Non-regular include file %s", path);
goto failure;
}
/* canonicalize path for comparison, clang uses ./header.h */
canonical = path;
canonical_len = path_len;
if (canonical[0] == '.' && canonical[1] == '/') {
canonical += 2;
canonical_len -= 2;
}
for (i = 0; i < ignore_headers_len; i++) {
ignore = ignore_headers[i];
ignore_len = strlen(ignore);
if (ignore_len > canonical_len) {
continue;
}
if (strncmp(canonical, ignore, ignore_len) == 0
&& (ignore[ignore_len-1] == DIR_DELIM_CH
|| canonical[ignore_len] == DIR_DELIM_CH
|| canonical[ignore_len] == '\0')) {
goto ignore;
}
}
/* Let's hash the include file. */
if (!(conf->sloppiness & SLOPPY_INCLUDE_FILE_MTIME)
&& st.st_mtime >= time_of_compilation) {
cc_log("Include file %s too new", path);
goto failure;
}
if (!(conf->sloppiness & SLOPPY_INCLUDE_FILE_CTIME)
&& st.st_ctime >= time_of_compilation) {
cc_log("Include file %s ctime too new", path);
goto failure;
}
hash_start(&fhash);
is_pch = is_precompiled_header(path);
if (is_pch) {
struct file_hash pch_hash;
if (!hash_file(&fhash, path)) {
goto failure;
}
hash_result_as_bytes(&fhash, pch_hash.hash);
pch_hash.size = fhash.totalN;
hash_delimiter(cpp_hash, "pch_hash");
hash_buffer(cpp_hash, pch_hash.hash, sizeof(pch_hash.hash));
}
if (conf->direct_mode) {
struct file_hash *h;
if (!is_pch) { /* else: the file has already been hashed. */
int result;
if (st.st_size > 0) {
if (!read_file(path, st.st_size, &source, &size)) {
goto failure;
}
} else {
source = x_strdup("");
size = 0;
}
result = hash_source_code_string(conf, &fhash, source, size, path);
if (result & HASH_SOURCE_CODE_ERROR
|| result & HASH_SOURCE_CODE_FOUND_TIME) {
goto failure;
}
}
h = x_malloc(sizeof(*h));
hash_result_as_bytes(&fhash, h->hash);
h->size = fhash.totalN;
hashtable_insert(included_files, path, h);
} else {
free(path);
}
free(source);
return;
failure:
if (conf->direct_mode) {
cc_log("Disabling direct mode");
conf->direct_mode = false;
}
/* Fall through. */
ignore:
free(path);
free(source);
}
/*
* Make a relative path from current working directory to path if path is under
* the base directory. Takes over ownership of path. Caller frees.
*/
static char *
make_relative_path(char *path)
{
char *canon_path, *path_suffix = NULL;
struct stat st;
if (str_eq(conf->base_dir, "") || !str_startswith(path, conf->base_dir)) {
return path;
}
#ifdef _WIN32
if (path[0] == '/') {
path++; /* skip leading slash */
}
#endif
/* x_realpath only works for existing paths, so if path doesn't exist, try
* dirname(path) and assemble the path afterwards. We only bother to try
* canonicalizing one of these two paths since a compiler path argument
* typically only makes sense if path or dirname(path) exists. */
if (stat(path, &st) != 0) {
/* path doesn't exist. */
char *dir, *p;
dir = dirname(path);
if (stat(dir, &st) != 0) {
/* And neither does its parent directory, so no action to take. */
free(dir);
return path;
}
free(dir);
path_suffix = basename(path);
p = path;
path = dirname(path);
free(p);
}
canon_path = x_realpath(path);
if (canon_path) {
char *relpath;
free(path);
relpath = get_relative_path(get_current_working_dir(), canon_path);
free(canon_path);
if (path_suffix) {
path = format("%s/%s", relpath, path_suffix);
free(relpath);
free(path_suffix);
return path;
} else {
return relpath;
}
} else {
/* path doesn't exist, so leave it as it is. */
free(path_suffix);
return path;
}
}
/*
* This function reads and hashes a file. While doing this, it also does these
* things:
*
* - Makes include file paths for which the base directory is a prefix relative
* when computing the hash sum.
* - Stores the paths and hashes of included files in the global variable
* included_files.
*/
static bool
process_preprocessed_file(struct mdfour *hash, const char *path)
{
char *data;
char *p, *q, *r, *end;
size_t size;
if (!read_file(path, 0, &data, &size)) {
return false;
}
ignore_headers = NULL;
ignore_headers_len = 0;
if (!str_eq(conf->ignore_headers_in_manifest, "")) {
char *header, *p, *q, *saveptr = NULL;
p = x_strdup(conf->ignore_headers_in_manifest);
q = p;
while ((header = strtok_r(q, PATH_DELIM, &saveptr))) {
ignore_headers = x_realloc(ignore_headers,
(ignore_headers_len+1) * sizeof(char *));
ignore_headers[ignore_headers_len++] = x_strdup(header);
q = NULL;
}
free(p);
}
included_files = create_hashtable(1000, hash_from_string, strings_equal);
/* Bytes between p and q are pending to be hashed. */
end = data + size;
p = data;
q = data;
/* There must be at least 7 characters (# 1 "x") left to potentially find an
* include file path. */
while (q < end - 7) {
/*
* Check if we look at a line containing the file name of an included file.
* At least the following formats exist (where N is a positive integer):
*
* GCC:
*
* # N "file"
* # N "file" N
* #pragma GCC pch_preprocess "file"
*
* HP's compiler:
*
* #line N "file"
*
* AIX's compiler:
*
* #line N "file"
* #line N
*
* Note that there may be other lines starting with '#' left after
* preprocessing as well, for instance "# pragma".
*/
if (q[0] == '#'
/* GCC: */
&& ((q[1] == ' ' && q[2] >= '0' && q[2] <= '9')
/* GCC precompiled header: */
|| (q[1] == 'p'
&& str_startswith(&q[2], "ragma GCC pch_preprocess "))
/* HP/AIX: */
|| (q[1] == 'l' && q[2] == 'i' && q[3] == 'n' && q[4] == 'e'
&& q[5] == ' '))
&& (q == data || q[-1] == '\n')) {
char *path;
bool system;
while (q < end && *q != '"' && *q != '\n') {
q++;
}
if (q < end && *q == '\n') {
/* A newline before the quotation mark -> no match. */
continue;
}
q++;
if (q >= end) {
cc_log("Failed to parse included file path");
free(data);
return false;
}
/* q points to the beginning of an include file path */
hash_buffer(hash, p, q - p);
p = q;
while (q < end && *q != '"') {
q++;
}
/* look for preprocessor flags, after the "filename" */
system = false;
r = q + 1;
while (r < end && *r != '\n') {
if (*r == '3') { /* system header */
system = true;
}
r++;
}
/* p and q span the include file path */
path = x_strndup(p, q - p);
if (!has_absolute_include_headers) {
has_absolute_include_headers = is_absolute_path(path);
}
path = make_relative_path(path);
hash_string(hash, path);
remember_include_file(path, hash, system);
p = r;
} else {
q++;
}
}
hash_buffer(hash, p, (end - p));
free(data);
/* Explicitly check the .gch/.pch/.pth file, Clang does not include any
* mention of it in the preprocessed output. */
if (included_pch_file) {
char *path = x_strdup(included_pch_file);
path = make_relative_path(path);
hash_string(hash, path);
remember_include_file(path, hash, false);
}
return true;
}
/*
* Replace absolute paths with relative paths in the provided dependency file.
*/
static void
use_relative_paths_in_depfile(const char *depfile)
{
FILE *f, *tmpf;
char buf[10000];
char *tmp_file;
char *relpath;
bool result = false;
char *token, *saveptr;
if (str_eq(conf->base_dir, "")) {
cc_log("Base dir not set, skip using relative paths");
return; /* nothing to do */
}
if (!has_absolute_include_headers) {
cc_log("No absolute path for included files found, skip using relative"
" paths");
return; /* nothing to do */
}
f = fopen(depfile, "r");
if (!f) {
cc_log("Cannot open dependency file: %s (%s)", depfile, strerror(errno));
return;
}
tmp_file = format("%s.tmp", depfile);
tmpf = create_tmp_file(&tmp_file, "w");
while (fgets(buf, sizeof(buf), f) && !ferror(tmpf)) {
token = strtok_r(buf, " \t", &saveptr);
while (token) {
if (is_absolute_path(token) && str_startswith(token, conf->base_dir)) {
relpath = make_relative_path(x_strdup(token));
result = true;
} else {
relpath = token;
}
if (token != buf) { /* this is a dependency file */
fputc(' ', tmpf);
}
fputs(relpath, tmpf);
if (relpath != token) {
free(relpath);
}
token = strtok_r(NULL, " \t", &saveptr);
}
}
if (ferror(f)) {
cc_log("Error reading dependency file: %s, skip relative path usage",
depfile);
result = false;
goto out;
}
if (ferror(tmpf)) {
cc_log("Error writing temporary dependency file: %s, skip relative path"
" usage", tmp_file);
result = false;
goto out;
}
out:
fclose(tmpf);
fclose(f);
if (result) {
if (x_rename(tmp_file, depfile) != 0) {
cc_log("Error renaming dependency file: %s -> %s (%s), skip relative"
" path usage", tmp_file, depfile, strerror(errno));
result = false;
} else {
cc_log("Renamed dependency file: %s -> %s", tmp_file, depfile);
}
}
if (!result) {
cc_log("Removing temporary dependency file: %s", tmp_file);
x_unlink(tmp_file);
}
free(tmp_file);
}
/* Copy or link a file to the cache. */
static void
put_file_in_cache(const char *source, const char *dest)
{
int ret;
struct stat st;
bool do_link = conf->hard_link && !conf->compression;
assert(!conf->read_only);
assert(!conf->read_only_direct);
if (do_link) {
x_unlink(dest);
ret = link(source, dest);
if (ret != 0) {
cc_log("Failed to link %s to %s: %s", source, dest, strerror(errno));
cc_log("Falling back to copying");
do_link = false;
}
}
if (!do_link) {
ret = copy_file(
source, dest, conf->compression ? conf->compression_level : 0);
if (ret != 0) {
cc_log("Failed to copy %s to %s: %s", source, dest, strerror(errno));
stats_update(STATS_ERROR);
failed();
}
}